text
stringlengths
14
6.51M
unit udmValePedagio; interface uses System.SysUtils, System.Classes, udmPadrao, DBAccess, IBC, Data.DB, MemDS; type TdmValePedagio = class(TdmPadrao) qryManutencaoNR_MANIFVALEPED: TStringField; qryManutencaoCNPJFORNVALEPED: TStringField; qryManutencaoRESPPAGAMENTOVALEPED: TStringField; qryManutencaoCOMPROVANTEVALEPED: TStringField; qryManutencaoVALORVALEPED: TFloatField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryLocalizacaoNR_MANIFVALEPED: TStringField; qryLocalizacaoCNPJFORNVALEPED: TStringField; qryLocalizacaoRESPPAGAMENTOVALEPED: TStringField; qryLocalizacaoCOMPROVANTEVALEPED: TStringField; qryLocalizacaoVALORVALEPED: TFloatField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FNrManifValPed : String; FCNPJFornValPed : String; FRespPagValPed : String; FComprovanteValPed : String; function GetSQL_DEFAULT: string; public function LocalizarValePedPorManifesto(DataSet: TDataSet = nil): Boolean; property NrManifValPed: string read FNrManifValPed write FNrManifValPed; property CNPJFornValPed: string read FCNPJFornValPed write FCNPJFornValPed; property RespPagValPed: string read FRespPagValPed write FRespPagValPed; property ComprovanteValPed: String read FComprovanteValPed write FComprovanteValPed; property SQLPadrao: string read GetSQL_DEFAULT; end; const SQL_DEFAULT = 'SELECT * FROM STWOPETVALEPED VPED '; var dmValePedagio: TdmValePedagio; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TdmValePedagio } function TdmValePedagio.GetSQL_DEFAULT: string; begin result := SQL_DEFAULT; end; function TdmValePedagio.LocalizarValePedPorManifesto( DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE VPED.NR_MANIFVALEPED = :NR_MANIF'); Params[0].AsString := FNrManifValPed; Open; Result := not IsEmpty; end; end; procedure TdmValePedagio.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE VPED.NR_MANIFVALEPED = :NR_MANIF'); SQL.Add(' AND VPED.CNPJFORNVALEPED = :CNPJFORN'); SQL.Add(' AND VPED.RESPPAGAMENTOVALEPED = :RESPPAG'); SQL.Add(' AND VPED.COMPROVANTEVALEPED = :COMPROVANTE'); SQL.Add(' ORDER BY VPED.NR_MANIFVALEPED, VPED.CNPJFORNVALEPED, VPED.RESPPAGAMENTOVALEPED, VPED.COMPROVANTEVALEPED'); Params[0].AsString := FNrManifValPed; Params[1].AsString := FCNPJFornValPed; Params[2].AsString := FRespPagValPed; Params[3].AsString := FComprovanteValPed; end; end; procedure TdmValePedagio.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' ORDER BY VPED.NR_MANIF, VPED.CNPJFORNVALEPEDAGIO, VPED.RESPPAGAMENTOVALEPED, VPED.COMPROVANTEVALEPED'); end; end; end.
unit IdMessageBuilder; interface {$i IdCompilerDefines.inc} uses Classes, IdMessage; type TIdMessageBuilderAttachment = class(TCollectionItem) private FContentID: String; FContentTransfer: String; FContentType: String; FData: TStream; FFileName: String; FName: String; public procedure Assign(Source: TPersistent); override; property ContentID: String read FContentID write FContentID; property ContentTransfer: String read FContentTransfer; property ContentType: String read FContentType write FContentType; property Data: TStream read FData write FData; property FileName: String read FFileName write FFileName; property Name: String read FName write FName; end; TIdMessageBuilderAttachments = class(TCollection) private function GetAttachment(Index: Integer): TIdMessageBuilderAttachment; procedure SetAttachment(Index: Integer; Value: TIdMessageBuilderAttachment); public constructor Create; reintroduce; function Add: TIdMessageBuilderAttachment; reintroduce; overload; function Add(const AFileName: String; const AContentID: String = ''): TIdMessageBuilderAttachment; overload; function Add(AData: TStream; const AContentType: String; const AContentID: String = ''): TIdMessageBuilderAttachment; overload; procedure AddToMessage(AMsg: TIdMessage; ParentPart: Integer); property Attachment[Index: Integer]: TIdMessageBuilderAttachment read GetAttachment write SetAttachment; default; end; TIdCustomMessageBuilder = class protected FAttachments: TIdMessageBuilderAttachments; FPlainText: TStrings; FPlainTextCharSet: String; FPlainTextContentTransfer: String; procedure AddAttachments(AMsg: TIdMessage); procedure FillBody(AMsg: TIdMessage); virtual; abstract; procedure FillHeaders(AMsg: TIdMessage); virtual; procedure SetPlainText(AValue: TStrings); procedure SetAttachments(AValue: TIdMessageBuilderAttachments); public constructor Create; virtual; destructor Destroy; override; // procedure Clear; virtual; procedure FillMessage(AMsg: TIdMessage); function NewMessage(AOwner: TComponent = nil): TIdMessage; // property Attachments: TIdMessageBuilderAttachments read FAttachments write SetAttachments; property PlainText: TStrings read FPlainText write SetPlainText; property PlainTextCharSet: String read FPlainTextCharSet write FPlainTextCharSet; property PlainTextContentTransfer: String read FPlainTextContentTransfer write FPlainTextContentTransfer; end; TIdMessageBuilderPlain = class(TIdCustomMessageBuilder) protected procedure FillBody(AMsg: TIdMessage); override; procedure FillHeaders(AMsg: TIdMessage); override; end; TIdMessageBuilderHtml = class(TIdCustomMessageBuilder) protected FHtml: TStrings; FHtmlCharSet: String; FHtmlContentTransfer: String; FHtmlFiles: TIdMessageBuilderAttachments; FHtmlViewerNeededMsg: String; procedure FillBody(AMsg: TIdMessage); override; procedure FillHeaders(AMsg: TIdMessage); override; procedure SetHtml(AValue: TStrings); procedure SetHtmlFiles(AValue: TIdMessageBuilderAttachments); public constructor Create; override; destructor Destroy; override; // procedure Clear; override; // property Html: TStrings read FHtml write SetHtml; property HtmlCharSet: String read FHtmlCharSet write FHtmlCharSet; property HtmlContentTransfer: String read FHtmlContentTransfer write FHtmlContentTransfer; property HtmlFiles: TIdMessageBuilderAttachments read FHtmlFiles write SetHtmlFiles; property HtmlViewerNeededMsg: String read FHtmlViewerNeededMsg write FHtmlViewerNeededMsg; end; TIdMessageBuilderRtfType = (idMsgBldrRtfMS, idMsgBldrRtfEnriched, idMsgBldrRtfRichtext); TIdMessageBuilderRtf = class(TIdCustomMessageBuilder) protected FRtf: TStrings; FRtfType: TIdMessageBuilderRtfType; FRtfViewerNeededMsg: String; procedure FillBody(AMsg: TIdMessage); override; procedure FillHeaders(AMsg: TIdMessage); override; procedure SetRtf(AValue: TStrings); public constructor Create; override; destructor Destroy; override; // procedure Clear; override; // property Rtf: TStrings read FRtf write SetRtf; property RtfType: TIdMessageBuilderRtfType read FRtfType write FRtfType; property RtfViewerNeededMsg: String read FRtfViewerNeededMsg write FRtfViewerNeededMsg; end; implementation uses IdGlobal, IdGlobalProtocols, IdAttachment, IdAttachmentFile, IdAttachmentMemory, IdResourceStringsProtocols, IdText, SysUtils; const cTextPlain = 'text/plain'; {do not localize} cTextHtml = 'text/html'; {do not localize} cTextRtf: array[TIdMessageBuilderRtfType] of String = ('text/rtf', 'text/enriched', 'text/richtext'); {do not localize} cMultipartAlternative = 'multipart/alternative'; {do not localize} cMultipartMixed = 'multipart/mixed'; {do not localize} cMultipartRelatedHtml = 'multipart/related; type="text/html"'; {do not localize} { TIdMessageBuilderAttachment } procedure TIdMessageBuilderAttachment.Assign(Source: TPersistent); begin if Source is TIdMessageBuilderAttachment then begin with TIdMessageBuilderAttachment(Source) do begin Self.FContentID := FContentID; Self.FContentTransfer := FContentTransfer; Self.FContentType := FContentType; Self.FData := FData; Self.FFileName := FFileName; Self.FName := FName; end; end else begin inherited Assign(Source); end; end; { TIdMessageBuilderAttachments } constructor TIdMessageBuilderAttachments.Create; begin inherited Create(TIdMessageBuilderAttachment); end; function TIdMessageBuilderAttachments.Add: TIdMessageBuilderAttachment; begin // This helps prevent unsupported TIdMessageBuilderAttachment from being added Result := nil; end; function TIdMessageBuilderAttachments.Add(const AFileName: String; const AContentID: String = ''): TIdMessageBuilderAttachment; begin Result := TIdMessageBuilderAttachment(inherited Add); Result.FContentID := AContentID; Result.FFileName := AFileName; end; function TIdMessageBuilderAttachments.Add(AData: TStream; const AContentType: String; const AContentID: String = ''): TIdMessageBuilderAttachment; begin Assert(AData <> nil); Result := TIdMessageBuilderAttachment(inherited Add); Result.FContentID := AContentID; Result.FContentType := AContentType; Result.FData := AData; end; procedure TIdMessageBuilderAttachments.AddToMessage(AMsg: TIdMessage; ParentPart: Integer); var I: Integer; LMsgBldrAttachment: TIdMessageBuilderAttachment; LMsgAttachment: TIdAttachment; LStream: TStream; function FormatContentId(Item: TIdMessageBuilderAttachment): String; begin if Item.ContentID <> '' then begin Result := EnsureMsgIDBrackets(Item.ContentID); end else begin Result := ''; end; end; function FormatContentType(Item: TIdMessageBuilderAttachment): String; begin if Item.ContentType <> '' then begin Result := Item.ContentType; end else begin Result := GetMIMETypeFromFile(Item.FileName); end; end; function FormatName(Item: TIdMessageBuilderAttachment): String; begin if Item.Name <> '' then begin Result := Item.Name; end else if Item.FileName <> '' then begin Result := ExtractFileName(Item.FileName); end else begin Result := ''; end; end; begin for I := 0 to Count-1 do begin LMsgBldrAttachment := Attachment[I]; if Assigned(LMsgBldrAttachment.Data) then begin LMsgAttachment := TIdAttachmentMemory.Create(AMsg.MessageParts); try LMsgAttachment.FileName := ExtractFileName(LMsgBldrAttachment.FileName); LStream := LMsgAttachment.PrepareTempStream; try LStream.CopyFrom(LMsgBldrAttachment.Data, 0); finally LMsgAttachment.FinishTempStream; end; except LMsgAttachment.Free; raise; end; end else begin LMsgAttachment := TIdAttachmentFile.Create(AMsg.MessageParts, LMsgBldrAttachment.FileName); end; LMsgAttachment.Name := FormatName(LMsgBldrAttachment); LMsgAttachment.ContentId := FormatContentId(LMsgBldrAttachment); LMsgAttachment.ContentType := FormatContentType(LMsgBldrAttachment); LMsgAttachment.ContentTransfer := LMsgBldrAttachment.ContentTransfer; if ParentPart > -1 then begin if IsHeaderMediaType(LMsgAttachment.ContentType, 'image') then begin {do not localize} LMsgAttachment.ContentDisposition := 'inline'; {do not localize} end; LMsgAttachment.ParentPart := ParentPart; end; end; end; function TIdMessageBuilderAttachments.GetAttachment(Index: Integer): TIdMessageBuilderAttachment; begin Result := TIdMessageBuilderAttachment(inherited GetItem(Index)); end; procedure TIdMessageBuilderAttachments.SetAttachment(Index: Integer; Value: TIdMessageBuilderAttachment); begin inherited SetItem(Index, Value); end; { TIdCustomMessageBuilder } constructor TIdCustomMessageBuilder.Create; begin inherited Create; FPlainText := TStringList.Create; FAttachments := TIdMessageBuilderAttachments.Create; end; destructor TIdCustomMessageBuilder.Destroy; begin FPlainText.Free; FAttachments.Free; inherited Destroy; end; procedure TIdCustomMessageBuilder.AddAttachments(AMsg: TIdMessage); begin FAttachments.AddToMessage(AMsg, -1); end; procedure TIdCustomMessageBuilder.Clear; begin FAttachments.Clear; FPlainText.Clear; FPlainTextCharSet := ''; FPlainTextContentTransfer := ''; end; procedure TIdCustomMessageBuilder.FillMessage(AMsg: TIdMessage); begin if not Assigned(AMsg) then begin Exit; end; // Clear only the body, ContentType, CharSet, and ContentTransferEncoding here... // AMsg.ClearBody; AMsg.ContentType := ''; AMsg.CharSet := ''; AMsg.ContentTransferEncoding := ''; // let the message decide how to encode itself // based on what parts are added in InternalFill() // AMsg.Encoding := meDefault; // fill in type-specific content first // FillBody(AMsg); // Are non-related attachments present? // AddAttachments(AMsg); // Determine the top-level ContentType and // ContentTranferEncoding for the message now // FillHeaders(AMsg); end; function TIdCustomMessageBuilder.NewMessage(AOwner: TComponent = nil): TIdMessage; begin Result := TIdMessage.Create(AOwner); try FillMessage(Result); except FreeAndNil(Result); raise; end; end; procedure TIdCustomMessageBuilder.SetAttachments(AValue: TIdMessageBuilderAttachments); begin FAttachments.Assign(AValue); end; procedure TIdCustomMessageBuilder.FillHeaders(AMsg: TIdMessage); begin if FAttachments.Count > 0 then begin if AMsg.MessageParts.Count > 1 then begin // plain text and/or formatting, and at least 1 non-related attachment // AMsg.ContentType := cMultipartMixed; AMsg.CharSet := ''; AMsg.ContentTransferEncoding := ''; end else begin // no plain text or formatting, only 1 non-related attachment // with AMsg.MessageParts[0] do begin AMsg.ContentType := ContentType; AMsg.CharSet := CharSet; AMsg.ContentTransferEncoding := ContentTransfer; end; end; end else begin AMsg.ContentType := ''; AMsg.CharSet := ''; AMsg.ContentTransferEncoding := ''; end; end; procedure TIdCustomMessageBuilder.SetPlainText(AValue: TStrings); begin FPlainText.Assign(AValue); end; { TIdMessageBuilderPlain } procedure TIdMessageBuilderPlain.FillBody(AMsg: TIdMessage); begin // Is plain text present? // if FPlainText.Count > 0 then begin // Should the message contain only plain text? // if FAttachments.Count = 0 then begin AMsg.Body.Assign(FPlainText); end else begin // At this point, multiple pieces will be present in the message // body, so everything must be stored in the MessageParts collection... // with TIdText.Create(AMsg.MessageParts, FPlainText) do begin ContentType := cTextPlain; CharSet := FPlainTextCharSet; ContentTransfer := FPlainTextContentTransfer; end; end; end; end; procedure TIdMessageBuilderPlain.FillHeaders(AMsg: TIdMessage); begin if (FPlainText.Count > 0) and (FAttachments.Count = 0) then begin // plain text only // AMsg.ContentType := cTextPlain; AMsg.CharSet := FPlainTextCharSet; AMsg.ContentTransferEncoding := FPlainTextContentTransfer; end else begin inherited FillHeaders(AMsg); end; end; { TIdMessageBuilderHtml } constructor TIdMessageBuilderHtml.Create; begin inherited Create; FHtml := TStringList.Create; FHtmlFiles := TIdMessageBuilderAttachments.Create; FHtmlViewerNeededMsg := rsHtmlViewerNeeded; end; destructor TIdMessageBuilderHtml.Destroy; begin FHtml.Free; FHtmlFiles.Free; inherited Destroy; end; procedure TIdMessageBuilderHtml.Clear; begin FHtml.Clear; FHtmlCharSet := ''; FHtmlContentTransfer := ''; FHtmlFiles.Clear; inherited Clear; end; procedure TIdMessageBuilderHtml.FillBody(AMsg: TIdMessage); var LUsePlain, LUseHtml, LUseHtmlFiles, LUseAttachments: Boolean; LAlternativeIndex, LRelatedIndex: Integer; begin // Cache these for better performance // LUsePlain := FPlainText.Count > 0; LUseHtml := FHtml.Count > 0; LUseHtmlFiles := LUseHtml and (FHtmlFiles.Count > 0); LUseAttachments := FAttachments.Count > 0; LAlternativeIndex := -1; LRelatedIndex := -1; // Is any body data present at all? // if not (LUsePlain or LUseHtml or LUseHtmlFiles or LUseAttachments) then begin Exit; end; // Should the message contain only plain text? // if LUsePlain and not (LUseHtml or LUseAttachments) then begin AMsg.Body.Assign(FPlainText); Exit; end; // Should the message contain only HTML? // if LUseHtml and not (LUsePlain or LUseHtmlFiles or LUseAttachments) then begin AMsg.Body.Assign(FHtml); Exit; end; // At this point, multiple pieces will be present in the message // body, so everything must be stored in the MessageParts collection... // If the message should contain both plain text and HTML, a // "multipart/alternative" piece is needed to wrap them if // non-related attachments are also present... // // RLebeau 5/23/2011: need to output the Alternative piece if // the "HTML Viewer is needed" text is going to be used... // if {LUsePlain and} LUseHtml and LUseAttachments then begin with TIdText.Create(AMsg.MessageParts, nil) do begin ContentType := cMultipartAlternative; LAlternativeIndex := Index; end; end; // Is plain text present? // if LUsePlain or LUseHtml then begin with TIdText.Create(AMsg.MessageParts, FPlainText) do begin if LUseHtml and (not LUsePlain) then begin Body.Text := FHtmlViewerNeededMsg; end; ContentType := cTextPlain; CharSet := FPlainTextCharSet; ContentTransfer := FPlainTextContentTransfer; ParentPart := LAlternativeIndex; end; end; // Is HTML present? // if LUseHtml then begin // related attachments can't be referenced by, or used inside // of, plain text, so there is no point in wrapping the plain // text inside the same "multipart/related" part with the HTML // and attachments. Some email programs don't do that as well. // This logic is newer and more accurate than what is described // in the "HTML Messages" article found on Indy's website. // if LUseHtmlFiles then begin with TIdText.Create(AMsg.MessageParts, nil) do begin ContentType := cMultipartRelatedHtml; ParentPart := LAlternativeIndex; LRelatedIndex := Index; end; end; // Add HTML // with TIdText.Create(AMsg.MessageParts, FHtml) do begin ContentType := cTextHtml; CharSet := FHtmlCharSet; ContentTransfer := FHtmlContentTransfer; if LRelatedIndex <> -1 then begin ParentPart := LRelatedIndex; // plain text and related attachments end else begin ParentPart := LAlternativeIndex; // plain text and optional non-related attachments end; end; // Are related attachments present? // if LUseHtmlFiles then begin FHtmlFiles.AddToMessage(AMsg, LRelatedIndex); end; end; end; procedure TIdMessageBuilderHtml.FillHeaders(AMsg: TIdMessage); begin if FAttachments.Count = 0 then begin if (FPlainText.Count > 0) and (FHtml.Count = 0) then begin // plain text only // AMsg.ContentType := cTextPlain; AMsg.CharSet := FPlainTextCharSet; AMsg.ContentTransferEncoding := FPlainTextContentTransfer; end else if FHtml.Count > 0 then begin if (FPlainText.Count = 0) and (FHtmlFiles.Count = 0) then begin // HTML only // AMsg.ContentType := cTextHtml; AMsg.CharSet := FHtmlCharSet; AMsg.ContentTransferEncoding := FHtmlContentTransfer; end else begin // plain text and HTML and no related attachments // AMsg.ContentType := cMultipartAlternative; AMsg.CharSet := ''; AMsg.ContentTransferEncoding := ''; end; end; end else begin inherited FillHeaders(AMsg); end; end; procedure TIdMessageBuilderHtml.SetHtml(AValue: TStrings); begin FHtml.Assign(AValue); end; procedure TIdMessageBuilderHtml.SetHtmlFiles(AValue: TIdMessageBuilderAttachments); begin FHtmlFiles.Assign(AValue); end; { TIdMessageBuilderRTF } constructor TIdMessageBuilderRtf.Create; begin inherited Create; FRtf := TStringList.Create; FRtfType := idMsgBldrRtfMS; FRtfViewerNeededMsg := rsRtfViewerNeeded; end; destructor TIdMessageBuilderRtf.Destroy; begin FRtf.Free; inherited Destroy; end; procedure TIdMessageBuilderRtf.Clear; begin FRtf.Clear; inherited Clear; end; procedure TIdMessageBuilderRtf.FillBody(AMsg: TIdMessage); var LUsePlain, LUseRtf, LUseAttachments: Boolean; LAlternativeIndex: Integer; begin // Cache these for better performance // LUsePlain := FPlainText.Count > 0; LUseRtf := FRtf.Count > 0; LUseAttachments := FAttachments.Count > 0; LAlternativeIndex := -1; // Is any body data present at all? // if not (LUsePlain or LUseRtf or LUseAttachments) then begin Exit; end; // Should the message contain only plain text? // if LUsePlain and not (LUseRtf or LUseAttachments) then begin AMsg.Body.Assign(FPlainText); Exit; end; // Should the message contain only RTF? // if LUseRtf and not (LUsePlain or LUseAttachments) then begin AMsg.Body.Assign(FRtf); Exit; end; // At this point, multiple pieces will be present in the message // body, so everything must be stored in the MessageParts collection... // If the message should contain both plain text and RTF, a // "multipart/alternative" piece is needed to wrap them if // attachments are also present... // if LUsePlain and LUseRtf and LUseAttachments then begin with TIdText.Create(AMsg.MessageParts, nil) do begin ContentType := cMultipartAlternative; LAlternativeIndex := Index; end; end; // Is plain text present? // if LUsePlain or LUseRtf then begin with TIdText.Create(AMsg.MessageParts, FPlainText) do begin if LUseRtf and (not LUsePlain) then begin Body.Text := FRtfViewerNeededMsg; end; ContentType := cTextPlain; ParentPart := LAlternativeIndex; end; end; // Is RTF present? // if LUseRtf then begin // Add RTF // with TIdText.Create(AMsg.MessageParts, FRtf) do begin ContentType := cTextRtf[FRtfType]; ParentPart := LAlternativeIndex; // plain text and optional non-related attachments end; end; end; procedure TIdMessageBuilderRtf.FillHeaders(AMsg: TIdMessage); begin if FAttachments.Count = 0 then begin if (FPlainText.Count > 0) and (FRtf.Count = 0) then begin // plain text only // AMsg.ContentType := cTextPlain; AMsg.CharSet := FPlainTextCharSet; AMsg.ContentTransferEncoding := FPlainTextContentTransfer; end else if (FRtf.Count > 0) and (FPlainText.Count = 0) then begin // RTF only // AMsg.ContentType := cTextRtf[FRtfType]; AMsg.CharSet := ''; AMsg.ContentTransferEncoding := ''; end else begin // plain text and RTF and no non-related attachments // AMsg.ContentType := cMultipartAlternative; AMsg.CharSet := ''; AMsg.ContentTransferEncoding := ''; end; end else begin inherited FillHeaders(AMsg); end; end; procedure TIdMessageBuilderRtf.SetRtf(AValue: TStrings); begin FRtf.Assign(AValue); end; end.
{ Mark Sattolo 428500 CSI-1100A DGD-1 TA: Chris Lankester 1996 Final Exam, Question 5 } program ListOrder_recursive (input,output); { Recursive program to find if an array is in increasing order. } { Data Dictionary Givens: L, N - L is an array of N numbers. Intermediates: J - an index to write out L. Results: Answer - a boolean which is true if L is in increasing order, and false otherwise. } const MaxSize = 27; type MarkArray = array[1..MaxSize] of integer; var N, J, K, Occ, Occ2 : integer; L : MarkArray; Answer : boolean; { ************************************************************************ } procedure LastOccurrence(L:MarkArray; N,K:integer; var P:integer); begin if L[N] = K then P := N else if N = 1 then P := 0 else LastOccurrence(L, N-1, K, P); end; { procedure LastOccurrence } { ************************************************************************ } procedure LastOcc2(L:MarkArray; N,K:integer; var P:integer); begin if N = 1 then if L[N] = K then P := N else P := 0 else if L[N] = K then P := N else LastOcc2(L, N-1, K, P); end; { procedure LastOccurrence2 } { ************************************************************************ } procedure ListOrder(L:MarkArray; N:integer; var Answer:boolean); begin if N <= 1 then Answer := true else if L[N-1] <= L[N] then ListOrder(L, N-1, Answer) else Answer := false; end; { procedure ListOrder } { ************************************************************************ } procedure FillArray(var ArrayName : MarkArray; var ArraySize : integer); var K : integer; { K - an index in the prompt for values. } begin { procedure FillArray } repeat write('Please enter the size [ from 1 to ', MaxSize, ' ] of the array? '); readln(ArraySize); writeln; until (ArraySize <= MaxSize) and (ArraySize > 0); for K := 1 to ArraySize do begin write('Please enter array value #', K, '? '); read(ArrayName[K]) end { for } end; { procedure FillArray } {*************************************************************************************} begin { program } repeat { start input loop } { Get the input values } writeln('For the array to be searched,'); FillArray(L, N); writeln; { body 1 } ListOrder(L, N, Answer); { write out the results } writeln; writeln('************************************************'); writeln(' 1996 Final Exam, Question 5'); writeln('************************************************'); writeln; for J := 1 to N do write(L[J]:5, ' '); writeln; writeln; write('IS '); if not Answer then write('NOT '); writeln('in increasing order.'); writeln; writeln('************************************************'); writeln(' 1997 Final Exam, Question 4'); writeln('************************************************'); writeln; { body 2 } write('Enter the number [ 666 to exit ] to find the last occurrence in the array: '); readln(K); LastOccurrence(L, N, K, Occ); LastOcc2(L, N, K, Occ2); { output 2} writeln; writeln('LastOccurrence gives ', Occ, ' as the position of the final ', K, ' in: '); writeln; for J := 1 to N do write(L[J]:5, ' '); writeln; writeln; writeln('LastOccurrence2 gives ', Occ2, ' as the position of the final ', K, ' in: '); writeln; for J := 1 to N do write(L[J]:5, ' '); writeln; writeln; writeln('==============================================================='); writeln; until K = 666; end. { program }
{ ************************************************************** Package: XWB - Kernel RPCBroker Date Created: Sept 18, 1997 (Version 1.1) Site Name: Oakland, OI Field Office, Dept of Veteran Affairs Developers: Joel Ivey Description: Unit testing MFunStr code - requires dUnit for unit testing. Current Release: Version 1.1 Patch 40 (January 7, 2005)) *************************************************************** } unit uUniTTestMFunStr; interface uses TestFramework, Sgnoncnf, Classes, Graphics, SysUtils, Forms; type TTestType = class(TTestCase) private // any private fields needed for processing protected // procedure SetUp; override; // procedure TearDown; override; published // procedure TestName1; // procedure TestName2; end; TTestMFunStr1 = class(TTestCase) private protected procedure Setup; override; public published procedure TestPiece1; procedure TestPiece2; procedure TestPiece3; procedure TestPiece4; procedure TestPiece5; procedure TestPiece6; procedure TestPiece7; procedure TestPiece8; procedure TestPiece9; end; TTestMFunStr2 = class(TTestCase) protected procedure Setup; override; published procedure TestTran1; procedure TestTran2; procedure TestTran3; procedure TestTran4; end; implementation uses MFunStr_1; var Str: String; Val: String; procedure TTestMFunStr1.TestPiece1; begin Val := Piece(Str,'^'); Check(Val = 'Piece1','Failed Piece not specified'); end; procedure TTestMFunStr1.Setup; begin Str := 'Piece1^Piece2^Piece3'; end; procedure TTestMFunStr1.TestPiece2; begin Val := Piece(Str,'^',2); Check(Val = 'Piece2', 'Failed Piece specified as 2'); end; procedure TTestMFunStr1.TestPiece3; begin Val := Piece(Str,'^',3); Check(Val = 'Piece3', 'Failed Piece specifed as 3'); end; procedure TTestMFunStr1.TestPiece4; begin Val := Piece(Str,'^',4); Check(Val = '','Failed piece specifed as 4'); end; procedure TTestMFunStr1.TestPiece5; begin Val := Piece(Str,'^',1,2); Check(Val = 'Piece1^Piece2','Failed Piece 1,2'); end; procedure TTestMFunStr1.TestPiece6; begin Val := Piece(Str,'^',2,3); Check(Val = 'Piece2^Piece3','Failed Piece 2,3'); end; procedure TTestMFunStr1.TestPiece7; begin Val := Piece(Str,'^',2,4); Check(Val = 'Piece2^Piece3', 'Failed on Piece 2,4'); end; procedure TTestMFunStr1.TestPiece8; begin Val := Piece(Str,'^',3,5); Check(Val = 'Piece3','Failed on Piece 3,5'); end; procedure TTestMFunStr1.TestPiece9; begin Val := Piece(Str,'^',4,6); Check(Val = '','Failed on Piece 4,6'); end; procedure TTestMFunStr2.Setup; begin Str := 'ABCDEFGHABCDE'; end; procedure TTestMFunStr2.TestTran1; begin Val := Translate(Str,'ABCDEFGH','abcdefgh'); Check(Val = 'abcdefghabcde','Failed upper to lower case'); end; procedure TTestMFunStr2.TestTran2; begin Val := Translate(Str,'ABCD','abcde'); Check(Val = 'abcdEFGHabcdE', 'Failed Partial'); end; procedure TTestMFunStr2.TestTran3; begin Val := Translate(Str,'ABCDEABC','abcdefgh'); Check(Val = 'abcdeFGHabcde', 'Failed repeat chars'); end; procedure TTestMFunStr2.TestTran4; begin Val := Translate(Str,'ABCDEFGH','abcdeabc'); Check(Val = 'abcdeabcabcde', 'Failed in assignment'); end; { // used with second method of registering tests function UnitTests: ITestSuite; var ATestSuite: TTestSuite; begin ATestSuite := TTestSuite.create('Some trivial tests'); // add each test suite to be tested ATestSuite.addSuite(TTestType.Suite); // ATestSuite.addSuite(TTestStringlist.Suite); Result := ATestSuite; end; } { procedure TTestType.TestName1; begin // Check( Boolean true for success, String comment for failed test) Check(1+1=2,'Comment on Failure') end; } initialization // one entry per testclass TestFramework.RegisterTest('Test Piece',TTestMFunStr1.Suite); TestFramework.RegisterTest('Test Translate',TTestMFunStr2.Suite); // or // TestFramework.RegisterTest('SimpleTest',UnitTests); end.
{ girfiles.pas Copyright (C) 2011 Andrew Haines andrewd207@aol.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. } unit girFiles; {$mode objfpc}{$H+} {$INTERFACES CORBA} interface uses Classes, SysUtils, DOM, girNameSpaces, girParser; type { TgirFile } TgirFile = class(IgirParser) private FNameSpaces: TgirNamespaces; FOnNeedGirFile: TgirNeedGirFileEvent; FOwner: TObject; procedure ParseNode(ANode: TDomNode); procedure SetOnNeedGirFile(AValue: TgirNeedGirFileEvent); procedure SetOwner(const AValue: TObject); procedure ParseIncludeNode(ANode: TDomNode; AIncludes: TList); public constructor Create(AOwner: TObject); destructor Destroy; override; procedure ParseXMLDocument(AXML: TXMLDocument); property NameSpaces: TgirNamespaces read FNameSpaces; property Owner: TObject read FOwner write SetOwner; property OnNeedGirFile: TgirNeedGirFileEvent read FOnNeedGirFile write SetOnNeedGirFile; end; implementation uses girErrors, girTokens; { TgirFile } { TgirFile } procedure TgirFile.ParseNode(ANode: TDomNode); var Node: TDomNode; NS: TgirNamespace; Includes: TList; begin if ANode.NodeName <> 'repository' then girError(geError, 'Not a Valid Document Type!'); Node := Anode.FirstChild; Ns := nil; Includes := TList.Create; while Node <> nil do begin case GirTokenNameToToken(Node.NodeName) of gtInclude: ParseIncludeNode(Node, Includes); gtNameSpace: begin NS := TgirNamespace.CreateFromRepositoryNode(NameSpaces, ANode, Includes); girError(geDebug, 'Adding Namespace '+NS.NameSpace+' to NameSpaces'); FNameSpaces.Add(NS); girError(geDebug, 'Added Namespace '+NS.NameSpace); NS.ParseNode(Node); end; gtPackage, gtCInclude: ;// ignore for now else girError(geDebug, 'Unknown Node Type for Reposiotory: '+ node.NodeName); end; Node := Node.NextSibling; end; {ANode := ANode.FindNode('namespace'); if ANode = nil then girError(geError, 'namespace node not found') else begin end;} end; procedure TgirFile.SetOnNeedGirFile(AValue: TgirNeedGirFileEvent); begin FNameSpaces.OnNeedGirFile:=AValue; if FOnNeedGirFile=AValue then Exit; FOnNeedGirFile:=AValue; end; procedure TgirFile.SetOwner(const AValue: TObject); begin if FOwner=AValue then exit; FOwner:=AValue; end; procedure TgirFile.ParseIncludeNode(ANode: TDomNode; AIncludes: TList); var NS: TgirNamespace; NSName, NSVersion: String; begin NSName := TDOMElement(ANode).GetAttribute('name'); NSVersion := TDOMElement(ANode).GetAttribute('version'); NS := FNameSpaces.FindNameSpace(NSName, NSVersion); if NS <> nil then begin AIncludes.Add(NS); end; end; constructor TgirFile.Create(AOwner: TObject); begin Owner := AOwner; FNameSpaces := TgirNamespaces.Create(Self); end; destructor TgirFile.Destroy; begin FNameSpaces.Free; inherited Destroy; end; procedure TgirFile.ParseXMLDocument(AXML: TXMLDocument); begin Self.ParseNode(AXML.DocumentElement); end; end.
unit StructureEnumeration; interface uses SysUtils, Rtti, TypInfo, System.Generics.Collections, Data.DbxJson ; type TStructureItem = TPair<string, TValue>; IArrayAccess = interface function GetLength: integer; function GetItemAt(const idx: integer): TStructureItem; function GetEnumerator: TEnumerator<TStructureItem>; property Length: integer read GetLength; property Item[const idx: integer]: TStructureItem read GetItemAt; default; end; TValueAsArray = class(TInterfacedObject, IArrayAccess) private FValue: TValue; protected { IArrayAccess } function GetLength: integer; function GetItemAt(const idx: integer): TStructureItem; function GetEnumerator: TEnumerator<TStructureItem>; public constructor Create(const value: TValue); end; TRawArray<T> = class(TInterfacedObject, IArrayAccess) private FValues: TArray<T>; private constructor Create(const values: TArray<T>); protected { IArrayAccess } function GetLength: integer; function GetItemAt(const idx: integer): TStructureItem; function GetEnumerator: TEnumerator<TStructureItem>; public class function From(const values: TArray<T>): TRawArray<T>; overload; class function From(const values: array of T): TRawArray<T>; overload; end; TArrayAccessEnumerator = class(TEnumerator<TStructureItem>) private FOwner: IArrayAccess; FIndex: integer; protected function DoGetCurrent: TStructureItem; override; function DoMoveNext: Boolean; override; public constructor Create(const owner: IArrayAccess); end; function ParseStructure(const value: TValue): IArrayAccess; function StructureToJson(const value: TValue): TJSONValue; function ArrayToJson(const arr: IArrayAccess): TJSONValue; implementation type TStructureEnumerable = class(TInterfacedObject, IArrayAccess) private FValue: TValue; FFields: TArray<TRttiField>; protected { IArrayAccess } function GetLength: integer; function GetItemAt(const idx: integer): TStructureItem; function GetEnumerator: TEnumerator<TStructureItem>; public constructor Create(const value: TValue); end; { TStructureEnumerable } constructor TStructureEnumerable.Create(const value: TValue); var ctx: TRttiContext; begin FValue := value; ctx := TRttiContext.Create; try FFields := ctx.GetType(FValue.TypeInfo).GetDeclaredFields; finally ctx.Free; end; end; function TStructureEnumerable.GetEnumerator: TEnumerator<TStructureItem>; begin Result := TArrayAccessEnumerator.Create(Self); end; function TStructureEnumerable.GetItemAt(const idx: integer): TStructureItem; begin Assert((idx >= Low(FFields)) and (idx <= High(FFields))); Result := TStructureItem.Create( FFields[idx].Name, FFields[idx].GetValue(FValue.GetReferenceToRawData) ); end; function TStructureEnumerable.GetLength: integer; begin Result := Length(FFields); end; { TValueAsArray } constructor TValueAsArray.Create(const value: TValue); begin Assert(value.Kind in [tkDynArray]); FValue := value; end; function TValueAsArray.GetEnumerator: TEnumerator<TStructureItem>; begin Result := TArrayAccessEnumerator.Create(Self); end; function TValueAsArray.GetItemAt(const idx: integer): TStructureItem; begin Assert((idx >= 0) and (idx < Self.GetLength)); Result := TStructureItem.Create( idx.ToString, FValue.GetArrayElement(idx) ); end; function TValueAsArray.GetLength: integer; begin Result := FValue.GetArrayLength; end; { TRawArray<T> } constructor TRawArray<T>.Create(const values: TArray<T>); begin FValues := values; end; class function TRawArray<T>.From(const values: array of T): TRawArray<T>; var i: integer; arr: TArray<T>; begin SetLength(arr, Length(values)); for i := Low(values) to High(values) do begin arr[i] := values[i]; end; Result := TRawArray<T>.Create(arr); end; class function TRawArray<T>.From(const values: TArray<T>): TRawArray<T>; begin Result := TRawArray<T>.Create(values); end; function TRawArray<T>.GetEnumerator: TEnumerator<TStructureItem>; begin Result := TArrayAccessEnumerator.Create(Self); end; function TRawArray<T>.GetItemAt(const idx: integer): TStructureItem; begin Assert((idx >= 0) and (idx < Self.GetLength)); Result := TStructureItem.Create( idx.ToString, TValue.From<T>(FValues[idx]) ); end; function TRawArray<T>.GetLength: integer; begin Result := Length(FValues); end; { TStructureEnumerator } constructor TArrayAccessEnumerator.Create( const owner: IArrayAccess); begin FOwner := owner; FIndex := -1; end; function TArrayAccessEnumerator.DoGetCurrent: TStructureItem; begin Result := FOwner[FIndex]; end; function TArrayAccessEnumerator.DoMoveNext: Boolean; begin Inc(FIndex); Result := FOwner.Length > FIndex; end; // ----- function ParseStructure(const value: TValue): IArrayAccess; begin Result := TStructureEnumerable.Create(value); end; function StructureToJson(const value: TValue): TJSONValue; var obj: TJSONObject; item: TStructureItem; begin obj := TJSONObject.Create; for item in ParseStructure(value) do begin if item.Value.Kind in [tkClass, tkRecord, tkInterface] then begin obj.AddPair(item.Key, StructureToJson(item.Value)); end else if item.Value.Kind in [tkDynArray] then begin obj.AddPair(item.Key, ArrayToJson(TValueAsArray.Create(item.Value))); end else begin obj.AddPair(item.Key, item.Value.ToString); end; end; Result := obj; end; function ArrayToJson(const arr: IArrayAccess): TJSONValue; var obj: TJSONArray; item: TStructureItem; begin obj := TJSONArray.Create; for item in arr do begin obj.Add(item.Value.ToString); end; Result := obj; end; end.
unit l3CStringDataObject; // Модуль: "w:\common\components\rtl\Garant\L3\l3CStringDataObject.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3CStringDataObject" MUID: (55E5CAA801A1) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3StorableDataObject , l3Interfaces ; type Tl3CStringDataObject = class(Tl3StorableDataObject, Il3DataObjectInfo) private f_String: Il3CString; protected function pm_GetIsQuestionNeedBeforeFlush: Boolean; function Store(aFormat: Tl3ClipboardFormat; const aPool: IStream): Boolean; override; procedure ClearFields; override; public constructor Create(const aString: Il3CString); reintroduce; class function Make(const aString: Il3CString): IDataObject; reintroduce; end;//Tl3CStringDataObject implementation uses l3ImplUses , SysUtils , l3_String , l3Chars , l3String , Windows //#UC START# *55E5CAA801A1impl_uses* //#UC END# *55E5CAA801A1impl_uses* ; constructor Tl3CStringDataObject.Create(const aString: Il3CString); //#UC START# *55E5CB0A0231_55E5CAA801A1_var* var l_F : Tl3ClipboardFormats; //#UC END# *55E5CB0A0231_55E5CAA801A1_var* begin //#UC START# *55E5CB0A0231_55E5CAA801A1_impl* SetLength(l_F, 3); l_F[0] := CF_UNICODETEXT; l_F[1] := CF_TEXT; l_F[2] := CF_OEMTEXT; inherited Create(l_F); f_String := aString; //#UC END# *55E5CB0A0231_55E5CAA801A1_impl* end;//Tl3CStringDataObject.Create class function Tl3CStringDataObject.Make(const aString: Il3CString): IDataObject; var l_Inst : Tl3CStringDataObject; begin l_Inst := Create(aString); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//Tl3CStringDataObject.Make function Tl3CStringDataObject.pm_GetIsQuestionNeedBeforeFlush: Boolean; //#UC START# *4680FC190114_55E5CAA801A1get_var* //#UC END# *4680FC190114_55E5CAA801A1get_var* begin //#UC START# *4680FC190114_55E5CAA801A1get_impl* Result := false; //#UC END# *4680FC190114_55E5CAA801A1get_impl* end;//Tl3CStringDataObject.pm_GetIsQuestionNeedBeforeFlush function Tl3CStringDataObject.Store(aFormat: Tl3ClipboardFormat; const aPool: IStream): Boolean; //#UC START# *48F37AC50290_55E5CAA801A1_var* function DoStore(aCodePage : Integer; const aStr: Tl3WString): Boolean; var l_S : Tl3_String; l_SizeToWrite : Integer; l_Written : Integer; begin//DoStore if (aStr.SCodePage <> aCodePage) then begin l_S := Tl3_String.Make(aStr); try l_S.CodePage := aCodePage; Assert(l_S.CodePage = aCodePage); Result := DoStore(aCodePage, l_S.AsWStr); Exit; finally FreeAndNil(l_S); end;//try..finally end;//aStr.SCodePage <> aCodePage l_SizeToWrite := (aStr.SLen + 1); // +1 - чтобы терминирующий ноль записать if (aCodePage = CP_Unicode) then l_SizeToWrite := l_SizeToWrite * SizeOf(WideChar); if SUCCEEDED(aPool.Write(aStr.S, l_SizeToWrite, @l_Written)) then Result := (l_SizeToWrite = l_Written) else Result := false; end;//DoStore var l_S : Tl3WString; //#UC END# *48F37AC50290_55E5CAA801A1_var* begin //#UC START# *48F37AC50290_55E5CAA801A1_impl* if (aPool = nil) then Result := false else begin l_S := f_String.AsWStr; Case aFormat of CF_TEXT: if l3IsANSI(l_S.SCodePage) then Result := DoStore(l_S.SCodePage, l_S) else Result := DoStore(CP_ANSI, l_S); CF_OEMTEXT: if l3IsOEM(l_S.SCodePage) then Result := DoStore(l_S.SCodePage, l_S) else Result := DoStore(CP_OEM, l_S); CF_UNICODETEXT: Result := DoStore(CP_UNICODE, l_S); else Result := false; end;//Case aFormat end;//aPool = nil //#UC END# *48F37AC50290_55E5CAA801A1_impl* end;//Tl3CStringDataObject.Store procedure Tl3CStringDataObject.ClearFields; begin f_String := nil; inherited; end;//Tl3CStringDataObject.ClearFields end.
unit evDecorHotSpot; // Модуль: "w:\common\components\gui\Garant\Everest\evDecorHotSpot.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevDecorHotSpot" MUID: (4E1D961D02D6) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface {$If Defined(evNeedHotSpot)} uses l3IntfUses , evHotSpotProxy , nevTools , nevGUIInterfaces , evDecorHyperlink , nevDecorActiveHyperlink , l3Interfaces ; type TevDecorHotSpot = class(TevHotSpotProxy) protected f_Para: InevPara; protected function NeedProxyHyperlink: Boolean; virtual; function GetDecorHyperlinkClass: RevDecorHyperlink; virtual; function DoTransMouseMove(const aView: InevControlView; const aKeys: TevMouseState; out theActiveElement: InevActiveElement): Boolean; override; procedure ClearFields; override; public constructor Create(const aPara: InevPara; const aHotSpot: IevHotSpot); reintroduce; class function Make(const aPara: InevPara; const aHotSpot: IevHotSpot): IevHotSpot; reintroduce; function GetDecorActiveHyperlinkClass: RnevDecorActiveHyperlinkClass; virtual; function QueryInterface(const IID: TGUID; out Obj): HResult; override; {* Приводит базовый интерфейс к запрашиваемуму, если это возможно. } end;//TevDecorHotSpot {$IfEnd} // Defined(evNeedHotSpot) implementation {$If Defined(evNeedHotSpot)} uses l3ImplUses , l3InterfacesMisc , SysUtils , nevNavigation //#UC START# *4E1D961D02D6impl_uses* //#UC END# *4E1D961D02D6impl_uses* ; constructor TevDecorHotSpot.Create(const aPara: InevPara; const aHotSpot: IevHotSpot); //#UC START# *4E1D79FC01E9_4E1D961D02D6_var* //#UC END# *4E1D79FC01E9_4E1D961D02D6_var* begin //#UC START# *4E1D79FC01E9_4E1D961D02D6_impl* Assert(aPara <> nil); inherited Create(aHotSpot); f_Para := aPara; //#UC END# *4E1D79FC01E9_4E1D961D02D6_impl* end;//TevDecorHotSpot.Create class function TevDecorHotSpot.Make(const aPara: InevPara; const aHotSpot: IevHotSpot): IevHotSpot; var l_Inst : TevDecorHotSpot; begin l_Inst := Create(aPara, aHotSpot); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TevDecorHotSpot.Make function TevDecorHotSpot.NeedProxyHyperlink: Boolean; //#UC START# *552FAB2002BB_4E1D961D02D6_var* //#UC END# *552FAB2002BB_4E1D961D02D6_var* begin //#UC START# *552FAB2002BB_4E1D961D02D6_impl* Result := True; //#UC END# *552FAB2002BB_4E1D961D02D6_impl* end;//TevDecorHotSpot.NeedProxyHyperlink function TevDecorHotSpot.GetDecorHyperlinkClass: RevDecorHyperlink; //#UC START# *55F6D02B0013_4E1D961D02D6_var* //#UC END# *55F6D02B0013_4E1D961D02D6_var* begin //#UC START# *55F6D02B0013_4E1D961D02D6_impl* Result := TevDecorHyperlink; //#UC END# *55F6D02B0013_4E1D961D02D6_impl* end;//TevDecorHotSpot.GetDecorHyperlinkClass function TevDecorHotSpot.GetDecorActiveHyperlinkClass: RnevDecorActiveHyperlinkClass; //#UC START# *55F7C7110022_4E1D961D02D6_var* //#UC END# *55F7C7110022_4E1D961D02D6_var* begin //#UC START# *55F7C7110022_4E1D961D02D6_impl* Result := TnevDecorActiveHyperlink; //#UC END# *55F7C7110022_4E1D961D02D6_impl* end;//TevDecorHotSpot.GetDecorActiveHyperlinkClass function TevDecorHotSpot.QueryInterface(const IID: TGUID; out Obj): HResult; {* Приводит базовый интерфейс к запрашиваемуму, если это возможно. } //#UC START# *47A0AD3A01F7_4E1D961D02D6_var* //#UC END# *47A0AD3A01F7_4E1D961D02D6_var* begin //#UC START# *47A0AD3A01F7_4E1D961D02D6_impl* Result := inherited QueryInterface(IID, Obj); if NeedProxyHyperlink then if l3IOk(Result) AND SysUtils.IsEqualGUID(IID, IevHyperlink) then IevHyperlink(Obj) := GetDecorHyperlinkClass.Make(f_Para, IevHyperlink(Obj)); //#UC END# *47A0AD3A01F7_4E1D961D02D6_impl* end;//TevDecorHotSpot.QueryInterface function TevDecorHotSpot.DoTransMouseMove(const aView: InevControlView; const aKeys: TevMouseState; out theActiveElement: InevActiveElement): Boolean; //#UC START# *4E1D94EF002C_4E1D961D02D6_var* //#UC END# *4E1D94EF002C_4E1D961D02D6_var* begin //#UC START# *4E1D94EF002C_4E1D961D02D6_impl* Result := inherited DoTransMouseMove(aView, aKeys, theActiveElement); if NeedProxyHyperlink then if Result then begin if (theActiveElement = nil) then Result := false else theActiveElement := GetDecorActiveHyperlinkClass.Make(f_Para, theActiveElement); end;//Result //#UC END# *4E1D94EF002C_4E1D961D02D6_impl* end;//TevDecorHotSpot.DoTransMouseMove procedure TevDecorHotSpot.ClearFields; begin f_Para := nil; inherited; end;//TevDecorHotSpot.ClearFields {$IfEnd} // Defined(evNeedHotSpot) end.
unit StopStatementParsingTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FpcUnit, TestRegistry, ParserBaseTestCase, WpcScriptCommons, WpcStatements, WpcScriptParser, WpcExceptions; type { TStopStatementParsingTestCase } TStopStatementParsingTestCase = class(TParserBaseTestCase) protected StopStatement : TWpcStopStatement; published procedure ShouldParseBaseStopStatement(); procedure ShouldParseStopStatementWithProbabilityProperty(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties(); end; implementation { TStopStatementParsingTestCase } // STOP procedure TStopStatementParsingTestCase.ShouldParseBaseStopStatement(); begin ScriptLines.Add(STOP_KEYWORD); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_STOP_STATEMENT_ID = MainBranchStatements[0].GetId()); StopStatement := TWpcStopStatement(MainBranchStatements[0]); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_PROBABILITY, StopStatement.GetProbability()); end; // STOP WITH PROBABILITY 50 procedure TStopStatementParsingTestCase.ShouldParseStopStatementWithProbabilityProperty(); begin ScriptLines.Add(STOP_KEYWORD + WITH_PROBABILITY_PROPERTY); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_STOP_STATEMENT_ID = MainBranchStatements[0].GetId()); StopStatement := TWpcStopStatement(MainBranchStatements[0]); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_PROBABILITY_VALUE, StopStatement.GetProbability()); end; // STOP AT procedure TStopStatementParsingTestCase.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase(); begin ScriptLines.Add(STOP_KEYWORD + ' AT'); WrapInMainBranch(ScriptLines); AssertScriptParseExceptionOnParse(1, 1); end; // STOP ALWAYS WITH PROBABILITY 50 procedure TStopStatementParsingTestCase.SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties(); begin ScriptLines.Add(STOP_KEYWORD + ' ALWAYS ' + WITH_PROBABILITY_PROPERTY); WrapInMainBranch(ScriptLines); AssertScriptParseExceptionOnParse(1, 1); end; // STOP WITH PROBABILITY 50 ANYTIME procedure TStopStatementParsingTestCase.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties; begin ScriptLines.Add(STOP_KEYWORD + WITH_PROBABILITY_PROPERTY + ' ANYTIME '); WrapInMainBranch(ScriptLines); AssertScriptParseExceptionOnParse(1, 4); end; initialization RegisterTest(PARSER_TEST_SUITE_NAME, TStopStatementParsingTestCase); end.
unit evdNativeUnpackedWriter; {* Писатель тегов в формате evd. } { Библиотека "Эверест" } { Автор: Люлин А.В. © } { Модуль: evEvdWrt - генератор текстов в формате evd } { Начат: 05.10.1999 13:00 } { $Id: evdNativeUnpackedWriter.pas,v 1.15 2014/09/01 09:42:07 lulin Exp $ } // $Log: evdNativeUnpackedWriter.pas,v $ // Revision 1.15 2014/09/01 09:42:07 lulin // - начинаем делать возможность задавать тегам артибуты типа "множество". // // Revision 1.14 2014/04/22 14:20:16 lulin // - переходим от интерфейсов к объектам. // // Revision 1.13 2014/04/09 16:03:02 lulin // - переходим от интерфейсов к объектам. // // Revision 1.12 2014/04/09 15:45:01 lulin // - переходим от интерфейсов к объектам. // // Revision 1.11 2014/03/27 14:20:05 lulin // - переходим от интерфейсов к объектам. // // Revision 1.10 2014/03/25 16:23:45 lulin // - переходим от интерфейсов к объектам. // // Revision 1.9 2014/03/06 17:23:24 lulin // - избавляемся от теговых обёрток. // // Revision 1.8 2013/10/23 16:04:43 lulin // - правильнее определяем "автоматические" типы. // // Revision 1.7 2013/10/22 16:45:05 lulin // - реорганизуем таблицу тегов, чтобы избавится от "шаманства" и идентификаторами. // // Revision 1.6 2013/10/21 15:43:12 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.5 2013/10/21 10:31:00 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.4 2013/10/18 14:11:31 lulin // - потихоньку избавляемся от использования идентификаторов типов тегов. // // Revision 1.3 2013/04/04 11:21:18 lulin // - портируем. // // Revision 1.2 2012/07/12 18:33:16 lulin // {RequestLink:237994598} // // Revision 1.1 2011/12/19 17:36:03 lulin // {RequestLink:282693895} // - делаем тест. // // Revision 1.55 2011/07/07 19:53:56 lulin // {RequestLink:228688745}. // // Revision 1.54 2010/06/22 12:50:12 lulin // {RequestLink:219122682}. // - bug fix: были проблемы с новыми пакованными комментариями. // // Revision 1.53 2010/06/18 14:14:48 lulin // {RequestLink:182452717}. // - меняем способ нумерования версий. Теперь версии нумеруем с шагом 20. 0-е - это Архивариус, 1-е - это F1. // // Revision 1.52 2010/06/15 12:46:37 lulin // {RequestLink:159355611}. // - правильнее инициализируем признак записи бинарности файла. // // Revision 1.50 2010/06/10 11:35:31 lulin // {RequestLink:159355611}. // // Revision 1.49 2009/07/06 16:38:17 lulin // - вычищаем ненужное. // // Revision 1.48 2009/07/03 16:24:09 lulin // - шаг к переходу от интерфейсов к объектам. // // Revision 1.47 2009/03/18 14:59:52 lulin // - делаем возможность отката, если во время записи произошло исключение. // // Revision 1.46 2009/03/04 13:33:09 lulin // - <K>: 137470629. Генерируем идентификаторы типов с модели и убираем их из общей помойки. // // Revision 1.45 2009/02/27 07:14:56 lulin // - <K>: 137465982. №26. // // Revision 1.44 2009/01/16 12:12:50 lulin // - bug fix: не падаем при записи невалидных текстовых EVD. // // Revision 1.43 2008/06/19 12:55:26 lulin // - переименованы константы. // // Revision 1.42 2008/02/20 17:23:05 lulin // - упрощаем строки. // // Revision 1.41 2008/02/19 18:48:17 lulin // - удалены ненужные классы. // // Revision 1.40 2008/02/19 11:05:55 lulin // - восстановил всякие экзотические поиски в списках объектов. // // Revision 1.39 2008/02/13 16:03:10 lulin // - убраны излишне гибкие методы поиска. // // Revision 1.38 2008/02/07 19:13:13 lulin // - избавляемся от излишне универсальных методов базовых списков. // // Revision 1.37 2008/02/06 11:44:39 lulin // - список строк переехал в отдельный файл. // // Revision 1.36 2008/02/05 18:20:38 lulin // - удалено ненужное свойство строк. // // Revision 1.35 2008/02/05 17:39:35 lulin // - избавляемся от ненужного именованного объекта. // // Revision 1.34 2008/02/05 16:13:12 lulin // - избавляем базовый объект от лишнего свойства. // // Revision 1.33 2008/02/05 12:49:20 lulin // - упрощаем базовые объекты. // // Revision 1.32 2008/02/01 15:14:50 lulin // - избавляемся от излишней универсальности списков. // // Revision 1.31 2007/09/25 13:55:42 lulin // - bug fix: не собиралось для Эверест (Lite). // // Revision 1.30 2007/08/29 17:05:04 lulin // - записываем короткую кодировку, если это возможно. // // Revision 1.29 2007/08/29 15:04:50 lulin // - страхуемся от попытки чтнения неверного формата. // // Revision 1.28 2007/08/29 14:52:33 lulin // - не пишем информацию о текстовых скобках. // // Revision 1.27 2007/08/29 14:27:02 lulin // - пакуем EVD-теги - вместо слова, пишем байт. // // Revision 1.26 2007/08/29 12:54:46 lulin // - cleanup. // // Revision 1.25 2007/08/29 12:46:19 lulin // - cleanup. // // Revision 1.24 2007/08/29 12:37:08 lulin // - файл версий переехал в правильную папку. // // Revision 1.23 2007/08/29 12:00:33 lulin // - константы распилены на два файла. // // Revision 1.22 2007/08/10 19:17:24 lulin // - cleanup. // // Revision 1.21 2007/08/09 18:05:28 lulin // - избавляемся от излишнего использования интерфейсов, т.к. переносимость может быть достигнута другими методами. // // Revision 1.20 2007/08/09 16:14:25 lulin // - обходимся без приведения типов. // // Revision 1.19 2007/08/09 16:12:06 lulin // - bug fix: не собиралась библиотека. // // Revision 1.18 2007/08/09 14:55:25 lulin // - избавляемся от излишнего использования интерфейсов. // // Revision 1.17 2007/08/09 13:01:44 lulin // - изолируем потомков от излишних знаний о внутренностях базового генератора. // // Revision 1.16 2007/08/09 11:19:25 lulin // - cleanup. // // Revision 1.15 2007/08/09 09:17:53 lulin // - cleanup. // // Revision 1.14 2006/12/01 17:08:06 lulin // - обращаемся к символам строки напрямую. // // Revision 1.13 2006/12/01 17:00:52 lulin // - bug fix: корректно записываем Unicode-строки. // // Revision 1.12 2006/12/01 16:45:17 lulin // - cleanup. // // Revision 1.11 2006/12/01 16:37:38 lulin // - cleanup. // // Revision 1.10 2006/11/25 16:50:30 lulin // - удалена запись,чтение маски заполненных тегов. // // Revision 1.9 2006/11/24 19:21:17 lulin // - корректно используем Unicode строки. // // Revision 1.8 2006/02/07 15:16:31 lulin // - попытка доточить под ветку (пока неудачно). // // Revision 1.7 2005/11/08 14:11:28 lulin // - new behavior: для атомарных атрибутов пытаемся преобразовывать строки в числа. // // Revision 1.6 2005/11/08 13:51:15 lulin // - cleanup. // // Revision 1.5 2005/11/08 13:46:55 lulin // - cleanup. // // Revision 1.3 2005/11/08 13:39:09 lulin // - bug fix: падало при попытке записать несуществующий атрибут. // // Revision 1.2 2005/10/28 12:48:17 lulin // - bug fix: не всегда записывались картинки в EVD. // // Revision 1.1 2005/07/21 13:00:42 lulin // - писатель формата EVD переехал в папку EVD. // // Revision 1.65.4.4 2005/07/21 10:20:04 lulin // - теперь TextSource не знает как создавать Reader'ы, а про это знает контейнер документа. // // Revision 1.65.4.3 2005/06/23 13:08:24 lulin // - файл с ключевыми словами переехал в папку EVD. // // Revision 1.65.4.2 2005/06/23 12:55:33 lulin // - файл с константами переехал в папку EVD. // // Revision 1.65.4.1 2005/05/18 12:42:46 lulin // - отвел новую ветку. // // Revision 1.64.2.2 2005/05/18 12:32:08 lulin // - очередной раз объединил ветку с HEAD. // // Revision 1.64.2.1 2005/04/28 09:18:29 lulin // - объединил с веткой B_Tag_Box. // // Revision 1.64.4.1 2005/04/22 10:40:27 lulin // - cleanup: убраны ненужные параметры. // // Revision 1.65 2005/04/28 15:03:37 lulin // - переложил ветку B_Tag_Box в HEAD. // // Revision 1.64.4.1 2005/04/22 10:40:27 lulin // - cleanup: убраны ненужные параметры. // // Revision 1.64 2005/03/25 17:09:01 lulin // - избавляемся от метода Tk2AtomW.sLong. // // Revision 1.63 2005/03/25 12:12:14 lulin // - используем _Ik2Type вместо Tk2Type. // // Revision 1.62 2005/03/22 17:03:04 lulin // - спрятаны ненужные методы. Чуть подоптимизирована загрузка - ГК в Эвересте на 1 сек меньше. // // Revision 1.61 2005/03/22 10:38:01 lulin // - cleanup. // // Revision 1.60 2005/03/22 09:05:56 narry // - bug fix: AV // // Revision 1.59 2005/03/21 13:42:58 lulin // - убраны ненужные методы. // // Revision 1.58 2005/03/21 10:04:49 lulin // - new interface: _Ik2Type. // // Revision 1.57 2004/09/21 12:55:40 lulin // - Release заменил на Cleanup. // // Revision 1.56 2004/06/10 09:32:09 law // - bug fix: неправильно записывались документы в бинарном виде в структурированное хранилище. // // Revision 1.55 2004/06/02 15:12:07 law // - конструкторы Make перенесены с _Tl3PVList на _Tl3PtrRecList. // // Revision 1.54 2004/05/14 18:06:41 law // - change: методы, связанные с генерацией evd перенесены с TevCustomFileGenerator на TevCustomEvdWriter. // // Revision 1.53 2004/05/14 16:22:57 law // - remove class: TevTextObjectGenerator. // - remove class: TevTextObjectParser. // // Revision 1.52 2004/05/14 16:07:56 law // - new units: evFileGenerator, evPlainTextGenerator. // // Revision 1.51 2004/05/14 15:16:52 law // - remove unit: evTypesE. // // Revision 1.50 2004/05/14 14:48:47 law // - исправлены префиксы у констант. // // Revision 1.49 2004/05/14 14:08:49 law // - change: TevVariant переименован в Tk2Variant и переехал в k2Types. // // Revision 1.48 2003/10/21 16:57:23 law // - new behavior: TevCustomEVDWriter - не вызываем _Flush при Undo (может это спорно может надо откатывать накопленные теги). // // Revision 1.47 2003/10/20 11:07:43 law // - bug fix: при формировании EVD-текст (для одного параграфа) оформление для всех парагграфов накапливалось в буфере. // // Revision 1.46 2003/10/20 09:43:07 law // - bug fix: при параллельном залитии справки и текста не ставилась директива %binary. // // Revision 1.45 2003/10/15 13:11:13 law // - bug fix: оформление параграфов накапливалось в один буфер. // // Revision 1.44 2003/10/15 08:29:20 law // - bug fix: оформление параграфов накапливалось в один буфер. // // Revision 1.43 2003/10/14 13:11:53 law // - new method: IeeGenerator._AddRawData. // // Revision 1.42 2003/10/14 12:48:30 law // - new prop: TevCustomEvdWriter.SkipTopBrackets. // // Revision 1.41 2003/10/14 12:15:59 law // - new prop: TevCustomEvdWriter.NeedOutHeader. // // Revision 1.40 2003/10/14 12:02:08 law // - bug fix: при записи в evd два раза писали директиву %binary. // // Revision 1.39 2003/06/23 11:09:44 law // - bug fix: не записывался текст в формате EVD-Binary. // // Revision 1.38 2003/04/25 10:46:23 law // - bug fix: нельзя было по-простому добавить ссылку. // // Revision 1.37 2002/09/23 12:18:19 law // - new prop: Tk2ChildrenProperty._DefaultChildType. // // Revision 1.36 2002/09/18 09:33:26 law // - new behavior: при записи в evd-binary опускаем тип дочернего тега по умолчанию. // // Revision 1.35 2002/09/18 09:02:46 law // - new behavior: при записи в evd-текст опускаем имя типа дочернего тега по умолчанию. // // Revision 1.34 2002/09/18 07:08:02 law // - new units: k2StackGenerator, k2Ver. // - new behavior: Tk2CustomReader теперь наследуется от Tk2CustomStackGenerator и соответственно наследует его поведение. // // Revision 1.33 2002/09/18 06:03:32 law // - cleanup: удален параметр IsDefault. // // Revision 1.32 2002/01/29 16:18:49 law // - bug fix: Range Check Error при записывании размера маски. // // Revision 1.31 2002/01/05 11:00:43 law // - some cosmetics. // // Revision 1.30 2001/10/23 15:21:31 law // - new proc: TevCustomEvdWriter._OutBinary. // // Revision 1.29 2001/10/19 16:20:22 law // - new unit: evEvdWriter. // // Revision 1.28 2001/09/11 10:11:08 law // - change method: добавлен параметр по умолчанию. // // Revision 1.27 2001/08/31 08:50:07 law // - cleanup: первые шаги к кроссплатформенности. // // Revision 1.26 2001/05/31 09:23:40 law // - cleanup: убрана работа со старой логикой масок тегов. // // Revision 1.25 2001/05/31 08:30:33 law // - cleanup: убрана запись компонент. // - comments: добавлены комментарии для xHelpGen. // // Revision 1.24 2001/04/18 13:56:35 law // - bug fix: AV при поиска TevTextObjectParser. // // Revision 1.23 2001/04/18 13:25:23 law // - comments: добавлены комментарии для xHelpGen. // // Revision 1.22 2001/03/27 13:59:43 law // - bug fix: неправильно выливалась таблица шрифтов. // // Revision 1.21 2001/03/14 13:24:54 law // - some cleaup and tuning. // // Revision 1.20 2001/03/13 13:20:39 law // - some tuning & comments. // // Revision 1.19 2001/01/24 14:53:43 law // - сделано более компактное сохранение имен шрифто // // Revision 1.18 2000/12/19 15:52:40 law // - убраны ненужные директивы компиляции. // // Revision 1.17 2000/12/15 15:10:35 law // - вставлены директивы Log. // {$Include evdDefine.inc } interface uses Classes, l3Types, l3Base, l3StringList, l3Variant, l3Interfaces, k2Interfaces, k2Types, k2Base, k2TagGen, k2FileGenerator, evdConst ; type TevdNativeUnpackedWriter = class(Tk2CustomFileGenerator) {* Писатель тегов в формате evd. } private {property fields} f_OutEndComment : Bool; f_FontNames : Tl3StringList; f_WasBinary : Boolean; f_NeedOutHeader : Boolean; f_SkipTopBrackets : Boolean; f_SmallHeader : Boolean; protected // property methods function pm_GetIndent: Long; virtual; {-} protected // internal methods procedure OutObject(AtomIndex: Long; O: Tl3Variant); {-} procedure WriteStream(aStream: TStream); {-} { procedure OutPropPath(PI: PPropInfo); {-} procedure CloseStream(NeedUndo: Bool); override; {-вызывается один раз в конце генерации} procedure CloseStructure(NeedUndo: Bool); override; {-вызывается на закрывающуюся скобку} function GetKeyWord(anID: Long): string; {-} procedure OutKeyWord(anID: Long); {-} procedure Cleanup; override; {-} procedure DoStartChild(TypeID: Tk2Type); //virtual; {-} procedure DoCloseStructure(NeedUndo: Bool); virtual; {-} procedure WriteStartChild(TypeID: Tk2Type); {-} procedure WriteAtom(AtomIndex: Long; const Value: Tk2Variant); {-} procedure OutBinary(WithPrefix: Bool = true); {-} procedure OutEndBinary; {-} function WriteTypeID(ID: TevTypeID): Long; {-} function WriteOrd(V: sInt32): Long; {-} function WriteTransparent: Long; {-} function WriteString(S : Tl3WString): Long; {-} public // public methods constructor Create(anOwner: Tk2TagGeneratorOwner = nil); override; {- P - адрес указателя куда будет положен Self} procedure StartTag(TagID: Long); override; {-} procedure StartChild(TypeID: Tl3VariantDef); override; {-} procedure AddAtomEx(AtomIndex: Long; const Value: Tk2Variant); override; {-} procedure AfterStreamOpened; override; {-} procedure OutHeader; virtual; {-} public // public properties property WasBinary: Boolean read f_WasBinary write f_WasBinary; {-} property Indent: Long read pm_GetIndent; {* - текущий уровень вложенности. } property OutEndComment : Bool read f_OutEndComment write f_OutEndComment default false; {-} property NeedOutHeader: Boolean read f_NeedOutHeader write f_NeedOutHeader; {-} property SkipTopBrackets: Boolean read f_SkipTopBrackets write f_SkipTopBrackets; {-} property SmallHeader: Boolean read f_SmallHeader write f_SmallHeader; {-} end;{TevdNativeUnpackedWriter} implementation uses SysUtils, TypInfo, l3Chars, l3String, k2Tags, k2Const, k2Except, evdVer, evdKW, evdTxtConst, Document_Const, k2FontName_Const ; // start class TevdNativeUnpackedWriter constructor TevdNativeUnpackedWriter.Create(anOwner: Tk2TagGeneratorOwner = nil); {override;} begin inherited; f_OutEndComment := false; KeyWords := EvdKeyWords; NeedOutHeader := true; end; procedure TevdNativeUnpackedWriter.Cleanup; //override; {-} begin l3Free(f_FontNames); inherited; end; function TevdNativeUnpackedWriter.pm_GetIndent: Long; {-} begin Result := Types.Hi; end; procedure TevdNativeUnpackedWriter.OutBinary(WithPrefix: Bool = true); {-} begin{OutBinary} if not f_WasBinary then begin f_WasBinary := true; Exit; if WithPrefix then OutString(evDirectivePrefix); OutKeyWord(evd_kwBinary); OutEOL; end;//not f_WasBinary end;{OutBinary} procedure TevdNativeUnpackedWriter.OutEndBinary; {-} begin if NeedOutHeader AND not SmallHeader then begin f_WasBinary := false; OutString(evDirectivePrefix + GetKeyWord(evd_kwEndBinary)); end;//NeedOutHeader end; function TevdNativeUnpackedWriter.WriteOrd(V: sInt32): Long; {-} begin if (V >= 0) then begin if (V <= High(uInt8)) then begin Result := WriteTypeID(ev_idUInt8); Inc(Result, WriteBuf(@V, SizeOf(uInt8))); end else if (V <= High(uInt16)) then begin Result := WriteTypeID(ev_idUInt16); Inc(Result, WriteBuf(@V, SizeOf(uInt16))); end else begin Result := WriteTypeID(ev_idUInt32); Inc(Result, WriteBuf(@V, SizeOf(uInt32))); end; end else begin if (V >= Low(sInt8)) then begin Result := WriteTypeID(ev_idSInt8); Inc(Result, WriteBuf(@V, SizeOf(sInt8))); end else if (V >= High(sInt16)) then begin Result := WriteTypeID(ev_idSInt16); Inc(Result, WriteBuf(@V, SizeOf(sInt16))); end else begin Result := WriteTypeID(ev_idSInt32); Inc(Result, WriteBuf(@V, SizeOf(sInt32))); end; end; end; function TevdNativeUnpackedWriter.WriteTransparent: Long; {-} begin Result := WriteTypeID(ev_idTransparent); end; function TevdNativeUnpackedWriter.WriteString(S : Tl3WString): Long; {-} var l_S : Tl3WString; l_CharSize : Long; begin l_S := S; if (l_S.SCodePage = CP_ANSI) OR (l_S.SCodePage = CP_RussianWin) then Result := 0 else begin Result := WriteTypeID(ev_idCodePage); Inc(Result, WriteLong(l_S.SCodePage)); end;{l_S.SCodePage <> CP_ANSI} if (l_S.SCodePage = CP_Unicode) then l_CharSize := SizeOf(WideChar) else l_CharSize := SizeOf(AnsiChar); if (l_S.SLen <= High(uInt8)) AND (l_CharSize = SizeOf(AnsiChar)) then begin Inc(Result, WriteTypeID(ev_idString8)); Inc(Result, WriteByte(l_S.SLen)); Inc(Result, WriteBuf(l_S.S, l_S.SLen)); end//l_S.SLen <= High(uInt8)) AND (l_CharSize = SizeOf(AnsiChar) else begin if (l_S.SLen <= High(uInt16)) then begin Inc(Result, WriteTypeID(ev_idString16)); Inc(Result, WriteWord(l_S.SLen)); end//l_S.SLen <= High(uInt16) else begin Inc(Result, WriteTypeID(ev_idString32)); Inc(Result, WriteLong(l_S.SLen)); end;//l_S.SLen <= High(uInt16) Inc(Result, WriteBuf(l_S.S, l_S.SLen * l_CharSize)); end;//SLen <= High(uInt8) end; function TevdNativeUnpackedWriter.WriteTypeID(ID: TevTypeID): Long; {-} begin Result := WriteBuf(@ID, SizeOf(ID)); end; procedure TevdNativeUnpackedWriter.OutHeader; {-} var Title : String; begin if NeedOutHeader then begin if (Filer.Pos = 0) then begin f_WasBinary := false; if not SmallHeader then begin Title := l3System.AppTitle; if not IsValidIdent(Title) then Title := cc_SingleQuote + Title + cc_SingleQuote; OutString(evDirectivePrefix); OutKeyWord(evd_kwProducer); OutString(cc_HardSpace + Title + cc_HardSpace); OutKeyWord(evd_kwDate); OutString(cc_HardSpace + cc_SingleQuote + DateToStr(Date) + cc_SingleQuote); OutEOL; Assert(evFormatCurVersionS <> ''); OutString(evDirectivePrefix + GetKeyWord(evd_kwFormat) + cc_HardSpace + GetKeyWord(evd_kwVersion) + cc_HardSpace + evFormatCurVersionS + cc_HardSpace); OutString(GetKeyWord(evd_kwRevision) + cc_HardSpace + GetKeyWord(evd_kwDate) + cc_HardSpace + cc_SingleQuote + evEVDCurRevisionDate + cc_SingleQuote + cc_HardSpace); end;//not SmallHeader OutBinary(SmallHeader) end//Filer.Pos = 0 else OutBinary; end;//NeedOutHeader end; procedure TevdNativeUnpackedWriter.AfterStreamOpened; {override;} {-} begin if Filer.Opened then OutHeader; end; procedure TevdNativeUnpackedWriter.CloseStream(NeedUndo: Bool); {override;} {-вызывается один раз в конце генерации} begin if (f_FontNames <> nil) then f_FontNames.Clear; OutEndBinary; inherited; end; procedure TevdNativeUnpackedWriter.CloseStructure(NeedUndo: Bool); {override;} {-вызывается на закрывающуюся скобку} begin DoCloseStructure(NeedUndo); inherited; end; procedure TevdNativeUnpackedWriter.DoCloseStructure(NeedUndo: Bool); //virtual; {-} begin if (Indent <> 0) OR not SkipTopBrackets then begin if NeedUndo then WriteWord(unpack_idRollback) else WriteWord(unpack_idFinish); end;//Indent <> 0 if (Indent = 0) OR CurrentType.IsKindOf(k2_typDocument) then begin if not NeedUndo then Filer.Flush else Filer.Rollback; if (f_FontNames <> nil) then f_FontNames.Clear; // - очищаем таблицу шрифтов в конце записи документа end;//Indent = 0.. end; function TevdNativeUnpackedWriter.GetKeyWord(anID: Long): string; {-} begin Result := KeyWords.DRByID[anID].AsString; end; procedure TevdNativeUnpackedWriter.OutKeyWord(anID: Long); {-} begin OutString(GetKeyWord(anID)); end; procedure TevdNativeUnpackedWriter.StartTag(TagID: Long); {override;} {-} begin inherited; if (Indent = 0) AND SkipTopBrackets then Exit; if (Indent = 0) then OutHeader; WriteWord(TagID); WriteTypeID(ev_idAtom); end; procedure TevdNativeUnpackedWriter.StartChild(TypeID: Tl3VariantDef); {override;} {-} begin inherited; DoStartChild(Tk2Type(TypeID)); end; procedure TevdNativeUnpackedWriter.DoStartChild(TypeID: Tk2Type); //virtual; {-} begin WriteStartChild(TypeID); end; procedure TevdNativeUnpackedWriter.WriteStartChild(TypeID: Tk2Type); {-} var TT : Tk2TypePrim; begin if (Indent = 0) AND SkipTopBrackets then Exit; if (Indent = 0) then OutHeader; TT := TopType[1]; if (TT <> nil) then begin if (TT.DefaultChildTypeID = TypeID) then begin WriteWord(unpack_idDefaultChild); Exit; end;//l_Prop <> nil.. end;//TT <> nil Assert(not TypeID.IsAuto); WriteWord(TypeID.ID); WriteTypeID(ev_idChild); end; procedure TevdNativeUnpackedWriter.OutObject(AtomIndex: Long; O: Tl3Variant); {-} var l_Index : Long; l_Prop : Tk2CustomPropertyPrim; l_AT : Tk2TypePrim; l_Tag : Tl3Variant; l_S : Tl3WString; begin l_Prop := CurrentType.Prop[AtomIndex]; if (l_Prop = nil) then l_AT := nil else l_AT := Tk2TypePrim(l_Prop.AtomType); if (l_AT <> nil) AND l_AT.IsKindOf(k2_typFontName) then begin if (f_FontNames <> nil) AND f_FontNames.FindData(O.AsWStr, l_Index) then begin WriteTypeID(ev_idFontID); WriteOrd(l_Index); end//f_FontNames <> nil else begin if (f_FontNames = nil) then f_FontNames := Tl3StringList.Make; f_FontNames.Add(O.AsWStr); WriteTypeID(ev_idFontName); WriteString(O.AsWStr) end;//f_FontNames <> nil.. end//..k2_idFontName.. else begin if (l_AT <> nil) then begin Case Tk2Type(l_AT).AtomType^.Kind of tkInteger, tkEnumeration, tkSet: begin try l_Tag := O; //l_Tag := Tk2Type(l_AT)._StrToTag(l3PCharLen2String(O.AsWStr)).AsObject; if l_Tag.IsValid then begin WriteOrd(l_Tag.AsLong); Exit; end;//l_Tag.IsValid except on EConvertError do ; on Ek2ConversionError do ; end;//try..except end;//tkInteger.. end;//Case l_Prop.AtomType.TypeInfo^.Kind end;//l_Prop <> nil WriteString(O.AsWStr); end;//l_Prop <> nil end; procedure TevdNativeUnpackedWriter.WriteStream(aStream: TStream); {-} var StreamSize : Long; begin aStream.Seek(0, soBeginning); StreamSize := aStream.Size; WriteByte(Ord(ev_idStream)); WriteLong(StreamSize); Filer.Stream.CopyFrom(aStream, StreamSize); end; procedure TevdNativeUnpackedWriter.AddAtomEx(AtomIndex: Long; const Value: Tk2Variant); {override;} {-} begin WriteAtom(AtomIndex, Value); end; procedure TevdNativeUnpackedWriter.WriteAtom(AtomIndex: Long; const Value: Tk2Variant); {-} var l_AT : Tk2TypePrim; l_Prop : Tk2CustomPropertyPrim; begin if (AtomIndex = k2_tiChildren) then AtomIndex := unpack_idChildren; with Value do Case Kind of k2_vkString : begin if not AsString.Empty then begin WriteWord(AtomIndex); OutObject(AtomIndex, AsVariant); end;//not AsString.Empty end;//ev_tkString else begin WriteWord(AtomIndex); Case Kind of k2_vkInteger: WriteOrd(AsInteger); k2_vkTransparent: WriteTransparent; k2_vkStream: WriteStream(AsStream); else inherited AddAtomEx(AtomIndex, Value); end;//Case Kind end;//else end;//Case Kind end; end.
unit K623486769_4; {* [Requestlink:623486769] } // Модуль: "w:\common\components\rtl\Garant\Daily\K623486769_4.pas" // Стереотип: "TestCase" // Элемент модели: "K623486769_4" MUID: (574EAFB50329) // Имя типа: "TK623486769_4" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoHTMLWithExternalHyperlinks ; type TK623486769_4 = class(TEVDtoHTMLWithExternalHyperlinks) {* [Requestlink:623486769] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK623486769_4 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *574EAFB50329impl_uses* //#UC END# *574EAFB50329impl_uses* ; function TK623486769_4.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '8.0'; end;//TK623486769_4.GetFolder function TK623486769_4.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '574EAFB50329'; end;//TK623486769_4.GetModelElementGUID initialization TestFramework.RegisterTest(TK623486769_4.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) 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.5 10/26/2004 10:03:22 PM JPMugaas Updated refs. Rev 1.4 4/19/2004 5:05:42 PM JPMugaas Class rework Kudzu wanted. Rev 1.3 2004.02.03 5:45:26 PM czhower Name changes Rev 1.2 1/22/2004 7:20:56 AM JPMugaas System.Delete changed to IdDelete so the code can work in NET. Rev 1.1 10/19/2003 3:48:20 PM DSiders Added localization comments. Rev 1.0 2/19/2003 05:49:50 PM JPMugaas Parsers ported from old framework. } unit IdFTPListParseWinQVTNET; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase; { This was tested with data obtained from WinQVT/Net Version 3.98.15 running on Windows 2000. No parser is required for later versions because those use the Unix listing format. } type TIdWinQVNetFTPListItem = class(TIdFTPListItem); TIdFTPLPWinQVNet = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; 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; end; (*HPPEMIT '#pragma link "IdFTPListParseWinQVTNET"'*) // 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 "IdFTPListParseWinQVTNET"'*) implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils; { TIdFTPLPWinQVNet } class function TIdFTPLPWinQVNet.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var LData : String; begin Result := False; if AListing.Count > 0 then { test.txt 0 10-23-2003 01:01 123456789012345678901234567890123456789012345678901234567890 1 2 3 4 5 6 } begin LData := AListing[0]; Result := (Copy(LData, 38, 1) = '-') and {do not localize} (Copy(LData, 41, 1) = '-') and {do not localize} (Copy(LData, 49, 1) = ':') and {do not localize} IsMMDDYY(Copy(LData, 36, 10), '-') and {do not localize} (Copy(LData, 46, 1) = ' ') and {do not localize} IsHHMMSS(Copy(LData, 47, 5), ':'); {do not localize} end; end; class function TIdFTPLPWinQVNet.GetIdent: String; begin Result := 'WinQVT/NET'; {do not localize} end; class function TIdFTPLPWinQVNet.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdWinQVNetFTPListItem.Create(AOwner); end; class function TIdFTPLPWinQVNet.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuf : String; begin //filename (note that it can contain spaces on WinNT with my test case AItem.FileName := ExtractQVNETFileName(AItem.Data); LBuf := AItem.Data; //item type if IndyPos('/', Copy(LBuf, 1, 13)) > 0 then begin {do not localize} AItem.ItemType := ditDirectory; end; IdDelete(LBuf, 1, 13); LBuf := TrimLeft(LBuf); //Size AItem.Size := IndyStrToInt64(Fetch(LBuf), 0); //Date LBuf := TrimLeft(LBuf); AItem.ModifiedDate := DateMMDDYY(Fetch(LBuf)); //Time LBuf := Trim(LBuf); AItem.ModifiedDate := AItem.ModifiedDate + TimeHHMMSS(LBuf); Result := True; end; initialization RegisterFTPListParser(TIdFTPLPWinQVNet); finalization UnRegisterFTPListParser(TIdFTPLPWinQVNet); end.
unit MFichas.Model.Permissoes.Metodos.Editar; interface uses System.SysUtils, System.Generics.Collections, System.StrUtils, MFichas.Model.Permissoes.Interfaces, MFichas.Model.Entidade.USUARIOPERMISSOES, MFichas.Controller.Types; type TModelPermissoesMetodosEditar = class(TInterfacedObject, iModelPermissoesEditar) private [weak] FParent : iModelPermissoes; FList : TDictionary<String, TTypeTipoUsuario>; FEntidade : TUSUARIOPERMISSOES; FListaPermissoes : TObjectList<TUSUARIOPERMISSOES>; FAbrirCaixa : Integer; FFecharCaixa : Integer; FSuprimentoCaixa : Integer; FSangriaCaixa : Integer; FCadastrarProdutos : Integer; FCadastrarGrupos : Integer; FCadastrarUsuarios : Integer; FAcessarRelatorios : Integer; FAcessarConfiguracoes: Integer; FExcluirProdutos : Integer; constructor Create(AParent: iModelPermissoes; AList: TDictionary<String, TTypeTipoUsuario>); procedure Validacao(AValue: Integer); procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelPermissoes; AList: TDictionary<String, TTypeTipoUsuario>): iModelPermissoesEditar; function AbrirCaixa(ABoolean: Integer) : iModelPermissoesEditar; function FecharCaixa(ABoolean: Integer) : iModelPermissoesEditar; function Suprimento(ABoolean: Integer) : iModelPermissoesEditar; function Sangria(ABoolean: Integer) : iModelPermissoesEditar; function CadastrarProdutos(ABoolean: Integer) : iModelPermissoesEditar; function CadastrarGrupos(ABoolean: Integer) : iModelPermissoesEditar; function CadastrarUsuarios(ABoolean: Integer) : iModelPermissoesEditar; function AcessarRelatorios(ABoolean: Integer) : iModelPermissoesEditar; function AcessarConfiguracoes(ABoolean: Integer) : iModelPermissoesEditar; function ExcluirProdutosPosImpressao(ABoolean: Integer): iModelPermissoesEditar; function Executar : iModelPermissoesEditar; function &End : iModelPermissoes; end; implementation { TModelPermissoesMetodosEditar } function TModelPermissoesMetodosEditar.AbrirCaixa( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FAbrirCaixa := ABoolean; end; function TModelPermissoesMetodosEditar.AcessarConfiguracoes( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FAcessarConfiguracoes := ABoolean; end; function TModelPermissoesMetodosEditar.AcessarRelatorios( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FAcessarRelatorios := ABoolean; end; function TModelPermissoesMetodosEditar.CadastrarGrupos( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FCadastrarGrupos := ABoolean; end; function TModelPermissoesMetodosEditar.CadastrarProdutos( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FCadastrarProdutos := ABoolean; end; function TModelPermissoesMetodosEditar.CadastrarUsuarios( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FCadastrarUsuarios := ABoolean; end; function TModelPermissoesMetodosEditar.&End: iModelPermissoes; begin Result := FParent; end; constructor TModelPermissoesMetodosEditar.Create(AParent: iModelPermissoes; AList: TDictionary<String ,TTypeTipoUsuario>); begin FParent := AParent; FList := AList; end; destructor TModelPermissoesMetodosEditar.Destroy; begin {$IFDEF MSWINDOWS} if Assigned(FEntidade) then FreeAndNil(FEntidade); if Assigned(FListaPermissoes) then FreeAndNil(FListaPermissoes); {$ELSE} if Assigned(FEntidade) then begin FEntidade.Free; FEntidade.DisposeOf; end; if Assigned(FListaPermissoes) then begin FListaPermissoes.Free; FListaPermissoes.DisposeOf; end; {$ENDIF} inherited; end; function TModelPermissoesMetodosEditar.ExcluirProdutosPosImpressao( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FExcluirProdutos := ABoolean; end; function TModelPermissoesMetodosEditar.Executar: iModelPermissoesEditar; begin Result := Self; Gravar; end; function TModelPermissoesMetodosEditar.FecharCaixa( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FFecharCaixa := ABoolean; end; procedure TModelPermissoesMetodosEditar.Gravar; var I: Integer; begin FListaPermissoes := FParent.DAO.Find; for I := 0 to Pred(FListaPermissoes.Count) do begin case AnsiIndexStr( FListaPermissoes[I].DESCRICAO, [ 'ABRIRCAIXA', 'FECHARCAIXA', 'SUPRIMENTOCAIXA', 'SANGRIACAIXA', 'CADASTRARPRODUTOS', 'CADASTRARGRUPOS', 'CADASTRARUSUARIOS', 'ACESSARRELATORIOS', 'ACESSARCONFIGURACOES', 'EXCLUIRPRODUTOS' ]) of 0: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FAbrirCaixa; FParent.DAO.Update(FListaPermissoes[I]); FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FAbrirCaixa); end; 1: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FFecharCaixa; FParent.DAO.Update(FListaPermissoes[I]); FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FFecharCaixa); end; 2: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FSuprimentoCaixa; FParent.DAO.Update(FListaPermissoes[I]); FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FSuprimentoCaixa); end; 3: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FSangriaCaixa; FParent.DAO.Update(FListaPermissoes[I]); FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FSangriaCaixa); end; 4: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FCadastrarProdutos; FParent.DAO.Update(FListaPermissoes[I]); FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FCadastrarProdutos); end; 5: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FCadastrarGrupos; FParent.DAO.Update(FListaPermissoes[I]); FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FCadastrarGrupos); end; 6: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FCadastrarUsuarios; FParent.DAO.Update(FListaPermissoes[I]); FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FCadastrarUsuarios); end; 7: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FAcessarRelatorios; FParent.DAO.Update(FListaPermissoes[I]); FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FAcessarRelatorios); end; 8: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FAcessarConfiguracoes; FParent.DAO.Update(FListaPermissoes[I]); FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FAcessarConfiguracoes); end; 9: begin FParent.DAO.Modify(FListaPermissoes[I]); FListaPermissoes[I].PERMISSAO := FExcluirProdutos; FList.Items[FListaPermissoes[I].DESCRICAO] := TTypeTipoUsuario(FExcluirProdutos); FParent.DAO.Update(FListaPermissoes[I]); end; end; end; end; class function TModelPermissoesMetodosEditar.New(AParent: iModelPermissoes; AList: TDictionary<String ,TTypeTipoUsuario>): iModelPermissoesEditar; begin Result := Self.Create(AParent, AList); end; function TModelPermissoesMetodosEditar.Sangria( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FSangriaCaixa := ABoolean; end; function TModelPermissoesMetodosEditar.Suprimento( ABoolean: Integer): iModelPermissoesEditar; begin Result := Self; Validacao(ABoolean); FSuprimentoCaixa := ABoolean; end; procedure TModelPermissoesMetodosEditar.Validacao(AValue: Integer); begin if (AValue < 0) or (AValue > 1) then raise Exception.Create( 'O valor de entrada para função de Editar Permissoes é inválido.' + sLineBreak + 'Insira 0 ou 1 como parametro de entrada.' ); end; end.
unit QueueADT; (* This unit implements a Queue ADT as a linked list. Sam Scott, 1999 *) interface (**************************** TYPE DEFINITIONS ************************) type Element = integer; NodePointer = ^QueueNode; QueueNode = record Contents: Element; Next: NodePointer; end; Queue = record First: NodePointer; Last: NodePointer; end; (*************** FORWARD DECLARATIONS *****************) procedure Create(var Q: Queue); procedure Destroy(var Q: Queue); function IsEmpty(Q: Queue):boolean; function IsFull(Q: Queue):boolean; procedure Enqueue(var Q: Queue; E: Element); function Dequeue(var Q: Queue): Element; function memcheck: boolean; implementation (************ MEMORY MANAGEMENT ROUTINES - DO NOT CHANGE **************) var MemCount: integer; (*** NOTE - for question 2, you may remove procedures ReturnNode and GetNode *** but leave the other procedures in place, since they are called by the main program. ***) (* Use GetNode instead of "new" *) procedure GetNode(var Q: NodePointer); begin new(Q); MemCount := MemCount + 1; end; (* Use ReturnNode instead of "dispose" *) procedure ReturnNode(var Q: NodePointer); begin dispose(Q); MemCount := MemCount - 1; end; function MemCheck: boolean; begin MemCheck := (MemCount = 0); end; procedure InitMemCount; begin MemCount := 0; end; (***************** BASIC QUEUE PROCESSING PROCEDURES ******************) (* Procedure Create(Q) * Givens: Q is Queue header with both pointers (First, Last) uninitialized. * Modified: Q becomes the empty Queue. *) procedure Create(var Q: Queue); begin Q.First := NIL; Q.Last := NIL; end; (* Procedure Destroy(Q) * Givens: Q is the empty queue. * Modified: Q is destroyed. *) procedure Destroy(var Q: Queue); begin end; (* Function IsEmpty(Q) * Givens: Q is Queue header with both pointers (First, Last). * Returns: TRUE if Q is empty, FALSE otherwise *) function IsEmpty(Q: Queue):boolean; begin IsEmpty := ((Q.First = NIL) AND (Q.Last = NIL)); end; (* Function IsFull(Q) * Givens: Q is Queue header with both pointers (First, Last). * Returns: TRUE if Q is full, FALSE otherwise *) function IsFull(Q: Queue):boolean; begin IsFull := FALSE; end; (* procedure Enqueue(var Q: Queue; E: Element); * Givens: Q is a Queue (could be empty), * E is the new Queue element to add. * Modified: a new node containing the E the new Queue element * and is inserted into Q at the end. *) procedure Enqueue(var Q: Queue; E: Element); var newnode: NodePointer; begin GetNode(newnode) ; newnode^.Contents := E; newnode^.Next := nil; if IsEmpty(Q) then Q.First := newnode else Q.Last^.Next := newnode; Q.Last := newnode; end ; (* procedure Dequeue(var Q: Queue; var E: Element); * Givens: Q is a Queue (could be empty), * Modified: returns the first element of the Queue. * Q no longer contains the first element in it, * Q also may become empty. *) function Dequeue(var Q: Queue): Element; var tmpPointer : NodePointer; begin if NOT(IsEmpty(Q)) then begin tmpPointer := Q.First; Q.First := Q.First^.Next; if Q.First = NIL then Q.Last := NIL; Dequeue := tmpPointer^.Contents; ReturnNode(tmpPointer); end else writeln('ERROR - dequeue from empty queue'); end; (*********************** INITIALIZATION CODE ***********************) begin memcount := 0 end.
{ * CGRemoteOperation.h * CoreGraphics * * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. * } { 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 CGRemoteOperation; 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,CFMachPort,CGBase,CGGeometry,CGErrors,CFDate; {$ALIGN POWER} type CGEventErr = CGError; const CGEventNoErr = 0; { Screen refresh or drawing notification } { * Callback function pointer; * Declare your callback function in this form. When an area of the display is * modified or refreshed, your callback function will be invoked with a count * of the number of rectangles in the refreshed areas, and a list of the refreshed * rectangles. The rectangles are in global coordinates. * * Your function should not modify, deallocate or free memory pointed to by rectArray. * * The system continues to accumulate refreshed areas constantly. Whenever new * information is available, your callback function is invoked.The list of rects * passed to the callback function are cleared from the accumulated refreshed area * when the callback is made. * * This callback may be triggered by drawing operations, window movement, and * display reconfiguration. * * Bear in mind that a single rectangle may occupy multiple displays, * either by overlapping the displays, or by residing on coincident displays * when mirroring is active. Use the CGGetDisplaysWithRect() to determine * the displays a rectangle occupies. } type CGRectCount = UInt32; type CGScreenRefreshCallback = procedure( count: CGRectCount; {const} rectArray: {variable-size-array} CGRectPtr; userParameter: UnivPtr); { Begin Old API } { * Register a callback function to be invoked when an area of the display * is refreshed, or modified. The function is invoked on the same thread * of execution that is processing events within your application. * userParameter is passed back with each invocation of the callback function. } function CGRegisterScreenRefreshCallback( func: CGScreenRefreshCallback; userParameter: UnivPtr ): CGError; external name '_CGRegisterScreenRefreshCallback'; { * Remove a previously registered calback function. * Both the function and the userParameter must match the registered entry to be removed. } procedure CGUnregisterScreenRefreshCallback( func: CGScreenRefreshCallback; userParameter: UnivPtr ); external name '_CGUnregisterScreenRefreshCallback'; { * In some applications it may be preferable to have a seperate thread wait for screen refresh data. * This function should be called on a thread seperate from the event processing thread. * If screen refresh callback functions are registered, this function should not be used. * The mechanisms are mutually exclusive. * * Deallocate screen refresh rects using CGReleaseScreenRefreshRects(). * * Returns an error code if parameters are invalid or an error occurs in retrieving * dirty screen rects from the server. } function CGWaitForScreenRefreshRects( var pRectArray: {variable-size-array} CGRectPtr; var pCount: CGRectCount ): CGEventErr; external name '_CGWaitForScreenRefreshRects'; { End Old API } { Begin New API } { * Screen refresh operation types. * Operations are encoded as bits. * All users of this API must support a simple refresh, kCGScreenUpdateOperationRefresh. } type CGScreenUpdateOperation = SInt32; const kCGScreenUpdateOperationRefresh = 0; kCGScreenUpdateOperationMove = 1 shl 0; kCGScreenUpdateOperationReducedDirtyRectangleCount = 1 shl 31; { * Move operation notifications are restricted to changes that move a region by * an integer number of pixels. * * dX and dY describe the direction of movement. * Positive values of dX indicate movement to the right. * Negative values of dX indicate movement to the left. * Positive values of dY indicate movement downward. * Negative values of dY indicate movement upward. } type CGScreenUpdateMoveDelta = record dX, dY: SInt32; end; { * Move operation callback function pointer; * Declare your callback function in this form. When an area of the display is * moved, your callback function will be invoked with a count * of the number of rectangles in the moved area, and a list of the moved. * The rectangles are in global coordinates, and describe the area prior to the move * operation. * * dX and dY describe the direction of movement. * Positive values of dX indicate movement to the right. * Negative values of dX indicate movement to the left. * Positive values of dY indicate movement downward. * Negative values of dY indicate movement upward. * * Your function should not modify, deallocate or free memory pointed to by rectArray. * * This callback may be triggered by window movement or scrolling operations. * * Bear in mind that a single rectangle may occupy multiple displays, * either by overlapping the displays, or by residing on coincident displays * when mirroring is active. Use the CGGetDisplaysWithRect() function to determine * the displays a rectangle occupies. * * If no move callback function pointer is registered, then move operations are remapped to * refresh operations, and the CGScreenRefreshCallback function, if any, is called. } type CGScreenUpdateMoveCallback = procedure( delta: CGScreenUpdateMoveDelta; count: size_t; {const} rectArray: {variable-size-array} CGRectPtr; userParameter: UnivPtr ); { * Register a callback function to be invoked when an area of the display * is moved. The function is invoked on the same thread * of execution that is processing events within your application. * userParameter is passed back with each invocation of the callback function. } function CGScreenRegisterMoveCallback( func: CGScreenUpdateMoveCallback; userParameter: UnivPtr ): CGError; external name '_CGScreenRegisterMoveCallback'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * Remove a previously registered callback function. } procedure CGScreenUnregisterMoveCallback( func: CGScreenUpdateMoveCallback; userParameter: UnivPtr ); external name '_CGScreenUnregisterMoveCallback'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * In some applications it may be preferable to have a seperate thread wait for screen update operations. * This function should be called on a thread seperate from the event processing thread. * If screen refresh callback functions are registered, this function should not be used. * The mechanisms are mutually exclusive. * * Deallocate screen update rects using CGReleaseScreenRefreshRects(). * * requestedOperations may be: * kCGScreenUpdateOperationRefresh * All move operations are converted to refresh operations * currentOperation will always be returned as kCGScreenUpdateOperationRefresh * (kCGScreenUpdateOperationRefresh | kCGScreenUpdateOperationMove) * Wait for move or refresh operations. * currentOperation will be either kCGScreenUpdateOperationRefresh or kCGScreenUpdateOperationMove * * pDelta is updated with valid content if the currentOperation is kCGScreenUpdateOperationMove * * Returns an error code if parameters are invalid or an error occurs in retrieving * the screen rect data from the server. } function CGWaitForScreenUpdateRects( requestedOperations: CGScreenUpdateOperation; var currentOperation: CGScreenUpdateOperation; var pRectArray: {variable-size-array} CGRectPtr; var pCount: size_t; var pDelta: CGScreenUpdateMoveDelta ): CGError; external name '_CGWaitForScreenUpdateRects'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { End New API } { * Deallocate the list of rects recieved from CGWaitForScreenRefreshRects() } procedure CGReleaseScreenRefreshRects( pRectArray: {variable-size-array} CGRectPtr); external name '_CGReleaseScreenRefreshRects'; { * Programs reading the frame buffer content may want to hide the cursor, if it is visible and * drawn in framebuffer memory. A cursor may also be generated in an overlay plane of some form. * * These APIs provide basic cursor visibility and drawing information. * The cursor may be hidden or shown using the CGDisplayHideCursor() and CGDisplayShowCursor() API. } function CGCursorIsVisible: boolean_t; external name '_CGCursorIsVisible'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) function CGCursorIsDrawnInFramebuffer: boolean_t; external name '_CGCursorIsDrawnInFramebuffer'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) { * Posting events: These functions post events into the system. Use for remote * operation and virtualization. * * Note that remote operation requires a valid connection to the server, which * must be owned by either the root/Administrator user or the logged in console * user. This means that your application must be running as root/Administrator * user or the logged in console user. } { * Synthesize mouse events. * mouseCursorPosition should be the global coordinates the mouse is at for the event. * updateMouseCursor should be TRUE if the on-screen cursor * should be moved to mouseCursorPosition. * * Based on the values entered, the appropriate mouse-down, mouse-up, mouse-move, * or mouse-drag events are generated, by comparing the new state with the current state. * * The current implemementation of the event system supports a maximum of thirty-two buttons. * The buttonCount parameter should be followed by 'buttonCount' boolean_t values * indicating button state. The first value should reflect the state of the primary * button on the mouse. The second value, if any, should reflect the state of the secondary * mouse button (right), if any. A third value woule be the center button, and the remaining * buttons would be in USB device order. } type CGButtonCount = UInt32; function CGPostMouseEvent( mouseCursorPosition: CGPoint; updateMouseCursorPosition: boolean_t; buttonCount: CGButtonCount; mouseButtonDown: boolean_t; ... ): CGError; external name '_CGPostMouseEvent'; { * Synthesize scroll wheel events. * * The current implemementation of the event system supports a maximum of three wheels. * * The wheelCount parameter should be followed by 'wheelCount' 32 bit integer values * indicating wheel movements. The first value should reflect the state of the primary * wheel on the mouse. The second value, if any, should reflect the state of a secondary * mouse wheel, if any. * * Wheel movement is represented by small signed integer values, * typically in a range from -10 to +10. Large values may have unexpected results, * depending on the application that processes the event. } type CGWheelCount = UInt32; function CGPostScrollWheelEvent( wheelCount: CGWheelCount; wheel1: SInt32; ... ): CGError; external name '_CGPostScrollWheelEvent'; { * Synthesize keyboard events. Based on the values entered, * the appropriate key down, key up, and flags changed events are generated. * If keyChar is NUL (0), an appropriate value will be guessed at, based on the * default keymapping. * * All keystrokes needed to generate a character must be entered, including * SHIFT, CONTROL, OPTION, and COMMAND keys. For example, to produce a 'Z', * the SHIFT key must be down, the 'z' key must go down, and then the SHIFT * and 'z' key must be released: * CGPostKeyboardEvent( (CGCharCode)0, (CGKeyCode)56, true ); // shift down * CGPostKeyboardEvent( (CGCharCode)'Z', (CGKeyCode)6, true ); // 'z' down * CGPostKeyboardEvent( (CGCharCode)'Z', (CGKeyCode)6, false ); // 'z' up * CGPostKeyboardEvent( (CGCharCode)0, (CGKeyCode)56, false ); // 'shift up } type CGCharCode = UInt16; { Character represented by event, if any } type CGKeyCode = UInt16; { Virtual keycode for event } function CGPostKeyboardEvent( keyChar: CGCharCode; virtualKey: CGKeyCode; keyDown: boolean_t ): CGError; external name '_CGPostKeyboardEvent'; { * Warp the mouse cursor to the desired position in global * coordinates without generating events } function CGWarpMouseCursorPosition( newCursorPosition: CGPoint ): CGError; external name '_CGWarpMouseCursorPosition'; { * Remote operation may want to inhibit local events (events from * the machine's keyboard and mouse). This may be done either as a * explicit request (tracked per app) or as a short term side effect of * posting an event. * * CGInhibitLocalEvents() is typically used for long term remote operation * of a system, as in automated system testing or telecommuting applications. * Local device state changes are discarded. * * Local event inhibition is turned off if the app that requested it terminates. } function CGInhibitLocalEvents( doInhibit: boolean_t ): CGError; external name '_CGInhibitLocalEvents'; { * Set the period of time in seconds that local hardware events (keyboard and mouse) * are suppressed after posting an event. Defaults to 0.25 second. } function CGSetLocalEventsSuppressionInterval( seconds: CFTimeInterval ): CGError; external name '_CGSetLocalEventsSuppressionInterval'; { * By default, the flags that indicate modifier key state (Command, Alt, Shift, etc.) * from the system's keyboard and from other event sources are ORed together as an event is * posted into the system, and current key and mouse button state is considered in generating new events. * This function allows your application to enable or disable the * merging of event state. When combining is turned off, the event state propagated in the events * posted by your app reflect state built up only by your app. The state within your app's generated * event will not be combined with the system's current state, so the system-wide state reflecting key * and mouse button state will remain unchanged * * When called with doCombineState equal to FALSE, this function initializes local (per application) * state tracking information to a state of all keys, modifiers, and mouse buttons up. * * When called with doCombineState equal to TRUE, the current global state of keys, modifiers, * and mouse buttons are used in generating events. } function CGEnableEventStateCombining( doCombineState: boolean_t ): CGError; external name '_CGEnableEventStateCombining'; { * By default the system suppresses local hardware events from the keyboard and mouse during * a short interval after a synthetic event is posted (see CGSetLocalEventsSuppressionInterval()) * and while a synthetic mouse drag (mouse movement with the left/only mouse button down). * * Some classes of applications may want to enable events from some of the local hardware. * For example, an app may want to post only mouse events, and so may wish to permit local * keyboard hardware events to pass through. Set the filter state to permit keyboard events * prior to posting the mouse event after which you want to get keyboard events. * * This interface lets an app specify a state (event suppression interval, or mouse drag), and * a mask of event categories to be passed through. The new filter state takes effect * with the next event your app posts. } const kCGEventFilterMaskPermitLocalMouseEvents = $00000001; { Mouse, scroll wheel } kCGEventFilterMaskPermitLocalKeyboardEvents = $00000002; { Alphanumeric keys and Command, Option, Control, Shift, AlphaLock } kCGEventFilterMaskPermitSystemDefinedEvents = $00000004; { Power key, bezel buttons, sticky keys } type CGEventFilterMask = UInt32; const kCGEventSuppressionStateSuppressionInterval = 0; kCGEventSuppressionStateRemoteMouseDrag = 1; kCGNumberOfEventSuppressionStates = 2; type CGEventSuppressionState = UInt32; const kCGEventFilterMaskPermitAllEvents = $00000007; function CGSetLocalEventsFilterDuringSuppressionState( filter: CGEventFilterMask; state: CGEventSuppressionState ): CGError; external name '_CGSetLocalEventsFilterDuringSuppressionState'; { * After posting a left mouse down, with remote mouse drag suppressing hardware mouse * move events, after some time with no remote mouse drag events, a warning is logged * to aid in diagnosing 'my hardware mouse is dead' problems. * No mechanism is provided to defeat this timeout. * * Mouse-down conditions of arbitrary length may be produced deliberately, as when scrolling * through a lengthly document. } const kCGMouseDownEventMaskingDeadSwitchTimeout = 60.0; { * Helper function to connect or disconnect the mouse and mouse cursor while the calling app * is in the foreground. * * While disconnected, mouse move and drag events will reflect the current position of * the mouse cursor position, which will not change with mouse movement. Use the * <CoreGraphics/CGDirectDisplay.h> function: * * void CGGetLastMouseDelta( CGMouseDelta * deltaX, CGMouseDelta * deltaY ); * * This will report mouse movement associated with the last mouse move or drag event. * * To update the display cursor position, use the function defined in this module: * * CGError CGWarpMouseCursorPosition( CGPoint newCursorPosition ); * * Note: The Force Quit key combination (CMD-OPT-ESC by default) will reconnect the mouse and cursor. } function CGAssociateMouseAndMouseCursorPosition( connected: boolean_t ): CGError; external name '_CGAssociateMouseAndMouseCursorPosition'; { * Some classes of applications need to detect when the window server process dies, or * is not running. The easiest way to do this is to use a CFMachPortRef. * * If the CoreGraphics window server is not running, this function returns NULL. * If the server is running, a CFMachPortRef is returned. * * A program can register a callback function to use a CFMachPortRef to determine * when the CoreGraphics window server exits: * * static void handleWindowServerDeath( CFMachPortRef port, void *info ) * ( * printf( "Window Server port death detected!\n" ); * CFRelease( port ); * exit( 1 ); * ) * * static void watchForServerDeath() * ( * CFMachPortRef port; * * port = CGWindowServerCFMachPort(); * CFMachPortSetInvalidationCallBack( port, handleWindowServerDeath ); * ) * * Note that when the window server exits, there may be a few seconds during which * no window server is running, until the operating system starts a new * window server/loginwindow pair of processes. This function will return NULL * until a new window server is running. * * Multiple calls to this function may return multiple CFMachPortRefs, each referring * to the same Mach port. Multiple callbacks registered on multiple CFMachPortRefs * obtained in this way may fire in a nondetermanistic manner. * * Your program will need to run a CFRunLoop for the port death * callback to function. A program which does not use a CFRunLoop may use * CFMachPortIsValid(CFMachPortRef port) periodically to check if the port is valid. } function CGWindowServerCFMachPort: CFMachPortRef; external name '_CGWindowServerCFMachPort'; { * OBSOLETE! * * Present for backwards compatibility with old header typos. } { #define kCGEventSupressionStateSupressionInterval kCGEventSuppressionStateSuppressionInterval #define kCGEventSupressionStateRemoteMouseDrag kCGEventSuppressionStateRemoteMouseDrag #define kCGNumberOfEventSupressionStates kCGNumberOfEventSuppressionStates #define CGEventSupressionState CGEventSuppressionState #define CGSetLocalEventsFilterDuringSupressionState(filter, state) \ CGSetLocalEventsFilterDuringSuppressionState(filter, state) } end.
{Sabine Wolf,5999219,q5999219@bonsai.fernuni-hagen.de} {In dieser Unit werden die Typen deklariert, die von mehreren Units gebraucht werden.} unit gomtypes; interface uses q5999219; const MINFELDSIZE = 5; MAXFELDSIZE = 30; type {Belegungsmoeglichkeiten fuer ein Feld} tStein = (Leer,Weiss,Schwarz,Tip); {Wie kann ein Spiel enden} tErgebnis = (Sieg,Unentschieden); {Zustaende in denen sich ein Spiel befinden kann} tSpielState = (Intro,StartVor,Start,WeissAmZug,SchwarzAmZug, ZeigSieg,Ende,Ende2,QuitFrage,Quit); {Die Groesse, die das Feld haben kann.} tFeldSize = MINFELDSIZE..MAXFELDSIZE; {Eine Koordinaten des Feldes} tFeldKoord = 0..MAXFELDSIZE+1; {Das Feldarray, das die Belegung mit Steines speichert.} tFeld = array[tFeldKoord,tFeldKoord] of tStein; {Die beiden Typen von Spielern} tSpieler = (Mensch,Computer); {Zuordnung von Spielertyp zu den Spielsteinfarben.} tZuordnung = array[tSpielState] of tSpieler; {Position auf dem Feld} tFeldPos = record x : integer; {tFeldKoord;} z : integer; {tFeldKoord;} end; {Urteil ueber das Spiel, wenn es zu ende ist} tBewertung = record typ : tErgebnis; stein : tStein; end; {Spielstrukturtyp, der den Zustand, in dem sich das Spiel befindet, zusammenfasst.} tSpiel = record Feld : tFeld; FeldSizeX : integer; {tFeldSize;} FeldSizeY : integer; {tFeldSize;} SpielState : tSpielState; status : tStatus; Zuordnung : tZuordnung; Bewertung : tBewertung; Spielstufe : integer; neuGesetzt : tFeldPos; end; var {Zuordnung Spielzustand -> Steinfarbe} stein : array[tSpielState] of tStein; {Der jeweilige Gegenspieler} Gegenspieler : array[tSpielState] of tSpielState; implementation begin stein[WeissAmZug] := Weiss; stein[SchwarzAmZug] := Schwarz; Gegenspieler[WeissAmZug] := SchwarzAmZug; Gegenspieler[SchwarzAmZug] := WeissAmZug; end.
(* ----------------------------------------------------------------------------------------- STATE ----------------------------------------------------------------------------------------- THIS SOFTWARE IS FREEWARE AND IS PROVIDED AS IS AND COMES WITH NO WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED. IN NO EVENT WILL THE AUTHOR(S) BE LIABLE FOR ANY DAMAGES RESULTING FROM THE USE OF THIS SOFTWARE. ----------------------------------------------------------------------------------------- INFORMATION ----------------------------------------------------------------------------------------- Description : btBeeper uses the PC speaker to produce various sounds. In fact you can make it play entire songs. It contains many "preset" sounds. You can play them just calling the PlayPresetSound method. Also it has the ability to play songs or sounds written in a plain ascii file. I wrote it just for fun but I think it maybe usefull in some situations ie. when a sound card is not present or when you don't like to use .wav files The code is straightforward and well commented - I think I used some fucntions posted to a (don't remember) newsgroup by jatkins@paktel.compulink.co.uk (John Atkins) Tested : Delphi 5 , Win2K Author : Theo Bebekis <bebekis@otenet.gr> More info : License : Freeware Thanks to : John Atkins [jatkins@paktel.compulink.co.uk] ----------------------------------------------------------------------------------------- HISTORY ----------------------------------------------------------------------------------------- Version Date Changes - Additions By ----------------------------------------------------------------------------------------- 0.01 25.09.1988 Initial Version 0.02 24.10.1988 ElapsedMillisecFrom function The ElapsedMillisecFrom function added as a correction to BeepFor function. ElapsedMillisecFrom posted to me by John Herbster (johnh@petronworld.com) as a solution to GetTickCount Win API function problem. Beeper uses GetTickCount to calculate the time for beep durations 0.03 26.10.1988 1. FBeeping boolean field added to prevent calling a beeping function again while a beep is currently played 2. Application.ProcessMessages call removed from the BeepFor function's while loop to prevent undesired sound effects if the owner form is receiving moving messages or a new form is created modally while a beep is played at the same time 0.04 21.05.2001 Added TSoundThread and the helper classes 0.05 27.05.2001 Added BeepSequence method for playing sequences of sounds The BeepSequence method provided by Friedrich Ing. Hajny [Cum_Hajny@compuserve.com] 0.06 08.01.2002 ElapsedMillisecFrom and the waiting loop replaced by simple calls to Sleep() as suggested by Peter Williams [pew@pcug.org.au] ----------------------------------------------------------------------------------------- *) unit btOdeum; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; const { WinApi Help denotes that frequency for the PC speaker (the dwFreq parameter for the Windows Beep function ) must be in the range 37 through 32,767 (0x25 through 0x7FFF). Well, I think that frequency > 5000 is to hard and reedy. The pitch is to high for the PC speaker. In addition I founded easier to use preset frequencies as musical tones - see below - than directly use a particular frequency. Of course the human ear can distinguish sounds lesser than a half step, so you always the chance to use such intervals when calling TbtBeeper methods } LOW_FREQ = 40; HIGH_FREQ = 5000; { Denotes a pseudo - frequency for the rests } REST = 1; { I use five octaves with TbtBeeper. C_0, C, C_1, C_2 and C_3. C_1 is the C note written on the first ledger line below the treble clef. That is the C in the middle of a piano keyboard, where the commercial sign usualle appears } C_0 = 65; C = 131; C_1 = 261; C_2 = 523; C_3 = 1046; Cp_0 = 69; Cp = 138; Cp_1 = 277; Cp_2 = 554; Cp_3 = 1109; //Db_0 = Cp_0; Db = Cp; Db_1 = Cp_1; Db_2 = Cp_2; Db_3 = Cp_3; D_0 = 73; D = 149; D_1 = 293; D_2 = 587; D_3 = 1174; Dp_0 =78 ; Dp = 155; Dp_1 = 311; Dp_2 = 622; Dp_3 = 1244; //Eb_0 = Dp_0; Eb = Dp; Eb_1 = Dp_1; Eb_2 = Dp_2; Eb_3 = Dp_3; E_0 = 82; E = 165; E_1 = 329; E_2 = 659; E_3 = 1318; F_0 = 87; F = 174; F_1 = 349; F_2 = 698; F_3 = 1397; Fp_0 = 92; Fp = 189; Fp_1 = 370; Fp_2 = 740; Fp_3 = 1480; //Gb_0 = Fp_0; Gb = Fp; Gb_1 = Fp_1; Gb_2 = Fp_2; Gb_3 = Fp_3; G_0 = 98; G = 196; G_1 = 392; G_2 = 784; G_3 = 1568; Gp_0 = 104; Gp = 207; Gp_1 = 415; Gp_2 = 830; Gp_3 = 1661; //Ab_0 = Fp_0; Ab = Gp; Ab_1 = Gp_1; Ab_2 = Gp_2; Ab_3 = Gp_3; A_0 = 110; A = 220; A_1 = 440; A_2 = 880; A_3 = 1760; Ap_0 = 116; Ap = 233; Ap_1 = 466; Ap_2 = 932; Ap_3 = 1864; //Bb_0 = Ap_0; Bb = Ap; Bb_1 = Ap_1; Bb_2 = Ap_2; Bb_3 = Ap_3; B_0 = 123; B = 247; B_1 = 494; B_2 = 988; B_3 = 1975; // aFreqs : array[0..60] of integer = ( 65, 69, 73, 78, 82, 87, 92, 98, 104, 110, 116, 123, 131, 138, 149, 155, 165, 174, 189, 196, 207, 220, 233, 247, 261, 277, 293, 311, 329, 349, 370, 392, 415, 440, 466, 494, 523, 554, 587, 622, 659, 698, 740, 784, 830, 880, 932, 988, 1046, 1109, 1174, 1244, 1318, 1397, 1480, 1568, 1661, 1760, 1864, 1975, 1); Tones : array[0..60] of string[4] = ( 'C_0', 'Cp_0', 'D_0', 'Dp_0', 'E_0', 'F_0', 'Fp_0', 'G_0', 'Gp_0', 'A_0', 'Ap_0', 'B_0', 'C', 'Cp', 'D', 'Dp', 'E', 'F', 'Fp', 'G', 'Gp', 'A', 'Ap', 'B', 'C_1', 'Cp_1', 'D_1', 'Dp_1', 'E_1', 'F_1', 'Fp_1', 'G_1', 'Gp_1', 'A_1', 'Ap_1', 'B_1', 'C_2', 'Cp_2', 'D_2', 'Dp_2', 'E_2', 'F_2', 'Fp_2', 'G_2', 'Gp_2', 'A_2', 'Ap_2', 'B_2', 'C_3', 'Cp_3', 'D_3', 'Dp_3', 'E_3', 'F_3', 'Fp_3', 'G_3', 'Gp_3', 'A_3', 'Ap_3', 'B_3', 'REST'); THE_END = 'FINE'; type TPresetSound = ( psOK, psError, psWelcome, psEmergency, psWrong, psCall, psOfficial, psDaze, psFall, psChord, psWhisle, psHanging, psClimb ); TBeatDuration = (bd_500, bd_1000, bd_1500, bd_2000); type (*--------------------------------------------------------------------------------*) TbtBeeper = class(TComponent) private FBeatDuration : TBeatDuration; FDuration : integer; FDefaultSound : TPresetSound; SoundList : TObject; SoundThread : TThread; procedure SetBeatDuration(Value:TBeatDuration); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure PlayDefaultSound; procedure PlayPresetSound(Sound:TPresetSound); procedure BeepSequence(ToneAndMSecs: array of DWord); procedure BeepFor(Tone : Word; MSecs : DWORD); procedure Beep(Tone : Word); procedure Pause; procedure PauseFor(MSecs : DWORD); procedure PlayTextFile(FileName, Song: string); published { BeatDuration affects only the Beep and the Pause methods} property BeatDuration : TBeatDuration read FBeatDuration write SetBeatDuration default bd_1000; property DefaultSound : TPresetSound read FDefaultSound write FDefaultSound default psOK; end; procedure Register; procedure StartBeep(Freq : Word); procedure StopBeep; implementation {$R btOdeum.res} type EBeepError = class(Exception); (*----------------------------------------------------------------------------------*) procedure RaiseError(const Msg: string); begin raise EBeepError.Create(Msg); end; (*----------------------------------------------------------------------------------*) procedure RaiseErrorFmt(const Msg: string; const Args: array of const); begin raise EBeepError.CreateFmt(Msg, Args); end; { utilities } (*--------------------------------------------------------------------------------*) procedure Register; begin RegisterComponents('btControls', [TbtBeeper]); end; {John Atkins [jatkins@paktel.compulink.co.uk] functions for playing beeps} (*--------------------------------------------------------------------------------*) function _GetPort(address:word):word; var bValue: byte; begin asm mov dx, address in al, dx mov bValue, al end; Result := bValue; end; (*--------------------------------------------------------------------------------*) procedure _SetPort(address, Value:Word); var bValue: byte; begin bValue := Trunc(Value and 255); asm mov dx, address mov al, bValue out dx, al end; end; (*--------------------------------------------------------------------------------*) procedure StartBeep(Freq : Word); var B: Byte; begin if (Freq >= LOW_FREQ) and (Freq <= HIGH_FREQ) then begin Freq := Word(1193181 div LongInt(Freq)); B := Byte(_GetPort($61)); if (B and 3) = 0 then begin _SetPort($61, Word(B or 3)); _SetPort($43, $B6); end; _SetPort($42, Freq); _SetPort($42, Freq shr 8); end; end; (*--------------------------------------------------------------------------------*) procedure StopBeep; var Value: Word; begin Value := _GetPort($61) and $FC; _SetPort($61, Value); end; { TCmd } type (*--------------------------------------------------------------------------------*) TCmd = class public Tone : Word; Duration : DWORD; procedure DoSound; constructor Create(Tone: Word; Duration: DWORD); end; (*--------------------------------------------------------------------------------*) constructor TCmd.Create(Tone: Word; Duration: DWORD); begin inherited Create; Self.Tone := Tone; Self.Duration := Duration; end; (*-------------------------------------------------------------------------------- Description : generates a Tone a MSecs long Notes : ElapsedMillisecFrom and the waiting loop is replaced by simple calls to Sleep() as suggested by Peter Williams [pew@pcug.org.au] ---------------------------------------------------------------------------------*) procedure TCmd.DoSound; begin if Tone = REST then begin Sleep(Duration); Exit; end; if (Win32Platform = VER_PLATFORM_WIN32_NT) then Windows.Beep (Tone, Duration) else begin StartBeep(Tone); Sleep(Duration); StopBeep; end; end; { TCriticalSection } type (*--------------------------------------------------------------------------------*) TCriticalSection = class (TObject) private FCS: TRTLCriticalSection; public constructor Create; destructor Destroy; override; procedure Enter; procedure Leave; end; (*--------------------------------------------------------------------------------*) constructor TCriticalSection.Create; begin inherited Create; InitializeCriticalSection(FCS); end; (*--------------------------------------------------------------------------------*) destructor TCriticalSection.Destroy; begin DeleteCriticalSection(FCS); inherited Destroy; end; (*--------------------------------------------------------------------------------*) procedure TCriticalSection.Enter; begin EnterCriticalSection(FCS); end; (*--------------------------------------------------------------------------------*) procedure TCriticalSection.Leave; begin LeaveCriticalSection(FCS); end; { TProtected - TQueueList} type (*--------------------------------------------------------------------------------*) TProtected = class protected CS : TCriticalSection; List : TStringList; public constructor Create; destructor Destroy; override; end; TQueueAction = (qaPushTop, qaPushBottom, qaPop); (*--------------------------------------------------------------------------------*) TQueueList = class(TProtected) private Thread : TThread; procedure AccessItem(var Obj: TObject; Action: TQueueAction); // TQueueAction = (qaPushTop, qaPushBottom, qaPop); public constructor Create(T: TThread); destructor Destroy; override; procedure Push(Obj: TObject); procedure PushTop(Obj: TObject); function Pop: TObject; end; { TProtected } (*--------------------------------------------------------------------------------*) constructor TProtected.Create; begin inherited Create; CS := TCriticalSection.Create; List := TStringList.Create; end; (*--------------------------------------------------------------------------------*) destructor TProtected.Destroy; begin CS.Free; List.Free; inherited Destroy; end; { TQueueList } (*--------------------------------------------------------------------------------*) constructor TQueueList.Create(T: TThread); begin inherited Create; Thread := T; end; (*--------------------------------------------------------------------------------*) destructor TQueueList.Destroy; begin while List.Count > 0 do begin TCmd(List.Objects[0]).Free; List.Delete(0); end; inherited Destroy; end; (*--------------------------------------------------------------------------------*) procedure TQueueList.AccessItem(var Obj: TObject; Action: TQueueAction); begin CS.Enter; try case Action of qaPushTop : begin if List.Count = 0 then List.AddObject('', Obj) else List.InsertObject(0, '', Obj); if Thread <> nil then if Thread.Suspended then Thread.Resume; { resume the Thread if needed } end; qaPushBottom : begin List.AddObject('', Obj); if Thread <> nil then if Thread.Suspended then Thread.Resume; { resume the Thread if needed } end; qaPop : begin if List.Count = 0 then begin Obj := nil; Exit; end; Obj := TObject(List.Objects[0]); List.Delete(0); end; end; finally CS.Leave; end; end; (*--------------------------------------------------------------------------------*) function TQueueList.Pop: TObject; begin AccessItem(Result, qaPop); end; (*--------------------------------------------------------------------------------*) procedure TQueueList.Push(Obj: TObject); begin AccessItem(Obj, qaPushBottom); end; (*--------------------------------------------------------------------------------*) procedure TQueueList.PushTop(Obj: TObject); begin AccessItem(Obj, qaPushTop); end; { TSoundThread } type (*--------------------------------------------------------------------------------*) TSoundThread = class(TThread) private Beeper : TbtBeeper; protected procedure Execute; override; public constructor Create(Beeper : TbtBeeper); procedure ResumeThread; procedure SuspendThread; end; (*--------------------------------------------------------------------------------*) constructor TSoundThread.Create(Beeper : TbtBeeper); begin inherited Create(True); { Create thread suspended } Priority := tpNormal; FreeOnTerminate := False; { Thread does not free Itself when terminated } Self.Beeper := Beeper; end; (*--------------------------------------------------------------------------------*) procedure TSoundThread.ResumeThread; begin if Suspended then Resume; end; (*--------------------------------------------------------------------------------*) procedure TSoundThread.SuspendThread; begin if not Suspended then Suspend; end; (*--------------------------------------------------------------------------------*) procedure TSoundThread.Execute; var Cmd : TCmd; begin while (Terminated = False) do begin Cmd := TCmd(TQueueList(Beeper.SoundList).Pop); if (Cmd = nil) then SuspendThread else begin Cmd.DoSound; Cmd.Free; end; end; end; { TbtBeeper } (*--------------------------------------------------------------------------------*) constructor TbtBeeper.Create(AOwner:TComponent); begin inherited Create(AOwner); FBeatDuration := bd_1000; FDuration := 1000; FDefaultSound := psOK; SoundThread := TSoundThread.Create(Self); SoundList := TQueueList.Create(SoundThread); end; (*--------------------------------------------------------------------------------*) destructor TbtBeeper.Destroy; begin SoundThread.Terminate; repeat Application.ProcessMessages; until TSoundThread(SoundThread).Terminated; SoundThread.Free; SoundList.Free; inherited Destroy; end; (*--------------------------------------------------------------------------------*) procedure TbtBeeper.PlayDefaultSound; begin PlayPresetSound(FDefaultSound); end; (*-------------------------------------------------------------------------------- Description : plays a sequence of sounds Example call : BeepSequence([F_2, 200, B_1, 200, F_2, 200 ]); Author : Friedrich Ing. Hajny [Cum_Hajny@compuserve.com] ---------------------------------------------------------------------------------*) procedure TbtBeeper.BeepSequence(ToneAndMSecs: array of DWord); var Inx: Integer; begin if Length(ToneAndMSecs) = 0 then Exit; for Inx := Low(ToneAndMSecs) to (Pred(High(ToneAndMSecs)) div 2) do TQueueList(SoundList).Push(TCmd.Create(ToneAndMSecs[Inx * 2], ToneAndMSecs[Succ(Inx * 2)])); end; (*--------------------------------------------------------------------------------*) procedure TbtBeeper.PlayPresetSound(Sound:TPresetSound); begin case Sound of psOK : begin BeepFor (Ap_2,100); BeepFor (B_2, 100); BeepFor (C_3, 100); end; psError : begin BeepFor (Fp_0,150); BeepFor (REST,200); BeepFor (C_0,500); end; psWelcome : begin BeepFor (Ap_2,100); BeepFor (B_2, 100); BeepFor (C_3, 100); BeepFor (REST,100); BeepFor (C_3, 100); BeepFor (B_2, 100); BeepFor (Ap_2,100); end; psEmergency : begin BeepFor (F_2,200); BeepFor (B_1, 200); BeepFor (F_2,200); BeepFor (B_1, 200); BeepFor (F_2,200); BeepFor (B_1, 200); BeepFor (F_2,200); BeepFor (B_1, 200); end; psWrong : begin BeepFor (C_1,150); BeepFor (B,50); BeepFor (Ap,50); BeepFor (A,50); BeepFor (Gp,50); BeepFor (G,50); BeepFor (Fp,50); BeepFor (F,50); BeepFor (E,50); BeepFor (Dp,50); BeepFor (D,50); BeepFor (Cp,50); BeepFor (C,100); BeepFor (C_0,200); end; psCall : begin BeepFor (G,650); BeepFor (REST,100); BeepFor (E,500); end; psOfficial : begin BeepFor (G,200); BeepFor (REST,50); BeepFor (G,200); BeepFor (REST,50); BeepFor (G,200); BeepFor (REST,50); BeepFor (E,700); BeepFor (REST,100); BeepFor (C_1,200); BeepFor (REST,50); BeepFor (C_1,200); BeepFor (REST,50); BeepFor (C_1,200); BeepFor (REST,50); BeepFor (C,700); end; psDaze : begin BeepFor (E_1,100); BeepFor (Dp_1,100); BeepFor (D_1,100); BeepFor (Dp_1,100); BeepFor (E_1,100); BeepFor (Dp_1,100); BeepFor (D_1,100); BeepFor (Dp_1,100); BeepFor (E_1,100); BeepFor (Dp_1,100); BeepFor (D_1,100); BeepFor (Dp_1,100); end; psFall : begin BeepFor (E_1,100); BeepFor (Dp_1,100); BeepFor (D_1,100); BeepFor (Dp_1,100); BeepFor (F_1,100); BeepFor (E_1,100); BeepFor (Dp_1,100); BeepFor (E_1,100); BeepFor (Fp_1,100); BeepFor (F_1,100); BeepFor (E_1,100); BeepFor (F_1,100); end; psChord : begin BeepFor (B_1,80); BeepFor (Ap_1,80); BeepFor (A_1,80); BeepFor (Gp_1,80); BeepFor (G_1,80); BeepFor (Fp_1,80); BeepFor (F_1,80); BeepFor (E_1,80); BeepFor (Dp_1,80); BeepFor (D_1,80); BeepFor (Cp_1,80); BeepFor (C_1,80); end; psWhisle : begin BeepFor (C_2,80); BeepFor (F_2,80); BeepFor (G_2,80); BeepFor (C_3,80); end; psHanging : begin BeepFor (G_2,80); BeepFor (C_3,80); BeepFor (Gp_2,80); BeepFor (Cp_3,80); BeepFor (A_2,80); BeepFor (D_3,80); BeepFor (Ap_2,80); BeepFor (Dp_3,80); BeepFor (B_2,80); BeepFor (E_3,80); BeepFor (C_3,80); BeepFor (F_3,80); end; psClimb : begin BeepFor (C_1,80); BeepFor (Cp_1,80); BeepFor (D_1,80); BeepFor (Dp_1,80); BeepFor (E_1,80); BeepFor (F_1,80); BeepFor (Fp_1,80); BeepFor (G_1,80); BeepFor (Gp_1,80); BeepFor (A_1,80); BeepFor (Ap_1,80); BeepFor (B_1,80); end; end; end; (*--------------------------------------------------------------------------------*) procedure TbtBeeper.Beep(Tone : word); begin BeepFor(Tone, FDuration); end; (*--------------------------------------------------------------------------------*) procedure TbtBeeper.BeepFor(Tone : Word; MSecs : DWORD); begin TQueueList(SoundList).Push(TCmd.Create(Tone, MSecs)); end; (*--------------------------------------------------------------------------------*) procedure TbtBeeper.Pause; begin PauseFor(FDuration); end; (*--------------------------------------------------------------------------------*) procedure TbtBeeper.PauseFor(MSecs : DWORD); begin BeepFor(REST, MSecs); end; (*--------------------------------------------------------------------------------*) procedure TbtBeeper.SetBeatDuration(Value:TBeatDuration); begin if Value <> FBeatDuration then begin FBeatDuration := Value; case Value of bd_500 : FDuration := 500 ; bd_1000 : FDuration := 1000; bd_1500 : FDuration := 1500; bd_2000 : FDuration := 2000; end; end; end; (*-------------------------------------------------------------------------------- Description : opens an ascii file and plays a song This file can be written with any text editor like notepad. The form of the file: <song title> <freq const>, <duration>, <freq const>, <duration>, <freq const>, <duration>, . . . FINE Note : see Songs.txt for an example You can have more than one song in the same file ---------------------------------------------------------------------------------*) procedure TbtBeeper.PlayTextFile(FileName, Song: string); const InValidChars = [#0..#47,#58..#64, #91..#94, #96, #123..#255]; var Stream : TMemoryStream; szFirst, szLast, szHolder : PChar; sTone, sMSecs : string; i : integer; begin Stream:=TMemoryStream.Create; try Stream.LoadFromFile(FileName); sTone :=''; sMSecs :=''; szFirst:= StrPos( Stream.Memory, PChar(Song) ); if szFirst = nil then begin RaiseErrorFmt('Can Not Locate Song %s in %s', [Song, FileName]); end else begin GetMem(szHolder, 5); // get mem for the holder PChar try Inc(szFirst, Length(Song) + 1); // move szFirst after song title while True do // loop for ever begin while szFirst^ in InValidChars do Inc(szFirst); // skip blanks FillChar(szHolder^, 5, #0); // zero the szHolder StrLCopy(szHolder, szFirst, 4); // get first 4 chars if String(szHolder) = THE_END then Break; szLast:= StrScan( szFirst, ',' ); // look for the next comma if szLast = nil then // if ok RaiseError('Beeper: Wrong Char'); FillChar(szHolder^, 5, #0); // zero the szHolder StrLCopy(szHolder, szFirst, (szLast ) - szFirst); // copy chars until szLast - 1 to szHolder sTone:=StrPas(szHolder); // convert it to Pascal string szFirst:=szLast + 1; // move szFirst after next comma while szFirst^ in InValidChars do Inc(szFirst); // skip blanks szLast:= StrScan( szFirst, ',' ); // look for the next comma if szLast = nil then // if ok RaiseError('Beeper: Wrong Char'); FillChar(szHolder^, 5, #0); // zero the szHolder StrLCopy(szHolder, szFirst, (szLast) - szFirst); // copy chars until szLast - 1 to szHolder sMSecs:=StrPas(szHolder); // convert it to Pascal string szFirst:=szLast + 1; // move szFirst after next comma for i:= 0 to 60 do if sTone = Tones[i] then // play the sound begin BeepFor(aFreqs[i], StrToInt(sMSecs)); Break; end; end; finally FreeMem(szHolder, 5); end; end; finally Stream.Clear; Stream.Free; end; end; end.
unit FMainMobile; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TabControl, FMX.StdCtrls, FMX.Gestures, FMX.Layouts, FMX.Memo, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, FMX.Edit; type TTabbedForm = class(TForm) HeaderToolBar: TToolBar; ToolBarLabel: TLabel; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; GestureManager1: TGestureManager; mmLog: TMemo; ttaProfile: TTetheringAppProfile; ttManager: TTetheringManager; lblID: TLabel; Button1: TButton; Label1: TLabel; edtRes: TEdit; procedure FormCreate(Sender: TObject); procedure FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); procedure FormShow(Sender: TObject); procedure ttManagerPairedFromLocal(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure ttManagerPairedToRemote(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure ttManagerUnPairManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure Button1Click(Sender: TObject); procedure ttaProfileResourceUpdated(const Sender: TObject; const AResource: TRemoteResource); private procedure _Log(AMsg:string); public { Public declarations } end; var TabbedForm: TTabbedForm; implementation {$R *.fmx} procedure TTabbedForm.Button1Click(Sender: TObject); var mInfo: TTetheringManagerInfo; begin _Log('--------------------'); ttManagerPairedToRemote(nil, mInfo); end; procedure TTabbedForm.FormCreate(Sender: TObject); begin { This defines the default active tab at runtime } TabControl1.ActiveTab := TabItem1; end; procedure TTabbedForm.FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); begin {$IFDEF ANDROID} case EventInfo.GestureID of sgiLeft: begin if TabControl1.ActiveTab <> TabControl1.Tabs[TabControl1.TabCount-1] then TabControl1.ActiveTab := TabControl1.Tabs[TabControl1.TabIndex+1]; Handled := True; end; sgiRight: begin if TabControl1.ActiveTab <> TabControl1.Tabs[0] then TabControl1.ActiveTab := TabControl1.Tabs[TabControl1.TabIndex-1]; Handled := True; end; end; {$ENDIF} end; procedure TTabbedForm.FormShow(Sender: TObject); begin lblID.Text := ttManager.Identifier; ttManager.AutoConnect(); end; procedure TTabbedForm.ttaProfileResourceUpdated(const Sender: TObject; const AResource: TRemoteResource); begin edtRes.Text := AResource.Value.AsString; end; procedure TTabbedForm.ttManagerPairedFromLocal(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin _Log('OnPairedFromLocal; ' + AManagerInfo.ManagerIdentifier); end; procedure TTabbedForm.ttManagerPairedToRemote(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); var rRes:TRemoteResource; pInfo:TTetheringProfileInfo; begin _Log('OnPairedToRemote; ' + AManagerInfo.ManagerIdentifier); // Nos suscribimos al recurso... pInfo := ttManager.RemoteProfiles[0]; rRes := ttaProfile.GetRemoteResourceValue(pInfo, 'SharedRes1'); // Nos subscribimos para futuros cambios ttaProfile.SubscribeToRemoteItem(pInfo, rRes); end; procedure TTabbedForm.ttManagerUnPairManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin _Log('OnUnPairManager; ' + AManagerInfo.ManagerIdentifier); end; procedure TTabbedForm._Log(AMsg: string); begin mmLog.Lines.Add(AMsg); mmLog.Text := mmLog.Text + AMsg + sLineBreak; end; end.
unit ce_synmemo; {$I ce_defines.inc} interface uses Classes, SysUtils, controls,lcltype, Forms, graphics, ExtCtrls, crc, SynPluginSyncroEdit, SynCompletion, SynEditKeyCmds, LazSynEditText, SynEdit, SynHighlighterLFM, SynEditHighlighter, SynEditMouseCmds, SynEditFoldedView, ce_common, ce_observer, ce_writableComponent, ce_d2syn, ce_txtsyn; type TCESynMemo = class; // Simple THintWindow descendant allowing the font size to be in sync with the editor. TCEEditorHintWindow = class(THintWindow) public class var FontSize: Integer; function CalcHintRect(MaxWidth: Integer; const AHint: String; AData: Pointer): TRect; override; end; // Stores the state of a particular source code folding. TCEFoldCache = class(TCollectionItem) private fCollapsed: boolean; fLineIndex: Integer; fNestedIndex: Integer; published property isCollapsed: boolean read fCollapsed write fCollapsed; property lineIndex: Integer read fLineIndex write fLineIndex; property nestedIndex: Integer read fNestedIndex write fNestedIndex; end; // Stores the state of a document between two cessions. TCESynMemoCache = class(TWritableLfmTextComponent) private fMemo: TCESynMemo; fFolds: TCollection; fCaretPosition: Integer; fSelectionEnd: Integer; fFontSize: Integer; fSourceFilename: string; procedure setFolds(someFolds: TCollection); published property caretPosition: Integer read fCaretPosition write fCaretPosition; property sourceFilename: string read fSourceFilename write fSourceFilename; property folds: TCollection read fFolds write setFolds; property selectionEnd: Integer read fSelectionEnd write fSelectionEnd; property fontSize: Integer read fFontSize write fFontSize; public constructor create(aComponent: TComponent); override; destructor destroy; override; // procedure beforeSave; override; procedure afterLoad; override; procedure save; procedure load; end; // buffer of caret positions allowing to jump quickly to the most recent locations. TCESynMemoPositions = class private fPos: Integer; fMax: Integer; fList: TFPList; fMemo: TCustomSynEdit; public constructor create(aMemo: TCustomSynEdit); destructor destroy; override; procedure store; procedure back; procedure next; end; TCESynMemo = class(TSynEdit) private fFilename: string; fModified: boolean; fFileDate: double; fIsDSource: boolean; fIsTxtFile: boolean; fIsConfig: boolean; fIdentifier: string; fTempFileName: string; fMultiDocSubject: TCECustomSubject; fDefaultFontSize: Integer; fPositions: TCESynMemoPositions; fMousePos: TPoint; fCallTipWin: TCEEditorHintWindow; fDDocWin: TCEEditorHintWindow; fHintDelay: Integer; fAutoDotDelay: Integer; fHintTimer: TIdleTimer; fAutoDotTimer: TIdleTimer; fCanShowHint: boolean; fCanAutoDot: boolean; fCompletionCaseSens: boolean; fOldMousePos: TPoint; fSyncEdit: TSynPluginSyncroEdit; fCompletion: TSynCompletion; function getMouseFileBytePos: Integer; procedure changeNotify(Sender: TObject); procedure identifierToD2Syn; procedure saveCache; procedure loadCache; class procedure cleanCache; static; procedure setDefaultFontSize(aValue: Integer); procedure getCallTips; procedure HintTimerEvent(sender: TObject); procedure AutoDotTimerEvent(sender: TObject); procedure InitHintWins; function getIfTemp: boolean; procedure SetcompletionMenuCaseCare(aValue: boolean); procedure setHintDelay(aValue: Integer); procedure setAutoDotDelay(aValue: Integer); procedure completionExecute(sender: TObject); procedure getCompletionList; function completionItemPaint(const AKey: string; ACanvas: TCanvas;X, Y: integer; Selected: boolean; Index: integer): boolean; procedure completionCodeCompletion(var Value: string; SourceValue: string; var SourceStart, SourceEnd: TPoint; KeyChar: TUTF8Char; Shift: TShiftState); protected procedure MouseLeave; override; procedure SetVisible(Value: Boolean); override; procedure SetHighlighter(const Value: TSynCustomHighlighter); override; procedure UTF8KeyPress(var Key: TUTF8Char); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y:Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y:Integer); override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; published property defaultFontSize: Integer read fDefaultFontSize write setDefaultFontSize; property hintDelay: Integer read fHintDelay write setHintDelay; property autoDotDelay: Integer read fAutoDotDelay write setAutoDotDelay; property completionMenuCaseCare: boolean read fCompletionCaseSens write SetcompletionMenuCaseCare; public constructor Create(aOwner: TComponent); override; destructor destroy; override; procedure setFocus; override; // procedure checkFileDate; procedure loadFromFile(const aFilename: string); procedure saveToFile(const aFilename: string); procedure save; procedure saveTempFile; // property Identifier: string read fIdentifier; property fileName: string read fFilename; property modified: boolean read fModified; property tempFilename: string read fTempFileName; // property syncroEdit: TSynPluginSyncroEdit read fSyncEdit; property isDSource: boolean read fIsDSource; property isProjectSource: boolean read fIsConfig; property isTemporary: boolean read getIfTemp; property TextView; // property MouseStart: Integer read getMouseFileBytePos; end; procedure SetDefaultCoeditKeystrokes(ed: TSynEdit); var D2Syn: TSynD2Syn; LfmSyn: TSynLfmSyn; TxtSyn: TSynTxtSyn; implementation uses ce_interfaces, ce_staticmacro, ce_dcd, SynEditHighlighterFoldBase; function TCEEditorHintWindow.CalcHintRect(MaxWidth: Integer; const AHint: String; AData: Pointer): TRect; begin Font.Size:= FontSize; result := inherited CalcHintRect(MaxWidth, AHint, AData); end; {$REGION TCESynMemoCache -------------------------------------------------------} constructor TCESynMemoCache.create(aComponent: TComponent); begin inherited create(nil); if (aComponent is TCESynMemo) then fMemo := TCESynMemo(aComponent); fFolds := TCollection.Create(TCEFoldCache); end; destructor TCESynMemoCache.destroy; begin fFolds.Free; inherited; end; procedure TCESynMemoCache.setFolds(someFolds: TCollection); begin fFolds.Assign(someFolds); end; procedure TCESynMemoCache.beforeSave; var i, start, prev: Integer; itm : TCEFoldCache; begin if fMemo = nil then exit; // fCaretPosition := fMemo.SelStart; fSourceFilename := fMemo.fileName; fSelectionEnd := fMemo.SelEnd; fFontSize := fMemo.Font.Size; TCEEditorHintWindow.FontSize := fMemo.Font.Size; // // TODO-cEditor Cache: >nested< folding persistence // cf. other ways: http://forum.lazarus.freepascal.org/index.php?topic=26748.msg164722#msg164722 prev := fMemo.Lines.Count-1; for i := fMemo.Lines.Count-1 downto 0 do begin // - CollapsedLineForFoldAtLine() does not handle the sub-folding. // - TextView visibility is increased so this is not the standard way of getting the infos. start := fMemo.TextView.CollapsedLineForFoldAtLine(i); if start = -1 then continue; if start = prev then continue; prev := start; itm := TCEFoldCache(fFolds.Add); itm.isCollapsed := true; itm.fLineIndex := start; end; end; procedure TCESynMemoCache.afterLoad; var i: integer; itm : TCEFoldCache; begin if fMemo = nil then exit; // if fFontSize > 0 then fMemo.Font.Size := fFontSize; // Currently collisions are not handled. if fMemo.fileName <> fSourceFilename then exit; // for i := 0 to fFolds.Count-1 do begin itm := TCEFoldCache(fFolds.Items[i]); if not itm.isCollapsed then continue; fMemo.TextView.FoldAtLine(itm.lineIndex-1); end; // fMemo.SelStart := fCaretPosition; fMemo.SelEnd := fSelectionEnd; end; {$IFDEF DEBUG}{$R-}{$ENDIF} procedure TCESynMemoCache.save; var fname: string; tempn: string; chksm: Cardinal; begin tempn := fMemo.fileName; if tempn = fMemo.tempFilename then exit; if not fileExists(tempn) then exit; // fname := getCoeditDocPath + 'editorcache' + DirectorySeparator; ForceDirectories(fname); chksm := crc32(0, nil, 0); chksm := crc32(chksm, @tempn[1], length(tempn)); fname := fname + format('%.8X.txt', [chksm]); saveToFile(fname); end; procedure TCESynMemoCache.load; var fname: string; tempn: string; chksm: Cardinal; begin tempn := fMemo.fileName; if not fileExists(tempn) then exit; // fname := getCoeditDocPath + 'editorcache' + DirectorySeparator; chksm := crc32(0, nil, 0); chksm := crc32(chksm, @tempn[1], length(tempn)); fname := fname + format('%.8X.txt', [chksm]); // if not fileExists(fname) then exit; loadFromFile(fname); end; {$IFDEF DEBUG}{$R+}{$ENDIF} {$ENDREGION} {$REGION TCESynMemoPositions ---------------------------------------------------} constructor TCESynMemoPositions.create(aMemo: TCustomSynEdit); begin fList := TFPList.Create; fMax := 20; fMemo := aMemo; fPos := -1; end; destructor TCESynMemoPositions.destroy; begin fList.Free; inherited; end; procedure TCESynMemoPositions.back; begin Inc(fPos); {$HINTS OFF} if fPos < fList.Count then fMemo.CaretY := NativeInt(fList.Items[fPos]) {$HINTS ON} else Dec(fPos); end; procedure TCESynMemoPositions.next; begin Dec(fPos); {$HINTS OFF} if fPos > -1 then fMemo.CaretY := NativeInt(fList.Items[fPos]) {$HINTS ON} else Inc(fPos); end; procedure TCESynMemoPositions.store; var delta: NativeInt; const thresh = 6; begin fPos := 0; {$HINTS OFF}{$WARNINGS OFF} if fList.Count > 0 then begin delta := fMemo.CaretY - NativeInt(fList.Items[fPos]); if (delta > -thresh) and (delta < thresh) then exit; end; fList.Insert(0, Pointer(NativeInt(fMemo.CaretY))); {$HINTS ON}{$WARNINGS ON} while fList.Count > fMax do fList.Delete(fList.Count-1); end; {$ENDREGION --------------------------------------------------------------------} {$REGION TCESynMemo ------------------------------------------------------------} constructor TCESynMemo.Create(aOwner: TComponent); var png: TPortableNetworkGraphic; begin inherited; // fDefaultFontSize := 10; SetDefaultCoeditKeystrokes(Self); // not called in inherited if owner = nil ! // ShowHint := false; InitHintWins; fHintDelay := 200; fHintTimer := TIdleTimer.Create(self); fHintTimer.AutoEnabled:=true; fHintTimer.Interval := fHintDelay; fHintTimer.OnTimer := @HintTimerEvent; // fAutoDotDelay := 200; fAutoDotTimer := TIdleTimer.Create(self); fAutoDotTimer.AutoEnabled:=true; fAutoDotTimer.Interval := fAutoDotDelay; fAutoDotTimer.OnTimer := @AutoDotTimerEvent; // Gutter.LineNumberPart.ShowOnlyLineNumbersMultiplesOf := 5; Gutter.LineNumberPart.MarkupInfo.Foreground := clGray; Gutter.SeparatorPart.LineOffset := 1; Gutter.SeparatorPart.LineWidth := 1; Gutter.SeparatorPart.MarkupInfo.Foreground := clGray; Gutter.CodeFoldPart.MarkupInfo.Foreground := clGray; BracketMatchColor.Foreground:=clRed; // fSyncEdit := TSynPluginSyncroEdit.Create(self); fSyncEdit.Editor := self; fSyncEdit.CaseSensitive := true; png := TPortableNetworkGraphic.Create; try png.LoadFromLazarusResource('link_edit'); fSyncEdit.GutterGlyph.Assign(png); finally png.Free; end; // fCompletionCaseSens:=false; fCompletion := TSyncompletion.create(nil); fCompletion.ShowSizeDrag := true; fCompletion.Editor := Self; fCompletion.OnExecute:= @completionExecute; fCompletion.OnCodeCompletion:=@completionCodeCompletion; fCompletion.OnPaintItem:= @completionItemPaint; fCompletion.CaseSensitive:=false; // MouseLinkColor.Style:= [fsUnderline]; with MouseActions.Add do begin Command := emcMouseLink; shift := [ssCtrl]; ShiftMask := [ssCtrl]; end; // Highlighter := D2Syn; Highlighter.ResetRange; // fTempFileName := GetTempDir(false) + 'temp_' + uniqueObjStr(self) + '.d'; fFilename := '<new document>'; fModified := false; TextBuffer.AddNotifyHandler(senrUndoRedoAdded, @changeNotify); // fPositions := TCESynMemoPositions.create(self); fMultiDocSubject := TCEMultiDocSubject.create; // subjDocNew(TCEMultiDocSubject(fMultiDocSubject), self); end; destructor TCESynMemo.destroy; begin saveCache; // subjDocClosing(TCEMultiDocSubject(fMultiDocSubject), self); fMultiDocSubject.Free; fPositions.Free; fCompletion.Free; // if fileExists(fTempFileName) then sysutils.DeleteFile(fTempFileName); // inherited; end; procedure SetDefaultCoeditKeystrokes(ed: TSynEdit); begin with ed do begin Keystrokes.Clear; // AddKey(ecUp, VK_UP, [], 0, []); AddKey(ecSelUp, VK_UP, [ssShift], 0, []); AddKey(ecScrollUp, VK_UP, [ssCtrl], 0, []); AddKey(ecDown, VK_DOWN, [], 0, []); AddKey(ecSelDown, VK_DOWN, [ssShift], 0, []); AddKey(ecScrollDown, VK_DOWN, [ssCtrl], 0, []); AddKey(ecLeft, VK_LEFT, [], 0, []); AddKey(ecSelLeft, VK_LEFT, [ssShift], 0, []); AddKey(ecWordLeft, VK_LEFT, [ssCtrl], 0, []); AddKey(ecSelWordLeft, VK_LEFT, [ssShift,ssCtrl], 0, []); AddKey(ecRight, VK_RIGHT, [], 0, []); AddKey(ecSelRight, VK_RIGHT, [ssShift], 0, []); AddKey(ecWordRight, VK_RIGHT, [ssCtrl], 0, []); AddKey(ecSelWordRight, VK_RIGHT, [ssShift,ssCtrl], 0, []); AddKey(ecPageDown, VK_NEXT, [], 0, []); AddKey(ecSelPageDown, VK_NEXT, [ssShift], 0, []); AddKey(ecPageBottom, VK_NEXT, [ssCtrl], 0, []); AddKey(ecSelPageBottom, VK_NEXT, [ssShift,ssCtrl], 0, []); AddKey(ecPageUp, VK_PRIOR, [], 0, []); AddKey(ecSelPageUp, VK_PRIOR, [ssShift], 0, []); AddKey(ecPageTop, VK_PRIOR, [ssCtrl], 0, []); AddKey(ecSelPageTop, VK_PRIOR, [ssShift,ssCtrl], 0, []); AddKey(ecLineStart, VK_HOME, [], 0, []); AddKey(ecSelLineStart, VK_HOME, [ssShift], 0, []); AddKey(ecEditorTop, VK_HOME, [ssCtrl], 0, []); AddKey(ecSelEditorTop, VK_HOME, [ssShift,ssCtrl], 0, []); AddKey(ecLineEnd, VK_END, [], 0, []); AddKey(ecSelLineEnd, VK_END, [ssShift], 0, []); AddKey(ecEditorBottom, VK_END, [ssCtrl], 0, []); AddKey(ecSelEditorBottom, VK_END, [ssShift,ssCtrl], 0, []); AddKey(ecToggleMode, VK_INSERT, [], 0, []); AddKey(ecDeleteChar, VK_DELETE, [], 0, []); AddKey(ecDeleteLastChar, VK_BACK, [], 0, []); AddKey(ecDeleteLastWord, VK_BACK, [ssCtrl], 0, []); AddKey(ecLineBreak, VK_RETURN, [], 0, []); AddKey(ecSelectAll, ord('A'), [ssCtrl], 0, []); AddKey(ecCopy, ord('C'), [ssCtrl], 0, []); AddKey(ecBlockIndent, ord('I'), [ssCtrl,ssShift], 0, []); AddKey(ecInsertLine, ord('N'), [ssCtrl], 0, []); AddKey(ecDeleteWord, ord('T'), [ssCtrl], 0, []); AddKey(ecBlockUnindent, ord('U'), [ssCtrl,ssShift], 0, []); AddKey(ecPaste, ord('V'), [ssCtrl], 0, []); AddKey(ecCut, ord('X'), [ssCtrl], 0, []); AddKey(ecDeleteLine, ord('Y'), [ssCtrl], 0, []); AddKey(ecDeleteEOL, ord('Y'), [ssCtrl,ssShift], 0, []); AddKey(ecUndo, ord('Z'), [ssCtrl], 0, []); AddKey(ecRedo, ord('Z'), [ssCtrl,ssShift], 0, []); AddKey(ecGotoMarker0, ord('0'), [ssCtrl], 0, []); AddKey(ecGotoMarker1, ord('1'), [ssCtrl], 0, []); AddKey(ecGotoMarker2, ord('2'), [ssCtrl], 0, []); AddKey(ecGotoMarker3, ord('3'), [ssCtrl], 0, []); AddKey(ecGotoMarker4, ord('4'), [ssCtrl], 0, []); AddKey(ecGotoMarker5, ord('5'), [ssCtrl], 0, []); AddKey(ecGotoMarker6, ord('6'), [ssCtrl], 0, []); AddKey(ecGotoMarker7, ord('7'), [ssCtrl], 0, []); AddKey(ecGotoMarker8, ord('8'), [ssCtrl], 0, []); AddKey(ecGotoMarker9, ord('9'), [ssCtrl], 0, []); AddKey(ecSetMarker0, ord('0'), [ssCtrl,ssShift], 0, []); AddKey(ecSetMarker1, ord('1'), [ssCtrl,ssShift], 0, []); AddKey(ecSetMarker2, ord('2'), [ssCtrl,ssShift], 0, []); AddKey(ecSetMarker3, ord('3'), [ssCtrl,ssShift], 0, []); AddKey(ecSetMarker4, ord('4'), [ssCtrl,ssShift], 0, []); AddKey(ecSetMarker5, ord('5'), [ssCtrl,ssShift], 0, []); AddKey(ecSetMarker6, ord('6'), [ssCtrl,ssShift], 0, []); AddKey(ecSetMarker7, ord('7'), [ssCtrl,ssShift], 0, []); AddKey(ecSetMarker8, ord('8'), [ssCtrl,ssShift], 0, []); AddKey(ecSetMarker9, ord('9'), [ssCtrl,ssShift], 0, []); AddKey(ecFoldLevel1, ord('1'), [ssAlt,ssShift], 0, []); AddKey(ecFoldLevel2, ord('2'), [ssAlt,ssShift], 0, []); AddKey(ecFoldLevel3, ord('3'), [ssAlt,ssShift], 0, []); AddKey(ecFoldLevel4, ord('4'), [ssAlt,ssShift], 0, []); AddKey(ecFoldLevel5, ord('5'), [ssAlt,ssShift], 0, []); AddKey(ecFoldLevel6, ord('6'), [ssAlt,ssShift], 0, []); AddKey(ecFoldLevel7, ord('7'), [ssAlt,ssShift], 0, []); AddKey(ecFoldLevel8, ord('8'), [ssAlt,ssShift], 0, []); AddKey(ecFoldLevel9, ord('9'), [ssAlt,ssShift], 0, []); AddKey(ecFoldLevel0, ord('0'), [ssAlt,ssShift], 0, []); AddKey(ecFoldCurrent, ord('-'), [ssAlt,ssShift], 0, []); AddKey(ecUnFoldCurrent, ord('+'), [ssAlt,ssShift], 0, []); AddKey(EcToggleMarkupWord, ord('M'), [ssAlt], 0, []); AddKey(ecNormalSelect, ord('N'), [ssCtrl,ssShift], 0, []); AddKey(ecColumnSelect, ord('C'), [ssCtrl,ssShift], 0, []); AddKey(ecLineSelect, ord('L'), [ssCtrl,ssShift], 0, []); AddKey(ecTab, VK_TAB, [], 0, []); AddKey(ecShiftTab, VK_TAB, [ssShift], 0, []); AddKey(ecMatchBracket, ord('B'), [ssCtrl,ssShift], 0, []); AddKey(ecColSelUp, VK_UP, [ssAlt, ssShift], 0, []); AddKey(ecColSelDown, VK_DOWN, [ssAlt, ssShift], 0, []); AddKey(ecColSelLeft, VK_LEFT, [ssAlt, ssShift], 0, []); AddKey(ecColSelRight, VK_RIGHT, [ssAlt, ssShift], 0, []); AddKey(ecColSelPageDown, VK_NEXT, [ssAlt, ssShift], 0, []); AddKey(ecColSelPageBottom, VK_NEXT, [ssAlt, ssShift,ssCtrl], 0, []); AddKey(ecColSelPageUp, VK_PRIOR, [ssAlt, ssShift], 0, []); AddKey(ecColSelPageTop, VK_PRIOR, [ssAlt, ssShift,ssCtrl], 0, []); AddKey(ecColSelLineStart, VK_HOME, [ssAlt, ssShift], 0, []); AddKey(ecColSelLineEnd, VK_END, [ssAlt, ssShift], 0, []); AddKey(ecColSelEditorTop, VK_HOME, [ssAlt, ssShift,ssCtrl], 0, []); AddKey(ecColSelEditorBottom, VK_END, [ssAlt, ssShift,ssCtrl], 0, []); end; end; procedure TCESynMemo.setDefaultFontSize(aValue: Integer); var old: Integer; begin old := Font.Size; if aValue < 5 then aValue := 5; fDefaultFontSize:= aValue; if Font.Size = old then Font.Size := fDefaultFontSize; end; procedure TCESynMemo.setFocus; begin inherited; checkFileDate; if (Highlighter <> nil) then begin LineTextChanged(nil, 0, Lines.Count); Highlighter.ScanRanges; end; identifierToD2Syn; subjDocFocused(TCEMultiDocSubject(fMultiDocSubject), self); end; procedure TCESynMemo.SetVisible(Value: Boolean); begin inherited; if Value then setFocus else begin fDDocWin.Hide; fCallTipWin.Hide; if fCompletion.IsActive then fCompletion.Deactivate; end; end; {$REGION DDoc hints ------------------------------------------------------------} procedure TCESynMemo.InitHintWins; begin if fCallTipWin = nil then begin fCallTipWin := TCEEditorHintWindow.Create(self); fCallTipWin.Color := clInfoBk + $01010100; fCallTipWin.Font.Color:= clInfoText; end; if fDDocWin = nil then begin fDDocWin := TCEEditorHintWindow.Create(self); fDDocWin.Color := clInfoBk + $01010100; fDDocWin.Font.Color:= clInfoText; end; end; procedure TCESynMemo.getCallTips(); var str: string; pnt: TPoint; begin DcdWrapper.getCallTip(str); if str <> '' then begin pnt := ClientToScreen(point(CaretXPix, CaretYPix)); fCallTipWin.FontSize := Font.Size; fCallTipWin.HintRect := fCallTipWin.CalcHintRect(0, str, nil); fCallTipWin.OffsetHintRect(pnt, Font.Size * 2); fCallTipWin.ActivateHint(str); end; end; procedure TCESynMemo.setHintDelay(aValue: Integer); begin fHintDelay:=aValue; fHintTimer.Interval:=fHintDelay; end; procedure TCESynMemo.SetcompletionMenuCaseCare(aValue: boolean); begin fCompletionCaseSens:=aValue; fCompletion.CaseSensitive:=aValue; end; procedure TCESynMemo.HintTimerEvent(sender: TObject); var str: string; begin if not Visible then exit; if not isDSource then exit; // if not fCanShowHint then exit; fCanShowHint := false; DcdWrapper.getDdocFromCursor(str); // if (length(str) > 0) then if str[1] = #13 then str := str[2..length(str)]; if (length(str) > 0) then if str[1] = #10 then str := str[2..length(str)]; // if str <> '' then begin fDDocWin.FontSize := Font.Size; fDDocWin.HintRect := fDDocWin.CalcHintRect(0, str, nil); fDDocWin.OffsetHintRect(mouse.CursorPos, Font.Size); fDDocWin.ActivateHint(fDDocWin.HintRect, str); end; end; {$ENDREGION --------------------------------------------------------------------} {$REGION Completion ------------------------------------------------------------} procedure TCESynMemo.completionExecute(sender: TObject); begin fCompletion.TheForm.Font.Size := Font.Size; getCompletionList; end; procedure TCESynMemo.getCompletionList; begin if not DcdWrapper.available then exit; // fCompletion.Position := 0; fCompletion.ItemList.Clear; DcdWrapper.getComplAtCursor(fCompletion.ItemList); end; procedure TCESynMemo.completionCodeCompletion(var Value: string; SourceValue: string; var SourceStart, SourceEnd: TPoint; KeyChar: TUTF8Char; Shift: TShiftState); begin // warning: '20' depends on ce_dcd, case knd of, string literals length Value := Value[1..length(Value)-20]; end; function TCESynMemo.completionItemPaint(const AKey: string; ACanvas: TCanvas;X, Y: integer; Selected: boolean; Index: integer): boolean; var lft, rgt: string; len: Integer; begin // warning: '20' depends on ce_dcd, case knd of, string literals length result := true; lft := AKey[1 .. length(AKey)-20]; rgt := AKey[length(AKey)-19 .. length(AKey)]; ACanvas.Font.Style := [fsBold]; len := ACanvas.TextExtent(lft).cx; ACanvas.TextOut(2 + X , Y, lft); ACanvas.Font.Style := [fsItalic]; ACanvas.TextOut(2 + X + len + 2, Y, rgt); end; procedure TCESynMemo.AutoDotTimerEvent(sender: TObject); begin if not fCanAutoDot then exit; if fAutoDotDelay = 0 then exit; fCanAutoDot := false; fCompletion.Execute('', ClientToScreen(point(CaretXPix, CaretYPix + Font.Size))); end; procedure TCESynMemo.setAutoDotDelay(aValue: Integer); begin fAutoDotDelay:=aValue; fAutoDotTimer.Interval:=fAutoDotDelay; end; {$ENDREGION --------------------------------------------------------------------} procedure TCESynMemo.SetHighlighter(const Value: TSynCustomHighlighter); begin inherited; fIsDSource := Highlighter = D2Syn; fIsConfig := Highlighter = LfmSyn; fIsTxtFile := Highlighter = TxtSyn; end; procedure TCESynMemo.identifierToD2Syn; begin fIdentifier := GetWordAtRowCol(LogicalCaretXY); if fIsDSource then D2Syn.CurrentIdentifier := fIdentifier else if fIsTxtFile then TxtSyn.CurrIdent := fIdentifier; end; procedure TCESynMemo.changeNotify(Sender: TObject); begin identifierToD2Syn; fModified := true; fPositions.store; subjDocChanged(TCEMultiDocSubject(fMultiDocSubject), self); end; procedure TCESynMemo.loadFromFile(const aFilename: string); var ext: string; begin ext := extractFileExt(aFilename); if dExtList.IndexOf(ext) = -1 then Highlighter := TxtSyn; Lines.LoadFromFile(aFilename); fFilename := aFilename; FileAge(fFilename, fFileDate); // loadCache; // fModified := false; if Showing then setFocus; subjDocChanged(TCEMultiDocSubject(fMultiDocSubject), self); end; procedure TCESynMemo.saveToFile(const aFilename: string); var ext: string; begin Lines.SaveToFile(aFilename); fFilename := aFilename; ext := extractFileExt(aFilename); if dExtList.IndexOf(ext) <> -1 then Highlighter := D2Syn; FileAge(fFilename, fFileDate); fModified := false; if fFilename <> fTempFileName then subjDocChanged(TCEMultiDocSubject(fMultiDocSubject), self); end; procedure TCESynMemo.save; begin Lines.SaveToFile(fFilename); FileAge(fFilename, fFileDate); fModified := false; if fFilename <> fTempFileName then subjDocChanged(TCEMultiDocSubject(fMultiDocSubject), self); end; procedure TCESynMemo.saveTempFile; begin saveToFile(fTempFileName); fModified := false; end; function TCESynMemo.getIfTemp: boolean; begin exit(fFilename = fTempFileName); end; procedure TCESynMemo.saveCache; var cache: TCESynMemoCache; begin cache := TCESynMemoCache.create(self); try cache.save; finally cache.free; end; end; procedure TCESynMemo.loadCache; var cache: TCESynMemoCache; begin cache := TCESynMemoCache.create(self); try cache.load; finally cache.free; end; end; class procedure TCESynMemo.cleanCache; var lst: TStringList; today, t: TDateTime; fname: string; y, m, d: word; begin lst := TStringList.Create; try listFiles(lst, getCoeditDocPath + 'editorcache' + DirectorySeparator); today := date(); for fname in lst do if FileAge(fname, t) then begin DecodeDate(t, y, m, d); IncAMonth(y, m, d, 3); if EncodeDate(y, m, d) <= today then sysutils.DeleteFile(fname); end; finally lst.free; end; end; procedure TCESynMemo.checkFileDate; var newDate: double; str: TStringList; begin if fFilename = fTempFileName then exit; if not FileAge(fFilename, newDate) then exit; if fFileDate = newDate then exit; if fFileDate <> 0.0 then begin // note: this could cause a bug in France during the switch from winter time to summer time. // e.g: save at 2h59, at 3h00, clock is reset to 2h00, set the focus on the doc: new version message. if dlgOkCancel(format('"%s" has been modified by another program, load the new version ?', [shortenPath(fFilename, 25)])) = mrOk then begin str := TStringList.Create; try str.LoadFromFile(fFilename); ClearAll; if str.Count > 0 then begin DoCopyToClipboard(str.Text); PasteFromClipboard; end; fModified := true; finally str.Free; end; end; end; fFileDate := newDate; end; procedure TCESynMemo.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; identifierToD2Syn; case Key of VK_BROWSER_BACK: fPositions.back; VK_BROWSER_FORWARD: fPositions.next; VK_ESCAPE: begin fCallTipWin.Hide; fDDocWin.Hide; end; end; if not (Shift = [ssCtrl]) then exit; case Key of VK_ADD: if Font.Size < 50 then Font.Size := Font.Size + 1; VK_SUBTRACT: if Font.Size > 3 then Font.Size := Font.Size - 1; VK_DECIMAL: Font.Size := fDefaultFontSize; end; TCEEditorHintWindow.FontSize := Font.Size; UpdateCursor; fCanShowHint:=false; fDDocWin.Hide; end; procedure TCESynMemo.KeyUp(var Key: Word; Shift: TShiftState); begin case Key of VK_PRIOR, VK_NEXT, Vk_UP: fPositions.store; VK_OEM_PERIOD, VK_DECIMAL: fCanAutoDot := true; end; inherited; // if StaticEditorMacro.automatic then StaticEditorMacro.Execute; end; procedure TCESynMemo.UTF8KeyPress(var Key: TUTF8Char); var c: TUTF8Char; begin c := Key; inherited; case c of '(': getCallTips; ')': fCallTipWin.Hide; end; end; function TCESynMemo.getMouseFileBytePos: Integer; var i, len, llen: Integer; begin result := 0; if fMousePos.y-1 > Lines.Count-1 then exit; llen := length(Lines.Strings[fMousePos.y-1]); if fMousePos.X > llen then exit; // // something note really clear: // TCEEditorWidget.getSymbolLoc works when using the line ending of the file. // TCESynMemo.getMouseFileBytePos works when using the line ending from the system. len := getSysLineEndLen; for i:= 0 to fMousePos.y-2 do result += length(Lines.Strings[i]) + len; result += fMousePos.x; end; procedure TCESynMemo.MouseLeave; begin fDDocWin.Hide; fCallTipWin.Hide; end; procedure TCESynMemo.MouseMove(Shift: TShiftState; X, Y: Integer); var dX, dY: Integer; begin fDDocWin.Hide; fCallTipWin.Hide; inherited; dx := X - fOldMousePos.x; dy := Y - fOldMousePos.y; fCanShowHint:=false; if (shift = []) then if ((dx < 0) and (dx > -5) or (dx > 0) and (dx < 5)) or ((dy < 0) and (dy > -5) or (dy > 0) and (dy < 5)) then fCanShowHint:=true; fOldMousePos := Point(X, Y); fMousePos := PixelsToRowColumn(fOldMousePos); if ssLeft in Shift then identifierToD2Syn; end; procedure TCESynMemo.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y:Integer); begin inherited; identifierToD2Syn; fCanShowHint := false; fDDocWin.Hide; fCallTipWin.Hide; end; procedure TCESynMemo.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y:Integer); begin inherited; case Button of mbMiddle: if (Shift = [ssCtrl]) then Font.Size := fDefaultFontSize; // linux, kde: mbExtra are never called mbExtra1: fPositions.back; mbExtra2: fPositions.next; mbLeft: fPositions.store; end; end; function TCESynMemo.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin result := inherited DoMouseWheel(Shift, WheelDelta, MousePos); fCanShowHint:=false; fHintTimer.Enabled:=false; end; {$ENDREGION --------------------------------------------------------------------} initialization D2Syn := TSynD2Syn.create(nil); LfmSyn := TSynLFMSyn.Create(nil); TxtSyn := TSynTxtSyn.create(nil); // LfmSyn.KeyAttri.Foreground := clNavy; LfmSyn.KeyAttri.Style := [fsBold]; LfmSyn.NumberAttri.Foreground := clMaroon; LfmSyn.StringAttri.Foreground := clBlue; // TCEEditorHintWindow.FontSize := 10; finalization D2Syn.Free; LfmSyn.Free; TxtSyn.Free; // TCESynMemo.cleanCache; end.
unit uCidadeVO; interface uses System.SysUtils, uKeyField, uTableName; type [TableName('Cidade')] TCidadeVO = class private FAtivo: Boolean; FUF: string; FCodigo: Integer; FId: integer; FNome: string; procedure SetAtivo(const Value: Boolean); procedure SetCodigo(const Value: Integer); procedure SetId(const Value: integer); procedure SetNome(const Value: string); procedure SetUF(const Value: string); public [KeyField('Cid_Id')] property Id: integer read FId write SetId; [FieldName('Cid_Codigo')] property Codigo: Integer read FCodigo write SetCodigo; [FieldName('Cid_Nome')] property Nome: string read FNome write SetNome; [FieldName('Cid_UF')] property UF: string read FUF write SetUF; [FieldName('Cid_Ativo')] property Ativo: Boolean read FAtivo write SetAtivo; end; implementation { TCidadeVO } procedure TCidadeVO.SetAtivo(const Value: Boolean); begin FAtivo := Value; end; procedure TCidadeVO.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TCidadeVO.SetId(const Value: integer); begin FId := Value; end; procedure TCidadeVO.SetNome(const Value: string); begin FNome := Value; end; procedure TCidadeVO.SetUF(const Value: string); begin FUF := Value; end; end.
program backup; {---------------------------------------------------------------------} {Author: Travis Keep Modification history: 3-1-97 Added drive letter as second argument of command line} {---------------------------------------------------------------------} uses dos; type backuptype=record f:file; disknum:integer; drivenum:integer; control:word; isopened:boolean end; var b:backuptype; path:string; thedrive:string[2]; g_buffer:pointer; Function checksum(var b:backuptype):longint; var temp:longint; begin if b.disknum = 1 then begin b.control := random(256); b.control := 256*b.control + random(256) end; temp := b.control; temp := temp*65536 + b.disknum; checksum := temp end; Procedure backupinit(var b:backuptype;drive:char); begin b.disknum := 0; b.drivenum := (ord(drive) and 95) - 64; b.isopened := false end; Function backupdriveletter(var b:backuptype):char; begin backupdriveletter := chr(b.drivenum + 64) end; Procedure backupprompt(var b:backuptype); var error:integer; done:boolean; cs:longint; result:word; fname:string[20]; begin b.disknum := b.disknum + 1; write('Insert disk ',b.disknum,' and press ENTER to resume.'); readln; cs := checksum(b); done := false; fname := '?:\tar.dat'; fname[1] := backupdriveletter(b); repeat assign(b.f,fname); {$I-} rewrite(b.f,1); {$I+} error := IOresult; if error <> 0 then begin write('Error writing to drive ',backupdriveletter(b),'. Press ENTER to retry.'); readln end else begin blockwrite(b.f,cs,sizeof(cs),result); if result < sizeof(cs) then begin write('Disk full in drive ',backupdriveletter(b),'. Press ENTER to retry.'); readln; close(b.f) end else begin b.isopened := true; done := true end end until done end; Procedure backupwrite(var b:backuptype;var buffer;count:word); var lefttowrite,result:word; segment,offset:word; spaceleft:longint; p:pointer; begin lefttowrite := count; segment := Seg(buffer); offset := Ofs(buffer); while lefttowrite > 0 do begin if not b.isopened then backupprompt(b); p := ptr(segment,offset); blockwrite(b.f,p^,lefttowrite,result); if result = 0 then begin spaceleft := diskfree(b.drivenum); blockwrite(b.f,p^,spaceleft,result); if result < spaceleft then begin writeln('Critical error in backupwrite'); halt(1) end end; if result < lefttowrite then begin close(b.f); b.isopened := false; lefttowrite := lefttowrite - result; offset := offset + result end else lefttowrite := 0 end end; Procedure backupclose(var b:backuptype); begin if b.isopened then close(b.f) end; Procedure curattrwrite(var b:backuptype;var srec:SearchRec); begin backupwrite(b,srec,sizeof(SearchRec)) end; Procedure curfilewrite(var b:backuptype;var srec:SearchRec); var f:file; numread:word; begin assign(f,srec.Name); reset(f,1); repeat blockread(f,g_buffer^,65520,numread); backupwrite(b,g_buffer^,numread) until (numread = 0); close(f) end; Procedure enddirwrite(var b:backuptype); var srec:SearchRec; begin srec.size := -1; curattrwrite(b,srec) end; Procedure endallwrite(var b:backuptype); var srec:SearchRec; begin srec.size := -2; curattrwrite(b,srec) end; Procedure curdirwrite(var b:backuptype;path:string); forward; Procedure curfiledirwrite(var b:backuptype;var srec:SearchRec); begin if (srec.Attr and 10) > 0 then begin end else if (srec.Name = '.') or (srec.Name = '..') then begin end else begin curattrwrite(b,srec); if (srec.Attr and 16) > 0 then begin chdir(srec.Name); curdirwrite(b,'*.*'); enddirwrite(b); chdir('..') end else curfilewrite(b,srec) end end; Procedure curdirwrite(var b:backuptype;path:string); var srec:SearchRec; error:integer; begin FindFirst(path,63,srec); error := DosError; while error = 0 do begin curfiledirwrite(b,srec); FindNext(srec); error := DosError end end; Function incurrentdir(var path:string):boolean; var i:integer; temp:boolean; begin temp := true; i := 1; while (temp) and (i <= length(path)) do begin if (path[i] = ':') or (path[i] = '\') then temp := false; i := i + 1 end; incurrentdir := temp end; begin FileMode := 0; randomize; getmem(g_buffer,65520); path := paramstr(1); if path = '' then begin writeln('You must specify files and directories to back up.'); halt(1) end; if not incurrentdir(path) then begin writeln('You must back up from the current directory'); halt(1) end; thedrive := paramstr(2); if thedrive = '' then backupinit(b,'a') else begin if not (thedrive[1] in ['A'..'Z','a'..'z']) then begin writeln('Invalid drive letter on command line'); halt(1) end; backupinit(b,thedrive[1]) end; curdirwrite(b,path); if (b.disknum = 0) then begin writeln('File not found.'); halt(1) end else endallwrite(b) end.
unit untCamposPersonalizadosMDL; interface uses untDescricaoJson; type TCamposPersonalizadosMDL = class private FResponsavelProposta002: string; FEntregaEmbalagem001: string; FCargoResponsavelProposta003: string; FCondicoesPagamento006: string; FEmailResponsavelProposta004: string; FTelefoneResponsavelProposta005: string; FOrdemServico007: string; FHdaOrHdn009: string; FOrdemVenda008: string; procedure SetEntregaEmbalagem001(const Value: string); procedure SetResponsavelProposta002(const Value: string); procedure SetCargoResponsavelProposta003(const Value: string); procedure SetCondicoesPagamento006(const Value: string); procedure SetEmailResponsavelProposta004(const Value: string); procedure SetTelefoneResponsavelProposta005(const Value: string); procedure SetOrdemServico007(const Value: string); procedure SetHdaOrHdn009(const Value: string); procedure SetOrdemVenda008(const Value: string); public // Sequencial é necessário para garantir que o replace no JSON será único. [DescricaoJson('Entrega e embalagem')] property EntregaEmbalagem001: string read FEntregaEmbalagem001 write SetEntregaEmbalagem001; [DescricaoJson('Responsável pela Proposta')] property ResponsavelProposta002: string read FResponsavelProposta002 write SetResponsavelProposta002; [DescricaoJson('Cargo do Responsável pela Proposta')] property CargoResponsavelProposta003: string read FCargoResponsavelProposta003 write SetCargoResponsavelProposta003; [DescricaoJson('Email do Responsável pela Proposta')] property EmailResponsavelProposta004: string read FEmailResponsavelProposta004 write SetEmailResponsavelProposta004; [DescricaoJson('Telefone do Responsável pela Proposta')] property TelefoneResponsavelProposta005: string read FTelefoneResponsavelProposta005 write SetTelefoneResponsavelProposta005; [DescricaoJson('Condições de Pagamento')] property CondicoesPagamento006: string read FCondicoesPagamento006 write SetCondicoesPagamento006; [DescricaoJson('Ordem de Serviço')] property OrdemServico007: string read FOrdemServico007 write SetOrdemServico007; [DescricaoJson('Ordem de Venda')] property OrdemVenda008: string read FOrdemVenda008 write SetOrdemVenda008; [DescricaoJson('HDA ou HDN')] property HdaOrHdn009: string read FHdaOrHdn009 write SetHdaOrHdn009; end; implementation { TCamposPersonalizados } procedure TCamposPersonalizadosMDL.SetCargoResponsavelProposta003(const Value: string); begin FCargoResponsavelProposta003 := Value; end; procedure TCamposPersonalizadosMDL.SetCondicoesPagamento006(const Value: string); begin FCondicoesPagamento006 := Value; end; procedure TCamposPersonalizadosMDL.SetEmailResponsavelProposta004(const Value: string); begin FEmailResponsavelProposta004 := Value; end; procedure TCamposPersonalizadosMDL.SetEntregaEmbalagem001(const Value: string); begin FEntregaEmbalagem001 := Value; end; procedure TCamposPersonalizadosMDL.SetHdaOrHdn009(const Value: string); begin FHdaOrHdn009 := Value; end; procedure TCamposPersonalizadosMDL.SetOrdemServico007(const Value: string); begin FOrdemServico007 := Value; end; procedure TCamposPersonalizadosMDL.SetOrdemVenda008(const Value: string); begin FOrdemVenda008 := Value; end; procedure TCamposPersonalizadosMDL.SetTelefoneResponsavelProposta005(const Value: string); begin FTelefoneResponsavelProposta005 := Value; end; procedure TCamposPersonalizadosMDL.SetResponsavelProposta002(const Value: string); begin FResponsavelProposta002 := Value; end; end.
unit nsTreeStruct; {* Дерево. Фасад к адаптерному дереву } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\Tree\nsTreeStruct.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsTreeStruct" MUID: (46835B4001A4) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , nsRootManager , l3TreeInterfaces , bsInterfaces , l3LongintList , nsINodeWrapBase , l3Interfaces , DynamicTreeUnit , l3InternalInterfaces , l3ProtoObject ; type TnsTreeStructState = class(Tl3ProtoObject, InsTreeStructState) private f_SelectedIndexList: Tl3LongintList; private procedure FillList(aSelectedIndexList: Tl3LongintList); protected function GetSelectedNodeCount: Integer; function GetSelectedNodeVisibleIndex(aIndex: Integer): Integer; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aSelectedIndexList: Tl3LongintList); reintroduce; class function Make(aSelectedIndexList: Tl3LongintList): InsTreeStructState; reintroduce; end;//TnsTreeStructState TnsTreeStruct = class(TnsRootManager, Il3RootSource, Il3SimpleTree, Il3ExpandedSimpleTree, InsTreeStructStateProvider, InsTreeStructStateConsumer) {* Дерево. Фасад к адаптерному дереву } private f_ShowRoot: Boolean; f_SelectedIndexList: Tl3LongintList; protected f_Root: Il3SimpleRootNode; private function GetNodeClass(const aNode: INodeBase): RnsINodeWrap; {* вычисляем класс ноды для создания обертки } protected function pm_GetRoot: Il3SimpleRootNode; virtual; procedure pm_SetRoot(const aValue: Il3SimpleRootNode); virtual; procedure DoSelectAllNodes(aMode: Tl3SetBitType); virtual; procedure DoSelectInterval(aFirstIndex: Integer; aLastIndex: Integer; aMode: Tl3SetBitType; aCleanOther: Boolean); virtual; procedure RootChanged(const aOld: Il3SimpleRootNode; const aNew: Il3SimpleRootNode); virtual; procedure MakeRootNode(const aRoot: INodeBase); virtual; function IsNodeVisible(const aNode: INodeBase): Boolean; procedure SelectCountChanged(anOldCount: Integer; aNewCount: Integer); {* нотификация визуальному дереву о смене количества выделенных элементов } function RootNodeClass: RnsINodeWrap; virtual; {* определяет класс обертки для Root } function MakeChildNode(const aChild: INodeBase): Il3SimpleNode; virtual; function DoMakeDataObject(const aData: Il3SimpleNode; const aBitmap: Il3Bitmap): IDataObject; virtual; {* объект данных дерева. aData - текущий элемент списка. aBitmap (Il3Bitmap) - картинка для перетаскивания } function DoCanAcceptData(const aTargetNode: Il3SimpleNode; const aData: Tl3TreeData; aProcessed: PBoolean): Boolean; virtual; function DoDropData(const aTargetNode: Il3SimpleNode; const aData: Tl3TreeData; var aProcessed: Boolean): Boolean; virtual; procedure ExternalModified(aNode: Integer; aDelta: Integer); {* в дереве были добавлены/удалены элементы. - aNode: Узел ниже которого добавили/удалили узлы. Нумерация начинается с нуля; - aDelta: Количество элементов которое было добавлено/удалено. Если aDelta со знаком минус элементы были удалены; } function DoChangeExpand(const aNode: Il3SimpleNode; aMode: Tl3SetBitType; aForceMode: Boolean): Boolean; virtual; function GetSelectCount: Integer; virtual; procedure DoSelectionChanged(anIndex: Integer; aSelected: Boolean); function Get_RootNode: Il3SimpleRootNode; procedure Set_RootNode(const aValue: Il3SimpleRootNode); procedure CursorTop; {* переставить курсор на первый видимый элемент. } function GetIndex(const aNode: Il3SimpleNode; const aSubRootNode: Il3SimpleNode = nil): Integer; {* возвращает видимый индекс aNode относительно aSubRootNode или корня. } function GetLevel(const aNode: Il3SimpleNode): Integer; {* возвращает уровень узла относительно корня. } procedure SelectAllNodes(aMode: Tl3SetBitType); {* выделяет/развыделяет все узлы. } procedure SelectInterval(aFirstIndex: Integer; aLastIndex: Integer; aMode: Tl3SetBitType; aCleanOther: Boolean); {* выделяет/развыделяет узлы на указанном интервале. } function ChangeExpand(const aNode: Il3SimpleNode; aMode: Tl3SetBitType; aForceMode: Boolean = False): Boolean; {* меняет развернутость узла. } procedure ExpandSubDir(const aNode: Il3SimpleNode = nil; anExpand: Boolean = True; aDeepLevel: Byte = 0); {* развернуть/свернуть узлы. } procedure SetBranchFlag(const aParentNode: Il3SimpleNode; aMode: Tl3SetBitType; aFlagsMask: Integer; anIterMode: Integer); {* зачем-то используется визуалкой в ExpandNode. } function CountViewItemsInSubDir(const aNode: Il3SimpleNode): Integer; {* зачем-то используется визуалкой в ShowMoreChildrenOnScreen. } function IsRoot(const aNode: Il3SimpleNode): Boolean; {* является ли узел корневым для дерева. } function IsExpanded(const aNode: Il3SimpleNode): Boolean; {* раскрыт ли узел. } function IsFirstVis(const aNode: Il3SimpleNode): Boolean; {* является ли узел первым видимым в ветке. } function IsLastVis(const aNode: Il3SimpleNode): Boolean; {* является ли узел последним видимым в ветке. } function HasVisibleChildren(const aNode: Il3SimpleNode): Boolean; {* есть ли видимые дети у aNode. } function GetLines(const aNode: Il3SimpleNode): Integer; {* маска для рисования линий (надо смотреть реализацию). } function Wake: Boolean; {* проснись!!! Типа начали рисовать. } function MoveNode(const aNode: Il3SimpleNode; aDirection: Tl3Direction): Boolean; {* переместить узел. } function SearchNameBegin(const aFirstNode: Il3SimpleNode; aSrchStr: PAnsiChar; aIterMode: Integer): Il3SimpleNode; {* зачем-то используется визуалкой в CharToItem. } function SearchNameOccur(const aFirstNode: Il3SimpleNode; aSrchStr: PAnsiChar; aIterMode: Integer): Il3SimpleNode; {* зачем-то используется визуалкой в SearchOccurStr, который сейчас никем не используется. } function MakeNodeVisible(const aNode: Il3SimpleNode): Integer; {* зачем-то используется визуалкой в CharToItem, видимо для перемещения курсора на узел. } function GetPrev(const aNode: Il3SimpleNode): Il3SimpleNode; {* предыдущий узел. Зачем-то используется в CharToItem. } function SimpleIterateF(Action: Tl3SimpleNodeAction; IterMode: Integer = 0; const aSubRootNode: Il3SimpleNode = nil): Il3SimpleNode; {* перебрать все узлы и освободить заглушку для Action. IterMode: imCheckResult, imParentNeed } function IsChanging: Boolean; {* дерево находится в фазе обновления. } procedure Changing; procedure Changed; function Get_ShowRoot: Boolean; procedure Set_ShowRoot(aValue: Boolean); function Get_CountView: Integer; function Get_SelectCount: Integer; function Get_Flags(anIndex: Integer): Integer; function Get_Select(anIndex: Integer): Boolean; procedure Set_Select(anIndex: Integer; aValue: Boolean); function Get_Nodes(anIndex: Integer): Il3SimpleNode; function FlagIterateF(Action: Tl3SimpleNodeAction; FlagMask: Word = 0; IterMode: Integer = 0; const aSubRootNode: Il3SimpleNode = nil; aCheckResult: Boolean = False): Il3SimpleNode; {* перебрать все узлы, удовлетворяющие FlagMask, и освободить заглушку для Action. IterMode: imCheckResult, imParentNeed } function MakeDataObject(const aNode: Il3SimpleNode; const aBitmap: IUnknown): IDataObject; {* сделать объект данных дерева, используется при перемещении элементов дерева в другие компоненты } function CanAcceptData(const aTargetNode: Il3SimpleNode; const aData: Tl3TreeData): Boolean; function DropData(const aTargetNode: Il3SimpleNode; const aData: Tl3TreeData): Boolean; function MakeState: InsTreeStructState; procedure AssignState(const aState: InsTreeStructState); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure FireChanged; override; procedure ChangeChildrenCountPrim(aNodeIndex: TVisibleIndex; aDelta: Integer; const aIndexPath: INodeIndexPath; aChildIndex: TIndexInParent); override; function GetShowRoot: Boolean; override; procedure ChangingPrim; override; procedure ChangedPrim; override; procedure ExternalInvalidate; override; procedure ExternalVisibleCountChanged(aNewCount: Integer; aNodeIndex: Integer; aDelta: Integer); override; {* нотификация визуальному дереву о смене количества видимых элементов } public constructor Create(const aRoot: INodeBase; aShowRoot: Boolean; aOneLevel: Boolean = False); reintroduce; virtual; class function Make(const aRoot: INodeBase; aShowRoot: Boolean; aOneLevel: Boolean = False): Il3SimpleTree; reintroduce; protected property Root: Il3SimpleRootNode read pm_GetRoot write pm_SetRoot; end;//TnsTreeStruct implementation uses l3ImplUses , SysUtils , l3InterfacesMisc , l3Nodes , l3Bits , l3Base , l3Types {$If NOT Defined(NoVCM)} , vcmBase {$IfEnd} // NOT Defined(NoVCM) , nsINodeRootWrap , nsINodeWrap , BaseTypesUnit //#UC START# *46835B4001A4impl_uses* , vcmDispatcher //#UC END# *46835B4001A4impl_uses* ; constructor TnsTreeStructState.Create(aSelectedIndexList: Tl3LongintList); //#UC START# *56A887A200DE_56A8877600AB_var* //#UC END# *56A887A200DE_56A8877600AB_var* begin //#UC START# *56A887A200DE_56A8877600AB_impl* inherited Create; Assert(aSelectedIndexList <> nil); f_SelectedIndexList := Tl3LongIntList.Create; FillList(aSelectedIndexList); //#UC END# *56A887A200DE_56A8877600AB_impl* end;//TnsTreeStructState.Create class function TnsTreeStructState.Make(aSelectedIndexList: Tl3LongintList): InsTreeStructState; var l_Inst : TnsTreeStructState; begin l_Inst := Create(aSelectedIndexList); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnsTreeStructState.Make procedure TnsTreeStructState.FillList(aSelectedIndexList: Tl3LongintList); //#UC START# *56A892DC0298_56A8877600AB_var* var l_Index: Integer; //#UC END# *56A892DC0298_56A8877600AB_var* begin //#UC START# *56A892DC0298_56A8877600AB_impl* for l_Index := 0 to Pred(aSelectedIndexList.Count) do f_SelectedIndexList.Add(aSelectedIndexList[l_Index]); //#UC END# *56A892DC0298_56A8877600AB_impl* end;//TnsTreeStructState.FillList function TnsTreeStructState.GetSelectedNodeCount: Integer; //#UC START# *56CD757F012F_56A8877600AB_var* //#UC END# *56CD757F012F_56A8877600AB_var* begin //#UC START# *56CD757F012F_56A8877600AB_impl* Result := f_SelectedIndexList.Count; //#UC END# *56CD757F012F_56A8877600AB_impl* end;//TnsTreeStructState.GetSelectedNodeCount function TnsTreeStructState.GetSelectedNodeVisibleIndex(aIndex: Integer): Integer; //#UC START# *56CD758B0198_56A8877600AB_var* //#UC END# *56CD758B0198_56A8877600AB_var* begin //#UC START# *56CD758B0198_56A8877600AB_impl* Result := f_SelectedIndexList[aIndex]; //#UC END# *56CD758B0198_56A8877600AB_impl* end;//TnsTreeStructState.GetSelectedNodeVisibleIndex procedure TnsTreeStructState.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_56A8877600AB_var* //#UC END# *479731C50290_56A8877600AB_var* begin //#UC START# *479731C50290_56A8877600AB_impl* FreeAndNil(f_SelectedIndexList); inherited; //#UC END# *479731C50290_56A8877600AB_impl* end;//TnsTreeStructState.Cleanup function TnsTreeStruct.pm_GetRoot: Il3SimpleRootNode; //#UC START# *48FDD9D901BB_46835B4001A4get_var* //#UC END# *48FDD9D901BB_46835B4001A4get_var* begin //#UC START# *48FDD9D901BB_46835B4001A4get_impl* Result := f_Root; //#UC END# *48FDD9D901BB_46835B4001A4get_impl* end;//TnsTreeStruct.pm_GetRoot procedure TnsTreeStruct.pm_SetRoot(const aValue: Il3SimpleRootNode); //#UC START# *48FDD9D901BB_46835B4001A4set_var* var l_Root : INodeBase; l_OldRoot : Il3SimpleRootNode; //#UC END# *48FDD9D901BB_46835B4001A4set_var* begin //#UC START# *48FDD9D901BB_46835B4001A4set_impl* if not l3IEQ(f_Root, aValue) then begin l_OldRoot := f_Root; try RootNode := nil; f_Root := aValue; DropCountView; Supports(f_Root, INodeBase, l_Root); RootNode := l_Root; CursorTop; RootChanged(l_OldRoot, aValue); finally l_OldRoot := nil; end;//try..finally end;//not l3IEQ(f_Root, aValue) //#UC END# *48FDD9D901BB_46835B4001A4set_impl* end;//TnsTreeStruct.pm_SetRoot procedure TnsTreeStruct.DoSelectAllNodes(aMode: Tl3SetBitType); //#UC START# *51F1503E01A9_46835B4001A4_var* var l_OldSelectCount, l_NewSelectCount: Integer; //#UC END# *51F1503E01A9_46835B4001A4_var* begin //#UC START# *51F1503E01A9_46835B4001A4_impl* if RootNode <> nil then begin l_OldSelectCount := RootNode.GetFlagCount(FM_SELECTION); if aMode = sbSelect then RootNode.SetAllFlag(FM_SELECTION, True) else if aMode = sbDeselect then begin f_SelectedIndexList.Clear; RootNode.SetAllFlag(FM_SELECTION, False); end; l_NewSelectCount := RootNode.GetFlagCount(FM_SELECTION); SelectCountChanged(l_OldSelectCount, l_NewSelectCount); end; //#UC END# *51F1503E01A9_46835B4001A4_impl* end;//TnsTreeStruct.DoSelectAllNodes procedure TnsTreeStruct.DoSelectInterval(aFirstIndex: Integer; aLastIndex: Integer; aMode: Tl3SetBitType; aCleanOther: Boolean); //#UC START# *51F1508A01EA_46835B4001A4_var* var l_Node: INodeBase; l_First, l_Last: LongInt; l_OldSelectCount, l_NewSelectCount: Integer; //#UC END# *51F1508A01EA_46835B4001A4_var* begin //#UC START# *51F1508A01EA_46835B4001A4_impl* if CurrentNode <> nil then begin l_Node := CurrentNode; l_First := aFirstIndex - CurrentNodeIndex; l_Last := aLastIndex - CurrentNodeIndex; end else if RootNode <> nil then begin l_Node := RootNode; l_First := aFirstIndex; l_Last := aLastIndex; end else exit; l_OldSelectCount := RootNode.GetFlagCount(FM_SELECTION); if aMode = sbSelect then l_Node.SetRangeFlag(l_First, l_Last, FM_SELECTION, True, aCleanOther) else if aMode = sbDeselect then l_Node.SetRangeFlag(l_First, l_Last, FM_SELECTION, False, aCleanOther); l_NewSelectCount := RootNode.GetFlagCount(FM_SELECTION); SelectCountChanged(l_OldSelectCount, l_NewSelectCount); //#UC END# *51F1508A01EA_46835B4001A4_impl* end;//TnsTreeStruct.DoSelectInterval constructor TnsTreeStruct.Create(const aRoot: INodeBase; aShowRoot: Boolean; aOneLevel: Boolean = False); //#UC START# *48FDD9270194_46835B4001A4_var* //#UC END# *48FDD9270194_46835B4001A4_var* begin //#UC START# *48FDD9270194_46835B4001A4_impl* inherited Create; f_SelectedIndexList := Tl3LongintList.Create; Self.OneLevel := aOneLevel; f_ShowRoot := aShowRoot; MakeRootNode(aRoot); //#UC END# *48FDD9270194_46835B4001A4_impl* end;//TnsTreeStruct.Create class function TnsTreeStruct.Make(const aRoot: INodeBase; aShowRoot: Boolean; aOneLevel: Boolean = False): Il3SimpleTree; var l_Inst : TnsTreeStruct; begin l_Inst := Create(aRoot, aShowRoot, aOneLevel); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnsTreeStruct.Make procedure TnsTreeStruct.RootChanged(const aOld: Il3SimpleRootNode; const aNew: Il3SimpleRootNode); //#UC START# *48FDDE4B01F5_46835B4001A4_var* procedure lp_Notify; var l_Index : Integer; l_Spy : Il3RootSpy; l_Item : IUnknown; begin if (NotifiedObjList <> nil) and (NotifiedObjList.Count > 0) then for l_Index := 0 to Pred(NotifiedObjList.Count) do begin l_Item := IUnknown(NotifiedObjList.Items[l_Index]); if Supports(l_Item, Il3RootSpy, l_Spy) and (l_Item = l_Spy) then l_Spy.RootChanged(aOld, aNew); end;//if (NotifiedObjList <> nil) end;//lp_Notify //#UC END# *48FDDE4B01F5_46835B4001A4_var* begin //#UC START# *48FDDE4B01F5_46835B4001A4_impl* lp_Notify; //#UC END# *48FDDE4B01F5_46835B4001A4_impl* end;//TnsTreeStruct.RootChanged procedure TnsTreeStruct.MakeRootNode(const aRoot: INodeBase); //#UC START# *48FDDE69025A_46835B4001A4_var* //#UC END# *48FDDE69025A_46835B4001A4_var* begin //#UC START# *48FDDE69025A_46835B4001A4_impl* Root := RootNodeClass.Make(aRoot) as Il3SimpleRootNode; //#UC END# *48FDDE69025A_46835B4001A4_impl* end;//TnsTreeStruct.MakeRootNode function TnsTreeStruct.IsNodeVisible(const aNode: INodeBase): Boolean; //#UC START# *48FDDE8402E9_46835B4001A4_var* Var l_Parent: INodeBase; l_PrevParent: INodeBase; //#UC END# *48FDDE8402E9_46835B4001A4_var* begin //#UC START# *48FDDE8402E9_46835B4001A4_impl* Result := false; if aNode <> nil then begin aNode.GetParent(l_Parent); while l_Parent <> nil do begin if not l_Parent.HasFlag(FM_OPEN) then exit; l_Parent.GetParent(l_PrevParent); l_Parent := nil; l_Parent := l_PrevParent; end; Result := true; end; //#UC END# *48FDDE8402E9_46835B4001A4_impl* end;//TnsTreeStruct.IsNodeVisible procedure TnsTreeStruct.SelectCountChanged(anOldCount: Integer; aNewCount: Integer); {* нотификация визуальному дереву о смене количества выделенных элементов } //#UC START# *48FDDE9E01C4_46835B4001A4_var* var l_Index : Integer; l_Intf : Il3SelectCountChangedRecipient; l_Item : IUnknown; //#UC END# *48FDDE9E01C4_46835B4001A4_var* begin //#UC START# *48FDDE9E01C4_46835B4001A4_impl* if HasNotified then for l_Index := Pred(NotifiedObjList.Count) downto 0 do begin l_Item := IUnknown(NotifiedObjList.Items[l_Index]); if Supports(IUnknown(NotifiedObjList[l_Index]), Il3SelectCountChangedRecipient, l_Intf) and (l_Item = l_Intf) then try l_Intf.SelectCountChanged(anOldCount, aNewCount); finally l_Intf := nil; end;//try..finally end;//for //#UC END# *48FDDE9E01C4_46835B4001A4_impl* end;//TnsTreeStruct.SelectCountChanged function TnsTreeStruct.GetNodeClass(const aNode: INodeBase): RnsINodeWrap; {* вычисляем класс ноды для создания обертки } //#UC START# *48FEE33D00A2_46835B4001A4_var* var l_NodeInfo: InsNodeImplementationInfo; //#UC END# *48FEE33D00A2_46835B4001A4_var* begin //#UC START# *48FEE33D00A2_46835B4001A4_impl* Result := TnsINodeWrap; if RootNode <> nil then begin if RootNode.IsSameNode(aNode) then Result := RootNodeClass else if Supports(f_Root, InsNodeImplementationInfo, l_NodeInfo) then Result := l_NodeInfo.ChildNodeClass; end; //#UC END# *48FEE33D00A2_46835B4001A4_impl* end;//TnsTreeStruct.GetNodeClass function TnsTreeStruct.RootNodeClass: RnsINodeWrap; {* определяет класс обертки для Root } //#UC START# *48FEE3640227_46835B4001A4_var* //#UC END# *48FEE3640227_46835B4001A4_var* begin //#UC START# *48FEE3640227_46835B4001A4_impl* Result := TnsINodeRootWrap; //#UC END# *48FEE3640227_46835B4001A4_impl* end;//TnsTreeStruct.RootNodeClass function TnsTreeStruct.MakeChildNode(const aChild: INodeBase): Il3SimpleNode; //#UC START# *48FEE50002EB_46835B4001A4_var* //#UC END# *48FEE50002EB_46835B4001A4_var* begin //#UC START# *48FEE50002EB_46835B4001A4_impl* Result := GetNodeClass(aChild).Make(aChild); //#UC END# *48FEE50002EB_46835B4001A4_impl* end;//TnsTreeStruct.MakeChildNode function TnsTreeStruct.DoMakeDataObject(const aData: Il3SimpleNode; const aBitmap: Il3Bitmap): IDataObject; {* объект данных дерева. aData - текущий элемент списка. aBitmap (Il3Bitmap) - картинка для перетаскивания } //#UC START# *48FEE6210205_46835B4001A4_var* //#UC END# *48FEE6210205_46835B4001A4_var* begin //#UC START# *48FEE6210205_46835B4001A4_impl* Result := nil; //#UC END# *48FEE6210205_46835B4001A4_impl* end;//TnsTreeStruct.DoMakeDataObject function TnsTreeStruct.DoCanAcceptData(const aTargetNode: Il3SimpleNode; const aData: Tl3TreeData; aProcessed: PBoolean): Boolean; //#UC START# *48FEE78E01B2_46835B4001A4_var* //#UC END# *48FEE78E01B2_46835B4001A4_var* begin //#UC START# *48FEE78E01B2_46835B4001A4_impl* Result := False; //#UC END# *48FEE78E01B2_46835B4001A4_impl* end;//TnsTreeStruct.DoCanAcceptData function TnsTreeStruct.DoDropData(const aTargetNode: Il3SimpleNode; const aData: Tl3TreeData; var aProcessed: Boolean): Boolean; //#UC START# *48FEE9D303B6_46835B4001A4_var* //#UC END# *48FEE9D303B6_46835B4001A4_var* begin //#UC START# *48FEE9D303B6_46835B4001A4_impl* Result := False; //#UC END# *48FEE9D303B6_46835B4001A4_impl* end;//TnsTreeStruct.DoDropData procedure TnsTreeStruct.ExternalModified(aNode: Integer; aDelta: Integer); {* в дереве были добавлены/удалены элементы. - aNode: Узел ниже которого добавили/удалили узлы. Нумерация начинается с нуля; - aDelta: Количество элементов которое было добавлено/удалено. Если aDelta со знаком минус элементы были удалены; } //#UC START# *48FEEAB703D5_46835B4001A4_var* var l_Index : Integer; l_Intf : Il3ExternalTreeChangedRecipient; l_Obj : IUnknown; //#UC END# *48FEEAB703D5_46835B4001A4_var* begin //#UC START# *48FEEAB703D5_46835B4001A4_impl* inherited; if HasNotified then for l_Index := Pred(NotifiedObjList.Count) downto 0 do begin l_Obj := IUnknown(NotifiedObjList[l_Index]); if Supports(l_Obj, Il3ExternalTreeChangedRecipient, l_Intf) and (l_Obj = l_Intf) then try l_Intf.ExternalModified(aNode, aDelta); finally l_Intf := nil; end;//try..finally end; //#UC END# *48FEEAB703D5_46835B4001A4_impl* end;//TnsTreeStruct.ExternalModified function TnsTreeStruct.DoChangeExpand(const aNode: Il3SimpleNode; aMode: Tl3SetBitType; aForceMode: Boolean): Boolean; //#UC START# *48FEFA1E02E7_46835B4001A4_var* var l_Node : INodeBase; //#UC END# *48FEFA1E02E7_46835B4001A4_var* begin //#UC START# *48FEFA1E02E7_46835B4001A4_impl* if Supports(aNode, INodeBase, l_Node) then try Result := true; Case aMode of sbSelect : l_Node.SetFlag(FM_OPEN, true); sbDeselect : l_Node.SetFlag(FM_OPEN, false); sbInvert : if IsExpanded(aNode) then l_Node.SetFlag(FM_OPEN, false) else l_Node.SetFlag(FM_OPEN, true); end;//Case aMode finally l_Node := nil; end//try..finally else Result := false; //#UC END# *48FEFA1E02E7_46835B4001A4_impl* end;//TnsTreeStruct.DoChangeExpand function TnsTreeStruct.GetSelectCount: Integer; //#UC START# *48FEFE040094_46835B4001A4_var* //#UC END# *48FEFE040094_46835B4001A4_var* begin //#UC START# *48FEFE040094_46835B4001A4_impl* if (RootNode = nil) then Result := 0 else Result := RootNode.GetFlagCount(FM_SELECTION); //#UC END# *48FEFE040094_46835B4001A4_impl* end;//TnsTreeStruct.GetSelectCount procedure TnsTreeStruct.DoSelectionChanged(anIndex: Integer; aSelected: Boolean); //#UC START# *56CD453700A7_46835B4001A4_var* //#UC END# *56CD453700A7_46835B4001A4_var* begin //#UC START# *56CD453700A7_46835B4001A4_impl* if aSelected then f_SelectedIndexList.Add(anIndex) else f_SelectedIndexList.Remove(anIndex); //#UC END# *56CD453700A7_46835B4001A4_impl* end;//TnsTreeStruct.DoSelectionChanged function TnsTreeStruct.Get_RootNode: Il3SimpleRootNode; //#UC START# *46825CAA0125_46835B4001A4get_var* //#UC END# *46825CAA0125_46835B4001A4get_var* begin //#UC START# *46825CAA0125_46835B4001A4get_impl* Result := Root; //#UC END# *46825CAA0125_46835B4001A4get_impl* end;//TnsTreeStruct.Get_RootNode procedure TnsTreeStruct.Set_RootNode(const aValue: Il3SimpleRootNode); //#UC START# *46825CAA0125_46835B4001A4set_var* //#UC END# *46825CAA0125_46835B4001A4set_var* begin //#UC START# *46825CAA0125_46835B4001A4set_impl* Root := aValue; //#UC END# *46825CAA0125_46835B4001A4set_impl* end;//TnsTreeStruct.Set_RootNode procedure TnsTreeStruct.CursorTop; {* переставить курсор на первый видимый элемент. } //#UC START# *4772448C01D2_46835B4001A4_var* //#UC END# *4772448C01D2_46835B4001A4_var* begin //#UC START# *4772448C01D2_46835B4001A4_impl* inherited CursorTop; //#UC END# *4772448C01D2_46835B4001A4_impl* end;//TnsTreeStruct.CursorTop function TnsTreeStruct.GetIndex(const aNode: Il3SimpleNode; const aSubRootNode: Il3SimpleNode = nil): Integer; {* возвращает видимый индекс aNode относительно aSubRootNode или корня. } //#UC START# *4772449B00A1_46835B4001A4_var* Var l_AdapterNode: INodeBase; //#UC END# *4772449B00A1_46835B4001A4_var* begin //#UC START# *4772449B00A1_46835B4001A4_impl* // может быть перенести в дальнейшем проверку видимости на адаптер Result := -1; if Supports(aNode, INodeBase, l_AdapterNode) then try try if IsNodeVisible(l_AdapterNode) then begin if (aSubRootNode <> nil) then Result := (aSubRootNode as INodeBase).GetVisibleDelta(l_AdapterNode) else if (RootNode <> nil) then begin Result := RootNode.GetVisibleDelta(l_AdapterNode); if not Self.GetShowRoot then dec(Result); end;//RootNode <> nil end;//IsNodeVisible(l_AdapterNode) except on ENotFound do ; // Ничего не нашли, вернем -1 end;//try..except finally l_AdapterNode := nil; end;//try..finally //#UC END# *4772449B00A1_46835B4001A4_impl* end;//TnsTreeStruct.GetIndex function TnsTreeStruct.GetLevel(const aNode: Il3SimpleNode): Integer; {* возвращает уровень узла относительно корня. } //#UC START# *477244BA0074_46835B4001A4_var* //#UC END# *477244BA0074_46835B4001A4_var* begin //#UC START# *477244BA0074_46835B4001A4_impl* if (aNode = nil) then Result := 0 else begin Result := aNode.GetLevelFor(Root); // Сейчас не нужно, т.к. в дереве корректируется // if not ShowRoot then // Dec(Result); end; //#UC END# *477244BA0074_46835B4001A4_impl* end;//TnsTreeStruct.GetLevel procedure TnsTreeStruct.SelectAllNodes(aMode: Tl3SetBitType); {* выделяет/развыделяет все узлы. } //#UC START# *477244CE02AE_46835B4001A4_var* //#UC END# *477244CE02AE_46835B4001A4_var* begin //#UC START# *477244CE02AE_46835B4001A4_impl* DoSelectAllNodes(aMode); //#UC END# *477244CE02AE_46835B4001A4_impl* end;//TnsTreeStruct.SelectAllNodes procedure TnsTreeStruct.SelectInterval(aFirstIndex: Integer; aLastIndex: Integer; aMode: Tl3SetBitType; aCleanOther: Boolean); {* выделяет/развыделяет узлы на указанном интервале. } //#UC START# *477244DD0292_46835B4001A4_var* //#UC END# *477244DD0292_46835B4001A4_var* begin //#UC START# *477244DD0292_46835B4001A4_impl* DoSelectInterval(aFirstIndex, aLastIndex, aMode, aCleanOther); //#UC END# *477244DD0292_46835B4001A4_impl* end;//TnsTreeStruct.SelectInterval function TnsTreeStruct.ChangeExpand(const aNode: Il3SimpleNode; aMode: Tl3SetBitType; aForceMode: Boolean = False): Boolean; {* меняет развернутость узла. } //#UC START# *47724512002D_46835B4001A4_var* //#UC END# *47724512002D_46835B4001A4_var* begin //#UC START# *47724512002D_46835B4001A4_impl* Result := DoChangeExpand(aNode, aMode, aForceMode); //#UC END# *47724512002D_46835B4001A4_impl* end;//TnsTreeStruct.ChangeExpand procedure TnsTreeStruct.ExpandSubDir(const aNode: Il3SimpleNode = nil; anExpand: Boolean = True; aDeepLevel: Byte = 0); {* развернуть/свернуть узлы. } //#UC START# *4772452E002D_46835B4001A4_var* var l_SubRoot: Il3SimpleNode; {* - развернуть/свернуть узлы. } function lpIterator(const aNode : Il3SimpleNode) : Boolean; var lNode : INodeBase; begin Result := True; // Нет детей if not aNode.HasChild then Exit; // Если aDeepLevel = 0, то разворачиваем все if aDeepLevel > 0 then // Проверим не превышена ли заданная глубина if aNode.GetLevelFor(l_SubRoot) > aDeepLevel then Exit; // Свернем/Развернем if Supports(aNode, INodeBase, lNode) then try lNode.SetFlag(FM_OPEN, anExpand); finally lNode := nil; end; end; //#UC END# *4772452E002D_46835B4001A4_var* begin //#UC START# *4772452E002D_46835B4001A4_impl* Changing; try if Assigned(aNode) then l_SubRoot := aNode else l_SubRoot := Root; if (l_SubRoot = nil) then // http://mdp.garant.ru/pages/viewpage.action?pageId=95489271&focusedCommentId=95489273#comment-95489273 Exit; if (aDeepLevel = 0) and l_SubRoot.IsSame(Root) then Root.ExpandCollapseAll(anExpand) else SimpleIterateF(l3L2SNA(@lpIterator), 0, aNode); finally Changed; end; //#UC END# *4772452E002D_46835B4001A4_impl* end;//TnsTreeStruct.ExpandSubDir procedure TnsTreeStruct.SetBranchFlag(const aParentNode: Il3SimpleNode; aMode: Tl3SetBitType; aFlagsMask: Integer; anIterMode: Integer); {* зачем-то используется визуалкой в ExpandNode. } //#UC START# *477245520298_46835B4001A4_var* var l_Node: INodeBase; //#UC END# *477245520298_46835B4001A4_var* begin //#UC START# *477245520298_46835B4001A4_impl* // только для использования в vtOutliner.ExpandNode if (anIterMode = 0) and (aFlagsMask = nfSelected) then begin if Supports(aParentNode, INodeBase, l_Node) then l_Node.SetAllFlag(FM_SELECTION, aMode = sbSelect); end else Assert(False); //#UC END# *477245520298_46835B4001A4_impl* end;//TnsTreeStruct.SetBranchFlag function TnsTreeStruct.CountViewItemsInSubDir(const aNode: Il3SimpleNode): Integer; {* зачем-то используется визуалкой в ShowMoreChildrenOnScreen. } //#UC START# *4772457D032A_46835B4001A4_var* //#UC END# *4772457D032A_46835B4001A4_var* begin //#UC START# *4772457D032A_46835B4001A4_impl* Result := 0// !STUB! //#UC END# *4772457D032A_46835B4001A4_impl* end;//TnsTreeStruct.CountViewItemsInSubDir function TnsTreeStruct.IsRoot(const aNode: Il3SimpleNode): Boolean; {* является ли узел корневым для дерева. } //#UC START# *477245A20228_46835B4001A4_var* //#UC END# *477245A20228_46835B4001A4_var* begin //#UC START# *477245A20228_46835B4001A4_impl* Result := (Root <> nil) AND (aNode <> nil) AND Root.IsSame(aNode); //#UC END# *477245A20228_46835B4001A4_impl* end;//TnsTreeStruct.IsRoot function TnsTreeStruct.IsExpanded(const aNode: Il3SimpleNode): Boolean; {* раскрыт ли узел. } //#UC START# *477245B301DE_46835B4001A4_var* var l_Node : INodeBase; //#UC END# *477245B301DE_46835B4001A4_var* begin //#UC START# *477245B301DE_46835B4001A4_impl* if Supports(aNode, INodeBase, l_Node) then try Result := l_Node.HasFlag(FM_OPEN); finally l_Node := nil; end//try..finally else Result := false; //#UC END# *477245B301DE_46835B4001A4_impl* end;//TnsTreeStruct.IsExpanded function TnsTreeStruct.IsFirstVis(const aNode: Il3SimpleNode): Boolean; {* является ли узел первым видимым в ветке. } //#UC START# *477245C40171_46835B4001A4_var* //#UC END# *477245C40171_46835B4001A4_var* begin //#UC START# *477245C40171_46835B4001A4_impl* if (aNode = nil) then Result := true else Result := aNode.IsFirst; //#UC END# *477245C40171_46835B4001A4_impl* end;//TnsTreeStruct.IsFirstVis function TnsTreeStruct.IsLastVis(const aNode: Il3SimpleNode): Boolean; {* является ли узел последним видимым в ветке. } //#UC START# *477245D9031B_46835B4001A4_var* //#UC END# *477245D9031B_46835B4001A4_var* begin //#UC START# *477245D9031B_46835B4001A4_impl* if (aNode = nil) then Result := true else Result := aNode.IsLast; //#UC END# *477245D9031B_46835B4001A4_impl* end;//TnsTreeStruct.IsLastVis function TnsTreeStruct.HasVisibleChildren(const aNode: Il3SimpleNode): Boolean; {* есть ли видимые дети у aNode. } //#UC START# *477245F301AE_46835B4001A4_var* //#UC END# *477245F301AE_46835B4001A4_var* begin //#UC START# *477245F301AE_46835B4001A4_impl* if (aNode = nil) then Result := false else Result := aNode.HasChild; //#UC END# *477245F301AE_46835B4001A4_impl* end;//TnsTreeStruct.HasVisibleChildren function TnsTreeStruct.GetLines(const aNode: Il3SimpleNode): Integer; {* маска для рисования линий (надо смотреть реализацию). } //#UC START# *477246040221_46835B4001A4_var* var lCNode : Il3SimpleNode; //#UC END# *477246040221_46835B4001A4_var* begin //#UC START# *477246040221_46835B4001A4_impl* with Root do if IsSame(aNode) then Result := 0 else begin Result := 1; lCNode := aNode.Parent; if (lCNode = nil) then Result := 0 else begin while not IsSame(lCNode) do begin Result := Result shl 1; If not IsLastVis(lCNode) then l3SetBit(Result, 0); lCNode := lCNode.Parent; If lCNode = nil then Exit; end; end;//lCNode = nil end;//IsSame(aNode) //#UC END# *477246040221_46835B4001A4_impl* end;//TnsTreeStruct.GetLines function TnsTreeStruct.Wake: Boolean; {* проснись!!! Типа начали рисовать. } //#UC START# *4772461601C6_46835B4001A4_var* //#UC END# *4772461601C6_46835B4001A4_var* begin //#UC START# *4772461601C6_46835B4001A4_impl* Result := false; // - мы типа и не спали //#UC END# *4772461601C6_46835B4001A4_impl* end;//TnsTreeStruct.Wake function TnsTreeStruct.MoveNode(const aNode: Il3SimpleNode; aDirection: Tl3Direction): Boolean; {* переместить узел. } //#UC START# *477246270133_46835B4001A4_var* //#UC END# *477246270133_46835B4001A4_var* begin //#UC START# *477246270133_46835B4001A4_impl* Result := false; // !STUB! //#UC END# *477246270133_46835B4001A4_impl* end;//TnsTreeStruct.MoveNode function TnsTreeStruct.SearchNameBegin(const aFirstNode: Il3SimpleNode; aSrchStr: PAnsiChar; aIterMode: Integer): Il3SimpleNode; {* зачем-то используется визуалкой в CharToItem. } //#UC START# *477246440037_46835B4001A4_var* //#UC END# *477246440037_46835B4001A4_var* begin //#UC START# *477246440037_46835B4001A4_impl* Result := nil; // !STUB! //#UC END# *477246440037_46835B4001A4_impl* end;//TnsTreeStruct.SearchNameBegin function TnsTreeStruct.SearchNameOccur(const aFirstNode: Il3SimpleNode; aSrchStr: PAnsiChar; aIterMode: Integer): Il3SimpleNode; {* зачем-то используется визуалкой в SearchOccurStr, который сейчас никем не используется. } //#UC START# *4772465F0276_46835B4001A4_var* //#UC END# *4772465F0276_46835B4001A4_var* begin //#UC START# *4772465F0276_46835B4001A4_impl* Result := nil; // !STUB! //#UC END# *4772465F0276_46835B4001A4_impl* end;//TnsTreeStruct.SearchNameOccur function TnsTreeStruct.MakeNodeVisible(const aNode: Il3SimpleNode): Integer; {* зачем-то используется визуалкой в CharToItem, видимо для перемещения курсора на узел. } //#UC START# *477246860169_46835B4001A4_var* Var l_Node : INodeBase; //#UC END# *477246860169_46835B4001A4_var* begin //#UC START# *477246860169_46835B4001A4_impl* Result := -1; if (RootNode <> nil) and Supports(aNode, INodeBase, l_Node) then try l_Node.MakeVisible; Result := GetVisibleIndex(l_Node); finally l_Node := nil; end; //#UC END# *477246860169_46835B4001A4_impl* end;//TnsTreeStruct.MakeNodeVisible function TnsTreeStruct.GetPrev(const aNode: Il3SimpleNode): Il3SimpleNode; {* предыдущий узел. Зачем-то используется в CharToItem. } //#UC START# *477246A40174_46835B4001A4_var* //#UC END# *477246A40174_46835B4001A4_var* begin //#UC START# *477246A40174_46835B4001A4_impl* Result := nil; // !STUB! //#UC END# *477246A40174_46835B4001A4_impl* end;//TnsTreeStruct.GetPrev function TnsTreeStruct.SimpleIterateF(Action: Tl3SimpleNodeAction; IterMode: Integer = 0; const aSubRootNode: Il3SimpleNode = nil): Il3SimpleNode; {* перебрать все узлы и освободить заглушку для Action. IterMode: imCheckResult, imParentNeed } //#UC START# *477246C70141_46835B4001A4_var* //#UC END# *477246C70141_46835B4001A4_var* begin //#UC START# *477246C70141_46835B4001A4_impl* Result := FlagIterateF(Action, 0, IterMode, aSubRootNode); //#UC END# *477246C70141_46835B4001A4_impl* end;//TnsTreeStruct.SimpleIterateF function TnsTreeStruct.IsChanging: Boolean; {* дерево находится в фазе обновления. } //#UC START# *477246E802B1_46835B4001A4_var* //#UC END# *477246E802B1_46835B4001A4_var* begin //#UC START# *477246E802B1_46835B4001A4_impl* Result := inherited IsChanging; //#UC END# *477246E802B1_46835B4001A4_impl* end;//TnsTreeStruct.IsChanging procedure TnsTreeStruct.Changing; //#UC START# *477246F7039B_46835B4001A4_var* //#UC END# *477246F7039B_46835B4001A4_var* begin //#UC START# *477246F7039B_46835B4001A4_impl* inherited Changing; //#UC END# *477246F7039B_46835B4001A4_impl* end;//TnsTreeStruct.Changing procedure TnsTreeStruct.Changed; //#UC START# *4772470100BC_46835B4001A4_var* //#UC END# *4772470100BC_46835B4001A4_var* begin //#UC START# *4772470100BC_46835B4001A4_impl* inherited Changed; //#UC END# *4772470100BC_46835B4001A4_impl* end;//TnsTreeStruct.Changed function TnsTreeStruct.Get_ShowRoot: Boolean; //#UC START# *477248FE005A_46835B4001A4get_var* //#UC END# *477248FE005A_46835B4001A4get_var* begin //#UC START# *477248FE005A_46835B4001A4get_impl* Result := GetShowRoot; //#UC END# *477248FE005A_46835B4001A4get_impl* end;//TnsTreeStruct.Get_ShowRoot procedure TnsTreeStruct.Set_ShowRoot(aValue: Boolean); //#UC START# *477248FE005A_46835B4001A4set_var* //#UC END# *477248FE005A_46835B4001A4set_var* begin //#UC START# *477248FE005A_46835B4001A4set_impl* f_ShowRoot := aValue; CursorTop; //#UC END# *477248FE005A_46835B4001A4set_impl* end;//TnsTreeStruct.Set_ShowRoot function TnsTreeStruct.Get_CountView: Integer; //#UC START# *4772490E02F7_46835B4001A4get_var* //#UC END# *4772490E02F7_46835B4001A4get_var* begin //#UC START# *4772490E02F7_46835B4001A4get_impl* Result := CountView; //#UC END# *4772490E02F7_46835B4001A4get_impl* end;//TnsTreeStruct.Get_CountView function TnsTreeStruct.Get_SelectCount: Integer; //#UC START# *4772491C01C5_46835B4001A4get_var* //#UC END# *4772491C01C5_46835B4001A4get_var* begin //#UC START# *4772491C01C5_46835B4001A4get_impl* Result := GetSelectCount; //#UC END# *4772491C01C5_46835B4001A4get_impl* end;//TnsTreeStruct.Get_SelectCount function TnsTreeStruct.Get_Flags(anIndex: Integer): Integer; //#UC START# *4772495902EE_46835B4001A4get_var* var l_Node : Il3SimpleNode; //#UC END# *4772495902EE_46835B4001A4get_var* begin //#UC START# *4772495902EE_46835B4001A4get_impl* l_Node := Get_Nodes(anIndex); if (l_Node = nil) then Result := 0 else Result := l_Node.Flags; //#UC END# *4772495902EE_46835B4001A4get_impl* end;//TnsTreeStruct.Get_Flags function TnsTreeStruct.Get_Select(anIndex: Integer): Boolean; //#UC START# *477249AB0057_46835B4001A4get_var* var l_Node : INodeBase; //#UC END# *477249AB0057_46835B4001A4get_var* begin //#UC START# *477249AB0057_46835B4001A4get_impl* l_Node := GetINode(anIndex); if (l_Node = nil) then Result := false else Result := l_Node.HasFlag(FM_SELECTION); //#UC END# *477249AB0057_46835B4001A4get_impl* end;//TnsTreeStruct.Get_Select procedure TnsTreeStruct.Set_Select(anIndex: Integer; aValue: Boolean); //#UC START# *477249AB0057_46835B4001A4set_var* var l_Node : INodeBase; l_CurSelectCount: Integer; //#UC END# *477249AB0057_46835B4001A4set_var* begin //#UC START# *477249AB0057_46835B4001A4set_impl* l_Node := GetINode(anIndex); if (l_Node <> nil) then begin l_Node.SetFlag(FM_SELECTION, aValue); if (RootNode <> nil) then begin DoSelectionChanged(anIndex, aValue); l_CurSelectCount := RootNode.GetFlagCount(FM_SELECTION); if aValue then SelectCountChanged(l_CurSelectCount - 1, l_CurSelectCount) else SelectCountChanged(l_CurSelectCount + 1, l_CurSelectCount); end;//RootNode <> nil end;//l_Node <> nil //#UC END# *477249AB0057_46835B4001A4set_impl* end;//TnsTreeStruct.Set_Select function TnsTreeStruct.Get_Nodes(anIndex: Integer): Il3SimpleNode; //#UC START# *477249EB02D9_46835B4001A4get_var* //#UC END# *477249EB02D9_46835B4001A4get_var* begin //#UC START# *477249EB02D9_46835B4001A4get_impl* Result := MakeChildNode(GetINode(anIndex)); //#UC END# *477249EB02D9_46835B4001A4get_impl* end;//TnsTreeStruct.Get_Nodes function TnsTreeStruct.FlagIterateF(Action: Tl3SimpleNodeAction; FlagMask: Word = 0; IterMode: Integer = 0; const aSubRootNode: Il3SimpleNode = nil; aCheckResult: Boolean = False): Il3SimpleNode; {* перебрать все узлы, удовлетворяющие FlagMask, и освободить заглушку для Action. IterMode: imCheckResult, imParentNeed } //#UC START# *47724AB70207_46835B4001A4_var* var l_RootNeeded, l_CheckResult, l_OneLevel, l_ActionResult : Boolean; l_RootNode, l_ChildNode : INodeBase; l_NodeIterator : INodeIterator; l_Node : Il3SimpleNode; l_Root : Il3SimpleNode; //#UC END# *47724AB70207_46835B4001A4_var* begin //#UC START# *47724AB70207_46835B4001A4_impl* Result := nil; try if (aSubRootNode = nil) then l_Root := Root else l_Root := aSubRootNode; if Supports(l_Root , INodeBase, l_RootNode) then begin l_CheckResult := l3TestMask(IterMode, imCheckResult); l_RootNeeded := l3TestMask(IterMode, imParentNeed); l_OneLevel := l3TestMask(IterMode, imOneLevel); l_RootNode.IterateNodes(FlagMask, l_NodeIterator); if l_RootNeeded then begin l_Node := MakeChildNode(l_RootNode); l_ActionResult := Action(l_Node); if l_ActionResult then Result := l_Node; end//l_RootNeeded else l_ActionResult := false; while not (l_CheckResult and l_ActionResult) do begin l_NodeIterator.GetNext(l_ChildNode); if (l_ChildNode <> nil) then begin l_Node := MakeChildNode(l_ChildNode); if l_OneLevel and (l_Node.GetLevelFor(l_Root) <> 1) then Continue; l_ActionResult := Action(l_Node); if l_ActionResult then begin Result := l_Node; if aCheckResult then Break; end; end//l_ChildNode <> nil else Break; end;//while not (l_CheckResult and l_ActionResult) end;//l_RootNode <> nil finally l3FreeFA(Tl3FreeAction(Action)); end;//try..finally //#UC END# *47724AB70207_46835B4001A4_impl* end;//TnsTreeStruct.FlagIterateF function TnsTreeStruct.MakeDataObject(const aNode: Il3SimpleNode; const aBitmap: IUnknown): IDataObject; {* сделать объект данных дерева, используется при перемещении элементов дерева в другие компоненты } //#UC START# *47A86EA80292_46835B4001A4_var* //#UC END# *47A86EA80292_46835B4001A4_var* begin //#UC START# *47A86EA80292_46835B4001A4_impl* Result := DoMakeDataObject(aNode, aBitmap As Il3Bitmap); //#UC END# *47A86EA80292_46835B4001A4_impl* end;//TnsTreeStruct.MakeDataObject function TnsTreeStruct.CanAcceptData(const aTargetNode: Il3SimpleNode; const aData: Tl3TreeData): Boolean; //#UC START# *47BAD3080349_46835B4001A4_var* var l_Processed: Boolean; //#UC END# *47BAD3080349_46835B4001A4_var* begin //#UC START# *47BAD3080349_46835B4001A4_impl* l_Processed := False; Result := DoCanAcceptData(aTargetNode, aData, @l_Processed); if not l_Processed and (aTargetNode <> nil) then Result := aTargetNode.CanAcceptData(aData); //#UC END# *47BAD3080349_46835B4001A4_impl* end;//TnsTreeStruct.CanAcceptData function TnsTreeStruct.DropData(const aTargetNode: Il3SimpleNode; const aData: Tl3TreeData): Boolean; //#UC START# *47BAD32501E2_46835B4001A4_var* procedure lp_Notify; var l_Index : Integer; l_Item : IUnknown; l_Listener : InsDropListener; begin for l_Index := 0 to Pred(NotifiedObjList.Count) do begin l_Item := IUnknown(NotifiedObjList.Items[l_Index]); if Supports(l_Item, InsDropListener, l_Listener) and (l_Item = l_Listener) then l_Listener.DataDropped; end;//for l_Index := 0 to Pred(NotifiedObjList.Count) do end;//lp_Notify var l_Processed: Boolean; //#UC END# *47BAD32501E2_46835B4001A4_var* begin //#UC START# *47BAD32501E2_46835B4001A4_impl* l_Processed := False; // Предложим данные дереву: Result := DoDropData(aTargetNode, aData, l_Processed); // Предложим данные узлу: if not l_Processed and (aTargetNode <> nil) then Result := aTargetNode.DropData(aData); // Уведомим о приёме данных: if Result then lp_Notify; //#UC END# *47BAD32501E2_46835B4001A4_impl* end;//TnsTreeStruct.DropData function TnsTreeStruct.MakeState: InsTreeStructState; //#UC START# *56A873120383_46835B4001A4_var* //#UC END# *56A873120383_46835B4001A4_var* begin //#UC START# *56A873120383_46835B4001A4_impl* Result := TnsTreeStructState.Make(f_SelectedIndexList); //#UC END# *56A873120383_46835B4001A4_impl* end;//TnsTreeStruct.MakeState procedure TnsTreeStruct.AssignState(const aState: InsTreeStructState); //#UC START# *56A89F6B03A5_46835B4001A4_var* var l_Index: Integer; l_SelectedNodeIndex: Integer; //#UC END# *56A89F6B03A5_46835B4001A4_var* begin //#UC START# *56A89F6B03A5_46835B4001A4_impl* Assert(aState <> nil); SelectAllNodes(sbDeselect); for l_Index := 0 to Pred(aState.GetSelectedNodeCount) do begin l_SelectedNodeIndex := aState.GetSelectedNodeVisibleIndex(l_Index); Set_Select(l_SelectedNodeIndex, True); end; //#UC END# *56A89F6B03A5_46835B4001A4_impl* end;//TnsTreeStruct.AssignState procedure TnsTreeStruct.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_46835B4001A4_var* //#UC END# *479731C50290_46835B4001A4_var* begin //#UC START# *479731C50290_46835B4001A4_impl* FreeAndNil(f_SelectedIndexList); Root := nil; inherited; //#UC END# *479731C50290_46835B4001A4_impl* end;//TnsTreeStruct.Cleanup procedure TnsTreeStruct.FireChanged; //#UC START# *48FC9D300237_46835B4001A4_var* //#UC END# *48FC9D300237_46835B4001A4_var* begin //#UC START# *48FC9D300237_46835B4001A4_impl* try CursorTop; inherited; except on ECannotFindData do ; // - гасим какое-то исключение с адаптера // - сюда попадаем например когда толковый словарь пропал end;//try..except //#UC END# *48FC9D300237_46835B4001A4_impl* end;//TnsTreeStruct.FireChanged procedure TnsTreeStruct.ChangeChildrenCountPrim(aNodeIndex: TVisibleIndex; aDelta: Integer; const aIndexPath: INodeIndexPath; aChildIndex: TIndexInParent); //#UC START# *48FDA11E02D1_46835B4001A4_var* function lp_ConvertChildIndexToVisibleIndex(const aParent: INodeBase; aChildIndex: TIndexInParent; aResult: Integer): Integer; var l_ChildNode: INodeBase; l_FirstChild: INodeBase; l_IDX: Integer; begin if aChildIndex = 0 then begin Result := aResult; Exit; end; if aParent = nil then begin Result := aChildIndex; Exit; end; aParent.GetFirstChild(l_FirstChild); l_ChildNode := l_FirstChild; try try for l_IDX := 1 to aChildIndex - 1 do begin l_FirstChild.GetNext(l_ChildNode); l_FirstChild := l_ChildNode; end; if Assigned(l_ChildNode) then Result := RootNode.GetVisibleDelta(l_ChildNode) else Result := aResult + aChildIndex; finally l_ChildNode := nil; end; finally l_FirstChild := nil; end; end; function lp_MakeNodeIndex: Integer; var l_Node : INodeBase; l_ParentIndex : Integer; begin Result := -1; if (aIndexPath.Count > 1) then begin try RootNode.GetNodeByPath(aIndexPath, l_Node); try l_ParentIndex := RootNode.GetVisibleDelta(l_Node); Result := l_ParentIndex; if aChildIndex = IIP_BEFORE_LEFT_CHILD then Dec(Result) else Result := lp_ConvertChildIndexToVisibleIndex(l_Node, aChildIndex, Result); finally l_Node := nil; end;{try..finally} except on ENotFound do begin end; end;{try..except} end//if (aIndexPath.GetCount > 1) then else if aChildIndex = IIP_BEFORE_LEFT_CHILD then Result := -1 else Result := lp_ConvertChildIndexToVisibleIndex(RootNode, aChildIndex, Result); if (Result <> -1) and not GetShowRoot then Dec(Result); end;//lp_MakeNodeIndex //#UC END# *48FDA11E02D1_46835B4001A4_var* begin //#UC START# *48FDA11E02D1_46835B4001A4_impl* inherited; if (aNodeIndex = -1) then begin if Assigned(aIndexPath) then ExternalModified(lp_MakeNodeIndex, aDelta); CallNotify(ntCountChange, 0); end;//if (aNodeIndex = -1) then //#UC END# *48FDA11E02D1_46835B4001A4_impl* end;//TnsTreeStruct.ChangeChildrenCountPrim function TnsTreeStruct.GetShowRoot: Boolean; //#UC START# *48FDA1A60056_46835B4001A4_var* //#UC END# *48FDA1A60056_46835B4001A4_var* begin //#UC START# *48FDA1A60056_46835B4001A4_impl* Result := f_ShowRoot; //#UC END# *48FDA1A60056_46835B4001A4_impl* end;//TnsTreeStruct.GetShowRoot procedure TnsTreeStruct.ChangingPrim; //#UC START# *48FDA1C3002E_46835B4001A4_var* //#UC END# *48FDA1C3002E_46835B4001A4_var* begin //#UC START# *48FDA1C3002E_46835B4001A4_impl* inherited; if TvcmDispatcher.Exists then TvcmDispatcher.Instance.As_IvcmDispatcher.LockActionUpdate; //#UC END# *48FDA1C3002E_46835B4001A4_impl* end;//TnsTreeStruct.ChangingPrim procedure TnsTreeStruct.ChangedPrim; //#UC START# *48FDA1D0006F_46835B4001A4_var* //#UC END# *48FDA1D0006F_46835B4001A4_var* begin //#UC START# *48FDA1D0006F_46835B4001A4_impl* inherited; if TvcmDispatcher.Exists then TvcmDispatcher.Instance.As_IvcmDispatcher.UnLockActionUpdate; //#UC END# *48FDA1D0006F_46835B4001A4_impl* end;//TnsTreeStruct.ChangedPrim procedure TnsTreeStruct.ExternalInvalidate; //#UC START# *48FDA1E701DF_46835B4001A4_var* var l_Index: Integer; l_Intf : Il3ExternalTreeChangedRecipient; //#UC END# *48FDA1E701DF_46835B4001A4_var* begin //#UC START# *48FDA1E701DF_46835B4001A4_impl* inherited; if HasNotified then for l_Index := Pred(NotifiedObjList.Count) downto 0 do if Supports(IUnknown(NotifiedObjList[l_Index]), Il3ExternalTreeChangedRecipient, l_Intf) then try l_Intf.ExternalInvalidate; finally l_Intf := nil; end;//try..finally //#UC END# *48FDA1E701DF_46835B4001A4_impl* end;//TnsTreeStruct.ExternalInvalidate procedure TnsTreeStruct.ExternalVisibleCountChanged(aNewCount: Integer; aNodeIndex: Integer; aDelta: Integer); {* нотификация визуальному дереву о смене количества видимых элементов } //#UC START# *48FDA30E0390_46835B4001A4_var* var l_Index : Integer; l_Intf : Il3ExternalTreeChangedRecipient; l_Obj : IUnknown; //#UC END# *48FDA30E0390_46835B4001A4_var* begin //#UC START# *48FDA30E0390_46835B4001A4_impl* inherited; if HasNotified then for l_Index := Pred(NotifiedObjList.Count) downto 0 do begin l_Obj := IUnknown(NotifiedObjList[l_Index]); if Supports(l_Obj, Il3ExternalTreeChangedRecipient, l_Intf) and (l_Obj = l_Intf) then try l_Intf.ExternalVisibleCountChanged(aNewCount, aNodeIndex, aDelta); finally l_Intf := nil; end;//try..finally end; //#UC END# *48FDA30E0390_46835B4001A4_impl* end;//TnsTreeStruct.ExternalVisibleCountChanged end.
unit CustomerQuestionAbout7StopsUnit; interface uses SysUtils, Classes, OutputUnit, AddressUnit; const //your api key Default_ApiKey = '11111111111111111111111111111111'; type TCustomerQuestionAbout7Stops = class private FOutput: IOutput; FApiKey: String; function MakeAddress(Name: String; Latitude, Longitude: double): TAddress; procedure PrintIfHasError(ErrorString: String); public constructor Create; destructor Destroy; override; procedure Execute; end; implementation uses OptimizationParametersUnit, IRoute4MeManagerUnit, Route4MeManagerUnit, RouteParametersUnit, DataObjectUnit, ConnectionUnit, EnumsUnit; constructor TCustomerQuestionAbout7Stops.Create; const ApikeyFilename = '..\..\..\..\apikey.txt'; var st: TStringList; begin FOutput := TOutputConsole.Create; if FileExists(ApikeyFilename) then begin st := TStringList.Create; try st.LoadFromFile(ApikeyFilename); FApiKey := st[0]; finally FreeAndNil(st); end; end else FApiKey := Default_ApiKey; end; destructor TCustomerQuestionAbout7Stops.Destroy; begin FOutput := nil; inherited; end; procedure TCustomerQuestionAbout7Stops.Execute; var Route4MeManager: IRoute4MeManager; RouteParameters: TRouteParameters; Address: TAddress; ErrorString: String; Parameters: TOptimizationParameters; DataObject: TDataObject; OptimizationProblemDetails: TDataObject; Route: TDataObjectRoute; DetailedRoute: TDataObjectRoute; GetRouteDirections: Boolean; GetRoutePathPoints: Boolean; begin try Route4MeManager := TRoute4MeManager.Create(TConnection.Create(FApiKey)); // Prepared input data with parameters RouteParameters := TRouteParameters.Create; RouteParameters.AlgorithmType := TAlgorithmType.TSP; RouteParameters.StoreRoute := True; RouteParameters.RouteName := 'Single Driver Route (Delphi, trucking)'; RouteParameters.Optimize := TOptimize.Distance; RouteParameters.DistanceUnit := TDistanceUnit.MI; RouteParameters.DeviceType := TDeviceType.Web; RouteParameters.TravelMode := TTravelMode.Trucking; Parameters := TOptimizationParameters.Create; try Parameters.Parameters := RouteParameters; Address := MakeAddress('151 Arbor Way Milledgeville, GA 31061, USA', 33.132701, -83.244743); Address.SequenceNo := 1; Parameters.AddAddress(Address); Parameters.AddAddress(MakeAddress('119 Bill Johnson Road Northeast Milledgeville, GA 31061, USA', 33.141095, -83.238278)); Parameters.AddAddress(MakeAddress('138 Bill Johnson Road Northeast Milledgeville, GA 31061, USA', 33.143078, -83.239336)); Parameters.AddAddress(MakeAddress('133 Bill Johnson Road Northeast Milledgeville, GA 31061, USA', 33.142300, -83.239066)); Parameters.AddAddress(MakeAddress('139 Bill Johnson Road Northeast Milledgeville, GA 31061, USA', 33.142745, -83.237464)); Parameters.AddAddress(MakeAddress('117 Bill Johnson Road Northeast Milledgeville, GA 31061, USA', 33.141329, -83.238278)); Parameters.AddAddress(MakeAddress('151 Bill Johnson Road Northeast Milledgeville, GA 31061, USA', 33.144197, -83.237563)); // Run optimization DataObject := Route4MeManager.Optimization.Run(Parameters, ErrorString); PrintIfHasError(ErrorString); try // Get more details OptimizationProblemDetails := Route4MeManager.Optimization.Get( DataObject.OptimizationProblemId, ErrorString); PrintIfHasError(ErrorString); try for Route in OptimizationProblemDetails.Routes do begin GetRouteDirections := False; GetRoutePathPoints := True; DetailedRoute := Route4MeManager.Route.Get(Route.RouteId, GetRouteDirections, GetRoutePathPoints, ErrorString); try PrintIfHasError(ErrorString); finally FreeAndNil(DetailedRoute); end; end; finally FreeAndNil(OptimizationProblemDetails); end; finally FreeAndNil(DataObject); end; finally FreeAndNil(Parameters); end; finally WriteLn(''); WriteLn('Press any key'); ReadLn; end; end; function TCustomerQuestionAbout7Stops.MakeAddress(Name: String; Latitude, Longitude: double): TAddress; begin Result := TAddress.Create; Result.AddressString := Name; Result.Latitude := Latitude; Result.Longitude := Longitude; Result.IsDepot := False; end; procedure TCustomerQuestionAbout7Stops.PrintIfHasError(ErrorString: String); begin if (ErrorString <> EmptyStr) then begin FOutput.Writeln(ErrorString); raise Exception.Create('We has error message'); end; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpSecP384R1FieldElement; {$I ..\..\..\..\Include\CryptoLib.inc} interface uses ClpNat, ClpMod, ClpSecP384R1Curve, ClpECFieldElement, ClpIECFieldElement, ClpSecP384R1Field, ClpISecP384R1FieldElement, ClpBigInteger, ClpArrayUtils, ClpCryptoLibTypes; resourcestring SInvalidValueForSecP384R1FieldElement = 'Value Invalid for SecP384R1FieldElement "%s"'; type TSecP384R1FieldElement = class(TAbstractFpFieldElement, ISecP384R1FieldElement) strict private function Equals(const other: ISecP384R1FieldElement): Boolean; reintroduce; overload; class function GetQ: TBigInteger; static; inline; strict protected var Fx: TCryptoLibUInt32Array; function GetFieldName: string; override; function GetFieldSize: Int32; override; function GetIsOne: Boolean; override; function GetIsZero: Boolean; override; function GetX: TCryptoLibUInt32Array; inline; property X: TCryptoLibUInt32Array read GetX; public constructor Create(); overload; constructor Create(const X: TBigInteger); overload; constructor Create(const X: TCryptoLibUInt32Array); overload; function TestBitZero: Boolean; override; function ToBigInteger(): TBigInteger; override; function Add(const b: IECFieldElement): IECFieldElement; override; function AddOne(): IECFieldElement; override; function Subtract(const b: IECFieldElement): IECFieldElement; override; function Multiply(const b: IECFieldElement): IECFieldElement; override; function Divide(const b: IECFieldElement): IECFieldElement; override; function Negate(): IECFieldElement; override; function Square(): IECFieldElement; override; function Invert(): IECFieldElement; override; /// <summary> /// return a sqrt root - the routine verifies that the calculation /// returns the right value - if <br />none exists it returns null. /// </summary> function Sqrt(): IECFieldElement; override; function Equals(const other: IECFieldElement): Boolean; overload; override; function GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI}override; property IsZero: Boolean read GetIsZero; property IsOne: Boolean read GetIsOne; property FieldName: string read GetFieldName; property FieldSize: Int32 read GetFieldSize; class property Q: TBigInteger read GetQ; end; implementation { TSecP384R1FieldElement } class function TSecP384R1FieldElement.GetQ: TBigInteger; begin result := TSecP384R1Curve.SecP384R1Curve_Q; end; function TSecP384R1FieldElement.GetX: TCryptoLibUInt32Array; begin result := Fx; end; constructor TSecP384R1FieldElement.Create; begin Inherited Create(); Fx := TNat.Create(12); end; constructor TSecP384R1FieldElement.Create(const X: TBigInteger); begin if ((not(X.IsInitialized)) or (X.SignValue < 0) or (X.CompareTo(Q) >= 0)) then begin raise EArgumentCryptoLibException.CreateResFmt (@SInvalidValueForSecP384R1FieldElement, ['x']); end; Inherited Create(); Fx := TSecP384R1Field.FromBigInteger(X); end; constructor TSecP384R1FieldElement.Create(const X: TCryptoLibUInt32Array); begin Inherited Create(); Fx := X; end; function TSecP384R1FieldElement.GetFieldName: string; begin result := 'SecP384R1Field'; end; function TSecP384R1FieldElement.GetFieldSize: Int32; begin result := Q.BitLength; end; function TSecP384R1FieldElement.GetHashCode: {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI} begin result := Q.GetHashCode() xor TArrayUtils.GetArrayHashCode(Fx, 0, 12); end; function TSecP384R1FieldElement.GetIsOne: Boolean; begin result := TNat.IsOne(12, Fx); end; function TSecP384R1FieldElement.GetIsZero: Boolean; begin result := TNat.IsZero(12, Fx); end; function TSecP384R1FieldElement.Sqrt: IECFieldElement; var x1, t1, t2, t3, t4, r: TCryptoLibUInt32Array; begin // Raise this element to the exponent 2^382 - 2^126 - 2^94 + 2^30 x1 := Fx; if ((TNat.IsZero(12, x1)) or (TNat.IsOne(12, x1))) then begin result := Self as IECFieldElement; Exit; end; t1 := TNat.Create(12); t2 := TNat.Create(12); t3 := TNat.Create(12); t4 := TNat.Create(12); TSecP384R1Field.Square(x1, t1); TSecP384R1Field.Multiply(t1, x1, t1); TSecP384R1Field.SquareN(t1, 2, t2); TSecP384R1Field.Multiply(t2, t1, t2); TSecP384R1Field.Square(t2, t2); TSecP384R1Field.Multiply(t2, x1, t2); TSecP384R1Field.SquareN(t2, 5, t3); TSecP384R1Field.Multiply(t3, t2, t3); TSecP384R1Field.SquareN(t3, 5, t4); TSecP384R1Field.Multiply(t4, t2, t4); TSecP384R1Field.SquareN(t4, 15, t2); TSecP384R1Field.Multiply(t2, t4, t2); TSecP384R1Field.SquareN(t2, 2, t3); TSecP384R1Field.Multiply(t1, t3, t1); TSecP384R1Field.SquareN(t3, 28, t3); TSecP384R1Field.Multiply(t2, t3, t2); TSecP384R1Field.SquareN(t2, 60, t3); TSecP384R1Field.Multiply(t3, t2, t3); r := t2; TSecP384R1Field.SquareN(t3, 120, r); TSecP384R1Field.Multiply(r, t3, r); TSecP384R1Field.SquareN(r, 15, r); TSecP384R1Field.Multiply(r, t4, r); TSecP384R1Field.SquareN(r, 33, r); TSecP384R1Field.Multiply(r, t1, r); TSecP384R1Field.SquareN(r, 64, r); TSecP384R1Field.Multiply(r, x1, r); TSecP384R1Field.SquareN(r, 30, t1); TSecP384R1Field.Square(t1, t2); if TNat.Eq(12, x1, t2) then begin result := TSecP384R1FieldElement.Create(t1); end else begin result := Nil; end; end; function TSecP384R1FieldElement.TestBitZero: Boolean; begin result := TNat.GetBit(Fx, 0) = 1; end; function TSecP384R1FieldElement.ToBigInteger: TBigInteger; begin result := TNat.ToBigInteger(12, Fx); end; function TSecP384R1FieldElement.Add(const b: IECFieldElement): IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(12); TSecP384R1Field.Add(Fx, (b as ISecP384R1FieldElement).X, z); result := TSecP384R1FieldElement.Create(z); end; function TSecP384R1FieldElement.AddOne: IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(12); TSecP384R1Field.AddOne(Fx, z); result := TSecP384R1FieldElement.Create(z); end; function TSecP384R1FieldElement.Subtract(const b: IECFieldElement) : IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(12); TSecP384R1Field.Subtract(Fx, (b as ISecP384R1FieldElement).X, z); result := TSecP384R1FieldElement.Create(z); end; function TSecP384R1FieldElement.Multiply(const b: IECFieldElement) : IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(12); TSecP384R1Field.Multiply(Fx, (b as ISecP384R1FieldElement).X, z); result := TSecP384R1FieldElement.Create(z); end; function TSecP384R1FieldElement.Divide(const b: IECFieldElement) : IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(12); TMod.Invert(TSecP384R1Field.P, (b as ISecP384R1FieldElement).X, z); TSecP384R1Field.Multiply(z, Fx, z); result := TSecP384R1FieldElement.Create(z); end; function TSecP384R1FieldElement.Negate: IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(12); TSecP384R1Field.Negate(Fx, z); result := TSecP384R1FieldElement.Create(z); end; function TSecP384R1FieldElement.Square: IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(12); TSecP384R1Field.Square(Fx, z); result := TSecP384R1FieldElement.Create(z); end; function TSecP384R1FieldElement.Invert: IECFieldElement; var z: TCryptoLibUInt32Array; begin z := TNat.Create(12); TMod.Invert(TSecP384R1Field.P, Fx, z); result := TSecP384R1FieldElement.Create(z); end; function TSecP384R1FieldElement.Equals(const other : ISecP384R1FieldElement): Boolean; begin if ((Self as ISecP384R1FieldElement) = other) then begin result := true; Exit; end; if (other = Nil) then begin result := false; Exit; end; result := TNat.Eq(12, Fx, other.X); end; function TSecP384R1FieldElement.Equals(const other: IECFieldElement): Boolean; begin result := Equals(other as ISecP384R1FieldElement); end; end.
{ Subroutine SST_RWCHECK (RW_USED,RW_ALLOWED,STAT) * * Check for proper read/write access. RW_USED indicates the type of * access attempted, and RW_ALLOWED indicates the legal access types. * STAT is returned with no error if the access is legal. } module sst_RWCHECK; define sst_rwcheck; %include 'sst2.ins.pas'; procedure sst_rwcheck ( {check for proper read/write access used} in rw_used: sst_rwflag_t; {read/write access actually used} in rw_allowed: sst_rwflag_t; {read/write access allowed} out stat: sys_err_t); {no error if legal access} begin sys_error_none (stat); {init to access is legal} if rw_used <= rw_allowed then return; {access is completely legal ?} if (sst_rwflag_write_k in rw_used) and (not (sst_rwflag_write_k in rw_allowed)) then begin sys_stat_set (sst_subsys_k, sst_stat_write_bad_k, stat); return; end; if (sst_rwflag_read_k in rw_used) and (not (sst_rwflag_read_k in rw_allowed)) then begin sys_stat_set (sst_subsys_k, sst_stat_read_bad_k, stat); return; end; writeln ('Internal error in subroutine SST_RWCHECK.'); sys_bomb; end;
unit TestMarshalOptimizationParametersUnit; interface uses TestFramework, SysUtils, TestBaseJsonMarshalUnit; type TTestMarshalOptimizationParameters = class(TTestBaseJsonMarshal) published procedure MultipleDepotMultipleDriver(); procedure MultipleDepotMultipleDriverTimeWindow(); procedure MultipleDepotMultipleDriverWith24StopsTimeWindow(); procedure SingleDepotMultipleDriverNoTimeWindow(); procedure SingleDriverMultipleTimeWindows(); procedure SingleDriverRoundTrip(); procedure SingleDriverRoute10Stops(); end; implementation { TTestOptimizationParametersToJson } uses IOptimizationParametersProviderUnit, SingleDriverRoute10StopsTestDataProviderUnit, SingleDriverRoundTripTestDataProviderUnit, SingleDriverMultipleTimeWindowsTestDataProviderUnit, SingleDepotMultipleDriverNoTimeWindowTestDataProviderUnit, MultipleDepotMultipleDriverTestDataProviderUnit, MultipleDepotMultipleDriverTimeWindowTestDataProviderUnit, MultipleDepotMultipleDriverWith24StopsTimeWindowTestDataProviderUnit, OptimizationParametersUnit; procedure TTestMarshalOptimizationParameters.MultipleDepotMultipleDriver(); var DataProvider: IOptimizationParametersProvider; OptimizationParameters: TOptimizationParameters; begin DataProvider := TMultipleDepotMultipleDriverTestDataProvider.Create; OptimizationParameters := DataProvider.OptimizationParameters; try CheckEquals( EtalonFilename('OptimizationParametersToJson\MultipleDepotMultipleDriver'), OptimizationParameters.ToJsonString); finally FreeAndNil(OptimizationParameters); end; end; procedure TTestMarshalOptimizationParameters.MultipleDepotMultipleDriverTimeWindow; var DataProvider: IOptimizationParametersProvider; OptimizationParameters: TOptimizationParameters; begin DataProvider := TMultipleDepotMultipleDriverTimeWindowTestDataProvider.Create; OptimizationParameters := DataProvider.OptimizationParameters; try CheckEquals( EtalonFilename('OptimizationParametersToJson\MultipleDepotMultipleDriverTimeWindow'), OptimizationParameters.ToJsonString); finally FreeAndNil(OptimizationParameters); end; end; procedure TTestMarshalOptimizationParameters.MultipleDepotMultipleDriverWith24StopsTimeWindow; var DataProvider: IOptimizationParametersProvider; OptimizationParameters: TOptimizationParameters; begin DataProvider := TMultipleDepotMultipleDriverWith24StopsTimeWindowTestDataProvider.Create; OptimizationParameters := DataProvider.OptimizationParameters; try CheckEquals( EtalonFilename('OptimizationParametersToJson\MultipleDepotMultipleDriverWith24StopsTimeWindow'), OptimizationParameters.ToJsonString); finally FreeAndNil(OptimizationParameters); end; end; procedure TTestMarshalOptimizationParameters.SingleDepotMultipleDriverNoTimeWindow; var DataProvider: IOptimizationParametersProvider; OptimizationParameters: TOptimizationParameters; begin DataProvider := TSingleDepotMultipleDriverNoTimeWindowTestDataProvider.Create; OptimizationParameters := DataProvider.OptimizationParameters; try CheckEquals( EtalonFilename('OptimizationParametersToJson\SingleDepotMultipleDriverNoTimeWindow'), OptimizationParameters.ToJsonString); finally FreeAndNil(OptimizationParameters); end; end; procedure TTestMarshalOptimizationParameters.SingleDriverMultipleTimeWindows; var DataProvider: IOptimizationParametersProvider; OptimizationParameters: TOptimizationParameters; begin DataProvider := TSingleDriverMultipleTimeWindowsTestDataProvider.Create; OptimizationParameters := DataProvider.OptimizationParameters; try CheckEquals( EtalonFilename('OptimizationParametersToJson\SingleDriverMultipleTimeWindows'), OptimizationParameters.ToJsonString); finally FreeAndNil(OptimizationParameters); end; end; procedure TTestMarshalOptimizationParameters.SingleDriverRoundTrip; var DataProvider: IOptimizationParametersProvider; OptimizationParameters: TOptimizationParameters; begin DataProvider := TSingleDriverRoundTripTestDataProvider.Create; OptimizationParameters := DataProvider.OptimizationParameters; try CheckEquals( EtalonFilename('OptimizationParametersToJson\SingleDriverRoundTrip'), OptimizationParameters.ToJsonString); finally FreeAndNil(OptimizationParameters); end; end; procedure TTestMarshalOptimizationParameters.SingleDriverRoute10Stops; var DataProvider: IOptimizationParametersProvider; OptimizationParameters: TOptimizationParameters; begin DataProvider := TSingleDriverRoute10StopsTestDataProvider.Create; OptimizationParameters := DataProvider.OptimizationParameters; try CheckEquals( EtalonFilename('OptimizationParametersToJson\SingleDriverRoute10Stops'), OptimizationParameters.ToJsonString); finally FreeAndNil(OptimizationParameters); end; end; initialization // Register any test cases with the test runner RegisterTest('JSON\Marshal\', TTestMarshalOptimizationParameters.Suite); end.
program a4; {This program tests the shortest path algorithm from program strategy 10.16 Below you will find a test program, and some procedure headers. You must fill in the bodies of the procedures. Do not alter the test program or type definitions in any way. You are given a constant for INFINITY, which is defined to be the same as MAXINT. This is a constant that returns the largest possible number of type integer. This assumes that you will use low edge weight values. Stick to weights less than 100 and the output will also look nicer. NOTE - always comment every single local variable you use. } USES GraphsUnit ; var G: GraphRep; {G and S define the graph} S: GraphSize; E, {Counts number of edges} Weight: integer; { Weight, Origin and Terminus are } Origin, Terminus : VertexNumber ; { for User input } answer: string; { Stores users' answers to questions } ShortestPaths: AdjacencyRow ; { Stores the shortest paths } begin IdentifyMyself; {INITIALIZE G} repeat write('What size of graph do you want (maximum size = ', MAX,'): ') ; readln(S); until S in [1..MAX] ; writeln; NewGraph(G,S); writeln('Enter the edges one by one until you are finished.'); writeln('Quit by entering a zero for the origin vertex.'); E := 0; repeat writeln; write('Origin: '); readln(Origin); if Origin > 0 then begin write('Terminus: '); readln(Terminus); write('Weight: '); readln(Weight); AddEdge(G,S,Origin,Terminus,Weight); E := E+1 end until ( Origin <= 0 ); {DISPLAY G IF REQUESTED} writeln; writeln('Your graph has ', S,' vertices and ', E,' edges.'); writeln; write('Would you like to see the adjacency matrix (y/n)' ); readln(answer); writeln; if (answer[1] = 'y') or (answer[1] = 'Y') then Show_adj_matrix ( G, S ) ; writeln; {RUN SHORTEST PATH IF REQUESTED } write('Would you like to run the shortest path algorithm? (y/n)'); readln(answer); writeln; if (answer[1] = 'y') or (answer[1] = 'Y') then begin write('What is the start vertex? (1..', S,'): '); readln(Origin); ShortestPath(G,S,Origin,ShortestPaths); writeln; writeln('Shortest paths from start vertex ', Origin,' are: '); for Terminus := 1 to S do write(Terminus:5,': ',ShortestPaths[Terminus]); writeln; end; {RUN minimal spanning tree IF REQUESTED } writeln ; write('Would you like to run the minimal spanning tree algorithm? (y/n)'); readln(answer); writeln; if answer[1] in ['y', 'Y'] then DisplayMST( G, S ) ; {QUIT} writeln; writeln('Bye bye') end.
unit simplex_code; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Grids, Vcl.ExtCtrls,simplex_,Matrix_; type TSimplexForm = class(TForm) SGRestrMatrix: TStringGrid; UpDown1: TUpDown; UpDown2: TUpDown; EdNumVars: TEdit; EdNumRestrs: TEdit; Label1: TLabel; Label2: TLabel; SGGoalFunct: TStringGrid; RGToMax: TRadioGroup; Label3: TLabel; SGSolution: TStringGrid; Label4: TLabel; LbFunctValue: TLabel; BtSolve: TButton; Label5: TLabel; CBPrimal: TCheckBox; CheckBox1: TCheckBox; procedure EdNumVarsChange(Sender: TObject); procedure EdNumRestrsChange(Sender: TObject); procedure BtSolveClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var SimplexForm: TSimplexForm; implementation {$R *.dfm} //############################################################## //Косметика - изменение к-ва уравнений и к-ва переменных procedure TSimplexForm.EdNumRestrsChange(Sender: TObject); var NumRests,OldNumRests: integer; i,j: integer; begin OldNumRests:=SGRestrMatrix.RowCount-1; NumRests:=StrToInt(EdNumRestrs.Text); if NumRests>OldNumRests then begin SGRestrMatrix.RowCount:=NumRests+1; for I := OldNumRests+1 to NumRests do begin for j := 0 to SGRestrMatrix.ColCount-1 do SGRestrMatrix.Cells[j,i]:='0'; SGRestrMatrix.Cells[SGRestrMatrix.ColCount-2,i]:='<='; end; end else if NumRests<OldNumRests then begin SGRestrMatrix.RowCount:=NumRests+1; end; end; procedure TSimplexForm.EdNumVarsChange(Sender: TObject); var tempcol: TStringList; i,j: integer; NumVars,oldNumVars: integer; begin NumVars:=StrToInt(EdNumVars.Text); OldNumVars:=SGRestrMatrix.ColCount-2; tempcol:=TStringList.Create; if NumVars>OldNumVars then begin SGRestrMatrix.ColCount:=StrToInt(EdNumVars.Text)+2; SGRestrMatrix.Cols[NumVars+1]:=SGRestrMatrix.Cols[OldNumVars+1]; SGRestrMatrix.Cols[NumVars]:=SGRestrMatrix.Cols[OldNumVars]; for j := OldNumVars to NumVars-1 do begin SGRestrMatrix.Cells[j,0]:='x'+inttostr(j+1); for i := 1 to SGRestrMatrix.RowCount-1 do SGRestrMatrix.Cells[j,i]:='0'; end; SGGoalFunct.ColCount:=NumVars; for j := 0 to NumVars-1 do begin SGGoalFunct.Cells[j,0]:='x'+inttostr(j+1); if SGGoalFunct.Cells[j,1]='' then SGGoalFunct.Cells[j,1]:='0'; end; end else if NumVars<OldNumVars then begin SGRestrMatrix.Cols[NumVars]:=SGRestrMatrix.Cols[OldNumVars]; SGRestrMatrix.Cols[NumVars+1]:=SGRestrMatrix.Cols[OldNumVars+1]; SGRestrMatrix.ColCount:=NumVars+2; SGGoalFunct.ColCount:=NumVars; end; end; procedure TSimplexForm.FormCreate(Sender: TObject); begin end; //############################################################# procedure TSimplexForm.BtSolveClick(Sender: TObject); var Restrictions: TMatrix; GoalFunction,Sign,B: TVect; i,j: integer; NumVars,NumRestrs: integer; ToMax: boolean; tempSign: string; x: TVect; begin NumVars:=StrToInt(EdNumVars.Text); NumRestrs:=StrToInt(EdNumRestrs.Text); SetLength(Restrictions,NumRestrs,NumVars); SetLength(GoalFunction,NumVars); SetLength(Sign,NumRestrs); SetLength(B,NumRestrs); for i := 0 to NumRestrs-1 do for j := 0 to NumVars-1 do Restrictions[i,j]:=StrToFloat(SGRestrMatrix.Cells[j,i+1]); for j := 0 to NumVars-1 do GoalFunction[j]:=StrToFloat(SGGoalFunct.Cells[j,1]); for i := 0 to NumRestrs-1 do begin tempSign:=SGRestrMatrix.Cells[NumVars,i+1]; if tempsign='<=' then Sign[i]:=-1; if tempsign='=' then sign[i]:=0; if tempsign='>=' then sign[i]:=1; end; for i := 0 to NumRestrs-1 do B[i]:=StrToFloat(SGRestrMatrix.Cells[NumVars+1,i+1]); ToMax:=RGToMax.ItemIndex=0; //flagClearFake:=CheckBox1.Checked; //setLength(x,NumVars+1); //отправляем на решение x:=Simplex(Restrictions,Sign,B,GoalFunction, ToMax, CBPrimal.Checked); //выводим на экран NumVars:=Length(x); if NumVars>0 then begin SGSolution.ColCount:=NumVars-1; for I := 0 to NumVars-2 do begin SGSolution.Cells[i,0]:='x'+inttostr(i+1); SGSolution.Cells[i,1]:=FloatToStr(x[i]); end; LbFunctValue.Caption:='Foptimal='+FloatToStr(x[NumVars-1]); end else ShowMessage('Симплекс-метод вернул пустое решение'); end; end.
unit eeg_type; {$mode delphi}{$H+} interface uses filter_rbj, sysutils; const kMaxChannels = 64; type SingleRA0 = array [0..0] of Single; Singlep0 = ^SingleRA0; TChannel = record previ: integer; SignalLead: boolean; Info,UnitType: string; DisplayMin,DisplayMax,DisplayScale,SampleRate : double; HighPass: TRbjEqFilter; end; TEEG = record maxsamples,numChannels,samplesprocessed, samplesacquired: integer; audiomin,audiomax: single; Time: TDateTime; Channels: array [0..kMaxChannels] of TChannel; samples,filtered: array [0..kMaxChannels] of Singlep0; end; procedure FreeEEG (var lEEG: TEEG); procedure CreateEEG(var lEEG: TEEG; channels,nSamples: integer; SampleHz, HighPassFreqHz: double); function NumChannels(lEEG: TEEG): integer; function NumSamples(lEEG: TEEG; lChannel: integer): integer; function MaxNumSamples(lEEG: TEEG): integer; function NumSamplesZeroIfVariable(lEEG: TEEG): integer; function SampleRateZeroIfVariable(lEEG: TEEG): double; //procedure DummyData(var lEEG: TEEG); procedure DummyData(var lEEG: TEEG; samples: integer); implementation procedure DummyData(var lEEG: TEEG; samples: integer); var nC, c, s: integer; begin nC := NumChannels(lEEG); //nS := 1000; for c := 0 to (nC-1) do for s := 0 to (samples-1) do lEEG.samples[c][s] := 32767.5* (1.0+(sin(s/(c+1))) ); //scale -1..+1 to 0..65535 lEEG.samplesprocessed := 0; lEEG.samplesacquired := samples; end; function NumChannels(lEEG: TEEG): integer; begin result := lEEG.numChannels; end; function NumSamples(lEEG: TEEG; lChannel: integer): integer; begin result := lEEG.samplesprocessed; end; function MaxNumSamples(lEEG: TEEG): integer; begin result := lEEG.samplesprocessed; end; function NumSamplesZeroIfVariable(lEEG: TEEG): integer; begin result := lEEG.samplesprocessed; end; function SampleRateZeroIfVariable(lEEG: TEEG): double; var r: double; c: integer; begin result := 0; if (NumChannels(lEEG) < 1) or (MaxNumSamples(lEEG)<1) then exit; r := lEEG.Channels[0].SampleRate; for c := 0 to NumChannels(lEEG)-1 do if r <> lEEG.Channels[0].SampleRate then exit; result := round(r); end; procedure FreeEEG(var lEEG: TEEG); var i: integer; begin lEEG.maxsamples := 0; lEEG.samplesacquired := 0; lEEG.samplesprocessed := 0; if lEEG.numChannels > 0 then begin for i := 0 to lEEG.numChannels-1 do begin freemem(lEEG.Samples[i]); freemem(lEEG.Filtered[i]); end;//for each channel end; //more than one channel lEEG.numChannels := 0; end; //freeEEG procedure CreateEEG(var lEEG: TEEG; channels,nSamples: integer; SampleHz, HighPassFreqHz: double); var i: integer; begin lEEG.samplesacquired := 0; lEEG.samplesprocessed := 0; lEEG.Time := Now; if channels > kMaxChannels then lEEG.numChannels := kMaxChannels else lEEG.numChannels := channels; //channelheight := pixelheightperchannelX; if channels > 0 then begin lEEG.maxsamples := nSamples; for i := 0 to lEEG.numChannels-1 do begin getmem(lEEG.Samples[i], lEEG.maxsamples*sizeof(single)); getmem(lEEG.Filtered[i], lEEG.maxsamples*sizeof(single)); lEEG.Channels[i].SignalLead := true; lEEG.Channels[i].Info := 'ch'+inttostr(i+1); lEEG.Channels[i].UnitType := 'uV'; lEEG.Channels[i].SampleRate := SampleHz ; lEEG.Channels[i].previ := 0; lEEG.Channels[i].DisplayScale := 1.0; lEEG.Channels[i].HighPass := TRbjEqFilter.Create(SampleHz,0); lEEG.Channels[i].HighPass.Freq := HighPassFreqHz; if HighPassFreqHz <> 0 then lEEG.Channels[i].HighPass.CalcFilterCoeffs(kHighPass,HighPassFreqHz,0.3{Q},0{Gain}, true {QIsBandWidthCheck}) end; end; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clMailHeader; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clHeaderFieldList, clEmailAddress, clEncoder; type TclMailHeaderFieldList = class(TclHeaderFieldList) private FCharSet: string; FEncoding: TclEncodeMethod; class function DecodeEncodedWord(const AFieldPart, ACharSet: string; AEncoding: TclEncodeMethod; ADecodedStream: TStream): string; class function TranslateDecodedWord(ADecodedStream: TStream; const ACharSet: string; AEncoding: TclEncodeMethod): string; class function EncodingNameToType(const AEncodingName: string): TclEncodeMethod; class procedure GetEncodedWord(const AText, ACharSet: string; var AEncodedWord: string; var AEncoding: TclEncodeMethod); class procedure GetStringsToEncode(const AText: string; AEncodedLength, ACharsPerLine: Integer; AStrings: TStrings); function GetMailFieldValue(AIndex: Integer): string; public constructor Create(const ACharSet: string; AEncoding: TclEncodeMethod; ACharsPerLine: Integer); function GetFieldValue(AIndex: Integer): string; overload; override; function GetDecodedFieldValue(const AName: string): string; overload; function GetDecodedFieldValue(AIndex: Integer): string; overload; function GetDecodedEmail(const AName: string): string; overload; function GetDecodedEmail(AIndex: Integer): string; overload; procedure GetDecodedEmailList(const AName: string; AList: TclEmailAddressList); overload; procedure GetDecodedEmailList(AIndex: Integer; AList: TclEmailAddressList); overload; function GetDecodedFieldValueItem(const ASource, AItemName: string): string; procedure AddEncodedField(const AName, AValue: string); procedure AddEncodedFieldItem(const AFieldName, AItemName, AValue: string); overload; procedure AddEncodedFieldItem(AFieldIndex: Integer; const AItemName, AValue: string); overload; procedure AddEncodedEmail(const AName, AValue: string); procedure AddEncodedEmailList(const AName: string; AList: TclEmailAddressList); class function DecodeEmail(const ACompleteEmail, ACharSet: string): string; class function DecodeField(const AFieldValue, ACharSet: string): string; class function EncodeEmail(const ACompleteEmail, ACharSet: string; AEncoding: TclEncodeMethod; ACharsPerLine: Integer): string; class function EncodeField(const AFieldValue, ACharSet: string; AEncoding: TclEncodeMethod; ACharsPerLine: Integer): string; property CharSet: string read FCharSet write FCharSet; property Encoding: TclEncodeMethod read FEncoding write FEncoding; end; implementation uses clUtils, clWUtils, clTranslator; { TclMailHeaderFieldList } procedure TclMailHeaderFieldList.AddEncodedEmail(const AName, AValue: string); var src: TStrings; begin Assert(Source <> nil); if (Trim(AValue) <> '') then begin src := TStringList.Create(); try src.Text := GetNameValuePair(AName, EncodeEmail(AValue, CharSet, Encoding, CharsPerLine - Length(AName) - Length(': '))); InsertFoldedStrings(HeaderEnd, src, '', #9); finally src.Free(); end; Parse(HeaderStart, Source); end; end; procedure TclMailHeaderFieldList.AddEncodedEmailList(const AName: string; AList: TclEmailAddressList); var i: Integer; src: TStrings; email: string; begin Assert(Source <> nil); if (AList.Count > 0) then begin src := TStringList.Create(); try email := EncodeEmail(AList[0].FullAddress, CharSet, Encoding, CharsPerLine - Length(AName) - Length(': ')); if (AList.Count > 1) then begin email := email + ','; end; AddTextStr(src, GetNameValuePair(AName, email)); for i := 1 to AList.Count - 1 do begin email := EncodeEmail(AList[i].FullAddress, CharSet, Encoding, CharsPerLine - Length(#9)); if (i < AList.Count - 1) then begin email := email + ','; end; AddTextStr(src, email); end; InsertFoldedStrings(HeaderEnd, src, '', #9); finally src.Free(); end; Parse(HeaderStart, Source); end; end; procedure TclMailHeaderFieldList.AddEncodedField(const AName, AValue: string); var src: TStrings; begin Assert(Source <> nil); if (Trim(AValue) <> '') then begin src := TStringList.Create(); try src.Text := GetNameValuePair(AName, EncodeField(AValue, CharSet, Encoding, CharsPerLine - Length(AName) - Length(': '))); InsertFoldedStrings(HeaderEnd, src, '', #9); finally src.Free(); end; Parse(HeaderStart, Source); end; end; procedure TclMailHeaderFieldList.AddEncodedFieldItem(AFieldIndex: Integer; const AItemName, AValue: string); var src: TStrings; line, newline, trimmedLine: string; fieldEnd: Integer; begin if ((AFieldIndex < 0) or (AFieldIndex >= FieldList.Count)) then Exit; Assert(Source <> nil); if (Trim(AValue) <> '') then begin src := TStringList.Create(); try newline := GetQuotedString(EncodeField(AValue, CharSet, Encoding, CharsPerLine - Length(#9) - Length(AItemName) - Length('=""'))); newline := GetItemNameValuePair(AItemName, newline); fieldEnd := GetFieldEnd(AFieldIndex); line := Source[fieldEnd]; trimmedLine := Trim(line); if (trimmedLine <> '') and (not CharInSet(trimmedLine[Length(trimmedLine)], [';', ':'])) then begin line := line + ';'; end; Source[fieldEnd] := line; src.Text := newline; InsertFoldedStrings(fieldEnd + 1, src, #9, #9); finally src.Free(); end; end; end; procedure TclMailHeaderFieldList.AddEncodedFieldItem(const AFieldName, AItemName, AValue: string); begin AddEncodedFieldItem(GetFieldIndex(AFieldName), AItemName, AValue); end; constructor TclMailHeaderFieldList.Create(const ACharSet: string; AEncoding: TclEncodeMethod; ACharsPerLine: Integer); begin inherited Create(); FCharSet := ACharSet; FEncoding := AEncoding; CharsPerLine := ACharsPerLine; end; class function TclMailHeaderFieldList.DecodeEmail(const ACompleteEmail, ACharSet: string): string; var name, email: string; begin Result := ACompleteEmail; if GetEmailAddressParts(Result, name, email) and (email <> '') then begin name := DecodeField(name, ACharSet); Result := GetCompleteEmailAddress(name, email); end; end; class function TclMailHeaderFieldList.DecodeEncodedWord(const AFieldPart, ACharSet: string; AEncoding: TclEncodeMethod; ADecodedStream: TStream): string; var encoder: TclEncoder; oldPos: Int64; begin encoder := TclEncoder.Create(nil); try encoder.SuppressCrlf := False; encoder.EncodeMethod := AEncoding; oldPos := ADecodedStream.Position; encoder.Decode(AFieldPart, ADecodedStream); ADecodedStream.Position := oldPos; Result := TranslateDecodedWord(ADecodedStream, ACharSet, AEncoding); finally encoder.Free(); end; end; class function TclMailHeaderFieldList.DecodeField(const AFieldValue, ACharSet: string): string; var Formatted: Boolean; EncodedBegin, FirstDelim, SecondDelim, EncodedEnd, TextBegin: Integer; CurLine, s, EncodingName, CharsetName: String; decodedStream: TStream; isUtf8: Boolean; begin Result := ''; decodedStream := TMemoryStream.Create(); try Formatted := False; TextBegin := 1; CurLine := AFieldValue; EncodedBegin := Pos('=?', CurLine); isUtf8 := True; while (EncodedBegin <> 0) do begin Result := Result + Copy(CurLine, TextBegin, EncodedBegin - TextBegin); TextBegin := EncodedBegin; FirstDelim := TextPos('?', CurLine, EncodedBegin + 2); if (FirstDelim <> 0) then begin SecondDelim := TextPos('?', CurLine, FirstDelim + 1); if ((SecondDelim - FirstDelim) = 2) then begin EncodedEnd := TextPos('?=', CurLine, SecondDelim + 1); if (EncodedEnd <> 0) then begin try CharsetName := Copy(CurLine, EncodedBegin + 2, FirstDelim - 2 - EncodedBegin); EncodingName := CurLine[FirstDelim + 1]; isUtf8 := isUtf8 and SameText(CharsetName, 'utf-8'); s := Copy(CurLine, SecondDelim + 1, EncodedEnd - SecondDelim - 1); Result := Result + DecodeEncodedWord(s, CharsetName, EncodingNameToType(EncodingName), decodedStream); TextBegin := EncodedEnd + 2; Formatted := True; except TextBegin := EncodedBegin + 2; Result := Result + '=?'; end; CurLine := Copy(CurLine, TextBegin, Length(CurLine)); s := TrimLeft(CurLine); if (Pos('=?', s) <> 1) then begin s := GetUnfoldedLine(CurLine); end; CurLine := s; EncodedBegin := Pos('=?', CurLine); TextBegin := 1; Continue; end; end; end; EncodedBegin := 0; end; if (CurLine <> '') then begin Result := Result + Copy(CurLine, TextBegin, Length(CurLine)); end; if Formatted and isUtf8 then begin decodedStream.Position := 0; Result := TranslateDecodedWord(decodedStream, 'utf-8', cmBase64); end else if (not Formatted) then begin Result := DecodeEncodedWord(AFieldValue, ACharSet, cmNone, decodedStream); end; finally decodedStream.Free(); end; end; class function TclMailHeaderFieldList.EncodeEmail(const ACompleteEmail, ACharSet: string; AEncoding: TclEncodeMethod; ACharsPerLine: Integer): string; var name, encodedName, email, encodedEmail: string; len, ind, chrsPerLine, encodedNameLen: Integer; begin Result := ACompleteEmail; if GetEmailAddressParts(Result, name, email) then begin chrsPerLine := ACharsPerLine - Length(' <'); encodedName := EncodeField(name, ACharSet, AEncoding, chrsPerLine); Result := GetCompleteEmailAddress(encodedName, email); encodedNameLen := Length(Result) - Length(email) - Length(' <>'); len := RTextPos(#13#10, Result); if (len > 0) then begin len := chrsPerLine - (encodedNameLen - (len - 1) - Length(#13#10)) - Length(#9); end else begin len := chrsPerLine - encodedNameLen; end; if (len + 1 >= Length(email)) then begin len := Length(email); end; ind := 1; encodedEmail := System.Copy(email, ind, len); Inc(ind, len); while (ind < Length(email)) do begin len := ACharsPerLine - Length(#9) - Length('>'); encodedEmail := encodedEmail + #13#10 + System.Copy(email, ind, len); Inc(ind, len); end; Result := GetCompleteEmailAddress(encodedName, encodedEmail); end; end; class function TclMailHeaderFieldList.EncodeField(const AFieldValue, ACharSet: string; AEncoding: TclEncodeMethod; ACharsPerLine: Integer): string; var i: Integer; s: string; enc: TclEncodeMethod; list: TStrings; begin Assert(ACharsPerLine > 0); Result := AFieldValue; if (Result = '') or (AEncoding = cmUUEncode) then Exit; list := TStringList.Create(); try s := ''; enc := AEncoding; GetEncodedWord(AFieldValue, ACharSet, s, enc); GetStringsToEncode(AFieldValue, Length(s), ACharsPerLine, list); if (enc = cmNone) and (list.Count > 1) then begin s := ''; enc := cmQuotedPrintable; GetEncodedWord(AFieldValue, ACharSet, s, enc); GetStringsToEncode(AFieldValue, Length(s), ACharsPerLine, list); end; Result := ''; for i := 0 to list.Count - 1 do begin s := ''; GetEncodedWord(list[i], ACharSet, s, enc); Result := Result + s + #13#10; end; Result := Trim(Result); if (Result = '') then begin Result := AFieldValue; end; finally list.Free(); end; end; class function TclMailHeaderFieldList.EncodingNameToType(const AEncodingName: string): TclEncodeMethod; begin Result := cmNone; if (AEncodingName = '') then Exit; case UpperCase(AEncodingName)[1] of 'Q': Result := cmQuotedPrintable; 'B': Result := cmBase64; end; end; function TclMailHeaderFieldList.GetDecodedFieldValue(const AName: string): string; begin Result := GetDecodedFieldValue(GetFieldIndex(AName)); end; function TclMailHeaderFieldList.GetDecodedEmail(const AName: string): string; begin Result := GetDecodedEmail(GetFieldIndex(AName)); end; function TclMailHeaderFieldList.GetDecodedEmail(AIndex: Integer): string; begin Result := DecodeEmail(GetFieldValue(AIndex), CharSet); end; procedure TclMailHeaderFieldList.GetDecodedEmailList(const AName: string; AList: TclEmailAddressList); begin GetDecodedEmailList(GetFieldIndex(AName), AList); end; procedure TclMailHeaderFieldList.GetDecodedEmailList(AIndex: Integer; AList: TclEmailAddressList); var i: Integer; list: TStrings; begin AList.Clear(); if ((AIndex < 0) or (AIndex >= FieldList.Count)) then Exit; list := TStringList.Create(); try ExtractQuotedWords(GetFieldValue(AIndex), list, ',', ['"', '('], ['"', ')'], True); for i := 0 to list.Count - 1 do begin AList.Add(DecodeEmail(Trim(list[i]), CharSet)); end; finally list.Free(); end; end; function TclMailHeaderFieldList.GetDecodedFieldValue(AIndex: Integer): string; begin Result := DecodeField(GetFieldValue(AIndex), CharSet); end; function TclMailHeaderFieldList.GetDecodedFieldValueItem(const ASource, AItemName: string): string; begin Result := DecodeField(GetFieldValueItem(ASource, AItemName), CharSet); end; class procedure TclMailHeaderFieldList.GetEncodedWord(const AText, ACharSet: string; var AEncodedWord: string; var AEncoding: TclEncodeMethod); const EncodingToName: array[TclEncodeMethod] of string = ('', 'Q', 'B', '', ''); var cnt: Integer; src: TStream; buf: TclByteArray; encoder: TclEncoder; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} src := nil; encoder := nil; try src := TMemoryStream.Create(); cnt := TclTranslator.GetByteCount(AText, ACharSet); if (cnt > 0) then begin SetLength(buf, cnt); buf := TclTranslator.GetBytes(AText, ACharSet); src.Write(buf[0], cnt); end; encoder := TclEncoder.Create(nil); encoder.SuppressCrlf := True; encoder.EncodeMethod := AEncoding; if (encoder.EncodeMethod = cmNone) then begin src.Position := 0; encoder.EncodeMethod := encoder.GetPreferredEncoding(src); end; AEncoding := encoder.EncodeMethod; src.Position := 0; AEncodedWord := encoder.Encode(src); if (encoder.EncodeMethod = cmQuotedPrintable) then begin AEncodedWord := StringReplace(AEncodedWord, #32, '_', [rfReplaceAll]); AEncodedWord := StringReplace(AEncodedWord, '='#13#10, #13#10, [rfReplaceAll]); end; if (EncodingToName[encoder.EncodeMethod] <> '') then begin AEncodedWord := Format('=?%s?%s?%s?=', [ACharSet, EncodingToName[encoder.EncodeMethod], AEncodedWord]); end; finally encoder.Free(); src.Free(); end; end; function TclMailHeaderFieldList.GetMailFieldValue(AIndex: Integer): string; var Ind, i: Integer; begin Assert(Source <> nil); if (AIndex > -1) and (AIndex < FieldList.Count) then begin Ind := GetFieldStart(AIndex); Result := System.Copy(Source[Ind], Length(FieldList[AIndex] + ':') + 1, MaxInt); Result := TrimFirstWhiteSpace(Result); for i := Ind + 1 to Source.Count - 1 do begin if not ((Source[i] <> '') and CharInSet(Source[i][1], [#9, #32])) then begin Break; end; if (Result <> '') and (Result[Length(Result)] = '>') then begin Result := Result + ','; end; Result := Result + GetUnfoldedLine(Source[i]); end; end else begin Result := ''; end; end; class procedure TclMailHeaderFieldList.GetStringsToEncode(const AText: string; AEncodedLength, ACharsPerLine: Integer; AStrings: TStrings); var ind, len, wordCnt, wordLen: Integer; begin AStrings.Clear(); wordCnt := AEncodedLength div ACharsPerLine; if (AEncodedLength mod ACharsPerLine) > 0 then begin Inc(wordCnt); end; len := Length(AText); wordLen := Trunc(len / wordCnt); ind := 1; while (ind <= len) do begin AStrings.Add(system.Copy(AText, ind, wordLen)); Inc(ind, wordLen); end; end; function TclMailHeaderFieldList.GetFieldValue(AIndex: Integer): string; begin Result := ''; if ((AIndex < 0) or (AIndex >= FieldList.Count)) then Exit; if ('subject' = FieldList[AIndex]) then begin Result := InternalGetFieldValue(AIndex); end else begin Result := Trim(GetMailFieldValue(AIndex)); end; end; class function TclMailHeaderFieldList.TranslateDecodedWord(ADecodedStream: TStream; const ACharSet: string; AEncoding: TclEncodeMethod): string; var i: Integer; buf: TclByteArray; size: Int64; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} Result := ''; size := ADecodedStream.Size - ADecodedStream.Position; if (size > 0) then begin SetLength(buf, size); ADecodedStream.Read(buf[0], size); if (AEncoding = cmQuotedPrintable) then begin for i := 0 to size - 1 do begin if (buf[i] = 95) then //'_' buf[i] := 32; //' ' end; end; Result := TclTranslator.GetString(buf, 0, size, ACharSet); end; end; end.
unit Model.CadastroFinanceiro; interface uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao; type TCadastroFinanceiro = class private FID: Integer; FSequencia: Integer; FTipoConta: String; FBanco: String; FAgencia: String; FConta: String; FOperacao: String; FAcao: TAcao; FAtivo: Boolean; FConexao: TConexao; FForma: string; FCPFCNPJFavorecido: String; FFavorecido: String; FChavePIX: String; FQuery: TFDQuery; function Insert(): Boolean; function Update(): Boolean; function Delete(): Boolean; public property ID: Integer read FID write FID; property Sequencia: Integer read FSequencia write FSequencia; property Forma: string read FForma write FForma; property TipoConta: String read FTipoConta write FTipoConta; property Banco: String read FBanco write FBanco; property Agencia: String read FAgencia write FAgencia; property Conta: String read FConta write FConta; property Operacao: String read FOperacao write FOperacao; property Ativo: Boolean read FAtivo write FAtivo; property Favorecido: String read FFavorecido write FFavorecido; property CPFCNPJFavorecido: String read FCPFCNPJFavorecido write FCPFCNPJFavorecido; property ChavePIX: String read FChavePIX write FChavePIX; property Query: TFDQuery read FQuery write FQuery; property Acao: TAcao read FAcao write FAcao; constructor Create(); function GetID(iID: Integer): Integer; function Localizar(aParam: array of variant): boolean; function Gravar(): Boolean; function SaveBatch(memTable: TFDMemTable): Boolean; function SetupClass(FDQuery: TFDQuery): boolean; function ClearClass(): boolean; end; const TABLENAME = 'cadastro_financeiro'; implementation { TCadastroFinanceiro } function TCadastroFinanceiro.ClearClass: boolean; begin Result := False; FID := 0; FSequencia := 0; FTipoConta := ''; FBanco := ''; FAgencia := ''; FConta := ''; FOperacao := ''; FAtivo := False; FForma := ''; FCPFCNPJFavorecido := ''; FFavorecido := ''; FChavePIX := ''; Result := True; end; constructor TCadastroFinanceiro.Create; begin FConexao := TConexao.Create; end; function TCadastroFinanceiro.Delete: Boolean; var sSQL : String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; if Self.Sequencia = -1 then begin sSQL := 'delete from ' + TABLENAME + ' ' + 'where id_cadastro = :pid_cadastro'; FDQuery.ExecSQL(sSQL,[Self.ID]); end else begin sSQL := 'delete from ' + TABLENAME + ' ' + 'where id_cadastro = :pid_cadastro and seq_financeiro = :pseq_financeiro'; FDQuery.ExecSQL(sSQL,[Self.ID, Self.Sequencia]); end; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroFinanceiro.GetID(iID: Integer): Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(seq_financeiro),0) + 1 from ' + TABLENAME + ' where id_cadastro = ' + iID.toString ); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroFinanceiro.Gravar: Boolean; begin case FAcao of tacIncluir: Result := Self.Insert(); tacAlterar: Result := Self.Update(); tacExcluir: Result := Self.Delete(); end; end; function TCadastroFinanceiro.Insert: Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); Self.Sequencia := GetID(Self.ID); sSQL := 'insert into ' + TABLENAME + '(id_cadastro, cod_tipo_cadastro, seq_financeiro, des_forma_credito, des_tipo_conta, ' + 'cod_banco, num_agencia, des_conta, cod_operacao, dom_ativo, nom_favorecido, num_cnpj_cpf_favorecido) ' + 'values (:id_cadastro, :seq_financeiro, :des_forma_credito, :des_tipo_conta, ' + ':cod_banco, :num_agencia, :des_conta, :cod_operacao, :dom_ativo, :nom_favorecido, :num_cnpj_cpf_favorecido);'; FDQuery.ExecSQL(sSQL,[Self.ID, Self.Sequencia, Self.Forma, Self.TipoConta, Self.Banco, Self.Agencia, Self.Conta, Self.Operacao, Self.Ativo, Self.Favorecido, Self.CPFCNPJFavorecido]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroFinanceiro.Localizar(aParam: array of variant): boolean; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('where id_cadastro = :id_cadastro'); FDQuery.ParamByName('id_cadastro').AsInteger := aParam[1]; end; if aParam[0] = 'SEQUENCIA' then begin FDQuery.SQL.Add('where id_cadastro = :id_cadastro and ' + 'seq_financeiro = :seq_financeiro'); FDQuery.ParamByName('id_cadastro').AsInteger := aParam[1]; FDQuery.ParamByName('seq_financeiroINANCEIRO').AsInteger := aParam[2]; end; if aParam[0] = 'TIPO' then begin FDQuery.SQL.Add('where des_tipo_conta like :des_tipo_conta'); FDQuery.ParamByName('des_tipo_conta').AsString := aParam[1]; end; if aParam[0] = 'BANCO' then begin FDQuery.SQL.Add('where cod_banco = :cod_banco'); FDQuery.ParamByName('cod_banco').AsString := aParam[1]; end; if aParam[0] = 'AGENCIA' then begin FDQuery.SQL.Add('where cod_agencia = :cod_agencia'); FDQuery.ParamByName('cod_agencia').AsString := aParam[1]; end; if aParam[0] = 'CONTA' then begin FDQuery.SQL.Add('where num_conta = :num_conta'); FDQuery.ParamByName('NUM_CONTA').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); if not FDQuery.isEmpty then begin FQuery := FDQuery; end; Result := True; finally FDQuery.Connection.close; FDQuery.Free; end; end; function TCadastroFinanceiro.SaveBatch(memTable: TFDMemTable): Boolean; begin Result := False; Self.Acao := tacExcluir; if not Self.Gravar then begin Exit; end; memTable.First; while not memTable.Eof do begin Self.Sequencia := GetID(Self.ID); Self.Forma := memTable.FieldByName('des_forma_credito').AsString; Self.TipoConta := memTable.FieldByName('des_tipo_conta').AsString; Self.Banco := memTable.FieldByName('cod_banco').AsString; Self.Agencia := memTable.FieldByName('num_agencia').AsString; Self.Operacao := memTable.FieldByName('cod_operacao').AsString; Self.Conta := memTable.FieldByName('des_conta').AsString; Self.Ativo := memTable.FieldByName('dom_ativo').AsBoolean; Self.Favorecido := memTable.FieldByName('des_conta').AsString; Self.CPFCNPJFavorecido := memTable.FieldByName('num_cnpj_cpf_favorecido').AsString; Self.Acao := tacIncluir; if not Self.Gravar then begin Exit; end; memTable.Next; end; Result := True; end; function TCadastroFinanceiro.SetupClass(FDQuery: TFDQuery): boolean; begin Result := False; FID := FDQuery.FieldByName('id_cadastro').Asinteger; FSequencia := FDQuery.FieldByName('seq_financeiro').Asinteger; FTipoConta := FDQuery.FieldByName('des_tipo_conta').Asstring; FBanco := FDQuery.FieldByName('cod_banco').Asstring; FAgencia := FDQuery.FieldByName('num_agencia').Asstring; FConta := FDQuery.FieldByName('des_conta').Asstring; FOperacao := FDQuery.FieldByName('cod_operacao').Asstring; FAtivo := FDQuery.FieldByName('dom_ativo').Asboolean; FForma := FDQuery.FieldByName('des_forma_credito').Asstring; FCPFCNPJFavorecido := FDQuery.FieldByName('num_cnpj_cpf_favorecido').Asstring; FFavorecido := FDQuery.FieldByName('nom_favorecido').Asstring; FChavePIX := FDQuery.FieldByName('des_chave_pix').Asstring; Result := True; end; function TCadastroFinanceiro.Update: Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; sSQL := 'update ' + TABLENAME + 'set ' + 'des_forma_credito = :pdes_forma_credito, des_tipo_conta = :pdes_tipo_conta, cod_banco = :pcod_banco, ' + 'num_agencia = :pnum_agencia, cod_operacao = :pcod_operacao, des_conta = :pdes_conta ' + 'dom_ativo = :pdom_ativo, nom_favorecido = :pnom_favorecido, num_cnpj_cpf_favorecido = :pnum_cnpj_cpf_favorecido ' + 'where id_cadastro = :pid_cadastro and seq_financeiro = :pseq_financeiro;'; FDQuery.ExecSQL(sSQL,[Self.Forma, Self.TipoConta, Self.Banco, Self.Agencia, Self.Conta, Self.Operacao, Self.Ativo, Self.Favorecido, Self.CPFCNPJFavorecido, Self.ID, Self.Sequencia]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
unit tcsettings; {$IFDEF FPC} {$MODE DELPHI}{$H+} {$ENDIF} {$IFDEF Win32} {$DEFINE Windows} {$ENDIF} interface uses {$IFDEF Windows} Windows, {$ENDIF} {$ifdef Darwin} MacOSAll, {$endif} Classes, SysUtils, IniFiles, Forms, constants; type { TConfigurations } TConfigurations = class(TObject) private ConfigFilePath: string; public MyDirectory: string; ComponentsDBFile: string; constructor Create; destructor Destroy; override; procedure ReadFromFile(Sender: TObject); procedure Save(Sender: TObject); end; var vConfigurations: TConfigurations; implementation { TConfigurations } { TConfigurations.Create () Creates an object, populates the class with the default configurations and then tryes to load the configurations from the XML file Under Mac OS X there is also the need to find the location of the Application Bundle } constructor TConfigurations.Create; {$ifdef Darwin} var pathRef: CFURLRef; pathCFStr: CFStringRef; pathStr: shortstring; {$endif} begin {$ifdef Windows} ConfigFilePath := ExtractFilePath(Application.EXEName) + 'magnifier.ini'; {$endif} {$ifdef Unix} {$ifdef Darwin} ConfigFilePath := GetEnvironmentVariable('HOME') + '/.magnifier.ini'; {$else} ConfigFilePath := GetAppConfigFile(False) + '.conf'; {$endif} {$endif} // Under Mac OS X we need to get the location of the bundle {$ifdef Darwin} pathRef := CFBundleCopyBundleURL(CFBundleGetMainBundle()); pathCFStr := CFURLCopyFileSystemPath(pathRef, kCFURLPOSIXPathStyle); CFStringGetPascalString(pathCFStr, @pathStr, 255, CFStringGetSystemEncoding()); CFRelease(pathRef); CFRelease(pathCFStr); MyDirectory := pathStr + BundleResourcesDirectory; {$endif} {$ifdef Windows} MyDirectory := ExtractFilePath(Application.EXEName); {$endif} // ReadFromFile(nil); { case Language of ID_MENU_PORTUGUESE: vTranslations.TranslateToPortuguese; ID_MENU_SPANISH: vTranslations.TranslateToSpanish; ID_MENU_FRENCH: vTranslations.TranslateToFrench; ID_MENU_GERMAN: vTranslations.TranslateToGerman; ID_MENU_ITALIAN: vTranslations.TranslateToItalian; else vTranslations.TranslateToEnglish; end; vTranslations.UpdateTranslations; } ComponentsDBFile := MyDirectory + STR_DB_COMPONENTS_FILE; end; { TConfigurations.Destroy () Dont call this method directly. Use Free instead. } destructor TConfigurations.Destroy; begin // Save(nil); inherited Destroy; end; procedure TConfigurations.ReadFromFile(Sender: TObject); var MyFile: TIniFile; begin MyFile := TIniFile.Create(ConfigFilePath); try {$ifdef UNIX} {$ifndef DARWIN} MyDirectory := MyFile.ReadString(SectionUnix, IdentMyDirectory, DefaultDirectory); {$endif} {$endif} finally MyFile.Free; end; end; procedure TConfigurations.Save(Sender: TObject); var MyFile: TIniFile; begin MyFile := TIniFile.Create(ConfigFilePath); try // MyFile.WriteBool(SectionGeneral, IdentgraphicalBorder, graphicalBorder); finally MyFile.Free; end; end; initialization vConfigurations := TConfigurations.Create; finalization FreeAndNil(vConfigurations); end.
unit evReq; {* Класс реквизита (одельная строка в таблице) } // Модуль: "w:\common\components\gui\Garant\Everest\qf\evReq.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevReq" MUID: (48D3BD0A02D7) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , evCustomControlTool , evQueryCardInt , evEditorControlFieldList , evEditorControlList , l3Base , l3Variant , nevTools , evdTypes , l3Interfaces , nevBase , evControl ; type RevControlClass = class of TevControl; TevReq = class(TevCustomControlTool, IevReq, IevComboReq, IevDatesReq, IevPhoneReq) {* Класс реквизита (одельная строка в таблице) } private f_FieldsList: TevEditorControlFieldList; {* Список полей для каждого реквизита группы (IevEditorControlField) } f_ControlsList: TevEditorControlList; {* Список виджетов для каждого реквизита (IevEditorControl) } f_ReqCaption: Tl3String; {* Текст метки реквизита } f_Group: Tl3Variant; private function AddValue(const aView: InevView; const aControl: IevEditorControl; const aPara: InevPara = nil; ToModel: Boolean = False; anAdd: Boolean = False): Boolean; {* Добавление нового поля в реквизит. aControl - виджет (поле или любой виджет возле поля), ToModel: только добавляем в модель aPara } function DeleteValue(const aView: InevView; const aControl: IevEditorControl = nil; ToModel: Boolean = False): Integer; {* Удаление поля из реквизита. Возвращает индекс поля вставшего вместо удаленного } function GetControlClass(aControlType: TevControlType): RevControlClass; function CanVisibleLogicBtn: Boolean; function LogicBtnEnabled: Boolean; protected procedure KeyAction(aCmd: Word); {* "Внешняя" обработка команды. } function AnalyzeString(const aValue: Il3CString; out aRslt: Il3CString): Boolean; procedure TextChange(const aView: InevView); {* Обработчик события изменения текста. } procedure RememberState(const aControl: IevCustomEditorControl); {* Запомнить состояние контрола для всплывающего меню. } function GetNextVisible(const aControl: IevEditorControl; OnlyFields: Boolean; out anIsLastField: Boolean): IevEditorControl; {* Возвращает следующий видимый контрол. } function GetFirstVisible(OnlyFields: Boolean): IevEditorControl; {* Возвращает первый видимый контрол для реквизита. } function GetPrevVisible(const aControl: IevEditorControl; OnlyFields: Boolean; out anIsFirstField: Boolean): IevEditorControl; {* Возвращает следующий видимый контрол. } function GetLastVisible(OnlyFields: Boolean): IevEditorControl; {* Возвращает последний видимый контрол. } function GetHint(var aValue: Il3CString; const aControl: IevEditorControl): Boolean; {* Получить хинт для контрола. } function IsRequired: Boolean; {* Обязательное поле (должно обязательно содержать значение). } function IsEmpty: Boolean; {* Проверяет, является ли реквизит пустым. } function FieldsCount: Integer; {* Количество контролов (полей редактора) в реквизите. } procedure ButtonPressed(const aView: InevView; const aControl: IevEditorControl; aBtnType: TevButtonType); {* Обработка реакции на нажатие кнопки по её типу. } procedure AfterSetText(const aField: IevEditorControlField); function AddField(const aView: InevView; NeedSetFocus: Boolean = False): IevEditorControlField; {* Добавление реквизита. } function GetItemImage(Index: Integer; var aImages: InevImageList): Integer; {* Ручка для получения картинки для выпадающего дерева. } procedure DeleteField(const aView: InevView; const aControl: IevEditorControlField = nil; NeedFocus: Boolean = False); {* Удаление реквизита. } procedure InsertToModel(const aView: InevView; const aControl: IevEditorControl; aChild: Tl3Variant; NeedFocus: Boolean = False; anAdd: Boolean = False); {* Добавление реквизита только в модель. } procedure DeleteFromModel(const aView: InevView; const aControl: IevEditorControl; NeedFocus: Boolean = False); {* Удаление реквизита только из модели. } procedure InitModel(const aTag: InevPara; AddValues: Boolean; anIndexField: Integer; anIndexCtrl: Integer); {* Инициализация дочерних компонентов. } function CheckEdit(const aField: IevEditorControlField): Boolean; {* Проверка значения поля. } procedure UpdateState(const aField: IevEditorControlField; const anOp: InevOp); {* Обновить состояния поля и кнопок, вокруг контрола. } function Get_ModelListener: IevModelListener; function Get_Fields(Index: Integer): IevEditorControlField; function Get_ReqName: Il3CString; function Get_ReqCaption: Il3CString; procedure SetFocus(const aField: IevEditorControlField; aAtEnd: Boolean = False); {* Установить фокус. } function FirstField: IevEditorControlField; {* Возвращает первый контрол в списке. } function LastField: IevEditorControlField; {* Возвращает последний контрол в списке. } function Get_Group: IevQueryGroup; function Get_QueryCard: IevQueryCard; procedure ClearLogicValue; procedure EscPressed(const aField: IevEditorFieldWithTree); function NeedAsterisk: Boolean; {* Нужно ли проверять значение '*' в тексте. } function GetTreeFromAdapter: InevSimpleTree; {* Получает дерево с адаптера. } function IsMulti: Boolean; {* Признак реквизита с несколькими значениями. } procedure HyperLinkClick; {* Щелчок по гиперссылке. } function Get_DefStateIndex: Integer; procedure Set_DefStateIndex(aValue: Integer); function IsContext: Boolean; {* Признак того, что реквизит является конекстом. } function GetNode(anIndex: Integer): InevSimpleNode; {* Получить узел выпадающего дерева по номеру поля. } function Get_HistoryList: Il3StringsEx; function Get_StartDate: TDateTime; procedure Set_StartDate(aValue: TDateTime); function Get_EndDate: TDateTime; procedure Set_EndDate(aValue: TDateTime); function Get_Code: Il3CString; procedure Set_Code(const aValue: Il3CString); function Get_Number: Il3CString; procedure Set_Number(const aValue: Il3CString); function GetPromptTreeFromAdapter: InevSimpleTree; procedure NotifyContextWrong; procedure Cleanup; override; {* Функция очистки полей объекта. } public class function Make(const aValue: InevPara): IevReq; reintroduce; constructor Create(const aPara: InevPara); override; end;//TevReq implementation uses l3ImplUses , OvcConst , evControlParaConst , l3String , k2Tags , evButtonControl , evDropCalendarControl , evDropCombo , evLabel , evSimpleEdit , evMemoEdit , evEmailEdit , evPhoneEdit , SysUtils , nevFacade , evControlParaTools {$If Defined(k2ForEditor)} , evParaTools {$IfEnd} // Defined(k2ForEditor) , l3InterfacesMisc , l3Date , l3Bits , Table_Const , ReqRow_Const , ControlPara_Const , ControlsBlock_Const {$If Defined(k2ForEditor)} , evReqRowImplementation {$IfEnd} // Defined(k2ForEditor) //#UC START# *48D3BD0A02D7impl_uses* //#UC END# *48D3BD0A02D7impl_uses* ; class function TevReq.Make(const aValue: InevPara): IevReq; var l_Inst : TevReq; begin l_Inst := Create(aValue); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TevReq.Make function TevReq.AddValue(const aView: InevView; const aControl: IevEditorControl; const aPara: InevPara = nil; ToModel: Boolean = False; anAdd: Boolean = False): Boolean; {* Добавление нового поля в реквизит. aControl - виджет (поле или любой виджет возле поля), ToModel: только добавляем в модель aPara } //#UC START# *48D3CD560338_48D3BD0A02D7_var* var i : Integer; l_Count : Integer; l_Empty : Boolean; l_HasEmpty : Boolean; l_Para : InevPara; l_Field : IevEditorControlField; l_Button : IevEditorControlButton; l_StateBtn : IevEditorStateButton; l_TreeCont : IevEditorFieldWithTree; l_NodeIndex : Integer; l_NewField : IevEditorControlField; l_OldField : IevEditorControlField; //#UC END# *48D3CD560338_48D3BD0A02D7_var* begin //#UC START# *48D3CD560338_48D3BD0A02D7_impl* l_Count := f_FieldsList.Count - 1; l_NodeIndex := -1; l_HasEmpty := False; Result := False; if not ToModel then//если просто добавляем в модель, то никаких действий не производим begin i := l_Count; while i >= 0 do begin l_Field := f_FieldsList[i]; l_Empty := l_Field.IsFieldEmpty; if l_Empty and (l_Count > 0) and (i <> l_Count) then begin DeleteValue(aView, l_Field); Dec(l_Count); l_Empty := False; end;//if l_Empty and ... if l_Empty then l_HasEmpty := True; Dec(i); end;//while i >= 0 do... end;//if ToModel then... if (not l_HasEmpty and (aControl <> nil)) or ToModel then begin if not ToModel then begin l_Para := aControl.Para; Get_QueryCard.InsertRowMode := True; //Может сработать TextChange при очистке полей try TevReqRowImplementation.Make(aView, l_Para.MakePoint.PointToTypedParent(k2_typTable), l_Para.DocumentContainer.Processor).InsertRows(1, True); finally Get_QueryCard.InsertRowMode := False; end; l_Para := l_Para.MakePoint.PointToTypedParent(k2_typReqRow).Obj.AsPara; // - смещаемся к строке таблицы InitModel(l_Para.Next, True, -1, -1); l_NewField := LastField; l_OldField := f_FieldsList[f_FieldsList.Count - 2]; end//if not ToModel then else begin for i := 0 to aPara.AsObject.ChildrenCount - 1 do if TevControlType(aPara.AsObject.Child[i].Child[0].IntA[k2_tiType]) = ev_ctCombo then begin with aPara.AsObject.Child[i].Child[0] do if IsValid and (IntA[k2_tiNodeVisibleIndex] <> -1) then l_NodeIndex := IntA[k2_tiNodeVisibleIndex]; Break; end; l_OldField := aControl.Field; if anAdd then InitModel(aPara, True, -1, -1) else InitModel(aPara, True, f_FieldsList.IndexOf(l_OldField), f_ControlsList.IndexOf(aControl)); if not aPara.AsObject.Child[i].Child[0].QT(IevEditorControlField, l_NewField) then Assert(false); end;// else if not ToModel then l_Button := l_NewField.FindButton(ev_btLogical); if Supports(l_Button, IevEditorStateButton, l_StateBtn) then l_StateBtn.CurrentIndex := l_StateBtn.ImageIndex + Self.Get_DefStateIndex; if ToModel and Supports(l_NewField, IevEditorFieldWithTree, l_TreeCont) then if l_NodeIndex > -1 then l_TreeCont.SetNodeByIndex(l_NodeIndex); UpdateState(l_OldField, nil); UpdateState(l_NewField, nil); Result := True; end;//if (not l_HasEmpty and (aControl <> nil)) or ToModel then... //#UC END# *48D3CD560338_48D3BD0A02D7_impl* end;//TevReq.AddValue function TevReq.DeleteValue(const aView: InevView; const aControl: IevEditorControl = nil; ToModel: Boolean = False): Integer; {* Удаление поля из реквизита. Возвращает индекс поля вставшего вместо удаленного } //#UC START# *48D3CD950327_48D3BD0A02D7_var* var i : Integer; l_Count : Integer; l_FirstIdx : Integer; l_LastIdx : Integer; l_Field : IevEditorControlField; l_NewField : IevEditorControlField; l_TreeCont : IevEditorFieldWithTree; l_ML : IevModelListener; //#UC END# *48D3CD950327_48D3BD0A02D7_var* begin //#UC START# *48D3CD950327_48D3BD0A02D7_impl* Get_QueryCard.ClearUpper; l_Count := f_FieldsList.Count; if (l_Count = 1) or ((l_Count = 2) and f_FieldsList[0].HasOtherField) then //Для единичного атрибута только чистим текст begin l_Field := f_FieldsList[0]; try l_Field.ClearText; UpdateState(l_Field, nil); finally l_Field := nil; end; Result := 0; end//if l_Count = 1 then... else begin try Get_QueryCard.BeforeDelete; if aControl <> nil then //Если что-то передали, то используем... begin if Supports(aControl, IevEditorControlField, l_Field) then //Виджет, который передали - поле редактора //l_Field.ClearText закомментировал в связи с [$274843876] else l_Field := aControl.Field; end else//Если - нет, то удалим последнее поле l_Field := LastField; Assert(l_Field <> nil, 'Не нашли связанное с кнопкой поле! '); //Удалим строку на экране (поле и кнопки). if Supports(l_Field, IevEditorFieldWithTree, l_TreeCont) then if l_TreeCont.Value <> nil then l_Field.Para.AsObject.IntA[k2_tiNodeVisibleIndex] := l_TreeCont.GetNodeIndex(l_TreeCont.Value) else l_Field.Para.AsObject.IntA[k2_tiNodeVisibleIndex] := -1 else l_Field.Para.AsObject.IntA[k2_tiNodeVisibleIndex] := -1; if not ToModel then TevReqRowImplementation.Make(aView, l_Field.Para.MakePoint.PointToTypedParent(k2_typTable), l_Field.Para.DocumentContainer.Processor).DeleteRow; //Теперь удалим все связи с дочерними объектами Result := f_FieldsList.Remove(l_Field); l_FirstIdx := f_ControlsList.IndexOf(l_Field.ChildList.First); l_LastIdx := f_ControlsList.IndexOf(l_Field.ChildList.Last); for i := l_LastIdx downto l_FirstIdx do f_ControlsList.Delete(i); if Result = f_FieldsList.Count then Dec(Result); l_NewField := f_FieldsList[Result]; try UpdateState(l_NewField, nil); finally l_NewField := nil; end; finally l_Field := nil; end; end;//else if l_Count = 1 then... {$If not Defined(Admin)} // http://mdp.garant.ru/pages/viewpage.action?pageId=493858212 l_ML := Get_ModelListener; if (l_ML <> nil) then l_ML.TextChange; {$ifend} //#UC END# *48D3CD950327_48D3BD0A02D7_impl* end;//TevReq.DeleteValue function TevReq.GetControlClass(aControlType: TevControlType): RevControlClass; //#UC START# *48D3CEA103E3_48D3BD0A02D7_var* //#UC END# *48D3CEA103E3_48D3BD0A02D7_var* begin //#UC START# *48D3CEA103E3_48D3BD0A02D7_impl* case aControlType of ev_ctButton, ev_ctStateButton : Result := TevButtonControl; ev_ctCalEdit : Result := TevDropCalendarControl; ev_ctCombo : Result := TevDropCombo; ev_ctLabel : Result := TevLabel; ev_ctEdit : Result := TevSimpleEdit; ev_ctMemoEdit : Result := TevMemoEdit; ev_ctEmailEdit : Result := TevEmailEdit; ev_ctPhoneEdit : Result := TevPhoneEdit else Result := TevControl; end;//case aControlType //#UC END# *48D3CEA103E3_48D3BD0A02D7_impl* end;//TevReq.GetControlClass function TevReq.CanVisibleLogicBtn: Boolean; //#UC START# *48D3D1C10394_48D3BD0A02D7_var* //#UC END# *48D3D1C10394_48D3BD0A02D7_var* begin //#UC START# *48D3D1C10394_48D3BD0A02D7_impl* Result := Para.AsObject.HasSubAtom(k2_tiOperations); //#UC END# *48D3D1C10394_48D3BD0A02D7_impl* end;//TevReq.CanVisibleLogicBtn function TevReq.LogicBtnEnabled: Boolean; //#UC START# *48D3D1E8007E_48D3BD0A02D7_var* //#UC END# *48D3D1E8007E_48D3BD0A02D7_var* begin //#UC START# *48D3D1E8007E_48D3BD0A02D7_impl* Result := (l3BitCountF(Para.AsObject.IntA[k2_tiOperations]) > 1); //#UC END# *48D3D1E8007E_48D3BD0A02D7_impl* end;//TevReq.LogicBtnEnabled procedure TevReq.KeyAction(aCmd: Word); {* "Внешняя" обработка команды. } //#UC START# *47CD666202DD_48D3BD0A02D7_var* var ML : IevModelListener; //#UC END# *47CD666202DD_48D3BD0A02D7_var* begin //#UC START# *47CD666202DD_48D3BD0A02D7_impl* if (aCmd = ccActionItem) then begin ML := Get_ModelListener; if (ML <> nil) then ML.EnterPressed; end; //#UC END# *47CD666202DD_48D3BD0A02D7_impl* end;//TevReq.KeyAction function TevReq.AnalyzeString(const aValue: Il3CString; out aRslt: Il3CString): Boolean; //#UC START# *47CD666F01DC_48D3BD0A02D7_var* var ML : IevModelListener; //#UC END# *47CD666F01DC_48D3BD0A02D7_var* begin //#UC START# *47CD666F01DC_48D3BD0A02D7_impl* ML := Get_ModelListener; if (ML <> nil) then Result := ML.AnalyzeString(aValue, aRslt) else Result := False; //#UC END# *47CD666F01DC_48D3BD0A02D7_impl* end;//TevReq.AnalyzeString procedure TevReq.TextChange(const aView: InevView); {* Обработчик события изменения текста. } //#UC START# *47CD668303E2_48D3BD0A02D7_var* var ML : IevModelListener; //#UC END# *47CD668303E2_48D3BD0A02D7_var* begin //#UC START# *47CD668303E2_48D3BD0A02D7_impl* ML := Get_ModelListener; if ML <> nil then ML.TextChange; //#UC END# *47CD668303E2_48D3BD0A02D7_impl* end;//TevReq.TextChange procedure TevReq.RememberState(const aControl: IevCustomEditorControl); {* Запомнить состояние контрола для всплывающего меню. } //#UC START# *47CD669103DE_48D3BD0A02D7_var* //#UC END# *47CD669103DE_48D3BD0A02D7_var* begin //#UC START# *47CD669103DE_48D3BD0A02D7_impl* Get_QueryCard.RememberState(aControl); //#UC END# *47CD669103DE_48D3BD0A02D7_impl* end;//TevReq.RememberState function TevReq.GetNextVisible(const aControl: IevEditorControl; OnlyFields: Boolean; out anIsLastField: Boolean): IevEditorControl; {* Возвращает следующий видимый контрол. } //#UC START# *47CD66A6009A_48D3BD0A02D7_var* var l_Index : Integer; l_Control : IevEditorControl; //#UC END# *47CD66A6009A_48D3BD0A02D7_var* begin //#UC START# *47CD66A6009A_48D3BD0A02D7_impl* Result := nil; anIsLastField := (f_ControlsList.Last = aControl); if not anIsLastField then begin l_Index := f_ControlsList.IndexOf(aControl); Inc(l_Index); while (l_Index < f_ControlsList.Count) do begin l_Control := f_ControlsList[l_Index]; try if l_Control.Visible and l_Control.Enabled then if not OnlyFields or (l_Control.ControlType in evEditControls) then begin Result := l_Control; Break; end; finally l_Control := nil; end; Inc(l_Index); end; if Result = nil then anIsLastField := True; end; //#UC END# *47CD66A6009A_48D3BD0A02D7_impl* end;//TevReq.GetNextVisible function TevReq.GetFirstVisible(OnlyFields: Boolean): IevEditorControl; {* Возвращает первый видимый контрол для реквизита. } //#UC START# *47CD66C1034C_48D3BD0A02D7_var* var i : Integer; l_Count : Integer; l_Field : IevEditorControl; //#UC END# *47CD66C1034C_48D3BD0A02D7_var* begin //#UC START# *47CD66C1034C_48D3BD0A02D7_impl* l_Count := f_ControlsList.Count - 1; for i := 0 to l_Count do begin l_Field := f_ControlsList[i]; try if l_Field.Visible and l_Field.Enabled then if not OnlyFields or (l_Field.ControlType in evEditControls) then begin Result := l_Field; Break; end; finally l_Field := nil; end; end; //#UC END# *47CD66C1034C_48D3BD0A02D7_impl* end;//TevReq.GetFirstVisible function TevReq.GetPrevVisible(const aControl: IevEditorControl; OnlyFields: Boolean; out anIsFirstField: Boolean): IevEditorControl; {* Возвращает следующий видимый контрол. } //#UC START# *47CD66D00085_48D3BD0A02D7_var* var l_Index : Integer; l_Control : IevEditorControl; //#UC END# *47CD66D00085_48D3BD0A02D7_var* begin //#UC START# *47CD66D00085_48D3BD0A02D7_impl* Result := nil; anIsFirstField := (f_ControlsList.First = aControl); if not anIsFirstField then begin l_Index := f_ControlsList.IndexOf(aControl); Dec(l_Index); while (l_Index >= 0) do begin l_Control := f_ControlsList[l_Index]; try if l_Control.Visible and l_Control.Enabled then if not OnlyFields or (l_Control.ControlType in evEditControls) then begin Result := l_Control; Break; end; finally l_Control := nil; end; Dec(l_Index); end; if Result = nil then anIsFirstField := True; end; //#UC END# *47CD66D00085_48D3BD0A02D7_impl* end;//TevReq.GetPrevVisible function TevReq.GetLastVisible(OnlyFields: Boolean): IevEditorControl; {* Возвращает последний видимый контрол. } //#UC START# *47CD66E90124_48D3BD0A02D7_var* var i : Integer; l_Count : Integer; l_Field : IevEditorControl; //#UC END# *47CD66E90124_48D3BD0A02D7_var* begin //#UC START# *47CD66E90124_48D3BD0A02D7_impl* l_Count := f_ControlsList.Count - 1; for i := l_Count downto 0 do begin l_Field := f_ControlsList[i]; try if l_Field.Visible and l_Field.Enabled then if not OnlyFields or (l_Field.ControlType in evEditControls) then begin Result := l_Field; Break; end; finally l_Field := nil; end; end; //#UC END# *47CD66E90124_48D3BD0A02D7_impl* end;//TevReq.GetLastVisible function TevReq.GetHint(var aValue: Il3CString; const aControl: IevEditorControl): Boolean; {* Получить хинт для контрола. } //#UC START# *47CD66F50173_48D3BD0A02D7_var* var ML : IevModelListener; //#UC END# *47CD66F50173_48D3BD0A02D7_var* begin //#UC START# *47CD66F50173_48D3BD0A02D7_impl* {$IFDEF TEST_MODEL} if aControl.ControlType in evEditControls then begin aValue := Get_ReqName; Result := True; end else Result := False; {$ELSE} if (aControl.ControlType = ev_ctCalEdit) then begin aValue := nil; Result := True; end//aControl.ControlType = ev_ctCalEdit else begin ML := Get_ModelListener; if ML <> nil then begin aValue := ML.GetHint(aControl); Result := not l3IsNil(aValue); end else Result := False; end; {$ENDIF} //#UC END# *47CD66F50173_48D3BD0A02D7_impl* end;//TevReq.GetHint function TevReq.IsRequired: Boolean; {* Обязательное поле (должно обязательно содержать значение). } //#UC START# *47CD670E02FC_48D3BD0A02D7_var* //#UC END# *47CD670E02FC_48D3BD0A02D7_var* begin //#UC START# *47CD670E02FC_48D3BD0A02D7_impl* Result := Para.AsObject.BoolA[k2_tiRequired]; //#UC END# *47CD670E02FC_48D3BD0A02D7_impl* end;//TevReq.IsRequired function TevReq.IsEmpty: Boolean; {* Проверяет, является ли реквизит пустым. } //#UC START# *47CD671F01FE_48D3BD0A02D7_var* var ML : IevModelListener; //#UC END# *47CD671F01FE_48D3BD0A02D7_var* begin //#UC START# *47CD671F01FE_48D3BD0A02D7_impl* ML := Get_ModelListener; if (ML <> nil) then Result := ML.IsEditEmpty else Result := True; //#UC END# *47CD671F01FE_48D3BD0A02D7_impl* end;//TevReq.IsEmpty function TevReq.FieldsCount: Integer; {* Количество контролов (полей редактора) в реквизите. } //#UC START# *47CD672E02A0_48D3BD0A02D7_var* //#UC END# *47CD672E02A0_48D3BD0A02D7_var* begin //#UC START# *47CD672E02A0_48D3BD0A02D7_impl* Result := f_FieldsList.Count; //#UC END# *47CD672E02A0_48D3BD0A02D7_impl* end;//TevReq.FieldsCount procedure TevReq.ButtonPressed(const aView: InevView; const aControl: IevEditorControl; aBtnType: TevButtonType); {* Обработка реакции на нажатие кнопки по её типу. } //#UC START# *47CD674100FC_48D3BD0A02D7_var* //#UC END# *47CD674100FC_48D3BD0A02D7_var* begin //#UC START# *47CD674100FC_48D3BD0A02D7_impl* case aBtnType of ev_btAdd : begin AddValue(aView, aControl); SetFocus(LastField); end; ev_btDelete: begin SetFocus(Get_Fields(DeleteValue(aView, aControl))); end; end; //#UC END# *47CD674100FC_48D3BD0A02D7_impl* end;//TevReq.ButtonPressed procedure TevReq.AfterSetText(const aField: IevEditorControlField); //#UC START# *47CD675402F3_48D3BD0A02D7_var* var ML : IevModelListener; //#UC END# *47CD675402F3_48D3BD0A02D7_var* begin //#UC START# *47CD675402F3_48D3BD0A02D7_impl* ML := Get_ModelListener; if ML <> nil then ML.AfterSetText(aField); //#UC END# *47CD675402F3_48D3BD0A02D7_impl* end;//TevReq.AfterSetText function TevReq.AddField(const aView: InevView; NeedSetFocus: Boolean = False): IevEditorControlField; {* Добавление реквизита. } //#UC START# *47CD677302C2_48D3BD0A02D7_var* //#UC END# *47CD677302C2_48D3BD0A02D7_var* begin //#UC START# *47CD677302C2_48D3BD0A02D7_impl* if IsMulti and AddValue(aView, LastField) then begin Result := LastField; if NeedSetFocus then SetFocus(LastField); end else Result := nil; //#UC END# *47CD677302C2_48D3BD0A02D7_impl* end;//TevReq.AddField function TevReq.GetItemImage(Index: Integer; var aImages: InevImageList): Integer; {* Ручка для получения картинки для выпадающего дерева. } //#UC START# *47CD67820275_48D3BD0A02D7_var* var ML : IevModelListener; //#UC END# *47CD67820275_48D3BD0A02D7_var* begin //#UC START# *47CD67820275_48D3BD0A02D7_impl* ML := Get_ModelListener; if ML <> nil then Result := ML.GetImage(Index, aImages) else begin aImages := nil; Result := -1; end; //#UC END# *47CD67820275_48D3BD0A02D7_impl* end;//TevReq.GetItemImage procedure TevReq.DeleteField(const aView: InevView; const aControl: IevEditorControlField = nil; NeedFocus: Boolean = False); {* Удаление реквизита. } //#UC START# *47CD679F00D4_48D3BD0A02D7_var* var l_IDX: Integer; //#UC END# *47CD679F00D4_48D3BD0A02D7_var* begin //#UC START# *47CD679F00D4_48D3BD0A02D7_impl* l_IDX := DeleteValue(aView, aControl); if NeedFocus then SetFocus(Get_Fields(l_IDX)); //#UC END# *47CD679F00D4_48D3BD0A02D7_impl* end;//TevReq.DeleteField procedure TevReq.InsertToModel(const aView: InevView; const aControl: IevEditorControl; aChild: Tl3Variant; NeedFocus: Boolean = False; anAdd: Boolean = False); {* Добавление реквизита только в модель. } //#UC START# *47CD69A301F3_48D3BD0A02D7_var* var l_Para: InevPara; //#UC END# *47CD69A301F3_48D3BD0A02D7_var* begin //#UC START# *47CD69A301F3_48D3BD0A02D7_impl* if aChild.QT(InevPara, l_Para) then begin AddValue(aView, aControl, l_Para, True, anAdd); if NeedFocus then SetFocus(LastField); end; //#UC END# *47CD69A301F3_48D3BD0A02D7_impl* end;//TevReq.InsertToModel procedure TevReq.DeleteFromModel(const aView: InevView; const aControl: IevEditorControl; NeedFocus: Boolean = False); {* Удаление реквизита только из модели. } //#UC START# *47CD69CD0294_48D3BD0A02D7_var* var l_IDX: Integer; //#UC END# *47CD69CD0294_48D3BD0A02D7_var* begin //#UC START# *47CD69CD0294_48D3BD0A02D7_impl* l_IDX := DeleteValue(aView, aControl, True); if NeedFocus then SetFocus(Get_Fields(l_IDX)); //#UC END# *47CD69CD0294_48D3BD0A02D7_impl* end;//TevReq.DeleteFromModel procedure TevReq.InitModel(const aTag: InevPara; AddValues: Boolean; anIndexField: Integer; anIndexCtrl: Integer); {* Инициализация дочерних компонентов. } //#UC START# *47CD6E090090_48D3BD0A02D7_var* var l_ComponentList: TevEditorControlList; l_FirstEditField: IevEditorControlField; l_EditField: IevEditorControlField; function GetChildControl(const aChild: InevPara; Index: Integer): Boolean; var l_ControlType : TevControlType; l_Class : RevControlClass; l_ContTag : InevPara; l_ED : IevEditorControl; begin Result := True; l_ContTag := aChild.AsList[0]; //Одна ячека таблицы - один виджет try with l_ContTag do if AsObject.IsKindOf(k2_typControlPara) then begin if AsObject.Attr[k2_tiType].IsValid then l_ControlType := TevControlType(l_ContTag.AsObject.IntA[k2_tiType]) else l_ControlType := ev_ctLabel; if (l_ControlType <> ev_ctUnknown) then begin l_Class := GetControlClass(l_ControlType); Assert(l_Class <> TevControl, 'Используется неизвестный класс виджет!'); l_ED := l_Class.Make(l_ContTag); try if (l_ControlType in evEditControls) then begin if Supports(l_ED, IevEditorControlField, l_EditField) then begin if AddValues and (anIndexField > -1) then f_FieldsList.Insert(anIndexField, l_EditField) else f_FieldsList.Add(l_EditField); end;//Supports(l_ED, IevEditorControlField, l_FirstEditField) if (l_FirstEditField = nil) then begin if Assigned(l_EditField) then l_FirstEditField := l_EditField; end//l_FirstEditField = nil else begin l_ComponentList.Add(l_ED); l_FirstEditField.InitOtherField(l_ED); l_ED.Field := l_FirstEditField; end;//l_FirstEditField = nil end//l_ControlType in evEditControls else begin l_ComponentList.Add(l_ED); l_ED.Field := l_FirstEditField; {$IFDEF TEST_MODEL} l_ED.InitBoolProperty(k2_tiVisible, True);//Для режима отладки все виджеты должны быть видны {$ELSE} //Заплатка if (l_ED.ControlType = ev_ctButton) or (l_ED.ControlType = ev_ctStateButton) then l_ED.InitBoolProperty(k2_tiVisible, False); {$ENDIF TEST_MODEL} end;//l_ControlType in evEditControls if AddValues and (anIndexField > -1) then f_ControlsList.Insert(anIndexCtrl + Index, l_ED) else f_ControlsList.Add(l_ED); finally l_ED := nil; end;//try..finally end//if (l_ControlType <> ev_ctUnknown) then else l_ContTag.AsObject.BoolW[k2_tiEnabled, nil] := False; end;//if IsKindOf(k2_typControlBlock) finally l_ContTag := nil; end;//try..finally end;//GetChildLine var i : Integer; l_Count : Integer; l_Label : IevEditorControlLabel; //#UC END# *47CD6E090090_48D3BD0A02D7_var* begin //#UC START# *47CD6E090090_48D3BD0A02D7_impl* l_ComponentList := TevEditorControlList.Make; try with aTag do if AsObject.IsValid then AsList.IterateParaF(nevL2PIA(@GetChildControl)); Assert(l_FirstEditField <> nil, 'Нет ни одного поля редактора. '); if (l_FirstEditField = nil) then Exit; l_Count := l_ComponentList.Count - 1; for i := 0 to l_Count do l_ComponentList[i].Field := l_FirstEditField; l_FirstEditField.ChildList.AssignList(l_ComponentList); if AddValues then begin if Supports(l_FirstEditField.ChildList[0], IevEditorControlLabel, l_Label) then try l_Label.Caption := nil; l_Label.InitBoolProperty(k2_tiVisible, False); finally l_Label := nil; end;//trt..finally end//AddValues else if (l_FirstEditField.ChildList.Count <> 0) then l3Set(f_ReqCaption, l_FirstEditField.ChildList[0].Caption) finally l_FirstEditField := nil; l_EditField := nil; l3Free(l_ComponentList); end;//try..finally //#UC END# *47CD6E090090_48D3BD0A02D7_impl* end;//TevReq.InitModel function TevReq.CheckEdit(const aField: IevEditorControlField): Boolean; {* Проверка значения поля. } //#UC START# *47CD6E2403C9_48D3BD0A02D7_var* var ML : IevModelListener; //#UC END# *47CD6E2403C9_48D3BD0A02D7_var* begin //#UC START# *47CD6E2403C9_48D3BD0A02D7_impl* ML := Get_ModelListener; if ML <> nil then begin Result := ML.CheckValue(aField); //f_IsValid := Result; end else Result := False; //#UC END# *47CD6E2403C9_48D3BD0A02D7_impl* end;//TevReq.CheckEdit procedure TevReq.UpdateState(const aField: IevEditorControlField; const anOp: InevOp); {* Обновить состояния поля и кнопок, вокруг контрола. } //#UC START# *47CD6E3401B9_48D3BD0A02D7_var* var i : Integer; l_Index : Integer; l_Count : Integer; l_Cal : IevEditorCalendarField; l_Field : IevEditorControlField; l_BTNControl : IevEditorControlButton; l_LBLControl : IevEditorControlLabel; //#UC END# *47CD6E3401B9_48D3BD0A02D7_var* begin //#UC START# *47CD6E3401B9_48D3BD0A02D7_impl* if Supports(aField, IevEditorCalendarField, l_Cal) then try if not l_Cal.IsStart then l_Cal.GetOtherField.QueryInterface(IevEditorControlField, l_Field) else l_Field := aField; finally l_Cal := nil; end else l_Field := aField; //Аккуратно со следующим кодом: для календаря в качестве массива полей может //использоваться массив поля "С:", а для проверки значений поле "По:" try l_Count := l_Field.ChildList.Count; l_Index := f_FieldsList.IndexOf(l_Field); for i := l_Count - 1 downto 0 do if Supports(l_Field.ChildList[i], IevEditorControlButton, l_BTNControl) then try {$IFNDEF TEST_MODEL} Case l_BTNControl.GetButtonType of ev_btDelete: l_BTNControl.Visible := (not aField.IsClear or (l_Index > 0)) and evIsSomeFieldFilled(aField.Req, true); ev_btAdd: l_BTNControl.Visible := CheckEdit(aField) and (l_Index = f_FieldsList.Count - 1) and not aField.IsFieldEmpty and IsMulti and aField.Valid; ev_btLogical: begin l_BTNControl.Visible := not aField.IsFieldEmpty and CanVisibleLogicBtn; if l_BTNControl.Visible then l_BTNControl.Enabled := LogicBtnEnabled; end;//ev_btLogical end;//l_BTNControl.GetButtonType {$ENDIF TEST_MODEL} finally l_BTNControl := nil; end else if (i = 0) and Supports(l_Field.ChildList[i], IevEditorControlLabel, l_LBLControl) then try if l_Index = 0 then begin l_LBLControl.RestoreCaption; l_LBLControl.Visible := True; end else l_LBLControl.Visible := False; finally l_LBLControl := nil; end; finally l_Field := nil; end; //#UC END# *47CD6E3401B9_48D3BD0A02D7_impl* end;//TevReq.UpdateState function TevReq.Get_ModelListener: IevModelListener; //#UC START# *47CD6E5E00F6_48D3BD0A02D7get_var* var l_QC : IevQueryCard; //#UC END# *47CD6E5E00F6_48D3BD0A02D7get_var* begin //#UC START# *47CD6E5E00F6_48D3BD0A02D7get_impl* l_QC := Get_QueryCard; {$IFNDEF TEST_MODEL} if (l_QC <> nil) AND (l_QC.AdapterModel <> nil) then Result := l_QC.AdapterModel.ModelListener(Self) else {$ENDIF TEST_MODEL} Result := nil; //#UC END# *47CD6E5E00F6_48D3BD0A02D7get_impl* end;//TevReq.Get_ModelListener function TevReq.Get_Fields(Index: Integer): IevEditorControlField; //#UC START# *47CD6E870081_48D3BD0A02D7get_var* //#UC END# *47CD6E870081_48D3BD0A02D7get_var* begin //#UC START# *47CD6E870081_48D3BD0A02D7get_impl* Result := f_FieldsList[Index]; //#UC END# *47CD6E870081_48D3BD0A02D7get_impl* end;//TevReq.Get_Fields function TevReq.Get_ReqName: Il3CString; //#UC START# *47CD6EB4017D_48D3BD0A02D7get_var* //#UC END# *47CD6EB4017D_48D3BD0A02D7get_var* begin //#UC START# *47CD6EB4017D_48D3BD0A02D7get_impl* Para.AsObject.Attr[k2_tiReqID].QI(Il3CString, Result); //#UC END# *47CD6EB4017D_48D3BD0A02D7get_impl* end;//TevReq.Get_ReqName function TevReq.Get_ReqCaption: Il3CString; //#UC START# *47CD6EC502B1_48D3BD0A02D7get_var* //#UC END# *47CD6EC502B1_48D3BD0A02D7get_var* begin //#UC START# *47CD6EC502B1_48D3BD0A02D7get_impl* if (f_ReqCaption = nil) then Result := nil else if not l3IOk(f_ReqCaption.QueryInterface(Il3CString, Result)) then Assert(false); //#UC END# *47CD6EC502B1_48D3BD0A02D7get_impl* end;//TevReq.Get_ReqCaption procedure TevReq.SetFocus(const aField: IevEditorControlField; aAtEnd: Boolean = False); {* Установить фокус. } //#UC START# *47CD6EE402F8_48D3BD0A02D7_var* //#UC END# *47CD6EE402F8_48D3BD0A02D7_var* begin //#UC START# *47CD6EE402F8_48D3BD0A02D7_impl* with Get_QueryCard do begin GetDocumentContainer.SetCursorToPara(aField.Para, aAtEnd, False); SetCurrPara(aField.Para); RememberState(aField); end;//with Get_QueryCard //#UC END# *47CD6EE402F8_48D3BD0A02D7_impl* end;//TevReq.SetFocus function TevReq.FirstField: IevEditorControlField; {* Возвращает первый контрол в списке. } //#UC START# *47CD6EF701E4_48D3BD0A02D7_var* //#UC END# *47CD6EF701E4_48D3BD0A02D7_var* begin //#UC START# *47CD6EF701E4_48D3BD0A02D7_impl* Result := f_FieldsList.First; //#UC END# *47CD6EF701E4_48D3BD0A02D7_impl* end;//TevReq.FirstField function TevReq.LastField: IevEditorControlField; {* Возвращает последний контрол в списке. } //#UC START# *47CD6F0502BD_48D3BD0A02D7_var* //#UC END# *47CD6F0502BD_48D3BD0A02D7_var* begin //#UC START# *47CD6F0502BD_48D3BD0A02D7_impl* Result := f_FieldsList.Last; //#UC END# *47CD6F0502BD_48D3BD0A02D7_impl* end;//TevReq.LastField function TevReq.Get_Group: IevQueryGroup; //#UC START# *47CD6F3B0317_48D3BD0A02D7get_var* var l_Group : Tl3Variant; //#UC END# *47CD6F3B0317_48D3BD0A02D7get_var* begin //#UC START# *47CD6F3B0317_48D3BD0A02D7get_impl* Result := nil; if (f_Group = nil) then if evInPara(Para.AsObject, k2_typControlsBlock, l_Group) then l_Group.SetRef(f_Group) else Exit; if (f_Group <> nil) AND f_Group.IsValid then f_Group.QT(IevQueryGroup, Result) // - хранение f_Group необходимо - это ЗАПЛАТКА, т.к. строка может удалится из таблицы, но все еще хранится в реквизите else Result := nil; //#UC END# *47CD6F3B0317_48D3BD0A02D7get_impl* end;//TevReq.Get_Group function TevReq.Get_QueryCard: IevQueryCard; //#UC START# *47CD6F770022_48D3BD0A02D7get_var* var l_QG : IevQueryGroup; //#UC END# *47CD6F770022_48D3BD0A02D7get_var* begin //#UC START# *47CD6F770022_48D3BD0A02D7get_impl* l_QG := Get_Group; if (l_QG <> nil) then Result := l_QG.QueryCard else Result := nil; //#UC END# *47CD6F770022_48D3BD0A02D7get_impl* end;//TevReq.Get_QueryCard procedure TevReq.ClearLogicValue; //#UC START# *47CD74B90340_48D3BD0A02D7_var* var l_Button : IevEditorControlButton; l_StateBtn : IevEditorStateButton; //#UC END# *47CD74B90340_48D3BD0A02D7_var* begin //#UC START# *47CD74B90340_48D3BD0A02D7_impl* l_Button := FirstField.FindButton(ev_btLogical); if l_Button <> nil then if Supports(l_Button, IevEditorStateButton, l_StateBtn) then l_StateBtn.CurrentIndex := l_StateBtn.ImageIndex + Self.Get_DefStateIndex; //#UC END# *47CD74B90340_48D3BD0A02D7_impl* end;//TevReq.ClearLogicValue procedure TevReq.EscPressed(const aField: IevEditorFieldWithTree); //#UC START# *47CD74C203DC_48D3BD0A02D7_var* var ML : IevAdapterModel; //#UC END# *47CD74C203DC_48D3BD0A02D7_var* begin //#UC START# *47CD74C203DC_48D3BD0A02D7_impl* if (Get_QueryCard = nil) then ML := nil else ML := Get_QueryCard.AdapterModel; if (ML <> nil) then ML.EscPressed(aField); //#UC END# *47CD74C203DC_48D3BD0A02D7_impl* end;//TevReq.EscPressed function TevReq.NeedAsterisk: Boolean; {* Нужно ли проверять значение '*' в тексте. } //#UC START# *47CD74D802DF_48D3BD0A02D7_var* //#UC END# *47CD74D802DF_48D3BD0A02D7_var* begin //#UC START# *47CD74D802DF_48D3BD0A02D7_impl* Result := Para.AsObject.BoolA[k2_tiNumList]; //#UC END# *47CD74D802DF_48D3BD0A02D7_impl* end;//TevReq.NeedAsterisk function TevReq.GetTreeFromAdapter: InevSimpleTree; {* Получает дерево с адаптера. } //#UC START# *47CD74ED0166_48D3BD0A02D7_var* var ML : IevAdapterModel; //#UC END# *47CD74ED0166_48D3BD0A02D7_var* begin //#UC START# *47CD74ED0166_48D3BD0A02D7_impl* if (Get_QueryCard = nil) then ML := nil else ML := Get_QueryCard.AdapterModel; if (ML <> nil) then Result := ML.GetTreeFromAdapter(Get_ReqName) else Result := nil; //#UC END# *47CD74ED0166_48D3BD0A02D7_impl* end;//TevReq.GetTreeFromAdapter function TevReq.IsMulti: Boolean; {* Признак реквизита с несколькими значениями. } //#UC START# *47CD750202FD_48D3BD0A02D7_var* //#UC END# *47CD750202FD_48D3BD0A02D7_var* begin //#UC START# *47CD750202FD_48D3BD0A02D7_impl* Result := Para.AsObject.BoolA[k2_tiMulty]; //#UC END# *47CD750202FD_48D3BD0A02D7_impl* end;//TevReq.IsMulti procedure TevReq.HyperLinkClick; {* Щелчок по гиперссылке. } //#UC START# *47CD75160008_48D3BD0A02D7_var* //#UC END# *47CD75160008_48D3BD0A02D7_var* begin //#UC START# *47CD75160008_48D3BD0A02D7_impl* Get_ModelListener.HyperLinkClick; //#UC END# *47CD75160008_48D3BD0A02D7_impl* end;//TevReq.HyperLinkClick function TevReq.Get_DefStateIndex: Integer; //#UC START# *47CD75890059_48D3BD0A02D7get_var* //#UC END# *47CD75890059_48D3BD0A02D7get_var* begin //#UC START# *47CD75890059_48D3BD0A02D7get_impl* Result := Para.AsObject.IntA[k2_tiStateIndex]; //#UC END# *47CD75890059_48D3BD0A02D7get_impl* end;//TevReq.Get_DefStateIndex procedure TevReq.Set_DefStateIndex(aValue: Integer); //#UC START# *47CD75890059_48D3BD0A02D7set_var* //#UC END# *47CD75890059_48D3BD0A02D7set_var* begin //#UC START# *47CD75890059_48D3BD0A02D7set_impl* Para.AsObject.IntA[k2_tiStateIndex] := aValue; //#UC END# *47CD75890059_48D3BD0A02D7set_impl* end;//TevReq.Set_DefStateIndex function TevReq.IsContext: Boolean; {* Признак того, что реквизит является конекстом. } //#UC START# *47CD759702B8_48D3BD0A02D7_var* //#UC END# *47CD759702B8_48D3BD0A02D7_var* begin //#UC START# *47CD759702B8_48D3BD0A02D7_impl* Result := TevReqKind(Para.AsObject.IntA[k2_tiReqKind]) = ev_rkContext; //#UC END# *47CD759702B8_48D3BD0A02D7_impl* end;//TevReq.IsContext function TevReq.GetNode(anIndex: Integer): InevSimpleNode; {* Получить узел выпадающего дерева по номеру поля. } //#UC START# *47CD75A9029C_48D3BD0A02D7_var* //#UC END# *47CD75A9029C_48D3BD0A02D7_var* begin //#UC START# *47CD75A9029C_48D3BD0A02D7_impl* Result := Get_QueryCard.GetNode(anIndex); //#UC END# *47CD75A9029C_48D3BD0A02D7_impl* end;//TevReq.GetNode function TevReq.Get_HistoryList: Il3StringsEx; //#UC START# *47CD75C30157_48D3BD0A02D7get_var* {$If not Defined(Admin) AND not Defined(Monitorings)} var ML : IevAdapterModel; {$IfEnd} //#UC END# *47CD75C30157_48D3BD0A02D7get_var* begin //#UC START# *47CD75C30157_48D3BD0A02D7get_impl* {$If not Defined(Admin) AND not Defined(Monitorings)} if (Get_QueryCard = nil) then ML := nil else ML := Get_QueryCard.AdapterModel; if ML <> nil then Result := ML.HistoryList else Result := nil; {$Else} Result := nil; {$IfEnd} //#UC END# *47CD75C30157_48D3BD0A02D7get_impl* end;//TevReq.Get_HistoryList function TevReq.Get_StartDate: TDateTime; //#UC START# *47CD76B60268_48D3BD0A02D7get_var* var l_Cal: IevEditorCalendarField; //#UC END# *47CD76B60268_48D3BD0A02D7get_var* begin //#UC START# *47CD76B60268_48D3BD0A02D7get_impl* if Supports(FirstField, IevEditorCalendarField, l_Cal) then try Result := l_Cal.aDate; finally l_Cal := nil; end else Result := NullDate; //#UC END# *47CD76B60268_48D3BD0A02D7get_impl* end;//TevReq.Get_StartDate procedure TevReq.Set_StartDate(aValue: TDateTime); //#UC START# *47CD76B60268_48D3BD0A02D7set_var* var l_Cal: IevEditorCalendarField; //#UC END# *47CD76B60268_48D3BD0A02D7set_var* begin //#UC START# *47CD76B60268_48D3BD0A02D7set_impl* if Supports(FirstField, IevEditorCalendarField, l_Cal) then try l_Cal.aDate := aValue; finally l_Cal := nil; end; //#UC END# *47CD76B60268_48D3BD0A02D7set_impl* end;//TevReq.Set_StartDate function TevReq.Get_EndDate: TDateTime; //#UC START# *47CD76C40235_48D3BD0A02D7get_var* var l_Cal: IevEditorCalendarField; //#UC END# *47CD76C40235_48D3BD0A02D7get_var* begin //#UC START# *47CD76C40235_48D3BD0A02D7get_impl* if Supports(FirstField, IevEditorCalendarField, l_Cal) then try Result := l_Cal.GetOtherField.aDate; finally l_Cal := nil; end else Result := NullDate; //#UC END# *47CD76C40235_48D3BD0A02D7get_impl* end;//TevReq.Get_EndDate procedure TevReq.Set_EndDate(aValue: TDateTime); //#UC START# *47CD76C40235_48D3BD0A02D7set_var* var l_Cal: IevEditorCalendarField; //#UC END# *47CD76C40235_48D3BD0A02D7set_var* begin //#UC START# *47CD76C40235_48D3BD0A02D7set_impl* if Supports(FirstField, IevEditorCalendarField, l_Cal) then try l_Cal.GetOtherField.aDate := aValue; finally l_Cal := nil; end; //#UC END# *47CD76C40235_48D3BD0A02D7set_impl* end;//TevReq.Set_EndDate function TevReq.Get_Code: Il3CString; //#UC START# *47CD76DE0101_48D3BD0A02D7get_var* var l_Field: IevEditorPhoneField; //#UC END# *47CD76DE0101_48D3BD0A02D7get_var* begin //#UC START# *47CD76DE0101_48D3BD0A02D7get_impl* if Supports(FirstField, IevEditorPhoneField, l_Field) then try Result := l_Field.Text; finally l_Field := nil; end else Result := nil; //#UC END# *47CD76DE0101_48D3BD0A02D7get_impl* end;//TevReq.Get_Code procedure TevReq.Set_Code(const aValue: Il3CString); //#UC START# *47CD76DE0101_48D3BD0A02D7set_var* var l_Field: IevEditorPhoneField; //#UC END# *47CD76DE0101_48D3BD0A02D7set_var* begin //#UC START# *47CD76DE0101_48D3BD0A02D7set_impl* if Supports(FirstField, IevEditorPhoneField, l_Field) then try l_Field.Text := aValue; finally l_Field := nil; end; //#UC END# *47CD76DE0101_48D3BD0A02D7set_impl* end;//TevReq.Set_Code function TevReq.Get_Number: Il3CString; //#UC START# *47CD76E9008F_48D3BD0A02D7get_var* var l_Field: IevEditorPhoneField; //#UC END# *47CD76E9008F_48D3BD0A02D7get_var* begin //#UC START# *47CD76E9008F_48D3BD0A02D7get_impl* if Supports(FirstField, IevEditorPhoneField, l_Field) then try Result := l_Field.GetOtherField.Text; finally l_Field := nil; end else Result := nil; //#UC END# *47CD76E9008F_48D3BD0A02D7get_impl* end;//TevReq.Get_Number procedure TevReq.Set_Number(const aValue: Il3CString); //#UC START# *47CD76E9008F_48D3BD0A02D7set_var* var l_Field: IevEditorPhoneField; //#UC END# *47CD76E9008F_48D3BD0A02D7set_var* begin //#UC START# *47CD76E9008F_48D3BD0A02D7set_impl* if Supports(FirstField, IevEditorPhoneField, l_Field) then try l_Field.GetOtherField.Text := aValue; finally l_Field := nil; end; //#UC END# *47CD76E9008F_48D3BD0A02D7set_impl* end;//TevReq.Set_Number function TevReq.GetPromptTreeFromAdapter: InevSimpleTree; //#UC START# *486C76EE0211_48D3BD0A02D7_var* var ML : IevAdapterModel; //#UC END# *486C76EE0211_48D3BD0A02D7_var* begin //#UC START# *486C76EE0211_48D3BD0A02D7_impl* if (Get_QueryCard = nil) then ML := nil else ML := Get_QueryCard.AdapterModel; if (ML <> nil) then Result := ML.GetPromptTreeFromAdapter else Result := nil; //#UC END# *486C76EE0211_48D3BD0A02D7_impl* end;//TevReq.GetPromptTreeFromAdapter procedure TevReq.NotifyContextWrong; //#UC START# *4885BB8A005E_48D3BD0A02D7_var* var ML : IevAdapterModel; //#UC END# *4885BB8A005E_48D3BD0A02D7_var* begin //#UC START# *4885BB8A005E_48D3BD0A02D7_impl* if (Get_QueryCard = nil) then ML := nil else ML := Get_QueryCard.AdapterModel; if (ML <> nil) then ML.NotifyContextWrong; //#UC END# *4885BB8A005E_48D3BD0A02D7_impl* end;//TevReq.NotifyContextWrong procedure TevReq.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48D3BD0A02D7_var* var l_Index : Integer; l_Row : Integer; l_Cleared : Boolean; //#UC END# *479731C50290_48D3BD0A02D7_var* begin //#UC START# *479731C50290_48D3BD0A02D7_impl* l_Cleared := false; if (Para <> nil) and Para.AsObject.IsValid then begin with Para.AsObject.Owner do if IsValid then begin l_Cleared := true; // - здесь вычищаем ссылку на данный реквизит из всех строк таблицы for l_Index := 0 to Pred(ChildrenCount) do with Child[l_Index] do if HasSubAtom(k2_tiModelControl) then // - проверка, чтобы в WevReqRow.GetAtomData не попадать if l3IEQ(Self, IUnknown(IntA[k2_tiModelControl])) then AttrW[k2_tiModelControl, nil] := nil; end;//IsValid end;//Para <> nil.. if not l_Cleared AND (f_Group <> nil) then begin // - это очистка на тот случай когда держим уже удаленный параграф - и у него уже нет Owner'а with f_Group do for l_Index := 0 to Pred(ChildrenCount) do with Child[l_Index] do for l_Row := 0 to Pred(ChildrenCount) do with Child[l_Row] do if HasSubAtom(k2_tiModelControl) then // - проверка, чтобы в WevReqRow.GetAtomData не попадать if l3IEQ(Self, IUnknown(IntA[k2_tiModelControl])) then AttrW[k2_tiModelControl, nil] := nil; end;//not l_Cleared FreeAndNil(f_Group); l3Free(f_ReqCaption); l3Free(f_ControlsList); l3Free(f_FieldsList); inherited; //#UC END# *479731C50290_48D3BD0A02D7_impl* end;//TevReq.Cleanup constructor TevReq.Create(const aPara: InevPara); //#UC START# *47CFE07602FE_48D3BD0A02D7_var* //#UC END# *47CFE07602FE_48D3BD0A02D7_var* begin //#UC START# *47CFE07602FE_48D3BD0A02D7_impl* inherited; f_FieldsList := TevEditorControlFieldList.Make; f_ControlsList := TevEditorControlList.Make; InitModel(aPara, False, -1, -1); aPara.AsObject.IntA[k2_tiModelControl] := Integer(IevReq(Self)); //#UC END# *47CFE07602FE_48D3BD0A02D7_impl* end;//TevReq.Create end.
unit proses_user_program; interface uses crt, tipe_data, konversi, proses_data, proses_buku; procedure Riwayat (var H : tabPinjam ; var B : TabBuku ; var active_user : tuser ); (*Procedure ini berfungsi untuk melihat riwayat peminjaman seorang user*) procedure Statistik (var U : TabUser; var B : TabBuku; var active_user : tuser); (*Procedure ini berfungsi untuk melihat statistik perpustakaan*) procedure cariAnggota (var array_user : tabUser; var active_user : tuser); (*Procedure ini mencari anggota perpustakaan berdasarkan keyword username*) procedure exiting_program(var array_buku : tabBuku; var array_user : tabUser; var array_pinjam : tabPinjam; var array_kembali : tabKembali; var array_hilang : tabHilang; var nama_file_kembali, nama_file_pinjam, nama_file_user, nama_file_buku, nama_file_hilang: string; var willExit,isLogin,isSave : boolean ); (*Procedure ini berfungsi untuk keluar dari program dan menyimpan data*) procedure registerAnggota( var array_user : tabUser; var active_user : tuser; var isSave: Boolean); (*Procedure ini berfungsi untuk mendaftarkan anggota baru dan hanya dapat dilakukan oleh admin*) procedure loginAnggota(var array_user : tabUser; var nama_file_user:string; var active_user: tuser; var isLogin: boolean); (*Procedure ini beru=fungsi untuk anggota perpustakaan login ke sistem*) procedure tampilMenuBelumLogin(); (*Procedure ini menampilkan interface aplikasi perpustakaan sebelum login*) procedure tampilMenu(var role_active_user:string); (*Procedure ini menampilkan interface aplikasi ketika sedang ada yang login, bergantung pada*) procedure showHelp(var isLogin: boolean); (*Procedure ini menampilkan pilihan menu yang dapat diakses oleh user*) procedure logout(var array_buku : tabBuku; var array_user : tabUser; var array_pinjam : tabPinjam; var array_kembali : tabKembali; var array_hilang : tabHilang; var nama_file_kembali, nama_file_pinjam, nama_file_user, nama_file_buku, nama_file_hilang: string; var isSave, isLogin : Boolean); (*Procedure untuk keluar dari program*) implementation procedure Riwayat (var H : tabPinjam ; var B : TabBuku ; var active_user : tuser ); (*Procedure ini berfungsi untuk melihat riwayat peminjaman seorang user*) {Kamus Lokal} var U : string; i,j : integer; total : integer; begin if(active_user.role = 'pengunjung') then begin writeln(''); writeln('Fitur ini hanya dapat diakses oleh admin. Kontak admin terdekat.'); writeln(''); end else begin total := 0; // Input writeln(''); write('Masukkan username pengunjung: '); readln(U); writeln('Riwayat: '); // Menuliskan riwayat pinjam buku user sesuai ketentuan -- menggunakan pengulangan untuk menampilkan data for i:=1 to H.Neff do begin if (H.T[i].Username = U) then begin total := total +1; for j:=1 to B.Neff do begin if(H.T[i].ID_Buku = B.T[j].ID_Buku) then begin writeln(H.T[i].Tanggal_Peminjaman, ' | ',H.T[i].ID_Buku,' | ',B.T[j].Judul_Buku) end; end; end; end; if(total = 0) then writeln('Tidak ada data yang ditemukan.'); writeln(''); end; end; procedure Statistik (var U : TabUser; var B : TabBuku; var active_user : tuser); (*Procedure ini berfungsi untuk melihat statistik perpustakaan*) {Kamus Lokal} var i,admin,pengunjung,sastra,sains,manga,sejarah,programming : integer; begin if(active_user.role = 'pengunjung') then begin writeln(''); writeln('Fitur ini hanya dapat diakses oleh admin. Kontak admin terdekat.'); writeln(''); end else begin writeln(''); // menggunakan pengulangan untuk menghitung jumlah data admin := 0; pengunjung := 0; for i:=1 to U.Neff do begin if (U.T[i].Role = 'admin') then begin admin := admin + 1; end else if (U.T[i].Role = 'pengunjung') then begin pengunjung := pengunjung + 1; end; end; // menggunakan pengulangan untuk menghitung jumlah data sastra := 0; sains := 0; manga := 0; sejarah := 0; programming := 0; for i:=1 to B.Neff do // menggunakan pengulangan untuk menghitung jumlah data begin if (B.T[i].Kategori = 'sastra') then begin sastra := sastra + (B.T[i].Jumlah_Buku); end else if (B.T[i].Kategori = 'sains') then begin sains := sains + (B.T[i].Jumlah_Buku); end else if (B.T[i].Kategori = 'manga') then begin manga := manga + (B.T[i].Jumlah_Buku); end else if (B.T[i].Kategori = 'sejarah') then begin sejarah := sejarah + (B.T[i].Jumlah_Buku); end else if (B.T[i].Kategori = 'programming') then begin programming := programming + (B.T[i].Jumlah_Buku); end; end; writeln('Pengguna: '); writeln('Admin | ',admin); writeln('Pengunjung | ',pengunjung); writeln('Total | ',(admin+pengunjung)); writeln('Buku: '); writeln('Sastra | ',sastra); writeln('Sains | ',sains); writeln('Manga | ',manga); writeln('Sejarah | ',sejarah); writeln('Programming | ',programming); writeln('Total | ',(sastra+sains+manga+sejarah+programming)); writeln(''); end; end; procedure cariAnggota (var array_user : tabUser; var active_user : tuser); (*Procedure ini mencari anggota perpustakaan berdasarkan keyword username*) {Kamus Lokal} var isFound : Boolean; i : integer; keyword : string; begin if(active_user.role = 'pengunjung') then begin writeln(''); writeln('Fitur ini hanya dapat diakses oleh admin. Kontak admin terdekat.'); writeln(''); end else begin writeln(''); isFound := False; write('Masukkan username yang ingin dicari: '); readln(keyword); for i:= 1 to array_user.Neff do begin if (array_user.T[i].username = keyword) then begin writeln('Nama Anggota: ', array_user.T[i].nama); writeln('Alamat Anggota: ', array_user.T[i]. alamat); isFound := true; Break; end; end; if (not isFound) then begin writeln('Maaf, username tidak ditemukan.') end; writeln(''); end; end; procedure exiting_program(var array_buku : tabBuku; var array_user : tabUser; var array_pinjam : tabPinjam; var array_kembali : tabKembali; var array_hilang : tabHilang; var nama_file_kembali, nama_file_pinjam, nama_file_user, nama_file_buku, nama_file_hilang: string; var willExit,isLogin,isSave : boolean ); (*Procedure ini berfungsi untuk keluar dari program dan menyimpan data*) {Kamus Lokal} var pilihan_menu : string; begin if(not isLogin) then begin writeln(''); writeln('Apakah anda yakin ingin keluar? (Y/N) '); readln(pilihan_menu); if (pilihan_menu = 'Y') then begin willExit := True; end; end else begin if(not isSave) then begin writeln(''); write('Apakah anda mau melakukan penyimpanan file yang sudah dilakukan (Y/N) ?'); writeln(''); readln(pilihan_menu); if(pilihan_menu = 'Y') then begin 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); end; end; writeln(''); writeln('Apakah anda yakin ingin keluar? (Y/N) '); writeln(''); readln(pilihan_menu); if (pilihan_menu = 'Y') then begin willExit := True; end; end; end; procedure tampilMenuBelumLogin(); (*Procedure ini menampilkan interface aplikasi perpustakaan sebelum login*) begin writeln('1.Login'); writeln('2.Cari Buku Per Kategori'); writeln('3.Cari Buku Per Tahun Terbit'); writeln('4.Keluar'); end; procedure tampilMenu(var role_active_user:string); (*Procedure ini menampilkan interface aplikasi ketika sedang ada yang login, bergantung pada*) begin if(role_active_user = 'pengunjung') then begin writeln('1.Cari Buku Per Kategori'); writeln('2.Cari Buku Per Tahun Terbit'); writeln('3.Pinjam Buku'); writeln('4.Kembalikan Buku'); writeln('5.Melaporkan buku hilang'); writeln('6.Log Out'); end else if(role_active_user = 'admin') then begin writeln('1.Register Akun Baru'); writeln('2.Tambah Buku Baru'); writeln('3.Tambah Jumlah Buku'); writeln('4.Lihat riwayat peminjaman'); writeln('5.Statistik perpustakaan'); writeln('6.Cari Anggota'); writeln('7.Log Out'); end; end; procedure registerAnggota( var array_user : tabUser; var active_user : tuser; var isSave: Boolean); (*Procedure ini berfungsi untuk mendaftarkan anggota baru dan hanya dapat dilakukan oleh admin*) (*Variabel lokal*) var nama, alamat, uname, password, role : string; begin if(active_user.role = 'pengunjung') then begin writeln(''); writeln('Fitur ini hanya dapat diakses oleh admin. Kontak admin terdekat.'); writeln(''); end else begin writeln(''); writeln('Registrasi Pengguna Baru'); write('Nama Lengkap: '); readln(nama); write('Alamat: '); readln(alamat); write('Username: '); readln(uname); write('Password: '); readln(password); write('Role: '); readln(role); array_user.Neff := array_user.Neff + 1; array_user.T[ array_user.Neff ].Nama := nama; array_user.T[ array_user.Neff ].Alamat := alamat; array_user.T[ array_user.Neff ].Username := uname; array_user.T[ array_user.Neff ].Password := hash(password); array_user.T[ array_user.Neff ].Role := role; writeln('Registrasi Berhasil Dilakukan!'); writeln(''); isSave := False; end; end; procedure loginAnggota(var array_user : tabUser; var nama_file_user:string; var active_user: tuser; var isLogin: boolean); (*Procedure ini beru=fungsi untuk anggota perpustakaan login ke sistem*) {Kamus Lokal} var in_Uname, in_Pass, check: string; ch : char = #0; i, user_masuk : integer; status: boolean; begin writeln(''); write('Masukkan Username Anda: '); readln(in_Uname); in_Pass:=''; write('Masukkan Password Anda: '); while true do begin ch :=ReadKey; if (ch=#13) then break; if (ch=#8) then begin if (Length(in_Pass)=0) then continue; Delete(in_Pass,Length(in_Pass),1); write(ch); ClrEol; Continue; end; in_Pass := in_Pass + ch; write('*'); end; writeln(''); status:= False; for i:=1 to array_user.Neff do begin check := unhash(array_user.T[i].password); if(in_Uname = array_user.T[i].username) and (in_Pass = check) then begin status := True; user_masuk := i; end; end; if (status = True) then begin active_user.nama := array_user.T[user_masuk].nama; active_user.password := unhash(array_user.T[user_masuk].password); active_user.username := array_user.T[user_masuk].username; active_user.role := array_user.T[user_masuk].role; active_user.alamat := array_user.T[user_masuk].alamat; writeln('Login Berhasil!'); writeln('User ', in_Uname ,' berhasil login ke sistem perpustakaan'); writeln('Selamat menikmati!'); writeln(''); writeln('Ketik "help" untuk menampilkan menu' ); writeln(''); isLogin := True; end else begin writeln('Pasangan username dan password salah! Masukkan yang benar!') end; end; procedure showHelp(var isLogin: boolean); (*Procedure ini menampilkan pilihan menu yang dapat diakses oleh user*) begin if (not isLogin) then begin {Jika tidak ada yang login} writeln(''); writeln('login : Masuk ke akun anda.'); writeln('cari : Cari buku dari 5 kategori: manga, programming, sastra, sains, dan sejarah.'); writeln('caritahunterbit : Cari buku berdasarkan tahun terbit.'); writeln('exit : Keluar dari program.'); writeln(''); end else begin {isLogin = True} writeln(''); writeln('============================DAFTAR PERINTAH YANG TERSEDIA======================'); writeln('==== register '); writeln('==== cari : Cari buku dari 5 kategori: manga,programming,sastra,sains,sejarah. '); writeln('==== caritahunterbit : Cari buku berdasarkan tahun terbit. '); writeln('==== pinjam_buku : Meminjam buku. '); writeln('==== kembalikan_buku : Mengembalikan buku. '); writeln('==== lapor_hilang : Lapor apabila ada kehilangan buku. '); writeln('==== lihat_laporan : Lihat laporan kehilangan. '); writeln('==== tambah_buku : Tambah buku baru ke perpustakaan. '); writeln('==== tambah_jumlah_buku : Tambah jumlah buku yang tersedia. '); writeln('==== riwayat : Lihat riwayat peminjaman. '); writeln('==== statistik : Lihat statistik perpustakaan. '); writeln('==== save : Simpan perubahan yang telah dilakukan. '); writeln('==== cari_anggota : Cari anggota perpustakaan. '); writeln('==== logout : Keluar dari akun Anda. '); writeln('==== exit : Keluar dari program. '); writeln('==============================================================================='); writeln(''); end; end; procedure logout(var array_buku : tabBuku; var array_user : tabUser; var array_pinjam : tabPinjam; var array_kembali : tabKembali; var array_hilang : tabHilang; var nama_file_kembali, nama_file_pinjam, nama_file_user, nama_file_buku, nama_file_hilang: string; var isSave, isLogin : Boolean); (*Procedure untuk keluar dari program*) {KAMUS LOKAL} var pilihan_menu : string; {ALGORITMA} begin if(not isSave) then begin writeln(''); write('Apakah anda mau melakukan penyimpanan file yang sudah dilakukan (Y/N) ? '); readln(pilihan_menu); if(pilihan_menu = 'Y') then begin 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); end; end; writeln('Apakah anda yakin ingin logout? (Y/N)'); readln(pilihan_menu); if (pilihan_menu = 'Y') then begin isLogin := False; end; end; end.
unit VclTransfer; interface uses Controls, Forms, CoreTypes, Transfer; type TVclPropertyStorage = class(TInterfacedObject, IPropertyStorage) public constructor Create(ctrl : TWinControl; lineal : boolean); private // IPropertyStorage function GetClass : string; function GetName : string; function SetName(const which : string) : boolean; function GetProperty(const name : string) : string; function IPropertyStorage.SetProperty = CreateProperty; function CreateProperty(const name, value : string) : boolean; function EnumProperties : IEnumNames; function OpenStorage(const name : string) : IPropertyStorage; function CreateStorage(const theClass, name : string) : IPropertyStorage; function EnumChildren : IEnumNames; private fControl : TWinControl; fLineal : boolean; function FindProperty(const name : string) : TControl; function FindStorage(const name : string) : TWinControl; end; implementation uses SysUtils, Classes; type TLinealCtrlProperties = class(TInterfacedObject, IEnumNames) public constructor Create(ctrl : TWinControl); private function Next(out which : array of string) : integer; function Skip(count : integer) : integer; procedure Reset; private fControl : TControl; fCurrent : integer; end; type TCtrlProperties = class(TInterfacedObject, IEnumNames) public constructor Create(ctrl : TWinControl); private function Next(out which : array of string) : integer; function Skip(count : integer) : integer; procedure Reset; private fControl : TWinControl; fCurrent : integer; end; type TCtrlStorages = class(TInterfacedObject, IEnumNames) public constructor Create(ctrl : TWinControl); private function Next(out which : array of string) : integer; function Skip(count : integer) : integer; procedure Reset; private fControl : TWinControl; fCurrent : integer; end; // Utils function FindLinearProperty(Container : TWinControl; const name : string) : TControl; var i : integer; aux : TComponent; begin Result := nil; i := Container.ComponentCount - 1; if i >= 0 then repeat aux := Container.Components[i]; if aux is TControl then if CompareText(aux.Name, name) = 0 then Result := TControl(aux) else if aux is TWinControl then Result := FindLinearProperty(TWinControl(aux), name); dec(i); until (i < 0) or (Result <> nil); end; function FindLocalProperty(Container : TWinControl; const name : string) : TControl; var i : integer; aux : TControl; begin Result := nil; i := Container.ControlCount - 1; if i >= 0 then repeat aux := Container.Controls[i]; if CompareText(aux.Name, name) = 0 then Result := TControl(aux); dec(i); until (i < 0) or (Result <> nil); end; function GetProperStorage(var which : TControl) : boolean; begin while (which.Name = '') and (which is TWinControl) and (TWinControl(which).ControlCount = 1) do which := TWinControl(which).Controls[0]; Result := (which.Name <> '') and (which is TWinControl) and (TWinControl(which).ControlCount > 0); end; // TVclPropertyStorage constructor TVclPropertyStorage.Create(ctrl : TWinControl; lineal : boolean); begin inherited Create; fControl := ctrl; fLineal := lineal; end; function TVclPropertyStorage.GetClass : string; begin Result := ''; end; function TVclPropertyStorage.GetName : string; begin Result := fControl.Name; end; function TVclPropertyStorage.SetName(const which : string) : boolean; begin fControl.Name := which; Result := true; end; function TVclPropertyStorage.GetProperty(const name : string) : string; var ctrl : TControl; len : integer; begin ctrl := FindProperty(name); if ctrl <> nil then begin len := ctrl.GetTextLen; if len > 0 then begin SetLength(Result, len); ctrl.GetTextBuf(pchar(Result), len + 1); end else Result := ''; end else Result := ''; end; function TVclPropertyStorage.CreateProperty(const name, value : string) : boolean; var ctrl : TControl; begin ctrl := FindProperty(name); Result := (ctrl <> nil); if Result then ctrl.SetTextBuf(pchar(value)); end; function TVclPropertyStorage.EnumProperties : IEnumStrings; begin if fLineal then Result := TLinealCtrlProperties.Create(fControl) else Result := TCtrlProperties.Create(fControl); end; function TVclPropertyStorage.OpenStorage(const name : string) : IPropertyStorage; var ctrl : TWinControl; begin if fLineal then Result := Self else begin ctrl := FindStorage(name); if ctrl <> nil then Result := TVclPropertyStorage.Create(TWinControl(ctrl), false) else Result := nil; end; end; function TVclPropertyStorage.CreateStorage(const theClass, name : string) : IPropertyStorage; begin Result := OpenStorage(name); end; function TVclPropertyStorage.EnumChildren : IEnumStrings; begin if fLineal then Result := nil else Result := TCtrlStorages.Create(fControl) end; function TVclPropertyStorage.FindProperty(const name : string) : TControl; begin if fLineal then Result := FindLinearProperty(fControl, name) else Result := FindLocalProperty(fControl, name); end; function TVclPropertyStorage.FindStorage(const name : string) : TWinControl; var aux : TControl; i : integer; begin Result := nil; i := fControl.ControlCount - 1; if i >= 0 then repeat aux := fControl.Controls[i]; if GetProperStorage(aux) and (CompareText(aux.Name, name) = 0) then Result := TWinControl(aux); dec(i); until (i < 0) or (Result <> nil); end; // TLinealCtrlProperties constructor TLinealCtrlProperties.Create(ctrl : TWinControl); begin inherited Create; fControl := ctrl; end; function TLinealCtrlProperties.Next(out which : array of string) : integer; var cc : integer; aux : TComponent; begin cc := fControl.ComponentCount; Result := 0; while (fCurrent < cc) and (Result <= high(which)) do begin aux := fControl.Components[fCurrent]; if (aux.Name <> '') and (aux is TControl) then begin which[Result] := aux.Name; inc(Result); end; inc(fCurrent); end; end; function TLinealCtrlProperties.Skip(count : integer) : integer; var cc : integer; aux : TComponent; begin cc := fControl.ComponentCount; Result := 0; while (fCurrent < cc) and (Result < count) do begin aux := fControl.Components[fCurrent]; if (aux.Name <> '') and (aux is TControl) then inc(Result); inc(fCurrent); end; end; procedure TLinealCtrlProperties.Reset; begin fCurrent := 0; end; // TCtrlProperties constructor TCtrlProperties.Create(ctrl : TWinControl); begin inherited Create; fControl := ctrl; end; function TCtrlProperties.Next(out which : array of string) : integer; var cc : integer; aux : string; begin cc := fControl.ControlCount; Result := 0; while (fCurrent < cc) and (Result <= high(which)) do begin aux := fControl.Controls[fCurrent].Name; if aux <> '' then begin which[Result] := aux; inc(Result); end; inc(fCurrent); end; end; function TCtrlProperties.Skip(count : integer) : integer; var cc : integer; begin cc := fControl.ControlCount; Result := 0; while (fCurrent < cc) and (Result < count) do begin if fControl.Controls[fCurrent].Name <> '' then inc(Result); inc(fCurrent); end; end; procedure TCtrlProperties.Reset; begin fCurrent := 0; end; // TCtrlStorages constructor TCtrlStorages.Create(ctrl : TWinControl); begin inherited Create; fControl := ctrl; end; function TCtrlStorages.Next(out which : array of string) : integer; var cc : integer; aux : TControl; begin cc := fControl.ControlCount; Result := 0; while (fCurrent < cc) and (Result <= high(which)) do begin aux := fControl.Controls[fCurrent]; if GetProperStorage(aux) then begin which[Result] := aux.Name; inc(Result); end; inc(fCurrent); end; end; function TCtrlStorages.Skip(count : integer) : integer; var cc : integer; aux : TControl; begin cc := fControl.ControlCount; Result := 0; while (fCurrent < cc) and (Result < count) do begin aux := fControl.Controls[fCurrent]; if GetProperStorage(aux) then inc(Result); inc(fCurrent); end; end; procedure TCtrlStorages.Reset; begin fCurrent := 0; end; end.
unit nsSettingsUtils; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/nsSettingsUtils.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> F1 Оболочка Без Прецедентов::F1 Without Usecases::View::SettingsUtils::nsSettingsUtils // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} procedure LoadStyleTableFromSettings; procedure SaveStyleTableToSettings; procedure InitialLoadStyleTableFromSettings; {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses ConfigInterfaces, nsStyleEditor, evDefaultStylesFontSizes ; // unit methods procedure InitialLoadStyleTableFromSettings; //#UC START# *4E32B50601F3_4AD5BB450335_var* var l_Editor: InsEditSettingsInfo; //#UC END# *4E32B50601F3_4AD5BB450335_var* begin //#UC START# *4E32B50601F3_4AD5BB450335_impl* l_Editor := TnsStyleTableSettingsInfo.Make; try l_Editor.InitialLoadStyleTableFromSettings; finally l_Editor := nil; end; //#UC END# *4E32B50601F3_4AD5BB450335_impl* end;//InitialLoadStyleTableFromSettings procedure LoadStyleTableFromSettings; //#UC START# *4AD5BB7002A2_4AD5BB450335_var* var l_Editor: InsEditSettingsInfo; //#UC END# *4AD5BB7002A2_4AD5BB450335_var* begin //#UC START# *4AD5BB7002A2_4AD5BB450335_impl* l_Editor := TnsStyleTableSettingsInfo.Make; try l_Editor.Load; finally l_Editor := nil; end; //#UC END# *4AD5BB7002A2_4AD5BB450335_impl* end;//LoadStyleTableFromSettings procedure SaveStyleTableToSettings; //#UC START# *4AD5BB7F00E5_4AD5BB450335_var* var l_Editor: InsEditSettingsInfo; //#UC END# *4AD5BB7F00E5_4AD5BB450335_var* begin //#UC START# *4AD5BB7F00E5_4AD5BB450335_impl* l_Editor := TnsStyleTableSettingsInfo.Make; try l_Editor.Save; finally l_Editor := nil; end; //#UC END# *4AD5BB7F00E5_4AD5BB450335_impl* end;//SaveStyleTableToSettings {$IfEnd} //not Admin AND not Monitorings end.
unit FileBin; interface uses Windows, SysUtils, Classes; type CFile=class filename:string; public // function Open(fname:string;read:boolean):boolean; procedure Close; function Size:DWORD; function GetHandle:THandle; procedure WriteString(str:string); procedure ReadString(len:integer;var str:string); procedure WriteNullTerminatedString(str:string); procedure ReadNullTerminatedString(var str:string); procedure WriteBool(b:boolean); procedure ReadBool(var b:boolean); procedure WriteWord(w:Word); procedure ReadWord(var w:Word); procedure WriteInt(i:integer); procedure ReadInt(var i:integer); procedure WriteFloat(s:Single); procedure ReadFloat(var s:Single); procedure WriteChar(c:Char); procedure ReadChar(var c:Char); procedure WriteDouble(d:Double); procedure ReadDouble(var d:Double); procedure WriteBuf(const Buffer;size : integer); procedure ReadBuf(var Buffer;size : integer); constructor Create; procedure SkipBytes(bcount : integer); //procedure BeginFileMapping(); //procedure EndFileMapping(); // procedure Write(Buffer:Untyped; private // Handle, Map: THandle; _Read: boolean; end; var wr:Cardinal; implementation { CFile } {procedure CFile.BeginFileMapping; begin (* if _Read then CreateFileMapping(Handle, nil, PAGE_READONLY, 0, 0, nil) else *) CreateFileMapping(Handle, nil, PAGE_READWRITE, 0, 0, nil); end; } procedure CFile.Close; begin CloseHandle(Handle); //if Map <> nil then // CloseHandle(Map); // Map := nil; end; constructor CFile.Create; begin //do something end; {procedure CFile.EndFileMapping; begin CloseHandle(Map); Map := nil; end;} function CFile.GetHandle: THandle; begin Result:=Handle; end; function CFile.Open(fname: string; read: boolean): boolean; begin if (not FileExists(fname)) and (read) then begin result:=false; exit; end; if read then Handle:=CreateFile(PANSICHAR(FNAME),GENERIC_READ,FILE_SHARE_READ,nil, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0) else Handle:=CreateFile(PANSICHAR(FNAME),GENERIC_WRITE,FILE_SHARE_WRITE,nil, OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); if Handle=INVALID_HANDLE_VALUE then Result:=false else Result:=true; filename:=fname; _Read := read; end; procedure CFile.ReadBool(var b: boolean); var c:char; begin ReadChar(c); b:=false; if ord(c)<>0 then b:=true; end; procedure CFile.ReadBuf(var Buffer; size: integer); begin ReadFile(Handle,Buffer,size,wr,nil); end; procedure CFile.ReadChar(var c: Char); var t:char; begin ReadFile(Handle,t,1,wr,nil); c:=t; end; procedure CFile.ReadDouble(var d: Double); var t:double; begin ReadFile(Handle,t,8,wr,nil); d:=t; end; procedure CFile.ReadFloat(var s: Single); var t:single; begin ReadFile(Handle,t,4,wr,nil); s:=T; end; procedure CFile.ReadInt(var i: integer); var t:integer; begin ReadFile(Handle,t,4,wr,nil); i:=t; end; procedure CFile.ReadNullTerminatedString(var str: string); var b:char; begin b:=#1; str:=''; while b<>#0 do begin ReadChar(b); if b<>#0 then str:=str+b; end; end; procedure CFile.ReadString(len:integer;var str:string); var b:char; i:integer; begin b:=#1; str:=''; for i:=1 to len do begin ReadChar(b); str:=str+b; end; end; procedure CFile.ReadWord(var w: Word); var t:Word; begin ReadFile(Handle,t,2,wr,nil); w:=t; end; function CFile.Size: DWORD; begin Result:=GetFileSize(Handle,nil); end; procedure CFile.SkipBytes(bcount: integer); begin SetFilePointer(Handle,bcount,Nil,FILE_CURRENT); end; procedure CFile.WriteBool(b: boolean); begin if b then WriteChar(#1) else WriteChar(#0); end; procedure CFile.WriteBuf(const Buffer; size: integer); begin WriteFile(Handle,Buffer,size,wr,nil); end; procedure CFile.WriteChar(c: Char); var t:char; begin t:=c; WriteFile(Handle,t,1,wr,nil); end; procedure CFile.WriteDouble(d: Double); var t:double; begin t:=d; WriteFile(Handle,t,8,wr,nil); end; procedure CFile.WriteFloat(s: Single); var t:single; begin t:=s; WriteFile(Handle,t,4,wr,nil); end; procedure CFile.WriteInt(i: integer); var t:integer; begin t:=i; WriteFile(Handle,t,4,wr,nil); end; procedure CFile.WriteNullTerminatedString(str: string); begin WriteString(str); WriteChar(#0); end; procedure CFile.WriteString(str: string); var b:char; i:integer; begin for i:=1 to length(str) do begin b:=str[i]; WriteChar(b); end; end; procedure CFile.WriteWord(w: Word); var t:WORD; begin t:=w; WriteFile(Handle,t,2,wr,nil); end; end.
unit nsContextSearchParams; (*----------------------------------------------------------------------------- Название: nsContextSearchParams Автор: Лукьянец Р. В. Назначение: Утилита для создания фильтра дла контекстного _поиска_ Версия: $Id: nsContextSearchParams.pas,v 1.3 2011/01/27 15:01:56 lulin Exp $ История: $Log: nsContextSearchParams.pas,v $ Revision 1.3 2011/01/27 15:01:56 lulin {RequestLink:248195582}. - упрощаем программирование на форме. Revision 1.2 2011/01/27 12:14:15 lulin {RequestLink:248195582}. - избавляемся от развесистых макарон. Revision 1.1 2009/09/14 11:28:53 lulin - выводим пути и для незавершённых модулей. Revision 1.4 2008/01/10 07:23:30 oman Переход на новый адаптер Revision 1.3.4.5 2007/12/05 12:43:44 oman Перепиливаем на новый адаптер - фабрики контейнеров Revision 1.3.4.4 2007/11/23 10:41:09 oman cleanup Revision 1.3.4.3 2007/11/22 14:20:24 oman Перепиливаем на новый адаптер Revision 1.3.4.2 2007/11/22 13:20:37 oman Перепиливаем на новый адаптер Revision 1.3.4.1 2007/11/20 15:07:05 oman Перепиливаем на новый адаптер Revision 1.3 2007/05/17 12:04:16 oman cleanup Revision 1.2 2007/05/17 10:33:52 oman cleanup Revision 1.1 2007/03/30 11:04:27 oman Унифицируем способ формирования фильтра при контекстном поиске -----------------------------------------------------------------------------*) interface uses l3Interfaces, DynamicTreeUnit ; function nsMakeContextSearchFilterList(const aContext: Il3CString; const aWholeWord: Boolean; const TreatParagraphAsAllLevel: Boolean) : IFilterList; {* - формирует адаптерный IFilter, помещает его в список и возвращает список. } implementation uses DataAdapter, nsTypes; function nsMakeContextSearchFilterList(const aContext: Il3CString; const aWholeWord: Boolean; const TreatParagraphAsAllLevel: Boolean) : IFilterList; {* - формирует адаптерный IFilter, помещает его в список и возвращает список. } //overload; var l_Filter : IContextFilter; begin l_Filter := defDataAdapter.NativeAdapter.MakeContextFilter; l_Filter.SetContext(nsIStr(aContext)); if aWholeWord then l_Filter.SetPlace(CP_WHOLE_WORD) else l_Filter.SetOrder(FO_ANY); if TreatParagraphAsAllLevel then l_Filter.SetArea(SA_ALL_LEVEL) else l_Filter.SetArea(SA_ONE_LEVEL); Result := defDataAdapter.NativeAdapter.MakeFilterList; Result.Add(l_Filter); end; end.
program a4; {This program tests the shortest path algorithm from program strategy 10.16 Below you will find a test program, and some procedure headers. You must fill in the bodies of the procedures. Do not alter the test program or type definitions in any way. You are given a constant for INFINITY, which is defined to be the same as MAXINT. This is a constant that returns the largest possible number of type integer. This assumes that you will use low edge weight values. Stick to weights less than 100 and the output will also look nicer. NOTE - always comment every single local variable you use. } {************* CONSTANTS ******************} Const MAX = 100; { This is the maximum size of graph. You can make this bigger if you want. } INFINITY = MAXINT; { Use this anywhere you need "infinity" } {************* TYPE DEFINITIONS *********************} Type {The type definitions below define an adjacency matrix graph representation that stores edge weights.} GraphSize = 0..MAX; VertexNumber = 1..MAX; AdjacencyRow = Array [VertexNumber] of integer; GraphRep = Array [VertexNumber] of AdjacencyRow; {ShortestPathArray is the type for the ShortestDistance variable that returns the result of Dijkstra's algorithm} ShortestPathArray = Array [VertexNumber] of integer; {************** The Procedures and Functions ********************} {procedure minimum(a,b) pre: a and b are integers post: returns the larger of a and b. NOTE - Pascal does not have a built in minimum function. Use this one if you need it.} function minimum(a,b: integer): integer; begin if a<b then minimum := a else minimum := b end; { fxn minimum } {procedure NewGraph(G,S) pre: S is the size of graph to create. post: G should be an adjacency matrix or adjacency list that corresponds to a graph with S vertices and no edges. If using an adjacency matrix, you must initialize the entire matrix. HINT: Remember that the distance from a vertex to itself is always 0.} procedure NewGraph(var G:GraphRep; S:GraphSize); var i, j: integer ; begin for i := 1 to S do for j := 1 to S do if i = j then G[i][j] := 0 else G[i][j] := INFINITY end; { proc NewGraph } {procedure AddEdge(G,S,Origin,Terminus,Weight) pre: G is a graph representation with S vertices. Origin, Terminus, and Weight define an edge to be added to G. post: G has the specified edge added. HINT - you might want to print an error message if Origin or Terminus are bigger than S.} procedure AddEdge( var G:GraphRep; S:GraphSize; Origin:VertexNumber; Terminus: VertexNumber; Weight: integer ); begin if ( not ( Origin in [1.. S] ) ) or ( not ( Terminus in [1..S] ) ) then writeln( 'Error: Origin and Terminus must be in the range 1 to ', S ) else if ( Origin = Terminus ) and ( Weight <> 0 ) then writeln( 'Error: the distance from a vertex to itself is always 0. ' ) else G[Origin][Terminus] := Weight end; { proc AddEdge } {procedure ShortestPath(G,S,Origin,ShortestDistance) pre: G is a graph representation with S vertices. Origin is the start vertex. post: ShortestDistance is an array containing the shortest distances from Origin to each vertex. HINT - program strategy 10.16 uses set variables. This is possible in Pascal, but you can't really use them the way you need to here. I suggest implementing the set W as an array of booleans. Initialize them all to FALSE and then each time you want to put a new vertex in the set, change the corresponding value to TRUE. You also might want to keep a count of the number of vertices in W. HINT - Watch out for the two "W" variables in 10.16. They use a big W and a small w. You can't do that in Pascal. I suggest using "w" for the small one and "BigW" for the big one. Of course you are free to use whatever variable names you want, but the closer you stick to the book, the easier it will be to mark. HINT - Comment this well! } procedure ShortestPath(var G:GraphRep; S:GraphSize; Origin: VertexNumber; var ShortestDistance: ShortestPathArray); var V, BigW : set of GraphSize ; MinDistance, w : integer ; i, j, k, y : VertexNumber ; begin w := -1 ; V := [1..S] ; BigW := [Origin] ; for i := 1 to S do ShortestDistance[i] := G[Origin][i] ; while BigW <> V do BEGIN MinDistance := INFINITY ; for j := 1 to S do if ( j in ( V - BigW ) ) then if ( ShortestDistance[j] < MinDistance ) then BEGIN MinDistance := ShortestDistance[j] ; w := j END { if } else y := j ; if w < 0 then w := y ; BigW := BigW + [w] ; for k := 1 to S do if ( k in ( V - BigW ) ) and ( G[w][k] <> INFINITY ) then ShortestDistance[k] := minimum(ShortestDistance[k], ShortestDistance[w] + G[w][k]) END { while } end; { proc ShortestPath } (**************************** IDENTIFICATION **************************) { Change this procedure to identify yourself } procedure IdentifyMyself; begin writeln; writeln('***** Student Name: Mark Sattolo'); writeln('***** Student Number: 428500'); writeln('***** Professor Name: Sam Scott'); writeln('***** Course Number: CSI-2114D'); writeln('***** T.A. Name: Adam Murray'); writeln('***** Tutorial Number: D-1'); writeln; end; var G: GraphRep; {G and S define the graph} S: GraphSize; E, {Counts number of edges} Weight: integer; { Weight, Origin and Terminus are } Origin, Terminus, { for User input} row, col: VertexNumber; { Row and Col are for looping through the adjacency matrix } answer: string; { Stores users' answers to questions } ShortestPaths: ShortestPathArray; { Stores the shortest paths } begin IdentifyMyself; {INITIALIZE G} write('What size of graph do you want (maximum size=',MAX,'): '); readln(S); writeln; NewGraph(G,S); writeln('Enter the edges one by one until you are finished.'); writeln('Quit by entering a zero for the origin vertex.'); E := 0; repeat writeln; write('Origin: '); readln(Origin); if Origin > 0 then begin write('Terminus: '); readln(Terminus); write('Weight: '); readln(Weight); AddEdge(G,S,Origin,Terminus,Weight); E := E+1 end until (Origin<=0); {DISPLAY G IF REQUESTED} writeln; writeln('Your graph has ',S,' vertices and ',E,' edges.'); writeln; write('Would you like to see the adjacency matrix (y/n)' ); readln(answer); writeln; if (answer[1] = 'y') or (answer[1] = 'Y') then for row := 1 to S do begin for col := 1 to S do if G[row,col]=INFINITY then write(' INF') else write(G[row,col]:4); writeln end; writeln; {RUN SHORTEST PATH IF REQUESTED } write('Would you like to run the shortest path algorithm? (y/n)'); readln(answer); writeln; if (answer[1] = 'y') or (answer[1] = 'Y') then begin write('What is the start vertex? (1..',S,'): '); readln(Origin); writeln; ShortestPath(G,S,Origin,ShortestPaths); writeln; writeln('Shortest paths from start vertex ',Origin,' are: '); for Terminus := 1 to S do write(Terminus:5,': ',ShortestPaths[Terminus]); writeln; end; {QUIT} writeln; writeln('Bye bye') end.
unit uTask.Image; interface uses { TThread } System.Classes, { IViewControl } uIViews, { TPicture } Vcl.Graphics; type TTaskImage = class(TThread) protected FBitmap: TBitMap; FFileName: String; class var RMain: IViewControl; procedure Execute; override; procedure ThreadCompleted(Sender: TObject); public constructor Create(AFileName: String); destructor Destroy; override; end; implementation uses { FormHelper } uFunctions.Form, { FreeAndNil } System.SysUtils, uConsts, { ImageHelper } uFunctions.ImageHelper, { Not using directly, but required for JPEG file format support } Vcl.Imaging.jpeg, { Not using directly, but required for PNG file format support } Vcl.Imaging.pngimage; constructor TTaskImage.Create(AFileName: String); begin if RMain = nil then FormHelper.GetFirstForm(IViewControl, RMain); OnTerminate := ThreadCompleted; FFileName := AFileName; inherited Create(True); end; destructor TTaskImage.Destroy; begin FBitmap.Free; inherited; end; procedure TTaskImage.Execute; var LImageResize: TImageResize; LPicture: TPicture; begin inherited; LPicture := nil; try LPicture := TPicture.Create; try LPicture.LoadFromFile(FFileName); FBitmap := TBitmap.Create; FBitmap.Width := CONST_IMAGE_WIDTH; FBitmap.Height := CONST_IMAGE_HEIGHT; with LImageResize do begin CurrentWidth := LPicture.Graphic.Width; CurrentHeight := LPicture.Graphic.Height; MaxWidth := CONST_IMAGE_WIDTH; MaxHeight := CONST_IMAGE_HEIGHT; end; ImageHelper.CalculateNewSize(LImageResize); FBitmap.Canvas.Lock; try FBitmap.Canvas.StretchDraw(Rect(0, 0, LImageResize.NewWidth, LImageResize.NewHeight), LPicture.Graphic); finally FBitmap.Canvas.UnLock; end; if RMain <> nil then Synchronize( procedure begin RMain.UpdateImage(FBitmap); end ); except FBitmap.Free; end; finally FreeAndNil(LPicture); end; end; procedure TTaskImage.ThreadCompleted(Sender: TObject); begin if RMain <> nil then Synchronize( procedure begin RMain.ImageThreadComleted(Self); end ); end; end.
unit kwFontIsItalic; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwFontIsItalic.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::FontKeywords::font_IsItalic // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses l3Interfaces, Graphics, tfwScriptingInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwFontWord.imp.pas} TkwFontIsItalic = {final} class(_kwFontWord_) protected // realized methods procedure DoFont(aFont: TFont; const aCtx: TtfwContext); override; procedure DoIFont(const aFont: Il3Font; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwFontIsItalic {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses SysUtils, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwFontIsItalic; {$Include ..\ScriptEngine\kwFontWord.imp.pas} // start class TkwFontIsItalic procedure TkwFontIsItalic.DoFont(aFont: TFont; const aCtx: TtfwContext); //#UC START# *5190B11A0069_5190B2DE02D6_var* //#UC END# *5190B11A0069_5190B2DE02D6_var* begin //#UC START# *5190B11A0069_5190B2DE02D6_impl* aCtx.rEngine.PushBool(fsItalic in aFont.Style); //#UC END# *5190B11A0069_5190B2DE02D6_impl* end;//TkwFontIsItalic.DoFont procedure TkwFontIsItalic.DoIFont(const aFont: Il3Font; const aCtx: TtfwContext); //#UC START# *5190DDC60327_5190B2DE02D6_var* //#UC END# *5190DDC60327_5190B2DE02D6_var* begin //#UC START# *5190DDC60327_5190B2DE02D6_impl* aCtx.rEngine.PushBool(aFont.Italic); //#UC END# *5190DDC60327_5190B2DE02D6_impl* end;//TkwFontIsItalic.DoIFont class function TkwFontIsItalic.GetWordNameForRegister: AnsiString; {-} begin Result := 'font:IsItalic'; end;//TkwFontIsItalic.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwFontWord.imp.pas} {$IfEnd} //not NoScripts end.
{ GDAX/Coinbase-Pro client library Copyright (c) 2018 mr-highball Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit gdax.api.ticker; {$i gdax.inc} interface uses Classes, SysUtils, gdax.api, gdax.api.consts, gdax.api.types; type { TGDAXTickerImpl } TGDAXTickerImpl = class(TGDAXRestApi,IGDAXTicker) strict private FProduct: IGDAXProduct; FSize: Extended; FAsk: Extended; FBid: Extended; FTime: TDateTime; FVolume: Extended; FPrice: Extended; protected function GetProduct: IGDAXProduct; procedure SetProduct(Const Value: IGDAXProduct); function GetSize: Extended; procedure SetSize(Const Value: Extended); function GetAsk: Extended; function GetBid: Extended; function GetTime: TDateTime; function GetVolume: Extended; procedure SetAsk(Const Value: Extended); procedure SetBid(Const Value: Extended); procedure SetTime(Const Value: TDateTime); procedure SetVolume(Const Value: Extended); function GetPrice: Extended; procedure SetPrice(Const Value: Extended); strict protected function GetEndpoint(Const AOperation: TRestOperation): string; override; function DoGet(Const AEndpoint: string; Const AHeaders: TStrings; out Content: string; out Error: string): Boolean; override; function DoGetSupportedOperations: TRestOperations; override; function DoLoadFromJSON(Const AJSON: string; out Error: string): Boolean; override; public property Product: IGDAXProduct read GetProduct write SetProduct; property Price: Extended read GetPrice write SetPrice; property Size: Extended read GetSize write SetSize; property Bid: Extended read GetBid write SetBid; property Ask: Extended read GetAsk write SetAsk; property Volume: Extended read GetVolume write SetVolume; property Time: TDateTime read GetTime write SetTime; constructor Create; override; destructor Destroy; override; end; implementation uses fpjson, jsonparser, fpindexer; { TProductTicket } constructor TGDAXTickerImpl.Create; begin inherited Create; FProduct := nil; FSize:=0; FAsk:=0; FBid:=0; FTime := Now; FVolume:=0; FPrice:=0; end; destructor TGDAXTickerImpl.Destroy; begin FProduct := nil; inherited Destroy; end; function TGDAXTickerImpl.DoGet(Const AEndpoint: string; Const AHeaders: TStrings; out Content: string; out Error: string): Boolean; begin Result := False; try if not Assigned(FProduct) then begin Error := Format(E_UNKNOWN,['product',Self.ClassName]); Exit; end; Result := inherited; except on E: Exception do Error := E.ClassName+': '+E.Message; end; end; function TGDAXTickerImpl.DoGetSupportedOperations: TRestOperations; begin Result:=[roGet]; end; function TGDAXTickerImpl.DoLoadFromJSON(Const AJSON: string; out Error: string): Boolean; var LJSON : TJSONObject; begin Result := False; try LJSON := TJSONObject(GetJSON(AJSON)); if not Assigned(LJSON) then raise Exception.Create(E_BADJSON); try FPrice := LJSON.Get('price'); FSize := LJSON.Get('size'); FAsk := LJSON.Get('ask'); FBid := LJSON.Get('bid'); FVolume := LJSON.Get('volume'); FTime := ISO8601ToDate(LJSON.Get('time')); Result := True; finally LJSON.Free; end; except on E: Exception do Error := E.ClassName+': '+E.Message; end; end; function TGDAXTickerImpl.GetAsk: Extended; begin Result := FAsk; end; function TGDAXTickerImpl.GetBid: Extended; begin Result := FBid; end; function TGDAXTickerImpl.GetEndpoint(Const AOperation: TRestOperation): string; begin Result:=''; if not Assigned(FProduct) then raise Exception.Create(Format(E_UNKNOWN,['product',Self.ClassName])); if AOperation=roGet then Result := Format(GDAX_END_API_TICKER,[FProduct.ID]); end; function TGDAXTickerImpl.GetPrice: Extended; begin Result := FPrice; end; function TGDAXTickerImpl.GetProduct: IGDAXProduct; var LMin: Extended; begin //auto-calc base min for deprecated property (backwards compat) //https://github.com/mr-highball/coinbase-pro/issues/8 if Assigned(FProduct) then begin //notional is placed in the min_market_funds //https://docs.cloud.coinbase.com/exchange/docs/changelog#2022-jun-02 if FPrice <> 0 then begin LMin := FProduct.MinMarketFunds / FPrice; FProduct.BaseMinSize := LMin; end; end; Result := FProduct; end; function TGDAXTickerImpl.GetSize: Extended; begin Result := FSize; end; function TGDAXTickerImpl.GetTime: TDateTime; begin Result := FTime; end; function TGDAXTickerImpl.GetVolume: Extended; begin Result := FVolume; end; procedure TGDAXTickerImpl.SetAsk(Const Value: Extended); begin FAsk := Value; end; procedure TGDAXTickerImpl.SetBid(Const Value: Extended); begin FBid := Value; end; procedure TGDAXTickerImpl.SetPrice(Const Value: Extended); begin FPrice := Value; end; procedure TGDAXTickerImpl.SetProduct(Const Value: IGDAXProduct); begin FProduct := nil; FProduct := Value; end; procedure TGDAXTickerImpl.SetSize(Const Value: Extended); begin FSize := Value; end; procedure TGDAXTickerImpl.SetTime(Const Value: TDateTime); begin FTime := Value; end; procedure TGDAXTickerImpl.SetVolume(Const Value: Extended); begin FVolume := Value; end; end.
unit nscNavigator; // Библиотека : "Визуальные компоненты проекта Немезис" // Автор : М. Морозов. // Начат : 06.12.2006 г. // Назначение : Компонент с вкладками // Версия : $Id: nscNavigator.pas,v 1.15 2016/09/13 18:32:40 kostitsin Exp $ // $Log: nscNavigator.pas,v $ // Revision 1.15 2016/09/13 18:32:40 kostitsin // {requestlink: 630194905 } // // Revision 1.14 2015/04/24 14:55:31 lulin // - правильный define. // // Revision 1.13 2015/03/13 13:22:56 morozov // {RequestLink: 590762196} // // Revision 1.12 2015/03/04 12:07:20 lulin // {RequestLink:590512167} // // Revision 1.11 2015/02/19 08:34:42 morozov // {RequestLink: 588832246} // // Revision 1.10 2015/02/06 18:58:34 lulin // - стараемся уйти от авторегистрируемых слов. // // Revision 1.9 2014/09/10 12:27:29 morozov // {RequestLink: 564993305} // // Revision 1.8 2014/07/02 14:45:30 lulin // - собираем библиотеки. // // Revision 1.7 2014/05/27 08:42:03 kostitsin // {requestlink: 342868625 } - регистрируем ещё один класс для тестов // // Revision 1.6 2014/01/10 16:24:53 kostitsin // [$510593012] // // Revision 1.5 2009/01/12 17:38:11 lulin // - <K>: 133138664. № 24. // // Revision 1.4 2009/01/12 09:14:30 oman // - new: Учим навигатор закрываться по Ctrl+F4 (К-113508400) // // Revision 1.3 2007/08/20 09:06:07 mmorozov // - new: уведомление об изменении активной вкладки (CQ: OIT5-26352); // // Revision 1.2 2006/12/12 11:42:27 mmorozov // - new: возможность определять класс плавающего окна; // // Revision 1.1 2006/12/07 14:23:11 mmorozov // - new: используем единые настройки для компонента с вкладками (CQ: OIT5-23819); // interface {$Include nscDefine.inc} uses Classes, Controls, ElPgCtl, vcmExternalInterfaces, vcmInterfaces, vcmDispatcher, nscInterfaces, vtNavigator ; {$IfNDef NoVCM} type _nscDestPageControl_ = TnpPageControl; {$Include nscPageControl.inc} TnscNavigatorPageControl = class(_nscPageControl_) protected procedure CMDockClient(var Message: TCMDockClient); message CM_DOCKCLIENT; end; TnscNavigator = class(TvtNavigator, IvcmOperationsProvider, IvcmMainFormDependent) private procedure CloseChildExecute(const aParams : IvcmExecuteParamsPrim); {-} procedure CloseChildTest(const aParams : IvcmTestParamsPrim); {-} protected // IvcmOperationsProvider procedure ProvideOps(const aPublisher : IvcmOperationsPublisher); {* - предоставить список доступных операций. } // IvcmMainFormDependent procedure MainFormChanged(aNewMainForm: TControl); {* - изменилась главная форма. } protected // methods function GetPageControlClass: RnpPageControl; override; {-} function GetFloatingWindowClass: RnpFloatingWindow; override; {* - получить класс плавающего окна. } end;//TnscNavigator TnscFloatingWindow = class(TnpFloatingWindow) {* Плавающего окно навигатора. } protected // methods function GetNavigatorClass: RvtNavigator; override; {* - ссылка на класс навигатора. } end;//TnscFloatingWindow {$EndIf NoVCM} implementation uses SysUtils, Graphics, afwVCL, {$IfNDef DesignTimeLibrary} vcmBase, {$EndIf DesignTimeLibrary} nscNewInterfaces, nscTabFont, vcmEntityForm {$If not defined(NoScripts)} , tfwClassRef {$IfEnd} //not NoScripts ; {$IfNDef NoVCM} const vcm_deEnclosedForms = 'EnclosedForms'; vcm_doCloseChild = 'CloseChild'; {$Include nscPageControl.inc} { TnscNavigatorPageControl } procedure TnscNavigatorPageControl.CMDockClient(var Message: TCMDockClient); begin inherited; Change; // - http://mdp.garant.ru/pages/viewpage.action?pageId=588575925, // http://mdp.garant.ru/pages/viewpage.action?pageId=588832246, end; { TnscNavigator } procedure TnscNavigator.CloseChildExecute( const aParams: IvcmExecuteParamsPrim); begin f_Header.CloseButton.Click end; procedure TnscNavigator.CloseChildTest(const aParams: IvcmTestParamsPrim); begin if aParams.Op.Flag[vcm_ofEnabled] then aParams.Op.Flag[vcm_ofEnabled] := Assigned(f_Header.CloseButton) and f_Header.CloseButton.Visible; end; function TnscNavigator.GetFloatingWindowClass: RnpFloatingWindow; begin Result := TnscFloatingWindow; end; function TnscNavigator.GetPageControlClass: RnpPageControl; begin Result := TnscNavigatorPageControl; end;//GetPageControlClass procedure TnscNavigator.ProvideOps( const aPublisher: IvcmOperationsPublisher); begin aPublisher.PublishOp(vcm_deEnclosedForms, vcm_doCloseChild, CloseChildExecute, CloseChildTest); end; procedure TnscNavigator.MainFormChanged(aNewMainForm: TControl); begin UpdateMainForm(aNewMainForm As TvcmEntityForm); end; { TnscFloatingWindow } function TnscFloatingWindow.GetNavigatorClass: RvtNavigator; begin Result := TnscNavigator; end; initialization {$If not defined(NoScripts)} TtfwClassRef.Register(TnscNavigatorPageControl); TtfwClassRef.Register(TnscNavigator); TtfwClassRef.Register(TnscFloatingWindow); {$IfEnd} {$EndIf NoVCM} end.
unit GetOptimizationUnit; interface uses SysUtils, BaseExampleUnit; type TGetOptimization = class(TBaseExample) public procedure Execute(OptimizationProblemId: String); end; implementation uses OptimizationParametersUnit, DataObjectUnit, EnumsUnit; procedure TGetOptimization.Execute(OptimizationProblemId: String); var DataObject: TDataObject; ErrorString: String; begin DataObject := Route4MeManager.Optimization.Get(OptimizationProblemId, ErrorString); try WriteLn(''); if (DataObject <> nil) then begin WriteLn('GetOptimization executed successfully'); WriteLn(Format('Optimization Problem ID: %s', [DataObject.OptimizationProblemId])); WriteLn(Format('State: %s', [TOptimizationDescription[TOptimizationState(DataObject.State)]])); end else WriteLn(Format('GetOptimization error: "%s"', [ErrorString])); finally FreeAndNil(DataObject); end; end; end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2022 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 FB4D.Response; interface uses System.SysUtils, System.JSON, System.Net.HttpClient, REST.Client, FB4D.Interfaces; type TFirebaseResponse = class(TInterfacedObject, IFirebaseResponse) private fHttpResp: IHTTPResponse; fRestResp: TRESTResponse; fOnError: TOnRequestError; fOnSuccess: TOnSuccess; public const ExceptOpNotAllowed = 'OPERATION_NOT_ALLOWED'; ExceptTokenExpired = 'TOKEN_EXPIRED'; ExceptUserDisabled = 'USER_DISABLED'; ExceptUserNotFound = 'USER_NOT_FOUND'; ExceptEmailNotFound = 'EMAIL_NOT_FOUND'; ExceptExpiredOobCode = 'EXPIRED_OOB_CODE'; ExceptInvalidOobCode = 'INVALID_OOB_CODE'; constructor Create(HTTPResponse: IHTTPResponse); overload; constructor Create(RestResponse: TRESTResponse; OnError: TOnRequestError; OnSuccess: TOnSuccess); overload; function ContentAsString: string; function GetContentAsJSONObj: TJSONObject; function GetContentAsJSONArr: TJSONArray; function GetContentAsJSONVal: TJSONValue; function GetServerTime(TimeZone: TTimeZone): TDateTime; procedure CheckForJSONObj; function IsJSONObj: boolean; procedure CheckForJSONArr; function StatusOk: boolean; function StatusIsUnauthorized: boolean; function StatusNotFound: boolean; function StatusCode: integer; function StatusText: string; function ErrorMsg: string; function ErrorMsgOrStatusText: string; function GetOnError: TOnRequestError; function GetOnSuccess: TOnSuccess; function HeaderValue(const HeaderName: string): string; end; implementation uses System.Generics.Collections, FB4D.Helpers; resourcestring rsResponseIsNotJSON = 'The reponse from the firestore is not a JSON: %s'; rsResponseIsNotJSONObj = 'The reponse from the firestore is not a JSON object: %s'; rsResponseIsNotJSONArr = 'The reponse from the firestore is not a JSON array: %s'; rsTimeZoneIsNotSupported = 'Time zone %d is not supported yet'; { TFirestoreResponse } constructor TFirebaseResponse.Create(HTTPResponse: IHTTPResponse); begin inherited Create; fRestResp := nil; fHttpResp := HTTPResponse; fOnSuccess.Create(nil); fOnError := nil; end; constructor TFirebaseResponse.Create(RestResponse: TRESTResponse; OnError: TOnRequestError; OnSuccess: TOnSuccess); begin inherited Create; fRestResp := RestResponse; fHttpResp := nil; fOnSuccess := OnSuccess; fOnError := OnError; end; function TFirebaseResponse.StatusCode: integer; begin if assigned(fHttpResp) then result := fHttpResp.StatusCode else if assigned(fRestResp) then result := fRestResp.StatusCode else raise EFirebaseResponse.Create('No initialized response class'); end; function TFirebaseResponse.StatusText: string; begin if assigned(fHttpResp) then result := fHttpResp.StatusText else if assigned(fRestResp) then result := fRestResp.StatusText else raise EFirebaseResponse.Create('No initialized response class'); end; function TFirebaseResponse.ContentAsString: string; begin if assigned(fHttpResp) then result := fHttpResp.ContentAsString else if assigned(fRestResp) then result := fRestResp.Content else raise EFirebaseResponse.Create('No initialized response class'); end; function TFirebaseResponse.StatusIsUnauthorized: boolean; begin result := (StatusCode = 401) or (StatusCode = 403); end; function TFirebaseResponse.StatusNotFound: boolean; begin result := StatusCode = 404; end; function TFirebaseResponse.StatusOk: boolean; begin result := (StatusCode >= 200) and (StatusCode < 300); end; procedure TFirebaseResponse.CheckForJSONObj; var JSONValue: TJSONValue; Error, ErrMsg: TJSONValue; begin JSONValue := TJSONObject.ParseJSONValue(ContentAsString); try if not Assigned(JSONValue) then raise EFirebaseResponse.CreateFmt(rsResponseIsNotJSON, [ContentAsString]) else if not (JSONValue is TJSONObject) then raise EFirebaseResponse.CreateFmt(rsResponseIsNotJSONObj, [ContentAsString]) else if (JSONValue as TJSONObject).TryGetValue('error', Error) and (Error.TryGetValue('message', ErrMsg)) then raise EFirebaseResponse.Create(ErrMsg.Value); finally JSONValue.Free; end; end; function TFirebaseResponse.ErrorMsg: string; var JSONValue: TJSONValue; Error, ErrMsg: TJSONValue; begin JSONValue := TJSONObject.ParseJSONValue(ContentAsString); try if not Assigned(JSONValue) then raise EFirebaseResponse.CreateFmt(rsResponseIsNotJSON, [ContentAsString]) else if not (JSONValue is TJSONObject) then raise EFirebaseResponse.CreateFmt(rsResponseIsNotJSONObj, [ContentAsString]) else if (JSONValue as TJSONObject).TryGetValue('error', Error) then begin if Error.TryGetValue('message', ErrMsg) then result := ErrMsg.Value else result := Error.Value; end else result := ''; finally JSONValue.Free; end; end; function TFirebaseResponse.ErrorMsgOrStatusText: string; var Cont: string; JSONValue: TJSONValue; Error, ErrMsg: TJSONValue; begin result := StatusText; Cont := ContentAsString; if not Cont.IsEmpty then begin JSONValue := TJSONObject.ParseJSONValue(Cont); try if Assigned(JSONValue) and (JSONValue is TJSONObject) and (JSONValue as TJSONObject).TryGetValue('error', Error) then begin if Error.TryGetValue('message', ErrMsg) then result := ErrMsg.Value else if Error is TJSONString then result := Error.Value; end; finally JSONValue.Free; end; end; end; function TFirebaseResponse.IsJSONObj: boolean; var JSONValue: TJSONValue; Error: TJSONValue; begin JSONValue := TJSONObject.ParseJSONValue(ContentAsString); try if not Assigned(JSONValue) then result := false else if not (JSONValue is TJSONObject) then result := false else if (JSONValue as TJSONObject).TryGetValue('error', Error) then result := false else result := true; finally JSONValue.Free; end; end; procedure TFirebaseResponse.CheckForJSONArr; var JSONValue: TJSONValue; Error, ErrMsg: TJSONValue; begin JSONValue := TJSONObject.ParseJSONValue(ContentAsString); try if not Assigned(JSONValue) then raise EFirebaseResponse.CreateFmt(rsResponseIsNotJSON, [ContentAsString]) else if not (JSONValue is TJSONArray) then raise EFirebaseResponse.CreateFmt(rsResponseIsNotJSONArr, [ContentAsString]) else if (JSONValue as TJSONArray).Count < 1 then raise EFirebaseResponse.CreateFmt(rsResponseIsNotJSONArr, [ContentAsString]) else if (JSONValue as TJSONArray).Items[0].TryGetValue('error', Error) then begin if Error.TryGetValue('message', ErrMsg) then raise EFirebaseResponse.Create(ErrMsg.Value) else raise EFirebaseResponse.Create(Error.Value); end; finally JSONValue.Free; end; end; function TFirebaseResponse.GetContentAsJSONObj: TJSONObject; begin result := TJSONObject.ParseJSONValue(ContentAsString) as TJSONObject; end; function TFirebaseResponse.GetContentAsJSONVal: TJSONValue; begin result := TJSONObject.ParseJSONValue(ContentAsString); end; function TFirebaseResponse.GetContentAsJSONArr: TJSONArray; begin result := TJSONObject.ParseJSONValue(ContentAsString) as TJSONArray; end; function TFirebaseResponse.GetServerTime(TimeZone: TTimeZone): TDateTime; const cInitialDate: double = 0; var ServerDate: string; begin result := TDateTime(cInitialDate); if assigned(fHttpResp) then ServerDate := fHttpResp.HeaderValue['Date'] else if assigned(fRestResp) then ServerDate := fRestResp.Headers.Values['Date'] else raise EFirebaseResponse.Create('No initialized response class'); case TimeZone of tzUTC: result := TFirebaseHelpers.ConvertRFC5322ToUTCDateTime(ServerDate); tzLocalTime: result := TFirebaseHelpers.ConvertRFC5322ToLocalDateTime(ServerDate); else EFirebaseResponse.CreateFmt(rsTimeZoneIsNotSupported, [Ord(TimeZone)]); end; end; function TFirebaseResponse.HeaderValue(const HeaderName: string): string; begin result := ''; if assigned(fHttpResp) then result := fHttpResp.HeaderValue[HeaderName]; end; function TFirebaseResponse.GetOnError: TOnRequestError; begin result := fOnError; end; function TFirebaseResponse.GetOnSuccess: TOnSuccess; begin result := fOnSuccess; end; end.
unit armedf_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,m68000,main_engine,controls_engine,gfx_engine,rom_engine,ym_3812, pal_engine,sound_engine,dac,timer_engine,nb1414_m4; function iniciar_armedf:boolean; implementation const //Armed F armedf_rom:array[0..5] of tipo_roms=( (n:'06.3d';l:$10000;p:0;crc:$0f9015e2),(n:'01.3f';l:$10000;p:$1;crc:$816ff7c5), (n:'07.5d';l:$10000;p:$20000;crc:$5b3144a5),(n:'02.4f';l:$10000;p:$20001;crc:$fa10c29d), (n:'af_08.rom';l:$10000;p:$40000;crc:$d1d43600),(n:'af_03.rom';l:$10000;p:$40001;crc:$bbe1fe2d)); armedf_sound:tipo_roms=(n:'af_10.rom';l:$10000;p:0;crc:$c5eacb87); armedf_char:tipo_roms=(n:'09.11c';l:$8000;p:0;crc:$5c6993d5); armedf_bg:array[0..1] of tipo_roms=( (n:'af_14.rom';l:$10000;p:0;crc:$8c5dc5a7),(n:'af_13.rom';l:$10000;p:$10000;crc:$136a58a3)); armedf_fg:array[0..1] of tipo_roms=( (n:'af_04.rom';l:$10000;p:0;crc:$44d3af4f),(n:'af_05.rom';l:$10000;p:$10000;crc:$92076cab)); armedf_sprites:array[0..1] of tipo_roms=( (n:'af_11.rom';l:$20000;p:0;crc:$b46c473c),(n:'af_12.rom';l:$20000;p:$20000;crc:$23cb6bfe)); //Terra Force terraf_rom:array[0..5] of tipo_roms=( (n:'8.6e';l:$10000;p:0;crc:$fd58fa06),(n:'3.6h';l:$10000;p:$1;crc:$54823a7d), (n:'7.4e';l:$10000;p:$20000;crc:$fde8de7e),(n:'2.4h';l:$10000;p:$20001;crc:$db987414), (n:'6.3e';l:$10000;p:$40000;crc:$a5bb8c3b),(n:'1.3h';l:$10000;p:$40001;crc:$d2de6d28)); terraf_sound:tipo_roms=(n:'11.17k';l:$10000;p:0;crc:$4407d475); terraf_nb1414:tipo_roms=(n:'10.11c';l:$4000;p:0;crc:$ac705812); terraf_char:tipo_roms=(n:'9.11e';l:$8000;p:0;crc:$bc6f7cbc); terraf_bg:array[0..1] of tipo_roms=( (n:'15.8a';l:$10000;p:0;crc:$2144d8e0),(n:'14.6a';l:$10000;p:$10000;crc:$744f5c9e)); terraf_fg:array[0..1] of tipo_roms=( (n:'5.15h';l:$10000;p:0;crc:$25d23dfd),(n:'4.13h';l:$10000;p:$10000;crc:$b9b0fe27)); terraf_sprites:array[0..1] of tipo_roms=( (n:'12.7d';l:$10000;p:0;crc:$2d1f2ceb),(n:'13.9d';l:$10000;p:$10000;crc:$1d2f92d6)); //Crazy Climber 2 cclimbr2_rom:array[0..5] of tipo_roms=( (n:'4.bin';l:$10000;p:0;crc:$7922ea14),(n:'1.bin';l:$10000;p:$1;crc:$2ac7ed67), (n:'6.bin';l:$10000;p:$20000;crc:$7905c992),(n:'5.bin';l:$10000;p:$20001;crc:$47be6c1e), (n:'3.bin';l:$10000;p:$40000;crc:$1fb110d6),(n:'2.bin';l:$10000;p:$40001;crc:$0024c15b)); cclimbr2_sound:array[0..1] of tipo_roms=( (n:'11.bin';l:$4000;p:0;crc:$fe0175be),(n:'12.bin';l:$8000;p:$4000;crc:$5ddf18f2)); cclimbr2_nb1414:tipo_roms=(n:'9.bin';l:$4000;p:0;crc:$740d260f); cclimbr2_char:tipo_roms=(n:'10.bin';l:$8000;p:0;crc:$7f475266); cclimbr2_bg:array[0..1] of tipo_roms=( (n:'17.bin';l:$10000;p:0;crc:$e24bb2d7),(n:'18.bin';l:$10000;p:$10000;crc:$56834554)); cclimbr2_fg:array[0..1] of tipo_roms=( (n:'7.bin';l:$10000;p:0;crc:$cbdd3906),(n:'8.bin';l:$10000;p:$10000;crc:$b2a613c0)); cclimbr2_sprites:array[0..3] of tipo_roms=( (n:'15.bin';l:$10000;p:$00000;crc:$4bf838be),(n:'13.bin';l:$10000;p:$20000;crc:$6b6ec999), (n:'16.bin';l:$10000;p:$10000;crc:$21a265c5),(n:'14.bin';l:$10000;p:$30000;crc:$f426a4ad)); //Legion legion_rom:array[0..3] of tipo_roms=( (n:'lg1.bin';l:$10000;p:1;crc:$c4aeb724),(n:'lg3.bin';l:$10000;p:$0;crc:$777e4935), (n:'legion.1b';l:$10000;p:$20001;crc:$c306660a),(n:'legion.1d';l:$10000;p:$20000;crc:$c2e45e1e)); legion_sound:array[0..1] of tipo_roms=( (n:'legion.1h';l:$4000;p:0;crc:$2ca4f7f0),(n:'legion.1i';l:$8000;p:$4000;crc:$79f4a827)); legion_nb1414:tipo_roms=(n:'lg7.bin';l:$4000;p:0;crc:$533e2b58); legion_char:tipo_roms=(n:'lg8.bin';l:$8000;p:0;crc:$e0596570); legion_bg:tipo_roms=(n:'legion.1l';l:$10000;p:0;crc:$29b8adaa); legion_fg:array[0..1] of tipo_roms=( (n:'legion.1e';l:$10000;p:0;crc:$a9d70faf),(n:'legion.1f';l:$8000;p:$18000;crc:$f018313b)); legion_sprites:array[0..1] of tipo_roms=( (n:'legion.1k';l:$10000;p:0;crc:$ff5a0db9),(n:'legion.1j';l:$10000;p:$10000;crc:$bae220c8)); var sprite_mask,sprite_num,video_reg,scroll_fg_x,scroll_fg_y,scroll_bg_x,scroll_bg_y:word; rom:array[0..$2ffff] of word; ram:array[0..$63ff] of word; ram_txt:array[0..$fff] of byte; ram_bg,ram_fg,ram_clut,ram_sprites:array[0..$7ff] of word; size_x,size_y,irq_level,sound_latch,frame,sprite_offset:byte; update_video:procedure; calc_pos_txt:function(x,y:byte):word; procedure draw_sprites(prio:byte); procedure armedf_put_gfx_sprite(nchar:dword;color:word;flipx,flipy:boolean;ngfx,clut:byte); var x,y,pos_y:byte; temp,temp2:pword; pos:pbyte; punto:word; dir_x,dir_y:integer; begin pos:=gfx[ngfx].datos; inc(pos,nchar*16*16); if flipy then begin pos_y:=15; dir_y:=-1; end else begin pos_y:=0; dir_y:=1; end; if flipx then begin temp2:=punbuf; inc(temp2,15); dir_x:=-1; end else begin temp2:=punbuf; dir_x:=1; end; for y:=0 to 15 do begin temp:=temp2; for x:=0 to 15 do begin punto:=ram_clut[clut*$10+pos^] and $f; if (punto<>15) then temp^:=paleta[punto+color] else temp^:=paleta[MAX_COLORES]; inc(temp,dir_x); inc(pos); end; putpixel_gfx_int(0,pos_y,16,PANT_SPRITES); pos_y:=pos_y+dir_y; end; end; var atrib,f,nchar,sx,sy:word; flip_x,flip_y:boolean; color,clut,pri:byte; begin for f:=0 to sprite_num do begin pri:=(buffer_sprites_w[(f*4)+0] and $3000) shr 12; if pri<>prio then continue; nchar:=buffer_sprites_w[(f*4)+1]; flip_x:=(nchar and $2000)<>0; flip_y:=(nchar and $1000)<>0; atrib:=buffer_sprites_w[(f*4)+2]; color:=(atrib shr 8) and $1f; clut:=atrib and $7f; sx:=buffer_sprites_w[(f*4)+3] and $1ff; sy:=sprite_offset+240-(buffer_sprites_w[(f*4)+0] and $1ff); armedf_put_gfx_sprite(nchar and sprite_mask,(color shl 4)+$200,flip_x,flip_y,3,clut); actualiza_gfx_sprite(sx,sy,5,3); end; end; procedure draw_fg_bg(f:word;x,y:byte); var color:byte; atrib,nchar:word; begin atrib:=ram_bg[f]; color:=atrib shr 11; if (gfx[1].buffer[f] or buffer_color[color+$40]) then begin nchar:=atrib and $3ff; put_gfx_trans(x*16,y*16,nchar,(color shl 4)+$600,3,1); gfx[1].buffer[f]:=false; end; atrib:=ram_fg[f]; color:=atrib shr 11; if (gfx[2].buffer[f] or buffer_color[color+$20]) then begin nchar:=atrib and $3ff; put_gfx_trans(x*16,y*16,nchar,(color shl 4)+$400,4,2); gfx[2].buffer[f]:=false; end; end; procedure update_video_armedf; var f,nchar,atrib:word; x,y,color:byte; begin for f:=0 to $7ff do begin x:=f div 32; y:=f mod 32; atrib:=ram_txt[$800+f]; color:=atrib shr 4; if (gfx[0].buffer[f] or buffer_color[color]) then begin nchar:=ram_txt[f]+((atrib and $3) shl 8); color:=color shl 4; put_gfx(x*8,y*8,nchar,color,1,0); if (atrib and $8)=0 then put_gfx_trans(x*8,y*8,nchar,color,2,0) else put_gfx_block_trans(x*8,y*8,2,8,8); gfx[0].buffer[f]:=false; end; draw_fg_bg(f,x,y); end; if (video_reg and $100)<>0 then actualiza_trozo(0,0,512,256,1,0,0,512,256,5) else fill_full_screen(5,$800); if (video_reg and $800)<>0 then scroll_x_y(3,5,scroll_bg_x,scroll_bg_y); if (video_reg and $200)<>0 then draw_sprites(2); if (video_reg and $400)<>0 then scroll_x_y(4,5,scroll_fg_x,scroll_fg_y); if (video_reg and $200)<>0 then draw_sprites(1); if (video_reg and $100)<>0 then actualiza_trozo(0,0,512,256,2,0,0,512,256,5); if (video_reg and $200)<>0 then draw_sprites(0); actualiza_trozo_final(96,8,320,240,5); fillchar(buffer_color,MAX_COLOR_BUFFER,0); copymemory(@buffer_sprites_w[0],@ram_sprites[0],$1000*2); end; function calc_pos_terraf(x,y:byte):word; begin calc_pos_terraf:=32*(31-y)+(x and $1f)+$800*(x div 32); end; function calc_pos_legion(x,y:byte):word; begin calc_pos_legion:=(x and $1f)*32+y+$800*(x div 32); end; procedure update_video_terraf; var f,nchar,atrib,pos:word; x,y,color:byte; begin for f:=0 to $7ff do begin x:=f div 32; y:=f mod 32; pos:=calc_pos_txt(x,y); if pos<$12 then begin atrib:=0; nchar:=0; color:=0; end else begin atrib:=ram_txt[$400+pos]; nchar:=ram_txt[pos]; color:=atrib shr 4; end; if (gfx[0].buffer[pos] or buffer_color[color]) then begin nchar:=nchar or ((atrib and $3) shl 8); color:=color shl 4; put_gfx(x*8,y*8,nchar,color,1,0); if (atrib and $8)=0 then put_gfx_trans(x*8,y*8,nchar,color,2,0) else put_gfx_block_trans(x*8,y*8,2,8,8); gfx[0].buffer[pos]:=false; end; draw_fg_bg(f,x,y); end; if (video_reg and $100)<>0 then scroll__x(1,5,512-128) else fill_full_screen(5,$800); if (video_reg and $800)<>0 then scroll_x_y(3,5,scroll_bg_x,scroll_bg_y); if (video_reg and $200)<>0 then draw_sprites(2); if (video_reg and $400)<>0 then scroll_x_y(4,5,scroll_fg_x,scroll_fg_y); if (video_reg and $200)<>0 then draw_sprites(1); if (video_reg and $100)<>0 then scroll__x(2,5,512-128); if (video_reg and $200)<>0 then draw_sprites(0); //actualiza_trozo_final(96,8,320,240,5); actualiza_trozo_final(96+size_x,8+size_y,320-(size_x shl 1),240-(size_y shl 1),5); fillchar(buffer_color,MAX_COLOR_BUFFER,0); copymemory(@buffer_sprites_w[0],@ram_sprites[0],$1000*2); end; procedure eventos_armedf; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fff7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $ffbf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $100); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $400); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $800); //P2 if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $20); if arcade_input.but2[1] then marcade.in1:=(marcade.in1 and $ffbf) else marcade.in1:=(marcade.in1 or $40); end; end; procedure armedf_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //sound z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; case f of 247:begin m68000_0.irq[irq_level]:=ASSERT_LINE; update_video; end; end; end; frame:=frame+1; eventos_armedf; video_sync; end; end; function armedf_getword(direccion:dword):word; begin case direccion of 0..$5ffff:armedf_getword:=rom[direccion shr 1]; $60000..$60fff:armedf_getword:=ram_sprites[(direccion and $fff) shr 1]; $61000..$65fff,$6c008..$6c7ff:armedf_getword:=ram[(direccion-$60000) shr 1]; $66000..$66fff:armedf_getword:=ram_bg[(direccion and $fff) shr 1]; $67000..$67fff:armedf_getword:=ram_fg[(direccion and $fff) shr 1]; $68000..$69fff:armedf_getword:=ram_txt[(direccion and $1fff) shr 1]; $6a000..$6afff:armedf_getword:=buffer_paleta[(direccion and $fff) shr 1]; $6b000..$6bfff:armedf_getword:=ram_clut[(direccion and $fff) shr 1]; $6c000:armedf_getword:=marcade.in0; $6c002:armedf_getword:=marcade.in1; $6c004:armedf_getword:=marcade.dswa; $6c006:armedf_getword:=marcade.dswb; end; end; procedure cambiar_color(pos,data:word); var color:tcolor; begin color.r:=pal4bit(data shr 8); color.g:=pal4bit(data shr 4); color.b:=pal4bit(data); set_pal_color(color,pos); case pos of 0..$1ff:buffer_color[pos shr 4]:=true;//chars $400..$5ff:buffer_color[((pos and $1ff) shr 4)+$20]:=true; //fg $600..$7ff:buffer_color[((pos and $1ff) shr 4)+$40]:=true; //bg end; end; procedure armedf_putword(direccion:dword;valor:word); begin case direccion of 0..$5ffff:; $60000..$60fff:ram_sprites[(direccion and $fff) shr 1]:=valor; $61000..$65fff,$6c000..$6c7ff:ram[(direccion-$60000) shr 1]:=valor; $66000..$66fff:if ram_bg[(direccion and $fff) shr 1]<>valor then begin ram_bg[(direccion and $fff) shr 1]:=valor; gfx[1].buffer[((direccion and $fff) shr 1) and $7ff]:=true; end; $67000..$67fff:if ram_fg[(direccion and $fff) shr 1]<>valor then begin ram_fg[(direccion and $fff) shr 1]:=valor; gfx[2].buffer[((direccion and $fff) shr 1) and $7ff]:=true; end; $68000..$69fff:if ram_txt[(direccion and $1fff) shr 1]<>(valor and $ff) then begin ram_txt[(direccion and $1fff) shr 1]:=valor and $ff; gfx[0].buffer[((direccion and $1fff) shr 1) and $7ff]:=true; end; $6a000..$6afff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin buffer_paleta[(direccion and $fff) shr 1]:=valor; cambiar_color((direccion and $fff) shr 1,valor); end; $6b000..$6bfff:ram_clut[(direccion and $fff) shr 1]:=valor; $6d000:video_reg:=valor; $6d002:scroll_bg_x:=valor; $6d004:scroll_bg_y:=valor; $6d006:scroll_fg_x:=valor; $6d008:scroll_fg_y:=valor; $6d00a:sound_latch:=((valor and $7f) shl 1) or 1; $6d00e:m68000_0.irq[1]:=CLEAR_LINE; end; end; //Terra Force function terraf_getword(direccion:dword):word; begin case direccion of 0..$5ffff:terraf_getword:=rom[direccion shr 1]; $60000..$603ff:terraf_getword:=ram_sprites[(direccion and $fff) shr 1]; $60400..$63fff,$6a000..$6a9ff:terraf_getword:=ram[(direccion-$60000) shr 1]; $64000..$64fff:terraf_getword:=buffer_paleta[(direccion and $fff) shr 1]; $68000..$69fff:terraf_getword:=ram_txt[(direccion and $1fff) shr 1]; $6c000..$6cfff:terraf_getword:=ram_clut[(direccion and $fff) shr 1]; $70000..$70fff:terraf_getword:=ram_fg[(direccion and $fff) shr 1]; $74000..$74fff:terraf_getword:=ram_bg[(direccion and $fff) shr 1]; $78000:terraf_getword:=marcade.in0; $78002:terraf_getword:=marcade.in1; $78004:terraf_getword:=marcade.dswa; $78006:terraf_getword:=marcade.dswb; end; end; procedure terraf_putword(direccion:dword;valor:word); var dir:word; begin case direccion of 0..$5ffff:; $60000..$603ff:ram_sprites[(direccion and $fff) shr 1]:=valor; $60400..$63fff,$6a000..$6a9ff:ram[(direccion-$60000) shr 1]:=valor; $64000..$64fff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin buffer_paleta[(direccion and $fff) shr 1]:=valor; cambiar_color((direccion and $fff) shr 1,valor); end; $68000..$69fff:if ram_txt[(direccion and $1fff) shr 1]<>(valor and $ff) then begin dir:=(direccion and $1fff) shr 1; ram_txt[dir]:=valor and $ff; gfx[0].buffer[(dir and $3ff)+(dir and $800)]:=true; end; $6c000..$6cfff:ram_clut[(direccion and $fff) shr 1]:=valor; $70000..$70fff:if ram_fg[(direccion and $fff) shr 1]<>valor then begin ram_fg[(direccion and $fff) shr 1]:=valor; gfx[2].buffer[((direccion and $fff) shr 1) and $7ff]:=true; end; $74000..$74fff:if ram_bg[(direccion and $fff) shr 1]<>valor then begin ram_bg[(direccion and $fff) shr 1]:=valor; gfx[1].buffer[((direccion and $fff) shr 1) and $7ff]:=true; end; $7c000:begin if (((valor and $4000)<>0) and ((video_reg and $4000)=0)) then nb1414m4_0.exec(scroll_fg_x,scroll_fg_y,frame); video_reg:=valor; end; $7c002:scroll_bg_x:=valor; $7c004:scroll_bg_y:=valor; $7c00a:sound_latch:=((valor and $7f) shl 1) or 1; $7c00e:m68000_0.irq[irq_level]:=CLEAR_LINE; end; end; //Sound function armedf_snd_getbyte(direccion:word):byte; begin armedf_snd_getbyte:=mem_snd[direccion]; end; procedure armedf_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$f7ff:; $f800..$ffff:mem_snd[direccion]:=valor; end; end; function armedf_snd_in(puerto:word):byte; begin case (puerto and $ff) of 4:sound_latch:=0; 6:armedf_snd_in:=sound_latch; end; end; procedure armedf_snd_out(puerto:word;valor:byte); begin case (puerto and $ff) of 0:ym3812_0.control(valor); 1:ym3812_0.write(valor); 2:dac_0.signed_data8_w(valor); 3:dac_1.signed_data8_w(valor); end; end; procedure armedf_snd_irq; begin z80_0.change_irq(HOLD_LINE); end; procedure cclimb2_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$bfff:; $c000..$ffff:mem_snd[direccion]:=valor; end; end; procedure armedf_sound_update; begin ym3812_0.update; dac_0.update; dac_1.update; end; //Main procedure reset_armedf; begin m68000_0.reset; z80_0.reset; YM3812_0.reset; dac_0.reset; dac_1.reset; if main_vars.tipo_maquina=276 then nb1414m4_0.reset; reset_audio; marcade.in0:=$ffff; marcade.in1:=$ffff; scroll_fg_x:=0; scroll_fg_y:=0; scroll_bg_x:=0; scroll_bg_y:=0; sound_latch:=0; frame:=0; video_reg:=0; end; function iniciar_armedf:boolean; var memoria_temp:array[0..$5ffff] of byte; const pf_x:array[0..15] of dword=(4, 0, 12, 8, 20, 16, 28, 24, 32+4, 32+0, 32+12, 32+8, 32+20, 32+16, 32+28, 32+24); pf_y:array[0..15] of dword=(0*64, 1*64, 2*64, 3*64, 4*64, 5*64, 6*64, 7*64, 8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64); ps_x:array[0..15] of dword=(4, 0, $800*64*8+4, $800*64*8+0, 12, 8, $800*64*8+12, $800*64*8+8, 20, 16, $800*64*8+20, $800*64*8+16, 28, 24, $800*64*8+28, $800*64*8+24); ps_x_terraf:array[0..15] of dword=(4, 0, $400*64*8+4, $400*64*8+0, 12, 8, $400*64*8+12, $400*64*8+8, 20, 16, $400*64*8+20, $400*64*8+16, 28, 24, $400*64*8+28, $400*64*8+24); ps_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32); procedure conv_chars(num:word); begin init_gfx(0,8,8,num); gfx[0].trans[15]:=true; gfx_set_desc_data(4,0,32*8,0,1,2,3); convert_gfx(0,0,@memoria_temp,@pf_x,@ps_y,false,false); end; procedure conv_tiles(num:word;ngfx:byte); begin init_gfx(ngfx,16,16,num); gfx[ngfx].trans[15]:=true; gfx_set_desc_data(4,0,128*8,0,1,2,3); convert_gfx(ngfx,0,@memoria_temp,@pf_x,@pf_y,false,false); end; procedure conv_sprites(num:word); begin init_gfx(3,16,16,num); gfx_set_desc_data(4,0,64*8,0,1,2,3); case main_vars.tipo_maquina of 275,277:convert_gfx(3,0,@memoria_temp,@ps_x,@ps_y,false,false); 276,278:convert_gfx(3,0,@memoria_temp,@ps_x_terraf,@ps_y,false,false) end; end; begin llamadas_maquina.bucle_general:=armedf_principal; llamadas_maquina.reset:=reset_armedf; llamadas_maquina.fps_max:=59.082012; iniciar_armedf:=false; iniciar_audio(false); //Pantallas screen_init(1,512,256,false); screen_mod_scroll(1,512,512,511,256,256,255); screen_init(2,512,256,true); screen_mod_scroll(2,512,512,511,256,256,255); screen_init(3,1024,512,true); screen_mod_scroll(3,1024,512,1023,512,256,511); screen_init(4,1024,512,true); screen_mod_scroll(4,1024,512,1023,512,256,511); screen_init(5,512,512,false,true); if ((main_vars.tipo_maquina=275) or (main_vars.tipo_maquina=278)) then main_screen.rot270_screen:=true; size_x:=0; size_y:=0; case main_vars.tipo_maquina of 275,276:iniciar_video(320,240); 277,278:begin iniciar_video(288,224); size_x:=16; size_y:=8; end; end; //Main CPU m68000_0:=cpu_m68000.create(8000000,256); //Sound CPU z80_0:=cpu_z80.create(4000000,256); z80_0.change_ram_calls(armedf_snd_getbyte,armedf_snd_putbyte); z80_0.change_io_calls(armedf_snd_in,armedf_snd_out); z80_0.init_sound(armedf_sound_update); timers.init(z80_0.numero_cpu,4000000/(4000000/512),armedf_snd_irq,nil,true); //Sound Chips if (main_vars.tipo_maquina=278) then ym3812_0:=ym3812_chip.create(YM3526_FM,4000000,0.4) else ym3812_0:=ym3812_chip.create(YM3812_FM,4000000,0.4); dac_0:=dac_chip.create(2); dac_1:=dac_chip.create(2); irq_level:=1; sprite_offset:=$80; calc_pos_txt:=calc_pos_terraf; update_video:=update_video_terraf; case main_vars.tipo_maquina of 275:begin //Armed F m68000_0.change_ram16_calls(armedf_getword,armedf_putword); //cargar roms if not(roms_load16w(@rom,armedf_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,armedf_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,armedf_char)) then exit; conv_chars($400); //convertir bg if not(roms_load(@memoria_temp,armedf_bg)) then exit; conv_tiles($400,1); //convertir fg if not(roms_load(@memoria_temp,armedf_fg)) then exit; conv_tiles($400,2); //convertir sprites if not(roms_load(@memoria_temp,armedf_sprites)) then exit; conv_sprites($800); //DIP marcade.dswa:=$ffdf; marcade.dswb:=$ffcf; //Misc update_video:=update_video_armedf; sprite_mask:=$7ff; sprite_num:=$200-1; end; 276:begin //Terra Force m68000_0.change_ram16_calls(terraf_getword,terraf_putword); //nb1414 nb1414m4_0:=tnb1414_m4.create(@ram_txt[0]); if not(roms_load(nb1414m4_0.get_internal_rom,terraf_nb1414)) then exit; //cargar roms if not(roms_load16w(@rom,terraf_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,terraf_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,terraf_char)) then exit; conv_chars($400); //convertir bg if not(roms_load(@memoria_temp,terraf_bg)) then exit; conv_tiles($400,1); //convertir fg if not(roms_load(@memoria_temp,terraf_fg)) then exit; conv_tiles($400,2); //convertir sprites if not(roms_load(@memoria_temp,terraf_sprites)) then exit; conv_sprites($400); //DIP marcade.dswa:=$ffcf; marcade.dswb:=$ff3f; //Misc sprite_mask:=$3ff; sprite_num:=$80-1; end; 277:begin //Crazy Climber 2 m68000_0.change_ram16_calls(terraf_getword,terraf_putword); //nb1414 nb1414m4_0:=tnb1414_m4.create(@ram_txt[0]); if not(roms_load(nb1414m4_0.get_internal_rom,cclimbr2_nb1414)) then exit; //cargar roms if not(roms_load16w(@rom,cclimbr2_rom)) then exit; //cargar sonido z80_0.change_ram_calls(armedf_snd_getbyte,cclimb2_snd_putbyte); if not(roms_load(@mem_snd,cclimbr2_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,cclimbr2_char)) then exit; conv_chars($400); //convertir bg if not(roms_load(@memoria_temp,cclimbr2_bg)) then exit; conv_tiles($400,1); //convertir fg if not(roms_load(@memoria_temp,cclimbr2_fg)) then exit; conv_tiles($400,2); //convertir sprites if not(roms_load(@memoria_temp,cclimbr2_sprites)) then exit; conv_sprites($800); //DIP marcade.dswa:=$ffdf; marcade.dswb:=$ffff; //Misc sprite_mask:=$7ff; sprite_num:=$200-1; irq_level:=2; sprite_offset:=0; end; 278:begin //Legion m68000_0.change_ram16_calls(terraf_getword,terraf_putword); //nb1414 nb1414m4_0:=tnb1414_m4.create(@ram_txt[0]); if not(roms_load(nb1414m4_0.get_internal_rom,legion_nb1414)) then exit; //cargar roms if not(roms_load16w(@rom,legion_rom)) then exit; //cargar sonido z80_0.change_ram_calls(armedf_snd_getbyte,cclimb2_snd_putbyte); if not(roms_load(@mem_snd,legion_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,legion_char)) then exit; conv_chars($400); //convertir bg if not(roms_load(@memoria_temp,legion_bg)) then exit; conv_tiles($400,1); //convertir fg if not(roms_load(@memoria_temp,legion_fg)) then exit; conv_tiles($400,2); //convertir sprites if not(roms_load(@memoria_temp,legion_sprites)) then exit; conv_sprites($400); //DIP marcade.dswa:=$ffdf; marcade.dswb:=$ffff; //Misc calc_pos_txt:=calc_pos_legion; sprite_mask:=$3ff; sprite_num:=$80-1; irq_level:=2; sprite_offset:=0; end; end; //final reset_armedf; iniciar_armedf:=true; end; end.
unit FindUnit.CompilerInterceptor; interface uses ToolsAPI, FindUnit.EnvironmentController, SysUtils; type TCompilerInterceptor = class(TNotifierObject, IOTANotifier, IOTAIDENotifier, IOTAIDENotifier50) protected class var FNotifierIndex: Integer; FEnvControl: TEnvironmentController; procedure FileNotification(NotifyCode: TOTAFileNotification; const FileName: string; var Cancel: Boolean); procedure BeforeCompile(const Project: IOTAProject; IsCodeInsight: Boolean; var Cancel: Boolean); overload; procedure AfterCompile(Succeeded: Boolean; IsCodeInsight: Boolean); overload; procedure BeforeCompile(const Project: IOTAProject; var Cancel: Boolean); overload; procedure AfterCompile(Succeeded: Boolean); overload; public constructor Create; procedure SetEnvControl(Env: TEnvironmentController); end; var CompilerInterceptor: TCompilerInterceptor; procedure Register; implementation procedure Register; var Services: IOTAServices; begin if not Supports(BorlandIDEServices, IOTAServices, Services) then Exit; CompilerInterceptor := TCompilerInterceptor.Create; CompilerInterceptor.FNotifierIndex := Services.AddNotifier(CompilerInterceptor); end; { TCompilerInterceptor } procedure TCompilerInterceptor.AfterCompile(Succeeded, IsCodeInsight: Boolean); begin end; procedure TCompilerInterceptor.AfterCompile(Succeeded: Boolean); begin end; procedure TCompilerInterceptor.BeforeCompile(const Project: IOTAProject; var Cancel: Boolean); begin Cancel := False; end; constructor TCompilerInterceptor.Create; begin inherited; FNotifierIndex := -1; end; procedure TCompilerInterceptor.BeforeCompile(const Project: IOTAProject; IsCodeInsight: Boolean; var Cancel: Boolean); begin Cancel := False; if FEnvControl = nil then Exit; if not IsCodeInsight then Exit; FEnvControl.ImportMissingUnits(False); end; procedure TCompilerInterceptor.FileNotification(NotifyCode: TOTAFileNotification; const FileName: string; var Cancel: Boolean); begin Cancel := False; end; procedure TCompilerInterceptor.SetEnvControl(Env: TEnvironmentController); begin FEnvControl := Env; end; procedure UnRegister; var Services: IOTAServices; begin if (CompilerInterceptor.FNotifierIndex > -1) and Supports(BorlandIDEServices, IOTAServices, Services) then Services.RemoveNotifier(CompilerInterceptor.FNotifierIndex); end; initialization finalization UnRegister; end.
unit uEstado; {$mode objfpc}{$H+} interface uses Classes, SysUtils, contnrs, uParamTransicao; type { TEstado } TEstado = class(TObject) private FId: string; FFinal: Boolean; FListaParamTransicoes: TListaParamTransicao; public constructor Create(const pId: string; const pFinal: boolean); destructor Destroy;override; property Id:string read FId; property Final: Boolean read FFinal default False; property ListaParamTransicoes: TListaParamTransicao read FListaParamTransicoes write FListaParamTransicoes; end; { TListaEstado } TListaEstado = class(TObjectList) private function GetItem(const pIndex: integer): TEstado; procedure SetItem(const pIndex: integer; pValue: TEstado); public function ItemByID(const pID: string): TEstado; property Items[index: Integer]: TEstado read GetItem write SetItem; end; implementation { TListaEstado } function TListaEstado.GetItem(const pIndex: integer): TEstado; begin result := TEstado(inherited Items[pIndex]); end; procedure TListaEstado.SetItem(const pIndex: integer; pValue: TEstado); begin Items[pIndex] := pValue; end; function TListaEstado.ItemByID(const pID: string): TEstado; var lIndex: integer; begin Result := nil; for lIndex := 0 to pred(Self.Count) do begin if Self.Items[lIndex].Fid = pID then begin Result := Self.Items[lIndex]; end; end; end; { TEstado } constructor TEstado.Create(const pId: string; const pFinal: boolean); begin inherited Create; FId := pId; FFinal := pFinal; FListaParamTransicoes := TListaParamTransicao.Create(); end; destructor TEstado.Destroy; begin FListaParamTransicoes.Destroy; inherited Destroy; end; end.
unit LoggingUnit; {* Операции логирования действий пользователя } // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\LoggingUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "Logging" MUID: (45ED58CF03E6) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , BaseTypesUnit ; type TLogEvent = ( {* События логирования } LE_OPEN_DOCUMENT_FROM_LIST {* Открытие документа из списка } , LE_OPEN_DOCUMENT_FROM_LINK {* Открытие документа по ссылке } , LE_OPEN_MAIN_MENU {* Открытие основного меню } , LE_OPEN_DICTIONARY {* Открытие толкового словаря } , LE_ADD_TO_LIST {* Добавление документов в список } , LE_DELETE_FROM_LIST {* Удаление документов из списка } , LE_GET_DOCUMENT_STRUCTURE {* Запрос структуры докумнта } , LE_SEARCH_IN_DOCUMENT {* Поиск в документе } , LE_OPEN_RELATED {* открытие справки } , LE_OPEN_ANNOTATION , LE_EXPORT_TO_FILE {* Экспорт в файл } , LE_EXPORT_TO_WORD {* Экспорт в ворд } , LE_USER_OPERATION {* Любая пользовательская операция из меню, тулбара итд } , LE_OPEN_DOCUMENT_FROM_FOLDERS {* открытие документа из папок } , LE_SAVE_DOCUMENT_TO_FOLDERS {* Сохранение документа в папки } , LE_PRIMARY_MONITOR_RESOLUTION {* Разрешение на основном мониторе } , LE_DPI {* Размер системного шрифта } , LE_FONT_SIZE {* Рзамер основоного шрифта } , LE_FIND_CONTEXT_IN_LIST {* Поиск контекста в списке } , LE_OPEN_DOCUMENT_FROM_HISTORY {* Открытие документа из истории } , LE_LIST_PRINT {* Печать списка } , LE_LIST_PRINT_PREVIEW {* Предварительный просмотр печати списка } , LE_LIST_SORT {* Направление и порядок сортировки списка } , LE_LIST_REFERENCE_ACTIVATE , LE_SYNCHROVIEW_ACTIVATE {* Вкладка Синхронный просмотр } , LE_TIME_MACHINE_ON {* Включение машины времени } , LE_TIME_MACHINE_OFF {* Выключение машины времени } , LE_NEXT_DOCUMENT {* Переход на след документ в списке } , LE_PREV_DOCUMENT {* Переход на предыдущий документ в списке } , LE_VIEW_DOCUMENT_EDITION_LIST {* просмотр списка редакций документа } , LE_VIEW_DOCUMENT_ATTRIBUTES {* просмотр атрибутов документа } , LE_BACK {* Шаг назад } , LE_FORWARD {* Шаг вперед } , LE_INC_FONT {* Увеличение шрифта } , LE_DEC_FONT {* Уменьшение шрифта } , LE_OPEN_NEWS_LINE {* Открытие Новостной ленты } , LE_OPEN_CONSULTATION {* Открытие Мои консультации } , LE_SAVE_QUERY {* Сохранение запроса в папки } , LE_LOAD_QUERY {* Загрузка запроса из папок } , LE_LOAD_QUERY_FROM_HISTORY {* Загрузка запроса из истории } , LE_CONTEXT_FILTER_IN_TREE {* Контекстаня фильтрация дерева } , LE_DOCUMENT_PRINT {* Печать документа } , LE_DOCUMENT_PRINT_PREVIEW {* Предварительный просмотр печати } , LE_VIEW_SAME_DOCUMENTS {* Просмотр похожих документов } , LE_SEND_DOCUMENT_BY_EMAIL {* Отправка документа по емейл } , LE_SEND_LIST_BY_EMAIL {* Отправка списка по емейлу } , LE_UNKNOWN {* Неизвестное событие - можно использовать при неготовности сервера/адаптера для логирования новых событий } , LE_SEND_TEST_REQUEST_TO_LEGAL_ADVISE {* Проверка соединения с ППО (отправка тестового запроса) } , LE_OPEN_MEDIC_FIRMS {* Открытие списка фирм } , LE_OPEN_MEDIC_DICTIONARY {* Открытие толкового медицинского словаря } , LE_USE_SUB_PANEL_DOCUMENT_OPERATION {* Факт вызова любых операций из Меню к фрагменту документа на полях документа } , LE_USE_BASE_SEARCH_EXAMPLE {* Количество подстановок в панель БП текстов из примеров } , LE_USE_TASK_PANEL_OPERATION {* Количество вызовов операций с вкладки "Панель задач" } , LE_SEND_REQUEST_TO_LEGAL_ADVISE {* Отправка запроса в ППО } , LE_OPEN_DOCUMENT_BY_NUMBER {* Открытие документа по номеру } , LE_OPEN_PHARM_DOCUMENT {* Открытие документа - описание препарата } , LE_OPEN_PHARM_FIRM_DOCUMENT {* Открытие документа описание фирмы } , LE_USE_BASE_SEARCH_HINT , LE_LIST_EXPORT_TO_FILE , LE_LIST_EXPORT_TO_WORD , LE_USE_BACK_SEARCH_BUTTON {* при контекстном поиске внутри документа нажатие на кнопку "Назад" } , LE_OPEN_INTERNET_AGENT {* открытие окна Интернет-агента } , LE_SWITCH_VERSION_COMMENTS {* включение-выключение версионных комментариев } , LE_CHAT_WINDOW_OPENS_COUNT {* работа с чатом } , LE_SEARCH_IN_DOCUMENT_DONE {* поиск в документе завершен } , LE_NEXT_SEARCH_IN_DOCUMENT {* поиск следующего вхождения в документе } , LE_PREVIOUS_SEARCH_IN_DOCUMENT {* поиск предыдущего вхождения в документе } , LE_DOCUMENT_NOT_EXIST {* Документа нет в базе или запрещен к просмотру } , LE_OPEN_DOCUMENT_FROM_SEARCH_HINT {* Открытие документа из словаря подсказок } );//TLogEvent ILogEventData = interface {* Данные события логирования } ['{4B1A4AE4-7B43-471C-8FC0-94167B5706BC}'] procedure AddObject(const data: IUnknown); stdcall; procedure AddString(data: PAnsiChar); stdcall; procedure AddUlong(data: Cardinal); stdcall; procedure AddDate(const data: TDate); stdcall; procedure WriteToLog(log_event: TLogEvent); stdcall; {* Записать в лог } end;//ILogEventData ILogManager = interface {* Менеджер записи в лог } ['{23621F05-BC03-409D-8EBB-53D5BB3E1D95}'] procedure AddEvent(log_event: TLogEvent; var data: ILogEventData); stdcall; end;//ILogManager implementation uses l3ImplUses ; end.
unit uFileFolder; interface uses SysUtils, Classes, Windows, Dialogs, uLNG, uSuperReplace; const { Parametry k funkci GetFileVersion } //GET_FILE_VER_ALL = 9; // Vrací celou verzi souboru GET_FILE_VER_MAJOR = 0; // Vrací pouze číslo MAJOR verze GET_FILE_VER_MINOR = 1; // Vrací pouze číslo MINOR verze GET_FILE_VER_RELEASE = 2; // Vrací pouze číslo RELEASE verze GET_FILE_VER_BUILD = 3; // Vrací pouze číslo BUILD verze procedure CheckFolder(Path: WideString; ErrorInfo: Boolean = False); function SetDateToFile(const FileName: WideString; Value: TDateTime): Boolean; // File function CreateFileIfNotExists(FileName: WideString): Boolean; function MoveFileIfExists(FileName, ExtPath: WideString; ReWrite: Boolean = False): Boolean; function CopyFileIfExists(ExistingFileName, NewFileName: WideString; Rewrite: Boolean = False): Boolean; function DeleteFileIfExists(FileName : WideString): Boolean; function GetFileVersionW(FileName: WideString): WideString; overload; function GetFileVersionW(FileName: WideString; Ver: DWORD): Byte; overload; // Folder function CreateFolderIfNotExists(FolderName: WideString): Boolean; function RemoveFolderIfExists(FolderName : WideString): Boolean; implementation procedure CheckFolder(Path: WideString; ErrorInfo: Boolean = False); var rec: TSearchRec; begin if FindFirst(Path, faDirectory, rec) = 0 then else begin try if ForceDirectories(Path)=False then if ErrorInfo=True then ShowMessage( TagsReplace( StringReplace(LNG('Texts', 'DirNotCreate', 'Can''t create directory: %path%') , '%path%', Path, [rfReplaceAll, rfIgnoreCase]) ) ); except if ErrorInfo=True then ShowMessage( TagsReplace( StringReplace(LNG('Texts', 'DirNotCreate', 'Can''t create directory: %path%'), '%path%', Path, [rfReplaceAll, rfIgnoreCase]) ) ); end; end; end; function SetDateToFile(const FileName: WideString; Value: TDateTime): Boolean; var hFile: THandle; begin Result := False; hFile := 0; try {open a file handle} hFile := FileOpen(FileName, fmOpenWrite or fmShareDenyNone); {if opened succesfully} if (hFile > 0) then {convert a datetime into DOS format and set a date} Result := (FileSetDate(hFile, DateTimeToFileDate(Value)) = 0) finally {close an opened file handle} FileClose(hFile); end; end; { FILE } function CreateFileIfNotExists(FileName: WideString): Boolean; var F: TextFile; begin if not FileExists(FileName) then begin AssignFile(F, FileName); ReWrite(F); WriteLn(F,'; Code page: UTF-8'); WriteLn(F); CloseFile(F); end; Result := FileExists(FileName); end; function MoveFileIfExists(FileName, ExtPath: WideString; ReWrite: Boolean = False): Boolean; var Param: Cardinal; begin CreateFolderIfNotExists( ExtractFileName(ExtPath) ); // existuje cílový adresář ? (*if ReWrite then begin Param := MOVEFILE_REPLACE_EXISTING; end else Param := 0; Result := True; *) if MoveFileExW( PWideChar(FileName), PWideChar(ExtPath), MOVEFILE_REPLACE_EXISTING) = True then begin Result := False; //ShowMessage( 'Error: ' + IntToStr(GetLastError) ); end; (*if CopyFileIfExists(FileName, ExtPath + ExtractFileName(FileName), ReWrite) then // byl zkopírováno ? DeleteFileW( PWideChar(FileName) ); // tak smaž původní soubor *) if not FileExists(FileName) then // byl smazán původní soubor ? Result := FileExists(ExtPath + ExtractFileName(FileName)) // byl přesunut ? else Result := False; // nahlaš chybu end; function CopyFileIfExists(ExistingFileName, NewFileName: WideString; ReWrite: Boolean = False): Boolean; begin if FileExists(ExistingFileName) then CopyFileW( PWideChar(ExistingFileName), PWideChar(NewFileName), not ReWrite); // not ReWrite = FALSE => Soubor bude přepsán Result := FileExists(ExistingFileName); end; function DeleteFileIfExists(FileName : WideString): Boolean; begin if FileExists(FileName) then DeleteFileW( PWideChar(FileName) ); Result := not FileExists(FileName); end; function GetFileVersionW(FileName: WideString): WideString; overload; begin Result := IntToStr( GetFileVersionW(FileName, GET_FILE_VER_MAJOR) ); Result := Result + '.' + IntToStr( GetFileVersionW(FileName, GET_FILE_VER_MINOR) ); Result := Result + '.' + IntToStr( GetFileVersionW(FileName, GET_FILE_VER_RELEASE) ); Result := Result + '.' + IntToStr( GetFileVersionW(FileName, GET_FILE_VER_BUILD) ); end; function GetFileVersionW(FileName: WideString; Ver: DWORD): Byte; overload; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; begin VerInfoSize := GetFileVersionInfoSizeW(PWideChar(FileName), Dummy); GetMem(VerInfo, VerInfoSize); GetFileVersionInfoW(PWideChar(FileName), 0, VerInfoSize, VerInfo); VerQueryValueW(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin case Ver of GET_FILE_VER_MAJOR: Result := dwFileVersionMS shr 16; GET_FILE_VER_MINOR: Result := dwFileVersionMS and $FFFF; GET_FILE_VER_RELEASE: Result := dwFileVersionLS shr 16; GET_FILE_VER_BUILD: Result := dwFileVersionLS and $FFFF; end; end; FreeMem(VerInfo, VerInfoSize); end; { FOLDER } function CreateFolderIfNotExists(FolderName: WideString): Boolean; begin if not DirectoryExists(FolderName) then CheckFolder( FolderName ); Result := DirectoryExists(FolderName); end; (*function MoveFolderIfNotExists(FolderName: WideString; ReWrite: Boolean = False): Boolean; begin if not DirectoryExists(FolderName) then CheckFolder( FolderName ); MoveFileExW() Result := DirectoryExists(FolderName); end;*) function RemoveFolderIfExists(FolderName : WideString): Boolean; begin if DirectoryExists(FolderName) then RemoveDirectoryW( PChar(FolderName) ); Result := not DirectoryExists(FolderName); end; end.
unit fvm.Combinations; interface uses Generics.Collections, Classes, SyncObjs; function CalculateNumberOfCombinations(NumPlaces, MaxValue: cardinal): cardinal; const MaxPlacesConst = 6; type TCombination = uint64; TCombinationRec = packed record case integer of 0 : (MaxValue, NumPlaces: byte; Data: array[0..MaxPlacesConst-1] of byte); 1 : (Blob: TCombination); end; function CombinationToString(Source: TCombination): string; function StringToCombination(const Line: string): TCombination; inline; type PCombinationListData = ^TCombinationListData; TCombinationListData = array[0..0] of TCombination; TCombinationList = class private FCount : integer; FCapacity : integer; Lock : TCriticalSection; function GetItems(Index: integer): TCombination; procedure SetItems(Index: integer; NewValue: TCombination); procedure SetCapacity(NewValue: integer); function GetNumPlaces: cardinal; function GetMaxValue: cardinal; function ToRawStrings: TStrings; public FItems : PCombinationListData; constructor Create; destructor Destroy; override; procedure Add(Item: TCombination); overload; procedure Delete(Index: integer); procedure Remove(Item: TCombination); procedure Clear; procedure Assign(Source: TCombinationList); procedure SaveToFile(const FileName: string); procedure LoadFromFile(const FileName: string); function ToStrings: TStrings; property Capacity: integer read FCapacity write SetCapacity; property Count: integer read FCount; property Items[Index: integer]: TCombination read GetItems write SetItems; property NumPlaces: cardinal read GetNumPlaces; property MaxValue: cardinal read GetMaxValue; end; procedure CalculateCombinations(NumPlaces, MaxValue: cardinal; ResultList: TCombinationList); // minvalue = 1 implementation uses SysUtils, fvm.Strings, Windows; const FlagMaskConst = $80; FlagShiftConst = 7; MaxValueMaskConst = $7F; MaxValueShiftConst = 0; FileHeaderConst = $80907050; FileVersionConst = 1; function FactorialIterative(aNumber: integer): int64; var i: Integer; begin Result := 1; for i := 1 to aNumber do Result := i * Result; end; function CombinationToString(Source: TCombination): string; var i: integer; r: TCombinationRec; begin r.Blob := Source; Result := ''; for i := 0 to r.NumPlaces-1 do Result := Result + IntToStr(r.Data[i]) + ' '; end; function StringToCombination(const Line: string): TCombination; var s: string; r: TCombinationRec; begin r.Blob := 0; s := Trim(Line); r.NumPlaces := 0; while (s <> '') and (r.NumPlaces < MaxPlacesConst) do begin r.Data[r.NumPlaces] := StrToIntDef(RetrieveNextValueFrom(s, ' '), 0); if r.Data[r.NumPlaces] = 0 then Break; inc(r.NumPlaces); end; Result := r.Blob; end; function CalculateNumberOfCombinations(NumPlaces, MaxValue: cardinal): cardinal; begin Result := FactorialIterative(MaxValue) div (FactorialIterative(NumPlaces)*FactorialIterative(MaxValue-NumPlaces)); end; {$IFDEF DEBUG} var OneConst : cardinal = 1; TwoConst : cardinal = 2; {$ENDIF} function NextCombination(var Combination: TCombination; NumPlaces, MaxValue: cardinal): boolean; var i: integer; r: TCombinationRec; begin r.Blob := Combination; i := NumPlaces-1; inc(r.Data[i]); while (i > 0) and (r.Data[i] >= MaxValue-NumPlaces+1+i) do begin dec(i); inc(r.Data[i]); end; if r.Data[0] > MaxValue-NumPlaces then // combination (n-k, n-k+1, ..., n) reached begin // No more combinations can be generated Result := FALSE; Exit; end; // Combination^ now looks like (..., x, n, n, n, ..., n). // turn it into (..., x, x + 1, x + 2, ...) for i := i+1 to NumPlaces-1 do r.Data[i] := r.Data[i-1]+1; r.MaxValue := MaxValue; r.NumPlaces := NumPlaces; Combination := r.Blob; Result := TRUE; end; procedure CalculateCombinations(NumPlaces, MaxValue: cardinal; ResultList: TCombinationList); var r : TCombinationRec; i, j : cardinal; combo : TCombination; function ComboPlusOne(const Source: TCombination): TCombination; var counter : cardinal; r2 : TCombinationRec; begin r2.Blob := Source; for counter := 0 to r2.NumPlaces-1 do inc(r2.Data[counter]); Result := r2.Blob; end; begin ResultList.Clear; {$IFDEF DEBUG} if NumPlaces < OneConst then Exit; if NumPlaces < TwoConst then Exit; {$ENDIF} // initial combination r.Blob := 0; r.MaxValue := MaxValue; r.NumPlaces := NumPlaces; for i := 0 to NumPlaces-1 do r.Data[i] := i; combo := r.Blob; ResultList.Add(ComboPlusOne(combo)); // all other combinations while NextCombination(combo, NumPlaces, MaxValue) do ResultList.Add(ComboPlusOne(combo)); end; { TCombinationList } procedure TCombinationList.Add(Item: TCombination); begin Lock.Enter; try if FCount = FCapacity then SetCapacity(FCapacity+128); FItems^[FCount] := Item; inc(FCount); finally Lock.Leave; end; end; procedure TCombinationList.Assign(Source: TCombinationList); begin Lock.Enter; try SetCapacity(Source.Capacity); FCount := Source.FCount; CopyMemory(FItems, Source.FItems, SizeOf(TCombination) * FCount); finally Lock.Leave; end; end; procedure TCombinationList.Clear; begin Lock.Enter; try FCount := 0; finally Lock.Leave; end; end; constructor TCombinationList.Create; begin inherited; FItems := nil; FCount := 0; FCapacity := 0; Lock := TCriticalSection.Create; end; procedure TCombinationList.Delete(Index: integer); var i: integer; begin Lock.Enter; try if Index <= FCount-2 then for i := Index+1 to FCount-1 do FItems^[i-1] := FItems^[i]; dec(FCount); finally Lock.Leave; end; end; destructor TCombinationList.Destroy; begin FreeMem(FItems); FItems := nil; FreeAndNil(Lock); inherited; end; function TCombinationList.GetItems(Index: integer): TCombination; begin Result := 0; Lock.Enter; try if (Index >= 0) or (Index < FCount) then Result := FItems[Index]; finally Lock.Leave; end; end; function TCombinationList.GetMaxValue: cardinal; begin Result := 0; if FCount > 0 then Result := TCombinationRec(FItems^[0]).MaxValue; end; function TCombinationList.GetNumPlaces: cardinal; begin Result := 0; if FCount > 0 then Result := TCombinationRec(FItems^[0]).NumPlaces; end; procedure TCombinationList.LoadFromFile(const FileName: string); var m : TMemoryStream; header, version, cnt : longword; begin Clear; SetCapacity(0); m := TMemoryStream.Create; try m.LoadFromFile(FileName); m.Position := 0; m.Read(header, 4); if header <> FileHeaderConst then Exit; m.Read(version, 4); if version > FileVersionConst then Exit; m.Read(cnt, 4); Lock.Enter; try SetCapacity(cnt); m.Read(FItems^, SizeOf(TCombination) * cnt); FCount := cnt; finally Lock.Leave; end; finally m.Free; end; end; procedure TCombinationList.Remove(Item: TCombination); var i: integer; begin Lock.Enter; try for i := 0 to FCount-1 do if FItems[i] = Item then begin Delete(i); Break; end; finally Lock.Leave; end; end; procedure TCombinationList.SaveToFile(const FileName: string); var m : TMemoryStream; n : longword; begin m := TMemoryStream.Create; try n := FileHeaderConst; m.Write(n, 4); n := FileVersionConst; m.Write(n, 4); Lock.Enter; try n := FCount; m.Write(n, 4); m.Write(FItems^, SizeOf(TCombination) * FCount); finally Lock.Leave; end; m.SaveToFile(FileName); finally m.Free; end; end; procedure TCombinationList.SetCapacity(NewValue: integer); begin FCapacity := NewValue; if FCapacity < 0 then FCapacity := 0; ReallocMem(FItems, FCapacity * SizeOf(TCombination)); if FCount > FCapacity then FCount := FCapacity; end; procedure TCombinationList.SetItems(Index: integer; NewValue: TCombination); begin FItems[Index] := NewValue; end; function TCombinationList.ToRawStrings: TStrings; var i: integer; begin Result := TStringList.Create; Lock.Enter; try for i := 0 to FCount-1 do Result.Add(Format('%d', [FItems^[i]])); finally Lock.Leave; end; end; function TCombinationList.ToStrings: TStrings; var i: integer; begin Result := TStringList.Create; Lock.Enter; try for i := 0 to FCount-1 do Result.Add(CombinationToString(FItems^[i])); finally Lock.Leave; end; end; { TCombination } (* function TCombination.ContainsOtherCombination(Other: PCombination): boolean; var i, j : integer; found : boolean; begin for i := 0 to Other^.Places-1 do begin for j := 0 to Places-1 do begin found := (Other^.Data[i] = Data[j]); if found then Break; end; if not found then Exit(FALSE); end; Result := TRUE; end; function TCombination.ToString: string; var i: integer; begin Result := ''; for i := 0 to Places-1 do Result := Result + IntToStr(Data[i]) + ' '; end; *) end.
unit Provect.ModalController; interface uses System.SysUtils, System.Classes, System.UITypes, System.Threading, FMX.Controls, FMX.TabControl, FMX.Forms, FMX.Types, FMX.Objects; type TFrameClass = class of TFrame; TModalController = class(TTabControl) private FWaitTask: ITask; FWaitTaskFuture: IFuture<Boolean>; FModalResult: TModalResult; function InternalCheckCurrent(const AClassName: string): Boolean; procedure InternalModal(const ATab: TTabItem; const AProc: TProc; const AFunc: TFunc<Boolean>); protected function IsInitialized: Boolean; function IsModal: Boolean; function IsWaitingTask: Boolean; procedure CallOnShow; property ModalResult: TModalResult read FModalResult write FModalResult; public class procedure CloseHide; class function CheckCurrent(const AFrame: TFrame): Boolean; overload; class function CheckCurrent(const AFrame: TFrameClass): Boolean; overload; class procedure EscapeHide; class procedure Hide(ANumber: Integer); reintroduce; overload; class procedure Hide(const AControl: TFrame); reintroduce; overload; class procedure HideModal(ANumber: Integer; AModalResult: TModalResult); reintroduce; overload; class procedure HideModal(const AControl: TFrame; AModalResult: TModalResult); reintroduce; overload; class procedure SetStyle(const AStyleName: string); class function Show(const AControl: TFrame): Integer; reintroduce; overload; class function Show(const AFrame: TFrameClass): Integer; reintroduce; overload; class function ShowModal(const AControl: TFrame; const AProc: TProc): TModalResult; overload; class function ShowModal(const AFrame: TFrameClass; const AProc: TProc): TModalResult; overload; class function ShowModal(const AFrame: TFrameClass; const AFunc: TFunc<Boolean>): TModalResult; overload; end; implementation uses System.Rtti, FMX.ActnList, FMX.Ani; var _ModalController: TModalController; function CheckModalController: Boolean; begin if not Assigned(_ModalController) then _ModalController := TModalController.Create(nil); Result := Assigned(_ModalController); end; { TModalController } class procedure TModalController.Hide(ANumber: Integer); begin if CheckModalController and _ModalController.IsInitialized and (_ModalController.TabCount > ANumber) and not _ModalController.IsWaitingTask and (_ModalController.ActiveTab.Index = ANumber) and not _ModalController.IsModal then begin if _ModalController.TabCount = 1 then begin TAnimator.AnimateFloat(_ModalController, 'Opacity', 0); _ModalController.Visible := False end else _ModalController.Previous(TTabTransition.Slide, TTabTransitionDirection.Reversed); _ModalController.Tabs[ANumber].Enabled := False; end; end; class procedure TModalController.Hide(const AControl: TFrame); var Item: TTabItem; I: Integer; begin if CheckModalController and Assigned(AControl) and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin for I := 0 to Pred(_ModalController.TabCount) do begin Item := _ModalController.Tabs[I]; if Item.StylesData['object-link'].AsType<TFrame> = AControl then begin TModalController.Hide(Item.Index); Break; end; end; end; end; class procedure TModalController.HideModal(ANumber: Integer; AModalResult: TModalResult); begin if CheckModalController then begin _ModalController.ModalResult := AModalResult; _ModalController.Hide(ANumber); end; end; class procedure TModalController.HideModal(const AControl: TFrame; AModalResult: TModalResult); begin if CheckModalController then begin _ModalController.ModalResult := AModalResult; _ModalController.Hide(AControl); end; end; procedure TModalController.CallOnShow; var Rtti: TRttiMethod; RttiClass: TObject; begin RttiClass := _ModalController.ActiveTab.StylesData['object-link'].AsObject; for Rtti in TRttiContext.Create.GetType(RttiClass.ClassInfo).GetDeclaredMethods do begin if CompareText(Rtti.Name, 'FrameShow') = 0 then Rtti.Invoke(RttiClass, []); end; end; class function TModalController.CheckCurrent(const AFrame: TFrameClass): Boolean; begin Result := _ModalController.InternalCheckCurrent(AFrame.ClassName); end; class function TModalController.CheckCurrent(const AFrame: TFrame): Boolean; begin Result := _ModalController.InternalCheckCurrent(AFrame.ClassName); end; class procedure TModalController.CloseHide; begin if CheckModalController and _ModalController.IsInitialized and _ModalController.Visible and not _ModalController.IsWaitingTask then begin while Assigned(_ModalController.ActiveTab) do begin _ModalController.ModalResult := mrAbort; _ModalController.Hide(_ModalController.ActiveTab.Index); end; end; end; class procedure TModalController.EscapeHide; begin if CheckModalController and _ModalController.IsInitialized and _ModalController.Visible and not _ModalController.IsWaitingTask then begin _ModalController.ModalResult := mrAbort; _ModalController.Hide(_ModalController.ActiveTab.Index); end; end; function TModalController.InternalCheckCurrent(const AClassName: string): Boolean; begin Result := False; if CheckModalController and _ModalController.IsInitialized and _ModalController.Visible then Result := _ModalController.ActiveTab.StylesData['object-link'].AsType<TFrame>.ClassName = AClassName; end; procedure TModalController.InternalModal(const ATab: TTabItem; const AProc: TProc; const AFunc: TFunc<Boolean>); begin ATab.StylesData['IsModal'] := True; try if Assigned(AProc) then begin FWaitTask := TTask.Create(AProc); FWaitTask.Start; while IsWaitingTask do begin Application.ProcessMessages; Sleep(100); end; HideModal(ATab.Index, mrOk); FWaitTask := nil; end else if Assigned(AFunc) then begin FWaitTaskFuture := TFuture<Boolean>.Create(TObject(nil), TFunctionEvent<Boolean>(nil), AFunc, TThreadPool.Default); FWaitTaskFuture.Start; while IsWaitingTask do begin Application.ProcessMessages; Sleep(1); end; if FWaitTaskFuture.Value then HideModal(ATab.Index, mrOk) else HideModal(ATab.Index, mrCancel); FWaitTaskFuture := nil; end else begin while ATab.Enabled do begin Application.ProcessMessages; Sleep(100); end; end; finally ATab.StylesData['IsModal'] := False; end; end; function TModalController.IsInitialized: Boolean; var I: Integer; TabsDisabled: Boolean; begin Result := Assigned(Parent); if not Result then begin if Assigned(Application) and Assigned(Application.MainForm) then begin Application.MainForm.AddObject(_ModalController); _ModalController.Align := TAlignLayout.Contents; _ModalController.TabPosition := TTabPosition.None; _ModalController.Visible := False; _ModalController.Opacity := 0; end; Result := Assigned(Parent); end else begin TabsDisabled := True; while TabsDisabled and (TabCount > 0) do begin for I := 0 to Pred(TabCount) do begin TabsDisabled := False; if not Tabs[I].Enabled then begin Delete(I); TabsDisabled := True; Break; end; end; end; end; end; function TModalController.IsModal: Boolean; begin Result := ActiveTab.StylesData['IsModal'].AsBoolean and (ModalResult = mrNone); end; function TModalController.IsWaitingTask: Boolean; begin Result := (Assigned(FWaitTask) and not FWaitTask.Wait(10)) or (Assigned(FWaitTaskFuture) and not FWaitTaskFuture.Wait(10)); end; class function TModalController.Show(const AControl: TFrame): Integer; var Item: TTabItem; begin Result := -1; if CheckModalController and Assigned(AControl) and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin _ModalController.ModalResult := mrNone; _ModalController.BeginUpdate; try Item := _ModalController.Add; Item.AddObject(AControl); AControl.Align := TAlignLayout.Center; Item.StylesData['object-link'] := AControl; Result := Item.Index; finally _ModalController.EndUpdate; end; _ModalController.BringToFront; _ModalController.Visible := True; if _ModalController.TabCount = 1 then begin _ModalController.ActiveTab := Item; TAnimator.AnimateFloat(_ModalController, 'Opacity', 1); end else _ModalController.Next(TTabTransition.Slide, TTabTransitionDirection.Reversed); _ModalController.CallOnShow; end; end; class procedure TModalController.SetStyle(const AStyleName: string); begin if CheckModalController then _ModalController.StyleLookup := AStyleName; end; class function TModalController.Show(const AFrame: TFrameClass): Integer; var TempFrame: TFrame; begin Result := -1; if CheckModalController and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin TempFrame := AFrame.Create(nil); Result := TModalController.Show(TempFrame); end; end; class function TModalController.ShowModal(const AFrame: TFrameClass; const AFunc: TFunc<Boolean>): TModalResult; var Tab: TTabItem; begin Result := -1; if CheckModalController and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin Tab := _ModalController.Tabs[Show(AFrame)]; _ModalController.InternalModal(Tab, nil, AFunc); Result := _ModalController.ModalResult; end; end; class function TModalController.ShowModal(const AFrame: TFrameClass; const AProc: TProc): TModalResult; var Tab: TTabItem; begin Result := -1; if Assigned(AProc) and CheckModalController and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin Tab := _ModalController.Tabs[Show(AFrame)]; _ModalController.InternalModal(Tab, AProc, nil); Result := _ModalController.ModalResult; end; end; class function TModalController.ShowModal(const AControl: TFrame; const AProc: TProc): TModalResult; var Tab: TTabItem; begin Result := -1; if Assigned(AProc) and CheckModalController and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin Tab := _ModalController.Tabs[Show(AControl)]; _ModalController.InternalModal(Tab, AProc, nil); Result := _ModalController.ModalResult; end; end; end.
unit TTSDCRUNTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSDCRUNRecord = record PRunNumber: Integer; PLenderNumber: String[4]; PUserID: String[10]; PDateTimeStart: String[20]; PDateTimeStop: String[20]; PStopStatus: String[10]; PDCFFilename: String[40]; PVersion: String[10]; PLoanAdd: Integer; PLoanchange: Integer; PLoanPaid: Integer; PTrackAdd: Integer; PTrackChange: Integer; PTrackDel: Integer; PBalanceInc: Integer; PBalanceDec: Integer; PLoanNumChange: Integer; PNotes: Integer; PCifAdd: Integer; PCifChange: Integer; PCifDel: Integer; PRecordsProcessed: Integer; PErrorsDetected: Integer; PPropertyAdd: Integer; PPropertyChange: Integer; PPropertyDelete: Integer; End; TTTSDCRUNBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSDCRUNRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSDCRUN = (TTSDCRUNPrimaryKey); TTTSDCRUNTable = class( TDBISAMTableAU ) private FDFRunNumber: TAutoIncField; FDFLenderNumber: TStringField; FDFUserID: TStringField; FDFDateTimeStart: TStringField; FDFDateTimeStop: TStringField; FDFStopStatus: TStringField; FDFDCFFilename: TStringField; FDFVersion: TStringField; FDFLoanAdd: TIntegerField; FDFLoanchange: TIntegerField; FDFLoanPaid: TIntegerField; FDFTrackAdd: TIntegerField; FDFTrackChange: TIntegerField; FDFTrackDel: TIntegerField; FDFBalanceInc: TIntegerField; FDFBalanceDec: TIntegerField; FDFLoanNumChange: TIntegerField; FDFNotes: TIntegerField; FDFCifAdd: TIntegerField; FDFCifChange: TIntegerField; FDFCifDel: TIntegerField; FDFRecordsProcessed: TIntegerField; FDFErrorsDetected: TIntegerField; FDFLog: TBlobField; FDFPropertyAdd: TIntegerField; FDFPropertyChange: TIntegerField; FDFPropertyDelete: TIntegerField; procedure SetPLenderNumber(const Value: String); function GetPLenderNumber:String; procedure SetPUserID(const Value: String); function GetPUserID:String; procedure SetPDateTimeStart(const Value: String); function GetPDateTimeStart:String; procedure SetPDateTimeStop(const Value: String); function GetPDateTimeStop:String; procedure SetPStopStatus(const Value: String); function GetPStopStatus:String; procedure SetPDCFFilename(const Value: String); function GetPDCFFilename:String; procedure SetPVersion(const Value: String); function GetPVersion:String; procedure SetPLoanAdd(const Value: Integer); function GetPLoanAdd:Integer; procedure SetPLoanchange(const Value: Integer); function GetPLoanchange:Integer; procedure SetPLoanPaid(const Value: Integer); function GetPLoanPaid:Integer; procedure SetPTrackAdd(const Value: Integer); function GetPTrackAdd:Integer; procedure SetPTrackChange(const Value: Integer); function GetPTrackChange:Integer; procedure SetPTrackDel(const Value: Integer); function GetPTrackDel:Integer; procedure SetPBalanceInc(const Value: Integer); function GetPBalanceInc:Integer; procedure SetPBalanceDec(const Value: Integer); function GetPBalanceDec:Integer; procedure SetPLoanNumChange(const Value: Integer); function GetPLoanNumChange:Integer; procedure SetPNotes(const Value: Integer); function GetPNotes:Integer; procedure SetPCifAdd(const Value: Integer); function GetPCifAdd:Integer; procedure SetPCifChange(const Value: Integer); function GetPCifChange:Integer; procedure SetPCifDel(const Value: Integer); function GetPCifDel:Integer; procedure SetPRecordsProcessed(const Value: Integer); function GetPRecordsProcessed:Integer; procedure SetPErrorsDetected(const Value: Integer); function GetPErrorsDetected:Integer; procedure SetPPropertyAdd(const Value: Integer); function GetPPropertyAdd:Integer; procedure SetPPropertyChange(const Value: Integer); function GetPPropertyChange:Integer; procedure SetPPropertyDelete(const Value: Integer); function GetPPropertyDelete:Integer; procedure SetEnumIndex(Value: TEITTSDCRUN); function GetEnumIndex: TEITTSDCRUN; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSDCRUNRecord; procedure StoreDataBuffer(ABuffer:TTTSDCRUNRecord); property DFRunNumber: TAutoIncField read FDFRunNumber; property DFLenderNumber: TStringField read FDFLenderNumber; property DFUserID: TStringField read FDFUserID; property DFDateTimeStart: TStringField read FDFDateTimeStart; property DFDateTimeStop: TStringField read FDFDateTimeStop; property DFStopStatus: TStringField read FDFStopStatus; property DFDCFFilename: TStringField read FDFDCFFilename; property DFVersion: TStringField read FDFVersion; property DFLoanAdd: TIntegerField read FDFLoanAdd; property DFLoanchange: TIntegerField read FDFLoanchange; property DFLoanPaid: TIntegerField read FDFLoanPaid; property DFTrackAdd: TIntegerField read FDFTrackAdd; property DFTrackChange: TIntegerField read FDFTrackChange; property DFTrackDel: TIntegerField read FDFTrackDel; property DFBalanceInc: TIntegerField read FDFBalanceInc; property DFBalanceDec: TIntegerField read FDFBalanceDec; property DFLoanNumChange: TIntegerField read FDFLoanNumChange; property DFNotes: TIntegerField read FDFNotes; property DFCifAdd: TIntegerField read FDFCifAdd; property DFCifChange: TIntegerField read FDFCifChange; property DFCifDel: TIntegerField read FDFCifDel; property DFRecordsProcessed: TIntegerField read FDFRecordsProcessed; property DFErrorsDetected: TIntegerField read FDFErrorsDetected; property DFLog: TBlobField read FDFLog; property DFPropertyAdd: TIntegerField read FDFPropertyAdd; property DFPropertyChange: TIntegerField read FDFPropertyChange; property DFPropertyDelete: TIntegerField read FDFPropertyDelete; property PLenderNumber: String read GetPLenderNumber write SetPLenderNumber; property PUserID: String read GetPUserID write SetPUserID; property PDateTimeStart: String read GetPDateTimeStart write SetPDateTimeStart; property PDateTimeStop: String read GetPDateTimeStop write SetPDateTimeStop; property PStopStatus: String read GetPStopStatus write SetPStopStatus; property PDCFFilename: String read GetPDCFFilename write SetPDCFFilename; property PVersion: String read GetPVersion write SetPVersion; property PLoanAdd: Integer read GetPLoanAdd write SetPLoanAdd; property PLoanchange: Integer read GetPLoanchange write SetPLoanchange; property PLoanPaid: Integer read GetPLoanPaid write SetPLoanPaid; property PTrackAdd: Integer read GetPTrackAdd write SetPTrackAdd; property PTrackChange: Integer read GetPTrackChange write SetPTrackChange; property PTrackDel: Integer read GetPTrackDel write SetPTrackDel; property PBalanceInc: Integer read GetPBalanceInc write SetPBalanceInc; property PBalanceDec: Integer read GetPBalanceDec write SetPBalanceDec; property PLoanNumChange: Integer read GetPLoanNumChange write SetPLoanNumChange; property PNotes: Integer read GetPNotes write SetPNotes; property PCifAdd: Integer read GetPCifAdd write SetPCifAdd; property PCifChange: Integer read GetPCifChange write SetPCifChange; property PCifDel: Integer read GetPCifDel write SetPCifDel; property PRecordsProcessed: Integer read GetPRecordsProcessed write SetPRecordsProcessed; property PErrorsDetected: Integer read GetPErrorsDetected write SetPErrorsDetected; property PPropertyAdd: Integer read GetPPropertyAdd write SetPPropertyAdd; property PPropertyChange: Integer read GetPPropertyChange write SetPPropertyChange; property PPropertyDelete: Integer read GetPPropertyDelete write SetPPropertyDelete; published property Active write SetActive; property EnumIndex: TEITTSDCRUN read GetEnumIndex write SetEnumIndex; end; { TTTSDCRUNTable } procedure Register; implementation procedure TTTSDCRUNTable.CreateFields; begin FDFRunNumber := CreateField( 'RunNumber' ) as TAutoIncField; FDFLenderNumber := CreateField( 'LenderNumber' ) as TStringField; FDFUserID := CreateField( 'UserID' ) as TStringField; FDFDateTimeStart := CreateField( 'DateTimeStart' ) as TStringField; FDFDateTimeStop := CreateField( 'DateTimeStop' ) as TStringField; FDFStopStatus := CreateField( 'StopStatus' ) as TStringField; FDFDCFFilename := CreateField( 'DCFFilename' ) as TStringField; FDFVersion := CreateField( 'Version' ) as TStringField; FDFLoanAdd := CreateField( 'LoanAdd' ) as TIntegerField; FDFLoanchange := CreateField( 'Loanchange' ) as TIntegerField; FDFLoanPaid := CreateField( 'LoanPaid' ) as TIntegerField; FDFTrackAdd := CreateField( 'TrackAdd' ) as TIntegerField; FDFTrackChange := CreateField( 'TrackChange' ) as TIntegerField; FDFTrackDel := CreateField( 'TrackDel' ) as TIntegerField; FDFBalanceInc := CreateField( 'BalanceInc' ) as TIntegerField; FDFBalanceDec := CreateField( 'BalanceDec' ) as TIntegerField; FDFLoanNumChange := CreateField( 'LoanNumChange' ) as TIntegerField; FDFNotes := CreateField( 'Notes' ) as TIntegerField; FDFCifAdd := CreateField( 'CifAdd' ) as TIntegerField; FDFCifChange := CreateField( 'CifChange' ) as TIntegerField; FDFCifDel := CreateField( 'CifDel' ) as TIntegerField; FDFRecordsProcessed := CreateField( 'RecordsProcessed' ) as TIntegerField; FDFErrorsDetected := CreateField( 'ErrorsDetected' ) as TIntegerField; FDFLog := CreateField( 'Log' ) as TBlobField; FDFPropertyAdd := CreateField( 'PropertyAdd' ) as TIntegerField; FDFPropertyChange := CreateField( 'PropertyChange' ) as TIntegerField; FDFPropertyDelete := CreateField( 'PropertyDelete' ) as TIntegerField; end; { TTTSDCRUNTable.CreateFields } procedure TTTSDCRUNTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSDCRUNTable.SetActive } procedure TTTSDCRUNTable.SetPLenderNumber(const Value: String); begin DFLenderNumber.Value := Value; end; function TTTSDCRUNTable.GetPLenderNumber:String; begin result := DFLenderNumber.Value; end; procedure TTTSDCRUNTable.SetPUserID(const Value: String); begin DFUserID.Value := Value; end; function TTTSDCRUNTable.GetPUserID:String; begin result := DFUserID.Value; end; procedure TTTSDCRUNTable.SetPDateTimeStart(const Value: String); begin DFDateTimeStart.Value := Value; end; function TTTSDCRUNTable.GetPDateTimeStart:String; begin result := DFDateTimeStart.Value; end; procedure TTTSDCRUNTable.SetPDateTimeStop(const Value: String); begin DFDateTimeStop.Value := Value; end; function TTTSDCRUNTable.GetPDateTimeStop:String; begin result := DFDateTimeStop.Value; end; procedure TTTSDCRUNTable.SetPStopStatus(const Value: String); begin DFStopStatus.Value := Value; end; function TTTSDCRUNTable.GetPStopStatus:String; begin result := DFStopStatus.Value; end; procedure TTTSDCRUNTable.SetPDCFFilename(const Value: String); begin DFDCFFilename.Value := Value; end; function TTTSDCRUNTable.GetPDCFFilename:String; begin result := DFDCFFilename.Value; end; procedure TTTSDCRUNTable.SetPVersion(const Value: String); begin DFVersion.Value := Value; end; function TTTSDCRUNTable.GetPVersion:String; begin result := DFVersion.Value; end; procedure TTTSDCRUNTable.SetPLoanAdd(const Value: Integer); begin DFLoanAdd.Value := Value; end; function TTTSDCRUNTable.GetPLoanAdd:Integer; begin result := DFLoanAdd.Value; end; procedure TTTSDCRUNTable.SetPLoanchange(const Value: Integer); begin DFLoanchange.Value := Value; end; function TTTSDCRUNTable.GetPLoanchange:Integer; begin result := DFLoanchange.Value; end; procedure TTTSDCRUNTable.SetPLoanPaid(const Value: Integer); begin DFLoanPaid.Value := Value; end; function TTTSDCRUNTable.GetPLoanPaid:Integer; begin result := DFLoanPaid.Value; end; procedure TTTSDCRUNTable.SetPTrackAdd(const Value: Integer); begin DFTrackAdd.Value := Value; end; function TTTSDCRUNTable.GetPTrackAdd:Integer; begin result := DFTrackAdd.Value; end; procedure TTTSDCRUNTable.SetPTrackChange(const Value: Integer); begin DFTrackChange.Value := Value; end; function TTTSDCRUNTable.GetPTrackChange:Integer; begin result := DFTrackChange.Value; end; procedure TTTSDCRUNTable.SetPTrackDel(const Value: Integer); begin DFTrackDel.Value := Value; end; function TTTSDCRUNTable.GetPTrackDel:Integer; begin result := DFTrackDel.Value; end; procedure TTTSDCRUNTable.SetPBalanceInc(const Value: Integer); begin DFBalanceInc.Value := Value; end; function TTTSDCRUNTable.GetPBalanceInc:Integer; begin result := DFBalanceInc.Value; end; procedure TTTSDCRUNTable.SetPBalanceDec(const Value: Integer); begin DFBalanceDec.Value := Value; end; function TTTSDCRUNTable.GetPBalanceDec:Integer; begin result := DFBalanceDec.Value; end; procedure TTTSDCRUNTable.SetPLoanNumChange(const Value: Integer); begin DFLoanNumChange.Value := Value; end; function TTTSDCRUNTable.GetPLoanNumChange:Integer; begin result := DFLoanNumChange.Value; end; procedure TTTSDCRUNTable.SetPNotes(const Value: Integer); begin DFNotes.Value := Value; end; function TTTSDCRUNTable.GetPNotes:Integer; begin result := DFNotes.Value; end; procedure TTTSDCRUNTable.SetPCifAdd(const Value: Integer); begin DFCifAdd.Value := Value; end; function TTTSDCRUNTable.GetPCifAdd:Integer; begin result := DFCifAdd.Value; end; procedure TTTSDCRUNTable.SetPCifChange(const Value: Integer); begin DFCifChange.Value := Value; end; function TTTSDCRUNTable.GetPCifChange:Integer; begin result := DFCifChange.Value; end; procedure TTTSDCRUNTable.SetPCifDel(const Value: Integer); begin DFCifDel.Value := Value; end; function TTTSDCRUNTable.GetPCifDel:Integer; begin result := DFCifDel.Value; end; procedure TTTSDCRUNTable.SetPRecordsProcessed(const Value: Integer); begin DFRecordsProcessed.Value := Value; end; function TTTSDCRUNTable.GetPRecordsProcessed:Integer; begin result := DFRecordsProcessed.Value; end; procedure TTTSDCRUNTable.SetPErrorsDetected(const Value: Integer); begin DFErrorsDetected.Value := Value; end; function TTTSDCRUNTable.GetPErrorsDetected:Integer; begin result := DFErrorsDetected.Value; end; procedure TTTSDCRUNTable.SetPPropertyAdd(const Value: Integer); begin DFPropertyAdd.Value := Value; end; function TTTSDCRUNTable.GetPPropertyAdd:Integer; begin result := DFPropertyAdd.Value; end; procedure TTTSDCRUNTable.SetPPropertyChange(const Value: Integer); begin DFPropertyChange.Value := Value; end; function TTTSDCRUNTable.GetPPropertyChange:Integer; begin result := DFPropertyChange.Value; end; procedure TTTSDCRUNTable.SetPPropertyDelete(const Value: Integer); begin DFPropertyDelete.Value := Value; end; function TTTSDCRUNTable.GetPPropertyDelete:Integer; begin result := DFPropertyDelete.Value; end; procedure TTTSDCRUNTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('RunNumber, AutoInc, 0, N'); Add('LenderNumber, String, 4, N'); Add('UserID, String, 10, N'); Add('DateTimeStart, String, 20, N'); Add('DateTimeStop, String, 20, N'); Add('StopStatus, String, 10, N'); Add('DCFFilename, String, 40, N'); Add('Version, String, 10, N'); Add('LoanAdd, Integer, 0, N'); Add('Loanchange, Integer, 0, N'); Add('LoanPaid, Integer, 0, N'); Add('TrackAdd, Integer, 0, N'); Add('TrackChange, Integer, 0, N'); Add('TrackDel, Integer, 0, N'); Add('BalanceInc, Integer, 0, N'); Add('BalanceDec, Integer, 0, N'); Add('LoanNumChange, Integer, 0, N'); Add('Notes, Integer, 0, N'); Add('CifAdd, Integer, 0, N'); Add('CifChange, Integer, 0, N'); Add('CifDel, Integer, 0, N'); Add('RecordsProcessed, Integer, 0, N'); Add('ErrorsDetected, Integer, 0, N'); Add('Log, Memo, 0, N'); Add('PropertyAdd, Integer, 0, N'); Add('PropertyChange, Integer, 0, N'); Add('PropertyDelete, Integer, 0, N'); end; end; procedure TTTSDCRUNTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, RunNumber, Y, Y, N, Y'); end; end; procedure TTTSDCRUNTable.SetEnumIndex(Value: TEITTSDCRUN); begin case Value of TTSDCRUNPrimaryKey : IndexName := ''; end; end; function TTTSDCRUNTable.GetDataBuffer:TTTSDCRUNRecord; var buf: TTTSDCRUNRecord; begin fillchar(buf, sizeof(buf), 0); buf.PRunNumber := DFRunNumber.Value; buf.PLenderNumber := DFLenderNumber.Value; buf.PUserID := DFUserID.Value; buf.PDateTimeStart := DFDateTimeStart.Value; buf.PDateTimeStop := DFDateTimeStop.Value; buf.PStopStatus := DFStopStatus.Value; buf.PDCFFilename := DFDCFFilename.Value; buf.PVersion := DFVersion.Value; buf.PLoanAdd := DFLoanAdd.Value; buf.PLoanchange := DFLoanchange.Value; buf.PLoanPaid := DFLoanPaid.Value; buf.PTrackAdd := DFTrackAdd.Value; buf.PTrackChange := DFTrackChange.Value; buf.PTrackDel := DFTrackDel.Value; buf.PBalanceInc := DFBalanceInc.Value; buf.PBalanceDec := DFBalanceDec.Value; buf.PLoanNumChange := DFLoanNumChange.Value; buf.PNotes := DFNotes.Value; buf.PCifAdd := DFCifAdd.Value; buf.PCifChange := DFCifChange.Value; buf.PCifDel := DFCifDel.Value; buf.PRecordsProcessed := DFRecordsProcessed.Value; buf.PErrorsDetected := DFErrorsDetected.Value; buf.PPropertyAdd := DFPropertyAdd.Value; buf.PPropertyChange := DFPropertyChange.Value; buf.PPropertyDelete := DFPropertyDelete.Value; result := buf; end; procedure TTTSDCRUNTable.StoreDataBuffer(ABuffer:TTTSDCRUNRecord); begin DFLenderNumber.Value := ABuffer.PLenderNumber; DFUserID.Value := ABuffer.PUserID; DFDateTimeStart.Value := ABuffer.PDateTimeStart; DFDateTimeStop.Value := ABuffer.PDateTimeStop; DFStopStatus.Value := ABuffer.PStopStatus; DFDCFFilename.Value := ABuffer.PDCFFilename; DFVersion.Value := ABuffer.PVersion; DFLoanAdd.Value := ABuffer.PLoanAdd; DFLoanchange.Value := ABuffer.PLoanchange; DFLoanPaid.Value := ABuffer.PLoanPaid; DFTrackAdd.Value := ABuffer.PTrackAdd; DFTrackChange.Value := ABuffer.PTrackChange; DFTrackDel.Value := ABuffer.PTrackDel; DFBalanceInc.Value := ABuffer.PBalanceInc; DFBalanceDec.Value := ABuffer.PBalanceDec; DFLoanNumChange.Value := ABuffer.PLoanNumChange; DFNotes.Value := ABuffer.PNotes; DFCifAdd.Value := ABuffer.PCifAdd; DFCifChange.Value := ABuffer.PCifChange; DFCifDel.Value := ABuffer.PCifDel; DFRecordsProcessed.Value := ABuffer.PRecordsProcessed; DFErrorsDetected.Value := ABuffer.PErrorsDetected; DFPropertyAdd.Value := ABuffer.PPropertyAdd; DFPropertyChange.Value := ABuffer.PPropertyChange; DFPropertyDelete.Value := ABuffer.PPropertyDelete; end; function TTTSDCRUNTable.GetEnumIndex: TEITTSDCRUN; var iname : string; begin result := TTSDCRUNPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSDCRUNPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSDCRUNTable, TTTSDCRUNBuffer ] ); end; { Register } function TTTSDCRUNBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..26] of string = ('RUNNUMBER','LENDERNUMBER','USERID','DATETIMESTART','DATETIMESTOP','STOPSTATUS' ,'DCFFILENAME','VERSION','LOANADD','LOANCHANGE','LOANPAID' ,'TRACKADD','TRACKCHANGE','TRACKDEL','BALANCEINC','BALANCEDEC' ,'LOANNUMCHANGE','NOTES','CIFADD','CIFCHANGE','CIFDEL' ,'RECORDSPROCESSED','ERRORSDETECTED','PROPERTYADD','PROPERTYCHANGE' ,'PROPERTYDELETE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 26) and (flist[x] <> s) do inc(x); if x <= 26 then result := x else result := 0; end; function TTTSDCRUNBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftAutoInc; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftInteger; 10 : result := ftInteger; 11 : result := ftInteger; 12 : result := ftInteger; 13 : result := ftInteger; 14 : result := ftInteger; 15 : result := ftInteger; 16 : result := ftInteger; 17 : result := ftInteger; 18 : result := ftInteger; 19 : result := ftInteger; 20 : result := ftInteger; 21 : result := ftInteger; 22 : result := ftInteger; 23 : result := ftInteger; 24 : result := ftInteger; 25 : result := ftInteger; 26 : result := ftInteger; end; end; function TTTSDCRUNBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PRunNumber; 2 : result := @Data.PLenderNumber; 3 : result := @Data.PUserID; 4 : result := @Data.PDateTimeStart; 5 : result := @Data.PDateTimeStop; 6 : result := @Data.PStopStatus; 7 : result := @Data.PDCFFilename; 8 : result := @Data.PVersion; 9 : result := @Data.PLoanAdd; 10 : result := @Data.PLoanchange; 11 : result := @Data.PLoanPaid; 12 : result := @Data.PTrackAdd; 13 : result := @Data.PTrackChange; 14 : result := @Data.PTrackDel; 15 : result := @Data.PBalanceInc; 16 : result := @Data.PBalanceDec; 17 : result := @Data.PLoanNumChange; 18 : result := @Data.PNotes; 19 : result := @Data.PCifAdd; 20 : result := @Data.PCifChange; 21 : result := @Data.PCifDel; 22 : result := @Data.PRecordsProcessed; 23 : result := @Data.PErrorsDetected; 24 : result := @Data.PPropertyAdd; 25 : result := @Data.PPropertyChange; 26 : result := @Data.PPropertyDelete; end; end; end.
unit uRoadRunnerAPI; { Copyright 2012 Herbert M Sauro 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. In plain english this means: You CAN freely download and use this software, in whole or in part, for personal, company internal, or commercial purposes; You CAN use the software in packages or distributions that you create. f You SHOULD include a copy of the license in any redistribution you may make; You are NOT required include the source of software, or of any modifications you may have made to it, in any redistribution you may assemble that includes it. YOU CANNOT: redistribute any piece of this software without proper attribution; } interface Uses SysUtils, Classes, Windows, uMatrix, Generics.Collections, IOUtils, uRRList, uRRTypes, uSBWArray; { C_DECL_SPEC bool rrCallConv setLogLevelFromString(const char* lvl); C_DECL_SPEC bool rrCallConv getLogLevel(int& lvl); C_DECL_SPEC char* rrCallConv getLogFileName(); C_DECL_SPEC char* rrCallConv getBuildDate(); C_DECL_SPEC char* rrCallConv getCopyright(); C_DECL_SPEC bool rrCallConv setTempFolder(const char* folder); C_DECL_SPEC char* rrCallConv getTempFolder(); } type TAnsiCharArray = array[0..100000] of AnsiChar; PAnsiCharArray = ^TAnsiCharArray; TAnsiCharArrayArray = array[0..100000] of PAnsiCharArray; // Array of char* PAnsiCharArrayArray = ^TAnsiCharArrayArray; TRRStringArray = record count : integer; strList : PAnsiCharArrayArray; end; PRRStringArray = ^TRRStringArray; TVoidCharFunc = function : PAnsiChar; stdcall; //char* func(void) TVoidBoolFunc = function : boolean; stdcall; // bool func (void); TVoidIntFunc = function : integer; stdcall; TVoidDoubleFunc = function : double; stdcall; TBoolBoolFunc = function (var value : boolean) : boolean; stdcall; TPointerVoidFunc = function : Pointer; stdcall; //void* func(void) TCharBoolFunc = function (str : PAnsiChar) : bool; stdcall; // bool func (char *) TDoubleBoolFunc = function (value : double) : bool; stdcall; // bool func (double) TIntBoolFunc = function (value : integer) : bool; stdcall; // bool func (double) TVarIntBoolFunc = function (var value : integer) : bool; stdcall; // bool func (double) TIntDoubleFunc = function (index : integer) : double; stdcall; TVoidStringListFunc = function() : PRRStringArray; stdcall; TGetCopyright = TVoidCharFunc; TGetRRInstance = TPointerVoidFunc; TGetCCode = function : PRRCCodeHandle; stdcall; TSetTimeStart = function (var value : double) : bool; stdcall; TSetTimeEnd = function (var value : double) : bool; stdcall; TSetNumPoints = function (var value : integer) : bool; stdcall; TSimulateEx = function (var timeStart : double; var timeEnd : double; var numberOfPoints : integer) : PRRResultHandle; stdcall; TGetMatrix = function : PRRMatrixHandle; stdcall; TFreeRRResult = function (ptr : PRRResultHandle) : boolean; stdcall; TFreeRRInstance = procedure (instance : Pointer); stdcall; TVoidVectorFunc = function : PRRDoubleVectorHandle; stdcall; TSetSelectionList = function (list : PAnsiChar) : bool; stdcall; TGetValue = function (speciesId : PAnsiChar; var value : double) : boolean; stdcall; TSetValue = function (speciesId : PAnsiChar; var value : double) : bool; stdcall; TGetReactionIds = TPointerVoidFunc; TReset = function : bool; stdcall; TFreeStringArray = function (handle : PRRStringArray) : boolean; stdcall; TFreeRRMatrix = function (matrix : PRRMatrixHandle) : boolean; stdcall; TFreeRRDoubleVector = function (vector : PRRDoubleVectorHandle) : boolean ; stdcall; TOneStep = function (var currentTime : double; var stepSize : double) : double; stdcall; TSteadyState = function (var value : double) : boolean; stdcall; TGetMCA = function (variable : PAnsiChar; parameter : PAnsiChar; var value : double) : boolean; stdcall; var DLLLoaded : boolean; selectionList : AnsiString; loggingEnabled : boolean = false; loggingTmpFileName : AnsiString = ''; function hasError : boolean; function getRRInstance : Pointer; procedure freeRRInstance; overload; procedure freeRRInstance (myInstance : Pointer); overload; function getLastError : AnsiString; function getBuildDate : AnsiString; function getRevision : integer; {$REGION 'Documentation'} /// <summary> /// Get copyright string /// </summary> /// <returns> /// Copyright string /// </returns> {$ENDREGION} function getCopyright : AnsiString; function getTempFolder : AnsiString; function enableLogging : boolean; function setLogLevel (debugLevel : AnsiString) : boolean; function getLogFileName : AnsiString; function setTempFolder (name : AnsiString) : boolean; {$REGION 'Documentation'} /// <summary> /// Returns the generated C Code for the model /// </summary> {$ENDREGION} function getCCode : TRRCCode; function loadSBML (sbmlStr : AnsiString) : boolean; function loadSBMLFromFile (fileName : AnsiString) : boolean; function getSBML : AnsiString; function getValue (Id : AnsiString) : double; function setValue (Id : AnsiString; value : double) : boolean; function reset : boolean; function setFloatingSpeciesInitialConcentrations (value : TDoubleArray) : boolean; procedure setTimeStart (value : double); procedure setTimeEnd (value : double); procedure setNumberOfPoints (value : integer); function simulate : T2DDoubleArray; function mSimulate : TMatrix; function simulateEx (timeStart: double; timeEnd : double; numberOfPoints : integer) : TMatrix; function oneStep (var currentTime : double; var stepSize : double) : double; function setTimeCourseSelectionList (strList : TStringList) : boolean; function getTimeCourseSelectionList: TRRList; function setCapabilities (str : AnsiString) : boolean; function getCapabilities : AnsiString; function evalModel : boolean; function getFullJacobian : T2DDoubleArray; function getReducedJacobian : T2DDoubleArray; function getStoichiometryMatrix : T2DDoubleArray; function getLinkMatrix : T2DDoubleArray; function getNrMatrix : T2DDoubleArray; function getL0Matrix : T2DDoubleArray; function getConservationMatrix : T2DDoubleArray; function getReactionRates : TDoubleArray; function getRatesOfChange : TDoubleArray; function getCompartmentIds : TStringList; function getReactionIds : TStringList; function getBoundarySpeciesIds : TStringList; function getFloatingSpeciesIds : TStringList; function getGlobalParameterIds : TStringList; function getRatesOfChangeIds : TStringList; function getEigenValueIds : TStringList; function getElasticityIds : TStringList; function getNumberOfReactions : integer; function getNumberOfBoundarySpecies : integer; function getNumberOfFloatingSpecies : integer; function getNumberOfGlobalParameters : integer; function getNumberOfCompartments : integer; function setCompartmentByIndex (index : integer; value : double) : boolean; function setFloatingSpeciesByIndex (index : integer; value : double) : boolean; function setBoundarySpeciesByIndex (index : integer; value : double) : boolean; function setGlobalParameterByIndex (index : integer; value : double) : boolean; function getCompartmentByIndex (index : integer) : double; function getFloatingSpeciesByIndex (index : integer) : double; function getBoundarySpeciesByIndex (index : integer) : double; function getGlobalParameterByIndex (index : integer) : double; function getFloatingSpeciesConcentrations : TDoubleArray; function getBoundarySpeciesConcentrations : TDoubleArray; function getNumberOfDependentSpecies : integer; function getNumberOfIndependentSpecies : integer; function steadyState : double; function computeSteadyStateValues : TDoubleArray; function setSteadyStateSelectionList (strList : TStringList) : boolean; function getEigenValues : T2DDoubleArray; function getuCC (variable : AnsiString; parameter : AnsiString) : double; function getCC (variable : AnsiString; parameter : AnsiString) : double; function getuEE (variable : AnsiString; parameter : AnsiString) : double; function getEE (variable : AnsiString; parameter : AnsiString) : double; function getAvailableSymbolsII : TRRList; function getAvailableTimeCourseSymbols : TRRList; function getAvailableSteadStateSymbols : TRRList; function setComputeAndAssignConservationLaws (value : boolean) : boolean; procedure setRoadRunnerLibraryName (newLibName : AnsiString); function loadRoadRunner (var errMsg : AnsiString; methodList : TStringList) : boolean; procedure releaseRoadRunnerLibrary; implementation type TLibGetAvailableSymbols = function : PRRListRecordHandle; stdcall; TlibSetInitialConditions = function (vec : PRRDoubleVectorHandle) : bool; stdcall; TlibComputeSteadyStateValues = function : PRRDoubleVectorHandle; var DLLHandle : Cardinal; libName : AnsiString = 'rr_c_API.dll'; instance : Pointer = nil; libLoadSBML : TCharBoolFunc; libLoadSBMLFromFile : TCharBoolFunc; libGetSBML : TVoidCharFunc; libHasError : TVoidBoolFunc; libGetLastError : TVoidCharFunc; libEnableLogging : TVoidBoolFunc; libSetLogLevel : TCharBoolFunc; libGetLogFileName : TVoidCharFunc; libSetTempFolder : function (folder : PAnsiChar) : bool; stdcall; libGetBuildDate : TVoidCharFunc; libGetRevision : TVoidIntFunc; libGetCopyright : TGetCopyright; libGetTempFolder : TVoidCharFunc; libGetCCode : TGetCCode; libGetRRInstance : TGetRRInstance; libFreeRRInstance : TFreeRRInstance; libFreeResult : TFreeRRResult; libSimulate : TPointerVoidFunc; libSimulateEx : TSimulateEx; libGetValue : TGetValue; libSetValue : TSetValue; libSetTimeCourseSelectionList : TSetSelectionList; libGetReactionIds : TGetReactionIds; libReset : TReset; libSetFloatingSpeciesInitialConcentrations : function (value : Pointer) : boolean; stdcall; libGetCapabilities : TVoidCharFunc; libSetCapabilities : TCharBoolFunc; libEvalModel : TVoidBoolFunc; libGetFullJacobian : function : PRRMatrixHandle; libGetReducedJacobian : function : PRRMatrixHandle; libSetTimeStart : TSetTimeStart; libSetTimeEnd : TSetTimeEnd; libSetNumberOfPoints : TSetNumPoints; libGetNumberOfReactions : TVoidIntFunc; libGetNumberOfBoundarySpecies : TVoidIntFunc; libGetNumberOfFloatingSpecies : TVoidIntFunc; libGetNumberOfGlobalParameters : TVoidIntFunc; libGetNumberOfCompartments : TVoidIntFunc; libSetCompartmentByIndex : function (var index : integer; var value : double) : boolean; stdcall; libSetFloatingSpeciesByIndex : function (var index : integer; var value : double) : boolean; stdcall; libSetBoundarySpeciesByIndex : function (var index : integer; var value : double) : boolean; stdcall; libSetGlobalParameterByIndex : function (var index : integer; var value : double) : boolean; stdcall; libGetCompartmentByIndex : function (var index : integer; var value : double) : boolean; stdcall; libGetGlobalParameterByIndex : function (var index : integer; var value : double) : boolean; stdcall; libGetFloatingSpeciesByIndex : function (var index : integer; var value : double) : boolean; stdcall; libGetBoundarySpeciesByIndex : function (var index : integer; var value : double) : boolean; stdcall; libGetFloatingSpeciesConcentrations : function : PRRDoubleVectorHandle; stdcall; libGetBoundarySpeciesConcentrations : function : PRRDoubleVectorHandle; stdcall; libSetFloatingSpeciesConcentrations : function (values : PRRDoubleVectorHandle) : boolean; stdcall; libSetBoundarySpeciesConcentrations : function (values : PRRDoubleVectorHandle) : boolean; stdcall; libGetNumberOfDependentSpecies : function : integer; stdcall; libGetNumberOfIndependentSpecies : function : integer; stdcall; libSteadyState : TSteadyState; libGetReactionRate : TIntDoubleFunc; libGetReactionRates : TVoidVectorFunc; libGetRatesOfChange : TVoidVectorFunc; libOneStep : TOneStep; libGetCompartmentIds : TVoidStringListFunc; libGetBoundarySpeciesIds : TVoidStringListFunc; libGetFloatingSpeciesIds : TVoidStringListFunc; libGetGlobalParameterIds : TVoidStringListFunc; libGetRatesOfChangeIds : TVoidStringListFunc; libGetEigenValueIds : TVoidStringListFunc; libGetElasticityIds : TVoidStringListFunc; libSetSteadyStateSelectionList : TCharBoolFunc; libGetSteadyStateSelectionList : function : PRRListRecordHandle; stdcall; libGetTimeCourseSelectionList : function : PRRListRecordHandle; stdcall; libGetAvailableTimeCourseSymbols : TLibGetAvailableSymbols; libGetAvailableSteadyStateSymbols : TLibGetAvailableSymbols; libComputeSteadyStateValues : TlibComputeSteadyStateValues; libSetInitialConditions : TlibSetInitialConditions; libSetComputeAndAssignConservationLaws : TBoolBoolFunc; libGetStoichiometryMatrix : TGetMatrix; libGetLinkMatrix : TGetMatrix; libGetNrMatrix : TGetMatrix; libGetL0Matrix : TGetMatrix; libGetConservationMatrix : TGetMatrix; libgetuCC : TGetMCA; libgetuEE : TGetMCA; libgetCC : TGetMCA; libgetEE : TGetMCA; libGetEigenValues : TGetMatrix; libCreateVector : function (size : integer) : PRRDoubleVectorHandle; stdcall; libGetListItem : function (list : pointer; index : integer) : PRRListItemRecord; stdcall; libFreeStringArray : TFreeStringArray; libFreeMatrix : TFreeRRMatrix; libFreeText : TCharBoolFunc; libFreeDoubleVector : TFreeRRDoubleVector; // Utility Routines // -------------------------------------------------------------- function getArrayOfStrings (pList: PRRStringArray) : TStringList; var nStrings : integer; i, j : integer; element : PAnsiCharArray; str : AnsiString; begin nStrings := pList^.count; result := TStringList.Create; for i := 0 to nStrings - 1 do begin element := pList^.strList[i]; j := 0; str := ''; while element[j] <> #0 do begin str := str + element[j]; inc (j); end; result.Add (str); end; end; function loadIntoMatrix (matrix : PRRMatrixHandle) : TMatrix; var nr, nc : integer; i, j : integer; begin nr := matrix^.RSize; nc := matrix^.CSize; result := TMatrix.Create (nr, nc); for i := 0 to nr - 1 do for j := 0 to nc - 1 do result[i+1,j+1] := matrix^.data[i*nc + j]; end; function loadInTo2DArray (matrix : PRRMatrixHandle) : T2DDoubleArray; var nr, nc : integer; i, j : integer; begin nr := matrix^.RSize; nc := matrix^.CSize; setLength (result, nr, nc); for i := 0 to nr - 1 do for j := 0 to nc - 1 do result[i,j] := matrix^.data[i*nc + j]; end; function extractList (list : PRRListRecordHandle) : TRRList; var i : integer; item : PRRListItemRecord; begin result := TRRList.Create; for i := 0 to list^.count - 1 do begin item := libGetListItem (list, i); case item^.ItemType of litList : result.Add (TRRListItem.Create (extractList (item^.lValue))); litString : result.Add (TRRListItem.Create (AnsiString (item^.sValue))); litInteger : result.Add (TRRListItem.Create (item^.iValue)); litDouble : result.Add (TRRListItem.Create (item^.dValue)); end; end; end; // ----------------------------------------------------------------- // For doumentation, see the C API docs at: // http://code.google.com/p/roadrunnerwork/ // ----------------------------------------------------------------- function getRRInstance : Pointer; begin result := libGetRRInstance; end; procedure freeRRInstance (myInstance : Pointer); begin if myInstance <> nil then libFreeRRInstance (myInstance); end; procedure freeRRInstance; begin if instance <> nil then libFreeRRInstance (instance); end; function getBuildDate : AnsiString; begin result := libGetBuildDate; end; function getRevision : integer; begin result := libGetRevision; end; function getCopyright : AnsiString; var p : PAnsiChar; begin p := libGetCopyright(); result := AnsiString (p); end; function getTempFolder : AnsiString; begin result := libGetTempFolder; end; function hasError : boolean; begin result := libHasError; end; function getLastError : AnsiString; begin result := libGetLastError; end; function enableLogging : boolean; begin result := libEnableLogging; loggingEnabled := true; end; function setLogLevel (debugLevel : AnsiString) : boolean; begin result := libSetLogLevel (PAnsiChar (debugLevel)); end; function getLogFileName : AnsiString; begin result := libGetLogFileName; end; function setTempFolder (name : AnsiString) : boolean; begin result := libSetTempFolder (PAnsiChar (name)); end; function getCCode : TRRCCode; var p : PRRCCodeHandle; begin p := libGetCCode; result.Header := p^.Header; result.Source := p^.Source; end; function setComputeAndAssignConservationLaws (value : boolean) : boolean; begin result := libSetComputeAndAssignConservationLaws (value); end; function loadSBML (sbmlStr : AnsiString) : boolean; begin result := libLoadSBML (PAnsiChar (sbmlStr)); end; function loadSBMLFromFile (fileName : AnsiString) : boolean; var str : AnsiString; begin if FileExists (fileName) then begin str := TFile.ReadAllText(fileName); result := libLoadSBMLFromFile (PAnsiChar (str)); end else raise Exception.Create ('Unable to locate SBML file [' + fileName + ']'); end; function getSBML : AnsiString; begin result := libGetSBML; end; function getValue (Id : AnsiString) : double; begin if not libGetValue (PAnsiChar (Id), result) then raise Exception.Create ('Error in getVlaue'); end; function setValue (Id : AnsiString; value : double) : boolean; begin result := libSetValue (PAnsiChar (Id), value); end; function reset : boolean; begin result := libReset; end; function setFloatingSpeciesInitialConcentrations (value : TDoubleArray) : boolean; var p : PRRDoubleVectorHandle; i : integer; begin p := libCreateVector (length (value)); for i := 0 to length (value) - 1 do p^.data[i] := value[i]; result := libSetFloatingSpeciesInitialConcentrations (p); libFreeDoubleVector (p); end; function getCapabilities : AnsiString; begin result := libGetCapabilities; end; function setCapabilities (str : AnsiString) : boolean; begin result := libSetCapabilities (PAnsiChar (str)); end; function evalModel : boolean; begin result := libEvalModel; end; function getFullJacobian : T2DDoubleArray; var p : PRRMatrixHandle; begin p := libGetFullJacobian; if p = nil then raise Exception.Create ('No Jacobian matrix'); try result := loadInTo2DArray (p); finally libFreeMatrix (p); end; end; function getReducedJacobian : T2DDoubleArray; var p : PRRMatrixHandle; begin p := libGetReducedJacobian; try result := loadInTo2DArray (p); finally libFreeMatrix (p); end; end; function setTimeCourseSelectionList (strList : TStringList) : boolean; var i : integer; begin if strList.Count = 0 then exit; selectionList := strList[0]; for i := 1 to strList.Count - 1 do selectionList := selectionList + ' ' + strList[i]; if not libSetTimeCourseSelectionList (PAnsiChar (selectionList)) then raise Exception.Create ('Error calling setSelectionList'); end; function getTimeCourseSelectionList: TRRList; var ptr : PRRListRecordHandle; begin ptr := libGetTimeCourseSelectionList; result := extractList (ptr); end; procedure setTimeStart (value : double); begin if not libSetTimeStart (value) then raise Exception.Create ('Error while calling setTimeStart'); end; procedure setTimeEnd (value : double); begin if not libSetTimeEnd (value) then raise Exception.Create ('Error while calling setTimeEnd'); end; procedure setNumberOfPoints (value : integer); begin if not libSetNumberOfPoints (value) then raise Exception.Create ('Error while calling setNumberOfPoints'); end; function simulate : T2DDoubleArray; var RRResult : PRRResultHandle; i, j : integer; nr, nc : integer; begin RRResult := libSimulate; if RRResult = nil then raise Exception.Create (getLastError()); try nr := RRResult^.RSize; nc := RRResult^.CSize; setLength (result, nr, nc); for i := 0 to nr - 1 do for j := 0 to nc - 1 do result[i,j] := RRResult^.data[i*nc + j]; finally libFreeResult (RRResult); end; end; function mSimulate : TMatrix; var RRResult : PRRResultHandle; i, j : integer; nr, nc : integer; begin RRResult := libSimulate; if RRResult = nil then raise Exception.Create (getLastError()); try nr := RRResult^.RSize; nc := RRResult^.CSize; result := TMatrix.Create (nr, nc); for i := 0 to nr - 1 do for j := 0 to nc - 1 do result[i+1,j+1] := RRResult^.data[i*nc + j]; finally libFreeResult (RRResult); end; end; function simulateEx (timeStart: double; timeEnd : double; numberOfPoints : integer) : TMatrix; var RRResult : PRRResultHandle; i, j : integer; nr, nc : integer; begin RRResult := libSimulateEx (timeStart, timeEnd, numberOfPoints); if RRResult = nil then raise Exception.Create (getLastError()); try nr := RRResult^.RSize; nc := RRResult^.CSize; result := TMatrix.Create (nr, nc); for i := 0 to nr - 1 do for j := 0 to nc - 1 do result[i+1,j+1] := RRResult^.data[i*nc + j]; finally libFreeResult (RRResult); end; end; function oneStep (var currentTime : double; var stepSize : double) : double; begin result := libOneStep (currentTime, stepSize); end; function getReactionIds : TStringList; var pList : PRRStringArray; begin pList := libGetReactionIds; if pList <> nil then try result := getArrayOfStrings(pList); finally libFreeStringArray (pList); end else result := TStringList.Create; end; function getNumberOfReactions : integer; begin result := libGetNumberOfReactions; end; function getNumberOfBoundarySpecies : integer; begin result := libGetNumberOfBoundarySpecies; end; function getBoundarySpeciesIds : TStringList; var p : PRRStringArray; begin p := libGetBoundarySpeciesIds; try if p = nil then result := TStringList.Create else result := getArrayOfStrings(p); finally libFreeStringArray (p); end; end; function getFloatingSpeciesIds : TStringList; var p : PRRStringArray; begin p := libGetFloatingSpeciesIds; try if p = nil then result := TStringList.Create else result := getArrayOfStrings(p); finally libFreeStringArray (p); end; end; function getGlobalParameterIds : TStringList; var p : PRRStringArray; begin p := libGetGlobalParameterIds; try if p = nil then result := TStringList.Create else result := getArrayOfStrings (p); finally libFreeStringArray (p); end; end; function getFloatingSpeciesConcentrations : TDoubleArray; var p : PRRDoubleVectorHandle; i : integer; begin p := libGetFloatingSpeciesConcentrations; try setLength (result, p^.count); for i := 0 to p^.count - 1 do result[i] := p^.data[i]; finally libFreeDoubleVector (p); end; end; function getBoundarySpeciesConcentrations : TDoubleArray; var p : PRRDoubleVectorHandle; i : integer; begin p := libGetBoundarySpeciesConcentrations; try setLength (result, p^.count); for i := 0 to p^.count - 1 do result[i] := p^.data[i]; finally if p^.count > 0 then libFreeDoubleVector (p); end; end; function getRatesOfChangeIds : TStringList; var p : PRRStringArray; begin p := libGetRatesOfChangeIds; try if p = nil then result := TStringList.Create else result := getArrayOfStrings (p); finally libFreeStringArray (p); end; end; function getEigenValueIds : TStringList; var p : PRRStringArray; begin p := libGetEigenValueIds; try if p = nil then result := TStringList.Create else result := getArrayOfStrings (p); finally libFreeStringArray (p); end; end; function getElasticityIds : TStringList; var p : PRRStringArray; begin p := libGetElasticityIds; try if p = nil then result := TStringList.Create else result := getArrayOfStrings (p); finally libFreeStringArray (p); end; end; function getNumberOfFloatingSpecies : integer; begin result := libGetNumberOfFloatingSpecies; end; function getNumberOfGlobalParameters : integer; begin result := libGetNumberOfGlobalParameters; end; function getNumberOfCompartments : integer; begin result := libGetNumberOfCompartments; end; function getCompartmentIds : TStringList; var pList : PRRStringArray; begin pList := libGetCompartmentIds; if pList <> nil then try result := getArrayOfStrings(pList); finally libFreeStringArray (pList); end else result := TStringList.Create; end; function setCompartmentByIndex (index : integer; value : double) : boolean; begin result := libSetCompartmentByIndex (index, value); end; function setFloatingSpeciesByIndex (index : integer; value : double) : boolean; begin result := libSetFloatingSpeciesByIndex (index, value); end; function setBoundarySpeciesByIndex (index : integer; value : double) : boolean; begin result := libSetBoundarySpeciesByIndex (index, value); end; function setGlobalParameterByIndex (index : integer; value : double) : boolean; begin result := libSetGlobalParameterByIndex (index, value); end; function getCompartmentByIndex (index : integer) : double; begin if not libGetCompartmentByIndex (index, result) then raise Exception.Create ('Index out of range in getCompartmentByIndex'); end; function getFloatingSpeciesByIndex (index : integer) : double; begin if not libGetFloatingSpeciesByIndex (index, result) then raise Exception.Create ('Index out of range in getFloatingSpeciesByIndex'); end; function getBoundarySpeciesByIndex (index : integer) : double; begin if not libGetBoundarySpeciesByIndex (index, result) then raise Exception.Create ('Index out of range in getBoundarySpeciesByIndex'); end; function getGlobalParameterByIndex (index : integer) : double; begin if not libGetGlobalParameterByIndex (index, result) then raise Exception.Create ('Index out of range in getGlobalParameterByIndex'); end; function getNumberOfDependentSpecies : integer; begin result := libGetNumberOfDependentSpecies; end; function getNumberOfIndependentSpecies : integer; begin result := libGetNumberOfIndependentSpecies; end; function steadyState : double; var errMsg : AnsiString; begin if not libSteadyState (result) then begin errMsg := getLastError; raise Exception.Create (errMsg); end; end; function computeSteadyStateValues : TDoubleArray; var p : PRRDoubleVectorHandle; i : integer; begin p := libComputeSteadyStateValues; try setLength (result, p.count); for i := 0 to p.count - 1 do result[i] := p.data[i]; finally libFreeDoubleVector (p); end; end; function getEigenValues : T2DDoubleArray; var p : PRRMatrixHandle; begin p := libGetEigenValues; if p = nil then raise Exception.Create ('No Eigenvalue matrix'); try result := loadInTo2DArray (p); finally libFreeMatrix (p); end; end; function setSteadyStateSelectionList (strList : TStringList) : boolean; var i : integer; str : AnsiString; begin if strList.Count > 0 then begin str := strList[0]; for i := 1 to strList.Count - 1 do str := ' ' + strList[i]; libSetSteadyStateSelectionList (PAnsiChar (str)); end; result := true; end; function getSteadyStateSelectionList: TRRList; var ptr : PRRListRecordHandle; begin ptr := libGetSteadyStateSelectionList; result := extractList (ptr); end; function getuCC (variable : AnsiString; parameter : AnsiString) : double; begin if not libgetuCC (PAnsiChar (variable), PAnsiChar (parameter), result) then raise Exception.Create ('Error in getCC function'); end; function getCC (variable : AnsiString; parameter : AnsiString) : double; begin if not libgetCC (PAnsiChar (variable), PAnsiChar (parameter), result) then raise Exception.Create ('Error in getCC function'); end; function getuEE (variable : AnsiString; parameter : AnsiString) : double; begin if not libgetuEE (PAnsiChar (variable), PAnsiChar (parameter), result) then raise Exception.Create ('Error in getCC function'); end; function getEE (variable : AnsiString; parameter : AnsiString) : double; begin if not libgetEE (PAnsiChar (variable), PAnsiChar (parameter), result) then raise Exception.Create ('Error in getCC function'); end; function getAvailableTimeCourseSymbols : TRRList; var ptr : PRRListRecordHandle; begin ptr := libGetAvailableTimeCourseSymbols(); result := extractList (ptr); end; function getAvailableSteadStateSymbols : TRRList; var ptr : PRRListRecordHandle; begin ptr := libGetAvailableSteadyStateSymbols(); result := extractList (ptr); end; // Deprecated function getAvailableSymbolsII : TRRList; var subList : TRRList; st : TStringList; i : integer; ptr : PRRListRecordHandle; begin ptr := libGetAvailableTimeCourseSymbols(); result := extractList (ptr); exit; subList := TRRList.Create; subList.Add (TRRListItem.Create ('time')); result.Add (TRRListItem.Create (subList)); subList := TRRList.Create; subList.Add (TRRListItem.Create ('Floating Species')); st := getFloatingSpeciesIds(); for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free; st := getBoundarySpeciesIds(); subList := TRRList.Create; subList.Add (TRRListItem.Create ('Boundary Species')); for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free; {st := getFloatingSpeciesAmountIds(); subList := TRRList.Create; for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free;} {st := getBoundarySpeciesAmountIds(); subList := TRRList.Create; for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); lresultist.Add (TRRListItem.Create (subList)); st.Free;} st := getGlobalParameterIds(); subList := TRRList.Create; subList.Add (TRRListItem.Create ('Global Parameter Ids')); for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free; {st := getCompartmentIds(); subList := TRRList.Create; subList.Add (TRRListItem.Create ('Compartments')); for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free;} st := getReactionIds(); subList := TRRList.Create; subList.Add (TRRListItem.Create ('Reaction Ids')); for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free; {st := getRatesOfChangeIds(); subList := TRRList.Create; subList.Add (TRRListItem.Create ('Rate of Change Ids')); for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free;} {st := getElasticityCoefficientIds(); subList := TRRList.Create; subList.Add (TRRListItem.Create ('Elasticity Coefficients')); for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free;} {st := getUnscaledElasticityCoefficientIds(); subList := TRRList.Create; subList.Add (TRRListItem.Create ('Unscaled Elasticity Coefficients')); for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free;} {st := getEigenValueIds(); subList := TRRList.Create; subList.Add (TRRListItem.Create ('Eigenvalues')); for i := 0 to st.Count - 1 do subList.Add (TRRListItem.Create (st[i])); result.Add (TRRListItem.Create (subList)); st.Free;} {p := libGetAvailableSymbols; setLength (result, p^.count); for i := 0 to p^.count - 1 do begin result[i].labelStr := p^.list[i].labelStr; result[i].stringList := getArrayOfStrings (@(p^.list[i])); end;} end; function getReactionRate (index : integer) : double; begin result := libGetReactionRate (index); end; function getReactionRates : TDoubleArray; var p : PRRDoubleVectorHandle; i : integer; begin p := libGetReactionRates; try if p = nil then begin setLength (result, 0); exit; end; setLength (result, p^.count); for i := 0 to p^.count - 1 do result[i] := p^.data[i]; finally libFreeDoubleVector (p); end; end; function getRatesOfChange : TDoubleArray; var p : PRRDoubleVectorHandle; i : integer; begin p := libGetRatesOfChange; try if p = nil then begin setLength (result, 0); exit; end; setLength (result, p^.count); for i := 0 to p^.count - 1 do result[i] := p^.data[i]; finally libFreeDoubleVector (p); end; end; function getStoichiometryMatrix : T2DDoubleArray; var st : PRRMatrixHandle; i : integer; begin st := libGetStoichiometryMatrix; try if st = nil then begin setLength (result, 0, 0); exit; end; result := loadInTo2DArray(st); finally libFreeMatrix (st); end; end; function getLinkMatrix : T2DDoubleArray; var st : PRRMatrixHandle; i, j : integer; begin st := libGetLinkMatrix; try if st = nil then begin setLength (result, 0, 0); exit; end; result := loadInTo2DArray (st); finally libFreeMatrix (st); end; end; function getNrMatrix : T2DDoubleArray; var st : PRRMatrixHandle; begin st := libGetNrMatrix; try if st = nil then begin setLength (result, 0, 0); exit; end; result := loadInTo2DArray (st); finally libFreeMatrix (st); end; end; function getL0Matrix : T2DDoubleArray; var st : PRRMatrixHandle; begin st := libGetL0Matrix; try if st = nil then begin setLength (result, 0, 0); exit; end; result := loadInTo2DArray (st); finally libFreeMatrix (st); end; end; function getConservationMatrix : T2DDoubleArray; var st : PRRMatrixHandle; begin st := libGetConservationMatrix; try if st = nil then begin setLength (result, 0, 0); exit; end; result := loadInTo2DArray (st); finally libFreeMatrix (st); end; end; // --------------------------------------------------------------------- procedure setRoadRunnerLibraryName (newLibName : AnsiString); begin libName := newLibName; end; function loadSingleMethod (methodName : string; var errMsg : AnsiString; var success : boolean; methodList : TStringList) : Pointer; begin result := GetProcAddress(dllHandle, PChar (methodName)); if not Assigned (result) then begin methodList.Add (methodName + ': ****************** FAILED'); errMsg := 'Failed to load method: ' + methodName; success := false; end else methodList.Add (methodName + ': found'); end; function loadMethods (var errMsg : AnsiString; methodList : TStringList) : boolean; begin result := true; try @libGetBuildDate := loadSingleMethod ('getBuildDate', errMsg, result, methodList); @libGetRevision := loadSingleMethod ('getVersion', errMsg, result, methodList); @libHasError := loadSingleMethod ('hasError', errMsg, result, methodList); @libGetLastError := loadSingleMethod ('getLastError', errMsg, result, methodList); @libSetLogLevel := loadSingleMethod ('setLogLevel', errMsg, result, methodList); @libEnableLogging := loadSingleMethod ('enableLogging', errMsg, result, methodList); libGetLogFileName := loadSingleMethod ('getLogFileName', errMsg, result, methodList); @libSetTempFolder := loadSingleMethod ('setTempFolder', errMsg, result, methodList); @libGetTempFolder := loadSingleMethod ('getTempFolder', errMsg, result, methodList); @libGetCCode := loadSingleMethod ('getCCode', errMsg, result, methodList); @libGetCopyright := loadSingleMethod ('getCopyright', errMsg, result, methodList); @libGetRRInstance := loadSingleMethod ('getRRInstance', errMsg, result, methodList); @libSetComputeAndAssignConservationLaws := loadSingleMethod ('setComputeAndAssignConservationLaws', errMsg, result, methodList); @libLoadSBMLFromFile := loadSingleMethod ('loadSBMLFromFile', errMsg, result, methodList); @libLoadSBML := loadSingleMethod ('loadSBML', errMsg, result, methodList); @libGetSBML := loadSingleMethod ('getSBML', errMsg, result, methodList); @libSetTimeStart := loadSingleMethod ('setTimeStart', errMsg, result, methodList); @libSetTimeEnd := loadSingleMethod ('setTimeEnd', errMsg, result, methodList); @libSetNumberOfPoints := loadSingleMethod ('setNumPoints', errMsg, result, methodList); @libSimulate := loadSingleMethod ('simulate', errMsg, result, methodList); @libSimulateEx := loadSingleMethod ('simulateEx', errMsg, result, methodList); @libOneStep := loadSingleMethod ('oneStep', errMsg, result, methodList); @libReset := loadSingleMethod ('reset', errMsg, result, methodList); @libGetCapabilities := loadSingleMethod ('getCapabilities', errMsg, result, methodList); @libSetCapabilities := loadSingleMethod ('setCapabilities', errMsg, result, methodList); @libSetFloatingSpeciesInitialConcentrations := loadSingleMethod ('_setFloatingSpeciesInitialConcentrations@4', errMsg, result, methodList); @libEvalModel := loadSingleMethod ('evalModel', errMsg, result, methodList); @libGetFullJacobian := loadSingleMethod('getFullJacobian', errMsg, result, methodList); @libGetReducedJacobian := loadSingleMethod('getReducedJacobian', errMsg, result, methodList); @libSetValue := loadSingleMethod ('setValue', errMsg, result, methodList); @libGetValue := loadSingleMethod ('getValue', errMsg, result, methodList); @libSetTimeCourseSelectionList := loadSingleMethod ('setTimeCourseSelectionList', errMsg, result, methodList); //@libGetTimeCourseSelectionList := loadSingleMethod ('getTimeCourseSelectionList', errMsg, result, methodList); @libGetNumberOfReactions := loadSingleMethod ('getNumberOfReactions', errMsg, result, methodList); @libGetNumberOfBoundarySpecies := loadSingleMethod ('getNumberOfBoundarySpecies', errMsg, result, methodList); @libGetNumberOfFloatingSpecies := loadSingleMethod ('getNumberOfFloatingSpecies', errMsg, result, methodList); @libGetNumberOfGlobalParameters := loadSingleMethod ('getNumberOfGlobalParameters', errMsg, result, methodList); @libGetNumberOfCompartments := loadSingleMethod ('getNumberOfCompartments', errMsg, result, methodList); @libSetCompartmentByIndex := loadSingleMethod ('setCompartmentByIndex', errMsg, result, methodList); @libSetFloatingSpeciesByIndex := loadSingleMethod ('setFloatingSpeciesByIndex', errMsg, result, methodList); @libSetBoundarySpeciesByIndex := loadSingleMethod ('setBoundarySpeciesByIndex', errMsg, result, methodList); @libSetGlobalParameterByIndex := loadSingleMethod ('setGlobalParameterByIndex', errMsg, result, methodList); @libGetCompartmentByIndex := loadSingleMethod ('getCompartmentByIndex', errMsg, result, methodList); @libGetFloatingSpeciesByIndex := loadSingleMethod ('getFloatingSpeciesByIndex', errMsg, result, methodList); @libGetBoundarySpeciesByIndex := loadSingleMethod ('getBoundarySpeciesByIndex', errMsg, result, methodList); @libGetGlobalParameterByIndex := loadSingleMethod ('getGlobalParameterByIndex', errMsg, result, methodList); @libGetFloatingSpeciesConcentrations := loadSingleMethod ('getFloatingSpeciesConcentrations', errMsg, result, methodList); @libGetBoundarySpeciesConcentrations := loadSingleMethod ('_getBoundarySpeciesConcentrations@0', errMsg, result, methodList); @libGetNumberOfDependentSpecies := loadSingleMethod ('getNumberOfDependentSpecies', errMsg, result, methodList); @libGetNumberOfIndependentSpecies := loadSingleMethod ('getNumberOfIndependentSpecies', errMsg, result, methodList); @libSteadyState := loadSingleMethod ('steadyState', errMsg, result, methodList); @libComputeSteadyStateValues := loadSingleMethod ('computeSteadyStateValues', errMsg, result, methodList); @libSetSteadyStateSelectionList := loadSingleMethod ('setSteadyStateSelectionList', errMsg, result, methodList); @libGetSteadyStateSelectionList := loadSingleMethod ('getSteadyStateSelectionList', errMsg, result, methodList); @libGetReactionRate := loadSingleMethod ('getReactionRate', errMsg, result, methodList); @libGetReactionRates := loadSingleMethod ('getReactionRates', errMsg, result, methodList); @libGetRatesOfChange := loadSingleMethod ('getRatesOfChange', errMsg, result, methodList); @libGetCompartmentIds := loadSingleMethod ('getCompartmentIds', errMsg, result, methodList); @libGetReactionIds := loadSingleMethod ('getReactionIds', errMsg, result, methodList); @libGetBoundarySpeciesIds := loadSingleMethod ('getBoundarySpeciesIds', errMsg, result, methodList); @libGetFloatingSpeciesIds := loadSingleMethod ('getFloatingSpeciesIds', errMsg, result, methodList); @libGetGlobalParameterIds := loadSingleMethod ('getGlobalParameterIds', errMsg, result, methodList); @libGetRatesOfChangeIds := loadSingleMethod ('getRatesOfChangeIds', errMsg, result, methodList); @libGetEigenValueIds := loadSingleMethod ('getEigenValueIds', errMsg, result, methodList); @libGetElasticityIds := loadSingleMethod ('getElasticityCoefficientIds', errMsg, result, methodList); @libGetAvailableTimeCourseSymbols := loadSingleMethod ('getAvailableTimeCourseSymbols', errMsg, result, methodList); @libGetAvailableSteadyStateSymbols := loadSingleMethod ('getAvailableSteadyStateSymbols', errMsg, result, methodList); @libGetStoichiometryMatrix := loadSingleMethod ('getStoichiometryMatrix', errMsg, result, methodList); @libGetLinkMatrix := loadSingleMethod ('getLinkMatrix', errMsg, result, methodList); @libGetNrMatrix := loadSingleMethod ('getNrMatrix', errMsg, result, methodList); @libGetL0Matrix := loadSingleMethod ('getL0Matrix', errMsg, result, methodList); @libGetConservationMatrix := loadSingleMethod ('getConservationMatrix', errMsg, result, methodList); @libgetuCC := loadSingleMethod ('getuCC', errMsg, result, methodList); @libgetuEE := loadSingleMethod ('getuEE', errMsg, result, methodList); @libgetCC := loadSingleMethod ('getCC', errMsg, result, methodList); @libgetEE := loadSingleMethod ('getEE', errMsg, result, methodList); @libGetEigenValues := loadSingleMethod ('getEigenValues', errMsg, result, methodList); @libGetListItem := loadSingleMethod ('getListItem', errMsg, result, methodList); @libFreeRRInstance := loadSingleMethod ('freeRRInstance', errMsg, result, methodList); @libFreeResult := loadSingleMethod ('freeResult', errMsg, result, methodList); @libFreeMatrix := loadSingleMethod ('freeMatrix', errMsg, result, methodList); @libFreeText := loadSingleMethod ('freeText', errMsg, result, methodList); @libFreeStringArray := loadSingleMethod ('freeStringArray', errMsg, result, methodList); @libCreateVector := loadSingleMethod ('createVector', errMsg, result, methodList); @libFreeDoubleVector := loadSingleMethod ('freeVector', errMsg, result, methodList); except on E: Exception do begin errMsg := e.message; result := false; exit; end; end; end; function loadRoadRunner (var errMsg : AnsiString; methodList : TStringList) : boolean; var errStr : string; tempString: WideString; aString: PChar; begin DLLLoaded := false; if FileExists (libName) then begin tempString := WideString (libName); DllHandle := LoadLibrary (PWideChar(tempString)); if DllHandle <> 0 then begin if loadMethods (errMsg, methodList) then begin DLLLoaded := True; result := true; end else result := false; end else begin errStr := SysErrorMessage(Windows.GetLastError); DLLLoaded := False; errMsg := 'Failed to load roadRunner at:[' + getCurrentDir + ']: ' + errStr; end; end else begin DLLLoaded := False; errMsg := 'Unable to locate roadRunner library at:[' + getCurrentDir + ']'; end; end; procedure releaseRoadRunnerLibrary; begin DLLLoaded := false; libFreeRRInstance (instance); // <- should this be here? freeLibrary (DLLHandle); end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit DBQueryThread; interface uses Windows, Messages, Forms, Db, Classes, Ora, StdCtrls, SysUtils, OraStorage, OraScript, OraError; const WM_MYSQL_THREAD_NOTIFY = WM_USER+100; type TThreadResult = record ThreadID : Integer; SessionID : Cardinal; Action : Integer; Sql : String; Result : Integer; Comment : String; end; TDBQueryThread = class(TThread) private FDBSession : TOraSession; FOwner : TObject; //->> TDBQuery object FSql : String; FResult : Integer; FComment : String; FSyncMode : Integer; FNotifyWndHandle : THandle; procedure ReportInit; procedure ReportStart; procedure ReportFinished; procedure ReportFreed; function GetExceptionData(AException : Exception) : TExceptionData; protected procedure Execute; override; procedure SetState (AResult : Integer; AComment : String); procedure SetNotifyWndHandle (Value : THandle); procedure NotifyStatus (AEvent : Integer); procedure NotifyStatusViaEventProc (AEvent : Integer); procedure NotifyStatusViaWinMessage (AEvent : Integer); function AssembleResult () : TThreadResult; function RunDataQuery (ASql : String; var ADataset : TDataset; out AExceptionData : TExceptionData) : Boolean; function RunUpdateQuery (ASql : String; out AExceptionData : TExceptionData) : Boolean; function RunExecQuery(ASql: String; out AExceptionData : TExceptionData): Boolean; function QuerySingleCellAsInteger (ASql : String) : Integer; procedure osError(Sender: TObject; E: Exception; SQL: String; var Action: TErrorAction); public constructor Create (AOwner : TObject; ADBSession : TOraSession; ASql : String; ASyncMode : Integer); destructor Destroy; override; property NotifyWndHandle : THandle read FNotifyWndHandle write SetNotifyWndHandle; end; implementation uses DBQuery, Dialogs, util ; function TDBQueryThread.AssembleResult: TThreadResult; begin ZeroMemory (@Result,SizeOf(Result)); Result.ThreadID := ThreadID; Result.SessionID := 1; Result.Action := 1; Result.Sql := FSql; Result.Result := FResult; Result.Comment := FComment; end; constructor TDBQueryThread.Create(AOwner : TObject; ADBSession : TOraSession; ASql : String; ASyncMode : Integer); begin Inherited Create(True); FOwner := AOwner; FDBSession := ADBSession; FSyncMode := ASyncMode; FResult := 0; FSql := ASql; FreeOnTerminate := True; end; destructor TDBQueryThread.Destroy; begin inherited; end; procedure TDBQueryThread.NotifyStatus(AEvent: Integer); var h : THandle; begin if Terminated then exit; if (FSyncMode=MQM_SYNC) and (AEvent=MQE_FREED) then begin h := OpenEvent (EVENT_ALL_ACCESS,False,PChar(TDBQuery(FOwner).EventName)); if h<>0 then SetEvent (h); end; case TDBQuery(FOwner).NotificationMode of MQN_EVENTPROC: NotifyStatusViaEventProc(AEvent); MQN_WINMESSAGE: NotifyStatusViaWinMessage(AEvent); end; end; procedure TDBQueryThread.NotifyStatusViaEventProc(AEvent: Integer); begin if FSyncMode=MQM_ASYNC then begin case AEvent of MQE_INITED: Synchronize(ReportInit); MQE_STARTED: Synchronize(ReportStart); MQE_FINISHED: Synchronize(ReportFinished); MQE_FREED: Synchronize(ReportFreed); end; end; end; procedure TDBQueryThread.NotifyStatusViaWinMessage(AEvent: Integer); var qr : TThreadResult; begin qr := AssembleResult(); //debug(Format('thr: Setting result and posting status %d via WM_MYSQL_THREAD_NOTIFY message', [AEvent])); TDBQuery(FOwner).SetThreadResult(qr); PostMessage(FNotifyWndHandle,WM_MYSQL_THREAD_NOTIFY,Integer(FOwner),AEvent); end; procedure TDBQueryThread.Execute; var q : TOraQuery; r : Boolean; e : TExceptionData; begin //debug(Format('thr: Thread %d running...', [ThreadID])); NotifyStatus(MQE_INITED); try if not FDBSession.Connected then FDBSession.Connect(); except on E: Exception do begin SetState (MQR_CONNECT_FAIL,Format('%s',[E.Message])); end; end; if FDBSession.Connected then begin NotifyStatus (MQE_STARTED); if ExpectResultSet(FSql) then begin q := nil; r := RunDataQuery (FSql,TDataSet(q),e); if r then begin if q.State=dsBrowse then begin // WTF? end; end; TDBQuery(FOwner).SetDBDataset(q); end else begin if ExpectScriptSet(FSql) then r := RunExecQuery (FSql,e) else r := RunUpdateQuery (FSql,e); end; if r then SetState (MQR_SUCCESS, 'SUCCESS') else SetState (MQR_QUERY_FAIL, e.Msg); end; if Terminated then SetState (MQR_CANCEL, 'CANCELLED'); NotifyStatus (MQE_FINISHED); NotifyStatus (MQE_FREED); debug(Format('thr: Thread %d suspending.', [ThreadID])); end; function TDBQueryThread.GetExceptionData( AException: Exception): TExceptionData; begin ZeroMemory (@Result,SizeOf(Result)); Result.Msg := AException.Message; Result.HelpContext := AException.HelpContext; end; function TDBQueryThread.QuerySingleCellAsInteger(ASql: String): Integer; var ds : TDataSet; e : TExceptionData; begin Result := 0; if RunDataQuery(ASql,ds,e) then begin if ds.Fields.Count > 0 then Result := ds.Fields[0].AsInteger; FreeAndNil (ds); end; end; procedure TDBQueryThread.ReportStart(); var qr : TThreadResult; begin qr := AssembleResult(); if FOwner <> nil then TDBQuery (FOwner).PostNotification(qr,MQE_STARTED); end; procedure TDBQueryThread.ReportFinished(); var qr : TThreadResult; begin qr := AssembleResult(); if FOwner <> nil then TDBQuery (FOwner).PostNotification(qr,MQE_FINISHED); end; procedure TDBQueryThread.ReportInit(); var qr : TThreadResult; begin qr := AssembleResult(); if FOwner <> nil then TDBQuery(FOwner).PostNotification(qr,MQE_INITED); end; procedure TDBQueryThread.ReportFreed; var qr : TThreadResult; begin qr := AssembleResult(); if FOwner <> nil then TDBQuery(FOwner).PostNotification(qr,MQE_FREED); end; function TDBQueryThread.RunDataQuery(ASql: String; var ADataset: TDataset; out AExceptionData : TExceptionData): Boolean; var q : TOraQuery; begin Result := False; q := TOraQuery.Create(nil); q.Session := FDBSession; q.SQL.Text := ASql; q.FetchRows := 500; try q.Active := True; ADataset := q; Result := True; except on E: Exception do begin AExceptionData := GetExceptionData(E); end; end; end; function TDBQueryThread.RunUpdateQuery(ASql: String; out AExceptionData : TExceptionData): Boolean; var q : TOraQuery; begin Result := False; q := TOraQuery.Create(nil); q.Session := FDBSession; q.AutoCommit := false; q.CachedUpdates := true; q.SQL.Text := ASql; try q.ExecSQL(); Result := True; TDBQuery(FOwner).SetRowsAffected(q.rowsaffected); except On E: Exception do AExceptionData := GetExceptionData(E); end; FreeAndNil (q); end; function TDBQueryThread.RunExecQuery(ASql: String; out AExceptionData : TExceptionData): Boolean; var q : TOraScript; begin Result := False; q := TOraScript.Create(nil); q.Session := FDBSession; q.OnError := osError; q.SQL.Text := ASql; try q.Execute; Result := True; TDBQuery(FOwner).SetRowsAffected(0); except On E: EOraError do AExceptionData := GetExceptionData(E); end; FreeAndNil (q); end; procedure TDBQueryThread.osError(Sender: TObject; E: Exception; SQL: String; var Action: TErrorAction); begin Action := eaFail; //hatanın RunExecQuery düşmesi için end; procedure TDBQueryThread.SetNotifyWndHandle(Value: THandle); begin FNotifyWndHandle := Value; end; procedure TDBQueryThread.SetState(AResult: Integer; AComment: String); begin FResult := AResult; FComment := AComment; end; end.
unit EasyExample; {$mode objfpc}{$H+} interface uses Classes, SysUtils, V8AddIn, fpTimer, FileUtil, LazUTF8; type { TTimerThread } TTimerThread = class (TThread) public Interval: Integer; OnTimer: TNotifyEvent; procedure Execute; override; end; { TAddInEasyExample } TAddInEasyExample = class (TAddIn) private FNum : DWORD; FIsEnabled: Boolean; FTimer: TTimerThread; procedure MyTimerProc(Sender: TObject); public function GetIsEnabled: Variant; procedure SetIsEnabled(AValue: Variant); function GetIsTimerPresent: Variant; procedure Enable; procedure Disable; procedure ShowInStatusLine(Text: Variant); procedure StartTimer; procedure StopTimer; destructor Destroy; override; function LoadPicture(FileName: Variant): Variant; function ReadNumber(Params: Variant):Variant; // Test nums procedure WriteNumber(Number: Variant); procedure ShowMessageBox; // test arrays //procedure mLoadArrayList(ArrayList,ArraySize : Variant); //function mReturnArrayList(ArraySize : Variant):Variant; end; implementation { TTimerThread } procedure TTimerThread.Execute; begin repeat Sleep(Interval); if Terminated then Break else OnTimer(Self); until False; end; { TAddInEasyExample } procedure TAddInEasyExample.MyTimerProc(Sender: TObject); begin ExternalEvent('EasyComponentNative', 'Timer', DateTimeToStr(Now)); end; function TAddInEasyExample.GetIsEnabled: Variant; begin Result := FIsEnabled; end; procedure TAddInEasyExample.SetIsEnabled(AValue: Variant); begin FIsEnabled := AValue; end; function TAddInEasyExample.GetIsTimerPresent: Variant; begin Result := True; end; procedure TAddInEasyExample.Enable; begin FIsEnabled := True; end; procedure TAddInEasyExample.Disable; begin FIsEnabled := False; end; procedure TAddInEasyExample.ShowInStatusLine(Text: Variant); begin SetStatusLine(Text); end; procedure TAddInEasyExample.StartTimer; begin if FTimer = nil then begin FTimer := TTimerThread.Create(True); FTimer.Interval := 1000; FTimer.OnTimer := @MyTimerProc; FTimer.Start; end; end; procedure TAddInEasyExample.StopTimer; begin if FTimer <> nil then FreeAndNil(FTimer); end; destructor TAddInEasyExample.Destroy; begin if FTimer <> nil then FreeAndNil(FTimer); inherited Destroy; end; function TAddInEasyExample.LoadPicture(FileName: Variant): Variant; var SFileName: String; FileStream: TFileStream; begin SFileName := UTF8ToSys(String(FileName)); FileStream := TFileStream.Create(SFileName, fmOpenRead); try Result := StreamTo1CBinaryData(FileStream); finally FileStream.Free; end; end; procedure TAddInEasyExample.ShowMessageBox; begin if Confirm(AppVersion) then Alert('OK') else Alert('Cancel'); end; procedure TAddInEasyExample.WriteNumber(Number: Variant); begin FNum := Number; end; function TAddInEasyExample.ReadNumber(Params: Variant):Variant; begin Result := Variant(FNum); end; //procedure TAddInEasyExample.mLoadArrayList(ArrayList,ArraySize : Variant); //var i : integer; //begin // for i := 0 to ArraySize-1 do // SetStatusLine('Тип значения ' + IntToStr(i) + ' ' + ArrayList[i]); //end; // //function TAddInEasyExample.mReturnArrayList(ArraySize : Variant):Variant; //begin // Result := nil; //end; end.
unit PDijkstra; interface uses PPriorityQ, Sysutils, Generics.Collections, PPlaceRoad, Vcl.Dialogs; type TDijkstra = class(TMinHeap) public function ShortestPath(s, d: string; Map: TObjectList<TPlace>) : TObjectList<TPlace>; function ReturnPath(List: TObjectList<TPlace>; Current, Source: string; Map: TObjectList<TPlace>): TObjectList<TPlace>; end; implementation { TDijkstra } function TDijkstra.ShortestPath(s, d: string; Map: TObjectList<TPlace>) : TObjectList<TPlace>; // find shortest route between two points on a map // s and d being the name of the source and destination vertex // the function returns the min distance // and prints the shortest path var ShortestRoute: TObjectList<TPlace>; // holds vertices in shortest path i, idx, k: integer; Current, Neighbour: TPlace; begin Current := TPlace.Create; Neighbour := TPlace.Create; ShortestRoute := TObjectList<TPlace>.Create; if not ContainsPlace(s, MinHeap) or not ContainsPlace(d, MinHeap) then // check if source or destination has been removed begin result := nil; end else begin for k := 0 to Count - 1 do // loops through MinHeap begin if MinHeap.List[k].GetName <> s then // Initialise all non source vertices to a distance of 1000 begin MinHeap.List[k].SetDist(1000); Update(1000, MinHeap.Items[k].GetName, '', Map); end else begin MinHeap.List[k].SetDist(0); // Initialise the source vertex to a distance of 0 MinHeap.List[k].SetParent(s); GetPlace(MinHeap.List[k].GetName, Map).SetDist(0); GetPlace(MinHeap.List[k].GetName, Map).SetParent(s); end; end; Build_Heap; // Initialise the heap extract_mini(Current); // extract the neighbouring vertex with lowest distance while Current.GetName <> d do // loop until the destination vertex is reached begin for i := 0 to (Current.edges.Count) - 1 do // loop through neighbouring edges begin Neighbour := GetPlace(Current.Neighbours[i], Map); if (Current.edges[i].GetWeight + Current.GetDist < Neighbour.GetDist) and ContainsPlace(Neighbour.GetName, MinHeap) then // check if new distance to neighbour is less than the current distance to neighbour begin idx := FindIndex(Neighbour); Neighbour.SetParent(Current.GetName); DecreaseKey(idx, Current.edges[i].GetWeight + Current.GetDist); // Decrease distance of Neighbour in MinHeap Update(Current.edges[i].GetWeight + Current.GetDist, Current.Neighbours[i], Current.GetName, Map); // Updates the distance in all instances of the objects end; end; extract_mini(Current); end; result := ReturnPath(ShortestRoute, d, s, Map); // return the Shortest Route list end; end; function TDijkstra.ReturnPath(List: TObjectList<TPlace>; Current, Source: string; Map: TObjectList<TPlace>): TObjectList<TPlace>; // Recurses through the parents of the shortest path and outputs the Shortest Path in a list // Starts at the Destination and works backwards using parents begin if Current = Source then // check whether it has reached the source begin List.Add(GetPlace(Current, Map)); // add to list end else begin ReturnPath(List, GetPlace(Current, Map).GetParent, Source, Map); // use current places' parent for each recursive call List.Add(GetPlace(Current, Map)); // add current to list as it unwinds the recursion end; result := List; end; end.
unit Project.Endereco; interface uses Project.Interfaces; type TEndereco<T : IInterface> = class(TInterfacedObject , iEndereco<T>) private [Weak] FParent : T; FRua : String; FNumero : Integer; public constructor Create(Parent : T); destructor Destroy; override; class function New(Parent : T) : iEndereco<T>; function Rua ( aValue : String ) : iEndereco<T>; overload; function Rua : String; overload; function Numero ( aValue : Integer ) : iEndereco<T>; overload; function Numero : Integer; overload; function &End : T; end; implementation { TEndereco } function TEndereco<T>.&End: T; begin Result := FParent; end; constructor TEndereco<T>.Create(Parent : T); begin FParent := Parent; end; destructor TEndereco<T>.Destroy; begin inherited; end; class function TEndereco<T>.New(Parent : T): iEndereco<T>; begin Result := Self.Create(Parent); end; function TEndereco<T>.Numero: Integer; begin Result := FNumero; end; function TEndereco<T>.Numero(aValue: Integer): iEndereco<T>; begin Result := Self; FNumero := aValue; end; function TEndereco<T>.Rua: String; begin Result := FRua; end; function TEndereco<T>.Rua(aValue: String): iEndereco<T>; begin Result := Self; FRua := aValue; end; end.
{***************************************** * Unit for basic statistical Functions * *****************************************} Unit Stats; Interface Const SIZE = 500; Type pVec = ^VEC; VEC = Array[1..SIZE] of Real; Procedure NormalStats(a:pVec; n:Integer; flag:Char; Var avg, std_dev: Real); Procedure NormalArray(a:pVec; n:Integer); Procedure LinearReg(x,y:pVec; n:Integer; flag:Char; Var a,b,s_yx,r: Real); Implementation Function Dot_Product(n:Integer; x,y:pVec): Real; Var i:Integer; temp:Real; Begin temp:=0.0; For i:=1 to n do temp:=temp + x^[i]*y^[i]; Dot_Product := temp End; Function Sum(n:Integer; x:pVec): Real; Var i:Integer; temp:Real; Begin temp:=0.0; For i:=1 to n do temp:=temp + x^[i]; Sum := temp End; {--------------------------------------------------------- ! Basic description statistics for normally distributed ! data. Calculates either sample or population statistics. ! Sets std_dev to -1 if error condition is detected. !--------------------------------------------------------} Procedure NormalStats(a:pVec; n:Integer; flag:Char; Var avg, std_dev: Real); Var sum_, sum_sq, variance: Real; i: Integer; Begin sum_ := Sum(n,a); sum_sq := DOT_PRODUCT(n,a,a); if (flag='p') or (flag='P') then variance := (sum_sq-Sqr(sum_)/(1.0*n))/(1.0*n) else if (flag='s') or (flag='S') then variance := (sum_sq-Sqr(sum_)/(1.0*(n-1)))/(1.0*(n-1)) else begin writeln(' From NormalStats: Flag Error, <P> assumed.'); variance := (sum_sq-Sqr(sum_)/(1.0*n))/(1.0*n) end; If variance < 0.0 Then {an error exists} begin writeln(' From NormalStats: negative variance ', variance); std_dev := -1.0 end Else std_dev := SQRT(variance); avg := sum_/n End; {NormalStats} {---------------------------------------------------------- ! For data to be represented by y=ax+b, calculates linear ! regression coefficients, sample standard error of y on x, ! and sample correlation coefficients. Sets r=0 if an error ! exists. If the intercept coefficient a is set to 0 on ! input, the regression is forced through (0,0). !---------------------------------------------------------} Procedure LinearReg(x,y:pVec; n:Integer; flag:Char; Var a,b,s_yx,r: Real); Var avg, std_dev: Real; sum_x,sum_y,sum_xy,sum_xx,sum_yy,temp: Real; Begin sum_x := SUM(n,x); sum_y := SUM(n,y); sum_xy := DOT_PRODUCT(n,x,y); sum_xx := DOT_PRODUCT(n,x,x); sum_yy := DOT_PRODUCT(n,y,y); If a <> 0.0 Then {calculate full expression} begin temp := n*sum_xx - Sqr(sum_x); a := (sum_y*sum_xx - sum_x*sum_xy)/temp; b := (n*sum_xy - sum_x*sum_y)/temp; s_yx := SQRT((sum_yy - a*sum_y - b*sum_xy)/n) end Else {just calculate slope} begin b := sum_y/sum_x; s_yx := SQRT((sum_yy - 2.0*b*sum_xy + b*b*sum_xx)/n) end; if (flag='s') or (flag='S') then s_yx := s_yx * SQRT((1.0*n)/(1.0*(n-2))); { Use NormalStats to get standard deviation of y } NormalStats(y,n,flag,avg,std_dev); If std_dev > 0.0 Then begin temp := 1.0 - Sqr(s_yx/std_dev); If temp > 0.0 Then r := SQRT(temp) Else {an error exists} begin r := 0.0; writeln(' From LinearReg: error in temp ', temp) end end Else {an error exists} r := 0.0 End; {LinearReg} {----------------------------------------------------------- ! Generates an array of normal random numbers from pairs of ! uniform random numbers in range [0,1]. !----------------------------------------------------------} Procedure NormalArray(a:pVec; n:Integer); Var i: Integer; u1,u2: Real; Begin {fills array with uniform random} For i:=1 to n do a^[i]:=Random; i:=1; Repeat u1 := a^[i]; u2 := a^[i+1]; If u1=0.0 Then u1 := 1e-12; {u must not be zero} If u2=0.0 Then u2 := 1e-12; a^[i] := SQRT(-2.0*Ln(u1))*COS(2.0*pi*u2); a^[i+1] := SQRT(-2.0*Ln(u2))*SIN(2.0*pi*u2); Inc(i,2); Until i>=n; If (n MOD 2) <> 0 Then {there is one extra element} begin If a^[n] = 0.0 Then a^[n] := 1e-12; a^[n] := SQRT(-2.0*Ln(a^[n]))*SIN(2.0*pi*a^[n]) end End; {NormalArray} End. {Unit Stats end of file Stats.pas}
unit frxMarkEditor; interface uses frxDsgnIntf, frxMarkDateTime, frxMarkItem, frxMarkNoItem, frxMarkOptionItem; type TmrxCellItemProperty = class(TfrxStringProperty) public function GetAttributes: TfrxPropertyAttributes; override; procedure GetValues; override; end; implementation { TmrxCellItemProperty } function TmrxCellItemProperty.GetAttributes: TfrxPropertyAttributes; begin Result := [paValueList, paMultiSelect]; end; procedure TmrxCellItemProperty.GetValues; begin inherited; Values.Clear; Values.Add('A:B:C:D:E'); Values.Add('A:B:C:D:E:F:G:H:I:J:K:L:M:N:O:P:Q:R:S:T:U:V:W:X:Y:Z'); Values.Add('a:b:c:d:e:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z'); Values.Add('0:1:2:3:4:5:6:7:8:9'); Values.Add('A:B:C:D:E:F:G:H:I:J:K:L:M:N:O:P:Q:R:S:T:U:V:W:X:Y:Z:0:1:2:3:4:5:6:7:8:9'); Values.Add('a:b:c:d:e:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z:0:1:2:3:4:5:6:7:8:9'); Values.Add('0:1:2:3:4:5:6:7:8:9:A:B:C:D:E:F:G:H:I:J:K:L:M:N:O:P:Q:R:S:T:U:V:W:X:Y:Z'); Values.Add('0:1:2:3:4:5:6:7:8:9:a:b:c:d:e:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z'); end; initialization frxPropertyEditors.Register(TypeInfo(String), TfrxMarkItem, 'CellItems', TmrxCellItemProperty); frxPropertyEditors.Register(TypeInfo(String), TfrxMarkNoItem, 'CellItems', TmrxCellItemProperty); end.
{ <wayland_xml.pas> Copyright (C) <2018> <Andrew Haines> <andrewd207@aol.com> This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA. } unit wayland_xml; {$mode objfpc}{$H+} interface uses Classes, SysUtils, XMLRead, DOM, contnrs, TypInfo; type TBaseNode = class; TForEachHandler = procedure(Element: TBaseNode; AData: Pointer) of object; { TBaseNode } TBaseNodeClass = class of TBaseNode; TBaseNode = class protected class var Map: TStringList; class constructor Create; class destructor Destroy; class procedure RegisterElement(AName: String; AClass: TBaseNodeClass); class function FindClass(AName: String): TBaseNodeClass; private FNode: TDomNode; FElementNumber: Integer; FAttrs: TStringList; function GetDescription: String; // most have this function GetName: String; procedure SetDescription(AValue: String); procedure SetName(AValue: String); protected function GetAttr(AAttrName: String): String; function DoForEach(AElementName: String; AHandler: TForEachHandler; AUserData: Pointer): Integer; public constructor Create(ANode: TDOMNode); virtual; destructor Destroy; override; procedure Assign(From: TBaseNode); virtual; function ElementIndex: Integer; // with this name! not the index in the parent!. published property Name: String read GetName write SetName; property Description: String read GetDescription write SetDescription; end; { TProtocol } TProtocol = class(TBaseNode) private FXML: TXMLDocument; FInterfaceIndex: Integer; public constructor Create(AProtocol: TStream; AFreeStream: Boolean); destructor Destroy; override; procedure ForEachInterface(AHandler: TForEachHandler; AUserData: Pointer); end; { TInterface } TInterface = class(TBaseNode) private FDestructorDefined: Boolean; FIndex: Integer; function GetHasEnums: Boolean; function GetHasEvents: Boolean; function GetHasRequests: Boolean; function GetVersion: String; procedure SetHasEvents(AValue: Boolean); procedure SetVersion(AValue: String); public function ForEachRequest(Handler: TForEachHandler; AUserData: Pointer): Integer; function ForEachEvent(Handler: TForEachHandler; AUserData: Pointer): integer; function ForEachEnum(Handler: TForEachHandler; AUserData: Pointer): Integer; property HasEvents: Boolean read GetHasEvents; property HasRequests: Boolean read GetHasRequests; property HasEnums: Boolean read GetHasEnums; property DestructorDefined: Boolean read FDestructorDefined write FDestructorDefined; property Index: Integer read FIndex write FIndex; published property Version: String read GetVersion write SetVersion; end; { TBaseWithArg } TBaseWithArg = class(TBaseNode) public function ForEachArg(AHandler: TForEachHandler; AUserData: Pointer): Integer; end; { TRequest } TRequest = class (TBaseWithArg) private function GetSince: String; function GetType: String; procedure SetSince(AValue: String); procedure SetType(AValue: String); public function GetNewIdInterface: String; published property Name; property &Type: String read GetType write SetType; property Since: String read GetSince write SetSince; end; { TEvent } TEvent = class(TBaseWithArg) private function GetSince: String; procedure SetSince(AValue: String); public function GetObjectIdInterface: String; published property Name; property Since: String read GetSince write SetSince; end; { TEnum } TEnum = class(TBaseNode) private function GetBitfield: Boolean; function GetSince: String; procedure SetBitfield(AValue: Boolean); procedure SetSince(AValue: String); public function ForEachEntry(AHandler: TForEachHandler; AUserData: Pointer): Integer; published property Name; property Since: String read GetSince write SetSince; property Bitfield: Boolean read GetBitfield write SetBitfield; end; { TEntry } TEntry = class(TBaseNode) private function GetSince: String; function GetSummary: String; function GetValue: String; procedure SetSince(AValue: String); procedure SetSummary(AValue: String); procedure SetValue(AValue: String); published property Name; property Value: String read GetValue write SetValue; property Summary: String read GetSummary write SetSummary; property Since: String read GetSince write SetSince; end; { TArg } TArg = class(TBaseNode) private FNeedsWrapper: Boolean; function GetAllowNull: String; function GetEnum: String; function GetInterface: String; function GetSummary: String; function GetType: String; procedure SetAllowNull(AValue: String); procedure SetEnum(AValue: String); procedure SetInterface(AValue: String); procedure SetSummary(AValue: String); procedure SetType(AValue: String); public property NeedsWrapper: Boolean read FNeedsWrapper write FNeedsWrapper; // used and set by binding creator published property Name; property &Type: String read GetType write SetType; property Summary: String read GetSummary write SetSummary; property &Interface: String read GetInterface write SetInterface; property AllowNull: String read GetAllowNull write SetAllowNull; property Enum: String read GetEnum write SetEnum; end; implementation { TArg } function TArg.GetAllowNull: String; begin Result := GetAttr('allow-null'); end; function TArg.GetEnum: String; begin Result := GetAttr('enum'); end; function TArg.GetInterface: String; begin Result := GetAttr('interface'); end; function TArg.GetSummary: String; begin Result := GetAttr('summary'); end; function TArg.GetType: String; begin Result := GetAttr('type'); end; procedure TArg.SetAllowNull(AValue: String); begin FAttrs.Values['allow-null'] := AValue; end; procedure TArg.SetEnum(AValue: String); begin FAttrs.Values['enum'] := AValue; end; procedure TArg.SetInterface(AValue: String); begin FAttrs.Values['interface'] := AValue; end; procedure TArg.SetSummary(AValue: String); begin FAttrs.Values['summary'] := AValue; end; procedure TArg.SetType(AValue: String); begin FAttrs.Values['type'] := AValue; end; { TEntry } function TEntry.GetSince: String; begin Result := GetAttr('since'); end; function TEntry.GetSummary: String; begin Result := GetAttr('summary'); end; function TEntry.GetValue: String; begin Result := GetAttr('value'); end; procedure TEntry.SetSince(AValue: String); begin FAttrs.Values['since'] := AValue; end; procedure TEntry.SetSummary(AValue: String); begin FAttrs.Values['summary'] := AValue; end; procedure TEntry.SetValue(AValue: String); begin FAttrs.Values['value'] := AValue; end; { TEnum } function TEnum.GetBitfield: Boolean; begin Result := GetAttr('bitfield') = 'true'; end; function TEnum.GetSince: String; begin end; procedure TEnum.SetBitfield(AValue: Boolean); begin FAttrs.Values['bitfield'] := BoolToStr(AValue); end; procedure TEnum.SetSince(AValue: String); begin FAttrs.Values['since'] := AValue; end; function TEnum.ForEachEntry(AHandler: TForEachHandler; AUserData: Pointer): Integer; begin Result := DoForEach('entry', AHandler, AUserData); end; { TEvent } function TEvent.GetSince: String; begin Result := GetAttr('since'); end; procedure TEvent.SetSince(AValue: String); begin FAttrs.Values['since'] := AValue; end; function TEvent.GetObjectIdInterface: String; var lNode: TDOMNode; begin Result:= ''; lNode:= FNode.FirstChild; while Assigned(lNode) do begin if (lNode.NodeName = 'arg') and (TDomElement(lNode).GetAttribute('type') = 'object') //and (TDomElement(lNode).GetAttribute('name') = 'id') then Exit(TDomElement(lNode).GetAttribute('interface')); lNode := lNode.NextSibling; end; end; { TBaseWithArg } function TBaseWithArg.ForEachArg(AHandler: TForEachHandler; AUserData: Pointer): Integer; begin Result := DoForEach('arg', AHandler, AUserData); end; { TRequest } function TRequest.GetType: String; begin Result := GetAttr('type'); end; procedure TRequest.SetSince(AValue: String); begin FAttrs.Values['since'] := AValue; end; procedure TRequest.SetType(AValue: String); begin FAttrs.Values['type'] := AValue; end; function TRequest.GetNewIdInterface: String; var lNode: TDOMNode; lInterfaceName: DOMString; begin Result:= ''; lNode:= FNode.FirstChild; while Assigned(lNode) do begin if (lNode.NodeName = 'arg') then begin lInterfaceName := TDomElement(lNode).GetAttribute('interface'); if lInterfaceName <> '' then Exit(lInterfaceName); end; lNode := lNode.NextSibling; end; end; function TRequest.GetSince: String; begin Result := GetAttr('since'); end; { TInterface } function TInterface.GetVersion: String; begin Result := GetAttr('version'); end; procedure TInterface.SetHasEvents(AValue: Boolean); begin end; procedure TInterface.SetVersion(AValue: String); begin FAttrs.Values['version'] := AValue; end; function TInterface.GetHasEnums: Boolean; begin Result := FNode.FindNode('enum') <> nil; end; function TInterface.GetHasEvents: Boolean; begin Result := FNode.FindNode('event') <> nil; end; function TInterface.GetHasRequests: Boolean; begin Result := FNode.FindNode('request') <> nil; end; function TInterface.ForEachRequest(Handler: TForEachHandler; AUserData: Pointer): Integer; begin Result := DoForEach('request', Handler, AUserData); end; function TInterface.ForEachEvent(Handler: TForEachHandler; AUserData: Pointer): integer; begin Result := DoForEach('event', Handler, AUserData); end; function TInterface.ForEachEnum(Handler: TForEachHandler; AUserData: Pointer): Integer; begin Result := DoForEach('enum', Handler, AUserData); end; { TBaseNode } class constructor TBaseNode.Create; begin Map := TStringList.Create; end; class destructor TBaseNode.Destroy; begin Map.Free; end; class procedure TBaseNode.RegisterElement(AName: String; AClass: TBaseNodeClass); begin Map.AddObject(AName, TObject(AClass)); end; class function TBaseNode.FindClass(AName: String): TBaseNodeClass; var i: Integer; begin Result := nil; i := Map.IndexOf(AName); if i = -1 then Exit; Result := TBaseNodeClass(Map.Objects[i]); end; function TBaseNode.GetName: String; begin Result := GetAttr('name'); end; procedure TBaseNode.SetDescription(AValue: String); begin FAttrs.Values['description'] := AValue; end; procedure TBaseNode.SetName(AValue: String); begin FAttrs.Values['name'] := AValue; end; function TBaseNode.GetDescription: String; var lDesc: TDOMNode; begin Result := ''; lDesc := FNode.FindNode('description'); if Assigned(lDesc) then Result := lDesc.TextContent; end; function TBaseNode.GetAttr(AAttrName: String): String; begin Result := FAttrs.Values[AAttrName]; if (Result = '') and Assigned(FNode) then begin Result := TDOMElement(FNode).GetAttribute(AAttrName); FAttrs.Values[AAttrName] := Result; end; end; function TBaseNode.DoForEach(AElementName: String; AHandler: TForEachHandler; AUserData: Pointer): Integer; var lChild: TDOMNode; lNode: TBaseNode; lSameIndex: Integer; begin Result := 0; lSameIndex := 0; lChild := FNode.FirstChild; while lChild <> nil do begin if lChild.NodeName = AElementName then begin Inc(Result); try lNode := FindClass(AElementName).Create(lChild); if lNode.InheritsFrom(TInterface) then TInterface(lNode).Index:=Result-1; lNode.FElementNumber := lSameIndex; AHandler(lNode, AUserData); finally lNode.Free; end; Inc(lSameIndex); end; lChild := lChild.NextSibling; end; end; constructor TBaseNode.Create(ANode: TDOMNode); begin FNode := ANode; FAttrs := TStringList.Create; end; destructor TBaseNode.Destroy; begin FAttrs.Free; inherited Destroy; end; procedure TBaseNode.Assign(From: TBaseNode); var lTypeInfo: PTypeInfo; lList: PPropList; lPropCount, i: Integer; lVal: Variant; begin lTypeInfo := PTypeInfo(TypeInfo(Self)); lPropCount := GetPropList(Self, lList); for i := 0 to lPropCount-1 do begin lVal := GetPropValue(From, lList^[i]); SetPropValue(Self, lList^[i], lVal); end; end; function TBaseNode.ElementIndex: Integer; begin Result := FElementNumber; end; { TProtocol } constructor TProtocol.Create(AProtocol: TStream; AFreeStream: Boolean); begin ReadXMLFile(FXML, AProtocol); if AFreeStream then FreeAndNil(AProtocol); FNode := FXML.DocumentElement; end; destructor TProtocol.Destroy; begin inherited Destroy; FXML.Free; end; procedure TProtocol.ForEachInterface(AHandler: TForEachHandler; AUserData: Pointer); begin DoForEach('interface', AHandler, AUserData); end; initialization TBaseNode.RegisterElement('protocol', TProtocol); TBaseNode.RegisterElement('interface', TInterface); TBaseNode.RegisterElement('request', TRequest); TBaseNode.RegisterElement('event', TEvent); TBaseNode.RegisterElement('enum', TEnum); TBaseNode.RegisterElement('entry', TEntry); TBaseNode.RegisterElement('arg', TArg); end.
unit vcmBaseOperationsCollection; {* Коллекция операций } // Модуль: "w:\common\components\gui\Garant\VCM\implementation\Components\vcmBaseOperationsCollection.pas" // Стереотип: "SimpleClass" // Элемент модели: "TvcmBaseOperationsCollection" MUID: (55D30E6601A8) {$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc} interface {$If NOT Defined(NoVCM)} uses l3IntfUses , vcmBaseCollection , Classes , vcmExternalInterfaces , vcmUserControls , vcmInterfaces , vcmOperationDefList , vcmBase ; type TvcmBaseOperationsCollection = class(TvcmBaseCollection) {* Коллекция операций } protected function GetAttrCount: Integer; override; function GetAttr(Index: Integer): String; override; function GetItemAttr(Index: Integer; ItemIndex: Integer): String; override; public function NeedToBeStored: Boolean; procedure Operation(aControl: TComponent; const aTarget: IUnknown; anOperationID: TvcmControlID; aMode: TvcmOperationMode; const aParams: IvcmParams); {* выполняет операцию сущности } procedure GetOperations(anOperations: TvcmOperationDefList); {* возвращает список описателей операций } procedure RegisterInRep; procedure PublishOp(aControl: TComponent; const anOperation: TvcmString; anExecute: TvcmControlExecuteEvent; aTest: TvcmControlTestEvent; aGetState: TvcmControlGetStateEvent); {* опубликовать операцию } procedure PublishOpWithResult(aControl: TComponent; const anOperation: TvcmString; anExecute: TvcmExecuteEvent; aTest: TvcmControlTestEvent; aGetState: TvcmControlGetStateEvent); {* опубликовать операцию } procedure UnlinkControl(aControl: TComponent); {* отвязать контрол } class function GetItemClass: TCollectionItemClass; override; end;//TvcmBaseOperationsCollection {$IfEnd} // NOT Defined(NoVCM) implementation {$If NOT Defined(NoVCM)} uses l3ImplUses , TypInfo , SysUtils , vcmBaseOperationsCollectionItem , vcmOperationsCollectionItem , vcmModule {$If NOT Defined(NoVCL)} , Menus {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *55D30E6601A8impl_uses* //#UC END# *55D30E6601A8impl_uses* ; function TvcmBaseOperationsCollection.NeedToBeStored: Boolean; //#UC START# *56116D4D02C6_55D30E6601A8_var* var l_Index: Integer; //#UC END# *56116D4D02C6_55D30E6601A8_var* begin //#UC START# *56116D4D02C6_55D30E6601A8_impl* Result := False; for l_Index := 0 to Pred(Count) do with TvcmBaseOperationsCollectionItem(Items[l_Index]) do if not (Handled([vcm_htControl]) and not Handled([vcm_htGlobal, vcm_htContext])) or SomePropStored then begin Result := True; Break; end;//..HandledOnlyByControl.. //#UC END# *56116D4D02C6_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.NeedToBeStored procedure TvcmBaseOperationsCollection.Operation(aControl: TComponent; const aTarget: IUnknown; anOperationID: TvcmControlID; aMode: TvcmOperationMode; const aParams: IvcmParams); {* выполняет операцию сущности } //#UC START# *56116D7B0216_55D30E6601A8_var* var l_Item: TvcmBaseOperationsCollectionItem; //#UC END# *56116D7B0216_55D30E6601A8_var* begin //#UC START# *56116D7B0216_55D30E6601A8_impl* l_Item := TvcmBaseOperationsCollectionItem(FindItemByID(anOperationID)); if (l_Item <> nil) then l_Item.Operation(aControl, aTarget, aMode, aParams, False); //#UC END# *56116D7B0216_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.Operation procedure TvcmBaseOperationsCollection.GetOperations(anOperations: TvcmOperationDefList); {* возвращает список описателей операций } //#UC START# *56116DA502E0_55D30E6601A8_var* var l_Index: Integer; //#UC END# *56116DA502E0_55D30E6601A8_var* begin //#UC START# *56116DA502E0_55D30E6601A8_impl* if (anOperations <> nil) then begin for l_Index := 0 to Pred(Count) do anOperations.Add(TvcmBaseOperationsCollectionItem(Items[l_Index]).OperationDef); end;//anOperations <> nil //#UC END# *56116DA502E0_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.GetOperations procedure TvcmBaseOperationsCollection.RegisterInRep; //#UC START# *56116DBA001A_55D30E6601A8_var* var l_Index: Integer; l_Item: TvcmBaseOperationsCollectionItem; //#UC END# *56116DBA001A_55D30E6601A8_var* begin //#UC START# *56116DBA001A_55D30E6601A8_impl* for l_Index := 0 to Pred(Count) do begin l_Item := TvcmBaseOperationsCollectionItem(Items[l_Index]); if (l_Item is TvcmOperationsCollectionItem) then TvcmOperationsCollectionItem(l_Item).Register; end;//for l_Index //#UC END# *56116DBA001A_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.RegisterInRep procedure TvcmBaseOperationsCollection.PublishOp(aControl: TComponent; const anOperation: TvcmString; anExecute: TvcmControlExecuteEvent; aTest: TvcmControlTestEvent; aGetState: TvcmControlGetStateEvent); {* опубликовать операцию } //#UC START# *56116DD0036F_55D30E6601A8_var* var l_Item: TvcmBaseOperationsCollectionItem; //#UC END# *56116DD0036F_55D30E6601A8_var* begin //#UC START# *56116DD0036F_55D30E6601A8_impl* l_Item := FindItemByName(anOperation) as TvcmBaseOperationsCollectionItem; if (l_Item = nil) then begin l_Item := Add as TvcmBaseOperationsCollectionItem; l_Item.Name := anOperation; l_Item.Options := [vcm_ooShowInContextMenu]; // - по-умолчанию показываем операции только в контекстном меню if (aControl is TvcmModule) then l_Item.Options := l_Item.Options + [vcm_ooShowInMainToolbar]; end;//l_Item = nil l_Item.PublishOp(aControl, anExecute, aTest, aGetState); //#UC END# *56116DD0036F_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.PublishOp procedure TvcmBaseOperationsCollection.PublishOpWithResult(aControl: TComponent; const anOperation: TvcmString; anExecute: TvcmExecuteEvent; aTest: TvcmControlTestEvent; aGetState: TvcmControlGetStateEvent); {* опубликовать операцию } //#UC START# *56116E0A026F_55D30E6601A8_var* var l_Item: TvcmBaseOperationsCollectionItem; //#UC END# *56116E0A026F_55D30E6601A8_var* begin //#UC START# *56116E0A026F_55D30E6601A8_impl* l_Item := FindItemByName(anOperation) as TvcmBaseOperationsCollectionItem; if (l_Item = nil) then begin l_Item := Add as TvcmBaseOperationsCollectionItem; l_Item.Name := anOperation; l_Item.Options := [vcm_ooShowInContextMenu]; // - по-умолчанию показываем операции только в контекстном меню end;//l_Item = nil l_Item.PublishOp(aControl, anExecute, aTest, aGetState); //#UC END# *56116E0A026F_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.PublishOpWithResult procedure TvcmBaseOperationsCollection.UnlinkControl(aControl: TComponent); {* отвязать контрол } //#UC START# *56116E2E0246_55D30E6601A8_var* var l_Index: Integer; //#UC END# *56116E2E0246_55D30E6601A8_var* begin //#UC START# *56116E2E0246_55D30E6601A8_impl* for l_Index := 0 to Pred(Count) do TvcmBaseOperationsCollectionItem(Items[l_Index]).UnlinkControl(aControl); //#UC END# *56116E2E0246_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.UnlinkControl class function TvcmBaseOperationsCollection.GetItemClass: TCollectionItemClass; //#UC START# *5607EE71032D_55D30E6601A8_var* //#UC END# *5607EE71032D_55D30E6601A8_var* begin //#UC START# *5607EE71032D_55D30E6601A8_impl* Result := TvcmBaseOperationsCollectionItem; //#UC END# *5607EE71032D_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.GetItemClass function TvcmBaseOperationsCollection.GetAttrCount: Integer; //#UC START# *560A9DA80335_55D30E6601A8_var* //#UC END# *560A9DA80335_55D30E6601A8_var* begin //#UC START# *560A9DA80335_55D30E6601A8_impl* Result := inherited GetAttrCount + 4; //#UC END# *560A9DA80335_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.GetAttrCount function TvcmBaseOperationsCollection.GetAttr(Index: Integer): String; //#UC START# *560A9DCD009D_55D30E6601A8_var* var l_C: Integer; //#UC END# *560A9DCD009D_55D30E6601A8_var* begin //#UC START# *560A9DCD009D_55D30E6601A8_impl* l_C := inherited GetAttrCount; if (Index >= l_C) then begin case Index - l_C of 0 : Result := 'Caption'; 1 : Result := 'Type'; 2 : Result := 'Name'; 3 : Result := 'ShortCut'; end;//case Index - l_C end//Index >= l_C else Result := inherited GetAttr(Index); //#UC END# *560A9DCD009D_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.GetAttr function TvcmBaseOperationsCollection.GetItemAttr(Index: Integer; ItemIndex: Integer): String; //#UC START# *560A9DEB0155_55D30E6601A8_var* var l_C: Integer; //#UC END# *560A9DEB0155_55D30E6601A8_var* begin //#UC START# *560A9DEB0155_55D30E6601A8_impl* l_C := inherited GetAttrCount; if (Index > l_C) then begin case Index - l_C of 1 : Result := GetEnumName(TypeInfo(TvcmOperationType), Ord(TvcmBaseOperationsCollectionItem(Items[ItemIndex]).OperationType)); 2 : Result := TvcmBaseOperationsCollectionItem(Items[ItemIndex]).Name; 3 : Result := ShortCutToText(TvcmBaseOperationsCollectionItem(Items[ItemIndex]).ShortCut); end;//case Index - l_C end//Index > l_C else Result := inherited GetItemAttr(Index, ItemIndex); //#UC END# *560A9DEB0155_55D30E6601A8_impl* end;//TvcmBaseOperationsCollection.GetItemAttr initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TvcmBaseOperationsCollection); {* Регистрация TvcmBaseOperationsCollection } {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // NOT Defined(NoVCM) end.
// islip - IneQuation's Simple LOLCODE Interpreter in Pascal // Written by Leszek "IneQuation" Godlewski <leszgod081@student.polsl.pl> // C-like type declarations for convenience unit typedefs; interface type int = integer; // short-hand for integer float = single; // 32-bit IEEE float pfloat = ^float; //double = double; // redundancy size_t = cardinal; // basically an unsigned int ushort = word; // unsigned short // these don't have anything to do with C, but they're here for convenience cfile = file of char; pcfile = ^cfile; pbool = ^boolean; implementation // nothing to see here, move along end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls; type TForm1 = class(TForm) Panel1: TPanel; Button1: TButton; Button2: TButton; RadioGroup1: TRadioGroup; GroupBox1: TGroupBox; TreeView1: TTreeView; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private-Deklarationen } public { Public-Deklarationen } end; var Form1: TForm1; implementation {$R *.DFM} function GetComponentName(c: TComponent): string; begin Result := c.Name; if Result = '' then begin Result := '0x' + Format('%.8x',[Integer(c)]); end; end; procedure BuildComponentTree(c:TComponent; tn:TTreeNodes); procedure AddComponent(n: TTreeNode; nodes:TTreeNodes;c: TComponent); var n1: TTreeNode; i: Integer; begin n1 := nodes.AddChildObject(n,GetComponentName(c)+': '+c.ClassName,Pointer(c)); for i := 0 to c.ComponentCount-1 do begin AddComponent(n1, nodes,c.Components[i]); end; end; begin AddComponent(nil, tn, c); end; procedure BuildControlTree(c: TControl; tn:TTreeNodes); procedure AddControl(n: TTreeNode; nodes:TTreeNodes;c: TControl); var n1: TTreeNode; i: Integer; begin n1 := nodes.AddChildObject(n,GetComponentName(c)+': '+c.ClassName,Pointer(c)); if c is TWinControl then begin for i := 0 to TWinControl(c).ControlCount-1 do begin AddControl(n1, nodes,TWinControl(c).Controls[i]); end; end; end; begin AddControl(nil, tn, c); end; procedure TForm1.Button1Click(Sender: TObject); begin TreeView1.Items.Clear; BuildComponentTree(Application, TreeView1.Items); TreeView1.FullExpand; end; procedure TForm1.Button2Click(Sender: TObject); begin TreeView1.Items.Clear; BuildControlTree(self, TreeView1.Items); TreeView1.FullExpand; end; end.
unit XMLEditor.Defaults; interface uses SysUtils, Forms; const APP_DIR = ''; DATA_DIR = 'Data'; TEMP_DIR = 'temp'; BCKP_DIR = 'BackupData'; function ApplicationPath: string; function DataPath: string; function TempPath: string; function BackUpPath: string; implementation function ApplicationPath: string; begin Result := ExtractFilePath(Application.ExeName) + APP_DIR; end; function DataPath: string; begin Result := ApplicationPath + DATA_DIR; end; function TempPath: string; begin Result := ApplicationPath + TEMP_DIR; end; function BackUpPath: string; begin Result := ApplicationPath + BCKP_DIR; end; end.
unit modELMTypes; interface type TmodELMMessageDataSource = function(var data: ansistring): integer of object; type TmodELMMessageDataDest = function(data: ansistring): integer of object; type TmodELMState = (modELMState_Idle, modELMState_awaiting_response); // normal - normal operation. // cleaner - just clean everything passed to you. Don't interpret it. type TmodELMInterfaceOperationMode = (modELMOpMode_normal, modELMOpMode_cleaner); // Normal - normal addressing : [ident] [pci] [data] // extended - extended addressing [ident] [addr] [pci] [data] type TmodELMInterfaceAddressingMode = (modELMAddrMode_Normal, modELMAddrMode_Extended); (* modELMCANFlowControlMode_ELM_provided (0) ~~~~~~~~~~~~~~~~~ ELM provides ID and Data bits User provides nothing modELMCANFlowControlMode_User_Provided (1) ~~~~~~~~~~~~~~~~~ user provides both, ELM nothing modELMCANFlowControlMode_Shared (2) ~~~~~~~~~~~~~~~~~ ELM - id bits user - data bytes *) type TmodELMInterfaceCANFlowControlMode = (modELMCANFlowControlMode_ELM_provided, modELMCANFlowControlMode_User_Provided, modELMCANFlowControlMode_Shared); (* Single type = 3 (0 = Clear To Send, 1 = Wait, 2 = Overflow/abort) 0 = remaining "frames" to be sent without flow control or delay <= 127, separation time in milliseconds. Single type = 3 (0 = Clear To Send, 1 = Wait, 2 = Overflow/abort) > 0 send number of "frames" before waiting for the next flow control frame 0xF1 to 0xF9, 100 to 900 microseconds. *) type TmodELMInterfaceCANFlowControlDatabytes = record // flow controll message can have between one and 5 data bytes, inclusive byte_count: byte; bytes: array [0 .. 4] of byte; end; type TmodELMInterfaceProtocolBOptions = record flags: byte; baudrate_divisor: byte; end; // (* // modELM_msg_result_success // - Message parsing was a success // *) // type // TmodELMMessageHandleResult = (modELM_msg_result_success, modELM_msg_result_ignore, modELM_msg_result_error); // things that have been requested, but we have not recieved conformation for yet. type TmodELMInterfaceRequestedParameters = record at_cea: byte; at_fc_sh: cardinal; at_fc_sd: TmodELMInterfaceCANFlowControlDatabytes; at_pb: TmodELMInterfaceProtocolBOptions; at_cra: cardinal; at_sh: cardinal; at_fc_sm: TmodELMInterfaceCANFlowControlMode; at_cm: cardinal; at_cf: cardinal; end; type TmodELMInterfaceParameterState = record // header setting can_header: cardinal; // can filter bits can_filter: cardinal; // can mask bits can_mask: cardinal; // CAN state can_addressing_mode: TmodELMInterfaceAddressingMode; // can extended addressing address can_ext_addressing_address: byte; // can flow control mode can_flow_control_mode: TmodELMInterfaceCANFlowControlMode; // can flow control header can_flow_control_header: cardinal; // can flow control data bytes can_flow_control_data_bytes: TmodELMInterfaceCANFlowControlDatabytes; // protocol B options protocol_b_options: TmodELMInterfaceProtocolBOptions; // can recieve address filter can_recv_address_filter: cardinal; end; implementation end.
unit ListInterfaces; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Business" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Business/ListInterfaces.pas" // Начат: 07.09.2009 14:34 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<Interfaces::Category>> F1 Core::Common::Business::ListInterfaces // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} type TbsLinkType = ( {* Тип ссылки на данные для сборки. Операция модуля использует этот тип для определения какую сборку необходимо создать } ltDocument // Открыть сборку документ , ltList // Открыть сборку список );//TbsLinkType {$IfEnd} //not Admin AND not Monitorings implementation end.
unit uString; interface function somenteNumeros(texto: string): string; implementation function somenteNumeros(texto: string): string; var I: integer; S: string; Virgula: Boolean; // Pra verificar se ja Possui virgula begin S := ''; Virgula := False; for I := 1 To Length(texto) Do begin if (texto[I] in ['0' .. '9']) or ((texto[I] in [',']) and (Virgula <> True)) then begin if (texto[I] in [',']) then Virgula := True; S := S + Copy(texto, I, 1); end; end; Result := S; end; end.
unit ColoredGauge; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TColorGauge = class(TCustomControl) private fPosition : integer; fSpacing : integer; fYellowPerc : integer; fRedPerc : integer; //fBuffer : TBitmap; protected procedure Paint; override; private procedure SetPosition ( Value : integer ); procedure SetSpacing ( Value : integer ); procedure SetYellowPerc( Value : integer ); procedure SetRedPerc ( Value : integer ); published property Position : integer read fPosition write SetPosition; property Spacing : integer read fSpacing write SetSpacing; property YellowPerc : integer read fYellowPerc write SetYellowPerc; property RedPerc : integer read fRedPerc write SetRedPerc; private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; end; procedure Register; implementation procedure TColorGauge.Paint; var i : integer; sp : integer; col : TColor; begin sp := 0; Canvas.Pen.Style := psClear; Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := clBlack; col := clBlack; for i := 0 to pred(Width) do begin if sp > 0 then begin dec( sp ); if sp = 0 then Canvas.Brush.Color := col; end; Canvas.Rectangle( i, 0, i + 2, Height + 1); if i mod fSpacing = 0 then begin if (100*i) div Width < fYellowPerc then if (100*i) div Width < Position then col := clLime else col := clGreen else if (100*i) div Width < fRedPerc then if (100*i) div Width < Position then col := clYellow else col := clOlive else if (100*i) div Width < Position then col := clRed else col := clMaroon; sp := 4; Canvas.Brush.Color := clBlack; end; end; end; procedure TColorGauge.SetPosition( Value : integer ); begin if fPosition <> Value then begin fPosition := Value; Invalidate; end; end; procedure TColorGauge.SetSpacing( Value : integer ); begin fSpacing := Value; Invalidate; end; procedure TColorGauge.SetYellowPerc( Value : integer ); begin fYellowPerc := Value; Invalidate; end; procedure TColorGauge.SetRedPerc( Value : integer ); begin fRedPerc := Value; Invalidate; end; procedure TColorGauge.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure Register; begin RegisterComponents('Five', [TColorGauge]); end; end.
unit StockDetailDataAccess; interface uses define_DealItem, define_datasrc, define_datetime, BaseDataSet, QuickList_DetailData, define_stock_quotes; type TStockDetailDataAccess = class(TBaseDataSetAccess) protected fStockItem: PRT_DealItem; fDetailDealData: TDetailDataList; fDataSource: TDealDataSource; fFirstDealDate: Word; fLastDealDate: Word; function GetFirstDealDate: Word; procedure SetFirstDealDate(const Value: Word); function GetLastDealDate: Word; procedure SetLastDealDate(const Value: Word); procedure SetStockItem(AStockItem: PRT_DealItem); function GetRecordItem(AIndex: integer): Pointer; override; function GetRecordCount: Integer; override; public constructor Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource); reintroduce; destructor Destroy; override; function FindDetail(AStockDateTime: TDateTimeStock): PRT_Quote_Detail; function CheckOutDetail(AStockDateTime: TDateTimeStock): PRT_Quote_Detail; function NewDetail(AStockDateTime: TDateTimeStock): PRT_Quote_Detail; procedure Sort; override; procedure Clear; override; class function DataTypeDefine: integer; override; property FirstDealDate: Word read GetFirstDealDate write SetFirstDealDate; property LastDealDate: Word read GetLastDealDate write SetLastDealDate; property StockItem: PRT_DealItem read fStockItem write SetStockItem; property DataSource: TDealDataSource read fDataSource write fDataSource; end; implementation uses SysUtils, define_dealstore_file, QuickSortList; { TStockDetailDataAccess } constructor TStockDetailDataAccess.Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource); begin inherited Create(AStockItem.DBType, GetDealDataSourceCode(ADataSrc)); fStockItem := AStockItem; fDetailDealData := TDetailDataList.Create; fDetailDealData.Duplicates := lstDupAccept; fDataSource := ADataSrc; end; destructor TStockDetailDataAccess.Destroy; begin Clear; FreeAndNil(fDetailDealData); inherited; end; class function TStockDetailDataAccess.DataTypeDefine: integer; begin Result := DataType_DetailData; end; procedure TStockDetailDataAccess.SetStockItem(AStockItem: PRT_DealItem); begin if nil <> AStockItem then begin if fStockItem <> AStockItem then begin Self.Clear; end; end; fStockItem := AStockItem; if nil <> fStockItem then begin end; end; function TStockDetailDataAccess.GetFirstDealDate: Word; begin Result := fFirstDealDate; end; procedure TStockDetailDataAccess.SetFirstDealDate(const Value: Word); begin fFirstDealDate := Value; end; function TStockDetailDataAccess.GetLastDealDate: Word; begin Result := fLastDealDate; end; procedure TStockDetailDataAccess.SetLastDealDate(const Value: Word); begin fLastDealDate := Value; end; function TStockDetailDataAccess.GetRecordCount: Integer; begin Result := fDetailDealData.Count; end; function TStockDetailDataAccess.GetRecordItem(AIndex: integer): Pointer; begin Result := nil; if AIndex < fDetailDealData.Count then begin Result := fDetailDealData.DetailData[AIndex]; end else begin if AIndex > 0 then begin end; end; end; procedure TStockDetailDataAccess.Sort; begin if nil <> fDetailDealData then fDetailDealData.Sort; end; procedure TStockDetailDataAccess.Clear; var i: integer; tmpQuote: PRT_Quote_Detail; begin inherited; if nil <> fDetailDealData then begin for i := fDetailDealData.Count - 1 downto 0 do begin tmpQuote := fDetailDealData.DetailData[i]; FreeMem(tmpQuote); end; fDetailDealData.Clear; end; end; function TStockDetailDataAccess.NewDetail(AStockDateTime: TDateTimeStock): PRT_Quote_Detail; begin Result := System.New(PRT_Quote_Detail); FillChar(Result^, SizeOf(TRT_Quote_Detail), 0); Result.DealDateTime := AStockDateTime; fDetailDealData.AddDetailData(Result.DealDateTime, Result); end; function TStockDetailDataAccess.CheckOutDetail(AStockDateTime: TDateTimeStock): PRT_Quote_Detail; begin Result := FindDetail(AStockDateTime); if nil = Result then begin Result := NewDetail(AStockDateTime); end; end; function TStockDetailDataAccess.FindDetail(AStockDateTime: TDateTimeStock): PRT_Quote_Detail; var tmpPos: integer; begin Result := nil; tmpPos := fDetailDealData.IndexOf(AStockDateTime); if 0 <= tmpPos then Result := fDetailDealData.DetailData[tmpPos]; end; end.
unit FullScreenWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DDraw, ExtCtrls, SpriteImages, FullScreenWindowMgr; type TFullScreenForm = class(TForm) OpenDialog: TOpenDialog; procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } fDirectDraw : IDirectDraw4; fPrimary : IDirectDrawSurface4; fBackBuffer : IDirectDrawSurface4; fClipper : IDirectDrawClipper; fTimer : TTimer; fAnimations : TList; fFSWindowMgr : TFullScreenWindowManager; procedure InitDirectDraw; procedure ReleaseAllObjects; procedure TimerTick(Sender : TObject); public { Public declarations } procedure WindowOpened(Wnd : HWND); procedure WindowClosed(Wnd : HWND); end; var FullScreenForm: TFullScreenForm; implementation {$R *.DFM} uses LogFile, SubWindow, ImageLoaders, GifLoader, SpriteLoaders, SpriteToSurface, Animations; const cScreenWidth = 1024; cScreenHeight = 768; cScreenBpp = 32; procedure TFullScreenForm.FormCreate(Sender: TObject); const cSpriteFileNames : array [0..8] of string = ( 'C:\Work\Five\Release\Client\cache\buildingimages\mapdismine64x32x0.gif', 'C:\Work\Five\Release\Client\cache\buildingimages\mapmoabmine64x32x0.gif', 'C:\Work\Five\Release\Client\cache\buildingimages\mapmoabfarm64x32x0.gif', 'C:\Work\Five\Release\Client\cache\buildingimages\mapmoabfood64x32x0.gif', 'C:\Work\Five\Release\Client\cache\buildingimages\MapDisHiResBEmpty64x32x0.gif', 'C:\Work\Five\Release\Client\cache\buildingimages\MapDisSmallFoodProc64x32x0.gif', 'C:\Work\Five\Release\Client\cache\buildingimages\mapdistv64x32x0.gif', 'C:\Work\Five\Release\Client\cache\buildingimages\mapdisrestaurantb64x32x0.gif', 'C:\Work\Five\Release\Client\cache\buildingimages\mapdisfarm64x32x0.gif' ); var SpriteImage : TFrameImage; curx, cury : integer; i : integer; begin fAnimations := TList.Create; fFSWindowMgr := TFullScreenWindowManager.Create; curx := 0; cury := 0; for i := 0 to 8 do begin LoadFrameImageFromFile(SpriteImage, cSpriteFileNames[i]); if curx + SpriteImage.Width > cScreenWidth then begin curx := 0; inc(cury, 250); end; fAnimations.Add(TAnimation.Create(SpriteImage, curx, cury)); inc(curx, SpriteImage.Width); end; fTimer := TTimer.Create(Self); fTimer.Interval := 40; fTimer.OnTimer := TimerTick; fTimer.Enabled := true; InitDirectDraw; fFSWindowMgr.Init(Handle, fDirectDraw, fPrimary, fBackBuffer); SetBounds(0, 0, Screen.Width, Screen.Height); end; procedure TFullScreenForm.InitDirectDraw; var ddsd : TDDSurfaceDesc2; ddscaps : TDDSCAPS2; hRet : HRESULT; ddrawobj : IDirectDraw; begin // Create the main DirectDraw object hRet := DirectDrawCreate(nil, ddrawobj, nil); if hRet <> DD_OK then LogThis('DirectDrawCreate FAILED') else begin // Fetch DirectDraw4 interface hRet := ddrawobj.QueryInterface(IID_IDirectDraw4, fDirectDraw); if hRet <> DD_OK then LogThis('QueryInterface FAILED') else begin // Get exclusive mode hRet := fDirectDraw.SetCooperativeLevel(Handle, DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN); if hRet <> DD_OK then LogThis('SetCooperativeLevel FAILED') else begin // Set the video mode to 640x480x8 hRet := fDirectDraw.SetDisplayMode(cScreenWidth, cScreenHeight, cScreenBpp, 0, 0); if hRet <> DD_OK then LogThis('SetDisplayMode FAILED') else begin // Create the primary surface with 1 back buffer fillchar(ddsd, sizeof(ddsd), 0); ddsd.dwSize := sizeof(ddsd); ddsd.dwFlags := DDSD_CAPS or DDSD_BACKBUFFERCOUNT; ddsd.ddsCaps.dwCaps := DDSCAPS_PRIMARYSURFACE or DDSCAPS_FLIP or DDSCAPS_COMPLEX; ddsd.dwBackBufferCount := 1; hRet := fDirectDraw.CreateSurface(ddsd, fPrimary, nil); if hRet <> DD_OK then LogThis('CreateSurface FAILED') else begin // Get a pointer to the back buffer // Load a bitmap into the front buffer. ddscaps.dwCaps := DDSCAPS_BACKBUFFER; hRet := fPrimary.GetAttachedSurface(ddscaps, fBackBuffer); if hRet <> DD_OK then LogThis('GetAttachedSurface FAILED') end; end; end; end; end; end; procedure TFullScreenForm.ReleaseAllObjects; begin if fDirectDraw <> nil then begin fDirectDraw.RestoreDisplayMode; fDirectDraw.SetCooperativeLevel(Handle, DDSCL_NORMAL); if fPrimary <> nil then fPrimary := nil; fDirectDraw := nil; end; end; procedure TFullScreenForm.TimerTick(Sender : TObject); var hret : HRESULT; DDBltFx : TDDBltFx; success : boolean; criterror : boolean; surfacedesc : TDDSurfaceDesc2; i : integer; CurAnimation : TAnimation; begin fillchar(DDBltFx, sizeof(DDBltFx), 0); DDBltFx.dwSize := sizeof(DDBltFx); DDBltFx.dwFillColor := RGB(0, 0, 0); fBackBuffer.Blt(nil, nil, nil, DDBLT_COLORFILL or DDBLT_WAIT, @DDBltFx); fillchar(surfacedesc, sizeof(surfacedesc), 0); surfacedesc.dwSize := sizeof(surfacedesc); if fBackBuffer.Lock(nil, surfacedesc, DDLOCK_WAIT, 0) = DD_OK then begin try for i := 0 to pred(fAnimations.Count) do begin CurAnimation := TAnimation(fAnimations[i]); with CurAnimation do begin Tick; RenderSpriteToSurface(Image, Pos.X, Pos.Y, Frame, 0, Rect(Pos.X, Pos.Y, Pos.X + Image.Width, Pos.Y + Image.Height), surfacedesc, nil); end; end; finally fBackBuffer.Unlock(nil); end; if not fFSWindowMgr.IsAnyWindowShowing then begin LogThis('Flipping surface.'); success := false; criterror := false; repeat hRet := fPrimary.Flip(nil, 0); if hRet = DD_OK then success := true else begin if hRet = DDERR_SURFACELOST then begin hRet := fPrimary._Restore; if hRet <> DD_OK then criterror := true; end; if hRet <> DDERR_WASSTILLDRAWING then criterror := true; end; until success or criterror; end else begin LogThis('Updating windows. Blitting.'); fFSWindowMgr.UpdateWindows; end; end else LogThis('Lock surface failed'); end; procedure TFullScreenForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_ESCAPE: Close; VK_F1: begin SubForm.Left := 0; SubForm.Top := 0; SubForm.Parent := Self; SubForm.Show; // Create a clipper (used in IDirectDrawSurface::Blt call) if fDirectDraw.CreateClipper(0, fClipper, nil) = DD_OK then fClipper.SetHWnd(0, Handle); // Normal GDI device, so just flip to GDI so content window can be seen fDirectDraw.FlipToGDISurface; end; end; end; procedure TFullScreenForm.FormClose(Sender: TObject; var Action: TCloseAction); begin fTimer.Enabled := false; ReleaseAllObjects; end; procedure TFullScreenForm.WindowOpened(Wnd : HWND); begin fFSWindowMgr.RegisterWindow(Wnd, false, 0); end; procedure TFullScreenForm.WindowClosed(Wnd : HWND); begin fFSWindowMgr.UnregisterWindow(Wnd); end; initialization InitSprites; RegisterLoader(GetGifLoader, 0); SetLogFile('C:\Temp\' + ExtractFileName(Application.ExeName) + '.log'); finalization DoneSprites; end.
unit GX_eQuote; {$I GX_CondDefine.inc} interface uses GX_EditorExpert, GX_eSelectionEditorExpert, GX_ConfigurationInfo, Classes, StdCtrls, Controls, Forms, GX_BaseForm, Graphics; type TQuoteExpert = class(TSelectionEditorExpert) protected function GetDisplayName: string; override; class function GetName: string; override; procedure InternalSaveSettings(Settings: TGExpertsSettings); override; procedure InternalLoadSettings(Settings: TGExpertsSettings); override; function ProcessSelected(Lines: TStrings): Boolean; override; function GetNoSelectionMode: TNoSelectionMode; override; public constructor Create; override; procedure Configure; override; procedure GetHelpString(List: TStrings); override; end; TPasteQuotedExpert = class(TEditorExpert) protected function GetDisplayName: string; override; class function GetName: string; override; procedure InternalSaveSettings(Settings: TGExpertsSettings); override; procedure InternalLoadSettings(Settings: TGExpertsSettings); override; public constructor Create; override; procedure Configure; override; procedure GetHelpString(List: TStrings); override; procedure Execute(Sender: TObject); override; end; TUnquoteExpert = class(TSelectionEditorExpert) protected function GetDisplayName: string; override; class function GetName: string; override; function ProcessSelected(Lines: TStrings): Boolean; override; function GetNoSelectionMode: TNoSelectionMode; override; public constructor Create; override; procedure GetHelpString(List: TStrings); override; function HasConfigOptions: Boolean; override; end; TCopyUnquotedExpert = class(TSelectionEditorExpert) protected function GetDisplayName: string; override; class function GetName: string; override; function ProcessSelected(Lines: TStrings): Boolean; override; function GetNoSelectionMode: TNoSelectionMode; override; public constructor Create; override; procedure GetHelpString(List: TStrings); override; function HasConfigOptions: Boolean; override; end; TfmQuoteConfig = class(TfmBaseForm) gbxStyle: TGroupBox; btnOK: TButton; btnCancel: TButton; lblEndOfLine: TLabel; cbxEndOfLine: TComboBox; end; implementation {$R *.dfm} uses SysUtils, GX_OtaUtils, Dialogs, ToolsAPI, GX_eQuoteSupport, Clipbrd, GX_GenericUtils; const cDefaultEndOfLine = '''+#13#10+'; VK_SingleQuote = $DE; var EndOfLine: string = ''; procedure VerifyCompatibleFileType; var FileName: string; begin FileName := GxOtaGetCurrentSourceFile; if not IsPascalSourceFile(FileName) then raise Exception.Create('This editor expert only supports Delphi source code.'); end; procedure SaveQuoteSettings(Settings: TGExpertsSettings); begin // Do not localize any of the below items Settings.WriteString('Quote', 'EndOfLine', EndOfLine); end; procedure LoadQuoteSettings(Settings: TGExpertsSettings); begin // Do not localize any of the below items EndOfLine := Settings.ReadString('Quote', 'EndOfLine', cDefaultEndOfLine); end; function ConfigureQuote: Boolean; var Dlg: TfmQuoteConfig; begin Dlg := TfmQuoteConfig.Create(nil); try // Possible end of line choices Dlg.cbxEndOfLine.Items.Add(' '' +'); Dlg.cbxEndOfLine.Items.Add('''#13#10+'); Dlg.cbxEndOfLine.Items.Add('''+#13#10+'); Dlg.cbxEndOfLine.Items.Add(''' + #13#10 +'); Dlg.cbxEndOfLine.Items.Add(''' + sLineBreak +'); Dlg.cbxEndOfLine.Text := EndOfLine; Result := Dlg.ShowModal = mrOk; if Result then EndOfLine := Dlg.cbxEndOfLine.Text; finally FreeAndNil(Dlg); end; end; { TQuoteExpert } procedure TQuoteExpert.Configure; begin if ConfigureQuote then SaveSettings; end; constructor TQuoteExpert.Create; begin inherited; ShortCut := scCtrl + VK_SingleQuote; end; function TQuoteExpert.GetDisplayName: string; resourcestring SQuoteName = 'Quote String'; begin Result := SQuoteName; end; procedure TQuoteExpert.GetHelpString(List: TStrings); resourcestring SQuoteHelp = ' This expert quotes a selected block of single or multi-line code. ' + 'This is useful for converting external code such as HTML or SQL into Delphi string ' + 'constants. To use it, select a block of code in the IDE code editor and ' + 'activate this expert.' + sLineBreak + sLineBreak + ' The column where the selection starts determines how far any subsequent lines are indented. '+ 'You can configure this expert to use different end of line styles.'; begin List.Text := SQuoteHelp; end; class function TQuoteExpert.GetName: string; begin Result := 'Quote'; end; function TQuoteExpert.GetNoSelectionMode: TNoSelectionMode; begin Result := nsmError; end; procedure TQuoteExpert.InternalLoadSettings(Settings: TGExpertsSettings); begin inherited; LoadQuoteSettings(Settings); end; procedure TQuoteExpert.InternalSaveSettings(Settings: TGExpertsSettings); begin inherited; SaveQuoteSettings(Settings); end; function TQuoteExpert.ProcessSelected(Lines: TStrings): Boolean; var EditView: IOTAEditView; BlockStart, BlockEnd: TOTAEditPos; SelStart, SelLength: Integer; begin Assert(Assigned(Lines)); Result := False; VerifyCompatibleFileType; EditView := GxOtaGetTopMostEditView; if EditView = nil then Exit; if not GxOtaGetSelection(EditView, BlockStart, BlockEnd, SelStart, SelLength) then Exit; QuoteLines(Lines, EndOfLine, BlockStart.Col); Result := True; end; { TUnQuoteExpert } constructor TUnQuoteExpert.Create; begin inherited; ShortCut := scCtrl + scAlt + VK_SingleQuote; end; function TUnQuoteExpert.GetDisplayName: string; resourcestring SUnquoteName = 'Unquote String'; begin Result := SUnquoteName; end; procedure TUnQuoteExpert.GetHelpString(List: TStrings); resourcestring SUnquoteHelp = ' This expert unquotes a selected block of Delphi code. ' + 'This may be useful when preparing to take external code like HTML ' + 'or SQL outside of the editor and into an external application. '+ 'To use it, select a block in the IDE code editor and ' + 'activate this expert.' + sLineBreak + ' Note: The results may not be correct when activated on ' + 'complicated strings that contain string concatinations with ' + 'functions.'; begin List.Text := SUnquoteHelp; end; class function TUnQuoteExpert.GetName: string; begin Result := 'Unquote'; end; function TUnquoteExpert.GetNoSelectionMode: TNoSelectionMode; begin Result := nsmError; end; function TUnQuoteExpert.HasConfigOptions: Boolean; begin Result := False; end; function TUnQuoteExpert.ProcessSelected(Lines: TStrings): Boolean; begin VerifyCompatibleFileType; Assert(Assigned(Lines)); UnquoteLines(Lines); Result := True; end; { TCopyUnquotedExpert } constructor TCopyUnquotedExpert.Create; begin inherited; //ShortCut := scAlt + scCtrl + scShift + Ord('C'); end; function TCopyUnquotedExpert.GetDisplayName: string; resourcestring SCopyUnquotedName = 'Copy Unquoted String'; begin Result := SCopyUnquotedName; end; procedure TCopyUnquotedExpert.GetHelpString(List: TStrings); resourcestring SCopyUnquotedHelp = ' This expert unquotes a selected block of Delphi code, then ' + 'copies it to the clipboard. ' + 'This may be useful for bringing external code like HTML ' + 'or SQL outside of the editor and into an external application. ' + 'To use it, select a block in the IDE code editor and ' + 'activate this expert.' + sLineBreak + ' Note: The results may not be correct when activated on ' + 'complicated strings that contain string concatinations with ' + 'functions.'; begin List.Text := SCopyUnquotedHelp; end; class function TCopyUnquotedExpert.GetName: string; begin Result := 'CopyUnquoted'; end; function TCopyUnquotedExpert.GetNoSelectionMode: TNoSelectionMode; begin Result := nsmError; end; function TCopyUnquotedExpert.HasConfigOptions: Boolean; begin Result := False; end; function TCopyUnquotedExpert.ProcessSelected(Lines: TStrings): Boolean; var EditView: IOTAEditView; BlockStart, BlockEnd: TOTAEditPos; SelStart, SelLength: Integer; begin Assert(Assigned(Lines)); Result := False; VerifyCompatibleFileType; EditView := GxOtaGetTopMostEditView; if EditView = nil then Exit; if not GxOtaGetSelection(EditView, BlockStart, BlockEnd, SelStart, SelLength) then Exit; UnquoteLines(Lines, BlockStart.Col); Clipboard.AsText := Lines.Text; end; { TPasteQuotedExpert } procedure TPasteQuotedExpert.Configure; begin if ConfigureQuote then SaveSettings; end; constructor TPasteQuotedExpert.Create; begin inherited; //ShortCut := scAlt + scCtrl + scShift + Ord('V'); end; procedure TPasteQuotedExpert.Execute(Sender: TObject); var EditView: IOTAEditView; Lines: TStringList; begin VerifyCompatibleFileType; Lines := TStringList.Create; try EditView := GxOtaGetTopMostEditView; Assert(Assigned(EditView), 'No edit view found'); Lines.Text := Clipboard.AsText; QuoteLines(Lines, EndOfLine, EditView.CursorPos.Col); GxOtaInsertTextIntoEditor(Lines.Text); finally FreeAndNil(Lines); end; end; function TPasteQuotedExpert.GetDisplayName: string; resourcestring SPasteQuotedName = 'Paste Quoted String'; begin Result := SPasteQuotedName; end; procedure TPasteQuotedExpert.GetHelpString(List: TStrings); resourcestring SPasteQuotedHelp = ' This expert pastes clipboard text with added quotes to create valid Delphi code. ' + 'This is useful for pasting external code such as HTML and SQL into the ' + 'editor as string constants. To use it, select a block in the IDE code editor and ' + 'activate this expert.' + sLineBreak + sLineBreak + 'You can configure this expert to use different end of line styles.'; begin List.Text := SPasteQuotedHelp; end; class function TPasteQuotedExpert.GetName: string; begin Result := 'PasteQuoted'; end; procedure TPasteQuotedExpert.InternalLoadSettings(Settings: TGExpertsSettings); begin inherited; LoadQuoteSettings(Settings); end; procedure TPasteQuotedExpert.InternalSaveSettings(Settings: TGExpertsSettings); begin inherited; SaveQuoteSettings(Settings); end; initialization RegisterEditorExpert(TQuoteExpert); RegisterEditorExpert(TUnquoteExpert); RegisterEditorExpert(TCopyUnquotedExpert); RegisterEditorExpert(TPasteQuotedExpert); end.
program exampleOnSets(input, output); type nums = 0 .. 100; integers = set of nums; var w : integers; s : integer; procedure printSet(arg : integers); var i : integer; begin for i in arg do write(i, ' '); writeln(); end; procedure readSet(); var size, i, number : integer; begin write('Enter the length of the set: '); read(size); for i := 1 to size do begin read(number); w := w + [number] end; end; function summationSet(arg : integers) : integer; var i, summation : integer; begin summation := 0; for i in arg do summation := summation + i; summationSet := summation; end; procedure subsetSum(arg : integers; n : nums); label halt; var t, x : integer; v : integers; begin if (arg = []) or (n <= 0) then goto halt; t := summationSet(arg); if t < s then goto halt; if(t = s) then begin printSet(arg); goto halt end else begin for x in arg do begin v := arg - [x]; subsetSum(v, s) end; end; halt: end; begin readSet(); printSet(w); write('s: '); read(s); subsetSum(w, s) end.
unit tfwParserService; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwParserService.pas" // Стереотип: "Service" // Элемент модели: "TtfwParserService" MUID: (57726B250063) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface uses l3IntfUses , l3ProtoObject , l3StringList , tfwParserServiceFileNameToFileNameMap ; (* MtfwParserService = interface {* Контракт сервиса TtfwParserService } function MakeCompiledCodeName(const aFileName: AnsiString; const anExt: AnsiString): AnsiString; function ResolveIncludedFilePath(const aFile: AnsiString): AnsiString; procedure AddIncludePath(const aPath: AnsiString); end;//MtfwParserService *) type ItfwParserService = interface {* Интерфейс сервиса TtfwParserService } function MakeCompiledCodeName(const aFileName: AnsiString; const anExt: AnsiString): AnsiString; function ResolveIncludedFilePath(const aFile: AnsiString): AnsiString; procedure AddIncludePath(const aPath: AnsiString); end;//ItfwParserService TtfwParserService = {final} class(Tl3ProtoObject) private f_CoFileDir: AnsiString; f_IncludePaths: Tl3StringList; f_FileNameToFileNameMap: TtfwParserServiceFileNameToFileNameMap; f_Alien: ItfwParserService; {* Внешняя реализация сервиса ItfwParserService } protected procedure pm_SetAlien(const aValue: ItfwParserService); procedure LoadIncludePaths; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public function MakeCompiledCodeName(const aFileName: AnsiString; const anExt: AnsiString): AnsiString; function ResolveIncludedFilePath(const aFile: AnsiString): AnsiString; procedure AddIncludePath(const aPath: AnsiString); class function Instance: TtfwParserService; {* Метод получения экземпляра синглетона TtfwParserService } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property Alien: ItfwParserService write pm_SetAlien; {* Внешняя реализация сервиса ItfwParserService } end;//TtfwParserService implementation uses l3ImplUses , SysUtils , IniFiles , l3FileUtils , StrUtils , l3Base //#UC START# *57726B250063impl_uses* , Classes //#UC END# *57726B250063impl_uses* ; var g_TtfwParserService: TtfwParserService = nil; {* Экземпляр синглетона TtfwParserService } procedure TtfwParserServiceFree; {* Метод освобождения экземпляра синглетона TtfwParserService } begin l3Free(g_TtfwParserService); end;//TtfwParserServiceFree procedure TtfwParserService.pm_SetAlien(const aValue: ItfwParserService); begin Assert((f_Alien = nil) OR (aValue = nil)); f_Alien := aValue; end;//TtfwParserService.pm_SetAlien procedure TtfwParserService.LoadIncludePaths; //#UC START# *57CD20D1028F_57726B250063_var* var l_IniName : String; l_IncludeName : String; l_Strings : TStrings; l_Index : Integer; //#UC END# *57CD20D1028F_57726B250063_var* begin //#UC START# *57CD20D1028F_57726B250063_impl* if (f_IncludePaths = nil) then begin f_IncludePaths := Tl3StringList.Create; l_IncludeName := '.'; l_IniName := ChangeFileExt(ParamStr(0), '.ini'); if FileExists(l_IniName) then begin with TIniFile.Create(l_IniName) do try l_IncludeName := ReadString('SCRIPT', 'IncludeFile', '.'); finally Free; end; end;//FileExists(l_IniName) if (l_IncludeName = '.') then begin l_IncludeName := ConcatDirName(GetCurrentDir, ExtractFileName(ChangeFileExt(ParamStr(0), '.include.ini'))); end//l_IncludeName = '.' else begin if (ExtractFilePath(l_IncludeName) = '') then begin l_IncludeName := ConcatDirName(ExtractFilePath(ParamStr(0)), l_IncludeName); end;//ExtractFilePath(l_IncludeName) = '' end;//l_IncludeName = '.' if FileExists(l_IncludeName) then begin l_Strings := TStringList.Create; try with TIniFile.Create(l_IncludeName) do try ReadSectionValues('INCLUDE', l_Strings); finally Free; end; for l_Index := 0 to Pred(l_Strings.Count) do f_IncludePaths.Add(l_Strings.Values[l_Strings.Names[l_Index]]); finally FreeAndNil(l_Strings); end;//try..finally end;//FileExists(l_IncludeName) end;//f_IncludePaths = nil //#UC END# *57CD20D1028F_57726B250063_impl* end;//TtfwParserService.LoadIncludePaths function TtfwParserService.MakeCompiledCodeName(const aFileName: AnsiString; const anExt: AnsiString): AnsiString; //#UC START# *57726B410203_57726B250063_var* const cDefaultDir = 'C:\Temp'; //cDefaultDir = '.'; var l_Path : String; l_IniName : String; //#UC END# *57726B410203_57726B250063_var* begin //#UC START# *57726B410203_57726B250063_impl* if (f_Alien <> nil) then Result := MakeCompiledCodeName(aFileName, anExt) else begin if (f_CoFileDir = '') then begin l_IniName := ChangeFileExt(ParamStr(0), '.ini'); if FileExists(l_IniName) then begin with TIniFile.Create(l_IniName) do try f_CoFileDir := ReadString('SCRIPT', 'CoFileDir', cDefaultDir); finally Free; end; end;//FileExists(l_IniName) if (f_CoFileDir = '') then f_CoFileDir := cDefaultDir; end;//f_CoFileDir = '' if (f_CoFileDir = '.') then Result := aFileName + anExt else begin l_Path := ExtractFilePath(aFileName); if (l_Path = '') OR (l_Path = '.\') then l_Path := GetCurrentDir; l_Path := AnsiReplaceStr(l_Path, ':', ''); l_Path := AnsiReplaceStr(l_Path, '\\', '\'); Result := ConcatDirName(f_CoFileDir, ConcatDirName(l_Path, ExtractFileName(aFileName) + anExt)); l_Path := ExtractFilePath(Result); // if (l_Path = 'C:\Temp\') then // l_Path := ExtractFilePath(Result); ForceDirectories(l_Path); end;//f_CoFileDir = '.' end;//f_Alien <> nil //#UC END# *57726B410203_57726B250063_impl* end;//TtfwParserService.MakeCompiledCodeName function TtfwParserService.ResolveIncludedFilePath(const aFile: AnsiString): AnsiString; //#UC START# *57A9967B0182_57726B250063_var* procedure DoResolve; var l_Index : Integer; l_FileName : String; l_ResultFileName : String; l_ItemIndex : Integer; begin//DoResolve Result := aFile; if not AnsiStartsText('axiom:', Result) then begin if (f_FileNameToFileNameMap = nil) then f_FileNameToFileNameMap := TtfwParserServiceFileNameToFileNameMap.Create; f_FileNameToFileNameMap.Lock; try begin l_ItemIndex := f_FileNameToFileNameMap.IndexByKey(Result); if (l_ItemIndex >= 0) then begin Result := f_FileNameToFileNameMap.ValueByIndex(l_ItemIndex); Exit; end//f_FileNameToFileNameMap.Has(Result) else if (f_FileNameToFileNameMap.Count > 5000) then f_FileNameToFileNameMap.Clear; end;//f_FileNameToFileNameMap = nil if not FileExists(Result) then begin LoadIncludePaths; if (f_IncludePaths <> nil) then begin l_FileName := ExtractFileName(Result); for l_Index := 0 to Pred(f_IncludePaths.Count) do begin l_ResultFileName := ConcatDirName(f_IncludePaths[l_Index].AsString, l_FileName); if FileExists(l_ResultFileName) then begin f_FileNameToFileNameMap.Add(Result, l_ResultFileName); Result := l_ResultFileName; Exit; end;//FileExists(l_ResultFileName) end;//for l_Index f_FileNameToFileNameMap.Add(Result, Result); end;//f_IncludePaths <> nil end//not FileExists(Result) else f_FileNameToFileNameMap.Add(Result, Result); finally f_FileNameToFileNameMap.Unlock; end;//try..finally end;//not AnsiStartsText('axiom:', Result) end;//DoResolve //#UC END# *57A9967B0182_57726B250063_var* begin //#UC START# *57A9967B0182_57726B250063_impl* if (f_Alien <> nil) then Result := f_Alien.ResolveIncludedFilePath(aFile) else DoResolve; //#UC END# *57A9967B0182_57726B250063_impl* end;//TtfwParserService.ResolveIncludedFilePath procedure TtfwParserService.AddIncludePath(const aPath: AnsiString); //#UC START# *57CD20F100D7_57726B250063_var* //#UC END# *57CD20F100D7_57726B250063_var* begin //#UC START# *57CD20F100D7_57726B250063_impl* if (f_Alien <> nil) then f_Alien.AddIncludePath(aPath) else begin LoadIncludePaths; Assert(f_IncludePaths <> nil); if (f_IncludePaths.IndexOf(aPath) < 0) then f_IncludePaths.Add(aPath); end;//f_Alien <> nil //#UC END# *57CD20F100D7_57726B250063_impl* end;//TtfwParserService.AddIncludePath class function TtfwParserService.Instance: TtfwParserService; {* Метод получения экземпляра синглетона TtfwParserService } begin if (g_TtfwParserService = nil) then begin l3System.AddExitProc(TtfwParserServiceFree); g_TtfwParserService := Create; end; Result := g_TtfwParserService; end;//TtfwParserService.Instance class function TtfwParserService.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TtfwParserService <> nil; end;//TtfwParserService.Exists procedure TtfwParserService.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_57726B250063_var* //#UC END# *479731C50290_57726B250063_var* begin //#UC START# *479731C50290_57726B250063_impl* FreeAndNil(f_IncludePaths); FreeAndNil(f_FileNameToFileNameMap); inherited; //#UC END# *479731C50290_57726B250063_impl* end;//TtfwParserService.Cleanup procedure TtfwParserService.ClearFields; begin Alien := nil; inherited; end;//TtfwParserService.ClearFields end.
unit TTSNOTICETAGTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSNOTICETAGRecord = record PCifFlag: String[1]; PLoanNum: String[20]; PCollNum: Integer; PTrackCode: String[8]; PCategorySub: Integer; PSendToType: String[1]; PSeparateBy: String[10]; PSortBy: String[120]; PNoticeCycle: Integer; PStdNotice: Boolean; PName1: String[40]; PPriorNoticeDate: String[10]; PLapse: Integer; End; TTTSNOTICETAGBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSNOTICETAGRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSNOTICETAG = (TTSNOTICETAGPrimaryKey, TTSNOTICETAGBySort); TTTSNOTICETAGTable = class( TDBISAMTableAU ) private FDFCifFlag: TStringField; FDFLoanNum: TStringField; FDFCollNum: TIntegerField; FDFTrackCode: TStringField; FDFCategorySub: TIntegerField; FDFSendToType: TStringField; FDFSeparateBy: TStringField; FDFSortBy: TStringField; FDFNoticeCycle: TIntegerField; FDFStdNotice: TBooleanField; FDFNoticeText: TBlobField; FDFName1: TStringField; FDFPriorNoticeDate: TStringField; FDFLapse: TIntegerField; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPCollNum(const Value: Integer); function GetPCollNum:Integer; procedure SetPTrackCode(const Value: String); function GetPTrackCode:String; procedure SetPCategorySub(const Value: Integer); function GetPCategorySub:Integer; procedure SetPSendToType(const Value: String); function GetPSendToType:String; procedure SetPSeparateBy(const Value: String); function GetPSeparateBy:String; procedure SetPSortBy(const Value: String); function GetPSortBy:String; procedure SetPNoticeCycle(const Value: Integer); function GetPNoticeCycle:Integer; procedure SetPStdNotice(const Value: Boolean); function GetPStdNotice:Boolean; procedure SetPName1(const Value: String); function GetPName1:String; procedure SetPPriorNoticeDate(const Value: String); function GetPPriorNoticeDate:String; procedure SetPLapse(const Value: Integer); function GetPLapse:Integer; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSNOTICETAG); function GetEnumIndex: TEITTSNOTICETAG; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSNOTICETAGRecord; procedure StoreDataBuffer(ABuffer:TTTSNOTICETAGRecord); property DFCifFlag: TStringField read FDFCifFlag; property DFLoanNum: TStringField read FDFLoanNum; property DFCollNum: TIntegerField read FDFCollNum; property DFTrackCode: TStringField read FDFTrackCode; property DFCategorySub: TIntegerField read FDFCategorySub; property DFSendToType: TStringField read FDFSendToType; property DFSeparateBy: TStringField read FDFSeparateBy; property DFSortBy: TStringField read FDFSortBy; property DFNoticeCycle: TIntegerField read FDFNoticeCycle; property DFStdNotice: TBooleanField read FDFStdNotice; property DFNoticeText: TBlobField read FDFNoticeText; property DFName1: TStringField read FDFName1; property DFPriorNoticeDate: TStringField read FDFPriorNoticeDate; property DFLapse: TIntegerField read FDFLapse; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PCollNum: Integer read GetPCollNum write SetPCollNum; property PTrackCode: String read GetPTrackCode write SetPTrackCode; property PCategorySub: Integer read GetPCategorySub write SetPCategorySub; property PSendToType: String read GetPSendToType write SetPSendToType; property PSeparateBy: String read GetPSeparateBy write SetPSeparateBy; property PSortBy: String read GetPSortBy write SetPSortBy; property PNoticeCycle: Integer read GetPNoticeCycle write SetPNoticeCycle; property PStdNotice: Boolean read GetPStdNotice write SetPStdNotice; property PName1: String read GetPName1 write SetPName1; property PPriorNoticeDate: String read GetPPriorNoticeDate write SetPPriorNoticeDate; property PLapse: Integer read GetPLapse write SetPLapse; published property Active write SetActive; property EnumIndex: TEITTSNOTICETAG read GetEnumIndex write SetEnumIndex; end; { TTTSNOTICETAGTable } procedure Register; implementation function TTTSNOTICETAGTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSNOTICETAGTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSNOTICETAGTable.GenerateNewFieldName } function TTTSNOTICETAGTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSNOTICETAGTable.CreateField } procedure TTTSNOTICETAGTable.CreateFields; begin FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFCollNum := CreateField( 'CollNum' ) as TIntegerField; FDFTrackCode := CreateField( 'TrackCode' ) as TStringField; FDFCategorySub := CreateField( 'CategorySub' ) as TIntegerField; FDFSendToType := CreateField( 'SendToType' ) as TStringField; FDFSeparateBy := CreateField( 'SeparateBy' ) as TStringField; FDFSortBy := CreateField( 'SortBy' ) as TStringField; FDFNoticeCycle := CreateField( 'NoticeCycle' ) as TIntegerField; FDFStdNotice := CreateField( 'StdNotice' ) as TBooleanField; FDFNoticeText := CreateField( 'NoticeText' ) as TBlobField; FDFName1 := CreateField( 'Name1' ) as TStringField; FDFPriorNoticeDate := CreateField( 'PriorNoticeDate' ) as TStringField; FDFLapse := CreateField( 'Lapse' ) as TIntegerField; end; { TTTSNOTICETAGTable.CreateFields } procedure TTTSNOTICETAGTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSNOTICETAGTable.SetActive } procedure TTTSNOTICETAGTable.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSNOTICETAGTable.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSNOTICETAGTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSNOTICETAGTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSNOTICETAGTable.SetPCollNum(const Value: Integer); begin DFCollNum.Value := Value; end; function TTTSNOTICETAGTable.GetPCollNum:Integer; begin result := DFCollNum.Value; end; procedure TTTSNOTICETAGTable.SetPTrackCode(const Value: String); begin DFTrackCode.Value := Value; end; function TTTSNOTICETAGTable.GetPTrackCode:String; begin result := DFTrackCode.Value; end; procedure TTTSNOTICETAGTable.SetPCategorySub(const Value: Integer); begin DFCategorySub.Value := Value; end; function TTTSNOTICETAGTable.GetPCategorySub:Integer; begin result := DFCategorySub.Value; end; procedure TTTSNOTICETAGTable.SetPSendToType(const Value: String); begin DFSendToType.Value := Value; end; function TTTSNOTICETAGTable.GetPSendToType:String; begin result := DFSendToType.Value; end; procedure TTTSNOTICETAGTable.SetPSeparateBy(const Value: String); begin DFSeparateBy.Value := Value; end; function TTTSNOTICETAGTable.GetPSeparateBy:String; begin result := DFSeparateBy.Value; end; procedure TTTSNOTICETAGTable.SetPSortBy(const Value: String); begin DFSortBy.Value := Value; end; function TTTSNOTICETAGTable.GetPSortBy:String; begin result := DFSortBy.Value; end; procedure TTTSNOTICETAGTable.SetPNoticeCycle(const Value: Integer); begin DFNoticeCycle.Value := Value; end; function TTTSNOTICETAGTable.GetPNoticeCycle:Integer; begin result := DFNoticeCycle.Value; end; procedure TTTSNOTICETAGTable.SetPStdNotice(const Value: Boolean); begin DFStdNotice.Value := Value; end; function TTTSNOTICETAGTable.GetPStdNotice:Boolean; begin result := DFStdNotice.Value; end; procedure TTTSNOTICETAGTable.SetPName1(const Value: String); begin DFName1.Value := Value; end; function TTTSNOTICETAGTable.GetPName1:String; begin result := DFName1.Value; end; procedure TTTSNOTICETAGTable.SetPPriorNoticeDate(const Value: String); begin DFPriorNoticeDate.Value := Value; end; function TTTSNOTICETAGTable.GetPPriorNoticeDate:String; begin result := DFPriorNoticeDate.Value; end; procedure TTTSNOTICETAGTable.SetPLapse(const Value: Integer); begin DFLapse.Value := Value; end; function TTTSNOTICETAGTable.GetPLapse:Integer; begin result := DFLapse.Value; end; procedure TTTSNOTICETAGTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('CifFlag, String, 1, N'); Add('LoanNum, String, 20, N'); Add('CollNum, Integer, 0, N'); Add('TrackCode, String, 8, N'); Add('CategorySub, Integer, 0, N'); Add('SendToType, String, 1, N'); Add('SeparateBy, String, 10, N'); Add('SortBy, String, 120, N'); Add('NoticeCycle, Integer, 0, N'); Add('StdNotice, Boolean, 0, N'); Add('NoticeText, Memo, 0, N'); Add('Name1, String, 40, N'); Add('PriorNoticeDate, String, 10, N'); Add('Lapse, Integer, 0, N'); end; end; procedure TTTSNOTICETAGTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, CifFlag;LoanNum;CollNum;TrackCode;CategorySub;SendToType, Y, Y, N, N'); Add('BySort, SeparateBy;SortBy, N, N, Y, N'); end; end; procedure TTTSNOTICETAGTable.SetEnumIndex(Value: TEITTSNOTICETAG); begin case Value of TTSNOTICETAGPrimaryKey : IndexName := ''; TTSNOTICETAGBySort : IndexName := 'BySort'; end; end; function TTTSNOTICETAGTable.GetDataBuffer:TTTSNOTICETAGRecord; var buf: TTTSNOTICETAGRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCifFlag := DFCifFlag.Value; buf.PLoanNum := DFLoanNum.Value; buf.PCollNum := DFCollNum.Value; buf.PTrackCode := DFTrackCode.Value; buf.PCategorySub := DFCategorySub.Value; buf.PSendToType := DFSendToType.Value; buf.PSeparateBy := DFSeparateBy.Value; buf.PSortBy := DFSortBy.Value; buf.PNoticeCycle := DFNoticeCycle.Value; buf.PStdNotice := DFStdNotice.Value; buf.PName1 := DFName1.Value; buf.PPriorNoticeDate := DFPriorNoticeDate.Value; buf.PLapse := DFLapse.Value; result := buf; end; procedure TTTSNOTICETAGTable.StoreDataBuffer(ABuffer:TTTSNOTICETAGRecord); begin DFCifFlag.Value := ABuffer.PCifFlag; DFLoanNum.Value := ABuffer.PLoanNum; DFCollNum.Value := ABuffer.PCollNum; DFTrackCode.Value := ABuffer.PTrackCode; DFCategorySub.Value := ABuffer.PCategorySub; DFSendToType.Value := ABuffer.PSendToType; DFSeparateBy.Value := ABuffer.PSeparateBy; DFSortBy.Value := ABuffer.PSortBy; DFNoticeCycle.Value := ABuffer.PNoticeCycle; DFStdNotice.Value := ABuffer.PStdNotice; DFName1.Value := ABuffer.PName1; DFPriorNoticeDate.Value := ABuffer.PPriorNoticeDate; DFLapse.Value := ABuffer.PLapse; end; function TTTSNOTICETAGTable.GetEnumIndex: TEITTSNOTICETAG; var iname : string; begin result := TTSNOTICETAGPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSNOTICETAGPrimaryKey; if iname = 'BYSORT' then result := TTSNOTICETAGBySort; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSNOTICETAGTable, TTTSNOTICETAGBuffer ] ); end; { Register } function TTTSNOTICETAGBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..13] of string = ('CIFFLAG','LOANNUM','COLLNUM','TRACKCODE','CATEGORYSUB','SENDTOTYPE' ,'SEPARATEBY','SORTBY','NOTICECYCLE','STDNOTICE','NAME1','PRIORNOTICEDATE','LAPSE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 13) and (flist[x] <> s) do inc(x); if x <= 13 then result := x else result := 0; end; function TTTSNOTICETAGBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftString; 5 : result := ftInteger; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftInteger; 10 : result := ftBoolean; 11 : result := ftString; 12 : result := ftString; 13 : result := ftInteger; end; end; function TTTSNOTICETAGBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCifFlag; 2 : result := @Data.PLoanNum; 3 : result := @Data.PCollNum; 4 : result := @Data.PTrackCode; 5 : result := @Data.PCategorySub; 6 : result := @Data.PSendToType; 7 : result := @Data.PSeparateBy; 8 : result := @Data.PSortBy; 9 : result := @Data.PNoticeCycle; 10 : result := @Data.PStdNotice; 11 : result := @Data.PName1; 12 : result := @Data.PPriorNoticeDate; 13 : result := @Data.PLapse; end; end; end.
unit evdTextToFirstParaAdder; {* Фильтр, добавляющий текст к первому параграфу } // Модуль: "w:\common\components\rtl\Garant\EVD\evdTextToFirstParaAdder.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevdTextToFirstParaAdder" MUID: (4CDD7C01013F) {$Include w:\common\components\rtl\Garant\EVD\evdDefine.inc} interface uses l3IntfUses , evdLeafParaFilter , l3Interfaces , k2Interfaces , l3Variant ; type TevdTextToFirstParaAdder = class(TevdLeafParaFilter) {* Фильтр, добавляющий текст к первому параграфу } private f_Text: Il3CString; f_WasAdd: Boolean; protected procedure Cleanup; override; {* Функция очистки полей объекта. } procedure DoWritePara(aLeaf: Tl3Variant); override; {* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца } procedure ClearFields; override; public class function SetTo(var theGenerator: Ik2TagGenerator; const aText: Il3CString): Ik2TagGenerator; constructor Create(const aText: Il3CString); reintroduce; end;//TevdTextToFirstParaAdder implementation uses l3ImplUses , k2Tags , l3CustomString , HyperLink_Const , evdTypes , l3String , l3Types , SysUtils //#UC START# *4CDD7C01013Fimpl_uses* //#UC END# *4CDD7C01013Fimpl_uses* ; class function TevdTextToFirstParaAdder.SetTo(var theGenerator: Ik2TagGenerator; const aText: Il3CString): Ik2TagGenerator; //#UC START# *4CDD7CC5001A_4CDD7C01013F_var* var l_Filter : TevdTextToFirstParaAdder; //#UC END# *4CDD7CC5001A_4CDD7C01013F_var* begin //#UC START# *4CDD7CC5001A_4CDD7C01013F_impl* if l3IsNil(aText) then Result := theGenerator else begin l_Filter := Create(aText); try l_Filter.Generator := theGenerator; theGenerator := l_Filter; finally FreeAndNil(l_Filter); end;//try..finally Result := theGenerator; end;//l3IsNil(aText) //#UC END# *4CDD7CC5001A_4CDD7C01013F_impl* end;//TevdTextToFirstParaAdder.SetTo constructor TevdTextToFirstParaAdder.Create(const aText: Il3CString); //#UC START# *4CDD7CFF03C8_4CDD7C01013F_var* //#UC END# *4CDD7CFF03C8_4CDD7C01013F_var* begin //#UC START# *4CDD7CFF03C8_4CDD7C01013F_impl* inherited Create; f_Text := aText; //#UC END# *4CDD7CFF03C8_4CDD7C01013F_impl* end;//TevdTextToFirstParaAdder.Create procedure TevdTextToFirstParaAdder.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4CDD7C01013F_var* //#UC END# *479731C50290_4CDD7C01013F_var* begin //#UC START# *479731C50290_4CDD7C01013F_impl* f_WasAdd := false; inherited; //#UC END# *479731C50290_4CDD7C01013F_impl* end;//TevdTextToFirstParaAdder.Cleanup procedure TevdTextToFirstParaAdder.DoWritePara(aLeaf: Tl3Variant); {* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца } //#UC START# *49E4883E0176_4CDD7C01013F_var* var l_S : Tl3CustomString; l_Len : Integer; l_H : Tl3Variant; //#UC END# *49E4883E0176_4CDD7C01013F_var* begin //#UC START# *49E4883E0176_4CDD7C01013F_impl* if not f_WasAdd then begin if aLeaf.HasSubAtom(k2_tiText) then begin l_S := (aLeaf.Attr[k2_tiText] As Tl3CustomString); if (l_S <> nil) AND not l_S.Empty then begin f_WasAdd := true; l_Len := l_S.Len; l_S.Append(l3PCharLen(f_Text)); with aLeaf.rAtomEx([k2_tiSegments, k2_tiChildren, k2_tiHandle, Ord(ev_slHyperlinks)]) do if IsValid then begin l_H := rAtomEx([k2_tiChildren, l3_siNative, l_Len]); if l_H.IsValid then if (l_H.IntA[k2_tiFinish] = l_Len) then l_H.IntA[k2_tiFinish] := l_S.Len; end;//IsValid end;//l_S <> nil end;//aLeaf.HasSubAtom(k2_tiText) end;//not f_WasAdd inherited; //#UC END# *49E4883E0176_4CDD7C01013F_impl* end;//TevdTextToFirstParaAdder.DoWritePara procedure TevdTextToFirstParaAdder.ClearFields; begin f_Text := nil; inherited; end;//TevdTextToFirstParaAdder.ClearFields end.
unit uimemo; interface uses SysUtils, Math, ui, uimpl, uihandle, uicomp, datastorage; type TWinMemo=class(TWinComp) private wTopItem:integer; wLines:TStringListEx; protected public constructor Create(Owner:TWinHandle);override; procedure CustomPaint;override; procedure CreatePerform;override; procedure MouseMovePerform(AButtonControl:cardinal; x,y:integer);override; procedure MouseLeavePerform;override; procedure MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override; procedure MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer);override; procedure KeyCharPerform(keychar:cardinal);override; procedure SetFocusPerform;override; procedure KillFocusPerform(handle:HWND);override; property Lines:TStringListEx read wLines; end; implementation constructor TWinMemo.Create(Owner:TWinHandle); begin inherited; wLines:=TStringListEx.Create; //TODO destroy wTopItem:=0; end; procedure TWinMemo.CreatePerform; begin inherited; wCursor:=crIBeam; end; procedure TWinMemo.CustomPaint; var r, rtxt : trect; i:integer; begin r:=GetClientRect; BeginPaint; rtxt:=r; rtxt.Left:=rtxt.Left+3; rtxt.Right:=rtxt.Right-1; rtxt.Top:=rtxt.Top+1; rtxt.Bottom:=rtxt.Top+18; i:=wTopItem; while(rtxt.Top<r.Bottom) do begin Polygon(bkcolor, bkcolor, rtxt.Left-2, rtxt.Top, rtxt.Right-1, rtxt.Bottom-1); if i<Lines.count then begin DrawText(rtxt, Lines[i], font, color, bkcolor, OPAQUE, DT_SINGLELINE or DT_LEFT or DT_TOP); end; inc(i); rtxt.Top:=rtxt.Top+18; rtxt.Bottom:=rtxt.Bottom+18; end; Polyline(clFaceBook1, 0, 5, r.Left, r.Top, r.Right-1, r.Bottom-1); EndPaint; end; procedure TWinMemo.MouseMovePerform(AButtonControl:cardinal; x,y:integer); begin inherited; //wText:=''; //RedrawPerform; end; procedure TWinMemo.MouseLeavePerform; begin inherited; //RedrawPerform; end; procedure TWinMemo.SetFocusPerform; begin inherited; ShowKeyCursor; RedrawPerform end; procedure TWinMemo.KillFocusPerform; begin inherited; HideKeyCursor; RedrawPerform end; procedure TWinMemo.MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer); begin if AButton=mbLeft then begin KeyCursorX:=x; KeyCursorY:=(y div 18)*18+2; end; inherited; end; procedure TWinMemo.MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer); begin inherited; wTopItem:=max(wTopItem-deltawheel,0); KeyCursorY:=KeyCursorY+deltawheel*18; ShowKeyCursor; RedrawPerform end; procedure TWinMemo.KeyCharPerform(keychar:cardinal); begin inherited; wText:=inttostr(keychar);//wText+chr(keychar); RedrawPerform; end; end.
unit Provect.Pipes; /// ///////////////////////////////////////////////////////////////////////////// // // Unit : Pipes // Author : rllibby, Nick Remeslennikov // /// ///////////////////////////////////////////////////////////////////////////// interface uses Winapi.Windows, System.SysUtils, System.Classes, System.Types, Winapi.Messages; resourcestring resThreadCtx = 'The notify window and the component window do not exist in the same thread!'; resPipeActive = 'Cannot change property while server is active!'; resPipeConnected = 'Cannot change property when client is connected!'; resBadPipeName = 'Invalid pipe name specified!'; resPipeBaseName = '\\.\pipe\'; resPipeBaseFmtName = '\\%s\pipe\'; resPipeName = 'PipeServer'; resConClass = 'ConsoleWindowClass'; resComSpec = 'ComSpec'; const MAX_NAME = 256; MAX_WAIT = 1000; MAX_BUFFER = Pred(MaxWord); DEF_SLEEP = 100; DEF_MEMTHROTTLE = 10240000; PIPE_MODE = PIPE_TYPE_MESSAGE or PIPE_READMODE_MESSAGE or PIPE_WAIT; PIPE_OPENMODE = PIPE_ACCESS_DUPLEX or FILE_FLAG_OVERLAPPED; PIPE_INSTANCES = PIPE_UNLIMITED_INSTANCES; STD_PIPE_INPUT = 0; STD_PIPE_OUTPUT = 1; STD_PIPE_ERROR = 2; MB_MAGIC = $4347414D; // MAGC MB_START = $424D5453; // STMB MB_END = $424D5445; // ETMB MB_PREFIX = 'PMM'; INSTANCE_COUNT = 313; WM_PIPEERROR_L = WM_USER + 100; WM_PIPEERROR_W = WM_USER + 101; WM_PIPECONNECT = WM_USER + 102; WM_PIPESEND = WM_USER + 103; WM_PIPEMESSAGE = WM_USER + 104; WM_PIPE_CON_OUT = WM_USER + 105; WM_PIPE_CON_ERR = WM_USER + 106; WM_PIPEMINMSG = WM_PIPEERROR_L; WM_PIPEMAXMSG = WM_PIPE_CON_ERR; WM_THREADCTX = WM_USER + 200; WM_DOSHUTDOWN = WM_USER + 300; CM_EXECPROC = $8FFD; CM_DESTROYWINDOW = $8FFC; type EPipeException = class(Exception); HPIPE = THandle; // Forward declarations TPipeServer = class; TPipeClient = class; TWriteQueue = class; // Std handles for console redirection TPipeStdHandles = array [STD_PIPE_INPUT .. STD_PIPE_ERROR] of THandle; // Process window info PPipeConsoleInfo = ^TPipeConsoleInfo; TPipeConsoleInfo = packed record ProcessID: DWORD; ThreadID: DWORD; Window: HWND; end; // Data write record PPipeWrite = ^TPipeWrite; TPipeWrite = packed record Buffer: PChar; Count: Integer; end; // Data write message block PPipeMsgBlock = ^TPipeMsgBlock; TPipeMsgBlock = packed record Size: DWORD; MagicStart: DWORD; ControlCode: DWORD; MagicEnd: DWORD; end; // Data writer list record PWriteNode = ^TWriteNode; TWriteNode = packed record PipeWrite: PPipeWrite; NextNode: PWriteNode; end; // Server pipe info record PPipeInfo = ^TPipeInfo; TPipeInfo = packed record Pipe: HPIPE; KillEvent: THandle; WriteQueue: TWriteQueue; end; // Thread sync info TSyncInfo = class FSyncBaseTID: THandle; FThreadWindow: HWND; FThreadCount: Integer; end; // Exception frame PRaiseFrame = ^TRaiseFrame; TRaiseFrame = record NextRaise: PRaiseFrame; ExceptAddr: Pointer; ExceptObject: TObject; ExceptionRecord: PExceptionRecord; end; // Window proc TWndMethod = procedure(var Message: TMessage) of object; // Object instance structure PObjectInstance = ^TObjectInstance; TObjectInstance = packed record Code: Byte; Offset: Integer; case Integer of 0: (Next: PObjectInstance); 1: (Method: TWndMethod); end; // Object instance page block PInstanceBlock = ^TInstanceBlock; TInstanceBlock = packed record Next: PInstanceBlock; Counter: Word; Code: array [1 .. 2] of Byte; WndProcPtr: Pointer; Instances: array [0 .. INSTANCE_COUNT] of TObjectInstance; end; // Pipe context for error messages TPipeContext = (pcListener, pcWorker); // Pipe Events TOnConsole = procedure(Sender: TObject; Stream: TStream) of object; TOnConsoleStop = procedure(Sender: TObject; ExitValue: LongWord) of object; TOnPipeConnect = procedure(Sender: TObject; Pipe: HPIPE) of object; TOnPipeDisconnect = procedure(Sender: TObject; Pipe: HPIPE) of object; TOnPipeMessage = procedure(Sender: TObject; Pipe: HPIPE; Stream: TStream) of object; TOnPipeSent = procedure(Sender: TObject; Pipe: HPIPE; Size: DWORD) of object; TOnPipeError = procedure(Sender: TObject; Pipe: HPIPE; PipeContext: TPipeContext; ErrorCode: Integer) of object; // TWriteQueue class TWriteQueue = class(TObject) private // Private declarations FMutex: THandle; FDataEv: THandle; FEmptyEv: THandle; FDataSize: LongWord; FHead: PWriteNode; FTail: PWriteNode; procedure UpdateState; function NodeSize(Node: PWriteNode): LongWord; protected // Protected declarations procedure Clear; procedure EnqueueControlPacket(ControlCode: DWORD); procedure EnqueueMultiPacket(PipeWrite: PPipeWrite); function GetEmpty: Boolean; function NewNode(PipeWrite: PPipeWrite): PWriteNode; public // Public declarations constructor Create; destructor Destroy; override; procedure Enqueue(PipeWrite: PPipeWrite); procedure EnqueueEndPacket; procedure EnqueueStartPacket; function Dequeue: PPipeWrite; property DataEvent: THandle read FDataEv; property DataSize: LongWord read FDataSize; property Empty: Boolean read GetEmpty; property EmptyEvent: THandle read FEmptyEv; end; // TThreadSync class TThreadSync = class private // Private declarations FSyncRaise: TObject; FMethod: TThreadMethod; FSyncBaseTID: THandle; public // Public declarations constructor Create; destructor Destroy; override; procedure Synchronize(Method: TThreadMethod); property SyncBaseTID: THandle read FSyncBaseTID; end; // TThreadEx class TThreadEx = class(TThread) private // Private declarations FSync: TThreadSync; procedure HandleTerminate; protected // Protected declarations procedure SafeSynchronize(Method: TThreadMethod); procedure Synchronize(Method: TThreadMethod); procedure DoTerminate; override; public // Public declarations constructor Create(CreateSuspended: Boolean); destructor Destroy; override; procedure Wait; property Sync: TThreadSync read FSync; end; // TSyncManager class TSyncManager = class(TObject) private // Private declarations FThreadLock: TRTLCriticalSection; FList: TList; protected // Protected declarations procedure DoDestroyWindow(Info: TSyncInfo); procedure FreeSyncInfo(Info: TSyncInfo); function AllocateWindow: HWND; function FindSyncInfo(SyncBaseTID: LongWord): TSyncInfo; public // Public declarations class function Instance: TSyncManager; constructor Create; destructor Destroy; override; procedure AddThread(ThreadSync: TThreadSync); procedure RemoveThread(ThreadSync: TThreadSync); procedure Synchronize(ThreadSync: TThreadSync); end; // TThreadCounter class TThreadCounter = class(TObject) private // Private declarations FLock: TRTLCriticalSection; FEmpty: THandle; FCount: Integer; protected // Protected declarations function GetCount: Integer; public // Public declarations constructor Create; destructor Destroy; override; procedure Increment; procedure Decrement; procedure WaitForEmpty; property Count: Integer read GetCount; end; // TFastMemStream class TFastMemStream = class(TMemoryStream) protected // Protected declarations function Realloc(var NewCapacity: Longint): Pointer; override; end; // Multipacket message handler TPipeMultiMsg = class(TObject) private // Private declarations FHandle: THandle; FStream: TStream; protected // Protected declarations procedure CreateTempBacking; public // Public declarations constructor Create; destructor Destroy; override; property Stream: TStream read FStream; end; // TPipeListenThread class TPipeListenThread = class(TThreadEx) private // Private declarations FNotify: HWND; FNotifyThread: THandle; FErrorCode: Integer; FPipe: HPIPE; FPipeName: string; FConnected: Boolean; FEvents: array [0 .. 1] of THandle; FOlapConnect: TOverlapped; FPipeServer: TPipeServer; FSA: TSecurityAttributes; protected // Protected declarations function CreateServerPipe: Boolean; procedure DoWorker; procedure Execute; override; function SafeSendMessage(Msg: Cardinal; wParam, lParam: Integer): LRESULT; public // Public declarations constructor Create(PipeServer: TPipeServer; KillEvent: THandle); destructor Destroy; override; end; // TPipeThread class TPipeThread = class(TThreadEx) private // Private declarations FServer: Boolean; FNotify: HWND; FNotifyThread: THandle; FPipe: HPIPE; FErrorCode: Integer; FCounter: TThreadCounter; FWrite: DWORD; FWriteQueue: TWriteQueue; FPipeWrite: PPipeWrite; FRcvRead: DWORD; FPendingRead: Boolean; FPendingWrite: Boolean; FMultiMsg: TPipeMultiMsg; FRcvStream: TFastMemStream; FRcvBuffer: PChar; FRcvAlloc: DWORD; FRcvSize: DWORD; FEvents: array [0 .. 3] of THandle; FOlapRead: TOverlapped; FOlapWrite: TOverlapped; protected // Protected declarations function QueuedRead: Boolean; function CompleteRead: Boolean; function QueuedWrite: Boolean; function CompleteWrite: Boolean; procedure DoMessage; procedure Execute; override; function SafeSendMessage(Msg: Cardinal; wParam, lParam: Integer): LRESULT; public // Public declarations constructor Create(Server: Boolean; NotifyWindow: HWND; NotifyThread: THandle; WriteQueue: TWriteQueue; Counter: TThreadCounter; Pipe: HPIPE; KillEvent: THandle); destructor Destroy; override; property Pipe: HPIPE read FPipe; end; // TPipeServer component class TPipeServer = class(TComponent) private // Private declarations FBaseThread: THandle; FHwnd: HWND; FPipeName: string; FDeferActive: Boolean; FActive: Boolean; FInShutDown: Boolean; FKillEv: THandle; FClients: TList; FThreadCount: TThreadCounter; FListener: TPipeListenThread; FSA: TSecurityAttributes; FOPS: TOnPipeSent; FOPC: TOnPipeConnect; FOPD: TOnPipeDisconnect; FOPM: TOnPipeMessage; FOPE: TOnPipeError; procedure DoStartup; procedure DoShutdown; protected // Protected declarations function AllocPipeInfo(Pipe: HPIPE): PPipeInfo; function GetClient(Index: Integer): HPIPE; function GetClientCount: Integer; function GetClientInfo(Pipe: HPIPE; out PipeInfo: PPipeInfo): Boolean; procedure WndMethod(var Message: TMessage); procedure RemoveClient(Pipe: HPIPE); procedure SetActive(Value: Boolean); procedure SetPipeName(Value: string); procedure AddWorkerThread(Pipe: HPIPE); procedure RemoveWorkerThread(Sender: TObject); procedure RemoveListenerThread(Sender: TObject); procedure Loaded; override; public // Public declarations constructor Create(AOwner: TComponent); override; constructor CreateUnowned; destructor Destroy; override; function Broadcast(var Buffer; Count: Integer): Boolean; overload; function Broadcast(var Prefix; PrefixCount: Integer; var Buffer; Count: Integer): Boolean; overload; function Disconnect(Pipe: HPIPE): Boolean; function Write(Pipe: HPIPE; var Prefix; PrefixCount: Integer; var Buffer; Count: Integer): Boolean; overload; function Write(Pipe: HPIPE; var Buffer; Count: Integer): Boolean; overload; function SendStream(Pipe: HPIPE; Stream: TStream): Boolean; property WindowHandle: HWND read FHwnd; property ClientCount: Integer read GetClientCount; property Clients[Index: Integer]: HPIPE read GetClient; published // Published declarations property Active: Boolean read FActive write SetActive; property OnPipeSent: TOnPipeSent read FOPS write FOPS; property OnPipeConnect: TOnPipeConnect read FOPC write FOPC; property OnPipeDisconnect: TOnPipeDisconnect read FOPD write FOPD; property OnPipeMessage: TOnPipeMessage read FOPM write FOPM; property OnPipeError: TOnPipeError read FOPE write FOPE; property PipeName: string read FPipeName write SetPipeName; end; // TPipeClient component class TPipeClient = class(TComponent) private // Private declarations FBaseThread: THandle; FHwnd: HWND; FPipe: HPIPE; FPipeName: string; FServerName: string; FDisconnecting: Boolean; FReply: Boolean; FThrottle: LongWord; FWriteQueue: TWriteQueue; FWorker: TPipeThread; FKillEv: THandle; FSA: TSecurityAttributes; FOPE: TOnPipeError; FOPD: TOnPipeDisconnect; FOPM: TOnPipeMessage; FOPS: TOnPipeSent; protected // Protected declarations function GetConnected: Boolean; procedure SetPipeName(Value: string); procedure SetServerName(Value: string); procedure RemoveWorkerThread(Sender: TObject); procedure WndMethod(var Message: TMessage); public // Public declarations constructor Create(AOwner: TComponent); override; constructor CreateUnowned; destructor Destroy; override; function Connect(WaitTime: DWORD = NMPWAIT_USE_DEFAULT_WAIT; Start: Boolean = True): Boolean; function WaitForReply(TimeOut: Cardinal = INFINITE): Boolean; procedure Disconnect; procedure FlushPipeBuffers; function SendStream(Stream: TStream): Boolean; function Write(var Prefix; PrefixCount: Integer; var Buffer; Count: Integer): Boolean; overload; function Write(var Buffer; Count: Integer): Boolean; overload; function Write(const AStr: string): Boolean; overload; property Connected: Boolean read GetConnected; property WindowHandle: HWND read FHwnd; property Pipe: HPIPE read FPipe; published // Published declarations property MemoryThrottle: LongWord read FThrottle write FThrottle; property PipeName: string read FPipeName write SetPipeName; property ServerName: string read FServerName write SetServerName; property OnPipeDisconnect: TOnPipeDisconnect read FOPD write FOPD; property OnPipeMessage: TOnPipeMessage read FOPM write FOPM; property OnPipeSent: TOnPipeSent read FOPS write FOPS; property OnPipeError: TOnPipeError read FOPE write FOPE; end; // TPipeConsoleThread class TPipeConsoleThread = class(TThreadEx) private // Private declarations FNotify: HWND; FStream: TFastMemStream; FProcess: THandle; FOutput: THandle; FError: THandle; procedure ProcessPipe(Handle: THandle; Msg: UINT); protected // Protected declarations procedure Execute; override; procedure ProcessPipes; function SafeSendMessage(Msg: Cardinal; wParam, lParam: Integer): LRESULT; public // Public declarations constructor Create(NotifyWindow: HWND; ProcessHandle, OutputPipe, ErrorPipe: THandle); destructor Destroy; override; end; // TPipeConsole component class TPipeConsole = class(TComponent) private // Private declarations FRead: TPipeStdHandles; FWrite: TPipeStdHandles; FWorker: TPipeConsoleThread; FPI: TProcessInformation; FSI: TStartupInfo; FLastErr: Integer; FVisible: Boolean; FStopping: Boolean; FHwnd: HWND; FOnStop: TOnConsoleStop; FOnOutput: TOnConsole; FOnError: TOnConsole; FApplication: string; FCommandLine: string; procedure ProcessPipe(Handle: THandle; Stream: TStream); function SynchronousRun(OutputStream, ErrorStream: TStream; TimeOut: DWORD): DWORD; protected // Protected declarations function GetConsoleHandle: HWND; function GetRunning: Boolean; function GetVisible: Boolean; function OpenStdPipes: Boolean; procedure CloseStdPipes; procedure RemoveWorkerThread(Sender: TObject); procedure SetLastErr(Value: Integer); procedure SetVisible(Value: Boolean); procedure WndMethod(var Message: TMessage); public // Public declarations constructor Create(AOwner: TComponent); override; constructor CreateUnowned; destructor Destroy; override; function ComSpec: string; function Execute(Application, CommandLine: string; OutputStream, ErrorStream: TStream; TimeOut: DWORD = INFINITE): DWORD; procedure SendCtrlBreak; procedure SendCtrlC; function Start(Application, CommandLine: string): Boolean; procedure Stop(ExitValue: DWORD); procedure Write(const Buffer; Length: Integer); property Application: string read FApplication; property CommandLine: string read FCommandLine; property ConsoleHandle: HWND read GetConsoleHandle; property Running: Boolean read GetRunning; published // Published declarations property LastError: Integer read FLastErr write SetLastErr; property OnError: TOnConsole read FOnError write FOnError; property OnOutput: TOnConsole read FOnOutput write FOnOutput; property OnStop: TOnConsoleStop read FOnStop write FOnStop; property Visible: Boolean read GetVisible write SetVisible; end; function ExecConsoleEvent(ProcessHandle: THandle; Event: DWORD): Boolean; procedure ExitProcessEx(ProcessHandle: THandle; ExitCode: DWORD); function GetConsoleWindowEx(ProcessHandle: THandle; ProcessID, ThreadID: DWORD): HWND; function AllocPipeWrite(const Buffer; Count: Integer): PPipeWrite; function AllocPipeWriteWithPrefix(const Prefix; PrefixCount: Integer; const Buffer; Count: Integer): PPipeWrite; procedure CheckPipeName(Value: string); procedure ClearOverlapped(var Overlapped: TOverlapped; ClearEvent: Boolean = False); procedure CloseHandleClear(var Handle: THandle); function ComputerName: string; procedure DisconnectAndClose(Pipe: HPIPE; IsServer: Boolean = True); procedure DisposePipeWrite(var PipeWrite: PPipeWrite); function EnumConsoleWindows(Window: HWND; lParam: Integer): BOOL; stdcall; procedure FlushMessages; function IsHandle(Handle: THandle): Boolean; procedure RaiseWindowsError; procedure InitializeSecurity(var SA: TSecurityAttributes); procedure FinalizeSecurity(var SA: TSecurityAttributes); function AllocateHWnd(Method: TWndMethod): HWND; procedure DeallocateHWnd(Wnd: HWND); procedure FreeObjectInstance(ObjectInstance: Pointer); function MakeObjectInstance(Method: TWndMethod): Pointer; procedure Register; implementation var InstBlockList: PInstanceBlock = nil; InstFreeList: PObjectInstance = nil; SyncManager: TSyncManager = nil; InstCritSect: TRTLCriticalSection; ThreadWndClass: TWndClass = (style: 0; lpfnWndProc: nil; cbClsExtra: 0; cbWndExtra: 0; hInstance: 0; hIcon: 0; hCursor: 0; hbrBackground: 0; lpszMenuName: nil; lpszClassName: 'ThreadSyncWindow'); ObjWndClass: TWndClass = (style: 0; lpfnWndProc: @DefWindowProc; cbClsExtra: 0; cbWndExtra: 0; hInstance: 0; hIcon: 0; hCursor: 0; hbrBackground: 0; lpszMenuName: nil; lpszClassName: 'ObjWndWindow'); constructor TPipeConsoleThread.Create(NotifyWindow: HWND; ProcessHandle, OutputPipe, ErrorPipe: THandle); begin // Perform inherited create (suspended) inherited Create(True); // Resource protection try // Set initial state FProcess := 0; FNotify := NotifyWindow; FOutput := OutputPipe; FError := ErrorPipe; FStream := TFastMemStream.Create; finally // Duplicate the process handle DuplicateHandle(GetCurrentProcess, ProcessHandle, GetCurrentProcess, @FProcess, 0, True, DUPLICATE_SAME_ACCESS); end; // Set thread parameters FreeOnTerminate := True; Priority := tpLower; end; destructor TPipeConsoleThread.Destroy; begin // Resource protection try // Close the process handle CloseHandleClear(FProcess); // Free the memory stream FStream.Free; finally // Perform inherited inherited Destroy; end; end; procedure TPipeConsoleThread.Execute; var dwExitCode: DWORD; begin // Set default return value ReturnValue := ERROR_SUCCESS; // Keep looping until the process terminates while True do begin // Wait for specified amount of time case WaitForSingleObject(FProcess, DEF_SLEEP) of // Object is signaled (process is finished) WAIT_OBJECT_0: begin // Process the output pipes one last time ProcessPipes; // Get the process exit code if GetExitCodeProcess(FProcess, dwExitCode) then ReturnValue := dwExitCode; // Break the loop break; end; // Timeout, check the output pipes for data WAIT_TIMEOUT: ProcessPipes; else // Failure, set return code ReturnValue := GetLastError; // Done processing break; end; end; end; procedure TPipeConsoleThread.ProcessPipes; begin // Process the output pipe ProcessPipe(FOutput, WM_PIPE_CON_OUT); // Process the error pipe ProcessPipe(FError, WM_PIPE_CON_ERR); end; procedure TPipeConsoleThread.ProcessPipe(Handle: THandle; Msg: UINT); var dwRead: DWORD; dwSize: DWORD; begin // Check the pipe for available data if PeekNamedPipe(Handle, nil, 0, nil, @dwSize, nil) and (dwSize > 0) then begin // Set the stream size FStream.Size := dwSize; // Resource protection try // Read from the pipe if ReadFile(Handle, FStream.Memory^, dwSize, dwRead, nil) then begin // Make sure we read the number of bytes specified by size if not(dwRead = dwSize) then FStream.Size := dwRead; // Rewind the stream FStream.Position := 0; // Send the message to the component SafeSendMessage(Msg, 0, Integer(FStream)); // Sleep Sleep(0); end; finally // Clear the stream FStream.Clear; end; end; end; function TPipeConsoleThread.SafeSendMessage(Msg: Cardinal; wParam, lParam: Integer): LRESULT; begin // Check window handle if IsWindow(FNotify) then // Send the message result := SendMessage(FNotify, Msg, wParam, lParam) else // Failure result := 0; end; constructor TPipeConsole.Create(AOwner: TComponent); begin // Perform inherited create inherited Create(AOwner); // Private declarations FHwnd := AllocateHWnd(WndMethod); FillChar(FRead, SizeOf(FRead), 0); FillChar(FWrite, SizeOf(FWrite), 0); FillChar(FPI, SizeOf(FPI), 0); FillChar(FSI, SizeOf(FSI), 0); FLastErr := ERROR_SUCCESS; SetLength(FApplication, 0); SetLength(FCommandLine, 0); FStopping := False; FVisible := False; FWorker := nil; end; constructor TPipeConsole.CreateUnowned; begin // Perform create with no owner Create(nil); end; destructor TPipeConsole.Destroy; begin // Resource protection try // Stop the console application Stop(0); // Deallocate the window handle DeallocateHWnd(FHwnd); finally // Perform inherited inherited Destroy; end; end; procedure TPipeConsole.SetLastErr(Value: Integer); begin // Resource protection try // Set the last error for the thread SetLastError(Value); finally // Update the last error status FLastErr := Value; end; end; function TPipeConsole.ComSpec: string; begin // Allocate buffer for result SetLength(result, MAX_PATH); // Resource protection try // Get the environment variable for COMSPEC and truncate to actual result SetLength(result, GetEnvironmentVariable(PChar(resComSpec), Pointer(result), MAX_PATH)); finally // Capture the last error code FLastErr := GetLastError; end; end; function TPipeConsole.OpenStdPipes: Boolean; var dwIndex: Integer; begin // Set default result result := False; // Resource protection try // Close any open handles CloseStdPipes; // Resource protection try // Iterate the pipe array and create new read / write pipe handles for dwIndex := STD_PIPE_INPUT to STD_PIPE_ERROR do begin // Create the pipes if CreatePipe(FRead[dwIndex], FWrite[dwIndex], nil, MAX_BUFFER) then begin // Duplicate the read handles so they can be inherited if DuplicateHandle(GetCurrentProcess, FRead[dwIndex], GetCurrentProcess, @FRead[dwIndex], 0, True, DUPLICATE_CLOSE_SOURCE or DUPLICATE_SAME_ACCESS) then // Duplicate the write handles so they can be inherited result := DuplicateHandle(GetCurrentProcess, FWrite[dwIndex], GetCurrentProcess, @FWrite[dwIndex], 0, True, DUPLICATE_CLOSE_SOURCE or DUPLICATE_SAME_ACCESS) else // Failed to duplicate result := False; end else // Failed to create pipes result := False; // Should we continue? if not(result) then break; end; finally // Capture the last error code FLastErr := GetLastError; end; finally // Close all handles on failure if not(result) then CloseStdPipes; end; end; procedure TPipeConsole.CloseStdPipes; var dwIndex: Integer; begin // Iterate the pipe array and close the read / write pipe handles for dwIndex := STD_PIPE_INPUT to STD_PIPE_ERROR do begin // Close and clear the read handle CloseHandleClear(FRead[dwIndex]); // Close and clear the read handle CloseHandleClear(FWrite[dwIndex]); end; end; function TPipeConsole.GetRunning: Boolean; begin // Check process information result := (IsHandle(FPI.hProcess) and (WaitForSingleObject(FPI.hProcess, 0) = WAIT_TIMEOUT)); end; procedure TPipeConsole.SendCtrlBreak; begin // Make sure the process is running, then inject and exec if GetRunning then ExecConsoleEvent(FPI.hProcess, CTRL_BREAK_EVENT); end; procedure TPipeConsole.SendCtrlC; begin // Make sure the process is running, then inject and exec if GetRunning then ExecConsoleEvent(FPI.hProcess, CTRL_C_EVENT); end; procedure TPipeConsole.Write(const Buffer; Length: Integer); var dwWrite: DWORD; begin // Check state if GetRunning and IsHandle(FWrite[STD_PIPE_INPUT]) then begin // Write data to the pipe WriteFile(FWrite[STD_PIPE_INPUT], Buffer, Length, dwWrite, nil); end; end; function TPipeConsole.GetConsoleHandle: HWND; var lpConInfo: TPipeConsoleInfo; begin // Clear the return handle result := 0; // Check to see if running if GetRunning then begin // Clear the window handle lpConInfo.Window := 0; // Resource protection try // Set process info lpConInfo.ProcessID := FPI.dwProcessID; lpConInfo.ThreadID := FPI.dwThreadID; // Enumerate the windows on the console thread EnumWindows(@EnumConsoleWindows, Integer(@lpConInfo)); finally // Return the window handle result := lpConInfo.Window; end; end; end; function TPipeConsole.GetVisible: Boolean; var hwndCon: HWND; begin // Check running state if not(GetRunning) then // If not running then return the stored state result := FVisible else begin // Attempt to get the window handle hwndCon := GetConsoleWindowEx(FPI.hProcess, FPI.dwProcessID, FPI.dwThreadID); // Check result if IsWindow(hwndCon) then // Return visible state result := IsWindowVisible(hwndCon) else // Return stored state result := FVisible; end; end; procedure TPipeConsole.SetVisible(Value: Boolean); var hwndCon: HWND; begin // Check against current state if not(GetVisible = Value) then begin // Update the state FVisible := Value; // Check to see if running if GetRunning then begin // Attempt to have the console window return us its handle hwndCon := GetConsoleWindowEx(FPI.hProcess, FPI.dwProcessID, FPI.dwThreadID); // Check result if IsWindow(hwndCon) then begin // Show or hide based on visibility if FVisible then // Show ShowWindow(hwndCon, SW_SHOWNORMAL) else // Hide ShowWindow(hwndCon, SW_HIDE); end; end; end; end; procedure TPipeConsole.WndMethod(var Message: TMessage); begin // Handle the pipe messages case Message.Msg of // Pipe output from console WM_PIPE_CON_OUT: if Assigned(FOnOutput) then FOnOutput(Self, TStream(Pointer(Message.lParam))); // Pipe error from console WM_PIPE_CON_ERR: if Assigned(FOnError) then FOnError(Self, TStream(Pointer(Message.lParam))); // Shutdown WM_DOSHUTDOWN: Stop(Message.wParam); else // Call default window procedure Message.result := DefWindowProc(FHwnd, Message.Msg, Message.wParam, Message.lParam); end; end; procedure TPipeConsole.RemoveWorkerThread(Sender: TObject); var dwReturn: LongWord; begin // Get the thread return value dwReturn := FWorker.ReturnValue; // Resource protection try // Set thread variable to nil FWorker := nil; // Resource protection try // Notify of process stop if (not(csDestroying in ComponentState) and Assigned(FOnStop)) then FOnStop(Self, dwReturn); finally // Close the process and thread handles CloseHandleClear(FPI.hProcess); CloseHandleClear(FPI.hThread); end; finally // Close the pipe handles CloseStdPipes; end; end; procedure TPipeConsole.ProcessPipe(Handle: THandle; Stream: TStream); var lpszBuffer: PChar; dwRead: DWORD; dwSize: DWORD; begin // Check the pipe for available data if PeekNamedPipe(Handle, nil, 0, nil, @dwSize, nil) and (dwSize > 0) then begin // Allocate buffer for read. Note, we need to clear the output even if no stream is passed lpszBuffer := AllocMem(dwSize); // Resource protection try // Read from the pipe if ReadFile(Handle, lpszBuffer^, dwSize, dwRead, nil) and Assigned(Stream) then begin // Save buffer to stream Stream.Write(lpszBuffer^, dwRead); end; finally // Free the memory FreeMem(lpszBuffer); end; end; end; function TPipeConsole.SynchronousRun(OutputStream, ErrorStream: TStream; TimeOut: DWORD): DWORD; begin // Set default return value SetLastErr(ERROR_SUCCESS); // Resource protection try // Keep looping until the process terminates while True do begin // Wait for specified amount of time case WaitForSingleObject(FPI.hProcess, DEF_SLEEP) of // Object is signaled (process is finished) WAIT_OBJECT_0: begin // Process the output pipes one last time ProcessPipe(FRead[STD_PIPE_OUTPUT], OutputStream); ProcessPipe(FRead[STD_PIPE_ERROR], ErrorStream); // Break the loop break; end; // Timeout, check the output pipes for data WAIT_TIMEOUT: begin // Process the output pipes ProcessPipe(FRead[STD_PIPE_OUTPUT], OutputStream); ProcessPipe(FRead[STD_PIPE_ERROR], ErrorStream); end; else // Failure, set return code SetLastErr(GetLastError); // Done processing break; end; // Check the timeout if (TimeOut > 0) and (GetTickCount > TimeOut) then begin // Terminate the process ExitProcessEx(FPI.hProcess, 0); // Set result SetLastErr(ERROR_TIMEOUT); // Done processing break; end; end; finally // Return last error result result := FLastErr; end; end; function TPipeConsole.Execute(Application, CommandLine: string; OutputStream, ErrorStream: TStream; TimeOut: DWORD = INFINITE): DWORD; begin // Set default result SetLastErr(ERROR_SUCCESS); // Both params cannot be null if (Length(Application) = 0) and (Length(CommandLine) = 0) then begin // Set error code SetLastErr(ERROR_INVALID_PARAMETER); // Failure result := FLastErr; end else begin // Stop existing process if running Stop(0); // Resource protection try // Clear the process information FillChar(FPI, SizeOf(FPI), 0); // Clear the startup info structure FillChar(FSI, SizeOf(FSI), 0); // Attempt to open the pipes for redirection if OpenStdPipes then begin // Resource protection try // Set structure size FSI.cb := SizeOf(FSI); // Set flags FSI.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; // Determine if the process will be shown or hidden if FVisible then // Show flag FSI.wShowWindow := SW_SHOWNORMAL else // Hide flag FSI.wShowWindow := SW_HIDE; // Set the redirect handles FSI.hStdInput := FRead[STD_PIPE_INPUT]; FSI.hStdOutput := FWrite[STD_PIPE_OUTPUT]; FSI.hStdError := FWrite[STD_PIPE_ERROR]; // Create the process if CreateProcess(Pointer(Application), Pointer(CommandLine), nil, nil, True, CREATE_NEW_CONSOLE or CREATE_NEW_PROCESS_GROUP or NORMAL_PRIORITY_CLASS, nil, nil, FSI, FPI) then begin // Resource protection try // Wait for input idle WaitForInputIdle(FPI.hProcess, INFINITE); // Check timeout value if (TimeOut = INFINITE) then // Synchronous loop with no timeout SynchronousRun(OutputStream, ErrorStream, 0) else // Synchronous loop with timeout SynchronousRun(OutputStream, ErrorStream, GetTickCount + TimeOut) finally // Close the process and thread handle CloseHandleClear(FPI.hProcess); CloseHandleClear(FPI.hThread); end; end else // Set the last error SetLastErr(GetLastError); finally // Close the pipe handles CloseStdPipes; end; end; finally // Return last error code result := FLastErr; end; end; end; function TPipeConsole.Start(Application, CommandLine: string): Boolean; begin // Both params cannot be null if (Length(Application) = 0) and (Length(CommandLine) = 0) then begin // Set error code SetLastErr(ERROR_INVALID_PARAMETER); // Failure result := False; end else begin // Stop existing process if running Stop(0); // Resource protection try // Clear the process information FillChar(FPI, SizeOf(FPI), 0); // Clear the startup info structure FillChar(FSI, SizeOf(FSI), 0); // Attempt to open the pipes for redirection if OpenStdPipes then begin // Set structure size FSI.cb := SizeOf(FSI); // Set flags FSI.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; // Determine if the process will be shown or hidden if FVisible then // Show flag FSI.wShowWindow := SW_SHOWNORMAL else // Hide flag FSI.wShowWindow := SW_HIDE; // Set the redirect handles FSI.hStdInput := FRead[STD_PIPE_INPUT]; FSI.hStdOutput := FWrite[STD_PIPE_OUTPUT]; FSI.hStdError := FWrite[STD_PIPE_ERROR]; // Create the process if CreateProcess(Pointer(Application), Pointer(CommandLine), nil, nil, True, CREATE_NEW_CONSOLE or CREATE_NEW_PROCESS_GROUP or NORMAL_PRIORITY_CLASS, nil, nil, FSI, FPI) then begin // Persist the strings used to start the process FApplication := Application; FCommandLine := CommandLine; // Wait for input idle WaitForInputIdle(FPI.hProcess, INFINITE); // Exception trap try // Process is created, now start the worker thread FWorker := TPipeConsoleThread.Create(FHwnd, FPI.hProcess, FRead[STD_PIPE_OUTPUT], FRead[STD_PIPE_ERROR]); // Resource protection try // Set the OnTerminate handler FWorker.OnTerminate := RemoveWorkerThread; finally // Resume the worker thread FWorker.Start; end; except // Stop the process Stop(0); end; end else // Get the last error SetLastErr(GetLastError); end; finally // Check final running state result := Assigned(FWorker); end; end; end; procedure TPipeConsole.Stop(ExitValue: DWORD); begin // Check to see if still running if GetRunning and not(FStopping) then begin // Check to see if in a send message if InSendMessage then // Defered shutdown PostMessage(FHwnd, WM_DOSHUTDOWN, ExitValue, 0) else begin // Set state FStopping := True; // Resource protection try // Clear strings SetLength(FApplication, 0); SetLength(FCommandLine, 0); // Resource protection try // Force the process to close ExitProcessEx(FPI.hProcess, ExitValue); // Wait for thread to finish up if Assigned(FWorker) then FWorker.Wait; finally // Close the process and thread handle CloseHandleClear(FPI.hProcess); CloseHandleClear(FPI.hThread); // Close the pipe handles CloseStdPipes; end; finally // Reset the stopping flag FStopping := False; end; end; end; end; constructor TPipeClient.Create(AOwner: TComponent); begin // Perform inherited inherited Create(AOwner); // Set defaults InitializeSecurity(FSA); FKillEv := CreateEvent(@FSA, True, False, nil); FPipe := INVALID_HANDLE_VALUE; FDisconnecting := False; FBaseThread := GetCurrentThreadID; FThrottle := DEF_MEMTHROTTLE; FWriteQueue := TWriteQueue.Create; FWorker := nil; FPipeName := resPipeName; FServerName := EmptyStr; FHwnd := AllocateHWnd(WndMethod); end; constructor TPipeClient.CreateUnowned; begin // Perform create with no owner Create(nil); end; destructor TPipeClient.Destroy; begin // Resource protection try // Disconnect the pipe Disconnect; // Close the event handle CloseHandle(FKillEv); // Free the write queue FWriteQueue.Free; // Free memory resources FinalizeSecurity(FSA); // Deallocate the window handle DeallocateHWnd(FHwnd); finally // Perform inherited inherited Destroy; end; end; function TPipeClient.GetConnected: Boolean; var dwExit: DWORD; begin // Check worker thread if Assigned(FWorker) then // Check exit state result := GetExitCodeThread(FWorker.Handle, dwExit) and (dwExit = STILL_ACTIVE) else // Not connected result := False; end; function TPipeClient.Connect(WaitTime: DWORD = NMPWAIT_USE_DEFAULT_WAIT; Start: Boolean = True): Boolean; var szName: string; dwMode: DWORD; begin // Resource protection try // Check current connected state if not(GetConnected) then begin // Check existing pipe handle if IsHandle(FPipe) then begin // Check Start mode if Start then begin // Pipe was already created, start worker thread against it try // Create thread to handle the pipe IO FWorker := TPipeThread.Create(False, FHwnd, FBaseThread, FWriteQueue, nil, FPipe, FKillEv); // Resource protection try // Set the OnTerminate handler FWorker.OnTerminate := RemoveWorkerThread; finally; // Resume the thread FWorker.Start; end; except // Free the worker thread FreeAndNil(FWorker); // Close the pipe handle CloseHandleClear(FPipe); end; end; end else begin // Check name against local computer name first if (Length(FServerName) = 0) or (CompareText(ComputerName, FServerName) = 0) then // Set base local pipe name szName := resPipeBaseName + FPipeName else // Set base pipe name using specified server szName := Format(resPipeBaseFmtName, [FServerName]) + FPipeName; // Attempt to wait for the pipe first if WaitNamedPipe(PChar(szName), WaitTime) then begin // Attempt to create client side handle FPipe := CreateFile(PChar(szName), GENERIC_READ or GENERIC_WRITE, 0, @FSA, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED, 0); // Success if we have a valid handle if IsHandle(FPipe) then begin // Set the pipe read mode flags dwMode := PIPE_READMODE_MESSAGE or PIPE_WAIT; // Update the pipe SetNamedPipeHandleState(FPipe, dwMode, nil, nil); // Check Start mode if Start then begin // Resource protection try // Create thread to handle the pipe IO FWorker := TPipeThread.Create(False, FHwnd, FBaseThread, FWriteQueue, nil, FPipe, FKillEv); // Resource protection try // Set the OnTerminate handler FWorker.OnTerminate := RemoveWorkerThread; finally; // Resume the thread FWorker.Start; end; except // Free the worker thread FreeAndNil(FWorker); // Close the pipe handle CloseHandleClear(FPipe); end; end; end; end; end; end; finally // Check connected state, or valid handle result := GetConnected or IsHandle(FPipe); end; end; procedure TPipeClient.Disconnect; begin // Check connected state if (GetConnected and not(FDisconnecting)) then begin // Check to see if processing a message from another thread if InSendMessage then // Defered shutdown PostMessage(FHwnd, WM_DOSHUTDOWN, 0, 0) else begin // Set disconnecting flag FDisconnecting := True; // Resource protection try // Resource protection try // Check worker thread if Assigned(FWorker) then begin // Resource protection try // Signal the kill event for the thread SetEvent(FKillEv); finally // Wait for the thread to complete FWorker.Wait; end; end; finally // Clear pipe handle FPipe := INVALID_HANDLE_VALUE; end; finally // Toggle flag FDisconnecting := False; end; end; end // Check pipe handle else if IsHandle(FPipe) then // Close handle CloseHandleClear(FPipe); end; procedure TPipeClient.FlushPipeBuffers; var hEvent: THandle; begin // Make sure we are not being called from one of the events if not(InSendMessage) then begin // Get the event handle for the empty state hEvent := FWriteQueue.EmptyEvent; // While the worker thread is running while GetConnected do begin // Wait until the empty flag is set or we get a message case MsgWaitForMultipleObjects(1, hEvent, False, INFINITE, QS_SENDMESSAGE) of // Empty event is signalled WAIT_OBJECT_0: break; // Messages waiting to be read WAIT_OBJECT_0 + 1: FlushMessages; end; end; end; end; function TPipeClient.WaitForReply(TimeOut: Cardinal = INFINITE): Boolean; var lpMsg: TMsg; dwMark: LongWord; begin // Clear reply flag FReply := False; // Resource protection try // Make sure we are not being called from one of the events if not(InSendMessage) then begin // Get current tick count dwMark := GetTickCount; // Check connected state while not(FReply) and GetConnected do begin // Check for timeout if not(TimeOut = INFINITE) and ((GetTickCount - dwMark) >= TimeOut) then break; // Peek message from the queue if PeekMessage(lpMsg, 0, WM_PIPEMINMSG, WM_PIPEMAXMSG, PM_REMOVE) then begin // Translate the message TranslateMessage(lpMsg); // Dispatch the message DispatchMessage(lpMsg); end; end; end; finally // Is the reply flag set result := FReply; end; end; function TPipeClient.SendStream(Stream: TStream): Boolean; var lpszBuffer: PChar; dwRead: Integer; begin // Check stream and current state if Assigned(Stream) and GetConnected then begin // Set default result result := True; // Resource protection try // Enqueue the start packet FWriteQueue.EnqueueStartPacket; // Resource protection try // Allocate buffer for sending lpszBuffer := AllocMem(MAX_BUFFER); // Resource protection try // Set stream position Stream.Position := 0; // Queue the first read dwRead := Stream.Read(lpszBuffer^, MAX_BUFFER); // While data while (dwRead > 0) and result do begin // Write the data if Write(lpszBuffer^, dwRead) then // Seed next data dwRead := Stream.Read(lpszBuffer^, MAX_BUFFER) else // Failed to write the data result := False; end; finally // Free memory FreeMem(lpszBuffer); end; finally // Enqueue the end packet FWriteQueue.EnqueueEndPacket; end; finally // Flush the buffers FlushPipeBuffers; end; end else // Invalid param or state result := False; end; function TPipeClient.Write(var Prefix; PrefixCount: Integer; var Buffer; Count: Integer): Boolean; begin // Check for memory throttling if ((FThrottle > 0) and (FWriteQueue.DataSize > FThrottle) and GetConnected) then FlushPipeBuffers; // Check connected state if GetConnected then begin // Resource protection try // Queue the data FWriteQueue.Enqueue(AllocPipeWriteWithPrefix(Prefix, PrefixCount, Buffer, Count)); finally // Success result := True; end; end else // Not connected result := False; end; function TPipeClient.Write(var Buffer; Count: Integer): Boolean; begin // Check for memory throttling if ((FThrottle > 0) and (FWriteQueue.DataSize > FThrottle) and GetConnected) then FlushPipeBuffers; // Check connected state if GetConnected then begin // Resource protection try // Queue the data FWriteQueue.Enqueue(AllocPipeWrite(Buffer, Count)); finally // Success result := True; end; end else // Not connected result := False; end; procedure TPipeClient.SetPipeName(Value: string); begin // Check connected state and pipe handle if GetConnected or IsHandle(FPipe) then // Raise exception raise EPipeException.CreateRes(@resPipeConnected) else begin // Check the pipe name CheckPipeName(Value); // Set the pipe name FPipeName := Value; end; end; procedure TPipeClient.SetServerName(Value: string); begin // Check connected state and pipe handle if GetConnected or IsHandle(FPipe) then // Raise exception raise EPipeException.CreateRes(@resPipeConnected) else // Set the server name FServerName := Value; end; procedure TPipeClient.RemoveWorkerThread(Sender: TObject); begin // Set thread variable to nil FWorker := nil; // Resource protection try // Notify of disconnect if (not(csDestroying in ComponentState) and Assigned(FOPD)) then FOPD(Self, FPipe); // Clear the write queue FWriteQueue.Clear; finally // Invalidate handle FPipe := INVALID_HANDLE_VALUE; end; end; procedure TPipeClient.WndMethod(var Message: TMessage); begin // Handle the pipe messages case Message.Msg of // Pipe worker error WM_PIPEERROR_W: if Assigned(FOPE) then FOPE(Self, Message.wParam, pcWorker, Message.lParam); // Pipe data sent WM_PIPESEND: if Assigned(FOPS) then FOPS(Self, Message.wParam, Message.lParam); // Pipe data read WM_PIPEMESSAGE: begin // Set reply flag FReply := True; // Fire event if Assigned(FOPM) then FOPM(Self, Message.wParam, TStream(Pointer(Message.lParam))); end; // Raise exception WM_THREADCTX: raise EPipeException.CreateRes(@resThreadCtx); // Disconect WM_DOSHUTDOWN: Disconnect; else // Call default window procedure Message.result := DefWindowProc(FHwnd, Message.Msg, Message.wParam, Message.lParam); end; end; function TPipeClient.Write(const AStr: string): Boolean; var TempStr: string; begin TempStr := AStr; Result := Write(TempStr[1], Length(TempStr) * SizeOf(Char)); end; constructor TPipeServer.Create(AOwner: TComponent); begin // Perform inherited inherited Create(AOwner); // Initialize the security attributes InitializeSecurity(FSA); // Set staring defaults FHwnd := AllocateHWnd(WndMethod); FBaseThread := GetCurrentThreadID; FPipeName := resPipeName; FActive := False; FDeferActive := False; FInShutDown := False; FKillEv := CreateEvent(@FSA, True, False, nil); FClients := TList.Create; FThreadCount := TThreadCounter.Create; FListener := nil; end; constructor TPipeServer.CreateUnowned; begin // Perform inherited create with no owner Create(nil); end; destructor TPipeServer.Destroy; begin // Resource protection try // Perform the shutdown if active Active := False; // Close the event handle CloseHandle(FKillEv); // Free the clients list FClients.Free; // Free the thread counter FThreadCount.Free; // Cleanup memory FinalizeSecurity(FSA); // Deallocate the window DeallocateHWnd(FHwnd); finally // Perform inherited inherited Destroy; end; end; procedure TPipeServer.WndMethod(var Message: TMessage); begin // Handle the pipe messages case Message.Msg of // Listener thread error WM_PIPEERROR_L: if Assigned(FOPE) then FOPE(Self, Message.wParam, pcListener, Message.lParam); // Worker thread error WM_PIPEERROR_W: if Assigned(FOPE) then FOPE(Self, Message.wParam, pcWorker, Message.lParam); // Pipe connected WM_PIPECONNECT: if Assigned(FOPC) then FOPC(Self, Message.wParam); // Data message sent on pipe WM_PIPESEND: if Assigned(FOPS) then FOPS(Self, Message.wParam, Message.lParam); // Data message recieved on pipe WM_PIPEMESSAGE: if Assigned(FOPM) then FOPM(Self, Message.wParam, TStream(Pointer(Message.lParam))); // Raise exception WM_THREADCTX: raise EPipeException.CreateRes(@resThreadCtx); // Disconect WM_DOSHUTDOWN: Active := False; else // Call default window procedure Message.result := DefWindowProc(FHwnd, Message.Msg, Message.wParam, Message.lParam); end; end; function TPipeServer.GetClientInfo(Pipe: HPIPE; out PipeInfo: PPipeInfo): Boolean; var dwIndex: Integer; begin // Clear outbound param PipeInfo := nil; // Resource protection try // Locate the pipe info record for the given pipe first for dwIndex := Pred(FClients.Count) downto 0 do begin // Check pipe info pointer if (PPipeInfo(FClients[dwIndex])^.Pipe = Pipe) then begin // Found the record PipeInfo := PPipeInfo(FClients[dwIndex]); // Done processing break; end; end; finally // Success if we have the record result := Assigned(PipeInfo); end; end; function TPipeServer.GetClient(Index: Integer): HPIPE; begin // Return the requested pipe result := PPipeInfo(FClients[Index])^.Pipe; end; function TPipeServer.GetClientCount: Integer; begin // Return the number of client pipes result := FClients.Count; end; function TPipeServer.Broadcast(var Buffer; Count: Integer): Boolean; var dwIndex: Integer; dwCount: Integer; begin // Set count dwCount := 0; // Resource protection try // Iterate the pipes and write the data to each one for dwIndex := Pred(FClients.Count) downto 0 do begin // Fail if a write fails if Write(Clients[dwIndex], Buffer, Count) then // Update count Inc(dwCount) else // Failed, break out break; end; finally // Success if all pipes got the message result := (dwCount = FClients.Count); end; end; function TPipeServer.Broadcast(var Prefix; PrefixCount: Integer; var Buffer; Count: Integer): Boolean; var dwIndex: Integer; dwCount: Integer; begin // Set count dwCount := 0; // Resource protection try // Iterate the pipes and write the data to each one for dwIndex := Pred(FClients.Count) downto 0 do begin // Fail if a write fails if Write(Clients[dwIndex], Prefix, PrefixCount, Buffer, Count) then // Update count Inc(dwCount) else // Failed, break out break; end; finally // Success if all pipes got the message result := (dwCount = FClients.Count); end; end; function TPipeServer.Write(Pipe: HPIPE; var Prefix; PrefixCount: Integer; var Buffer; Count: Integer): Boolean; var ppiClient: PPipeInfo; begin // Get the pipe info if GetClientInfo(Pipe, ppiClient) then begin // Queue the data ppiClient.WriteQueue.Enqueue(AllocPipeWriteWithPrefix(Prefix, PrefixCount, Buffer, Count)); // Success result := True; end else // No client info result := False; end; function TPipeServer.Write(Pipe: HPIPE; var Buffer; Count: Integer): Boolean; var ppiClient: PPipeInfo; begin // Get the pipe info if GetClientInfo(Pipe, ppiClient) then begin // Queue the data ppiClient.WriteQueue.Enqueue(AllocPipeWrite(Buffer, Count)); // Success result := True; end else // No client info result := False; end; function TPipeServer.SendStream(Pipe: HPIPE; Stream: TStream): Boolean; var ppiClient: PPipeInfo; lpszBuffer: PChar; dwRead: Integer; begin // Check stream and current state if Assigned(Stream) and GetClientInfo(Pipe, ppiClient) then begin // Resource protection try // Enqueue the start packet ppiClient^.WriteQueue.EnqueueStartPacket; // Resource protection try // Allocate buffer for sending lpszBuffer := AllocMem(MAX_BUFFER); // Resource protection try // Set stream position Stream.Position := 0; // Queue the first read dwRead := Stream.Read(lpszBuffer^, MAX_BUFFER); // While data while (dwRead > 0) do begin // Enqueue the data ppiClient^.WriteQueue.Enqueue(AllocPipeWrite(lpszBuffer^, dwRead)); // Seed next data dwRead := Stream.Read(lpszBuffer^, MAX_BUFFER) end; finally // Free memory FreeMem(lpszBuffer); end; finally // Enqueue the end packet ppiClient^.WriteQueue.EnqueueEndPacket; end; finally // Set default result result := True; end; end else // Invalid param or state result := False; end; procedure TPipeServer.RemoveClient(Pipe: HPIPE); var ppiClient: PPipeInfo; begin // Attempt to get the pipe info if GetClientInfo(Pipe, ppiClient) then begin // Remove from the client list FClients.Remove(ppiClient); // Resource protection try // Resource protection try // Free the write queue ppiClient^.WriteQueue.Free; // Close the event handle CloseHandle(ppiClient^.KillEvent); finally // Free the client record FreeMem(ppiClient); end; finally // Call the OnDisconnect if assigned and not destroying if not(csDestroying in ComponentState) and Assigned(FOPD) then FOPD(Self, Pipe); end; end; end; function TPipeServer.Disconnect(Pipe: HPIPE): Boolean; var ppiClient: PPipeInfo; dwIndex: Integer; begin // Set default result result := True; // Check pipe passed in if (Pipe = 0) then begin // Disconnect all for dwIndex := Pred(FClients.Count) downto 0 do begin // Signal the kill event SetEvent(PPipeInfo(FClients[dwIndex])^.KillEvent); end; end // Get the specifed pipe info else if GetClientInfo(Pipe, ppiClient) then // Set the kill event SetEvent(ppiClient^.KillEvent) else // Failed to locate the pipe result := False; end; procedure TPipeServer.Loaded; begin // Perform inherited inherited; // Set deferred active state SetActive(FDeferActive); end; procedure TPipeServer.SetActive(Value: Boolean); begin // Check against current state if not(FActive = Value) then begin // Check loaded state if (csLoading in ComponentState) then // Set deferred state FDeferActive := Value // Check designing state. The problem is that in the IDE, a count on the // handle will be left open and cause us issues with client connections when // running in debugger. else if (csDesigning in ComponentState) then // Just update the value FActive := Value else if (Value) then // Perform startup DoStartup else // Perform shutdown DoShutdown; end; end; procedure TPipeServer.SetPipeName(Value: string); begin // Check for change if not(Value = FPipeName) then begin // Check active state if FActive then // Cannot change pipe name if pipe server is active raise EPipeException.CreateRes(@resPipeActive) else begin // Check the pipe name CheckPipeName(Value); // Set the new pipe name FPipeName := Value; end; end; end; function TPipeServer.AllocPipeInfo(Pipe: HPIPE): PPipeInfo; begin // Create a new pipe info structure to manage the pipe result := AllocMem(SizeOf(TPipeInfo)); // Resource protection try // Set the pipe value result^.Pipe := Pipe; // Create the write queue result^.WriteQueue := TWriteQueue.Create; // Create individual kill events result^.KillEvent := CreateEvent(nil, True, False, nil); finally // Add to client list FClients.Add(result); end; end; procedure TPipeServer.AddWorkerThread(Pipe: HPIPE); var pstWorker: TPipeThread; ppInfo: PPipeInfo; begin // Set worker thread pstWorker := nil; // Create a new pipe info structure to manage the pipe ppInfo := AllocPipeInfo(Pipe); // Resource protection try // Create the server worker thread pstWorker := TPipeThread.Create(True, FHwnd, FBaseThread, ppInfo^.WriteQueue, FThreadCount, Pipe, ppInfo^.KillEvent); // Resource protection try // Set the OnTerminate handler pstWorker.OnTerminate := RemoveWorkerThread; finally // Resume the thread pstWorker.Start; end; except // Exception during thread create, remove the client record RemoveClient(Pipe); // Disconnect and close the pipe handle DisconnectAndClose(Pipe); // Free the worker thread object FreeAndNil(pstWorker); end; end; procedure TPipeServer.RemoveWorkerThread(Sender: TObject); begin // Remove the pipe info record associated with this thread RemoveClient(TPipeThread(Sender).Pipe); end; procedure TPipeServer.RemoveListenerThread(Sender: TObject); begin // Nil the thread var FListener := nil; // If we are not in a shutdown and are the only thread, then change the active state if (not(FInShutDown) and (FThreadCount.Count = 1)) then FActive := False; end; procedure TPipeServer.DoStartup; begin // Check active state if not(FActive) then begin // Make sure the kill event is in a non-signaled state ResetEvent(FKillEv); // Resource protection try // Create the listener thread FListener := TPipeListenThread.Create(Self, FKillEv); // Resource protection try // Set the OnTerminate handler FListener.OnTerminate := RemoveListenerThread; finally // Resume FListener.Start; end; except // Free the listener thread FreeAndNil(FListener); // Re-raise the exception raise; end; // Set active state FActive := True; end; end; procedure TPipeServer.DoShutdown; begin // If we are not active then exit if FActive and not(FInShutDown) then begin // Check in message flag if InSendMessage then // Defered shutdown PostMessage(FHwnd, WM_DOSHUTDOWN, 0, 0) else begin // Set shutdown flag FInShutDown := True; // Resource protection try // Resource protection try // Signal the kill event for the listener thread SetEvent(FKillEv); // Disconnect all Disconnect(0); // Wait until threads have finished up FThreadCount.WaitForEmpty; finally // Reset active state FActive := False; end; finally // Set active state to false FInShutDown := False; end; end; end; end; constructor TPipeThread.Create(Server: Boolean; NotifyWindow: HWND; NotifyThread: THandle; WriteQueue: TWriteQueue; Counter: TThreadCounter; Pipe: HPIPE; KillEvent: THandle); begin // Perform inherited create (suspended) inherited Create(True); // Increment the thread counter if assigned // statement changed 1-12-2013 // if Assigned(FCounter) then // FCounter.Increment; if Assigned(Counter) then Counter.Increment; // Set initial state FServer := Server; FNotify := NotifyWindow; FNotifyThread := NotifyThread; FWriteQueue := WriteQueue; FCounter := Counter; FPipe := Pipe; FErrorCode := ERROR_SUCCESS; FPendingRead := False; FPendingWrite := False; FPipeWrite := nil; FMultiMsg := nil; FRcvSize := MAX_BUFFER; FRcvAlloc := MAX_BUFFER; FRcvBuffer := AllocMem(FRcvAlloc); FRcvStream := TFastMemStream.Create; ClearOverlapped(FOlapRead, True); ClearOverlapped(FOlapWrite, True); FOlapRead.hEvent := CreateEvent(nil, True, False, nil); FOlapWrite.hEvent := CreateEvent(nil, True, False, nil); ResetEvent(KillEvent); FEvents[0] := KillEvent; FEvents[1] := FOlapRead.hEvent; FEvents[2] := FOlapWrite.hEvent; FEvents[3] := FWriteQueue.DataEvent; // Set thread parameters FreeOnTerminate := True; Priority := tpLower; end; destructor TPipeThread.Destroy; begin // Resource protection try // Resource protection try // Free the write buffer we may be holding on to DisposePipeWrite(FPipeWrite); // Free the receiver stream FRcvStream.Free; // Free buffer memory FreeMem(FRcvBuffer); finally // Decrement the thread counter if assigned if Assigned(FCounter) then FCounter.Decrement; end; finally // Perform inherited inherited Destroy; end; end; function TPipeThread.SafeSendMessage(Msg: Cardinal; wParam, lParam: Integer): LRESULT; begin // Check notification window if IsWindow(FNotify) then // Send the message result := SendMessage(FNotify, Msg, wParam, lParam) else // Failure result := 0; end; function TPipeThread.QueuedRead: Boolean; begin // Resource protection try // If we already have a pending read then nothing to do if not(FPendingRead) then begin // Set buffer size FRcvSize := FRcvAlloc; // Keep reading all available data until we get a pending read or a failure while not(FPendingRead) do begin // Set overlapped fields ClearOverlapped(FOlapRead); // Perform a read if ReadFile(FPipe, FRcvBuffer^, FRcvSize, FRcvRead, @FOlapRead) then begin // Resource protection try // We read a full message FRcvStream.Write(FRcvBuffer^, FRcvRead); // Call the OnData DoMessage; finally // Reset the read event ResetEvent(FOlapRead.hEvent); end; end else begin // Get the last error code FErrorCode := GetLastError; // Handle cases where message is larger than read buffer used if (FErrorCode = ERROR_MORE_DATA) then begin // Write the current data FRcvStream.Write(FRcvBuffer^, FRcvSize); // Determine how much we need to expand the buffer to if PeekNamedPipe(FPipe, nil, 0, nil, nil, @FRcvSize) then begin // Determine if required size is larger than allocated size if (FRcvSize > FRcvAlloc) then begin // Realloc buffer ReallocMem(FRcvBuffer, FRcvSize); // Update allocated size FRcvAlloc := FRcvSize; end; end else begin // Failure FErrorCode := GetLastError; // Done break; end; end // Pending read else if (FErrorCode = ERROR_IO_PENDING) then // Set pending flag FPendingRead := True else // Failure break; end; end; end; finally // Success if we have a pending read result := FPendingRead; end; end; function TPipeThread.CompleteRead: Boolean; begin // Reset the read event and pending flag ResetEvent(FOlapRead.hEvent); // Reset pending read FPendingRead := False; // Check the overlapped results result := GetOverlappedResult(FPipe, FOlapRead, FRcvRead, True); // Handle failure if not(result) then begin // Get the last error code FErrorCode := GetLastError; // Check for more data if (FErrorCode = ERROR_MORE_DATA) then begin // Write the current data to the stream FRcvStream.Write(FRcvBuffer^, FRcvSize); // Determine how much we need to expand the buffer to result := PeekNamedPipe(FPipe, nil, 0, nil, nil, @FRcvSize); // Check result if result then begin // Determine if required size is larger than allocated size if (FRcvSize > FRcvAlloc) then begin // Realloc buffer ReallocMem(FRcvBuffer, FRcvSize); // Update allocated size FRcvAlloc := FRcvSize; end; // Set overlapped fields ClearOverlapped(FOlapRead); // Read from the file again result := ReadFile(FPipe, FRcvBuffer^, FRcvSize, FRcvRead, @FOlapRead); // Handle error if not(result) then begin // Set error code FErrorCode := GetLastError; // Check for pending again, which means our state hasn't changed if (FErrorCode = ERROR_IO_PENDING) then begin // Still a pending read FPendingRead := True; // Success result := True; end; end; end else // Set error code FErrorCode := GetLastError; end; end; // Check result and pending read flag if result and not(FPendingRead) then begin // We have the full message FRcvStream.Write(FRcvBuffer^, FRcvRead); // Call the OnData DoMessage; end; end; function TPipeThread.QueuedWrite: Boolean; var bWrite: Boolean; begin // Set default result result := True; // Check pending state if not(FPendingWrite) then begin // Check state of data event if (WaitForSingleObject(FEvents[3], 0) = WAIT_OBJECT_0) then begin // Dequeue write block FPipeWrite := FWriteQueue.Dequeue; // Is the record assigned? if Assigned(FPipeWrite) then begin // Set overlapped fields ClearOverlapped(FOlapWrite); // Write the data to the client bWrite := WriteFile(FPipe, FPipeWrite^.Buffer^, FPipeWrite^.Count, FWrite, @FOlapWrite); // Get the last error code FErrorCode := GetLastError; // Check the write operation if bWrite then begin // Resource protection try // Flush the pipe FlushFileBuffers(FPipe); // Call the OnData in the main thread SafeSendMessage(WM_PIPESEND, FPipe, FWrite); // Free the pipe write data DisposePipeWrite(FPipeWrite); finally // Reset the write event ResetEvent(FOlapWrite.hEvent); end; end // Only acceptable error is pending else if (FErrorCode = ERROR_IO_PENDING) then // Set pending flag FPendingWrite := True else // Failure result := False; end; end else // No data to write result := True; end; end; function TPipeThread.CompleteWrite: Boolean; begin // Reset the write event and pending flag ResetEvent(FOlapWrite.hEvent); // Resource protection try // Check the overlapped results result := GetOverlappedResult(FPipe, FOlapWrite, FWrite, True); // Resource protection try // Handle failure if not(result) then // Get the last error code FErrorCode := GetLastError else begin // Flush the pipe FlushFileBuffers(FPipe); // We sent a full message so call the OnSent in the main thread SafeSendMessage(WM_PIPESEND, FPipe, FWrite); end; finally // Make sure to free the queued pipe data DisposePipeWrite(FPipeWrite); end; finally // Reset pending flag FPendingWrite := False; end; end; procedure TPipeThread.DoMessage; var lpControlMsg: PPipeMsgBlock; begin // Rewind the stream FRcvStream.Position := 0; // Resource protection try // Check the data to see if this is a multi part message if (FRcvStream.Size = SizeOf(TPipeMsgBlock)) then begin // Cast memory as control message lpControlMsg := PPipeMsgBlock(FRcvStream.Memory); // Check constants if (lpControlMsg^.Size = SizeOf(TPipeMsgBlock)) and (lpControlMsg^.MagicStart = MB_MAGIC) and (lpControlMsg^.MagicEnd = MB_MAGIC) then begin // Check to see if this is a start if (lpControlMsg^.ControlCode = MB_START) then begin // Free existing multi part message FreeAndNil(FMultiMsg); // Create new multi part message FMultiMsg := TPipeMultiMsg.Create; end // Check to see if this is an end else if (lpControlMsg^.ControlCode = MB_END) then begin // The multi part message must be assigned if Assigned(FMultiMsg) then begin // Resource protection try // Rewind the stream FMultiMsg.Stream.Position := 0; // Send the message to the notification window SafeSendMessage(WM_PIPEMESSAGE, FPipe, Integer(FMultiMsg.Stream)); finally // Free the multi part message FreeAndNil(FMultiMsg); end; end; end else // Unknown code FreeAndNil(FMultiMsg); end else begin // Check for multi part message packet if Assigned(FMultiMsg) then // Add data to existing stream FMultiMsg.Stream.Write(FRcvStream.Memory^, FRcvStream.Size) else // Send the message to the notification window SafeSendMessage(WM_PIPEMESSAGE, FPipe, Integer(FRcvStream)); end; end // Check to see if we are in a multi part message else if Assigned(FMultiMsg) then // Add data to existing stream FMultiMsg.Stream.Write(FRcvStream.Memory^, FRcvStream.Size) else // Send the message to the notification window SafeSendMessage(WM_PIPEMESSAGE, FPipe, Integer(FRcvStream)); finally // Clear the read stream FRcvStream.Clear; end; end; procedure TPipeThread.Execute; var dwEvents: Integer; bOK: Boolean; begin // Resource protection try // Check sync base thread against the component main thread if not(Sync.SyncBaseTID = FNotifyThread) then // Post message to main window and we are done PostMessage(FNotify, WM_THREADCTX, 0, 0) else begin // Notify the pipe server of the connect if FServer then SafeSendMessage(WM_PIPECONNECT, FPipe, 0); // Loop while not terminated while not(Terminated) do begin // Make sure we always have an outstanding read and write queued up bOK := (QueuedRead and QueuedWrite); // Relinquish time slice Sleep(0); // Check current queue state if bOK then begin // Set number of events to wait on dwEvents := 4; // If a write is pending, then don't wait on the write queue data event if FPendingWrite then Dec(dwEvents); // Handle the event that was signalled (or failure) case WaitForMultipleObjects(dwEvents, @FEvents, False, INFINITE) of // Killed by pipe server WAIT_OBJECT_0: begin // Resource protection try // Finish any final read / write (allow them a small delay to finish up) if FPendingWrite and (WaitForSingleObject(FEvents[2], DEF_SLEEP) = WAIT_OBJECT_0) then CompleteWrite; if FPendingRead and (WaitForSingleObject(FEvents[1], DEF_SLEEP) = WAIT_OBJECT_0) then CompleteRead; finally // Terminate the thread Terminate; end; end; // Read completed WAIT_OBJECT_0 + 1: bOK := CompleteRead; // Write completed WAIT_OBJECT_0 + 2: bOK := CompleteWrite; // Data waiting to be sent WAIT_OBJECT_0 + 3: ; else // General failure FErrorCode := GetLastError; // Set status bOK := False; end; end; // Check status if not(bOK) then begin // Call OnError in the main thread if this is not a disconnect. Disconnects // have their own event, and are not to be considered an error if not(FErrorCode = ERROR_BROKEN_PIPE) then SafeSendMessage(WM_PIPEERROR_W, FPipe, FErrorCode); // Terminate the thread Terminate; end; end; end; finally // Disconnect and close the pipe handle at this point DisconnectAndClose(FPipe, FServer); // Close all open handles that we own CloseHandle(FOlapRead.hEvent); CloseHandle(FOlapWrite.hEvent); end; end; /// / TPipeListenThread /// ////////////////////////////////////////////////////// constructor TPipeListenThread.Create(PipeServer: TPipeServer; KillEvent: THandle); begin // Perform inherited create (suspended) inherited Create(True); // Set starting parameters FreeOnTerminate := True; Priority := tpLower; FPipeServer := PipeServer; // Increment the thread counter FPipeServer.FThreadCount.Increment; // *** 2010-12-01: MMC -- Moved this line from just after the "inherited Create(TRUE)" to after the assignment has been made to the property FNotifyThread := FPipeServer.FBaseThread; FPipeName := PipeServer.PipeName; FNotify := PipeServer.WindowHandle; InitializeSecurity(FSA); FPipe := INVALID_HANDLE_VALUE; FConnected := False; FillChar(FOlapConnect, SizeOf(FOlapConnect), 0); FOlapConnect.hEvent := CreateEvent(@FSA, True, False, nil);; FEvents[0] := KillEvent; FEvents[1] := FOlapConnect.hEvent; end; destructor TPipeListenThread.Destroy; begin // Resource protection try // Resource protection try // Close the connect event handle CloseHandle(FOlapConnect.hEvent); // Disconnect and free the handle if IsHandle(FPipe) then begin // Check connected state if FConnected then // Disconnect and close DisconnectAndClose(FPipe) else // Just close the handle CloseHandle(FPipe); end; // Release memory for security structure FinalizeSecurity(FSA); finally // Decrement the thread counter FPipeServer.FThreadCount.Decrement; end; finally // Perform inherited inherited Destroy; end; end; function TPipeListenThread.CreateServerPipe: Boolean; begin // Create the outbound pipe first FPipe := CreateNamedPipe(PChar(resPipeBaseName + FPipeName), PIPE_OPENMODE, PIPE_MODE, PIPE_INSTANCES, 0, 0, 1000, @FSA); // Resource protection try // Set result value based on valid handle if IsHandle(FPipe) then // Success FErrorCode := ERROR_SUCCESS else // Get last error FErrorCode := GetLastError; finally // Success if handle is valid result := IsHandle(FPipe); end; end; procedure TPipeListenThread.DoWorker; begin // Call the pipe server on the main thread to add a new worker thread FPipeServer.AddWorkerThread(FPipe); end; function TPipeListenThread.SafeSendMessage(Msg: Cardinal; wParam, lParam: Integer): LRESULT; begin // Check notify window handle if IsWindow(FNotify) then // Send the message result := SendMessage(FNotify, Msg, wParam, lParam) else // Not a window result := 0; end; procedure TPipeListenThread.Execute; begin // Check sync base thread against the component main thread if not(Sync.SyncBaseTID = FNotifyThread) then // Post message to main window and we are done PostMessage(FNotify, WM_THREADCTX, 0, 0) else begin // Thread body while not(Terminated) do begin // Set default state FConnected := False; // Attempt to create first pipe server instance if CreateServerPipe then begin // Connect the named pipe FConnected := ConnectNamedPipe(FPipe, @FOlapConnect); // Handle failure if not(FConnected) then begin // Check the last error code FErrorCode := GetLastError; // Is pipe connected? if (FErrorCode = ERROR_PIPE_CONNECTED) then // Set connected state FConnected := True // IO pending? else if (FErrorCode = ERROR_IO_PENDING) then begin // Wait for a connect or kill signal case WaitForMultipleObjects(2, @FEvents, False, INFINITE) of WAIT_FAILED: FErrorCode := GetLastError; WAIT_OBJECT_0: Terminate; WAIT_OBJECT_0 + 1: FConnected := True; end; end; end; end; // If we are not connected at this point then we had a failure if not(FConnected) then begin // Resource protection try // No error if terminated or client connects / disconnects (no data) if not(Terminated or (FErrorCode = ERROR_NO_DATA)) then SafeSendMessage(WM_PIPEERROR_L, FPipe, FErrorCode); finally // Close and clear CloseHandleClear(FPipe); end; end else // Notify server of connect Synchronize(DoWorker); end; end; end; /// / TThreadCounter /// ///////////////////////////////////////////////////////// constructor TThreadCounter.Create; begin // Perform inherited inherited Create; // Create critical section lock InitializeCriticalSection(FLock); // Create event for empty state FEmpty := CreateEvent(nil, True, True, nil); // Set the starting count FCount := 0; end; destructor TThreadCounter.Destroy; begin // Resource protection try // Close the event handle CloseHandleClear(FEmpty); // Delete the critical section DeleteCriticalSection(FLock); finally // Perform inherited inherited Destroy; end; end; function TThreadCounter.GetCount: Integer; begin // Enter critical section EnterCriticalSection(FLock); // Resource protection try // Return the count result := FCount; finally // Leave the critical section LeaveCriticalSection(FLock); end; end; procedure TThreadCounter.Increment; begin // Enter critical section EnterCriticalSection(FLock); // Resource protection try // Increment the count Inc(FCount); // Reset the empty event ResetEvent(FEmpty); finally // Leave the critical section LeaveCriticalSection(FLock); end; end; procedure TThreadCounter.Decrement; begin // Enter critical section EnterCriticalSection(FLock); // Resource protection try // Decrement the count if (FCount > 0) then Dec(FCount); // Signal empty event if count is zero if (FCount = 0) then SetEvent(FEmpty); finally // Leave the critical section LeaveCriticalSection(FLock); end; end; procedure TThreadCounter.WaitForEmpty; begin // Wait until the empty event is signalled while (MsgWaitForMultipleObjects(1, FEmpty, False, INFINITE, QS_SENDMESSAGE) = WAIT_OBJECT_0 + 1) do begin // Messages waiting to be read FlushMessages; end; end; /// / TWriteQueue /// //////////////////////////////////////////////////////////// constructor TWriteQueue.Create; begin // Perform inherited inherited Create; // Set defaults FHead := nil; FTail := nil; FMutex := 0; FDataEv := 0; FDataSize := 0; FEmptyEv := 0; // Create mutex to allow for single access into the write queue FMutex := CreateMutex(nil, False, nil); // Check mutex handle if (FMutex = 0) then // Raise exception RaiseWindowsError else begin // Create event to signal when we have data to write FDataEv := CreateEvent(nil, True, False, nil); // Check event handle if (FDataEv = 0) then // Raise exception RaiseWindowsError else begin // Create event to signal when the queue becomes empty FEmptyEv := CreateEvent(nil, True, True, nil); // Check event handle, raise exception on failure if (FEmptyEv = 0) then RaiseWindowsError; end; end; end; destructor TWriteQueue.Destroy; begin // Resource protection try // Clear Clear; // Close the data event handle CloseHandleClear(FDataEv); // Close the empty event handle CloseHandleClear(FEmptyEv); // Close the mutex handle CloseHandleClear(FMutex); finally // Perform inherited inherited Destroy; end; end; function TWriteQueue.GetEmpty: Boolean; begin // Determine if queue is empty result := (FHead = nil); end; procedure TWriteQueue.Clear; var lpNode: PWriteNode; begin // Access the mutex WaitForSingleObject(FMutex, INFINITE); // Resource protection try // Reset the writer event ResetEvent(FDataEv); // Resource protection try // Resource protection try // Free all the items in the stack while Assigned(FHead) do begin // Get the head node and push forward lpNode := FHead; // Resource protection try // Update head FHead := lpNode^.NextNode; // Free the pipe write data DisposePipeWrite(lpNode^.PipeWrite); finally // Free the queued node FreeMem(lpNode); end; end; finally // Clear the tail FTail := nil; // Reset the data size FDataSize := 0; end; finally // Signal the empty event SetEvent(FEmptyEv); end; finally // Release the mutex ReleaseMutex(FMutex); end; end; function TWriteQueue.NodeSize(Node: PWriteNode): LongWord; begin // Result is at least size of TWriteNode plus allocator size result := SizeOf(TWriteNode) + SizeOf(Integer); // Check pipe write if Assigned(Node^.PipeWrite) then begin // Include the pipe write structure Inc(result, SizeOf(TPipeWrite) + SizeOf(Integer)); // Include the pipe write data count Inc(result, Node^.PipeWrite^.Count + SizeOf(Integer)); end; end; function TWriteQueue.NewNode(PipeWrite: PPipeWrite): PWriteNode; begin // Allocate memory for new node GetMem(result, SizeOf(TWriteNode)); // Resource protection try // Set the pipe write field result^.PipeWrite := PipeWrite; // Update the data count Inc(FDataSize, NodeSize(result)); finally // Make sure the next link is nil result^.NextNode := nil; end; end; procedure TWriteQueue.EnqueueControlPacket(ControlCode: DWORD); var lpControlMsg: TPipeMsgBlock; begin // Access the mutex WaitForSingleObject(FMutex, INFINITE); // Resource protection try // Set control message constants lpControlMsg.Size := SizeOf(TPipeMsgBlock); lpControlMsg.MagicStart := MB_MAGIC; lpControlMsg.MagicEnd := MB_MAGIC; // Set end control message lpControlMsg.ControlCode := ControlCode; // Create pipe write and queue the data Enqueue(AllocPipeWrite(lpControlMsg, SizeOf(TPipeMsgBlock))); finally // Release the mutex ReleaseMutex(FMutex); end; end; procedure TWriteQueue.EnqueueEndPacket; begin // Enqueue the start EnqueueControlPacket(MB_END); end; procedure TWriteQueue.EnqueueStartPacket; begin // Enqueue the start EnqueueControlPacket(MB_START); end; procedure TWriteQueue.EnqueueMultiPacket(PipeWrite: PPipeWrite); var lpData: PChar; dwSize: Integer; begin // Access the mutex WaitForSingleObject(FMutex, INFINITE); // Resource protection try // Resource protection try // Resource protection try // Enqueue the start packet EnqueueStartPacket; // Get pointer to pipe write data lpData := PipeWrite^.Buffer; // While count of data to move while (PipeWrite^.Count > 0) do begin // Determine packet size if (PipeWrite^.Count > MAX_BUFFER) then // Full packet size dwSize := MAX_BUFFER else // Final packet dwSize := PipeWrite^.Count; // Resource protection try // Create pipe write and queue the data Enqueue(AllocPipeWrite(lpData^, dwSize)); // Increment the data pointer Inc(lpData, dwSize); finally // Decrement the remaining count Dec(PipeWrite^.Count, dwSize); end; end; finally // Enqueue the end packet EnqueueEndPacket; end; finally // Dispose of the original pipe write DisposePipeWrite(PipeWrite); end; finally // Release the mutex ReleaseMutex(FMutex); end; end; procedure TWriteQueue.UpdateState; begin // Check head node if Assigned(FHead) then begin // Signal data event SetEvent(FDataEv); // Reset empty event ResetEvent(FEmptyEv); end else begin // Reset data event ResetEvent(FDataEv); // Signal empty event SetEvent(FEmptyEv); end; end; procedure TWriteQueue.Enqueue(PipeWrite: PPipeWrite); var lpNode: PWriteNode; begin // Access the mutex WaitForSingleObject(FMutex, INFINITE); // Resource protection try // Check pipe write if Assigned(PipeWrite) then begin // Resource protection try // Check count of bytes in the pipe write record if (PipeWrite^.Count > MAX_BUFFER) then // Need to create multi packet message EnqueueMultiPacket(PipeWrite) else begin // Create a new node lpNode := NewNode(PipeWrite); // Resource protection try // Make this the last item in the queue if Assigned(FTail) then // Update the next node FTail^.NextNode := lpNode else // Set the head node FHead := lpNode; finally // Update the new tail FTail := lpNode; end; end; finally // Update event state UpdateState; end; end; finally // Release the mutex ReleaseMutex(FMutex); end; end; function TWriteQueue.Dequeue: PPipeWrite; var lpNode: PWriteNode; begin // Access the mutex WaitForSingleObject(FMutex, INFINITE); // Resource protection try // Resource protection try // Remove the first item from the queue if Assigned(FHead) then begin // Get head node lpNode := FHead; // Update the data count Dec(FDataSize, NodeSize(lpNode)); // Resource protection try // Set the return data result := lpNode^.PipeWrite; // Does head = Tail? if (FHead = FTail) then FTail := nil; // Update the head FHead := lpNode^.NextNode; finally // Free the memory for the node FreeMem(lpNode); end; end else // No queued data result := nil; finally // Update state UpdateState; end; finally // Release the mutex ReleaseMutex(FMutex); end; end; /// / TPipeMultiMsg /// ////////////////////////////////////////////////////////// procedure TPipeMultiMsg.CreateTempBacking; var lpszPath: array [0 .. MAX_PATH] of Char; lpszFile: array [0 .. MAX_PATH] of Char; begin // Resource protection try // Attempt to get temp file if (GetTempPath(MAX_PATH, lpszPath) > 0) and (GetTempFileName(@lpszPath, MB_PREFIX, 0, @lpszFile) > 0) then // Open the temp file FHandle := CreateFile(@lpszFile, GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0) else // Failed to get temp filename FHandle := INVALID_HANDLE_VALUE; finally // If we failed to open a temp file then we will use memory for data backing if IsHandle(FHandle) then // Create handle stream FStream := THandleStream.Create(FHandle) else // Create fast memory stream FStream := TFastMemStream.Create; end; end; constructor TPipeMultiMsg.Create; begin // Perform inherited inherited Create; // Create temp file backing CreateTempBacking; end; destructor TPipeMultiMsg.Destroy; begin // Resource protection try // Free the stream FreeAndNil(FStream); // Close handle if open if IsHandle(FHandle) then CloseHandle(FHandle); finally // Perform inherited inherited Destroy; end; end; /// / TFastMemStream /// ///////////////////////////////////////////////////////// function TFastMemStream.Realloc(var NewCapacity: Longint): Pointer; var dwDelta: Integer; lpMemory: Pointer; begin // Get current memory pointer lpMemory := Memory; // Resource protection try // Calculate the delta to be applied to the capacity if (NewCapacity > 0) then begin // Check new capacity if (NewCapacity > MaxWord) then // Delta is 1/4 of desired capacity dwDelta := NewCapacity div 4 else // Minimum allocation of 64 KB dwDelta := MaxWord; // Update by delta Inc(NewCapacity, dwDelta); end; // Determine if capacity has changed if not(NewCapacity = Capacity) then begin // Check for nil alloc if (NewCapacity = 0) then begin // Release the memory FreeMem(lpMemory); // Clear result lpMemory := nil; end else begin // Check current capacity if (Capacity = 0) then // Allocate memory lpMemory := AllocMem(NewCapacity) else // Reallocate memory ReallocMem(lpMemory, NewCapacity); end; end; finally // Return modified pointer result := lpMemory; end; end; /// / Thread window procedure /// //////////////////////////////////////////////// function ThreadWndProc(Window: HWND; Message, wParam, lParam: Longint) : Longint; stdcall; begin // Handle the window message case Message of // Exceute the method in thread CM_EXECPROC: begin // The lParam constains the thread sync information with TThreadSync(lParam) do begin // Set message result result := 0; // Exception trap try // Clear the exception FSyncRaise := nil; // Call the method FMethod; except FSyncRaise := AcquireExceptionObject; end; end; end; // Thead destroying CM_DESTROYWINDOW: begin // Get instance of sync manager TSyncManager.Instance.DoDestroyWindow(TSyncInfo(lParam)); // Set message result result := 0; end; else // Call the default window procedure result := DefWindowProc(Window, Message, wParam, lParam); end; end; /// / TSyncManager /// /////////////////////////////////////////////////////////// constructor TSyncManager.Create; begin // Perform inherited inherited Create; // Initialize the critical section InitializeCriticalSection(FThreadLock); // Create the info list FList := TList.Create; end; destructor TSyncManager.Destroy; var dwIndex: Integer; begin // Resource protection try // Free all info records for dwIndex := Pred(FList.Count) downto 0 do FreeSyncInfo(TSyncInfo(FList[dwIndex])); // Free the list FList.Free; // Delete the critical section DeleteCriticalSection(FThreadLock); finally // Call inherited inherited Destroy; end; end; class function TSyncManager.Instance: TSyncManager; begin // Enter critical section EnterCriticalSection(InstCritSect); // Resource protection try // Check global instance, create if needed if (SyncManager = nil) then SyncManager := TSyncManager.Create; // Return instance of sync manager result := SyncManager finally // Leave critical section LeaveCriticalSection(InstCritSect); end; end; function TSyncManager.AllocateWindow: HWND; var clsTemp: TWndClass; bClassReg: Boolean; begin // Set instance handle ThreadWndClass.hInstance := hInstance; ThreadWndClass.lpfnWndProc := @ThreadWndProc; // Attempt to get class info bClassReg := GetClassInfo(hInstance, ThreadWndClass.lpszClassName, clsTemp); // Ensure the class is registered and the window procedure is the default window proc if not(bClassReg) or not(clsTemp.lpfnWndProc = @ThreadWndProc) then begin // Unregister if already registered if bClassReg then Winapi.Windows.UnregisterClass(ThreadWndClass.lpszClassName, hInstance); // Register Winapi.Windows.RegisterClass(ThreadWndClass); end; // Create the thread window result := CreateWindowEx(0, ThreadWndClass.lpszClassName, '', 0, 0, 0, 0, 0, 0, 0, hInstance, nil); end; procedure TSyncManager.AddThread(ThreadSync: TThreadSync); var lpInfo: TSyncInfo; begin // Enter critical section EnterCriticalSection(FThreadLock); // Resource protection try // Find the info using the base thread id lpInfo := FindSyncInfo(ThreadSync.SyncBaseTID); // Resource protection try // Check assignment if (lpInfo = nil) then begin // Create new info record lpInfo := TSyncInfo.Create; // Set base thread id lpInfo.FSyncBaseTID := ThreadSync.SyncBaseTID; // Add info to list FList.Add(lpInfo); end; // Check thread count, create window if needed if (lpInfo.FThreadCount = 0) then lpInfo.FThreadWindow := AllocateWindow; finally // Increment the thread count Inc(lpInfo.FThreadCount); end; finally // Leave the critical section LeaveCriticalSection(FThreadLock); end; end; procedure TSyncManager.RemoveThread(ThreadSync: TThreadSync); var lpInfo: TSyncInfo; begin // Enter critical section EnterCriticalSection(FThreadLock); // Resource protection try // Find the info using the base thread id lpInfo := FindSyncInfo(ThreadSync.SyncBaseTID); // Check assignment if Assigned(lpInfo) then PostMessage(lpInfo.FThreadWindow, CM_DESTROYWINDOW, 0, Longint(lpInfo)); finally // Leave the critical section LeaveCriticalSection(FThreadLock); end; end; procedure TSyncManager.DoDestroyWindow(Info: TSyncInfo); begin // Enter critical section EnterCriticalSection(FThreadLock); // Resource protection try // Decrement the thread count Dec(Info.FThreadCount); // Check for zero threads if (Info.FThreadCount = 0) then FreeSyncInfo(Info); finally // Leave the critical section LeaveCriticalSection(FThreadLock); end; end; procedure TSyncManager.FreeSyncInfo(Info: TSyncInfo); begin // Check thread window if not(Info.FThreadWindow = 0) then begin // Resource protection try // Destroy window DestroyWindow(Info.FThreadWindow); // Remove from list FList.Remove(Info); finally // Free the class structure Info.Free; end; end; end; procedure TSyncManager.Synchronize(ThreadSync: TThreadSync); var lpInfo: TSyncInfo; begin // Find the info using the base thread id lpInfo := FindSyncInfo(ThreadSync.SyncBaseTID); // Check assignment, send message to thread window if Assigned(lpInfo) then SendMessage(lpInfo.FThreadWindow, CM_EXECPROC, 0, Longint(ThreadSync)); end; function TSyncManager.FindSyncInfo(SyncBaseTID: LongWord): TSyncInfo; var dwIndex: Integer; begin // Set default result result := nil; // Locate in list for dwIndex := 0 to Pred(FList.Count) do begin // Compare thread id's if (TSyncInfo(FList[dwIndex]).FSyncBaseTID = SyncBaseTID) then begin // Found the info structure result := TSyncInfo(FList[dwIndex]); // Done processing break; end; end; end; /// / TThreadSync /// //////////////////////////////////////////////////////////// constructor TThreadSync.Create; begin // Perform inherited inherited Create; // Set the base thread id FSyncBaseTID := GetCurrentThreadID; // Add self to sync manager TSyncManager.Instance.AddThread(Self); end; destructor TThreadSync.Destroy; begin // Resource protection try // Remove self from sync manager TSyncManager.Instance.RemoveThread(Self); finally // Perform inherited inherited Destroy; end; end; procedure TThreadSync.Synchronize(Method: TThreadMethod); begin // Clear sync raise exception object FSyncRaise := nil; // Set the method pointer FMethod := Method; // Resource protection try // Have the sync manager call the method TSyncManager.Instance.Synchronize(Self); finally // Check to see if the exception object was set if Assigned(FSyncRaise) then raise FSyncRaise; end; end; /// / TThreadEx /// ////////////////////////////////////////////////////////////// constructor TThreadEx.Create(CreateSuspended: Boolean); begin // Create the sync FSync := TThreadSync.Create; // Perform inherited inherited Create(CreateSuspended); end; destructor TThreadEx.Destroy; begin // Resource protection try // Free the sync object FSync.Free; finally // Perform inherited inherited Destroy; end; end; procedure TThreadEx.DoTerminate; begin // Overide the DoTerminate and don't call inherited if Assigned(OnTerminate) then Sync.Synchronize(HandleTerminate); end; procedure TThreadEx.HandleTerminate; begin // Call OnTerminate if assigned if Assigned(OnTerminate) then OnTerminate(Self); end; procedure TThreadEx.Synchronize(Method: TThreadMethod); begin // Call the sync's version of synchronize Sync.Synchronize(Method); end; procedure TThreadEx.SafeSynchronize(Method: TThreadMethod); begin // Exception trap try // Call synchronize Sync.Synchronize(Method); except // Eat the actual exception, just call terminate on the thread Terminate; end; end; procedure TThreadEx.Wait; var hThread: THandle; dwExit: DWORD; begin // Set the thread handle hThread := Handle; // Check current thread against the sync thread id if (GetCurrentThreadID = Sync.SyncBaseTID) then begin // Message wait while (MsgWaitForMultipleObjects(1, hThread, False, INFINITE, QS_ALLINPUT) = WAIT_OBJECT_0 + 1) do begin // Flush the messages FlushMessages; // Check thread state (because the handle is not duplicated, it can become invalid. Testing // WaitForSingleObject(Handle, 0) even returns WAIT_TIMEOUT for the invalid handle) if not(GetExitCodeThread(hThread, dwExit)) or not(dwExit = STILL_ACTIVE) then break; end; end else // Wait is not being called from base thread id, so use WaitForSingleObject WaitForSingleObject(hThread, INFINITE); end; /// / Console helper functions /// /////////////////////////////////////////////// type TConsoleEvent = function(dwCtrlEvent: DWORD; dwProcessGroupId: DWORD) : BOOL; stdcall; TConsoleHwnd = function(): HWND; stdcall; function ConsoleWindow(ConsoleHwnd: TConsoleHwnd): HWND; stdcall; begin // Check function pointer if Assigned(@ConsoleHwnd) then // Call function result := ConsoleHwnd() else // Return zero result := 0; end; function GetConsoleWindow(ProcessHandle: THandle): HWND; var lpConsoleHwnd: Pointer; hThread: THandle; dwSize: NativeUInt; dwWrite: NativeUInt; dwExit: Cardinal; begin // Get size of function that we need to inject dwSize := PChar(@GetConsoleWindow) - PChar(@ConsoleWindow); // Allocate memory in remote process lpConsoleHwnd := VirtualAllocEx(ProcessHandle, nil, dwSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // Check memory, write code from this process if Assigned(lpConsoleHwnd) then begin // Write memory WriteProcessMemory(ProcessHandle, lpConsoleHwnd, @ConsoleWindow, dwSize, dwWrite); // Resource protection try // Create remote thread starting at the injected function, passing in the address to GetConsoleWindow hThread := CreateRemoteThread(ProcessHandle, nil, 0, lpConsoleHwnd, GetProcAddress(GetModuleHandle(kernel32), 'GetConsoleWindow'), 0, DWORD(Pointer(nil)^)); // Check thread if (hThread = 0) then // Failed to create thread result := 0 else begin // Resource protection try // Wait for the thread to complete WaitForSingleObject(hThread, INFINITE); // Get the exit code from the thread if GetExitCodeThread(hThread, dwExit) then // Set return result := dwExit else // Failed to get exit code result := 0; finally // Close the thread handle CloseHandle(hThread); end; end; finally // Free allocated memory VirtualFreeEx(ProcessHandle, lpConsoleHwnd, 0, MEM_RELEASE); end; end else // Failed to create remote injected function result := 0; end; function GetConsoleWindowEx(ProcessHandle: THandle; ProcessID, ThreadID: DWORD): HWND; var lpConInfo: TPipeConsoleInfo; begin // Call the optimal routine first result := GetConsoleWindow(ProcessHandle); // Check return handle if (result = 0) then begin // Clear the window handle lpConInfo.Window := 0; // Resource protection try // Set process info lpConInfo.ProcessID := ProcessID; lpConInfo.ThreadID := ThreadID; // Enumerate the windows on the console thread EnumWindows(@EnumConsoleWindows, Integer(@lpConInfo)); finally // Return the window handle result := lpConInfo.Window; end; end; end; function CtrlBreak(ConsoleEvent: TConsoleEvent): DWORD; stdcall; begin // Generate the control break result := DWORD(ConsoleEvent(CTRL_BREAK_EVENT, 0)); end; function CtrlC(ConsoleEvent: TConsoleEvent): DWORD; stdcall; begin // Generate the control break result := DWORD(ConsoleEvent(CTRL_C_EVENT, 0)); end; function ExecConsoleEvent(ProcessHandle: THandle; Event: DWORD): Boolean; var lpCtrlEvent: Pointer; hThread: THandle; dwSize: NativeUInt; dwWrite: NativeUInt; dwExit: Cardinal; begin // Check event case Event of // Control C CTRL_C_EVENT: begin // Get size of function that we need to inject dwSize := PChar(@ExecConsoleEvent) - PChar(@CtrlC); // Allocate memory in remote process lpCtrlEvent := VirtualAllocEx(ProcessHandle, nil, dwSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // Check memory, write code from this process if Assigned(lpCtrlEvent) then WriteProcessMemory(ProcessHandle, lpCtrlEvent, @CtrlC, dwSize, dwWrite); end; // Control break CTRL_BREAK_EVENT: begin // Get size of function that we need to inject dwSize := PChar(@CtrlC) - PChar(@CtrlBreak); // Allocate memory in remote process lpCtrlEvent := VirtualAllocEx(ProcessHandle, nil, dwSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // Check memory, write code from this process if Assigned(lpCtrlEvent) then WriteProcessMemory(ProcessHandle, lpCtrlEvent, @CtrlBreak, dwSize, dwWrite); end; else // Not going to handle lpCtrlEvent := nil; end; // Check remote function address if Assigned(lpCtrlEvent) then begin // Resource protection try // Create remote thread starting at the injected function, passing in the address to GenerateConsoleCtrlEvent hThread := CreateRemoteThread(ProcessHandle, nil, 0, lpCtrlEvent, GetProcAddress(GetModuleHandle(kernel32), 'GenerateConsoleCtrlEvent'), 0, DWORD(Pointer(nil)^)); // Check thread if (hThread = 0) then // Failed to create thread result := False else begin // Resource protection try // Wait for the thread to complete WaitForSingleObject(hThread, INFINITE); // Get the exit code from the thread if GetExitCodeThread(hThread, dwExit) then // Set return result := not(dwExit = 0) else // Failed to get exit code result := False; finally // Close the thread handle CloseHandle(hThread); end; end; finally // Free allocated memory VirtualFreeEx(ProcessHandle, lpCtrlEvent, 0, MEM_RELEASE); end; end else // Failed to create remote injected function result := False; end; procedure ExitProcessEx(ProcessHandle: THandle; ExitCode: DWORD); var hKernel: HMODULE; hThread: THandle; begin // Get handle to kernel32 hKernel := GetModuleHandle(kernel32); // Check handle if not(hKernel = 0) then begin // Create a remote thread in the external process and have it call ExitProcess (tricky) hThread := CreateRemoteThread(ProcessHandle, nil, 0, GetProcAddress(hKernel, 'ExitProcess'), Pointer(ExitCode), 0, DWORD(Pointer(nil)^)); // Check the thread handle if (hThread = 0) then // Just terminate the process TerminateProcess(ProcessHandle, ExitCode) else begin // Resource protection try // Wait for the thread to complete WaitForSingleObject(hThread, INFINITE); finally // Close the handle CloseHandle(hThread); end; end; end else // Attempt to use the process handle from the create process call TerminateProcess(ProcessHandle, ExitCode); end; /// / Pipe helper functions /// ////////////////////////////////////////////////// procedure ClearOverlapped(var Overlapped: TOverlapped; ClearEvent: Boolean = False); begin // Check to see if all fields should be clered if ClearEvent then // Clear whole structure FillChar(Overlapped, SizeOf(Overlapped), 0) else begin // Clear all fields except for the event handle Overlapped.Internal := 0; Overlapped.InternalHigh := 0; Overlapped.Offset := 0; Overlapped.OffsetHigh := 0; end; end; procedure CloseHandleClear(var Handle: THandle); begin // Resource protection try // Check for invalid handle or zero if IsHandle(Handle) then CloseHandle(Handle); finally // Set to invalid handle Handle := INVALID_HANDLE_VALUE; end; end; procedure DisconnectAndClose(Pipe: HPIPE; IsServer: Boolean = True); begin // Check handle if IsHandle(Pipe) then begin // Resource protection try // Cancel overlapped IO on the handle CancelIO(Pipe); // Flush file buffer FlushFileBuffers(Pipe); // Disconnect the server end of the named pipe if flag is set if IsServer then DisconnectNamedPipe(Pipe); finally // Close the pipe handle CloseHandle(Pipe); end; end; end; procedure RaiseWindowsError; begin RaiseLastOSError; end; procedure FlushMessages; var lpMsg: TMsg; begin // Flush the message queue for the calling thread while PeekMessage(lpMsg, 0, 0, 0, PM_REMOVE) do begin // Translate the message TranslateMessage(lpMsg); // Dispatch the message DispatchMessage(lpMsg); // Allow other threads to run Sleep(0); end; end; function IsHandle(Handle: THandle): Boolean; begin // Determine if a valid handle (only by value) Result := not((Handle = 0) or (Handle = INVALID_HANDLE_VALUE)); end; function ComputerName: string; var dwSize: DWORD; begin // Set max size dwSize := Succ(MAX_PATH); // Resource protection try // Set string length SetLength(result, dwSize); // Attempt to get the computer name if not(GetComputerName(@result[1], dwSize)) then dwSize := 0; finally // Truncate string SetLength(result, dwSize); end; end; function AllocPipeWriteWithPrefix(const Prefix; PrefixCount: Integer; const Buffer; Count: Integer): PPipeWrite; var lpBuffer: PChar; begin // Allocate memory for the result result := AllocMem(SizeOf(TPipeWrite)); // Set the count of the buffer result^.Count := PrefixCount + Count; // Allocate enough memory to store the prefix and data buffer result^.Buffer := AllocMem(result^.Count); // Set buffer pointer lpBuffer := result^.Buffer; // Resource protection try // Move the prefix data in System.Move(Prefix, lpBuffer^, PrefixCount); // Increment the buffer position Inc(lpBuffer, PrefixCount); finally // Move the buffer data in System.Move(Buffer, lpBuffer^, Count); end; end; function AllocPipeWrite(const Buffer; Count: Integer): PPipeWrite; begin // Allocate memory for the result result := AllocMem(SizeOf(TPipeWrite)); // Resource protection try // Set the count of the buffer result^.Count := Count; // Allocate enough memory to store the data buffer result^.Buffer := AllocMem(Count); finally // Move data to the buffer System.Move(Buffer, result^.Buffer^, Count); end; end; procedure DisposePipeWrite(var PipeWrite: PPipeWrite); begin // Check pointer if Assigned(PipeWrite) then begin // Resource protection try // Resource protection try // Dispose of the memory being used by the pipe write structure if Assigned(PipeWrite^.Buffer) then FreeMem(PipeWrite^.Buffer); finally // Free the memory record FreeMem(PipeWrite); end; finally // Clear the pointer PipeWrite := nil; end; end; end; function EnumConsoleWindows(Window: HWND; lParam: Integer): BOOL; stdcall; var lpConInfo: PPipeConsoleInfo; begin // Get the console info lpConInfo := Pointer(lParam); // Get the thread id and compare against the passed structure if (lpConInfo^.ThreadID = GetWindowThreadProcessId(Window, nil)) then begin // Found the window, return the handle lpConInfo^.Window := Window; // Stop enumeration result := False; end else // Keep enumerating result := True; end; procedure CheckPipeName(Value: string); begin // Validate the pipe name if (Pos('\', Value) > 0) or (Length(Value) > MAX_NAME) or (Length(Value) = 0) then raise EPipeException.CreateRes(@resBadPipeName); end; procedure InitializeSecurity(var SA: TSecurityAttributes); var sd: PSecurityDescriptor; begin // Allocate memory for the security descriptor sd := AllocMem(SECURITY_DESCRIPTOR_MIN_LENGTH); // Initialize the new security descriptor if InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION) then begin // Add a NULL descriptor ACL to the security descriptor if SetSecurityDescriptorDacl(sd, True, nil, False) then begin // Set up the security attributes structure SA.nLength := SizeOf(TSecurityAttributes); SA.lpSecurityDescriptor := sd; SA.bInheritHandle := True; end else // Failed to init the sec descriptor RaiseWindowsError; end else // Failed to init the sec descriptor RaiseWindowsError; end; procedure FinalizeSecurity(var SA: TSecurityAttributes); begin // Release memory that was assigned to security descriptor if Assigned(SA.lpSecurityDescriptor) then begin // Reource protection try // Free memory FreeMem(SA.lpSecurityDescriptor); finally // Clear pointer SA.lpSecurityDescriptor := nil; end; end; end; function StdWndProc(Window: HWND; Message, wParam: Longint; lParam: Longint) : Longint; stdcall; assembler; asm xor eax, eax push eax push LParam push WParam push Message mov edx, esp mov eax, [ecx].LongInt[4] call [ecx].Pointer add esp, 12 pop eax end; function CalcJmpOffset(Src, Dest: Pointer): Longint; begin // Calculate the jump offset result := Longint(Dest) - (Longint(Src) + 5); end; function CalcJmpTarget(Src: Pointer; Offs: Integer): Pointer; begin // Calculate the jump target Integer(result) := Offs + (Longint(Src) + 5); end; function GetInstanceBlock(ObjectInstance: Pointer): PInstanceBlock; var lpInst: PObjectInstance; begin // Cast as object instance lpInst := ObjectInstance; // Check instance if (lpInst = nil) then // Return nil result := nil else // Get instance block Pointer(result) := Pointer(Longint(CalcJmpTarget(lpInst, lpInst^.Offset)) - SizeOf(Word) - SizeOf(PInstanceBlock)); end; function MakeObjectInstance(Method: TWndMethod): Pointer; var lpBlock: PInstanceBlock; lpInst: PObjectInstance; const BlockCode: array [1 .. 2] of Byte = ($59, // POP ECX $E9 // JMP StdWndProc ); PageSize = 4096; begin // Enter critical section EnterCriticalSection(InstCritSect); // Resource protection try // Check free list if (InstFreeList = nil) then begin // Allocate a new instance block lpBlock := VirtualAlloc(nil, PageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // Update the next pointer lpBlock^.Next := InstBlockList; // Set block code Word(lpBlock^.Code) := Word(BlockCode); // Set wndproc pointer lpBlock^.WndProcPtr := Pointer(CalcJmpOffset(@lpBlock^.Code[2], @StdWndProc)); // Set block counter lpBlock^.Counter := 0; // Update all block instances lpInst := @lpBlock^.Instances; repeat // Set call to near pointer offser lpInst^.Code := $E8; // Calculate the jump offset lpInst^.Offset := CalcJmpOffset(lpInst, @lpBlock^.Code); // Set next instance lpInst^.Next := InstFreeList; // Update the instance list InstFreeList := lpInst; // Push pointer forward Inc(Longint(lpInst), SizeOf(TObjectInstance)); until (Longint(lpInst) - Longint(lpBlock) >= SizeOf(TInstanceBlock)); // Update the block list InstBlockList := lpBlock; end; // Get instance from free list result := InstFreeList; // Next instance in free list lpInst := InstFreeList; InstFreeList := lpInst^.Next; // Update the moethod pointer lpInst^.Method := Method; // Increment the block counter Inc(GetInstanceBlock(lpInst)^.Counter); finally // Leave the critical section LeaveCriticalSection(InstCritSect); end; end; function FreeInstanceBlock(Block: Pointer): Boolean; var lpBlock: PInstanceBlock; lpInst: PObjectInstance; lpPrev: PObjectInstance; lpNext: PObjectInstance; begin // Get the instance block lpBlock := Block; // Check the block if (lpBlock = nil) or (lpBlock^.Counter > 0) then // Cant free instance block result := False else begin // Get free list lpInst := InstFreeList; // Set previous lpPrev := nil; // While assigned while Assigned(lpInst) do begin // Get next instance lpNext := lpInst^.Next; // Check instance block against passed block if (GetInstanceBlock(lpInst) = lpBlock) then begin // Check previous if Assigned(lpPrev) then lpPrev^.Next := lpNext; // Check against list if (lpInst = InstFreeList) then InstFreeList := lpNext; end; // Update previous lpPrev := lpInst; // Next instance lpInst := lpNext; end; // Free the block of memory VirtualFree(lpBlock, 0, MEM_RELEASE); // Success result := True; end; end; procedure FreeInstanceBlocks; var lpPrev: PInstanceBlock; lpNext: PInstanceBlock; lpBlock: PInstanceBlock; begin // Set previous to nil lpPrev := nil; // Get current block lpBlock := InstBlockList; // While assigned while Assigned(lpBlock) do begin // Get next block lpNext := lpBlock^.Next; // Attempt to free if FreeInstanceBlock(lpBlock) then begin // Relink blocks if Assigned(lpPrev) then lpPrev^.Next := lpNext; // Reset list if needed if (lpBlock = InstBlockList) then InstBlockList := lpNext; end else // Failed to free block lpBlock := nil; // Update previous lpPrev := lpBlock; // Next block lpBlock := lpNext; end; end; procedure FreeObjectInstance(ObjectInstance: Pointer); var lpBlock: PInstanceBlock; begin // Check instance if Assigned(ObjectInstance) then begin // Enter critical section EnterCriticalSection(InstCritSect); // Resource protection try // Get instance block lpBlock := GetInstanceBlock(ObjectInstance); // Check block if Assigned(lpBlock) then begin // Check block counter if ((lpBlock^.Counter > 0) and (lpBlock^.Counter <= Succ(INSTANCE_COUNT))) then begin // Set the next pointer PObjectInstance(ObjectInstance)^.Next := InstFreeList; // Update free list InstFreeList := ObjectInstance; // Decrement the counter Dec(lpBlock^.Counter); // If counter is at (or below) zero then free the instance blocks if (lpBlock^.Counter <= 0) then FreeInstanceBlocks; end; end; finally // Leave critical section LeaveCriticalSection(InstCritSect); end; end; end; function AllocateHWnd(Method: TWndMethod): HWND; var clsTemp: TWndClass; bClassReg: Boolean; begin // Enter critical section EnterCriticalSection(InstCritSect); // Resource protection try // Set instance handle ObjWndClass.hInstance := hInstance; // Attempt to get class info bClassReg := GetClassInfo(hInstance, ObjWndClass.lpszClassName, clsTemp); // Ensure the class is registered and the window procedure is the default window proc if not(bClassReg) or not(clsTemp.lpfnWndProc = @DefWindowProc) then begin // Unregister if already registered if bClassReg then Winapi.Windows.UnregisterClass(ObjWndClass.lpszClassName, hInstance); // Register Winapi.Windows.RegisterClass(ObjWndClass); end; // Create the window result := CreateWindowEx(0, ObjWndClass.lpszClassName, '', WS_POPUP, 0, 0, 0, 0, 0, 0, hInstance, nil); // Set method pointer if Assigned(Method) then SetWindowLong(result, GWL_WNDPROC, Longint(MakeObjectInstance(Method))); finally // Leave critical section LeaveCriticalSection(InstCritSect); end; end; procedure DeallocateHWnd(Wnd: HWND); var Instance: Pointer; begin // Enter critical section EnterCriticalSection(InstCritSect); // Resource protection try // Get the window procedure Instance := Pointer(GetWindowLong(Wnd, GWL_WNDPROC)); // Resource protection try // Destroy the window DestroyWindow(Wnd); finally // If not the default window procedure then free the object instance if Assigned(Instance) and not(Instance = @DefWindowProc) then FreeObjectInstance(Instance); end; finally // Leave critical section LeaveCriticalSection(InstCritSect); end; end; procedure CreateMessageQueue; var lpMsg: TMsg; begin // Spin a message queue PeekMessage(lpMsg, 0, WM_USER, WM_USER, PM_NOREMOVE); end; procedure Register; begin // Register the components under the Win32 tab RegisterComponents('Win32', [TPipeServer, TPipeClient, TPipeConsole]); end; initialization // Initialize the critical section for instance handling InitializeCriticalSection(InstCritSect); // If this is a console application then create a message queue if IsConsole then CreateMessageQueue; finalization // Check sync manager if Assigned(SyncManager) then FreeAndNil(SyncManager); // Delete the critical section for instance handling DeleteCriticalSection(InstCritSect); end.
unit CustomActionWordpack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\CustomActionWordpack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "CustomActionWordpack" MUID: (57FB3E5D00AD) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , ActnList , tfwClassLike , tfwScriptingInterfaces , TypInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *57FB3E5D00ADimpl_uses* //#UC END# *57FB3E5D00ADimpl_uses* ; type TkwPopActionChecked = {final} class(TtfwClassLike) {* Слово скрипта pop:Action:Checked } private function Checked(const aCtx: TtfwContext; aAction: TCustomAction): Boolean; {* Реализация слова скрипта pop:Action:Checked } 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;//TkwPopActionChecked function TkwPopActionChecked.Checked(const aCtx: TtfwContext; aAction: TCustomAction): Boolean; {* Реализация слова скрипта pop:Action:Checked } //#UC START# *57FB3E9D03C1_57FB3E9D03C1_47E7626B0083_Word_var* //#UC END# *57FB3E9D03C1_57FB3E9D03C1_47E7626B0083_Word_var* begin //#UC START# *57FB3E9D03C1_57FB3E9D03C1_47E7626B0083_Word_impl* Result := aAction.Checked; //#UC END# *57FB3E9D03C1_57FB3E9D03C1_47E7626B0083_Word_impl* end;//TkwPopActionChecked.Checked class function TkwPopActionChecked.GetWordNameForRegister: AnsiString; begin Result := 'pop:Action:Checked'; end;//TkwPopActionChecked.GetWordNameForRegister function TkwPopActionChecked.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopActionChecked.GetResultTypeInfo function TkwPopActionChecked.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopActionChecked.GetAllParamsCount function TkwPopActionChecked.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TCustomAction)]); end;//TkwPopActionChecked.ParamsTypes procedure TkwPopActionChecked.DoDoIt(const aCtx: TtfwContext); var l_aAction: TCustomAction; begin try l_aAction := TCustomAction(aCtx.rEngine.PopObjAs(TCustomAction)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aAction: TCustomAction : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(Checked(aCtx, l_aAction)); end;//TkwPopActionChecked.DoDoIt initialization TkwPopActionChecked.RegisterInEngine; {* Регистрация pop_Action_Checked } TtfwTypeRegistrator.RegisterType(TypeInfo(TCustomAction)); {* Регистрация типа TCustomAction } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
{------------------------------------------------------------------------------ TNotepad component Developed by Rodrigo Depiné Dalpiaz (digão dalpiaz) Non visual component to store TStrings at DFM file https://github.com/digao-dalpiaz/NoteEditor Please, read the documentation at GitHub link. ------------------------------------------------------------------------------} unit Notepad; interface uses System.Classes; type TNotepad = class(TComponent) private FAbout: String; S: TStrings; procedure SetLines(const Value: TStrings); function GetCount: Integer; function GetText: String; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Text: String read GetText; property Count: Integer read GetCount; procedure Add(const A: String); procedure Sort; procedure Clear; function Has(const A: String): Boolean; function AddIfNotEx(const A: String): Boolean; published property About: String read FAbout; property Lines: TStrings read S write SetLines; end; implementation constructor TNotepad.Create(AOwner: TComponent); begin inherited; FAbout := 'Digão Dalpiaz / Version 1.0'; S := TStringList.Create; end; destructor TNotepad.Destroy; begin S.Free; inherited; end; procedure TNotepad.SetLines(const Value: TStrings); begin S.Assign(Value); end; function TNotepad.GetCount: Integer; begin Result := S.Count; end; procedure TNotepad.Sort; begin TStringList(S).Sort; end; procedure TNotepad.Add(const A: String); begin S.Add(A); end; function TNotepad.GetText: String; begin Result := S.Text; end; procedure TNotepad.Clear; begin S.Clear; end; function TNotepad.Has(const A: String): Boolean; begin Result := ( S.IndexOf(A) <> (-1) ); end; function TNotepad.AddIfNotEx(const A: String): Boolean; begin Result := not Has(A); if Result then Add(A); end; end.
unit VzorGUI; (* Formular pro vyber vzoru a editaci cviceni s nakresem *) (* ===================================================== *) interface uses Windows, Messages, Variants, Graphics, Dialogs, Buttons, SysUtils, Forms, StdCtrls, Controls, Classes, ExtCtrls, MyUtils; type TForm2 = class(TForm) Image1: TImage; ZpetButton: TSpeedButton; VpredButton: TSpeedButton; Label1: TLabel; Name: TEdit; GroupBox1: TGroupBox; Label2: TLabel; Popis: TMemo; OKButton: TSpeedButton; Label3: TLabel; Minut: TEdit; procedure VypisCviceni(Index:Integer); procedure ZpetButtonClick(Sender: TObject); procedure VpredButtonClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure aktualizuj_seznam(); procedure MinutExit(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; SeznamSouboru:TStringList; Aktual,Max: Integer; implementation {$R *.dfm} procedure TForm2.VypisCviceni(Index:Integer); var filename:String; begin Popis.Lines.Clear; filename:=ExtractFileName(SeznamSouboru.Strings[Index]); if FileExists('cviceni\'+filename) then Image1.Picture.LoadFromFile('cviceni\'+filename); filename:=ChangeFileExt(filename,'.TXT'); if FileExists('text\'+filename) then begin Popis.Lines.LoadFromFile('text\'+filename); Name.Text:=Popis.Lines.Strings[0]; Popis.Lines.Delete(0); end else Name.Text:=SeznamSouboru.Strings[Index]; end; procedure TForm2.aktualizuj_seznam(); var sr: TSearchRec; begin SeznamSouboru.Clear; if FindFirst('cviceni\*.JPG', faAnyFile, sr)=0 then begin repeat SeznamSouboru.Add(sr.Name); until FindNext(sr) <> 0; FindClose(sr); end; SeznamSouboru.Sort; Aktual:=0; Max:=SeznamSouboru.Count-1; end; procedure TForm2.ZpetButtonClick(Sender: TObject); begin Aktual:=Aktual-1; If Aktual<0 then Aktual:=Max; VypisCviceni(Aktual); end; procedure TForm2.VpredButtonClick(Sender: TObject); begin Aktual:=Aktual+1; If Aktual>Max then Aktual:=0; VypisCviceni(Aktual); end; procedure TForm2.FormCreate(Sender: TObject); begin SeznamSouboru:=TStringList.Create; aktualizuj_seznam(); VypisCviceni(Aktual); end; procedure TForm2.OKButtonClick(Sender: TObject); begin ModalResult := mrOK; end; procedure TForm2.MinutExit(Sender: TObject); begin Minut.Text:=ZpracujNaCislo(Minut.Text); end; end.
unit RESTRequest4D.Request.Body.Intf; interface uses System.JSON, REST.Types; type /// <summary> /// Interface to represent the body of a request. /// </summary> IRequestBody = interface ['{D0D60888-6E42-4718-8E2D-1F6A9F10445A}'] /// <summary> /// Removes all content added in the request body. /// </summary> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function Clear: IRequestBody; /// <summary> /// Adds content to the body of the request. /// </summary> /// <param name="AContent"> /// Content to be added. /// </param> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function Add(const AContent: string; const AContentType: TRESTContentType = ctNone): IRequestBody; overload; /// <summary> /// Adds content to the body of the request. /// </summary> /// <param name="AContent"> /// Content to be added in JSON format. /// </param> /// <param name="AOwns"> /// Indicates who owns JSON. /// </param> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function Add(const AContent: TJSONObject; const AOwns: Boolean = True): IRequestBody; overload; /// <summary> /// Adds content to the body of the request. /// </summary> /// <param name="AContent"> /// Content to be added in JSON array format. /// </param> /// <param name="AOwns"> /// Indicates who owns JSON. /// </param> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function Add(const AContent: TJSONArray; const AOwns: Boolean = True): IRequestBody; overload; /// <summary> /// Adds content to the body of the request. /// </summary> /// <param name="AContent"> /// Object that must be serialized. /// </param> /// <param name="AOwns"> /// Indicates who owns object. /// </param> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function Add(const AContent: TObject; const AOwns: Boolean = True): IRequestBody; overload; end; implementation end.
const inputFileName = 'input.dat'; const outputFileName = 'output.dat'; const numbersCount = 64; const generatedArraySize = numbersCount; const partArraySize = 16; const resultingArraySize = generatedArraySize div 16 + 1; type integerArrayType = array [1..generatedArraySize] of integer; type sixteenArrayType = array [1..partArraySize] of integer; type resultingArrayType = array [1..generatedArraySize] of sixteenArrayType; procedure generateFile(); begin var inputFile: file of integer; Assign(inputFile, inputFileName); Rewrite(inputFile); for var index := 1 to numbersCount do begin write(inputFile, random(100)); end; Close(inputFile); end; function getDataInFile(currentFile: file of integer): integerArrayType; begin reset(currentFile); var index: integer := 1; var data: integerArrayType; while not EOF(currentFile) do begin var number: integer; read(currentFile, number); data[index] := number; index := index + 1; end; Result := data; end; function divideData(data: integerArrayType): resultingArrayType; begin var dividedData: resultingArrayType; var sixteenArray :sixteenArrayType; var dividedDataIndex: integer := 1; for var index: integer := 1 to generatedArraySize do begin if index mod 16 = 0 then begin sixteenArray[16] := data[index]; dividedData[dividedDataIndex] := sixteenArray; dividedDataIndex := dividedDataIndex + 1; end else begin sixteenArray[index mod 16] := data[index]; end; end; Result := dividedData; end; procedure writeDataToFile(outputFile: file of sixteenArrayType; data: resultingArrayType); begin rewrite(outputFile); for var index := 1 to resultingArraySize do begin write(outputFile, data[index]); end; end; procedure viewDividedData(dividedData: resultingArrayType); begin write('['); for var index: integer := 1 to resultingArraySize - 2 do begin write(dividedData[index]); write(', '); end; write(dividedData[resultingArraySize - 1]); write(']'); end; begin generateFile(); var inputFile: file of integer; var outputFile: file of sixteenArrayType; Assign(inputFile, inputFileName); Assign(outputFile, outputFileName); var data: integerArrayType := getDataInFile(inputFile); writeln('Data: '); writeln(data); writeln(); var dividedData: resultingArrayType := divideData(data); writeln('Divided data: '); viewDividedData(dividedData); writeDataToFile(outputFile, dividedData); Close(inputFile); Close(outputFile); end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StMath.pas 4.04 *} {*********************************************************} {* SysTools: Miscellaneous math functions *} {*********************************************************} {$I StDefine.inc} unit StMath; interface uses Windows, SysUtils, StDate, StBase, StConst; const RadCor : Double = 57.29577951308232; {number of degrees in a radian} function StInvCos(X : Double): Double; {-Returns the ArcCos of Y} function StInvSin(Y : Double): Double; {-Returns the ArcSin of Y} function StInvTan2(X, Y : Double) : Double; {-Returns the ArcTangent of Y / X} function StTan(A : Double) : Double; {-Returns the Tangent of A} {-------------------------------------------------------} implementation {-------------------------------------------------------} function StTan(A : Double) : Double; var C, S : Double; begin C := Cos(A); S := Sin(A); if (Abs(C) >= 5E-12) then Result := S / C else if (C < 0) then Result := 5.0e-324 else Result := 1.7e+308; end; {-------------------------------------------------------} function StInvTan2(X, Y : Double) : Double; begin if (Abs(X) < 5.0E-12) then begin if (X < 0) then Result := 3 * Pi / 2 else Result := Pi / 2; end else begin Result := ArcTan(Y / X); if (X < 0) then Result := Result + Pi else if (Y < 0) then Result := Result + 2 * Pi; end; end; {-------------------------------------------------------} function StInvSin(Y : Double): Double; begin if (Abs(Abs(Y) - 1) > 5.0E-12) then Result := ArcTan(Y / Sqrt(1 - Y * Y)) else begin if (Y < 0) then Result := 3 * Pi / 2 else Result := Pi / 2; end; end; {-------------------------------------------------------} function StInvCos(X : Double): Double; begin if (Abs(Abs(X) - 1) > 5.0E-12) then Result := (90 / RadCor) - ArcTan(X / Sqrt(1 - X * X)) else begin if ((X - Pi / 2) > 0) then Result := 0 else Result := Pi; end; end; end.
unit kangaroo_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,rom_engine,ay_8910,pal_engine, sound_engine,qsnapshot; function iniciar_kangaroo:boolean; implementation const kangaroo_rom:array[0..5] of tipo_roms=( (n:'tvg_75.0';l:$1000;p:0;crc:$0d18c581),(n:'tvg_76.1';l:$1000;p:$1000;crc:$5978d37a), (n:'tvg_77.2';l:$1000;p:$2000;crc:$522d1097),(n:'tvg_78.3';l:$1000;p:$3000;crc:$063da970), (n:'tvg_79.4';l:$1000;p:$4000;crc:$9e5cf8ca),(n:'tvg_80.5';l:$1000;p:$5000;crc:$2fc18049)); kangaroo_gfx:array[0..3] of tipo_roms=( (n:'tvg_83.v0';l:$1000;p:0;crc:$c0446ca6),(n:'tvg_85.v2';l:$1000;p:$1000;crc:$72c52695), (n:'tvg_84.v1';l:$1000;p:$2000;crc:$e4cb26c2),(n:'tvg_86.v3';l:$1000;p:$3000;crc:$9e6a599f)); kangaroo_sound:tipo_roms=(n:'tvg_81.8';l:$1000;p:0;crc:$fb449bfd); //DIP kangaroo_dipa:array [0..3] of def_dip=( (mask:$20;name:'Music';number:2;dip:((dip_val:$0;dip_name:'On'),(dip_val:$20;dip_name:'Off'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$40;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Flip Screen';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$80;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); kangaroo_dipb:array [0..4] of def_dip=( (mask:$1;name:'Lives';number:2;dip:((dip_val:$0;dip_name:'3'),(dip_val:$1;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Difficulty';number:2;dip:((dip_val:$0;dip_name:'Easy'),(dip_val:$2;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$8;dip_name:'10000 30000'),(dip_val:$c;dip_name:'20000 40000'),(dip_val:$4;dip_name:'10000'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$f0;name:'Coinage';number:16;dip:((dip_val:$10;dip_name:'2C/1C'),(dip_val:$20;dip_name:'A 2C/1C B 1C/3C'),(dip_val:$0;dip_name:'1C/1C'),(dip_val:$30;dip_name:'A 1C/1C B 1C/2C'),(dip_val:$40;dip_name:'A 1C/1C B 1C/3C'),(dip_val:$50;dip_name:'A 1C/1C B 1C/4C'),(dip_val:$60;dip_name:'A 1C/1C B 1C/5C'),(dip_val:$70;dip_name:'A 1C/1C B 1C/6C'),(dip_val:$80;dip_name:'1C/2C'),(dip_val:$90;dip_name:'A 1C/2C B 1C/4C'),(dip_val:$a0;dip_name:'A 1C/2C B 1C/5C'),(dip_val:$e0;dip_name:'A 1C/2C B 1C/6C'),(dip_val:$b0;dip_name:'A 1C/2C B 1C/10C'),(dip_val:$c0;dip_name:'A 1C/2C B 1C/11C'),(dip_val:$d0;dip_name:'A 1C/2C B 1C/12C'),(dip_val:$f0;dip_name:'Free Play'))),()); var video_control:array[0..$f] of byte; sound_latch,mcu_clock,rom_bank:byte; video_ram:array[0..(256*64)-1] of dword; gfx_data:array[0..1,0..$1fff] of byte; procedure update_video_kangaroo; var x,y,scrolly,scrollx,maska,maskb,xora,xorb:byte; effxb,effyb,pixa,pixb,finalpens:byte; effxa,effya,sy,tempa,tempb:word; enaa,enab,pria,prib:boolean; punt:array[0..$1ffff] of word; begin scrolly:=video_control[6]; scrollx:=video_control[7]; maska:=(video_control[10] and $28) shr 3; maskb:=(video_control[10] and $07); xora:=$ff*((video_control[9] and $20) shr 5); xorb:=$ff*((video_control[9] and $10) shr 4); enaa:=(video_control[9] and $08)<>0; enab:=(video_control[9] and $04)<>0; pria:=(not(video_control[9]) and $02)<>0; prib:=(not(video_control[9]) and $01)<>0; // iterate over pixels */ for y:=0 to 255 do begin sy:=0; for x:=0 to 255 do begin effxa:=scrollx+(x xor xora); effya:=scrolly+(y xor xora); effxb:=x xor xorb; effyb:=y xor xorb; tempa:=effya+256*(effxa shr 2); tempb:=effyb+256*(effxb shr 2); pixa:=(video_ram[tempa] shr (8*(effxa mod 4)+0)) and $f; pixb:=(video_ram[tempb] shr (8*(effxb mod 4)+4)) and $f; // for each layer, contribute bits if (a) enabled, and (b) either has priority or the opposite plane is 0 */ finalpens:=0; if (enaa and (pria or (pixb=0))) then finalpens:=finalpens or pixa; if (enab and (prib or (pixa=0))) then finalpens:=finalpens or pixb; // store the first of two pixels, which is always full brightness */ punt[sy*256+(255-y)]:=paleta[finalpens and 7]; // KOS1 alternates at 5MHz, offset from the pixel clock by 1/2 clock */ // when 0, it enables the color mask for pixels with Z = 0 */ finalpens:=0; if (enaa and (pria or (pixb=0))) then begin if ((pixa and $08)=0) then pixa:=pixa and maska; finalpens:=finalpens or pixa; end; if (enab and (prib or (pixa=0))) then begin if ((pixb and $08)=0) then pixb:=pixb and maskb; finalpens:=finalpens or pixb; end; // store the second of two pixels, which is affected by KOS1 and the A/B masks */ punt[(sy+1)*256+(255-y)]:=paleta[finalpens and 7]; sy:=sy+2; end; end; putpixel(0,0,$20000,@punt,1); actualiza_trozo(8,0,240,512,1,0,0,240,512,PANT_TEMP); end; procedure eventos_kangaroo; begin if event.arcade then begin //P1 if arcade_input.right[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.left[0] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); if arcade_input.up[0] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $fb); if arcade_input.down[0] then marcade.in1:=(marcade.in1 or $8) else marcade.in1:=(marcade.in1 and $f7); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 or $10) else marcade.in1:=(marcade.in1 and $ef); //P2 if arcade_input.right[1] then marcade.in2:=(marcade.in2 or $1) else marcade.in2:=(marcade.in2 and $fe); if arcade_input.left[1] then marcade.in2:=(marcade.in2 or $2) else marcade.in2:=(marcade.in2 and $fd); if arcade_input.up[1] then marcade.in2:=(marcade.in2 or $4) else marcade.in2:=(marcade.in2 and $fb); if arcade_input.down[1] then marcade.in2:=(marcade.in2 or $8) else marcade.in2:=(marcade.in2 and $f7); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); //System if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); end; end; procedure kangaroo_principal; var frame_m,frame_s:single; f:word; 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 259 do begin //Main z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; if f=247 then begin z80_0.change_irq(HOLD_LINE); z80_1.change_irq(HOLD_LINE); update_video_kangaroo; end; end; eventos_kangaroo; video_sync; end; end; procedure videoram_write(offset:word;data,mask:byte); var expdata,layermask:dword; begin // data contains 4 2-bit values packed as DCBADCBA; expand these into 4 8-bit values */ expdata:=0; if (data and $01)<>0 then expdata:=expdata or $00000055; if (data and $10)<>0 then expdata:=expdata or $000000aa; if (data and $02)<>0 then expdata:=expdata or $00005500; if (data and $20)<>0 then expdata:=expdata or $0000aa00; if (data and $04)<>0 then expdata:=expdata or $00550000; if (data and $40)<>0 then expdata:=expdata or $00aa0000; if (data and $08)<>0 then expdata:=expdata or $55000000; if (data and $80)<>0 then expdata:=expdata or $aa000000; // determine which layers are enabled */ layermask:=0; if (mask and $08)<>0 then layermask:=layermask or $30303030; if (mask and $04)<>0 then layermask:=layermask or $c0c0c0c0; if (mask and $02)<>0 then layermask:=layermask or $03030303; if (mask and $01)<>0 then layermask:=layermask or $0c0c0c0c; // update layers */ video_ram[offset]:=(video_ram[offset] and not(layermask)) or (expdata and layermask); end; procedure blitter_execute; var src,dst,effdst,effsrc:word; height,width,mask,x,y:byte; begin src:=video_control[0]+(video_control[1] shl 8); dst:=video_control[2]+(video_control[3] shl 8); height:=video_control[5]; width:=video_control[4]; mask:=video_control[8]; // during DMA operations, the top 2 bits are ORed together, as well as the bottom 2 bits */ // adjust the mask to account for this */ if (mask and $0c)<>0 then mask:=mask or $0c; if (mask and $03)<>0 then mask:=mask or $03; // loop over height, then width */ for y:=0 to height do begin for x:=0 to width do begin effdst:=(dst+x) and $3fff; effsrc:=src and $1fff; src:=src+1; videoram_write(effdst,gfx_data[0,effsrc],mask and $05); videoram_write(effdst,gfx_data[1,effsrc],mask and $0a); end; dst:=dst+256; end; end; function kangaroo_getbyte(direccion:word):byte; begin case direccion of 0..$5fff,$e000..$e3ff:kangaroo_getbyte:=memoria[direccion]; $c000..$dfff:kangaroo_getbyte:=gfx_data[rom_bank,direccion and $1fff]; $e400..$e7ff:kangaroo_getbyte:=marcade.dswb; $ec00..$ecff:kangaroo_getbyte:=marcade.in0+marcade.dswa; $ed00..$edff:kangaroo_getbyte:=marcade.in1; $ee00..$eeff:kangaroo_getbyte:=marcade.in2; $ef00..$efff:begin mcu_clock:=mcu_clock+1; kangaroo_getbyte:=mcu_clock and $f; end; end; end; procedure kangaroo_putbyte(direccion:word;valor:byte); begin case direccion of 0..$5fff:; $8000..$bfff:videoram_write((direccion and $3fff),valor,video_control[8]); $e000..$e3ff:memoria[direccion]:=valor; $e800..$ebff:begin video_control[direccion and $f]:=valor; case (direccion and $f) of 5:blitter_execute; 8:rom_bank:=byte((valor and $5)=0); end; end; $ec00..$ecff:sound_latch:=valor; end; end; function kangaroo_snd_getbyte(direccion:word):byte; begin case direccion of 0..$fff:kangaroo_snd_getbyte:=mem_snd[direccion]; $4000..$4fff:kangaroo_snd_getbyte:=mem_snd[$4000+(direccion and $3ff)]; $6000..$6fff:kangaroo_snd_getbyte:=sound_latch; end; end; procedure kangaroo_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$fff:; $4000..$4fff:mem_snd[$4000+(direccion and $3ff)]:=valor; $7000..$7fff:ay8910_0.write(valor); $8000..$8fff:ay8910_0.control(valor); end; end; procedure kangaroo_sound_update; begin ay8910_0.update; end; procedure kangaroo_qsave(nombre:string); var data:pbyte; size:word; buffer:array[0..2] of byte; begin open_qsnapshot_save('kangaroo'+nombre); getmem(data,200); //CPU size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=z80_1.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=ay8910_0.save_snapshot(data); savedata_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria[$6000],$a000); savedata_com_qsnapshot(@mem_snd[$1000],$f000); //MISC buffer[0]:=sound_latch; buffer[1]:=mcu_clock; buffer[2]:=rom_bank; savedata_qsnapshot(@buffer,3); savedata_com_qsnapshot(@video_control,$10); savedata_com_qsnapshot(@video_ram,$4000*4); freemem(data); close_qsnapshot; end; procedure kangaroo_qload(nombre:string); var data:pbyte; buffer:array[0..2] of byte; begin if not(open_qsnapshot_load('kangaroo'+nombre)) then exit; getmem(data,200); //CPU loaddata_qsnapshot(data); z80_0.load_snapshot(data); loaddata_qsnapshot(data); z80_1.load_snapshot(data); //SND loaddata_qsnapshot(data); ay8910_0.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria[$6000]); loaddata_qsnapshot(@mem_snd[$1000]); //MISC loaddata_qsnapshot(@buffer); sound_latch:=buffer[0]; mcu_clock:=buffer[1]; rom_bank:=buffer[2]; loaddata_qsnapshot(@video_control); loaddata_qsnapshot(@video_ram); freemem(data); close_qsnapshot; end; //Main procedure reset_kangaroo; begin z80_0.reset; z80_0.change_nmi(PULSE_LINE); z80_1.reset; ay8910_0.reset; reset_audio; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; sound_latch:=0; fillchar(video_control,$10,0); fillchar(video_ram,256*64*4,0); mcu_clock:=0; rom_bank:=0; end; function iniciar_kangaroo:boolean; var colores:tpaleta; f:word; mem_temp:array[0..$3fff] of byte; begin llamadas_maquina.bucle_general:=kangaroo_principal; llamadas_maquina.reset:=reset_kangaroo; llamadas_maquina.fps_max:=60.096154; llamadas_maquina.save_qsnap:=kangaroo_qsave; llamadas_maquina.load_qsnap:=kangaroo_qload; iniciar_kangaroo:=false; iniciar_audio(false); screen_init(1,256,512); iniciar_video(240,512); //Main CPU z80_0:=cpu_z80.create(10000000 div 4,260); z80_0.change_ram_calls(kangaroo_getbyte,kangaroo_putbyte); //Sound CPU z80_1:=cpu_z80.create(10000000 div 8,260); z80_1.change_ram_calls(kangaroo_snd_getbyte,kangaroo_snd_putbyte); z80_1.change_io_calls(kangaroo_snd_getbyte,kangaroo_snd_putbyte); z80_1.init_sound(kangaroo_sound_update); //Sound chip ay8910_0:=ay8910_chip.create(10000000 div 8,AY8910,0.5); //cargar roms if not(roms_load(@memoria,kangaroo_rom)) then exit; //cargar roms snd if not(roms_load(@mem_snd,kangaroo_sound)) then exit; //cargar gfx if not(roms_load(@mem_temp,kangaroo_gfx)) then exit; copymemory(@gfx_data[0,0],@mem_temp[0],$2000); copymemory(@gfx_data[1,0],@mem_temp[$2000],$2000); for f:=0 to 7 do begin colores[f].r:=pal1bit(f shr 2); colores[f].g:=pal1bit(f shr 1); colores[f].b:=pal1bit(f shr 0); end; set_pal(colores,8); marcade.dswa:=$0; marcade.dswa_val:=@kangaroo_dipa; marcade.dswb:=$0; marcade.dswb_val:=@kangaroo_dipb; //final reset_kangaroo; iniciar_kangaroo:=true; end; end.
{ *************************************************************************** Copyright (c) 2016-2021 Kike Pérez Unit : Quick.Parameters Description : Map comandline to class Author : Kike Pérez Version : 1.4 Created : 12/07/2020 Modified : 01/08/2021 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Parameters; {$i QuickLib.inc} interface uses Classes, SysUtils, StrUtils, Generics.Collections, Quick.Commons, {$IFDEF CONSOLE} Quick.Console, {$ENDIF} rtti, TypInfo, Quick.RTTI.Utils; type CommandDescription = class(TCustomAttribute) private fDescription : string; public constructor Create(const aDescription : string); property Description : string read fDescription; end; ParamCommand = class(TCustomAttribute) private fPosition : Integer; public constructor Create(aPosition : Integer); property Position : Integer read fPosition; end; ParamName = class(TCustomAttribute) private fName : string; fAlias : string; public constructor Create(const aName: string; const aAlias : string = ''); property Name : string read fName; property Alias : string read fAlias; end; ParamValueIsNextParam = class(TCustomAttribute); ParamHelp = class(TCustomAttribute) private fHelp : string; fValueName : string; public constructor Create(const aHelp : string; const aValueName : string = ''); property Help : string read fHelp; property ValueName : string read fValueName; end; ParamSwitchChar = class(TCustomAttribute) private fSwithChar : string; public constructor Create(const aSwitchChar : string); property SwitchChar : string read fSwithChar write fSwithChar; end; ParamValueSeparator = class(TCustomAttribute) private fValueSeparator : string; public constructor Create(const aValueSeparator : string); property ValueSeparator : string read fValueSeparator write fValueSeparator; end; ParamRequired = class(TCustomAttribute); {$IFDEF CONSOLE} TColorizeHelp = class private fCommandName : TConsoleColor; fCommandDescription : TConsoleColor; fCommandUsage : TConsoleColor; fSections : TConsoleColor; fArgumentName : TConsoleColor; fArgumentDescription : TConsoleColor; public property CommandName : TConsoleColor read fCommandName write fCommandName; property CommandDescription : TConsoleColor read fCommandDescription write fCommandDescription; property CommandUsage : TConsoleColor read fCommandUsage write fCommandUsage; property Sections : TConsoleColor read fSections write fSections; property ArgumentName : TConsoleColor read fArgumentName write fArgumentName; property ArgumentDescription : TConsoleColor read fArgumentDescription write fArgumentDescription; end; {$ENDIF} {$M+} TParameters = class type TValueType = (vtString, vtInteger, vtFloat, vtBoolean, vtEnumeration); TParam = class private fName : string; fAlias : string; fValue : string; fPrecisePosition : Integer; fParamType: TValueType; fRequired : Boolean; fHelp : string; fValueName : string; fValueIsNextParam: Boolean; fSwitchChar: string; fValueSeparator: string; fIsPresent: Boolean; public constructor Create; property Name : string read fName write fName; property Alias : string read fAlias write fAlias; property Value : string read fValue write fValue; property PrecisePosition : Integer read fPrecisePosition write fPrecisePosition; property ParamType : TValueType read fParamType write fParamType; property Required : Boolean read fRequired write fRequired; property SwitchChar : string read fSwitchChar write fSwitchChar; property ValueSeparator : string read fValueSeparator write fValueSeparator; property Help : string read fHelp write fHelp; property HepValueName : string read fValueName write fValueName; property ValueIsNextParam : Boolean read fValueIsNextParam write fValueIsNextParam; property IsPresent : Boolean read fIsPresent write fIsPresent; function IsSwitch : Boolean; function IsCommand : Boolean; function ValueIsSwitch : Boolean; end; private fParams : TObjectList<TParam>; fDescription : string; fHelp: Boolean; {$IFDEF CONSOLE} fColorizeHelp: TColorizeHelp; {$ENDIF} function ExistParam(aParameter : TParam; const aParam : string) : Boolean; overload; function GetParamName(aParameter : TParam; const aParam : string) : string; function GetParamValue(aParameter : TParam; const aParam : string) : string; function ValueType(const aProp : TRttiProperty) : TValueType; procedure ParseParams; function CheckHelpSwitch : Boolean; protected {$IFDEF CONSOLE} procedure GetColors; virtual; {$ENDIF} procedure Validate; virtual; public constructor Create(aAutoHelp : Boolean = True); virtual; destructor Destroy; override; property Description : string read fDescription write fDescription; {$IFDEF CONSOLE} property ColorizeHelp : TColorizeHelp read fColorizeHelp write fColorizeHelp; procedure ShowHelp; virtual; {$ENDIF} function GetHelp : TStringList; property Help : Boolean read fHelp write fHelp; function ExistsParam(const aParam : string): Boolean; overload; end; {$M-} TServiceParameters = class(TParameters) private fInstance : string; fInstall : Boolean; fRemove : Boolean; fConsole : Boolean; published [ParamHelp('Install service with a custom name','Service name')] property Instance : string read fInstance write fInstance; [ParamHelp('Install as a service')] property Install : Boolean read fInstall write fInstall; [ParamHelp('Remove service')] property &Remove : Boolean read fRemove write fRemove; [ParamHelp('Force run as a console application (when runned from another service)')] property Console : Boolean read fConsole write fConsole; end; ENotValidCommandlineParameter = class(Exception); ERequiredParameterNotFound = class(Exception); EParameterValueNotFound = class(Exception); EParamValueNotSupported = class(Exception); implementation { TParameter } constructor TParameters.Create(aAutoHelp : Boolean = True); begin {$IFDEF CONSOLE} fColorizeHelp := TColorizeHelp.Create; GetColors; {$ENDIF} fParams := TObjectList<TParam>.Create(True); ParseParams; {$IFDEF CONSOLE} if (aAutoHelp) and (fHelp) then begin ShowHelp; Halt; end; {$ENDIF} Validate; end; destructor TParameters.Destroy; begin fParams.Free; {$IFDEF CONSOLE} if Assigned(fColorizeHelp) then fColorizeHelp.Free; fColorizeHelp := nil; {$ENDIF} inherited; end; function TParameters.ExistParam(aParameter : TParam; const aParam : string) : Boolean; var i : Integer; parName : string; begin Result := False; if aParam.IsEmpty then Exit; for i := 1 to ParamCount do begin parName := ParamStr(i); if parName = aParameter.ValueSeparator then raise ENotValidCommandlineParameter.CreateFmt('Not valid commandline "%s"', [parName]); parName := GetParamName(aParameter,ParamStr(i)); if CompareText(parName,aParam) = 0 then Exit(True); end; end; function TParameters.GetParamName(aParameter : TParam; const aParam : string) : string; var switch : string; begin if CompareText(aParam,'-' + aParameter.Alias) = 0 then switch := '-' else switch := aParameter.SwitchChar; if aParam.StartsWith(switch) then Result := aParam.Substring(switch.Length); if Result.Contains(aParameter.ValueSeparator) then Result := Result.Substring(0,Result.IndexOf(aParameter.ValueSeparator)); end; function TParameters.GetParamValue(aParameter : TParam; const aParam : string) : string; var i : Integer; parName : string; param : string; begin Result := ''; for i := 1 to ParamCount do begin param := ParamStr(i); parName := GetParamName(aParameter,param); if CompareText(parName,aParam) = 0 then begin if aParameter.ValueIsNextParam then begin if i < ParamCount then Result := ParamStr(i+1); end else begin if param.Contains(aParameter.ValueSeparator) then Result := param.Substring(param.IndexOf(aParameter.ValueSeparator)+(aParameter.ValueSeparator.Length)); end; Exit; end; end; end; function TParameters.CheckHelpSwitch: Boolean; var param : TParam; begin param := TParam.Create; param.Name := 'help'; param.Alias := 'h'; try Result := ExistParam(param,param.Name); finally param.Free; end; end; function TParameters.ExistsParam(const aParam : string): Boolean; var param : TParam; begin param := TParam.Create; param.Name := aParam; param.Alias := ''; try Result := ExistParam(param,param.Name); finally param.Free; end; end; procedure TParameters.ParseParams; var param : TParam; value : TValue; valueint : Int64; valuefloat : Extended; rType : TRttiType; rProp : TRttiProperty; attr : TCustomAttribute; pinfo : PTypeInfo; found : Boolean; begin fHelp := CheckHelpSwitch; rType := TRTTI.GetType(Self.ClassInfo); //get main info for attr in rType.GetAttributes do begin if attr is CommandDescription then Self.Description := CommandDescription(attr).Description; end; //get parameters for rProp in TRTTI.GetProperties(rType,TRttiPropertyOrder.roFirstBase) do begin if rProp.Visibility <> TMemberVisibility.mvPublished then continue; param := TParam.Create; fParams.Add(param); param.Name := rProp.Name; for attr in rProp.GetAttributes do begin if attr is ParamHelp then begin param.Help := ParamHelp(attr).Help; param.HepValueName := ParamHelp(attr).ValueName; end; if attr is ParamName then begin param.Name := ParamName(attr).Name; param.Alias := ParamName(attr).Alias; end; if attr is ParamCommand then param.PrecisePosition := ParamCommand(attr).Position; if attr is ParamRequired then param.Required := True; if attr is ParamSwitchChar then param.SwitchChar := ParamSwitchChar(attr).SwitchChar; if attr is ParamValueSeparator then param.ValueSeparator := ParamValueSeparator(attr).ValueSeparator; if attr is ParamValueIsNextParam then param.ValueIsNextParam := True; end; param.ParamType := ValueType(rProp); if param.IsCommand then begin found := ParamCount >= param.PrecisePosition; param.SwitchChar := ' '; if param.ValueIsSwitch then found := False; end else found := (ExistParam(param,param.Name)) or (ExistParam(param,param.Alias)); value := nil; if found then begin if param.IsSwitch then begin value := True; end else begin if param.IsCommand then param.Value := ParamStr(param.PrecisePosition) else param.Value := GetParamValue(param,param.Name); if (param.Value.IsEmpty) and (not param.Alias.IsEmpty) then param.Value := GetParamValue(param,param.Alias); if (not param.Value.IsEmpty) and (not fHelp) then case param.ParamType of TValueType.vtString : begin value := param.Value; end; TValueType.vtInteger : begin if not TryStrToInt64(param.Value,valueint) then raise EParamValueNotSupported.CreateFmt('Parameter "%s" needs a numeric value',[param.Name]); value := valueint; end; TValueType.vtFloat : begin if not TryStrToFloat(param.Value,valuefloat) then raise EParamValueNotSupported.CreateFmt('Parameter "%s" needs a float value',[param.Name]); value := valuefloat; end; TValueType.vtEnumeration : begin pinfo := TRTTI.GetPropertyValue(Self,param.Name).TypeInfo; if not IsInteger(param.Value) then TValue.Make(GetEnumValue(pinfo,param.Value),pinfo,value) else TValue.Make(StrToInt(param.Value),pinfo,value); end; end; end; param.IsPresent := True; if not value.IsEmpty then rProp.SetValue(Self,value); end; end; //add help param := TParam.Create; param.Name := 'Help'; param.Alias := 'h'; param.ParamType := TValueType.vtBoolean; param.Help := 'Show this documentation'; fParams.Add(param); end; procedure TParameters.Validate; var param : TParam; begin if help then Exit; for param in fParams do begin if param.IsPresent then begin if (not param.IsSwitch) and (param.Value.IsEmpty) then raise EParamValueNotSupported.CreateFmt('Value for parameter "%s" not specified',[param.Name]); end else begin if param.Required then raise ERequiredParameterNotFound.CreateFmt('Required parameter "%s" not found',[param.Name]); end; end; end; function TParameters.ValueType(const aProp: TRttiProperty): TValueType; var rType : TRttiType; begin rType := aProp.PropertyType; case rType.TypeKind of tkString, tkWideString, tkChar, tkUnicodeString : Result := TValueType.vtString; tkInteger, tkInt64 : Result := TValueType.vtInteger; tkFloat : Result := TValueType.vtFloat; tkEnumeration : begin if TRTTI.GetPropertyValue(Self,aProp.Name).TypeInfo = System.TypeInfo(Boolean) then Result := TValueType.vtBoolean else Result := TValueType.vtEnumeration; end; else raise EParamValueNotSupported.CreateFmt('Parameter "%s": Value not supported',[aProp.Name]); end; end; {$IFDEF CONSOLE} procedure TParameters.ShowHelp; var version : string; arg : string; value : string; usage : string; commands : string; param : TParam; maxlen : Integer; arglen : Integer; begin //show app and version version := GetAppVersionStr; if version.IsEmpty then cout(GetAppName,fColorizeHelp.CommandName) else cout(Format('%s v.%s',[GetAppName,GetAppVersionStr]),fColorizeHelp.CommandName); usage := ''; maxlen := 0; commands := ''; //show usage arglen := 0; for param in fParams do begin if (param.Name.Length + param.Alias.Length) > maxlen then maxlen := param.Name.Length + param.Alias.Length; if param.Required then arg := '<' + param.SwitchChar + param.Name +'%s>' else arg := '[' + param.SwitchChar + param.Name + '%s]'; if param.IsSwitch then begin arg := Format(arg,['']); end else if param.IsCommand then begin if param.HepValueName.IsEmpty then value := param.Name else value := param.HepValueName; if param.Required then commands := commands + Format('<%s> ',[value]) else commands := commands + Format('[%s] ',[value]); Continue; end else begin if param.ValueIsNextParam then value := ' <value>' else value := param.ValueSeparator + '<value>'; if not param.HepValueName.IsEmpty then value := StringReplace(value,'value',param.HepValueName,[rfIgnoreCase,rfReplaceAll]); arg := Format(arg,[value]); end; //fit usage line arglen := arglen + arg.Length; if arglen > 80 then begin usage := usage + #10 + FillStr(' ',8 + (GetAppName.Length)); arglen := arg.Length; end; usage := usage + arg + ' '; end; maxlen := maxlen + 5; coutSL('Usage: ',fColorizeHelp.Sections); coutSL(Format('%s %s%s',[GetAppName,commands,usage]),fColorizeHelp.CommandUsage); cout('',ccWhite); cout('',ccWhite); //show description cout(Description,fColorizeHelp.CommandDescription); cout('',ccWhite); //show arguments cout('Arguments:',fColorizeHelp.Sections); cout('',ccWhite); for param in fParams do begin //if param.IsCommand then Continue; if param.Alias.IsEmpty then begin coutSL(Format(' %s%s%s',[param.SwitchChar,param.Name,FillStr(' ',maxlen - param.Name.Length)]),fColorizeHelp.ArgumentName); end else begin coutSL(Format(' %s%s, -%s%s',[param.SwitchChar,param.Name,param.Alias,FillStr(' ',maxlen - (param.Name.Length + param.Alias.Length + 3))]),fColorizeHelp.ArgumentName); end; coutSL(param.Help,fColorizeHelp.ArgumentDescription); cout('',ccWhite); end; cout('',ccWhite); end; procedure TParameters.GetColors; begin fColorizeHelp.CommandName := ccLightCyan; fColorizeHelp.CommandDescription := ccDarkGray; fColorizeHelp.CommandUsage := ccLightGray; fColorizeHelp.fSections := ccWhite; fColorizeHelp.ArgumentName := ccWhite; fColorizeHelp.ArgumentDescription := ccLightGray; end; {$ENDIF} function TParameters.GetHelp : TStringList; var line : string; version : string; arg : string; value : string; usage : string; commands : string; param : TParam; maxlen : Integer; arglen : Integer; begin Result := TStringList.Create; line := ''; //show app and version version := GetAppVersionStr; if version.IsEmpty then Result.Add(GetAppName) else Result.Add(Format('%s v.%s',[GetAppName,GetAppVersionStr])); usage := ''; maxlen := 0; commands := ''; //show usage arglen := 0; for param in fParams do begin if (param.Name.Length + param.Alias.Length) > maxlen then maxlen := param.Name.Length + param.Alias.Length; if param.Required then arg := '<' + param.SwitchChar + param.Name +'%s>' else arg := '[' + param.SwitchChar + param.Name + '%s]'; if param.IsSwitch then begin arg := Format(arg,['']); end else if param.IsCommand then begin if param.HepValueName.IsEmpty then value := param.Name else value := param.HepValueName; if param.Required then commands := commands + Format('<%s> ',[value]) else commands := commands + Format('[%s] ',[value]); Continue; end else begin if param.ValueIsNextParam then value := ' <value>' else value := param.ValueSeparator + '<value>'; if not param.HepValueName.IsEmpty then value := StringReplace(value,'value',param.HepValueName,[rfIgnoreCase,rfReplaceAll]); arg := Format(arg,[value]); end; //fit usage line arglen := arglen + arg.Length; if arglen > 80 then begin usage := usage + #10 + FillStr(' ',8 + (GetAppName.Length)); arglen := arg.Length; end; usage := usage + arg + ' '; end; maxlen := maxlen + 5; Result.Add(Format('Usage: %s %s%s',[GetAppName,commands,usage])); Result.Add(''); Result.Add(''); //show description Result.Add(Description); Result.Add(''); //show arguments Result.Add('Arguments:'); Result.Add(''); for param in fParams do begin //if param.IsCommand then Continue; line := ''; if param.Alias.IsEmpty then begin line := line + Format(' %s%s%s',[param.SwitchChar,param.Name,FillStr(' ',maxlen - param.Name.Length)]); end else begin line := line + Format(' %s%s, -%s%s',[param.SwitchChar,param.Name,param.Alias,FillStr(' ',maxlen - (param.Name.Length + param.Alias.Length + 3))]); end; line := line + param.Help; Result.Add(line); Result.Add(''); end; end; { CommandDescription } constructor CommandDescription.Create(const aDescription: string); begin fDescription := aDescription; end; { ParamName } constructor ParamName.Create(const aName: string; const aAlias : string = ''); begin fName := aName; fAlias := aAlias; end; { ParamHelp } constructor ParamHelp.Create(const aHelp : string; const aValueName : string = ''); begin fHelp := aHelp; if not aValueName.IsEmpty then fValueName := aValueName else fValueName := 'value'; end; { TParameters.TParam } constructor TParameters.TParam.Create; begin IsPresent := False; fSwitchChar := '--'; fValueSeparator := '='; fPrecisePosition := 0; end; function TParameters.TParam.IsCommand: Boolean; begin Result := fPrecisePosition > 0; end; function TParameters.TParam.IsSwitch: Boolean; begin Result := fParamType = TValueType.vtBoolean; end; function TParameters.TParam.ValueIsSwitch: Boolean; begin Result := (fValue.StartsWith('/')) or (fValue.StartsWith('-')) or (fValue.StartsWith(fSwitchChar)); end; { ParamSwitchChar } constructor ParamSwitchChar.Create(const aSwitchChar: string); begin fSwithChar := aSwitchChar; end; { ParamValueSeparator } constructor ParamValueSeparator.Create(const aValueSeparator: string); begin fValueSeparator := aValueSeparator; end; { ParamCommand } constructor ParamCommand.Create(aPosition: Integer); begin fPosition := aPosition; end; end.
unit uBaseMainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBaseForm, ActnList, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinscxPCPainter, dxRibbonSkins, dxSkinOffice2013White, dxSkinsdxRibbonPainter, dxRibbonCustomizationForm, dxSkinsdxBarPainter, dxBar, dxStatusBar, dxRibbonStatusBar, cxClasses, dxRibbon, ImgList, uBaseData; type TBaseMainForm = class(TBaseForm) barman: TdxBarManager; ribMain: TdxRibbonTab; ribbon: TdxRibbon; ribHelp: TdxRibbonTab; actAbout: TAction; actHelp: TAction; dxBarLargeButton12: TdxBarLargeButton; dxBarLargeButton13: TdxBarLargeButton; stbMain: TdxRibbonStatusBar; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); private protected function GetBaseData: TBaseData; procedure AfterChangeConnectionState(Sender: TObject); virtual; public function GetMainFormCaption: string; end; var BaseMainForm: TBaseMainForm; implementation uses cxGridStrs, uServices, JclFileUtils, JclDateTime, StrUtils; {$R *.dfm} procedure TBaseMainForm.FormDestroy(Sender: TObject); var Data: TBaseData; lSecurityService: ISecurityService; begin Data := GetBaseData; if Data <> nil then begin Data.AfterConnect.UnRegisterListener(AfterChangeConnectionState); Data.AfterDisconnect.UnRegisterListener(AfterChangeConnectionState); end; if Services.TryGetService(ISecurityService, lSecurityService) then begin lSecurityService.AfterLogin.UnRegisterListener(AfterChangeConnectionState); lSecurityService.AfterLogout.UnRegisterListener(AfterChangeConnectionState); end; inherited; end; procedure TBaseMainForm.AfterChangeConnectionState(Sender: TObject); var SecurityService: ISecurityService; SqlService: ISqlService; begin if Services.TryGetService(ISqlService, SqlService) then stbMain.Panels[0].Text := SqlService.DatabaseToString; if Services.TryGetService(ISecurityService, SecurityService) then stbMain.Panels[1].Text := 'Пользователь: ' + SecurityService.CurrentUserFio; end; procedure TBaseMainForm.FormCreate(Sender: TObject); var Data: TBaseData; lSecurityService: ISecurityService; begin inherited; Data := GetBaseData; if Data <> nil then begin Data.AfterConnect.RegisterListener(AfterChangeConnectionState); Data.AfterDisconnect.RegisterListener(AfterChangeConnectionState); AfterChangeConnectionState(Data.conMain); end; if Services.TryGetService(ISecurityService, lSecurityService) then begin lSecurityService.AfterLogin.RegisterListener(AfterChangeConnectionState); lSecurityService.AfterLogout.RegisterListener(AfterChangeConnectionState); end; Caption := GetMainFormCaption(); end; function TBaseMainForm.GetBaseData: TBaseData; var Data: TBaseData; SqlService: ISqlService; begin Data := nil; if Services.TryGetService(ISqlService, SqlService) then begin Data := TBaseData(SqlService.DataModule); end; Result := Data; end; function TBaseMainForm.GetMainFormCaption: string; var Ver: TJclFileVersionInfo; begin Result := Caption; try Ver := TJclFileVersionInfo.Create(Application.ExeName); Result := Application.Title + '. Версия ' + Ver.BinFileVersion + ' от ' + DateToStr(FileTimeToDateTime(GetFileLastWrite(Application.ExeName))); Ver.Free; except end; end; initialization cxSetResourceString(@scxGridGroupByBoxCaption, 'Перетяните заголовок столбца для группировки данных по нему ...'); end.
unit ComponentPoolData; interface uses System.SysUtils, System.Classes, CrossPlatformHeaders, fmx.Forms, System.Generics.Collections, System.Diagnostics, System.SyncObjs, FMX.Types; type TcomponentPool<ComponentType : TFmxObject> = class private container : TStack<ComponentType>; genSize : Integer; generateThread : Tthread; mutex : TSemaphore; procedure generatePool( size : integer ); function createComponent() : ComponentType; public constructor Create( generateSize : Integer = 10 ); destructor destroy(); override; function getComponent(): ComponentType; procedure returnComponent( t : ComponentType ); end; implementation constructor TComponentPool<ComponentType>.create( generateSize : Integer = 10 ); begin inherited Create(); container := TStack<ComponentType>.create(); gensize := generateSize; generatePool( genSize ); mutex := TSemaphore.Create(); end; destructor TComponentPool<ComponentType>.destroy(); var it : TStack<ComponentType>.TEnumerator; begin if generateThread <> nil then begin generateThread.Terminate; generateThread.WaitFor; generateThread.Free; end; it := container.GetEnumerator; while( it.MoveNext )do begin it.Current.free; end; it.Free; container.Free; mutex.Free; inherited; end; function TComponentPool<ComponentType>.createComponent() : ComponentType; begin result := ComponentType.create( nil ); end; procedure TComponentPool<ComponentType>.generatePool( size : integer ); begin if generateThread <> nil then begin generateThread.Terminate; generateThread.WaitFor; generateThread.Free; end; generateThread := TThread.CreateAnonymousThread( procedure begin while( container.Count < genSize ) do begin returnComponent( createComponent ); end; end); generateThread.FreeOnTerminate := false; generateThread.Start; end; procedure TComponentPool<ComponentType>.returnComponent( t : ComponentType ); begin if t.owner <> nil then raise Exception.Create('Component can not have owner'); t.parent := nil; mutex.Acquire; container.Push( t ); mutex.Release; end; function TComponentPool<ComponentType>.getComponent(): ComponentType; begin mutex.Acquire; if container.Count > 0 then begin result := container.Pop; end else begin result := createComponent(); end; mutex.Release; end; end.
{******************************************************************************* 作者: dmzn@163.com 2008-08-07 描述: 系统数据库常量定义 备注: *.自动创建SQL语句,支持变量:$Inc,自增;$Float,浮点;$Integer=sFlag_Integer; $Decimal=sFlag_Decimal;$Image,二进制流 *******************************************************************************} unit USysDB; {$I Link.inc} interface uses SysUtils, Classes; const cSysDatabaseName: array[0..4] of String = ( 'Access', 'SQL', 'MySQL', 'Oracle', 'DB2'); //db names type TSysDatabaseType = (dtAccess, dtSQLServer, dtMySQL, dtOracle, dtDB2); //db types PSysTableItem = ^TSysTableItem; TSysTableItem = record FTable: string; FNewSQL: string; end; //系统表项 PNameAndValue = ^TNameAndValue; TNameAndValue = record FName : string; //数据名称 FDesc : string; //数据描述 FValue : string; //数据取值 end; //基础档案 PBaseDataItem = ^TBaseDataItem; TBaseDataItem = record FRecord : string; //记录编号 FGroup : string; //分组标识 FGroupName: string; //分组名称 FName : string; //名称 FParamA : string; //参数A FParamB : string; //参数B FDefault : Boolean; //默认值 FMemo : string; //备注信息 end; var gSysTableList: TList = nil; //系统表数组 gSysDBType: TSysDatabaseType = dtSQLServer; //系统数据类型 //------------------------------------------------------------------------------ const //自增字段 sField_Access_AutoInc = 'Counter'; sField_SQLServer_AutoInc = 'Integer IDENTITY (1,1) PRIMARY KEY'; //小数字段 sField_Access_Decimal = 'Float'; sField_SQLServer_Decimal = 'Decimal(15, 5)'; //图片字段 sField_Access_Image = 'OLEObject'; sField_SQLServer_Image = 'Image'; //日期相关 sField_SQLServer_Now = 'getDate()'; const sFlag_Base_Lanuage = 'lanuage'; //基础档案: 语言 sFlag_Base_Author = 'author'; //基础档案: 作者 sFlag_Base_Publish = 'publish'; //基础档案: 出版社 sFlag_Base_Provide = 'provide'; //基础档案: 供货商 sFlag_Base_Age = 'age'; //基础档案: 年龄段 sFlag_Base_Payment = 'payment'; //基础档案: 付款方式 sFlag_Base_BookClass = 'bookclass'; //基础档案: 图书分类 sFlag_Base_MemLevel = 'memlevel'; //基础档案: 会员等级 sFlag_Base_Goods = 'goods'; //基础档案: 零售商品 sFlag_Language_CN = '中文'; sFlag_Language_EN = '英文'; sFlag_Language_Default = sFlag_Language_CN + '|' + sFlag_Language_EN; sFlag_Member_Level_VIP = 'VIP会员'; sFlag_Member_Level_Common = '普通会员'; sFlag_Member_Levels = sFlag_Member_Level_VIP + '|' + sFlag_Member_Level_Common; //会员等级列表 cBaseData: array[0..8] of TNameAndValue = ( (FName: sFlag_Base_Lanuage; FDesc: '语言'; FValue: sFlag_Language_Default), (FName: sFlag_Base_Author; FDesc: '作者'; FValue: ''), (FName: sFlag_Base_Publish; FDesc: '出版社'; FValue: ''), (FName: sFlag_Base_Provide; FDesc: '供应商'; FValue: ''), (FName: sFlag_Base_Age; FDesc: '年龄段'; FValue: ''), (FName: sFlag_Base_MemLevel; FDesc: '会员等级'; FValue: sFlag_Member_Levels), (FName: sFlag_Base_Payment; FDesc: '付款方式'; FValue: ''), (FName: sFlag_Base_BookClass;FDesc: '图书分类'; FValue: ''), (FName: sFlag_Base_Goods; FDesc: '零售商品'; FValue: '') ); //基础项列表 ResourceString {*权限项*} sPopedom_Read = 'A'; //浏览 sPopedom_Add = 'B'; //添加 sPopedom_Edit = 'C'; //修改 sPopedom_Delete = 'D'; //删除 sPopedom_Preview = 'E'; //预览 sPopedom_Print = 'F'; //打印 sPopedom_Export = 'G'; //导出 {*相关标记*} sFlag_Yes = 'Y'; //是 sFlag_No = 'N'; //否 sFlag_Enabled = 'Y'; //启用 sFlag_Disabled = 'N'; //禁用 sFlag_Integer = 'I'; //整数 sFlag_Decimal = 'D'; //小数 sFlag_Male = 'M'; //性别: 男 sFlag_Female = 'F'; //性别: 女 sFlag_In = 'I'; //方向: 进系统 sFlag_Out = 'O'; //方向: 出系统 sFlag_ID_BusGroup = 'BusFunction'; //业务编码组 sFlag_ID_Member = 'Bus_Member'; //会员编号 sFlag_ID_Books = 'Bus_Books'; //图书档案编号 sFlag_ID_BookDtl = 'Bus_BookDtl'; //图书明细编号 sFlag_PlayArea = 'yw001'; //游玩区标识 sFlag_Member = 'Member'; //会员相关 {*数据表*} sTable_Group = 'Sys_Group'; //用户组 sTable_User = 'Sys_User'; //用户表 sTable_Menu = 'Sys_Menu'; //菜单表 sTable_Popedom = 'Sys_Popedom'; //权限表 sTable_PopItem = 'Sys_PopItem'; //权限项 sTable_Entity = 'Sys_Entity'; //字典实体 sTable_DictItem = 'Sys_DataDict'; //字典明细 sTable_SysDict = 'Sys_Dict'; //系统字典 sTable_ExtInfo = 'Sys_ExtInfo'; //附加信息 sTable_SysLog = 'Sys_EventLog'; //系统日志 sTable_SerialBase = 'Sys_SerialBase'; //编码种子 sTable_BaseInfo = 'Sys_BaseInfo'; //基础信息 sTable_Members = 'M_Members'; //会员档案 sTable_InOutMoney = 'M_InOutMoney'; //资金明细 sTable_PlayGoods = 'M_PlayGoods'; //游玩零售 sTable_Books = 'B_Books'; //图书 sTable_BookDetail = 'B_BookDtl'; //图书明细(丛书) sTable_BookInOut = 'B_BookInOut'; //出入库记录 sTable_BookBorrow = 'B_BookBorrow'; //图书借阅 sTable_BookSale = 'B_BookSale'; //图书销售 {*新建表*} sSQL_NewSysDict = 'Create Table $Table(D_ID $Inc, D_Name varChar(15),' + 'D_Desc varChar(30), D_Value varChar(50), D_Memo varChar(20),' + 'D_ParamA $Float, D_ParamB varChar(50), D_Index Integer Default 0)'; {----------------------------------------------------------------------------- 系统字典: SysDict *.D_ID: 编号 *.D_Name: 名称 *.D_Desc: 描述 *.D_Value: 取值 *.D_Memo: 相关信息 *.D_ParamA: 浮点参数 *.D_ParamB: 字符参数 *.D_Index: 显示索引 -----------------------------------------------------------------------------} sSQL_NewExtInfo = 'Create Table $Table(I_ID $Inc, I_Group varChar(20),' + 'I_ItemID varChar(20), I_Item varChar(30), I_Info varChar(500),' + 'I_ParamA $Float, I_ParamB varChar(50), I_Index Integer Default 0)'; {----------------------------------------------------------------------------- 扩展信息表: ExtInfo *.I_ID: 编号 *.I_Group: 信息分组 *.I_ItemID: 信息标识 *.I_Item: 信息项 *.I_Info: 信息内容 *.I_ParamA: 浮点参数 *.I_ParamB: 字符参数 *.I_Memo: 备注信息 *.I_Index: 显示索引 -----------------------------------------------------------------------------} sSQL_NewSysLog = 'Create Table $Table(L_ID $Inc, L_Date DateTime,' + 'L_Man varChar(32),L_Group varChar(20), L_ItemID varChar(20),' + 'L_KeyID varChar(20), L_Event varChar(220))'; {----------------------------------------------------------------------------- 系统日志: SysLog *.L_ID: 编号 *.L_Date: 操作日期 *.L_Man: 操作人 *.L_Group: 信息分组 *.L_ItemID: 信息标识 *.L_KeyID: 辅助标识 *.L_Event: 事件 -----------------------------------------------------------------------------} sSQL_NewSerialBase = 'Create Table $Table(R_ID $Inc, B_Group varChar(15),' + 'B_Object varChar(32), B_Prefix varChar(25), B_IDLen Integer,' + 'B_Base Integer, B_Date DateTime)'; {----------------------------------------------------------------------------- 串行编号基数表: SerialBase *.R_ID: 编号 *.B_Group: 分组 *.B_Object: 对象 *.B_Prefix: 前缀 *.B_IDLen: 编号长 *.B_Base: 基数 *.B_Date: 参考日期 -----------------------------------------------------------------------------} sSQL_NewBaseInfo = 'Create Table $Table(B_ID $Inc, B_Group varChar(15),' + 'B_GroupName varChar(50), B_Text varChar(100), B_Py varChar(25),' + 'B_ParamA varChar(100), B_ParamB varChar(100), B_Default Char(1),' + 'B_Memo varChar(50), B_PID Integer, B_Index Float)'; {----------------------------------------------------------------------------- 基本信息表: BaseInfo *.B_ID: 编号 *.B_Group: 分组 *.B_Text: 内容 *.B_Py: 拼音简写 *.B_ParamA,B_ParamB:参数 *.B_Default: 默认 *.B_Memo: 备注信息 *.B_PID: 上级节点 *.B_Index: 创建顺序 -----------------------------------------------------------------------------} sSQL_NewMembers = 'Create Table $Table(R_ID $Inc, M_ID varChar(15),' + 'M_Name varChar(32), M_Py varChar(25), M_Card varChar(32),' + 'M_Phone varChar(32), M_Sex Char(1), M_Level varChar(100),' + 'M_JoinDate DateTime, M_ValidDate DateTime, ' + 'M_BorrowNum Integer, M_BorrowBooks Integer,' + 'M_BuyNum Integer, M_BuyBooks Integer,' + 'M_NoReturnAllowed Integer,' + 'M_MonCH Integer, M_MonCHHas Integer,' + 'M_MonEN Integer, M_MonENHas Integer, M_Month varChar(10),' + 'M_PlayArea Integer, M_Memo varChar(50))'; {----------------------------------------------------------------------------- 会员档案: Members *.R_ID: 记录编号 *.M_ID: 会员编号 *.M_Name,M_Py: 会员名称 *.M_Card: 会员卡号 *.M_Phone: 手机号 *.M_Sex: 性别 *.M_Level: 会员等级 *.M_JoinDate: 入会时间 *.M_ValidDate: 有效时间 *.M_BorrowNum: 借阅次数 *.M_BorrowBooks: 书本数 *.M_BuyNum: 购买次数 *.M_BuyBooks: 购买本数 *.M_NoReturnAllowed: 允许借出未还的本数 *.M_MonCH: 可借阅中文本数 *.M_MonCHHas: 当月中文已借 *.M_MonEN: 可借阅外文本数 *.M_MonENHas: 当月英文已借 *.M_Month: 计数月份 *.M_PlayArea: 游玩区计数 *.M_Memo: 备注信息 -----------------------------------------------------------------------------} sSQL_NewInOutMoney = 'Create Table $Table(R_ID $Inc, M_MemID varChar(15),' + 'M_MemName varChar(80), M_Type Char(1), M_Payment varChar(100),' + 'M_Money $Float, M_Man varChar(32),' + 'M_Date DateTime, M_Memo varChar(200))'; {----------------------------------------------------------------------------- 出入金明细: InOutMoney *.M_MemID: 会员编号 *.M_MemName:会员姓名 *.M_Type: 入金,出金 *.M_Payment:付款方式 *.M_Money:缴纳金额 *.M_Date:操作日期 *.M_Man:操作人 *.M_Memo:描述 -----------------------------------------------------------------------------} sSQL_NewBooks = 'Create Table $Table(R_ID $Inc, B_ID varChar(15),' + 'B_ISBN varChar(32), B_Name varChar(100), B_Py varChar(100),' + 'B_Author varChar(80), B_Lang varChar(80), B_Class varChar(80),' + 'B_NumAll Integer, B_NumIn Integer, B_NumOut Integer,' + 'B_NumSale Integer, B_Valid Char(1),' + 'B_Man varChar(32), B_Date DateTime, B_Memo varChar(200))'; {----------------------------------------------------------------------------- 图书档案: Books *.B_ID: 图书编号 *.B_ISBN: isbn *.B_Name,B_Py: 图书名称 *.B_Author:作者 *.B_Lang:语种 *.B_Class:分类 *.B_NumAll: 总库存 *.B_NumIn: 未出借 *.B_NumOut: 已出借 *.B_NumSale: 售出量 *.B_Valid: 有效(Y/N) *.B_Date:建档日期 *.B_Man:建档人 *.B_Memo:备注 -----------------------------------------------------------------------------} sSQL_NewBookDtl = 'Create Table $Table(R_ID $Inc, D_ID varChar(15),' + 'D_Book varChar(15), D_ISBN varChar(32),' + 'D_Name varChar(100), D_Py varChar(100),' + 'D_Author varChar(80), D_AuthorPy varChar(80),' + 'D_Publisher varChar(80), D_PubTime varChar(80), D_Provider varChar(80),' + 'D_PubPrice $Float, D_GetPrice $Float, D_SalePrice $Float,' + 'D_NumAll Integer, D_NumIn Integer, D_NumOut Integer,' + 'D_NumSale Integer, D_Valid Char(1),' + 'D_Man varChar(32), D_Date DateTime, D_Memo varChar(200))'; {----------------------------------------------------------------------------- 图书明细: BookDtl *.D_ID: 图书编号 *.D_Book: 图书档案 *.D_ISBN: isbn *.D_Name,D_Py: 图书名称 *.D_Author,D_AuthorPy:作者 *.D_Publisher:出版商 *.D_PubTime:版次 *.D_Provider:供应商 *.D_PubPrice:定价 *.D_GetPrice: 采购价 *.D_SalePrice: 销售价 *.D_NumAll: 总库存 *.D_NumIn: 未出借 *.D_NumOut: 已出借 *.D_NumSale: 售出量 *.D_Valid: 有效(Y/N) *.D_Man:入库人 *.D_Date:入库日期 *.D_Memo: 备注 -----------------------------------------------------------------------------} sSQL_NewBookInOut = 'Create Table $Table(R_ID $Inc, I_Book varChar(15),' + 'I_BookDtl varChar(15), I_Type Char(1), I_Num Integer, I_NumBefore Integer,' + 'I_Man varChar(32), I_Date DateTime, I_Memo varChar(200))'; {----------------------------------------------------------------------------- 图书出入库: BookInOut *.I_Book,I_BookDtl: 图书编号 *.I_Type: 入库/出库 *.I_Num: 图书数量 *.I_NumBefore: 未入库前库存 *.I_Man:入库人 *.I_Date:入库日期 *.I_Memo: 备注 -----------------------------------------------------------------------------} sSQL_NewBookBorrow = 'Create Table $Table(R_ID $Inc, B_Member varChar(15),' + 'B_Book varChar(15), B_BookDtl varChar(15), B_Type Char(1),' + 'B_NumBorrow Integer, B_NumReturn Integer,' + 'B_ManBorrow varChar(32), B_ManReturn varChar(32),' + 'B_DateBorrow DateTime, B_DateReturn DateTime, B_Memo varChar(200))'; {----------------------------------------------------------------------------- 图书借阅: BookBorrow *.B_Member: 会员编号 *.B_Book,B_BookDtl: 图书编号 *.B_Type: 借阅/购买 *.B_NumBorrow: 借阅数量 *.B_NumReturn: 归还数量 *.B_ManBorrow,B_ManReturn:操作人 *.B_DateBorrow,B_DateReturn:日期 *.B_Memo: 备注 -----------------------------------------------------------------------------} sSQL_NewBookSale = 'Create Table $Table(R_ID $Inc, S_Member varChar(15),' + 'S_Book varChar(15), S_BookDtl varChar(15), S_Type Char(1),' + 'S_Num Integer, S_Return Integer,' + 'S_Man varChar(32), S_Date DateTime, S_Memo varChar(200))'; {----------------------------------------------------------------------------- 图书销售: BookSale *.S_Member: 会员编号 *.S_Book,S_BookDtl: 图书编号 *.S_Type: 销售/退还 *.S_Num: 数量 *.S_Return: 退回 *.S_Man:操作人 *.S_Date:日期 *.S_Memo: 备注 -----------------------------------------------------------------------------} sSQL_NewPlayGoods = 'Create Table $Table(R_ID $Inc, P_Member varChar(15),' + 'P_GoodsID varChar(32), P_GoodsName varChar(100), P_GoodsPy varChar(100),' + 'P_Number Integer, P_Price $Float, P_Money $Float, P_Payment varChar(100),' + 'P_Man varChar(32), P_Date DateTime, P_Memo varChar(200))'; {----------------------------------------------------------------------------- 游玩零售: PlayGoods *.P_Member: 会员编号 *.P_GoodsID: 商品标识 *.P_GoodsName,P_GoodsPy: 商品名称 *.P_Number: 商品数量 *.P_Price: 商品价格 *.P_Money: 商品金额 *.P_Payment: 支付方式 *.P_Man:操作人 *.P_Date:日期 *.P_Memo: 备注 -----------------------------------------------------------------------------} implementation //------------------------------------------------------------------------------ //Desc: 添加系统表项 procedure AddSysTableItem(const nTable,nNewSQL: string); var nP: PSysTableItem; begin New(nP); gSysTableList.Add(nP); nP.FTable := nTable; nP.FNewSQL := nNewSQL; end; //Desc: 系统表 procedure InitSysTableList; begin gSysTableList := TList.Create; AddSysTableItem(sTable_SysDict, sSQL_NewSysDict); AddSysTableItem(sTable_ExtInfo, sSQL_NewExtInfo); AddSysTableItem(sTable_SysLog, sSQL_NewSysLog); AddSysTableItem(sTable_SerialBase, sSQL_NewSerialBase); AddSysTableItem(sTable_BaseInfo, sSQL_NewBaseInfo); AddSysTableItem(sTable_Members, sSQL_NewMembers); AddSysTableItem(sTable_InOutMoney, sSQL_NewInOutMoney); AddSysTableItem(sTable_Books, sSQL_NewBooks); AddSysTableItem(sTable_BookDetail, sSQL_NewBookDtl); AddSysTableItem(sTable_BookInOut, sSQL_NewBookInOut); AddSysTableItem(sTable_BookBorrow, sSQL_NewBookBorrow); AddSysTableItem(sTable_BookSale, sSQL_NewBookSale); AddSysTableItem(sTable_PlayGoods, sSQL_NewPlayGoods); end; //Desc: 清理系统表 procedure ClearSysTableList; var nIdx: integer; begin for nIdx:= gSysTableList.Count - 1 downto 0 do begin Dispose(PSysTableItem(gSysTableList[nIdx])); gSysTableList.Delete(nIdx); end; FreeAndNil(gSysTableList); end; initialization InitSysTableList; finalization ClearSysTableList; end.
UNIT Statistic; INTERFACE CONST AlphabetUp = ['A'..'Z', 'À'..'ß', '¨']; AlphabetDown = ['a'..'z', 'à'..'ÿ', '¸']; Alphabet = AlphabetUp + AlphabetDown; LetterChange = 32; PROCEDURE GetWord(VAR FInput: TEXT; VAR WordTree: STRING); IMPLEMENTATION PROCEDURE Checking(VAR Uncheked: CHAR); BEGIN{Checking} IF ((Uncheked = '¨') OR (Uncheked = '¸')) THEN Uncheked := 'å'; IF (Uncheked IN AlphabetUp) THEN Uncheked := CHR(ORD(Uncheked) + LetterChange); END;{Checking} PROCEDURE GetWord(VAR FInput: TEXT; VAR WordTree: STRING); VAR Ch: CHAR; BEGIN {GetWord} WordTree := ''; READ(FInput, Ch); WHILE NOT(Ch IN Alphabet) AND NOT EOF(FInput) DO READ(FInput, Ch); WHILE ((Ch IN Alphabet) AND NOT EOF(FInput)) DO BEGIN Checking(Ch); WordTree := WordTree + Ch; READ(FInput, Ch) END; IF (Ch IN Alphabet) AND EOF(FInput) THEN BEGIN Checking(Ch); WordTree := WordTree + Ch END END;{GetWord} BEGIN END.
unit ufrmTesteAtributos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Atributos, teste; type TfrmTesteAtributos = class(TForm) pnl1: TPanel; lb1: TLabel; mmo1: TMemo; btInserir: TButton; btSalvar: TButton; btExcluir: TButton; edId: TLabeledEdit; procedure btChavePrimClick(Sender: TObject); procedure btInserirClick(Sender: TObject); procedure btSalvarClick(Sender: TObject); procedure btExcluirClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } wId : Integer; public { Public declarations } end; var frmTesteAtributos: TfrmTesteAtributos; implementation Uses formOrm,Base, dmMeuORM; //DaoUib, Base; {$R *.dfm} procedure TfrmTesteAtributos.btChavePrimClick(Sender: TObject); var ATab: TTeste; Pk: TResultArray; chave: string; begin ATab := TTeste.Create; try Pk := PegaPks(ATab); mmo1.Clear; for chave in Pk do mmo1.Lines.Add(chave); finally ATab.Free; end; end; procedure TfrmTesteAtributos.btExcluirClick(Sender: TObject); var ATab: TTeste; Registros: Integer; begin ATab := TTeste.Create; wId := StrToInt(Trim(edId.Text)); try TDaoSingleton.Get.Con.StartTransaction; try Registros := TDaoSingleton.Get.Con.Excluir(ATab); TDaoSingleton.Get.Con.Commit; ATab.Id := wId; Mmo1.Lines.Add(Format('Registro excluido: %d', [Registros])); except on E: Exception do begin TDaoSingleton.Get.Con.RollBack; ShowMessage('Ocorreu um problema ao executar operação: ' + e.Message); end; end; finally ATab.Free; end; end; procedure TfrmTesteAtributos.btInserirClick(Sender: TObject); var ATab: TTeste; Registros: Integer; begin ATab := TTeste.Create; try Inc(wId); edId.Text := IntToStr(wId); with ATab do begin id := wId; Estado := 'MA'; Descricao := 'MARANHÃO'; Habitantes := 6569683; Data := Now; RendaPerCapta := 319; end; TDaoSingleton.Get.Con.StartTransaction; try Registros := TDaoSingleton.Get.Con.Inserir(ATab); TDaoSingleton.Get.Con.Commit; mmo1.Lines.Add(Format('Registro inserido: %d', [Registros])); mmo1.Lines.Add(Format('id: %d, nome: %s',[ATab.Id, atab.Descricao])); except on E: Exception do begin TDaoSingleton.Get.Con.RollBack; ShowMessage('Ocorreu um problema ao executar operação: ' + e.Message); end; end; finally ATab.Free; end; end; procedure TfrmTesteAtributos.btSalvarClick(Sender: TObject); var ATab: TTeste; Registros: Integer; begin ATab := TTeste.Create; wId := StrToInt(Trim(edId.Text)); try with ATab do begin id := wId; Estado := 'MA'; Descricao := 'MARANHÃO (ALTERADO)'; Data := Now; Habitantes := 6569683; RendaPerCapta := 319; end; TDaoSingleton.Get.Con.StartTransaction; try Registros := TDaoSingleton.Get.Con.Salvar(Atab); TDaoSingleton.Get.Con.Commit; Mmo1.Lines.Add(Format('Registro inserido: %d', [Registros])); Mmo1.Lines.Add(Format('id: %d, nome: %s',[ATab.Id, atab.Descricao])); except on E: Exception do begin TDaoSingleton.Get.Con.RollBack; ShowMessage('Ocorreu um problema ao executar operação: '+ e.Message); end; end; finally ATab.Free; end; end; procedure TfrmTesteAtributos.FormCreate(Sender: TObject); begin // dmMORM.conORM. dmMORM.SQL_1.SQL.Clear; dmMORM.SQL_1.SQL.Add('select * from Teste'); dmMORM.SQL_1.Open; wId := dmMORM.SQL_1.RowsAffected; edId.Text := Trim(IntToStr(wId)); end; end.
unit akAutoMover; interface uses Classes, Menus, Windows, Controls, Forms; const VM_MENUITEM = 0; VM_TOCLOSE = 1; VM_CONTROL = 2; type TAutoMover = class(TThread) private FMenuItem: TMenuItem; FMode: Integer; FTargetForm: TForm; FTargetControl: TControl; procedure SetMenuItem(const Value: TMenuItem); procedure SetMode(const Value: Integer); procedure SetTargetForm(const Value: TForm); procedure SetTargetControl(const Value: TControl); { Private declarations } private prevX: Integer; prevY: Integer; protected procedure Execute; override; procedure MoveMouseToMenuItem(target: TMenuItem); procedure MoveMouseToAnyMenuItem(target: TMenuItem); procedure MoveMouseToClose(target: TForm); procedure MoveMouseToControl(target: TControl); procedure PressLeftButton; procedure MoveMouseToPos(toPos: TPoint); property MenuItem: TMenuItem read FMenuItem write SetMenuItem; property TargetForm: TForm read FTargetForm write SetTargetForm; property TargetControl: TControl read FTargetControl write SetTargetControl; public property Mode: Integer read FMode write SetMode; procedure ExecuteMenuItem(mn: TMenuItem); procedure ExecuteCloseForm(fm: TForm); procedure ExecuteControl(cnt: TControl); end; implementation uses akMisc, akDataUtils; { TAutoMover } procedure TAutoMover.Execute; begin case Mode of VM_MENUITEM: MoveMouseToAnyMenuItem(MenuItem); VM_TOCLOSE: MoveMouseToClose(TargetForm); VM_CONTROL: MoveMouseToControl(TargetControl); end; end; procedure TAutoMover.MoveMouseToMenuItem(target: TMenuItem); var toPos: TPoint; rc: TRect; begin GetMenuItemRect(TWinControl(target.Owner).Handle, target.Parent.Handle, target.MenuIndex, rc); toPos.X := iifs(prevX = 0, rc.Left + 20, prevX + 20); toPos.Y := rc.Top + 8; // if prevX <> 0 then // prevX := rc.Left // else prevX := rc.Left; prevY := rc.Top; MoveMouseToPos(toPos); PressLeftButton; end; procedure TAutoMover.MoveMouseToAnyMenuItem(target: TMenuItem); var i: Integer; par: TList; l: TMenuItem; begin prevX := 0; prevY := 0; par := TList.Create; try l := target; while Assigned(l) do begin par.Add(l); l := l.Parent; end; par.Delete(par.Count - 1); for i := par.Count - 1 downto 0 do MoveMouseToMenuItem(par[i]); finally par.Free; end; end; procedure TAutoMover.PressLeftButton; begin mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); Sleep(100); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); Sleep(300); end; procedure TAutoMover.MoveMouseToPos(toPos: TPoint); var p: TPoint; r: TRect; dst: Integer; ps: TPoint; begin repeat GetCursorPos(ps); r := Rect(ps.x, ps.y, toPos.x, toPos.y); dst := DistOf(r); p := MovePointTo(r, 5); SetCursorPos(p.x, p.y); Sleep(10); if dst < 5 then dst := 0; until dst <= 0; end; procedure TAutoMover.SetMenuItem(const Value: TMenuItem); begin FMenuItem := Value; end; procedure TAutoMover.ExecuteMenuItem(mn: TMenuItem); begin Mode := VM_MENUITEM; MenuItem := mn; Resume; end; procedure TAutoMover.SetMode(const Value: Integer); begin FMode := Value; end; procedure TAutoMover.MoveMouseToClose(target: TForm); var toPos: TPoint; begin with target do begin toPos.X := Left + Width - 15; toPos.Y := Top + 15; end; MoveMouseToPos(toPos); PressLeftButton; end; procedure TAutoMover.SetTargetForm(const Value: TForm); begin FTargetForm := Value; end; procedure TAutoMover.ExecuteCloseForm(fm: TForm); begin Mode := VM_TOCLOSE; TargetForm := fm; Resume; end; procedure TAutoMover.MoveMouseToControl(target: TControl); var toPos: TPoint; rc: TRect; begin with target do begin rc := ClientRect; toPos.X := rc.Left + Round(ClientWidth / 2); toPos.Y := rc.Top + Round(ClientHeight / 2); toPos := ClientToScreen(toPos); end; MoveMouseToPos(toPos); PressLeftButton; end; procedure TAutoMover.SetTargetControl(const Value: TControl); begin FTargetControl := Value; end; procedure TAutoMover.ExecuteControl(cnt: TControl); begin Mode := VM_CONTROL; TargetControl := cnt; Resume; end; end.
unit mnSynHighlighterGo; {$mode objfpc}{$H+} {** * NOT COMPLETED * * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey * * https://www.tutorialspoint.com/go/go_basic_syntax.htm * *} interface uses Classes, SysUtils, SynEdit, SynEditTypes, SynEditHighlighter, SynHighlighterHashEntries, mnSynHighlighterMultiProc; type { TGoProcessor } TGoProcessor = class(TCommonSynProcessor) private protected function GetIdentChars: TSynIdentChars; override; function GetEndOfLineAttribute: TSynHighlighterAttributes; override; public procedure QuestionProc; procedure SlashProc; procedure GreaterProc; procedure LowerProc; procedure Next; override; procedure Prepare; override; procedure MakeProcTable; override; end; { TSynDSyn } TSynGoSyn = class(TSynMultiProcSyn) private protected function GetSampleSource: string; override; public class function GetLanguageName: string; override; public constructor Create(AOwner: TComponent); override; procedure InitProcessors; override; published end; const SYNS_LangGo = 'Go'; SYNS_FilterGo = 'Go Lang Files (*.go)|*.go'; cGoSample = 'package main'#13#10+ '//line comment'#13#10+ 'import "fmt"'#13#10+ 'func main() {'#13#10+ ' fmt.Println("hello world")'#13#10+ ' /* All rest of program here'#13#10+ ' */'#13#10+ '}'#13#10; {$INCLUDE 'GoKeywords.inc'} implementation uses mnUtils; procedure TGoProcessor.GreaterProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); if Parent.FLine[Parent.Run] in ['=', '>'] then Inc(Parent.Run); end; procedure TGoProcessor.LowerProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); case Parent.FLine[Parent.Run] of '=': Inc(Parent.Run); '<': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '=' then Inc(Parent.Run); end; end; end; procedure TGoProcessor.SlashProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '/': begin CommentSLProc; end; '*': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '*' then DocumentMLProc else CommentMLProc; end; else Parent.FTokenID := tkSymbol; end; end; procedure TGoProcessor.MakeProcTable; var I: Char; begin inherited; for I := #0 to #255 do case I of '?': ProcTable[I] := @QuestionProc; '''': ProcTable[I] := @StringSQProc; '"': ProcTable[I] := @StringDQProc; '`': ProcTable[I] := @StringBQProc; '/': ProcTable[I] := @SlashProc; '>': ProcTable[I] := @GreaterProc; '<': ProcTable[I] := @LowerProc; '0'..'9': ProcTable[I] := @NumberProc; 'A'..'Z', 'a'..'z', '_': ProcTable[I] := @IdentProc; end; end; procedure TGoProcessor.QuestionProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '>': begin Parent.Processors.Switch(Parent.Processors.MainProcessor); Inc(Parent.Run); Parent.FTokenID := tkProcessor; end else Parent.FTokenID := tkSymbol; end; end; procedure TGoProcessor.Next; begin Parent.FTokenPos := Parent.Run; if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then ProcTable[Parent.FLine[Parent.Run]] else case Range of rscComment: begin CommentMLProc; end; rscDocument: begin DocumentMLProc; end; rscStringSQ, rscStringDQ, rscStringBQ: StringProc; else if ProcTable[Parent.FLine[Parent.Run]] = nil then UnknownProc else ProcTable[Parent.FLine[Parent.Run]]; end; end; procedure TGoProcessor.Prepare; begin inherited; EnumerateKeywords(Ord(tkKeyword), sGoKeywords, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkFunction), sGoFunctions, TSynValidStringChars, @DoAddKeyword); SetRange(rscUnknown); end; function TGoProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes; begin if (Range = rscDocument) or (LastRange = rscDocument) then Result := Parent.DocumentAttri else Result := inherited GetEndOfLineAttribute; end; function TGoProcessor.GetIdentChars: TSynIdentChars; begin Result := TSynValidStringChars; end; constructor TSynGoSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); FDefaultFilter := SYNS_FilterGo; end; procedure TSynGoSyn.InitProcessors; begin inherited; Processors.Add(TGoProcessor.Create(Self, 'Go')); Processors.MainProcessor := 'Go'; Processors.DefaultProcessor := 'Go'; end; class function TSynGoSyn.GetLanguageName: string; begin Result := SYNS_LangGo; end; function TSynGoSyn.GetSampleSource: string; begin Result := cGoSample; end; end.
unit Creature; interface uses Engine, DGLE, DGLE_Types, Entity, Types, Bar, Digit; const CreatureFName: array [0..CREATURES_COUNT - 1] of AnsiString = ( 'Gnome.png', 'Spider.png' ); function GetDist(x1, y1, x2, y2: single): word; type TForce = (fcAlly, fcEnemy); type TCreature = class(TEntity) private FActive: Boolean; FLife: TBar; FForce: TForce; FTarget: TPoint; FSpeed: TBar; procedure SetActive(const Value: Boolean); procedure SetLife(const Value: TBar); procedure SetForce(const Value: TForce); procedure SetTarget(const Value: TPoint); procedure SetSpeed(const Value: TBar); public constructor Create(X, Y, ID: Integer; Force: TForce); destructor Destroy; override; property Active: Boolean read FActive write SetActive; property Life: TBar read FLife write SetLife; property Speed: TBar read FSpeed write SetSpeed; property Force: TForce read FForce write SetForce; property Target: TPoint read FTarget write SetTarget; procedure Move(X, Y: Integer); function MouseOver(): Boolean; end; type TACreature = array of TCreature; type TCreatures = class(TObject) private pLifebar: ITexture; pSelEnemyUnit: ITexture; pSelAllyUnit: ITexture; pSelUserUnit: ITexture; FCreature: TACreature; procedure SetCreature(const Value: TACreature); public constructor Create; destructor Destroy; override; procedure Add(X, Y, ID: Integer; Force: TForce); procedure ModLife(ID, Dam: Integer); function EmptyCell(X, Y: Integer): Boolean; property Creature: TACreature read FCreature write SetCreature; function GetCreatureID(X, Y: Integer): Integer; function GetTagret(C: Integer): Integer; procedure SetTargets; function Count: Integer; procedure Process(I: Integer); procedure Render(); procedure Update(); end; implementation uses SysUtils, Tile, uBox, uPF; function GetDist(x1, y1, x2, y2: single): word; begin Result := Round(sqrt(sqr(x2 - x1) + sqr(y2 - y1))); end; { TCreature } constructor TCreature.Create(X, Y, ID: Integer; Force: TForce); begin inherited Create(X, Y, ID, 'Resources\Sprites\Creatures\' + CreatureFName[ID], pResMan); Self.Target := Point(0, 0); Self.Active := True; Self.Force := Force; Life := TBar.Create; Life.SetMax(100); Life.SetToMax; Speed := TBar.Create; Speed.SetMax(100); Speed.SetToMax; end; destructor TCreature.Destroy; begin Speed.Free; Life.Free; inherited; end; function TCreature.MouseOver: Boolean; begin Result := (Round(ScreenPos.X) = Pos.X - MAP_LEFT) and (Round(ScreenPos.Y) = Pos.Y - MAP_TOP) end; procedure TCreature.Move(X, Y: Integer); begin SetPosition(Pos.X + X, Pos.Y + Y); end; procedure TCreature.SetActive(const Value: Boolean); begin FActive := Value; end; procedure TCreature.SetForce(const Value: TForce); begin FForce := Value; end; procedure TCreature.SetLife(const Value: TBar); begin FLife := Value; end; procedure TCreature.SetSpeed(const Value: TBar); begin FSpeed := Value; end; procedure TCreature.SetTarget(const Value: TPoint); begin FTarget := Value; end; { TCreatures } procedure TCreatures.Process(I: Integer); var J, E: Integer; var LX, LY, NX, NY, JX, JY: Integer; function FreeCell(AX, AY: Integer): Boolean; stdcall; begin Result := True or EmptyCell(AX, AY); end; { if (Length(Enemy) > 0) then for J := 0 to PC.AP.Max do for I := 0 to High(Enemy) do if not Enemy[I].Life.IsMin and not PC.Life.IsMin then begin with Enemy[I] do if AP.IsMin then begin Process; AP.SetToMax; end else AP.Dec; end; } begin SetTargets; if (I = CURRENT_ALLY) and Creature[CURRENT_ALLY].Speed.IsMin then begin for J := 0 to Count - 1 do if Creature[J].Active then Creature[J].Speed.SetToMax; end; // for I := 0 to Count - 1 do if Creature[I].Active then begin if not DoPF(MAP_WIDTH, MAP_HEIGHT, Creature[I].Pos.X, Creature[I].Pos.Y, Creature[I].Target.X, Creature[I].Target.Y, @FreeCell, NX, NY) then Exit;//Continue; if (NX <= 0) or (NY <= 0) then Exit;//Continue; if (GetDist(Creature[I].Target.X, Creature[I].Target.Y, Creature[I].Pos.X, Creature[I].Pos.Y) > 9) then Exit;//Continue; if (Creature[I].Speed.IsMin) then Exit;//Continue; if not EmptyCell(NX, NY) then begin E := GetCreatureID(NX, NY); if (E > -1) and (Creature[I].Force <> Creature[E].Force) then begin Self.ModLife(E, -Rand(5, 15)); Creature[I].Speed.SetToMin; end; Exit;//Continue; end; Creature[I].SetPosition(NX, NY); Creature[I].Speed.SetToMin; end; end; procedure TCreatures.Add(X, Y, ID: Integer; Force: TForce); var I: Integer; begin if (Count <> 0) then for I := 0 to Count - 1 do if not Creature[I].Active then begin Creature[I].Create(X, Y, ID, Force); Exit; end; SetLength(FCreature, Count + 1); Creature[Count - 1] := TCreature.Create(X, Y, ID, Force); end; function TCreatures.Count: Integer; begin Result := System.Length(Creature); end; constructor TCreatures.Create; begin pResMan.Load('Resources\Sprites\Interface\Lifebar.png', IEngineBaseObject(pLifebar), TEXTURE_LOAD_DEFAULT_2D); pResMan.Load('Resources\Sprites\Interface\SelEnemyUnit.png', IEngineBaseObject(pSelEnemyUnit), TEXTURE_LOAD_DEFAULT_2D); pResMan.Load('Resources\Sprites\Interface\SelAllyUnit.png', IEngineBaseObject(pSelAllyUnit), TEXTURE_LOAD_DEFAULT_2D); pResMan.Load('Resources\Sprites\Interface\SelUserUnit.png', IEngineBaseObject(pSelUserUnit), TEXTURE_LOAD_DEFAULT_2D); end; destructor TCreatures.Destroy; var I: Integer; begin for I := 0 to Count - 1 do Creature[I].Free; pSelEnemyUnit := nil; pSelAllyUnit := nil; pSelUserUnit := nil; pLifebar := nil; inherited; end; procedure TCreatures.Render; var I: Integer; W: Byte; procedure RenderSelUnit(T: ITexture); begin pRender2D.DrawTexture(T, Point2((Creature[I].Pos.X - MAP_LEFT) * TILE_SIZE + SCR_LEFT, (Creature[I].Pos.Y - MAP_TOP) * TILE_SIZE + SCR_TOP), Point2(TILE_SIZE, TILE_SIZE)); end; begin for I := 0 to Count - 1 do if Creature[I].Active then begin if (I <> CURRENT_ALLY) and Creature[I].MouseOver then case Creature[I].Force of fcEnemy: RenderSelUnit(pSelEnemyUnit); fcAlly: RenderSelUnit(pSelAllyUnit); end; if (I = CURRENT_ALLY) then RenderSelUnit(pSelUserUnit); pRender2D.DrawTexture(Creature[I].Texture, Point2((Creature[I].Pos.X - MAP_LEFT) * TILE_SIZE + SCR_LEFT, (Creature[I].Pos.Y - MAP_TOP) * TILE_SIZE + SCR_TOP), Point2(TILE_SIZE, TILE_SIZE)); W := 30 - BarWidth(Creature[I].Life.Cur, Creature[I].Life.Max, 30); pRender2D.DrawTexture(pLifebar, Point2((Creature[I].Pos.X - MAP_LEFT) * TILE_SIZE + SCR_LEFT + 2 + W, (Creature[I].Pos.Y - MAP_TOP) * TILE_SIZE + SCR_TOP - 2), Point2(TILE_SIZE - 4 - (W * 2), 4)); W := 30 - BarWidth(Creature[I].Speed.Cur, Creature[I].Speed.Max, 30); pRender2D.DrawTexture(pLifebar, Point2((Creature[I].Pos.X - MAP_LEFT) * TILE_SIZE + SCR_LEFT + 2 + W, (Creature[I].Pos.Y - MAP_TOP) * TILE_SIZE + SCR_TOP - 2 + (TILE_SIZE - 2)), Point2(TILE_SIZE - 4 - (W * 2), 4)); { TextOut((Creature[I].Pos.X - MAP_LEFT) * TILE_SIZE + SCR_LEFT + 2 + W, (Creature[I].Pos.Y - MAP_TOP) * TILE_SIZE + SCR_TOP - 2, StrToPAChar(IntToStr(I) + '|' + IntToStr(Creature[I].Pos.X) + ':' + IntToStr(Creature[I].Pos.Y) + '|' + IntToStr(Creature[I].Target.X) + ':' + IntToStr(Creature[I].Target.Y) ), Color4); } end; Digit.Render; end; procedure TCreatures.ModLife(ID, Dam: Integer); begin if (Dam = 0) or not Creature[ID].Active then Exit; Digit.Add(Creature[ID].Pos.X, Creature[ID].Pos.Y, Dam); if (Dam < 0) then Creature[ID].Life.Dec(Abs(Dam)); if (Dam > 0) then Creature[ID].Life.Inc(Dam); if Creature[ID].Life.IsMin then Creature[ID].Active := False; end; procedure TCreatures.Update; begin Digit.Update; end; procedure TCreatures.SetCreature(const Value: TACreature); begin FCreature := Value; end; procedure TCreatures.SetTargets; var I, T: Integer; begin for I := 0 to Count - 1 do if Creature[I].Active and (I <> CURRENT_ALLY) then begin T := GetTagret(I); if (T > -1) then Creature[I].Target := Creature[T].Pos; end; end; function TCreatures.EmptyCell(X, Y: Integer): Boolean; var I: Integer; begin Result := True; for I := 0 to Count - 1 do if Creature[I].Active and (X = Creature[I].Pos.X) and (Y = Creature[I].Pos.Y) then begin Result := False; Exit; end; end; function TCreatures.GetCreatureID(X, Y: Integer): Integer; var I: Integer; begin Result := -1; for I := 0 to Count - 1 do if Creature[I].Active and (X = Creature[I].Pos.X) and (Y = Creature[I].Pos.Y) then begin Result := I; Exit; end; end; function TCreatures.GetTagret(C: Integer): Integer; var I: Integer; begin Result := -1; for I := 0 to Count - 1 do if Creature[I].Active and (I <> C) then begin if (GetDist(Creature[C].Pos.X, Creature[C].Pos.Y, Creature[I].Pos.X, Creature[I].Pos.Y) <= 5) then begin if (Creature[C].Force = Creature[I].Force) then Continue; Result := I; Exit; end; end; end; end.
unit evSavedCursor; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Everest/evSavedCursor.pas" // Начат: 21.03.2008 19:09 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::Everest::Cursors::evSavedCursor // // Объект для сохранения курсора. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses nevTools, l3ProtoObject ; type TevSavedCursor = class(Tl3ProtoObject) {* Объект для сохранения курсора. } private // private fields f_Cursor : InevBasePoint; {* Поле для свойства Cursor} f_Old : IevSavedCursor; {* Поле для свойства Old} f_New : IevSavedCursor; {* Поле для свойства New} protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public // public methods constructor Create(const aCursor: InevBasePoint; const aOld: IevSavedCursor; const aNew: IevSavedCursor); reintroduce; public // public properties property Cursor: InevBasePoint read f_Cursor write f_Cursor; {* курсор, который изменялся. } property Old: IevSavedCursor read f_Old write f_Old; {* старое значение курсора. } property New: IevSavedCursor read f_New write f_New; {* новое значение курсора. } end;//TevSavedCursor PevSavedCursor = ^TevSavedCursor; implementation // start class TevSavedCursor constructor TevSavedCursor.Create(const aCursor: InevBasePoint; const aOld: IevSavedCursor; const aNew: IevSavedCursor); //#UC START# *47E3E1DE01E5_47E3DFD00379_var* //#UC END# *47E3E1DE01E5_47E3DFD00379_var* begin //#UC START# *47E3E1DE01E5_47E3DFD00379_impl* inherited Create; Cursor := aCursor; Old := aOld; New := aNew; //#UC END# *47E3E1DE01E5_47E3DFD00379_impl* end;//TevSavedCursor.Create procedure TevSavedCursor.Cleanup; //#UC START# *479731C50290_47E3DFD00379_var* //#UC END# *479731C50290_47E3DFD00379_var* begin //#UC START# *479731C50290_47E3DFD00379_impl* Cursor := nil; Old := nil; New := nil; inherited; //#UC END# *479731C50290_47E3DFD00379_impl* end;//TevSavedCursor.Cleanup procedure TevSavedCursor.ClearFields; {-} begin Cursor := nil; Old := nil; New := nil; inherited; end;//TevSavedCursor.ClearFields end.
unit clipbrdFunctions; interface uses Classes, clipbrd, windows, SysUtils; type {$ifndef UNICODE} RawByteString = AnsiString; {$endif} TClipboardEx = class(TClipboard) public procedure SetBuffer(Format: Word; var Buffer; Size: Integer); procedure AddToCurrent(Format: Word; Handle: Cardinal); end; PClipbrdCopyFormat = ^TClipbrdCopyFormat; TClipbrdCopyFormat = record ID: Word; Name: AnsiString; Size: Cardinal; Data: pointer; end; TClipbrdCopy = class private FFormatList: TList; FFilename: String; function AddFormat(ID: Word; Name: AnsiString; var Data; Size: Cardinal): Integer; procedure DeleteFormat(nr: Integer); procedure Warning(Text: String); public property Filename: string read FFilename; function LoadFromStream(AStream: TStream): Boolean; procedure SaveToStream(AStream: TStream); procedure ReadClipbrd; procedure WriteClipbrd(useStoredIDs: boolean); constructor Create; destructor Destroy; override; procedure Clear; end; procedure SaveClipboardtoFile(Filename, Description, PlugInName, ogame_domain: String; UserUniName: String); function ReadClipboardHtml: string; function ReadClipboardHtmlUTF8: AnsiString; function GetHtmlFormat: Integer; function getClipboardTextANSI: AnsiString; function GetClipboardTextUTF8: RawByteString; function GetClipboardTextWide: WideString; function GetClipBoardText: String; function ReadClipboardText: string; function FindClipbrdFormat(name: String): Integer; implementation function conv_UTF8(const s: AnsiString): string; begin {$ifdef UNICODE} Result := UTF8ToWideString(s); {$else} Result := s; {$endif} end; function FindClipbrdFormat(name: String): Integer; var i: integer; s: array[0..255] of Char; begin i := 0; Result := 0; while Clipboard.Formats[i] <> 0 do begin GetClipboardFormatName(Clipboard.Formats[i],@s,256); if pos(name,s) > 0 then begin Result := Clipboard.Formats[i]; Break; end; inc(i); end; end; function GetHtmlFormat: Integer; begin Result := FindClipbrdFormat('HTML'); end; function GetClipboardText: string; begin {$ifdef UNICODE} Result := GetClipBoardTextWide; {$else} Result := GetClipBoardTextUTF8; {$endif} end; function getClipboardTextANSI: AnsiString; var Data: THandle; begin Data := Clipboard.GetAsHandle(CF_TEXT); try if Data <> 0 then Result := PAnsiChar(GlobalLock(Data)) else Result := ''; finally if Data <> 0 then GlobalUnlock(Data); end; end; function GetClipboardTextUTF8: RawByteString; begin if (Clipboard.HasFormat(CF_UNICODETEXT)) then begin Result := UTF8Encode(GetClipboardTextWide); end else begin Result := UTF8Encode(RawByteString(getClipboardTextANSI)); end; end; function GetClipboardTextWide: WideString; var Data: THandle; begin Data := Clipboard.GetAsHandle(CF_UNICODETEXT); try if Data <> 0 then Result := PWideChar(GlobalLock(Data)) else Result := ''; finally if Data <> 0 then GlobalUnlock(Data); end; end; function ReadClipboardText: string; begin Result := GetClipboardText; end; function ReadClipboardHtmlString(CutFormatHeader: Boolean = False): AnsiString; var MyHandle: THandle; TextPtr: PAnsiChar; CF_HTML: Word; begin CF_HTML := GetHtmlFormat; Result := ''; ClipBoard.Open; try MyHandle := Clipboard.GetAsHandle(CF_HTML); TextPtr := GlobalLock(MyHandle); Result := TextPtr; GlobalUnlock(MyHandle); finally Clipboard.Close; end; end; function ReadClipboardHtmlUTF8: AnsiString; var MyHandle: THandle; ptr: pointer; size: integer; CF_HTML: Word; sig: Word; begin Result := ''; CF_HTML := GetHtmlFormat; ClipBoard.Open; try if Clipboard.HasFormat(CF_HTML) then begin MyHandle := Clipboard.GetAsHandle(CF_HTML); size := GlobalSize(MyHandle); ptr := GlobalLock(MyHandle); if size > sizeof(sig) then Move(ptr^,sig,sizeof(sig)) else sig := 0; case sig of $feff: //WideString begin Result := UTF8Encode(PWideChar(ptr)); end; else //UTF8 Result := PAnsiChar(ptr); end; GlobalUnlock(MyHandle); end; finally Clipboard.Close; end; end; function ReadClipboardHtml: String; begin {$ifdef UNICODE} Result := UTF8ToWideString(ReadClipboardHtmlUTF8); {$else} Result := ReadClipboardHtmlUTF8; {$endif} end; procedure SaveClipboardtoFile(Filename, Description, PlugInName, ogame_domain: String; UserUniName: String); procedure WriteStringToStream(s: AnsiString; stream: TStream); overload; var i: integer; {4Byte ~ 2^31 Zeichen} begin i := length(s); stream.WriteBuffer(i,sizeof(i)); stream.WriteBuffer(PAnsiChar(s)^,i); end; procedure WriteStringToStream(s: WideString; stream: TStream); overload; begin WriteStringToStream(UTF8Encode((s)), stream); end; procedure WriteClipboardFormatToStream(Format: Word; stream: TStream); var MyHandle: THandle; size: integer; begin Clipboard.Open; try MyHandle := Clipboard.GetAsHandle(Format); size := GlobalSize(MyHandle); stream.Write(size,sizeof(size)); stream.Write(GlobalLock(MyHandle)^,size); GlobalUnlock(MyHandle); finally Clipboard.Close; end; end; var stream: TFileStream; cc: TClipbrdCopy; begin stream := TFileStream.Create(filename,fmCreate); WriteStringToStream('cS - clipbrdfile',stream); WriteStringToStream(GetClipboardText,stream); WriteStringToStream(ReadClipboardHtml,stream); WriteStringToStream(Description,stream); WriteStringToStream(PlugInName,stream); WriteStringToStream(ogame_domain,stream); WriteStringToStream(UserUniName,stream); WriteStringToStream('ClipbrdCopy',stream); cc := TClipbrdCopy.Create; cc.ReadClipbrd; cc.SaveToStream(stream); cc.Free; stream.Free; end; function TClipbrdCopy.AddFormat(ID: Word; Name: AnsiString; var Data; Size: Cardinal): Integer; var Format: PClipbrdCopyFormat; begin New(Format); Format^.ID := ID; Format^.Name := Name; Format^.Size := Size; GetMem(Format^.Data,Size); CopyMemory(Format^.Data,@Data,Size); Result := FFormatList.Add(Format); end; procedure TClipbrdCopy.Clear; begin while FFormatList.Count > 0 do DeleteFormat(0); end; constructor TClipbrdCopy.Create; begin inherited; FFormatList := TList.Create; end; procedure TClipbrdCopy.DeleteFormat(nr: Integer); var Format: PClipbrdCopyFormat; begin Format := FFormatList[nr]; FreeMem(Format^.Data); Dispose(Format); FFormatList.Delete(nr); end; destructor TClipbrdCopy.Destroy; begin Clear; FFormatList.Free; inherited; end; function TClipbrdCopy.LoadFromStream(AStream: TStream): Boolean; function ReadStringFromStream(stream: TStream): AnsiString; var i: integer; begin stream.ReadBuffer(i,SizeOf(i)); SetLength(Result,i); stream.ReadBuffer(PAnsiChar(Result)^,i); end; var ID: Word; Name: AnsiString; Size: Cardinal; Data: pointer; begin Clear; while (AStream.Position < AStream.Size) do begin AStream.ReadBuffer(ID,SizeOf(ID)); Name := ReadStringFromStream(AStream); AStream.ReadBuffer(Size,SizeOf(Size)); GetMem(Data,Size); AStream.ReadBuffer(Data^,Size); AddFormat(ID,Name,Data^,Size); FreeMem(Data); end; Result := True; end; procedure TClipbrdCopy.ReadClipbrd; var i, ID, size: integer; {$ifdef UNICODE} s: array[byte] of WideChar; {$else} s: array[byte] of AnsiChar; {$endif} hndl: THandle; data: pointer; format_name: AnsiString; begin Clear; ClipBoard.Open; try for i := 0 to Clipboard.FormatCount-1 do begin ID := Clipboard.Formats[i]; FillChar(s,sizeof(s),0); {$ifdef UNICODE} GetClipboardFormatName(ID,@s,sizeof(s)); format_name := UTF8Encode(s); {$else} GetClipboardFormatName(ID,@s,sizeof(s)); format_name := s; {$endif} hndl := Clipboard.GetAsHandle(ID); size := GlobalSize(hndl); data := GlobalLock(hndl); AddFormat(ID,format_name,data^,size); GlobalUnlock(hndl); end; finally Clipboard.Close; end; end; procedure TClipbrdCopy.SaveToStream(AStream: TStream); procedure WriteStringToStream(s: AnsiString; stream: TStream); var i: integer; {4Byte ~ 2^31 Zeichen} begin i := length(s); stream.WriteBuffer(i,sizeof(i)); stream.WriteBuffer(PAnsiChar(s)^,i); end; var i: integer; begin for i := 0 to FFormatList.Count-1 do with TClipbrdCopyFormat(FFormatList[i]^) do begin AStream.WriteBuffer(ID,SizeOf(ID)); WriteStringToStream(Name,AStream); AStream.WriteBuffer(Size,SizeOf(Size)); AStream.WriteBuffer(Data^,Size); end; end; procedure TClipbrdCopy.Warning(Text: String); begin end; procedure TClipbrdCopy.WriteClipbrd(useStoredIDs: boolean); var i, nID: integer; clpb: TClipboardEx; begin clpb := TClipboardEx.Create; clpb.Open; try clpb.Clear; for i := 0 to FFormatList.Count-1 do with TClipbrdCopyFormat(FFormatList[i]^) do begin {$ifdef UNICODE} nID := RegisterClipboardFormat(PWideChar(UTF8ToWideString(Name))); {$else} nID := RegisterClipboardFormat(PChar(Name)); {$endif} if (nID <> 0)and(nID <> ID) then begin Warning('New ID of ' + conv_UTF8(Name) + ': ' + IntToStr(nID) + '. The old was: ' + IntToStr(ID) + '.'); if not useStoredIDs then begin ID := nID; end; end; clpb.SetBuffer(ID,Data^,Size); end; finally clpb.Close; end; end; procedure TClipboardEx.AddToCurrent(Format: Word; Handle: Cardinal); begin Open; try SetClipboardData(Format,Handle); finally Close; end; end; procedure TClipboardEx.SetBuffer(Format: Word; var Buffer; Size: Integer); begin inherited; end; end.
{***********************************************************************} { TMacroRecorder component } { for Delphi & C++Builder } { version 1.0 } { } { written by } { TMS Software } { Copyright © 2004 } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } {***********************************************************************} unit MacroRecorderReg; interface uses MacroRecorder, Classes; procedure Register; implementation procedure Register; begin RegisterComponents('TMS System', [TMacroRecorder]); end; end.
program BCD; // Devoir Maison N°1 de Programmation Pascal : // Gestion d'un afficheur 7 segments. uses Crt, DOS; // On inclus le package Crt contenant GotoXY et ClrScr // (pour l'affichage), DOS contient GetTime pour afficher // l'heure. (* Les conversions des chiffres décimaux en nombres binaires à 4 digits seront des BinaryNumber (de simples tableaux de 4 booléens). Un afficheur sept segments est un ensemble de 7 booléens nommés 'a' à 'g'. On stockera ces valeurs dans un SevenSegmentDisplay. *) Type BinaryNumber = Array [0..3] of Boolean; SevenSegmentDisplay = Array['a'..'g'] of Boolean; Const // Taille de l'écran (utilisé par les fonctions d'affichage via GotoXY). screenWidth = 80; screenHeight = 25; // Partie 1 : (* Description de convertDigitToBinary : digit : Paramètre entrée, contient un digit décimal (0 à 9) à convertir en nombre booléen. retour : Un BinaryNumber contenant la valeur de digit. La case 0 contient les unités et la case 3 contient le facteur de 2^3. *) Function convertDigitToBinary(digit : Integer) : BinaryNumber; var i : Integer; result : BinaryNumber; Begin // Début convertDigitToBinary for i:=0 to 3 do // On sait d'avance que l'on stockera la division sur 4 Begin // booléens, quitte à stocker [0,0,0,1]. result[i] := (digit MOD 2 = 1); // result[i] prend la valeur True si digit := digit DIV 2; // digit MOD 2 vaut 1, Faux sinon. End; convertDigitToBinary := result; // Et on retourne le résultat. End; // Fin convertDigitToBinary. //------------------------------------------------------------------------------ // Fin de la Partie 1.########################################################## // Partie 2 : (* Description de isSegmentLit : segment : Le nom du segment à analyser (de a à g). nBool : L'écriture en binaire quatre bits d'un chiffre décimal (0 à 9). retour: Le segment doit-il être allumé ? Note : Version 1 = Décodeur vrai, en cas d'entrée fausse (nBool = 10 à 16) la sortie sera systématiquement fausse (mode Debug). Version 2 = Décodeur partiel, en cas d'entrée fausse la sortie est inconnue, mais l'exécution est légèrement plus rapide (mode Release). *) {<!-- Function isSegmentLit(segment : Char; nBool : BinaryNumber) : Boolean; // Version 1, mode Debug Begin // Début de isSegmentLit. Case segment of 'a' : isSegmentLit := ((Not nBool[3] and nBool[1]) or (Not nBool[3] and nBool[2] and nBool[0]) or (Not nBool[2] and Not nBool[1] and Not nBool[0]) or (nBool[3] and Not nBool[2] and Not nBool[1])); 'b' : isSegmentLit := ((not nBool[3] and Not nBool[2]) or ( Not nBool[2] and Not nBool[1]) or (Not nBool[3] and nBool[1] and nBool[0]) or (Not nBool[3] and Not nBool[1] and Not nBool[0])); 'c' : isSegmentLit := ((Not nBool[3] and nBool[2]) or (Not nBool[3] and nBool[0]) or (Not nBool[2] and Not nBool[1])); 'd' : isSegmentLit := ((Not nBool[2] and Not nBool[1] and Not nBool[0]) or (nBool[3] and Not nBool[2] and Not nBool[1]) or (Not nBool[3] and Not nBool[2]and nBool[1]) or (Not nBool[3] and nBool[1] and Not nBool[0]) or (Not nBool[3] and nBool[2] and Not nBool[1] and nBool[0])); 'e' : isSegmentLit := ((Not nBool[2] and Not nBool[1] and Not nBool[0]) or (Not nBool[3] and nBool[1] and Not nBool[0])) ; 'f' : isSegmentLit := ((Not nBool[3] and Not nBool[1] and Not nBool[0]) or (Not nBool[3] and nBool[2]and Not nBool[1]) or(nBool[3] and Not nBool[2] and Not nBool[1]) or (Not nBool[3] and nBool[2] and Not nBool[0])); 'g' : isSegmentLit := ((Not nBool[3] and nBool[2] and Not nBool[1]) or (nBool[3] and Not nBool[2] and Not nBool[1]) or (Not nBool[3] and Not nBool[2] and nBool[1]) or (Not nBool[3] and nBool[1] and Not nBool[0])); End; // Fin de Case of. End; // Fin de isSegmentLit. //------------------------------------------------------------------------------ --!>} Function isSegmentLit(segment : Char; nBool : BinaryNumber) : Boolean; // Version 2, mode Release Begin // Début de isSegmentLit. Case segment of 'a' : isSegmentLit := (nBool[3] or nBool[1] or (Not nBool[2] and Not nBool[0]) or (nBool[2] and nBool[0])); 'b' : isSegmentLit := ((Not nBool[1] and Not nBool[0]) or (nBool[1] and nBool[0]) or Not nBool[2]); 'c' : isSegmentLit := (Not nBool[1] or nBool[0] or nBool[2]); 'd' : isSegmentLit := (nBool[3] or (Not nBool[2] and nBool[1]) or (Not nBool[2] and Not nBool[0]) or (nBool[2] and Not nBool[1] and nBool[0]) or (nBool[1] and Not nBool[0])); 'e' : isSegmentLit := ((Not nBool[2] and Not nBool[0]) or (nBool[1] and Not nBool[0])); 'f' : isSegmentLit := (nBool[3] or (Not nBool[1] and Not nBool[0]) or (nBool[2] and Not nBool[1]) or (nBool[2] and Not nBool[0])); 'g' : isSegmentLit := (nBool[3] or (nBool[2] and Not nBool[1]) or (Not nBool[2] and nBool[1]) or (nBool[1] and Not nBool[0])); End; // Fin de Case. End; // Fin de isSegmentLit. //------------------------------------------------------------------------------ // Fin de la Partie 2. ######################################################### // Partie 3 : (* Description de lineWidth: length : La longueur de la ligne. retour : La largeur de la ligne. *) Function lineWidth(length : Integer) : Integer; Begin lineWidth := 1 + length DIV 6; // Les lignes prennent 1 de largeur // tous les 6 de longueur ; longueur [1,5] -> largeur = 1, End;// longueur [6,11] -> largeur = 2, longueur [12,17] -> largeur = 3, etc... //------------------------------------------------------------------------------ (* Description de readSegmentLength : maxDigitWidth : La largeur maximale du chiffre dont on saisit la longueur des segments. retour : La longueur de segment choisie. Lit au clavier une taille de segment de manière sécurisée. Elle doit être un nombre positif non nul tel que la largeur d'un caractère ne dépasse pas maxDigitWidth. *) Function readSegmentLength(maxDigitWidth : Integer) : Integer; Var dataEntry : String[3]; conversionError : Integer; // Vaudra 0 si la saisie est bien un nombre. segmentWidth : Integer; Begin // Début readSegmentLength repeat Write('Veuillez entrer la longueur des segments a afficher : '); Readln(dataEntry); Val(dataEntry, readSegmentLength, conversionError); segmentWidth := lineWidth(readSegmentLength); // Si le segment est trop gros, chiffre > maxDigitWidth en largeur. if(readSegmentLength + 2*segmentWidth > maxDigitWidth) then WriteLn('Erreur ! La largeur d''un chiffre ne peut exceder ', maxDigitWidth, ' !'); // Alors c'est pas bon ! ;) // Recommencer tant que n n'est pas valide. until((conversionError = 0) and (readSegmentLength >= 1) and ((readSegmentLength + 2*segmentWidth) < maxDigitWidth)); End; // Fin readSegmentLength. //------------------------------------------------------------------------------ (* Description de readPrintChar : retour : Le caractère d'affichage choisi. Lit au clavier un caractère (qui ne soit pas une séquence d'échappement). *) Function readPrintChar() : Char; Begin // Début readPrintChar repeat // Saisie du caractère d'affichage. ReadLn(readPrintChar); // Aucune valeur interdite, à part le until(readPrintChar <> #13); // carriage return (obtenu si l'on clique End; // Fin readPrintChar. // sur Entrée sans avoir saisi de caractère). //------------------------------------------------------------------------------ (* Description de displaySegments : display : L'afficheur sept digits à afficher (structure de 7 booléens numérotés de 'a' à 'g'). segLength : La taille des segments de l'afficheur. displayChar : Le symbole à imprimer sur les zones allumées de l'afficheur. cas spécial : ' ' pour Debug, affiche le nom du segment (a à g). x0, y0 : La position du coin en haut à gauche de l'afficheur. *) Procedure displaySegments(display : SevenSegmentDisplay; segLength : Integer; displayChar : Char; x0, y0 : Integer); var seg : Char; x, y, l, w : Integer; // x abscisse, y ordonnée : [1,1] en haut à gauche. segWidth, deltaL : Integer; // On fera des segments de largeur variable. // Les segments ont des bords pointus, deltaL gère le changement de longueur // des segments selon la couche d'épaisseur en cours. isSegmentHorizontal : Boolean; Begin // Début displaySegments segWidth := lineWidth(segLength); for seg := 'a' to 'g' do // Pour chaque segment : Begin Case seg of // Initialisation du segment : // Les segments ont été listés dans l'ordre classique de lecture. 'a' : Begin // Position initiale (début du segment) : On pose le // début d'un segment à son extrémité haute ou gauche. x := segWidth; // Attention : Origine = [1,1] (pas [0,0]) ! y := 0; // On commencera donc le segment à [x+1,y+1] isSegmentHorizontal := True; // dans l'affichage End; 'f' : Begin x := 0; y := segWidth; isSegmentHorizontal := False; End; 'b' : Begin x := segWidth+segLength; y := segWidth; isSegmentHorizontal := False; End; 'g' : Begin x := segWidth; y := segWidth+segLength; isSegmentHorizontal := True; End; 'e' : Begin x := 0; y := 2*segWidth+segLength; isSegmentHorizontal := False; End; 'c' : Begin x := segWidth+segLength; y := 2*segWidth+segLength; isSegmentHorizontal := False; End; 'd' : Begin x := segWidth; y := 2*segWidth+2*segLength; isSegmentHorizontal := True; End; End; // Fin du Case of. // Afficher le segment : if(display[seg]) then // Si le segment est allumé alors on lance la Begin // procédure d'affichage. deltaL := 0; // On commence avec un décalage de 0. // On affiche chaque ligne du segment. for w:= 0 to segWidth-1 do Begin // On affiche la longueur de segment pour la couche en cours. for l := -deltaL to (segLength-1)+deltaL do Begin if(isSegmentHorizontal) then GotoXY(x0+x+l,y0+y+w) // Si le segment est horizontal else // on avance sur l'axe des x, sinon GotoXY(x0+x+w, y0+y+l); // on avance sur l'axe des y. if(displayChar <> ' ') then // Cas général, correspond Write(displayChar) // donc à la vérification du test. else // Cas spécial, si displayChar = ' ' Write(seg); // chaque segment affiche son nom // ['a'..'g] (permet d'indentifier End; // tout segment mal positionné) // deltaL s'incrémente jusqu'à segWidth/2 puis redescend à 0. if(w+1 < (segWidth+1) DIV 2) then deltaL := deltaL+1 else if (w+1 > segWidth DIV 2) then // Et surtout pas else, pour deltaL := deltaL-1; // gérer les largeurs paires. End; // On répète l'opération pour la ligne suivante. End; // Fin du if(display[seg]) End; // Fin du for seg. // On positionne le curseur à la ligne : GotoXY(1, 4*segWidth+2*segLength+y0); End; // Fin displaySegments. //------------------------------------------------------------------------------ // Fin de la Partie 3. ######################################################### (* Description de DisplaySingleDigit: 1 - Demande la saisie d'un chiffre (0 à 9). 2 - Affiche la traduction du chiffre saisi en binaire 4 bits. 3 - Affiche l'état des segments de l'afficheur 7 segments pour le chiffre saisi. 4 - Demande à l'utilisateur de saisir une taille et un caractère d'affichage puis affiche le chiffre saisi dans la console. *) Procedure displaySingleDigit(); var dataEntry : String[2]; n, i, segmentLength : Integer; nBool : BinaryNumber; printChar, c : Char; segments : SevenSegmentDisplay; Begin // Début DisplaySingleDigit // Partie 1 : Affichage d'un chiffre en nombre binaire à 4 bits. n := -1; // On initialise n à une valeur invalide. repeat // Saisie sécurisée d'un chiffre : dataEntry[2] := char(0); // dataEntry[2] identifie les saisies de Write('Veuillez entrer un chiffre : '); // plusieurs caractères. Readln(dataEntry); if(dataEntry[2] = char(0)) then // Si la saisie ne fait qu'un caractère n := ord(dataEntry[1]) - ord('0'); // alors n:=integer(saisie). until((n < 10) and (n>=0)); // Recommencer tant que n n'est pas un chiffre. nBool := convertDigitToBinary(n); Write('La conversion en binaire du chiffre ', n, ' est '); for i := 3 downto 0 do // La case 0 contient les unités, il faut donc Begin // l'écrire en dernier. if(nBool[i]) then Write('1') Else Write('0'); End; WriteLn(' !'); // Fin de la Partie 1. // Partie 2 : Affichage de la valeur de chaque segment en fonction de n. (* On rappelle les correspondances nom/segment : a ---- f | | b | g | ---- e | | c | | ---- d *) WriteLn('Etat des segments : (True = Allume, False = Eteint)'); for c := 'a' to 'g' do // c représente les segments de l'afficheur (a à g). Begin // On affiche l'état des segments de l'afficheur 7 segments. segments[c] := isSegmentLit(c, nBool); WriteLn('segment ', c, ': ', segments[c]); End; // Fin de la partie 2. // Partie 3 : Affichage du digit sous forme d'afficheur 7 segments. // Saisie de la longueur de segment, taille max d'un chiffre = screenWidth. segmentLength := readSegmentLength(screenWidth); Write('Veuillez entrer le caractere d affichage : '); printChar := readPrintChar(); // Saisie du caractère d'affichage. ClrScr(); // On commence par effacer l'écran. // On affiche le chiffre selon les paramètres saisis. displaySegments(segments, segmentLength, printChar, 1, 1); // Fin de la Partie 3. End; // Fin DisplaySingleDigit. //------------------------------------------------------------------------------ // Partie Fun. ################################################################# (* Description de displayMultipleSegments : n : Le nombre à afficher (en chaîne de caractères). La chaîne de caractère autorise les grands nombres et les nombres commençant par 0. segLength : La taille des segments de l'afficheur. displayChar : Le symbole à imprimer sur les zones allumées de l'afficheur. cas spécial : ' ' pour Debug, affiche le nom du segment ('a' à 'g'). x0, y0 : La position du coin en haut à gauche de l'afficheur. *) Procedure DisplayMultipleSegments(n : String; segLength : Integer; displayChar : Char; x, y : Integer); Var i : Integer; c : Char; nBool : BinaryNumber; display : SevenSegmentDisplay; segWidth : Integer; Begin // Début DisplayMultipleSegments segWidth := lineWidth(segLength); for i:=1 to length(n) do // Boucle d'affichage du nombre n. Begin // On transforme le ième caractère de n en chiffre décimal codé binaire. nBool := convertDigitToBinary(ord(n[i])); for c := 'a' to 'g' do // On calcule les segments à afficher display[c] := isSegmentLit(c, nBool); // pour ce chiffre. displaySegments(display, segLength, displayChar, x, y); // On calcule la position d'affichage du caractère suivant, en laissant x := x + segLength + 3*segWidth; // un espace de segWidth. // Si le prochain caractère déborde de l'écran if(x + 2*segWidth + segLength > 80) then // On passe à la ligne Begin // suivante. x := 1; y := y + 2*segLength + 5*segWidth; // On laise un espace End; // vertical de 2* segWidth. End; // Fin pour. GotoXY(1, y + 2*segLength + 4*segWidth); // On revient à la ligne. End; // Fin DisplayMultipleSegments. //------------------------------------------------------------------------------ (* Description de DisplayManyDigits : 1 - Demande la saisie d'un nombre (moins de 255 caractères). 2 - Demande à l'utilisateur de saisir une taille et un caractère d'affichage puis affiche le nombre saisi dans la console. Note : La procédure doit gérer elle-même l'espacement des caractères et les éventuels retours à la ligne. TODO : Eviter le bug à l'exécution 'Ranges overrun' pour les grand nombres. *) Procedure DisplayNumber(); Var i : LongInt; segLength : Integer; conversionError : Integer; // Sert à vérifier si n est bien un nombre. printChar : Char; n : String; // N contient le nombre à afficher. Begin // Début DisplayNumber repeat // On demande la saisie du nombre à afficher. Write('Veuillez entrer un nombre : '); Readln(n); Val(n, i, conversionError); // On verifie que l'entrée est un entier. until(conversionError = 0); // Recommencer tant que n n'est pas un entier. // Saisie de la longueur des segments. segLength := readSegmentLength(screenWidth); Write('Veuillez entrer le caractere d affichage : '); printChar := readPrintChar(); // Saisie du caractère d'affichage. ClrScr(); // On commence par effacer l'écran. DisplayMultipleSegments(n, segLength, printChar, 1, 1); GotoXY(1, WhereY + 1); // On revient à la ligne. End; // Fin DisplayNumber. //------------------------------------------------------------------------------ (* Description de DisplayTime : Affiche l'heure à l'écran. Fait tourner l'heure tant qu'elle est affichée. TODO : Lire le clavier sans mettre en pause pour pouvoir quitter (évènement ? Lecture du buffer ?..), et mettre en place un buffer pour empêcher l'affichage de saccader (ça ne paraît pas possible avec le fonctionnement actuel de DisplaySegments). *) Procedure DisplayTime(); Var time : Array[0..3] of Integer; i, j, segLength, segWidth, charWidth, charHeight, refreshDelay : Integer; displayChar : Char; tmpStr : String; Begin // Début DisplayTime // Saisie de la longueur des segments (au delà de 16 de largeur, les // chiffres dépassent de la console). segLength := readSegmentLength(16); Write('Veuillez entrer le caractere d affichage : '); displayChar := readPrintChar(); Write('Veuillez entrer le temps d''attente entre les rafraichissement : '); WriteLn('(temps en centiemes de secondes)'); ReadLn(refreshDelay); segWidth := lineWidth(segLength); charWidth := segLength+3*segWidth; // prend compte de l'espace entre charHeight := 2*segLength+4*segWidth; // les chiffres (segWidth). repeat GetTime(time[0], time[1], time[2], time[3]); // On récupère l'heure. ClrScr(); // On efface l'écran avant l'affichage. for i := 0 to 3 do // On affiche l'heure. (H:min'\n'sec:sec100) Begin str(time[i], tmpStr); // tmpStr prend la valeur de time[i] if(time[i] < 10) then // Si time[i] ne fait qu'un digit, on tmpStr := '0'+tmpStr; // rajoute un zéro avant à l'affichage. DisplayMultipleSegments(tmpStr, segLength, displayChar, screenWidth DIV 2 - (2*charWidth+segWidth) + (i MOD 2)*(2*charWidth + 3*segWidth), 1 + (i DIV 2)*charHeight); End; if((time[3] < 25) or (time[3] > 75)) then // Si on est au changement Begin // de demi-seconde on affiche les ':' de l'horloge. for j:=0 to 1 do Begin GotoXY(40, charHeight DIV 2 + j*charHeight -(1+segWidth DIV 2)); Write(char(219)); // Le 219ème caractère ASCII est le GotoXY(40, charHeight DIV 2 + j*charHeight+1+(segWidth-1)DIV 2); Write(char(219)); // caractère plein. End; End; GotoXY(1,1); Delay(10*refreshDelay); // On attend (temps en ms). until False; // Boucle infinie. (CTRL+C pour terminer). End; // Fin DisplayTime. //------------------------------------------------------------------------------ (* Description de Quit : 1 - Affiche des jolis caractères random dans le fond. 2 - Affiche le message exitMessage au milieu de la console, puis attend une saisie pour quitter le programme. *) procedure Quit(); Const exitText = 'Au revoir et a bientot !'; Var i : Integer; Begin for i:= 1 to 100 do Begin // On va à un position aléatoire sur l'écran. GotoXY(random(screenWidth), random(screenHeight)); // On affiche un des premiers caractères ASCII choisi aléatoirement. Write(char(random(15)+1)); End; // Enfin on affiche le message d'adieu. GotoXY((screenWidth-length(exitText)) DIV 2, screenHeight DIV 2); Write(exitText); // On revient ensuite en bas de la page pour la saisie empêchant la GotoXY(1,screenHeight); // fermeture brusque du programme. Write('Appuyez sur Entree pour quitter...'); ReadLn; // On attend une entrée inutile pour empêcher la fin du programme. Halt(0); // Fin du programme, aucune erreur à déclarer. End; //------------------------------------------------------------------------------ // Fin de la Partie Fun. ####################################################### // Programme principal : const // Pour modifier les options, entrer ici le nombre total d'options et le texte // associé à chaque option, puis saisir la procédure les définissant en fin du // programme principal. nbOfOptions = 4; // Nombre total d'options du menu principal. optionText : Array[1..nbOfOptions] of String = ( // Texte associé à '1 : Afficher un chiffre.', // chaque option. '2 : Afficher un nombre.', '3 : Afficher l''heure.', '4 : Quitter.' // Merci de ne pas dépasser 76 caractères. ); menuText = 'Menu'; // Ces textes peuvent être changés simplement en les inputText = 'Saisir choix : '; // modifiant ici. // Ces constantes contiennent les caractères d'affichage du cadre du menu. topLeftCorner = char(201); topRightCorner = char(187); botLeftCorner = char(200); botRightCorner = char(188); HorizontalBar = char(205); VerticalBar = char(186); var i, option, largestOptionLength : Integer; choice : String[4]; // On définit choice comme une chaîne de caractères pour // gérer les mauvaises saises non numériques. choiceVal,conversionError : Integer; // Conversion en entier de choice. Begin // Début Programme Principal randomize(); // On initialise la fonction random. repeat // Boucle principale du menu (mal indentée). repeat // Affichage du menu et saisie du choix (+ClrScr). largestOptionLength := 0; ClrScr(); for option:=1 to nbOfOptions do Begin // On affiche les différentes options. // La plus grande ligne déterminera la largeur du cadre. if (length(optionText[option]) > largestOptionLength) then largestOptionLength := length(optionText[option]); GotoXY((screenWidth - length(optionText[option])) DIV 2, (screenHeight - nbOfOptions) DIV 2 + option); Write(optionText[option]); // On affiche l'option en cours. End; // Titre du Menu : GotoXY((screenWidth - length(menuText)) DIV 2, (screenHeight - nbOfOptions) DIV 2 - 2); Write(menuText); // On affiche le cadre du menu : // 1ère ligne. GotoXY((screenWidth - largestOptionLength - 4) DIV 2, // On va en (screenHeight - nbOfOptions - 2) DIV 2); // haut à gauche. Write(topLeftCorner); for i := 1 to largestOptionLength+2 do Write(HorizontalBar); Write(topRightCorner); // lignes 2 à nbofOptions+4-1. for i:=1 to nbofOptions+2 do Begin // On affiche les lignes verticales du cadre. GotoXY((screenWidth - largestOptionLength - 4) DIV 2, (screenHeight - nbOfOptions - 2) DIV 2 + i); Write(VerticalBar); GotoXY((screenWidth + largestOptionLength + 2) DIV 2, (screenHeight - nbOfOptions - 2) DIV 2 + i); Write(VerticalBar); End; // Dernière ligne (nbOfOptions+4). GotoXY((screenWidth - largestOptionLength - 4) DIV 2, // On va en (screenHeight - nbOfOptions) DIV 2 + i); // bas à gauche. Write(botLeftCorner); for i := 1 to largestOptionLength+2 do Write(HorizontalBar); Write(botRightCorner); // Fin de l'affichage du cadre // Affichage de la ligne de saisie GotoXY((screenWidth - length(inputText)) DIV 2, (screenHeight - nbOfOptions) DIV 2 + nbOfOptions + 3); Write(inputText); ReadLn(choice); Val(choice, choiceVal, conversionError); ClrScr(); // On recommence jusqu'à obtenir une saisie correcte de l'utilisateur // (soit un chiffre entre 1 et nbOfOptions). until ((conversionError=0) and (choiceVal>0) and (choiceVal<=nbOfOptions)); // Lancement du programme choisi : case choiceVal of //!\\ Entrer ici le code des différentes options : 1 : DisplaySingleDigit(); // Afficher un chiffre. 2 : DisplayNumber(); // Afficher un nombre. 3 : DisplayTime(); // Afficher l'heure. 4 : Quit(); // Quitter. End; // Fin Case choiceVal of . Write('Appuyez sur Entree pour revenir au menu...'); ReadLn; // On attend une entrée inutile pour empêcher la fin du programme. until false; // On boucle à l'infini tant que l'utilisateur n'a pas // sélectionné l'option 'Quitter'. End. // Fin Programme Principal. //______________________________________________________________________________
unit Thread.EDITFO; interface uses System.Classes; type Thread_ImportEDITFO = class(TThread) private FTotalRegistros: Integer; FCliente: Integer; FTotalInconsistencias: Integer; FCancelar: Boolean; FLog: String; FProgresso: Double; FArquivo: String; FProcesso: Boolean; procedure UpdateLOG(sMensagem: String); protected procedure Execute; override; public property Arquivo: String read FArquivo write FArquivo; property Processo: Boolean read FProcesso write FProcesso; property Log: String read FLog write FLog; property Progresso: Double read FProgresso write FProgresso; property TotalRegistros: Integer read FTotalRegistros write FTotalRegistros; property TotalInconsistencias: Integer read FTotalInconsistencias write FTotalInconsistencias; property Cliente: Integer read FCliente write FCliente; property Cancelar: Boolean read FCancelar write FCancelar; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_ImportEDITFO.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { Thread_ImportEDITFO } procedure Thread_ImportEDITFO.Execute; begin { Place thread code here } end; procedure Thread_ImportEDITFO.UpdateLOG(sMensagem: String); begin if FLog <> '' then begin FLog := FLog + #13; end; FLog := FLog + sMensagem; end; end.