text stringlengths 14 6.51M |
|---|
(*output: not(a and b) = TRUE
((a or b)or a) and b) = FALSE
(a and b) and b = FALSE
(a and b) and b = FALSE
Line 1 - Condition is true *)
program test13;
var a, b, c: boolean;
begin
a := true;
b := false;
c := not(a and b);
writeln('not(a and b) = ', c);
c := ((a or b)or a) and b;
writeln('((a or b)or a) and b) = ' , c);
a := false;
b := true;
c := (a and b) and b;
writeln('(a and b) and b = ' , c);
c := (a and b) and b;
writeln('(a and b) and b = ' , c);
if (a or b) then
writeln('Line 1 - Condition is true' )
else
writeln('Line 1 - Condition is not true');
end.
|
unit PayPosTermProcess;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus,
Vcl.ExtCtrls, Vcl.StdCtrls, cxButtons, cxGroupBox, cxRadioGroup, cxLabel,
cxTextEdit, cxCurrencyEdit, Vcl.ActnList, dsdAction, cxClasses,
cxPropertiesStore, dsdAddOn, dsdDB, dxSkinsCore, TypInfo,
dxSkinsDefaultPainters, PosInterface, Vcl.ComCtrls, cxProgressBar;
type
TPosTermThread = class(TThread)
private
FPosTerm: IPos;
FSalerCash : currency;
FPeyResult: Boolean;
FRefund : boolean;
FShowInfo : TThreadProcedure;
FEndPayPosTerm : TThreadProcedure;
FMsgDescription : string;
FRRN : string;
procedure Execute; override;
public
{ Public declarations }
constructor Create;
destructor Destroy; override;
procedure MsgDescriptionProc(AMsgDescription : string);
procedure UpdateMsgDescription;
function GetLastPosError : string;
end;
TPayPosTermProcessForm = class(TForm)
edMsgDescription: TEdit;
cxProgressBar1: TcxProgressBar;
Timer: TTimer;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FPosTermThread : TPosTermThread;
public
{ Public declarations }
procedure EndPayPosTerm;
end;
var PayPosTermProcessForm : TPayPosTermProcessForm;
function PayPosTerminal(PosTerm: IPos; ASalerCash : currency; ARefund : boolean = False; ARRN : String = '') : Boolean;
implementation
{$R *.dfm}
procedure Add_PosLog(AMessage: String);
var F: TextFile;
begin
try
AssignFile(F,ChangeFileExt(Application.ExeName,'_PosJSON.log'));
if not fileExists(ChangeFileExt(Application.ExeName,'_PosJSON.log')) then
begin
Rewrite(F);
end
else
Append(F);
//
try Writeln(F, DateTimeToStr(Now) + ': ' + AMessage);
finally CloseFile(F);
end;
except
end;
end;
{TPosTermThread}
constructor TPosTermThread.Create;
begin
inherited Create(True);
FPosTerm := Nil;
FSalerCash := 0;
FPeyResult := False;
FMsgDescription := '';
FRRN := '';
end;
destructor TPosTermThread.Destroy;
begin
inherited Destroy;
end;
procedure TPosTermThread.Execute;
begin
if Terminated then Exit;
if not Assigned(FPosTerm) then Exit;
Add_PosLog('+++++++++++ Старт потока');
while not Terminated do
begin
Sleep(500);
if FPosTerm.ProcessType = pptThread then
begin
if FPosTerm.ProcessState = ppsWaiting then Continue;
Add_PosLog('--> ' + GetEnumName(TypeInfo(TPosProcessState), Ord(FPosTerm.ProcessState)));
if FPosTerm.ProcessState = ppsError then Break;
if FPosTerm.ProcessState = ppsUndefined then
begin
FPosTerm.CheckConnection;
end else if FPosTerm.ProcessState = ppsOkConnection then
begin
if FSalerCash <= 0 then
begin
Break;
end else
if FRefund then
begin
FPosTerm.Refund(FSalerCash, FRRN);
end else
begin
FPosTerm.Payment(FSalerCash);
end;
end else if (FPosTerm.ProcessState = ppsOkPayment) or (FPosTerm.ProcessState = ppsOkRefund) then
begin
FPeyResult := True;
Break;
end else Break;
end else
begin
if FPosTerm.CheckConnection then
begin
if (FSalerCash > 0) then
begin
if FRefund then FPosTerm.Refund(FSalerCash, FRRN)
else FPosTerm.Payment(FSalerCash);
end;
end;
Break;
end;
end;
if Assigned(FEndPayPosTerm) then FEndPayPosTerm;
Add_PosLog('-------- Финиш потока');
end;
procedure TPosTermThread.MsgDescriptionProc(AMsgDescription : string);
begin
if FMsgDescription <> AMsgDescription then
begin
FMsgDescription := AMsgDescription;
Synchronize(UpdateMsgDescription);
end;
end;
procedure TPosTermThread.UpdateMsgDescription;
begin
PayPosTermProcessForm.edMsgDescription.Text := FMsgDescription;
end;
function TPosTermThread.GetLastPosError : string;
begin
if Assigned(FPosTerm) then Result := FPosTerm.LastPosError;
end;
{TPayPosTermProcessForm}
procedure TPayPosTermProcessForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if Assigned(FPosTermThread) and not FPosTermThread.Finished and
(FPosTermThread.FPosTerm.ProcessState <> ppsError) and
(FPosTermThread.FPosTerm.ProcessState <> ppsOkPayment) and
(FPosTermThread.FPosTerm.ProcessState <> ppsOkRefund) then
begin
if MessageDlg('Прервать оплату документа?',mtConfirmation,mbYesNo,0) <> mrYes then
begin
Action := caNone;
ModalResult := 0;
Exit;
end else if not FPosTermThread.FPosTerm.Canceled and (FPosTermThread.FPosTerm.ProcessState <> ppsError) then
begin
FPosTermThread.FPosTerm.Cancel;
Action := caNone;
ModalResult := 0;
Exit;
end;
end;
if Assigned(FPosTermThread) and (ModalResult <> mrOk) and
((FPosTermThread.FPosTerm.ProcessState = ppsOkPayment) or (FPosTermThread.FPosTerm.ProcessState = ppsOkRefund)) then
begin
ModalResult := mrOk;
end;
if Assigned(FPosTermThread) then
begin
if FPosTermThread.GetLastPosError <> '' then ShowMessage(FPosTermThread.GetLastPosError);
if not FPosTermThread.Finished then FPosTermThread.Terminate;
while not FPosTermThread.Finished do Sleep(500);
FreeAndNil(FPosTermThread);
end;
Timer.Enabled := False;
end;
procedure TPayPosTermProcessForm.FormDestroy(Sender: TObject);
begin
if Assigned(FPosTermThread) then FPosTermThread.Free;
end;
procedure TPayPosTermProcessForm.FormShow(Sender: TObject);
begin
if Assigned(FPosTermThread) then FPosTermThread.Start;
Timer.Enabled := True;
end;
procedure TPayPosTermProcessForm.TimerTimer(Sender: TObject);
begin
if Assigned(FPosTermThread) then
begin
if FPosTermThread.Finished then Close;
end else Close;
end;
procedure TPayPosTermProcessForm.EndPayPosTerm;
begin
if Assigned(FPosTermThread) and FPosTermThread.FPeyResult then
begin
Add_PosLog('Успешное завершение оплаты');
ModalResult := mrOk
end else
begin
if Assigned(FPosTermThread) then Add_PosLog('Ошибка завершения оплаты')
else Add_PosLog('Ошибка завершения оплаты: Потока нет');
ModalResult := mrCancel;
end;
end;
function PayPosTerminal(PosTerm: IPos; ASalerCash : currency; ARefund : boolean = False; ARRN : String = '') : Boolean;
Begin
if NOT assigned(PayPosTermProcessForm) then
PayPosTermProcessForm := TPayPosTermProcessForm.Create(Application);
With PayPosTermProcessForm do
try
edMsgDescription.Text := 'Подключение к терминалу';
try
FPosTermThread := TPosTermThread.Create;
FPosTermThread.FPosTerm := PosTerm;
FPosTermThread.FSalerCash := ASalerCash;
FPosTermThread.FRefund := ARefund;
FPosTermThread.FRRN := ARRN;
FPosTermThread.FEndPayPosTerm := EndPayPosTerm;
PosTerm.OnMsgDescriptionProc := FPosTermThread.MsgDescriptionProc;
Result := ShowModal = mrOK;
Except ON E: Exception DO
MessageDlg(E.Message,mtError,[mbOk],0);
end;
finally
PosTerm.OnMsgDescriptionProc := Nil;
FreeAndNil(PayPosTermProcessForm);
end;
End;
end.
|
unit UStdRspsEdit;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2005 by Bradford Technologies, Inc. }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ComCtrls, Buttons, UForms;
type
TEditRsps = class(TAdvancedForm)
StatusBar1: TStatusBar;
RspList: TListBox;
GroupBox1: TGroupBox;
edtRsp: TEdit;
btnAdd: TButton;
GroupBox2: TGroupBox;
btnOK: TButton;
btnCancel: TButton;
btnMoveUp: TBitBtn;
btnMoveDown: TBitBtn;
btnSort: TButton;
btnDelete: TButton;
btnReplace: TButton;
btnInsert: TButton;
procedure btnAddClick(Sender: TObject);
procedure edtRspKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtRspKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnSortClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure RspListClick(Sender: TObject);
procedure btnReplaceClick(Sender: TObject);
procedure btnInsertClick(Sender: TObject);
procedure btnPasteClick(Sender: TObject);
procedure btnMoveUpClick(Sender: TObject);
procedure btnMoveDownClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FModified: Boolean;
procedure SetRsps(Rsps:String);
function GetRsps: String;
procedure AdjustDPISettings;
public
constructor Create(AOwner: TComponent); override;
procedure SetButtonState;
property Modified: Boolean read FModified write FModified;
property RspItems: string read GetRsps write SetRsps;
end;
var
EditRsps: TEditRsps;
implementation
{$R *.DFM}
uses
ClipBrd,
UContainer,
UEditor,
UStdRspUtil;
constructor TEditRsps.Create(AOwner: TComponent);
begin
inherited;
if assigned(AOwner)then
if AOwner is TContainer then
if assigned(TContainer(AOwner).docEditor) and (TContainer(AOwner).docEditor is TTextEditor) then
begin
edtRsp.AutoSelect := False;
edtRsp.text := (TContainer(AOwner).docEditor as TTextEditor).AnsiText;
edtRsp.SelStart := length(edtRsp.text)+1; //place cursor at end
end;
end;
//Load the responses into the list
procedure TEditRsps.SetRsps(Rsps:String);
var
i, j, m,n: Integer;
s: String;
begin
m:= 1;
j := CountRspItems(Rsps);
for i := 1 to j do
begin
n := Pos('|', Rsps);
S := Copy(Rsps, 1, n-m);
RspList.Items.Add(S);
Delete(Rsps, 1, n);
end;
SetButtonState;
end;
function TEditRsps.GetRsps: String;
var
i: Integer;
begin
result := '';
for i := 0 to RspList.Items.count-1 do
result := result + RspList.items[i] + '|';
end;
procedure TEditRsps.SetButtonState;
var
hasText: Boolean;
hasSelection: Boolean;
hasMultiple: Boolean;
begin
hasText := (Length(edtRsp.text) > 0);
hasSelection := (RspList.ItemIndex > -1);
hasMultiple := RspList.Count > 1;
btnSort.Enabled := hasMultiple;
btnMoveUp.Enabled := hasSelection and hasMultiple;
btnMoveDown.Enabled := hasSelection and hasMultiple;
btnAdd.Enabled := hasText;
btnReplace.Enabled := hasText and hasSelection;
btnDelete.Enabled := hasSelection;
btnInsert.Enabled := hasText and hasSelection;
end;
procedure TEditRsps.edtRspKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
btnAddClick(sender);
Key := 0; //no beeps
end;
end;
procedure TEditRsps.edtRspKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
SetButtonState;
end;
procedure TEditRsps.RspListClick(Sender: TObject);
begin
if RspList.itemIndex > -1 then
begin
edtRsp.AutoSelect := True;
edtRsp.text := RspList.Items.Strings[RspList.itemIndex];
end;
SetButtonState;
end;
procedure TEditRsps.btnSortClick(Sender: TObject);
begin
RspList.itemIndex := -1;
RspList.Sorted := True; //do it, get
RspList.Sorted := False; //ready for next
FModified := True;
end;
procedure TEditRsps.btnAddClick(Sender: TObject);
begin
if Length(edtRsp.text) > 0 then
begin
RspList.Items.add(edtRsp.text);
edtRsp.text := '';
SetButtonState; //set the button state
FModified := True;
end;
end;
procedure TEditRsps.btnDeleteClick(Sender: TObject);
begin
RspList.Items.Delete(RspList.itemIndex);
SetButtonState;
FModified := True;
end;
procedure TEditRsps.btnReplaceClick(Sender: TObject);
begin
RspList.Items.Strings[RspList.itemIndex] := edtRsp.text;
edtRsp.text := '';
RspList.itemIndex := -1;
SetButtonState;
FModified := True;
end;
procedure TEditRsps.btnInsertClick(Sender: TObject);
begin
RspList.Items.Insert(RspList.itemIndex, edtRsp.text);
edtRsp.text := '';
RspList.itemIndex := -1;
SetButtonState;
FModified := True;
end;
procedure TEditRsps.btnPasteClick(Sender: TObject);
begin
RspList.Items.Text := ClipBoard.AsText;
FModified := True;
end;
procedure TEditRsps.btnMoveUpClick(Sender: TObject);
var
n, n2: integer;
begin
n := RspList.ItemIndex;
if n > 0 then
begin
n2 := n-1;
RspList.Items.Exchange(n, n2); // for display
FModified := True;
end
else
beep;
end;
procedure TEditRsps.btnMoveDownClick(Sender: TObject);
var
n, n2: integer;
begin
n := RspList.ItemIndex;
If n < RspList.Items.Count-1 then
begin
n2 := n+1;
RspList.Items.Exchange(n, n2); // for display
FModified := True;
end
else
beep;
end;
procedure TEditRsps.AdjustDPISettings;
begin
self.ClientHeight := GroupBox2.Height + GroupBox1.Height + StatusBar1.Height;
self.ClientWidth := Groupbox1.Width;
self.Constraints.minHeight := self.Height;
self.Constraints.MinWidth := self.width;
end;
procedure TEditRsps.FormShow(Sender: TObject);
begin
AdjustDPISettings;
end;
end.
|
unit AbstractDatabaseMessagingService;
interface
uses
MessagingServiceCommonObjects,
MessagingServiceUnit,
VariantTypeUnit,
QueryExecutor,
SysUtils,
Classes;
type
TDatabaseMessagingServiceSchemaData = class
public
MessageTableName: String;
MessageNameColumnName: String;
MessageContentColumnName: String;
MessageSenderColumnName: String;
MessageReceiversColumnName: String;
MessageAttachmentsColumnName: String;
MessageNameQueryParamName: String;
MessageContentQueryParamName: String;
MessageSenderQueryParamName: String;
MessageReceiversQueryParamName: String;
MessageAttachmentsQueryParamName: String;
end;
TAbstractDatabaseMessagingServiceException = class (Exception)
end;
TAbstractDatabaseMessagingService =
class (TInterfacedObject, IMessagingService)
private
FSchemaData: TDatabaseMessagingServiceSchemaData;
FQueryExecutor: IQueryExecutor;
FPreparedMessageDataInsertingQueryPattern: String;
protected
procedure SetSchemaData(const Value: TDatabaseMessagingServiceSchemaData);
function PreparedMessageDataInsertingQueryPattern: String;
protected
function PrepareMessageDataInsertingQueryPattern(
SchemaData: TDatabaseMessagingServiceSchemaData
): String; virtual;
protected
function MapMessageDataInsertingQueryParamsFrom(Message: IMessage): TQueryParams; virtual;
function MapMessageNameDataFrom(const MessageName: String): Variant; virtual;
function MapMessageContentDataFrom(const MessageContent: TStrings): Variant; virtual;
function MapMessageSenderDataFrom(MessageSender: IMessageMember): Variant; virtual;
function MapMessageReceiversDataFrom(MessageReceivers: IMessageMembers): Variant; virtual;
function MapMessageAttachmentsDataFrom(MessageAttachments: IMessageAttachments): Variant; virtual;
protected
procedure ExecuteMessageDataInsertingQuery(
const QueryText: String;
QueryParams: TQueryParams
); virtual;
procedure ExecuteMessageDataInsertingQueryAsync(
const QueryText: String;
QueryParams: TQueryParams;
Message: IMessage;
RelatedState: TObject;
OnMessageSentEventHandler: TOnMessageSentEventHandler;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler
); virtual;
protected
procedure OnModificationQuerySuccessedEventHandler(
Sender: TObject;
RowsAffected: Integer;
RelatedState: TObject
);
procedure OnModificationQueryFailedEventHandler(
Sender: TObject;
const Error: Exception;
RelatedState: TObject
);
protected
procedure InternalSendMessageAsync(
Message: IMessage;
OnMessageSentEventHandler: TOnMessageSentEventHandler = nil;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler = nil;
RelatedState: TObject = nil
); virtual;
public
destructor Destroy; override;
constructor Create(
SchemaData: TDatabaseMessagingServiceSchemaData;
QueryExecutor: IQueryExecutor
);
function GetSelf: TObject;
function CreateMessageInstance: IMessage; virtual;
function CreateMessagesInstance: IMessages; virtual;
procedure SendMessage(Message: IMessage); virtual;
procedure SendMessages(Messages: IMessages); virtual;
procedure SendMessageAsync(
Message: IMessage;
OnMessageSentEventHandler: TOnMessageSentEventHandler = nil;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler = nil;
RelatedState: TObject = nil
); virtual;
procedure SendMessagesAsync(
Messages: IMessages;
OnMessageSentEventHandler: TOnMessageSentEventHandler = nil;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler = nil;
RelatedState: TObject = nil
); virtual;
published
property QueryExecutor: IQueryExecutor
read FQueryExecutor write FQueryExecutor;
property SchemaData: TDatabaseMessagingServiceSchemaData
read FSchemaData write SetSchemaData;
end;
implementation
uses
Variants,
AuxDebugFunctionsUnit;
type
TAsyncSendingMessageEventHandlersData = class
Message: IMessage;
RelatedState: TObject;
OnMessageSentEventHandler: TOnMessageSentEventHandler;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler;
constructor Create(
Message: IMessage;
RelatedState: TObject;
OnMessageSentEventHandler: TOnMessageSentEventHandler;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler
);
end;
{ TAbstractDatabaseMessagingService }
constructor TAbstractDatabaseMessagingService.Create(
SchemaData: TDatabaseMessagingServiceSchemaData;
QueryExecutor: IQueryExecutor
);
begin
inherited Create;
Self.SchemaData := SchemaData;
Self.QueryExecutor := QueryExecutor;
FPreparedMessageDataInsertingQueryPattern :=
PrepareMessageDataInsertingQueryPattern(SchemaData);
end;
function TAbstractDatabaseMessagingService.CreateMessageInstance: IMessage;
begin
Result := TCommonMessage.Create;
end;
function TAbstractDatabaseMessagingService.CreateMessagesInstance: IMessages;
begin
Result := TCommonMessages.Create;
end;
destructor TAbstractDatabaseMessagingService.Destroy;
begin
FreeAndNil(FSchemaData);
inherited;
end;
procedure TAbstractDatabaseMessagingService.
ExecuteMessageDataInsertingQuery(
const QueryText: String;
QueryParams: TQueryParams
);
begin
FQueryExecutor.ExecuteModificationQuery(
QueryText,
QueryParams
);
end;
procedure TAbstractDatabaseMessagingService.
ExecuteMessageDataInsertingQueryAsync(
const QueryText: String;
QueryParams: TQueryParams;
Message: IMessage;
RelatedState: TObject;
OnMessageSentEventHandler: TOnMessageSentEventHandler;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler
);
begin
FQueryExecutor.ExecuteModificationQueryAsync(
QueryText,
QueryParams,
TAsyncSendingMessageEventHandlersData.Create(
Message,
RelatedState,
OnMessageSentEventHandler,
OnMessageSendingFailedEventHandler
),
OnModificationQuerySuccessedEventHandler,
OnModificationQueryFailedEventHandler
);
end;
function TAbstractDatabaseMessagingService.GetSelf: TObject;
begin
Result := Self;
end;
procedure TAbstractDatabaseMessagingService.InternalSendMessageAsync(
Message: IMessage;
OnMessageSentEventHandler: TOnMessageSentEventHandler;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler;
RelatedState: TObject
);
var MessageDataInsertingQueryParams: TQueryParams;
begin
MessageDataInsertingQueryParams :=
MapMessageDataInsertingQueryParamsFrom(Message);
try
ExecuteMessageDataInsertingQueryAsync(
PreparedMessageDataInsertingQueryPattern,
MessageDataInsertingQueryParams,
Message,
RelatedState,
OnMessageSentEventHandler,
OnMessageSendingFailedEventHandler
);
finally
FreeAndNil(MessageDataInsertingQueryParams);
end;
end;
function TAbstractDatabaseMessagingService.MapMessageAttachmentsDataFrom(
MessageAttachments: IMessageAttachments): Variant;
var MessageAttachment: IMessageAttachment;
AttachmentListString: String;
begin
for MessageAttachment in MessageAttachments do begin
if AttachmentListString = '' then
AttachmentListString := MessageAttachment.FilePath
else
AttachmentListString :=
AttachmentListString + ';' + MessageAttachment.FilePath;
end;
Result := AttachmentListString;
end;
function TAbstractDatabaseMessagingService.MapMessageDataInsertingQueryParamsFrom(
Message: IMessage
): TQueryParams;
var CommonMessage: TCommonMessage;
begin
if not (Message.Self is TCommonMessage) then
raise TAbstractDatabaseMessagingServiceException.Create(
'Не известен тип отправляемого сообщения ' +
'для выполнения разбора'
);
CommonMessage := Message.Self as TCommonMessage;
Result :=
TQueryParams
.Create
.AddFluently(
SchemaData.MessageNameQueryParamName,
MapMessageNameDataFrom(CommonMessage.Name)
)
.AddFluently(
SchemaData.MessageContentQueryParamName,
MapMessageContentDataFrom(CommonMessage.Content)
)
.AddFluently(
SchemaData.MessageSenderQueryParamName,
MapMessageSenderDataFrom(CommonMessage.Sender)
)
.AddFluently(
SchemaData.MessageReceiversQueryParamName,
MapMessageReceiversDataFrom(CommonMessage.Receivers)
)
.AddFluently(
SchemaData.MessageAttachmentsQueryParamName,
MapMessageAttachmentsDataFrom(CommonMessage.Attachments)
);
end;
function TAbstractDatabaseMessagingService.MapMessageContentDataFrom(
const MessageContent: TStrings): Variant;
var ContentString: String;
I: Integer;
begin
for I := 0 to MessageContent.Count - 1 do begin
if ContentString = '' then
ContentString := MessageContent[I]
else
ContentString := ContentString + '\r\n' + MessageContent[I];
end;
Result := ContentString;
end;
function TAbstractDatabaseMessagingService.MapMessageNameDataFrom(
const MessageName: String): Variant;
begin
Result := MessageName;
end;
function TAbstractDatabaseMessagingService.MapMessageReceiversDataFrom(
MessageReceivers: IMessageMembers
): Variant;
var MessageReceiver: IMessageMember;
ReceiverListString: String;
begin
for MessageReceiver in MessageReceivers do begin
if ReceiverListString = '' then
ReceiverListString := VarToStr(MessageReceiver.Identifier)
else
ReceiverListString :=
ReceiverListString + ',' + VarToStr(MessageReceiver.Identifier);
end;
Result := ReceiverListString;
end;
function TAbstractDatabaseMessagingService.MapMessageSenderDataFrom(
MessageSender: IMessageMember): Variant;
begin
Result := VarToStr(MessageSender.Identifier);
end;
procedure TAbstractDatabaseMessagingService.
OnModificationQueryFailedEventHandler(
Sender: TObject;
const Error: Exception;
RelatedState: TObject
);
var AsyncSendingMessageEventHandlersData: TAsyncSendingMessageEventHandlersData;
begin
AsyncSendingMessageEventHandlersData :=
RelatedState as TAsyncSendingMessageEventHandlersData;
try
if Assigned(AsyncSendingMessageEventHandlersData.OnMessageSendingFailedEventHandler)
then begin
AsyncSendingMessageEventHandlersData.OnMessageSendingFailedEventHandler(
Self,
AsyncSendingMessageEventHandlersData.Message,
Error,
AsyncSendingMessageEventHandlersData.RelatedState
);
end;
finally
FreeAndNil(AsyncSendingMessageEventHandlersData);
end;
end;
procedure TAbstractDatabaseMessagingService.
OnModificationQuerySuccessedEventHandler(
Sender: TObject;
RowsAffected: Integer;
RelatedState: TObject
);
var AsyncSendingMessageEventHandlersData: TAsyncSendingMessageEventHandlersData;
begin
AsyncSendingMessageEventHandlersData :=
RelatedState as TAsyncSendingMessageEventHandlersData;
try
if Assigned(AsyncSendingMessageEventHandlersData.OnMessageSentEventHandler)
then begin
AsyncSendingMessageEventHandlersData.OnMessageSentEventHandler(
Self,
AsyncSendingMessageEventHandlersData.Message,
AsyncSendingMessageEventHandlersData.RelatedState
);
end;
finally
FreeAndNil(AsyncSendingMessageEventHandlersData);
end;
end;
function TAbstractDatabaseMessagingService.
PreparedMessageDataInsertingQueryPattern: String;
begin
Result := FPreparedMessageDataInsertingQueryPattern;
end;
function TAbstractDatabaseMessagingService.
PrepareMessageDataInsertingQueryPattern(
SchemaData: TDatabaseMessagingServiceSchemaData
): String;
begin
Result :=
Format(
'INSERT INTO %s ' +
'(%s,%s,%s,%s,%s) ' +
'VALUES (:%s,:%s,:%s,:%s,:%s)',
[
SchemaData.MessageTableName,
SchemaData.MessageNameColumnName,
SchemaData.MessageContentColumnName,
SchemaData.MessageSenderColumnName,
SchemaData.MessageReceiversColumnName,
SchemaData.MessageAttachmentsColumnName,
SchemaData.MessageNameQueryParamName,
SchemaData.MessageContentQueryParamName,
SchemaData.MessageSenderQueryParamName,
SchemaData.MessageReceiversColumnName,
SchemaData.MessageAttachmentsQueryParamName
]
);
end;
procedure TAbstractDatabaseMessagingService.SendMessage(Message: IMessage);
var MessageDataInsertingQueryParams: TQueryParams;
begin
MessageDataInsertingQueryParams :=
MapMessageDataInsertingQueryParamsFrom(Message);
try
ExecuteMessageDataInsertingQuery(
PreparedMessageDataInsertingQueryPattern,
MessageDataInsertingQueryParams
);
finally
FreeAndNil(MessageDataInsertingQueryParams);
end;
end;
procedure TAbstractDatabaseMessagingService.SendMessageAsync(
Message: IMessage;
OnMessageSentEventHandler: TOnMessageSentEventHandler;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler;
RelatedState: TObject
);
begin
InternalSendMessageAsync(
Message,
OnMessageSentEventHandler,
OnMessageSendingFailedEventHandler
);
end;
procedure TAbstractDatabaseMessagingService.SendMessages(Messages: IMessages);
var Message: IMessage;
begin
{ Refactor: перенести в более абстрактный класс,
как реализацию по умолчанию }
for Message in Messages do SendMessage(Message);
end;
procedure TAbstractDatabaseMessagingService.SendMessagesAsync(
Messages: IMessages;
OnMessageSentEventHandler: TOnMessageSentEventHandler;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler;
RelatedState: TObject
);
var Message: IMessage;
begin
{ Refactor: перенести в более абстрактный класс,
как реализацию по умолчанию }
for Message in Messages do begin
InternalSendMessageAsync(
Message,
OnMessageSentEventHandler,
OnMessageSendingFailedEventHandler,
RelatedState
);
end;
end;
procedure TAbstractDatabaseMessagingService.SetSchemaData(
const Value: TDatabaseMessagingServiceSchemaData);
begin
FreeAndNil(FSchemaData);
FSchemaData := Value;
end;
{ TAsyncSendingMessageEventHandlersData }
constructor TAsyncSendingMessageEventHandlersData.Create(
Message: IMessage;
RelatedState: TObject;
OnMessageSentEventHandler: TOnMessageSentEventHandler;
OnMessageSendingFailedEventHandler: TOnMessageSendingFailedEventHandler
);
begin
inherited Create;
Self.Message := Message;
Self.RelatedState := RelatedState;
Self.OnMessageSentEventHandler := OnMessageSentEventHandler;
Self.OnMessageSendingFailedEventHandler := OnMessageSendingFailedEventHandler;
end;
end.
|
unit uiwindow_wndproc_mouse;
interface
uses
Windows,
Messages,
uiwindow_clip;
var
IsDragStarting: Boolean = False;
DragStartPoint: TSmallPoint;
WMMouseMove_CursorPoint: TSmallPoint;
function UIWndProcA_Mouse(AUIWindow: PUIWindow; AMsg: UINT; wParam: WPARAM; lParam: LPARAM; var AWndProcResult: LRESULT): Boolean;
implementation
uses
uiwindow_wndproc_paint;
function WndProcA_WMLButtonUp(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
IsDragStarting := false;
UIWindowPaint(AUIWindow);
Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_LBUTTONUP, wParam, lParam);
end;
function WndProcA_WMLButtonDown(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
if 20 > TSmallPoint(lParam).y then
begin
SendMessage(AUIWindow.BaseWnd.UIWndHandle, WM_SYSCOMMAND, HTCaption or SC_MOVE, 0);
// SendMessage(AUIWindow.BaseWnd.UIWndHandle, WM_NCLButtonDown, HTCaption, GetMessagePos);
IsDragStarting := False;
end else
begin
DragStartPoint := TSmallPoint(lParam);
IsDragStarting := True;
end;
Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_LBUTTONDOWN, wParam, lParam);
end;
function WndProcA_WMMouseMove(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
WMMouseMove_CursorPoint := TSmallPoint(lParam);
UIWindowPaint(AUIWindow);
Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_MOUSEMOVE, wParam, lParam);
end;
function WndProcA_WMMouseWheel(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_MOUSEWHEEL, wParam, lParam);
end;
function WndProcA_WMSetCursor(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_SETCURSOR, wParam, lParam);
end;
function WndProcA_WMNCHitTest(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := HTCLIENT;
end;
function WndProcA_WMMouseHover(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_MOUSEHOVER, wParam, lParam);
end;
function WndProcA_WMMouseLeave(AUIWindow: PUIWindow; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
Result := DefWindowProcA(AUIWindow.BaseWnd.UIWndHandle, WM_MOUSELEAVE, wParam, lParam);
end;
function UIWndProcA_Mouse(AUIWindow: PUIWindow; AMsg: UINT; wParam: WPARAM; lParam: LPARAM; var AWndProcResult: LRESULT): Boolean;
begin
Result := true;
case AMsg of
WM_LButtonUp: AWndProcResult := WndProcA_WMLButtonUp(AUIWindow, wParam, lParam);
WM_LButtonDown: AWndProcResult := WndProcA_WMLButtonDown(AUIWindow, wParam, lParam);
WM_MouseMove: AWndProcResult := WndProcA_WMMouseMove(AUIWindow, wParam, lParam);
WM_MOUSEWHEEL: AWndProcResult := WndProcA_WMMouseWheel(AUIWindow, wParam, lParam);
WM_SETCURSOR: AWndProcResult := WndProcA_WMSetCursor(AUIWindow, wParam, lParam);
WM_NCHITTEST: AWndProcResult := WndProcA_WMNCHitTest(AUIWindow, wParam, lParam);
WM_MOUSEHOVER: AWndProcResult := WndProcA_WMMouseHover(AUIWindow, wParam, lParam);
WM_MOUSELEAVE: AWndProcResult := WndProcA_WMMouseLeave(AUIWindow, wParam, lParam);
else
Result := false;
end;
end;
end.
|
unit uP2_pesan;
interface
procedure shoutWarning(kodePesan : string);
{Menampilkan peringatan pesan kesalahan berdasarkan kodePesan}
procedure tampilkanMenu(kodeMenu : string);
{Menampilkan tampilan menu berdasarkan kodeMenu}
implementation
procedure shoutWarning(kodePesan : string);
{Menampilkan peringatan pesan kesalahan berdasarkan kodePesan}
begin
case (kodePesan) of
'belumLoad' : begin
writeln('-------------------------------------------');
writeln('WARNING : Anda belum meload file eksternal!');
writeln('-------------------------------------------');
writeln();
end;
'salahPerintah' : begin
writeln('-----------------------------------------------------------------');
writeln('WARNING : Perintah yang anda masukkan tidak tepat atau salah eja.');
writeln('-----------------------------------------------------------------');
writeln();
end;
'exitProgram' : begin
writeln('Terima kasih telah menggunakan jasa kami!');
writeln('Sampai berjumpa di lain waktu!');
writeln('Tekan "enter" untuk mengakhiri program');
end;
end;
end;
procedure tampilkanMenu(kodeMenu : string);
{Menampilkan tampilan menu berdasarkan kodeMenu}
begin
case (kodeMenu) of
'utama' : begin
writeln('Berikut pilihan perintah yang dapat anda masukkan pada prompt :');
writeln('1. load');
writeln('2. exit');
writeln('3. start i (i=id simulasi yang diinginkan');
writeln('4. lihatInventori');
writeln('5. lihatResep');
writeln('6. cariResep');
writeln('7. tambahResep');
writeln('8. upgradeInventori');
end;
'startSimulasi' : begin
writeln('--------------------------------------');
writeln('--------------SIMULASI----------------');
writeln('--------------------------------------');
writeln('Berikut pilihan perintah simulasi yang dapat anda masukkan');
writeln('1. stopSimulasi');
writeln('2. beliBahan');
writeln('3. olahBahan');
writeln('4. jualOlahan');
writeln('5. jualResep');
writeln('6. makan');
writeln('7. istirahat');
writeln('8. tidur');
writeln('9. lihatStatistik');
writeln('10. lihatInventori');
writeln('11. lihatResep');
writeln('12. cariResep');
writeln('13. tambahResep');
writeln('14. upgradeInventori');
writeln('Masukkan perintah anda setelah tanda ">> "');
end;
'awal' : begin
writeln('----------------------------------------');
writeln('----PROGRAM SIMULASI ENGI''S KITCHEN----');
writeln('----------------------------------------');
writeln();
end;
end;
end;
end.
|
unit UAMC_SavePak;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UAMC_WorkFlowBaseFrame, StdCtrls, RzShellDialogs,
UContainer, UAMC_Base, ShellAPI, MSXML6_TLB;
type
TAMC_SavePak = class(TWorkflowBaseFrame)
edtXMLDirPath: TEdit;
btnSavePDF: TButton;
edtPDFDirPath: TEdit;
edtENVDirPath: TEdit;
btnSaveXML: TButton;
btnSaveENV: TButton;
stxNoteEmbeddedPDF: TStaticText;
cbxUseSameFolder: TCheckBox;
btnSaveAll: TButton;
stxXMLSaved: TStaticText;
stxPDFSaved: TStaticText;
stxENVSaved: TStaticText;
stxXML: TStaticText;
stxPDF: TStaticText;
stxENV: TStaticText;
edtSaveAllDirPath: TEdit;
btnBrowse: TButton;
SelectFolderDialog: TRzSelectFolderDialog;
lblUseSameFolder: TStaticText;
ck_xml: TCheckBox;
ck_pdf: TCheckBox;
ck_env: TCheckBox;
btnEmail: TButton;
procedure btnSaveXMLClick(Sender: TObject);
procedure btnSavePDFClick(Sender: TObject);
procedure btnSaveENVClick(Sender: TObject);
procedure btnSaveAllClick(Sender: TObject);
procedure EnDisOptions(SaveAll: Boolean);
procedure cbxUseSameFolderClick(Sender: TObject);
procedure btnBrowseClick(Sender: TObject);
procedure btnEmailClick(Sender: TObject);
procedure ck_xmlClick(Sender: TObject);
procedure ck_pdfClick(Sender: TObject);
procedure ck_envClick(Sender: TObject);
private
FFilesSaved: Integer;
FUseSameName: Boolean;
public
constructor CreateFrame(AOwner: TComponent; ADoc: TContainer; AData: TDataPackage); override;
procedure InitPackageData; override;
function ProcessedOK: Boolean; override;
procedure SetDefaultFileNames;
procedure SetSuccessfulSaveNotice(extOpt: Integer);
procedure ResetDirs(SelDir: String);
procedure SaveDataFile(dataFile: TDataFile; extOpt: Integer);
procedure SaveXMLDataFile(dataFile: TDataFile; filePath: String);
function GetFileName(const fName, fPath: String; extOpt: Integer): String;
function GetDocFileNameWithDataExt(extOpt: Integer): String;
end;
implementation
{$R *.dfm}
uses
UGlobals, UMyClickForms, UUtil1, UFileFinder, UStatus;
const
optXML = 1; //options to set the fileExt during save
optPDF = 2;
optENV = 3;
XML_SAVE_CAPTION = 'XML file has been successfully saved';
PDF_SAVE_CAPTION = 'PDF file has been successfully saved';
ENV_SAVE_CAPTION = 'ENV file has been successfully saved';
{ TAMC_SavePak }
constructor TAMC_SavePak.CreateFrame(AOwner: TComponent; ADoc: TContainer;
AData: TDataPackage);
begin
inherited;
FFilesSaved := 0; //set it here so its not reset by InitPakdata
FUseSameName := True; //use same name as Doc
end;
procedure TAMC_SavePak.InitPackageData;
var
ChkBoxTopAdj : Integer;
begin
inherited;
ChkBoxTopAdj := Round((cbxUseSameFolder.Height - lblUseSameFolder.Height) / 2);
cbxUseSameFolder.Top := lblUseSameFolder.Top + ChkBoxTopAdj;
lblUseSameFolder.Font.Size := Font.Size;
//initial settings
edtXMLDirPath.Enabled := False;
btnSaveXML.Enabled := False;
edtPDFDirPath.enabled := False;
btnSavePDF.enabled := False;
edtENVDirPath.enabled := False;
btnSaveENV.Enabled := False;
ck_xml.Enabled := False;
ck_pdf.Enabled := False;
ck_env.Enabled := False;
edtSaveAllDirPath.Enabled := False;
if PackageData.DataFiles.Count > 1 then //we have data files to save
begin
cbxUseSameFolder.Visible := True;
cbxUseSameFolder.Checked := appPref_DirWorkflowSameDir;
edtSaveAllDirPath.Visible := True;
edtSaveAllDirPath.Text := appPref_DirWorkflowSameDirPath;
end;
if PackageData.DataFiles.DataFileHasData(fTypXML26GSE) or
PackageData.DataFiles.DataFileHasData(fTypXML26) then
begin
stxNoteEmbeddedPDF.Visible := PackageData.FEmbbedPDF;
end;
EnDisOptions(cbxUseSameFolder.Checked);
SetDefaultFileNames;
///*** clear the label caption when we first started
stxXMLSaved.Caption := '';
stxPDFSaved.Caption := '';
stxENVSaved.Caption := '';
///*** reset FFilesSaved so the prev/next button will work properly if we go back and forth
FFilesSaved:=0;
end;
function TAMC_SavePak.ProcessedOK: Boolean;
var
needMoreSaves: Boolean;
function WarningMsg: String;
begin
if FFilesSaved = 0 then
result := 'Stop! No files have been saved. Do you want to continue?'
else
result := 'Not all the files have been saved. Do you want to continue?';
end;
begin
needMoreSaves := (FFilesSaved < PackageData.DataFiles.Count);
PackageData.FEndMsg := 'The appraisal files were successfully saved.'; //finishing message to user
PackageData.FAlertMsg := '';
PackageData.FGoToNextOk := not needMoreSaves;
PackageData.FHardStop := False;
if needMoreSaves then
if WarnOK2Continue(WarningMsg) then
begin
PackageData.FGoToNextOk := True; //we are leaving so let them know, files not save
PackageData.FEndMsg := 'The appraisal files were not saved.'; //finishing message to user
end
else
begin
PackageData.FGoToNextOk := False;
end;
result := PackageData.FGoToNextOk;
end;
procedure TAMC_SavePak.btnSaveXMLClick(Sender: TObject);
var
dataFile: TDataFile;
begin
inherited;
dataFile := nil;
if PackageData.DataFiles.DataFileHasData(fTypXML26) then
begin
dataFile := PackageData.DataFiles.GetDataFileObj(fTypXML26, False);
end
else if PackageData.DataFiles.DataFileHasData(fTypXML26GSE) then
begin
dataFile := PackageData.DataFiles.GetDataFileObj(fTypXML26GSE, False);
end
else if PackageData.DataFiles.DataFileHasData(fTypXML241) then
begin
dataFile := PackageData.DataFiles.GetDataFileObj(fTypXML241, False);
end;
if assigned(dataFile) then
SaveDataFile(dataFile, optXML);
ck_xml.Enabled := True;
end;
procedure TAMC_SavePak.btnSavePDFClick(Sender: TObject);
var
dataFile: TDataFile;
begin
inherited;
dataFile := PackageData.DataFiles.GetDataFileObj(fTypPDF, False);
if assigned(dataFile) then
SaveDataFile(dataFile, optPDF);
ck_pdf.Enabled := True;
end;
procedure TAMC_SavePak.btnSaveENVClick(Sender: TObject);
var
dataFile: TDataFile;
begin
inherited;
dataFile := PackageData.DataFiles.GetDataFileObj(fTypENV, False);
if assigned(dataFile) then
SaveDataFile(dataFile, optENV);
ck_env.Enabled := True;
end;
procedure TAMC_SavePak.SaveDataFile(dataFile: TDataFile; extOpt: Integer);
var
fName, filePath: String;
dFolder: String;
begin
fName := GetDocFileNameWithDataExt(extOpt);
//set the destination folder
case extOpt of
optXML: dFolder := appPref_DirWorkflowXMLPath;
optPDF: dFolder := appPref_DirWorkflowPDFPath;
optENV: dFolder := appPref_DirWorkflowENVPath;
end;
//do we put files into same folder
if cbxUseSameFolder.checked and VerifyFolder(dFolder) then
filepath := IncludeTrailingPathDelimiter(dFolder) + fName
else
filePath := GetFileName(fName, dFolder, extOpt);
if length(filePath) > 0 then //a file path was actually returned
begin
//reset the destion folder prefs in case they changed
if cbxUseSameFolder.checked then
begin
appPref_DirWorkflowXMLPath := ExtractFilePath(filePath);
appPref_DirWorkflowPDFPath := ExtractFilePath(filePath);
appPref_DirWorkflowENVPath := ExtractFilePath(filePath);
end;
if fileExists(filePath) then //eliminate duplicates at destination
DeleteFile(filePath);
try
try
//dataFile.SaveToFile(filePath);
case extOpt of //refresh the new full file name back to the edit box
optXML: begin
SaveXMLDataFile(dataFile, filePath);
edtXMLDirPath.Text := filePath;
appPref_DirWorkflowXMLPath := ExtractFileDir(filePath); //remember them individually
end;
optPDF: begin
dataFile.SaveToFile(filePath);
edtPDFDirPath.Text := filePath;
appPref_DirWorkflowPDFPath := ExtractFileDir(filePath);
end;
optENV: begin
dataFile.SaveToFile(filePath);
edtENVDirPath.Text := filePath;
appPref_DirWorkflowENVPath := ExtractFileDir(filePath);
end;
end;
Inc(FFilesSaved);
except
on E: Exception do
ShowAlert(atWarnAlert, 'A problem was encountered saving the file: ' + E.Message);
end;
finally
appPref_DirWorkflowSameDir := cbxUseSameFolder.Checked;
SetSuccessfulSaveNotice(extOpt);
end;
end;
end;
procedure TAMC_SavePak.btnSaveAllClick(Sender: TObject);
var
dataFile: TDataFile;
begin
inherited;
dataFile := nil;
if PackageData.DataFiles.DataFileHasData(fTypXML26) then
begin
dataFile := PackageData.DataFiles.GetDataFileObj(fTypXML26, False);
end
else if PackageData.DataFiles.DataFileHasData(fTypXML26GSE) then
begin
dataFile := PackageData.DataFiles.GetDataFileObj(fTypXML26GSE, False);
end
else if PackageData.DataFiles.DataFileHasData(fTypXML241) then
begin
dataFile := PackageData.DataFiles.GetDataFileObj(fTypXML241, False);
end;
if assigned(dataFile) then
begin
SaveDataFile(dataFile, optXML);
ck_xml.Enabled := true;
end;
dataFile := PackageData.DataFiles.GetDataFileObj(fTypPDF, False);
if assigned(dataFile) then
begin
SaveDataFile(dataFile, optPDF);
ck_pdf.Enabled := true;
end;
dataFile := PackageData.DataFiles.GetDataFileObj(fTypENV, False);
if assigned(dataFile) then
begin
SaveDataFile(dataFile, optENV);
ck_env.Enabled := true;
end;
end;
//Similar code in UAMC_BuildPDF. Probably should put in Utilities
function TAMC_SavePak.GetFileName(const fName, fPath: String; ExtOpt: Integer): String;
var
myClkDir: String;
SaveDialog: TSaveDialog;
begin
result := '';
myClkDir := MyFolderPrefs.MyClickFormsDir;
SaveDialog := TSaveDialog.Create(nil);
try
SaveDialog.InitialDir := VerifyInitialDir(fPath, myClkDir);
SaveDialog.FileName := fName;
case ExtOpt of
OptXML: begin
SaveDialog.DefaultExt := 'xml';
SaveDialog.Filter := 'MISMO XML (*.xml)|*.xml';
end;
OptPDF: begin
SaveDialog.DefaultExt := 'pdf';
SaveDialog.Filter := 'PDF (*.pdf)|*.pdf'; //'*.xml|All Files (*.*)|*.*';
end;
optENV: begin
SaveDialog.DefaultExt := 'env';
SaveDialog.Filter := 'ENV (*.env)|*.env'; //'*.xml|All Files (*.*)|*.*';
end;
end;
SaveDialog.FilterIndex := 1;
if SaveDialog.Execute then
result := SaveDialog.Filename;
finally
SaveDialog.Free;
end;
end;
function TAMC_SavePak.GetDocFileNameWithDataExt(extOpt: Integer): String;
var
extension: String;
begin
case extOpt of
optXML: extension := '.xml';
optPDF: extension := '.pdf';
optENV: extension := '.env';
end;
result := ChangeFileExt(FDoc.docFileName, extension);
end;
procedure TAMC_SavePak.SetDefaultFileNames;
var
dFolder, fName: String;
begin
if PackageData.DataFiles.DataFileHasData(fTypXML26GSE) or
PackageData.DataFiles.DataFileHasData(fTypXML26) or
PackageData.DataFiles.DataFileHasData(fTypXML241) then
begin
fName := 'Untitled';
if FUseSameName then
fName := GetDocFileNameWithDataExt(optXML);
dFolder := '';
if length(appPref_DirWorkflowXMLPath) > 0 then
dFolder := IncludeTrailingPathDelimiter(appPref_DirWorkflowXMLPath);
edtXMLDirPath.Text := dFolder + fName;
end;
if PackageData.DataFiles.DataFileHasData(fTypPDF) then
begin
fName := 'Untitled';
if FUseSameName then
fName := GetDocFileNameWithDataExt(optPDF);
dFolder := '';
if length(appPref_DirWorkflowPDFPath) > 0 then
dFolder := IncludeTrailingPathDelimiter(appPref_DirWorkflowPDFPath);
edtPDFDirPath.Text := dFolder + fName;
end;
if PackageData.DataFiles.DataFileHasData(fTypENV) then
begin
fName := 'Untitled';
if FUseSameName then
fName := GetDocFileNameWithDataExt(optENV);
dFolder := '';
if length(appPref_DirWorkflowENVPath) > 0 then
dFolder := IncludeTrailingPathDelimiter(appPref_DirWorkflowENVPath);
edtENVDirPath.Text := dFolder + fName;
end;
end;
procedure TAMC_SavePak.SetSuccessfulSaveNotice(extOpt: Integer);
begin
case extOpt of
optXML: begin stxXMLSaved.Visible := True; stxXMLSaved.Caption := XML_SAVE_CAPTION; end;
optPDF: begin stxPDFSaved.Visible := True; stxPDFSaved.Caption := PDF_SAVE_CAPTION; end;
optENV: begin stxENVSaved.Visible := True; stxENVSaved.Caption := ENV_SAVE_CAPTION; end;
end;
end;
procedure TAMC_SavePak.ResetDirs(SelDir: String);
function ResetDir(theDir, theFName: String): String;
var
CurFName: String;
begin
CurFName := ExtractFileName(theFName);
if CurFName <> '' then
Result := theDir + CurFName;
end;
begin
if (SelDir <> '') and (DirectoryExists(SelDir)) then
begin
SelDir := IncludeTrailingPathDelimiter(SelDir);
edtSaveAllDirPath.Text := SelDir;
appPref_DirWorkflowXMLPath := SelDir;
appPref_DirWorkflowPDFPath := SelDir;
appPref_DirWorkflowENVPath := SelDir;
appPref_DirWorkflowSameDirPath := SelDir;
if (edtXMLDirPath.Text <> '') and DirectoryExists(ExtractFileDir(edtXMLDirPath.Text)) then
begin
if edtXMLDirPath.Text <> 'XML Directory' then
edtXMLDirPath.Text := ResetDir(SelDir, edtXMLDirPath.Text);
if edtPDFDirPath.Text <> 'PDF Directory' then
edtPDFDirPath.Text := ResetDir(SelDir, edtPDFDirPath.Text);
if edtENVDirPath.Text <> 'ENV Directory' then
edtENVDirPath.Text := ResetDir(SelDir, edtENVDirPath.Text);
end;
end;
end;
procedure TAMC_SavePak.EnDisOptions(SaveAll: Boolean);
begin
edtSaveAllDirPath.Enabled := SaveAll;
btnBrowse.Enabled := SaveAll;
btnSaveAll.Enabled := SaveAll;
stxXML.Enabled := False;
edtXMLDirPath.Enabled := False;
btnSaveXML.Enabled := False;
if (not SaveAll) and
(PackageData.DataFiles.DataFileHasData(fTypXML26GSE) or
PackageData.DataFiles.DataFileHasData(fTypXML26) or
PackageData.DataFiles.DataFileHasData(fTypXML241)) then
begin
stxXML.Enabled := True;
edtXMLDirPath.Enabled := True;
btnSaveXML.Enabled := True;
end;
stxPDF.Enabled := False;
edtPDFDirPath.Enabled := False;
btnSavePDF.Enabled := False;
if (not SaveAll) and PackageData.DataFiles.DataFileHasData(fTypPDF) then
begin
stxPDF.Enabled := True;
edtPDFDirPath.Enabled := True;
btnSavePDF.Enabled := True;
end;
stxENV.Enabled := False;
edtENVDirPath.Enabled := False;
btnSaveENV.Enabled := False;
if (not SaveAll) and PackageData.DataFiles.DataFileHasData(fTypENV) then
begin
stxENV.Enabled := True;
edtENVDirPath.Enabled := True;
btnSaveENV.Enabled := True;
end;
end;
procedure TAMC_SavePak.cbxUseSameFolderClick(Sender: TObject);
begin
inherited;
EnDisOptions(cbxUseSameFolder.Checked);
if cbxUseSameFolder.Checked then
begin
if (edtSaveAllDirPath.Text <> '') and (DirectoryExists(edtSaveAllDirPath.Text)) then
ResetDirs(edtSaveAllDirPath.Text)
else
edtSaveAllDirPath.Text := 'Same Directory';
end;
end;
procedure TAMC_SavePak.btnBrowseClick(Sender: TObject);
begin
inherited;
SelectFolderDialog.Title := 'Select the Save All folder';
SelectFolderDialog.SelectedPathName := appPref_DirWorkflowSameDirPath;
if SelectFolderDialog.Execute then
ResetDirs(SelectFolderDialog.SelectedPathName);
end;
procedure TAMC_SavePak.btnEmailClick(Sender: TObject);
var
ParamType{,s} : String;
PDFAttachments: TStringList;
begin
inherited;
PDFAttachments := TStringList.Create;
try
if ck_xml.Checked then
PDFAttachments.Add(edtXMLDirPath.Text);
if ck_pdf.Checked then
PDFAttachments.Add(edtPDFDirPath.Text);
if ck_env.Checked then
PDFAttachments.Add(edtENVDirPath.Text);
ParamType := Pchar(PDFAttachments.DelimitedText+';'+'');
ShellExecute(0, nil,PChar(IncludeTrailingPathDelimiter(appPref_DirCommon) +
'\Mail.exe'), PChar(ParamType),nil,SW_HIDE);
finally
PDFAttachments.Free;
end;
end;
procedure TAMC_SavePak.ck_xmlClick(Sender: TObject);
begin
inherited;
btnEmail.Enabled := True;
end;
procedure TAMC_SavePak.ck_pdfClick(Sender: TObject);
begin
inherited;
btnEmail.Enabled := True;
end;
procedure TAMC_SavePak.ck_envClick(Sender: TObject);
begin
inherited;
btnEmail.Enabled := True;
end;
procedure TAMC_SavePak.SaveXMLDataFile(dataFile: TDataFile; filePath: String);
var
xmlDoc: IXMLDOMDocument2;
begin
xmlDoc := CoDomDocument60.Create;
xmlDoc.loadXML(dataFile.FData);
if xmlDoc.parseError.errorCode <> 0 then
raise Exception.Create('Invalid XML string');
xmlDoc.save(filePath);
end;
end.
|
//
// out123.h header binding for the Free Pascal Compiler aka FPC
//
// Binaries and demos available at http://www.djmaster.com/
//
(*
out123: audio output interface
copyright 1995-2016 by the mpg123 project,
free software under the terms of the LGPL 2.1
see COPYING and AUTHORS files in distribution or http://mpg123.org
initially written as audio.h by Michael Hipp, reworked into out123 API
by Thomas Orgis
*)
(** \file out123.h The header file for the libout123 audio output facility. *)
unit out123;
{$mode objfpc}{$H+}
{$inline on}
interface
(* We only need size_t definition. *)
// #include <stddef.h>
(* Common audio encoding specification, including a macro for getting
* size of encodined samples in bytes. Said macro is still hardcoded
* into out123_encsize(). Relying on this one may help an old program
* know sizes of encodings added to fmt123.h later on.
* If you don't care, just use the macro.
*)
// #include <fmt123.h>
uses
sysutils,
fmt123,
ctypes;
type
pppcchar = ^ppcchar;
ppcchar = ^pcchar;
ppcint = ^pcint;
const
LIB_OUT123 = 'libout123-0.dll';
(** A macro to check at compile time which set of API functions to expect.
* This should be incremented at least each time a new symbol is added
* to the header.
*)
const
OUT123_LIB_VERSION = '1.25.13';
OUT123_API_VERSION = 2;
OUT123_LIB_PATCHLEVEL = 2;
// (** Defines needed for MS Visual Studio(tm) DLL builds.
// * Every public function must be prefixed with MPG123_EXPORT. When building
// * the DLL ensure to define BUILD_MPG123_DLL. This makes the function accessible
// * for clients and includes it in the import library which is created together
// * with the DLL. When consuming the DLL ensure to define LINK_MPG123_DLL which
// * imports the functions from the DLL.
// *)
// #ifdef BUILD_MPG123_DLL
// (* The dll exports. *)
// #define MPG123_EXPORT __declspec(dllexport)
// #else
// #ifdef LINK_MPG123_DLL
// (* The exe imports. *)
// #define MPG123_EXPORT __declspec(dllimport)
// #else
// (* Nothing on normal/UNIX builds *)
// #define MPG123_EXPORT
// #endif
// #endif
(** \defgroup out123_api out123 library API
* This is out123, a library focused on continuous playback of audio streams
* via various platform-specific output methods. It glosses over details of
* the native APIs to give an interface close to simply writing data to a
* file. There might be the option to tune details like buffer (period) sizes
* and the number of them on the device side in future, but the focus of the
* library is to ease the use case of just getting that raw audio data out
* there, without interruptions.
*
* The basic idea is to create a handle with out123_new() and open a certain
* output device (using a certain driver module, possibly build-time defaults)
* with out123_open(). Now, you can query the output device for supported
* encodings for given rate and channel count with out123_get_encodings() and
* decide what to use for actually starting playback with out123_start().
*
* Then, you just need to provide (interleaved pcm) data for playback with
* out123_play(), which will block when the device's buffers are full. You get
* your timing from that (instead of callbacks). If your program does the
* production of the audio data just a little bit faster than the playback,
* causing out123_play() to block ever so briefly, you're fine.
*
* You stop playback with out123_stop(), or just close the device and driver
* via out123_close(), or even just decide to drop it all and do out123_del()
* right away when you're done.
*
* There are other functions for specific needs, but the basic idea should be
* covered by the above.
@{
*)
type
(** Typedef shortcut as preferrend name for the handle type. *)
pout123_handle = ^out123_handle;
out123_handle = ^out123_struct;
(** Opaque structure for the libout123 handle. *)
out123_struct = record
end;
type
(** Enumeration of codes for the parameters that it is possible to set/get. *)
out123_parms = clong;
const
OUT123_FLAGS_ = 1; (**< integer, various flags, see enum out123_flags *)
OUT123_PRELOAD = 2; (**< float, fraction of buffer to fill before playback *)
OUT123_GAIN = 3; (**< integer, output device gain (module-specific) *)
OUT123_VERBOSE = 4; (**< integer, verbosity to stderr, >= 0 *)
OUT123_DEVICEBUFFER = 5; (**<
* float, length of device buffer in seconds;
* This might be ignored, might have only a loose relation to actual
* buffer sizes and latency, depending on output driver. Try to tune
* this before opening a device if you want to influcence latency or reduce
* dropouts. Value <= 0 uses some default, usually favouring stable playback
* over low latency. Values above 0.5 are probably too much.
*)
OUT123_PROPFLAGS_ = 6; (**< integer, query driver/device property flags (r/o) *)
OUT123_NAME = 7; (**< string, name of this instance (NULL restores default);
* The value returned by out123_getparam() might be different if the audio
* backend changed it (to be unique among clients, p.ex.).
* TODO: The name provided here is used as prefix in diagnostic messages. *)
OUT123_BINDIR = 8; (**< string, path to a program binary directory to use
* as starting point in the search for the output module directory
* (e.g. ../lib/mpg123 or ./plugins). The environment variable MPG123_MODDIR
* is always tried first and the in-built installation path last.
*)
type
(** Flags to tune out123 behaviour *)
out123_flags = clong;
const
OUT123_HEADPHONES = $01; (**< output to headphones (if supported) *)
OUT123_INTERNAL_SPEAKER = $02; (**< output to speaker (if supported) *)
OUT123_LINE_OUT = $04; (**< output to line out (if supported) *)
OUT123_QUIET = $08; (**< no printouts to standard error *)
OUT123_KEEP_PLAYING = $10; (**<
* When this is set (default), playback continues in a loop when the device
* does not consume all given data at once. This happens when encountering
* signals (like SIGSTOP, SIGCONT) that cause interruption of the underlying
* functions.
* Note that this flag is meaningless when the optional buffer is employed,
* There, your program will always block until the buffer completely took
* over the data given to it via out123_play(), unless a communication error
* arises.
*)
type
(** Read-only output driver/device property flags (OUT123_PROPFLAGS). *)
out123_propflags = clong;
const
OUT123_PROP_LIVE = $01; (**< This is a live output, meaning that
* special care might be needed for pauses in playback (p.ex. stream
* of silence instead of interruption), as opposed to files on disk.
*)
OUT123_PROP_PERSISTENT = $02; (**< This (live) output does not need
* special care for pauses (continues with silence itself),
* out123_pause() does nothing to the device.
*)
(** Create a new output handle.
* This only allocates and initializes memory, so the only possible
* error condition is running out of memory.
* \return pointer to new handle or NULL on error
*)
function out123_new(): pout123_handle; cdecl; external LIB_OUT123;
(** Delete output handle.
* This implies out123_close().
*)
procedure out123_del(ao: pout123_handle); cdecl; external LIB_OUT123;
type
(** Error code enumeration
* API calls return a useful (positve) value or zero (OUT123_OK) on simple
* success. A negative value (-1 == OUT123_ERR) usually indicates that some
* error occured. Which one, that can be queried using out123_errcode()
* and friends.
*)
out123_error = clong;
const
OUT123_ERR = -1; (**< generic alias for verbosity, always == -1 *)
OUT123_OK = 0; (**< just a name for zero, not going to change *)
OUT123_DOOM = 1; (**< dazzled, out of memory *)
OUT123_BAD_DRIVER_NAME = 2; (**< bad driver name given *)
OUT123_BAD_DRIVER = 3; (**< unspecified issue loading a driver *)
OUT123_NO_DRIVER = 4; (**< no driver loaded *)
OUT123_NOT_LIVE = 5; (**< no active audio device *)
OUT123_DEV_PLAY = 6; (**< some device playback error *)
OUT123_DEV_OPEN = 7; (**< error opening device *)
OUT123_BUFFER_ERROR = 8; (**<
* Some (really unexpected) error in buffer infrastructure.
*)
OUT123_MODULE_ERROR = 9; (**< basic failure in module loading *)
OUT123_ARG_ERROR = 10; (**< some bad function arguments supplied *)
OUT123_BAD_PARAM = 11; (**< unknown parameter code *)
OUT123_SET_RO_PARAM = 12; (**< attempt to set read-only parameter *)
OUT123_BAD_HANDLE = 13; (**< bad handle pointer (NULL, usually) *)
OUT123_ERRCOUNT = 14; (**< placeholder for shaping arrays *)
(** Get string representation of last encountered error in the
* context of given handle.
* \param ao handle
* \return error string
*)
function out123_strerror(ao: pout123_handle): pchar; cdecl; external LIB_OUT123;
(** Get the plain errcode intead of a string.
* Note that this used to return OUT123_ERR instead of
* OUT123_BAD_HANDLE in case of ao==NULL before mpg123-1.23.5 .
* \param ao handle
* \return error code recorded in handle or OUT123_BAD_HANDLE
*)
function out123_errcode(ao: pout123_handle): cint; cdecl; external LIB_OUT123;
(** Return the error string for a given error code.
* \param errcode the integer error code
* \return error string
*)
function out123_plain_strerror(errcode: cint): pchar; cdecl; external LIB_OUT123;
(** Set a desired output buffer size.
* This starts a separate process that handles the audio output, decoupling
* the latter from the main process with a memory buffer and saving you the
* burden to ensure sparing CPU cycles for actual playback.
* This is for applicatons that prefer continuous playback over small latency.
* In other words: The kind of applications that out123 is designed for.
* This routine always kills off any currently active audio output module /
* device, even if you just disable the buffer when there is no buffer.
*
* Keep this in mind for memory-constrainted systems: Activating the
* buffer causes a fork of the calling process, doubling the virtual memory
* use. Depending on your operating system kernel's behaviour regarding
* memory overcommit, it might be wise to call out123_set_buffer() very
* early in your program before allocating lots of memory.
*
* There _might_ be a change to threads in future, but for now this is
* classic fork with shared memory, working without any threading library.
* If your platform or build does not support that, you will always get an
* error on trying to set up a non-zero buffer (but the API call will be
* present).
*
* Also, if you do intend to use this from a multithreaded program, think
* twice and make sure that your setup is happy with forking full-blown
* processes off threaded programs. Probably you are better off spawning a
* buffer thread yourself.
*
* \param ao handle
* \param buffer_bytes size (bytes) of a memory buffer for decoded audio,
* a value of zero disables the buffer.
* \return 0 on success, OUT123_ERR on error
*)
function out123_set_buffer(ao: pout123_handle; buffer_bytes: size_t): cint; cdecl; external LIB_OUT123;
(** Set a specific parameter, for a specific out123_handle, using a parameter
* code chosen from the out123_parms enumeration, to the specified value.
* The parameters usually only change what happens on next out123_open, not
* incfluencing running operation.
* \param ao handle
* \param code parameter code
* \param value input value for integer parameters
* \param fvalue input value for floating point parameters
* \param svalue input value for string parameters (contens are copied)
* \return 0 on success, OUT123_ERR on error.
*)
function out123_param(ao: pout123_handle; code: out123_parms; value: clong; fvalue: cdouble; const svalue: pchar): cint; cdecl; external LIB_OUT123;
function out123_param_int(ao: pout123_handle; code: out123_parms; value: clong): cint; cdecl; inline;
function out123_param_float(ao: pout123_handle; code: out123_parms; value: cdouble): cint; cdecl; inline;
function out123_param_string(ao: pout123_handle; code: out123_parms; value: pchar): cint; cdecl; inline;
(** Get a specific parameter, for a specific out123_handle, using a parameter
* code chosen from the out123_parms enumeration, to the specified value.
* \param ao handle
* \param code parameter code
* \param ret_value output address for integer parameters
* \param ret_fvalue output address for floating point parameters
* \param ret_svalue output address for string parameters (pointer to
* internal memory, so no messing around, please)
* \return 0 on success, OUT123_ERR on error (bad parameter name or bad handle).
*)
function out123_getparam(ao: pout123_handle; code: out123_parms; ret_value: pclong; ret_fvalue: pcdouble; ret_svalue: ppchar): cint; cdecl; external LIB_OUT123;
function out123_getparam_int(ao: pout123_handle; code: out123_parms; value: pclong): cint; cdecl; inline;
function out123_getparam_float(ao: pout123_handle; code: out123_parms; value: pcdouble): cint; cdecl; inline;
function out123_getparam_string(ao: pout123_handle; code: out123_parms; value: ppchar): cint; cdecl; inline;
(** Copy parameters from another out123_handle.
* \param ao handle
* \param from_ao the handle to copy parameters from
* \return 0 in success, -1 on error
*)
function out123_param_from(ao: pout123_handle; from_ao: pout123_handle): cint; cdecl; external LIB_OUT123;
(** Get list of driver modules reachable in system in C argv-style format.
* The client is responsible for freeing the memory of both the individual
* strings and the lists themselves.
* A module that is not loadable because of missing libraries is simply
* skipped. You will get stderr messages about that unless OUT123_QUIET was
* was set, though. Failure to open the module directory is a serious error,
* resulting in negative return value.
* \param ao handle
* \param names address for storing list of names
* \param descr address for storing list of descriptions
* \return number of drivers found, -1 on error
*)
function out123_drivers(ao: pout123_handle; names: pppchar; descr: pppchar): cint; cdecl; external LIB_OUT123;
(** Open an output device with a certain driver
* Note: Opening means that the driver code is loaded and the desired
* device name recorded, possibly tested for availability or tentatively
* opened. After out123_open(), you can ask for supported encodings
* and then really open the device for playback with out123_start().
* \param ao handle
* \param driver (comma-separated list of) output driver name(s to try),
* NULL for default (stdout for file-based drivers)
* \param device device name to open, NULL for default
* \return 0 on success, -1 on error.
*)
function out123_open(ao: pout123_handle; const driver: pchar; const device: pchar): cint; cdecl; external LIB_OUT123;
(** Give info about currently loaded driver and device
* Any of the return addresses can be NULL if you are not interested in
* everything. You get pointers to internal storage. They are valid
* as long as the driver/device combination is opened.
* The device may be NULL indicating some unnamed default.
* TODO: Make the driver modules return names for such defaults.
* \param ao handle
* \param driver return address for driver name
* \param device return address for device name
* \return 0 on success, -1 on error (i.e. no driver loaded)
*)
function out123_driver_info(ao: pout123_handle; driver: ppchar; device: ppchar): cint; cdecl; external LIB_OUT123;
(** Close the current output device and driver.
* This implies out123_drain() to ensure no data is lost.
* With a buffer, that might cause considerable delay during
* which your main application is blocked waiting.
* Call out123_drop() beforehand if you want to end things
* quickly.
* \param ao handle
*)
procedure out123_close(ao: pout123_handle); cdecl; external LIB_OUT123;
(** Get supported audio encodings for given rate and channel count,
* for the currently openend audio device.
* TODO: Reopening the underlying audio device for each query
* is dumb, at least when dealing with JACK. It takes
* a long time and is just a waste. Reconsider that.
* Make sure that all output modules are fine with it, though!
* Usually, a wider range of rates is supported, but the number
* of sample encodings is limited, as is the number of channels.
* So you can call this with some standard rate and hope that the
* returned encodings work also for others, with the tested channel
* count.
* The return value of -1 on some encountered error conveniently also
* does not match any defined format (only 15 bits used for encodings,
* so this would even work with 16 bit integers).
* This implies out123_stop() to enter query mode.
* \param ao handle
* \param rate sampling rate
* \param channels number of channels
* \return supported encodings combined with bitwise or, to be checked
* against your favourite bitmask, -1 on error
*)
function out123_encodings(ao: pout123_handle; rate: clong; channels: cint): cint; cdecl; external LIB_OUT123;
(** Return the size (in bytes) of one mono sample of the named encoding.
* \param encoding The encoding value to analyze.
* \return positive size of encoding in bytes, 0 on invalid encoding. *)
function out123_encsize(encoding: cint): cint; cdecl; external LIB_OUT123;
(** Get list of supported formats for currently opened audio device.
* Given a list of sampling rates and minimal/maximal channel count,
* this quickly checks what formats are supported with these
* constraints. The first entry is always reserved for a default
* format for the output device. If there is no such default,
* all values of the format are -1.
* For each requested combination of rate and channels, a format entry is
* created, possible with encoding value 0 to indicate that this combination
* has been tested and rejected. So, when there is no basic error, the
* number of returned format entries should be
* (ratecount*(maxchannels-minchannels+1)+1)
* . But instead of forcing you to guess, this will be allocated by
* successful run.
* For the first entry, the encoding member is supposed to be a definite
* encoding, for the others it is a bitwise combination of all possible
* encodings.
* This function is more efficient than many calls to out123_encodings().
* \param ao handle
* \param rates pointer to an array of sampling rates, may be NULL for none
* \param ratecount number of provided sampling rates
* \param minchannels minimal channel count
* \param maxchannels maximal channel count
* \param fmtlist return address for array of supported formats
* the encoding field of each entry is a combination of all
* supported encodings at this rate and channel count;
* Memory shall be freed by user.
* \return number of returned format enries, -1 on error
*)
function out123_formats(ao: pout123_handle; const rates: pclong; ratecount: cint; minchannels: cint; maxchannels: cint; fmtlist: ppmpg123_fmt): cint; cdecl; external LIB_OUT123;
(** Get list of encodings known to the library.
* You are responsible for freeing the allocated array.
* \param enclist return address for allocated array of encoding codes
* \return number of encodings, -1 on error
*)
function out123_enc_list(enclist: ppcint): cint; cdecl; external LIB_OUT123;
(** Find encoding code by name.
* \param name short or long name to find encoding code for
* \return encoding if found (enum mpg123_enc_enum), else 0
*)
function out123_enc_byname(const name: pchar): cint; cdecl; external LIB_OUT123;
(** Get name of encoding.
* \param encoding code (enum mpg123_enc_enum)
* \return short name for valid encodings, NULL otherwise
*)
function out123_enc_name(encoding: cint): pchar; cdecl; external LIB_OUT123;
(** Get long name of encoding.
* \param encoding code (enum mpg123_enc_enum)
* \return long name for valid encodings, NULL otherwise
*)
function out123_enc_longname(encoding: cint): pchar; cdecl; external LIB_OUT123;
(** Start playback with a certain output format
* It might be a good idea to have audio data handy to feed after this
* returns with success.
* Rationale for not taking a pointer to struct mpg123_fmt: This would
* always force you to deal with that type and needlessly enlarge the
* shortest possible program.
* \param ao handle
* \param encoding sample encoding (values matching libmpg123 API)
* \param channels number of channels (1 or 2, usually)
* \param rate sampling rate
* \return 0 on success, negative on error (bad format, usually)
*)
function out123_start(ao: pout123_handle; rate: clong; channels: cint; encoding: cint): cint; cdecl; external LIB_OUT123;
(** Pause playback
* Interrupt playback, holding any data in the optional buffer.
*
* This closes the audio device if it is a live sink, ready to be re-opened
* by out123_continue() or out123_play() with the existing parameters.
* \param ao handle
*)
procedure out123_pause(ao: pout123_handle); cdecl; external LIB_OUT123;
(** Continue playback
* The counterpart to out123_pause(). Announce to the driver that playback
* shall continue.
*
* Playback might not resume immediately if the optional buffer is configured
* to wait for a minimum fill and close to being empty. You can force playback
* of the last scrap with out123_drain(), or just by feeding more data with
* out123_play(), which will trigger out123_continue() for you, too.
* \param ao handle
*)
procedure out123_continue(ao: pout123_handle); cdecl; external LIB_OUT123;
(** Stop playback.
* This waits for pending audio data to drain to the speakers.
* You might want to call out123_drop() before stopping if you want
* to end things right away.
* \param ao handle
*)
procedure out123_stop(ao: pout123_handle); cdecl; external LIB_OUT123;
(** Hand over data for playback and wait in case audio device is busy.
* This survives non-fatal signals like SIGSTOP/SIGCONT and keeps on
* playing until the buffer is done with if the flag
* OUT123_KEEP_PLAYING ist set (default). So, per default, if
* you provided a byte count divisible by the PCM frame size, it is an
* error when less bytes than given are played.
* To be sure if an error occured, check out123_errcode().
* Also note that it is no accident that the buffer parameter is not marked
* as constant. Some output drivers might need to do things like swap
* byte order. This is done in-place instead of wasting memory on yet
* another copy.
* \param ao handle
* \param buffer pointer to raw audio data to be played
* \param bytes number of bytes to read from the buffer
* \return number of bytes played (might be less than given, even zero)
*)
function out123_play(ao: pout123_handle; buffer: pointer; bytes: size_t): size_t; cdecl; external LIB_OUT123;
(** Drop any buffered data, making next provided data play right away.
* This does not imply an actual pause in playback.
* You are expected to play something, unless you called out123_pause().
* Feel free to call out123_stop() afterwards instead for a quicker
* exit than the implied out123_drain().
* For live sinks, this may include dropping data from their buffers.
* For others (files), this only concerns data in the optional buffer.
* \param ao handle
*)
procedure out123_drop(ao: pout123_handle); cdecl; external LIB_OUT123;
(** Drain the output, waiting until all data went to the hardware.
* This does imply out123_continue() before and out123_pause()
* after draining.
* This might involve only the optional buffer process, or the
* buffers on the audio driver side, too.
* \param ao handle
*)
procedure out123_drain(ao: pout123_handle); cdecl; external LIB_OUT123;
(** Drain the output, but only partially up to the given number of
* bytes. This gives you the opportunity to do something while
* the optional buffer is writing remaining data instead of having
* one atomic API call for it all.
*
* It is wholly expected that the return value of out123_buffered()
* before and after calling this has a bigger difference than the
* provided limit, as the buffer is writing all the time in the
* background.
*
* This is just a plain out123_drain() if the optional buffer is not
* in use. Also triggers out123_continue(), but only out123_pause()
* if there is no buffered data anymore.
* \param ao handle
* \param bytes limit of buffered bytes to drain
* \return number of bytes drained from buffer
*)
procedure out123_ndrain(ao: pout123_handle; bytes: size_t); cdecl; external LIB_OUT123;
(** Get an indication of how many bytes reside in the optional buffer.
* This might get extended to tell the number of bytes queued up in the
* audio backend, too.
* \param ao handle
* \return number of bytes in out123 library buffer
*)
function out123_buffered(ao: pout123_handle): size_t; cdecl; external LIB_OUT123;
(** Extract currently used audio format from handle.
* matching mpg123_getformat().
* Given return addresses may be NULL to indicate no interest.
* \param ao handle
* \param rate address for sample rate
* \param channels address for channel count
* \param encoding address for encoding
* \param framesize size of a full PCM frame (for convenience)
* \return 0 on success, -1 on error
*)
function out123_getformat(ao: pout123_handle; rate: pclong; channels: pcint; encoding: pcint; framesize: pcint): cint; cdecl; external LIB_OUT123;
(* @} *)
implementation
function out123_param_int(ao: pout123_handle; code: out123_parms; value: clong): cint; cdecl; inline;
begin
Result := out123_param(ao, code, value, 0.0, nil);
end;
function out123_param_float(ao: pout123_handle; code: out123_parms; value: cdouble): cint; cdecl; inline;
begin
Result := out123_param(ao, code, 0, value, nil);
end;
function out123_param_string(ao: pout123_handle; code: out123_parms; value: pchar): cint; cdecl; inline;
begin
Result := out123_param(ao, code, 0, 0.0, value);
end;
function out123_getparam_int(ao: pout123_handle; code: out123_parms; value: pclong): cint; cdecl; inline;
begin
Result := out123_getparam(ao, code, value, nil, nil);
end;
function out123_getparam_float(ao: pout123_handle; code: out123_parms; value: pcdouble): cint; cdecl; inline;
begin
Result := out123_getparam(ao, code, nil, value, nil);
end;
function out123_getparam_string(ao: pout123_handle; code: out123_parms; value: ppchar): cint; cdecl; inline;
begin
Result := out123_getparam(ao, code, nil, nil, value);
end;
end.
|
{
Description: vPlot paths class.
Copyright (C) 2017-2018 Melchiorre Caruso <melchiorrecaruso@gmail.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., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
}
unit vppaths;
{$mode objfpc}
interface
uses
classes, vpmath, vpsetting;
type
tvpentity = class(tobject)
private
flist: tfplist;
function getcount: longint;
function get(index: longint): pvppoint;
public
constructor create;
destructor destroy; override;
procedure add(p: pvppoint);
procedure delete(index: longint);
procedure clear;
procedure invert;
function first: pvppoint;
function last: pvppoint;
public
property items[index: longint]: pvppoint read get;
property count: longint read getcount;
end;
tvppath = class(tobject)
private
flist: tfplist;
fenabled: boolean;
function getcount: longint;
function get(index: longint): tvpentity;
public
constructor create;
destructor destroy; override;
procedure add(entity: tvpentity);
procedure delete(index: longint);
procedure clear;
procedure reorder;
public
property enabled: boolean read fenabled write fenabled;
property items[index: longint]: tvpentity read get;
property count: longint read getcount;
end;
tvppaths = class(tobject)
private
flist: tfplist;
fpathnames: tstringlist;
function getcount: longint;
function get(index: longint): tvppath;
function getname(index: longint): string;
public
constructor create;
destructor destroy; override;
procedure addline (entity: pvpline; const pathname: string);
procedure addcircle (entity: pvpcircle; const pathname: string);
procedure addcirclearc(entity: pvpcirclearc; const pathname: string);
procedure addellipse (entity: pvpellipse; const pathname: string);
procedure delete(index: longint);
procedure clear;
procedure createtoolpath;
procedure zerocenter;
public
property items[index: longint]: tvppath read get;
property itemname[index: longint]: string read getname;
property count: longint read getcount;
end;
procedure dxf2paths(const afilename: string; apaths: tvppaths);
implementation
uses
math, sysutils, vpdxfreader;
// internal toolpath routines
function interpolate_line(entity: pvpline): tvpentity;
var
dx, dy: double;
i, j: longint;
p: tvppoint;
begin
j := max(1, round(len_segment(entity)/(1.2/setting.mode)));
dx := (entity^.p1.x - entity^.p0.x)/j;
dy := (entity^.p1.y - entity^.p0.y)/j;
result := tvpentity.create;
for i := 0 to j do
begin
p.x := i * dx;
p.y := i * dy;
p := translate_point(entity^.p0, p);
result.add(@p);
end;
end;
function interpolate_circle(entity: pvpcircle): tvpentity;
var
i, j: longint;
p: tvppoint;
start: tvppoint;
sweep: double;
begin
start.x := entity^.radius;
start.y := 0.0;
sweep := 2 * pi;
j := max(1, round((abs(sweep)*entity^.radius)/(1.2/setting.mode)));
result := tvpentity.create;
for i := 0 to j do
begin
p := rotate_point(start, (i * (sweep / j)));
p := translate_point(entity^.center, p);
result.add(@p);
end;
end;
function interpolate_circlearc(entity: pvpcirclearc): tvpentity;
var
i, j: longint;
p: tvppoint;
start: tvppoint;
sweep: double;
begin
start.x := entity^.radius;
start.y := 0.0;
start := rotate_point(start, degtorad(entity^.startangle));
sweep := degtorad(entity^.endangle - entity^.startangle);
j := max(1, round(abs(sweep)*entity^.radius/(1.2/setting.mode)));
result := tvpentity.create;
for i := 0 to j do
begin
p := rotate_point(start, (i * (sweep / j)));
p := translate_point(entity^.center, p);
result.add(@p);
end;
end;
function interpolate_elipse(entity: pvpellipse): tvpentity;
begin
// ...
end;
// internal commont routines
function distance_between_two_position(p0, p1: pvppoint): double;
begin
result := sqrt(sqr(p1^.x - p0^.x) + sqr(p1^.y - p0^.y));
end;
function compare_position(p0, p1: pvppoint): boolean;
begin
result := distance_between_two_position(p0, p1) < 0.001;
end;
function get_next(p0: pvppoint; list: tfplist): longint;
var
i: longint;
begin
result := -1;
for i := 0 to list.count - 1 do
if compare_position(p0, tvpentity(list[i]).first) or
compare_position(p0, tvpentity(list[i]).last ) then
begin
result := i;
exit;
end;
end;
function get_near(p0: pvppoint; list: tfplist): longint;
var
i: longint;
len1: double = $FFFFFFF;
len2: double = $FFFFFFF;
begin
result := 0;
for i := 0 to list.count - 1 do
begin
len2 := distance_between_two_position(p0, tvpentity(list[i]).first);
if len1 > len2 then
begin
len1 := len2;
result := i;
end;
len2 := distance_between_two_position(p0, tvpentity(list[i]).last);
if len1 > len2 then
begin
tvpentity(list[i]).invert;
len1 := len2;
result := i;
end;
end;
end;
function is_closed(entity: tvpentity): boolean;
begin
result := true;
if entity.count > 1 then
begin
result := compare_position(entity.get(0), entity.get(entity.count-1));
end;
end;
// tvpentity
constructor tvpentity.create;
begin
inherited create;
flist := tfplist.create;
end;
destructor tvpentity.destroy;
begin
clear;
flist.destroy;
inherited destroy;
end;
procedure tvpentity.delete(index: longint);
begin
dispose(pvppoint(flist[index]));
flist.delete(index);
end;
procedure tvpentity.clear;
var
i: longint;
begin
for i := 0 to flist.count - 1 do
begin
dispose(pvppoint(flist[i]));
end;
flist.clear;
end;
procedure tvpentity.add(p: pvppoint);
var
point: pvppoint;
begin
new(point);
point^.x := p^.x;
point^.y := p^.y;
point^.z := p^.z;
flist.add(point);
end;
procedure tvpentity.invert;
var
i: longint;
tmp: tlist;
begin
tmp := tlist.create;
for i := flist.count - 1 downto 0 do tmp.add(flist[i]);
for i := flist.count - 1 downto 0 do flist[i] := tmp[i];
tmp.destroy;
end;
function tvpentity.first: pvppoint;
begin
result := pvppoint(flist[0]);
end;
function tvpentity.last: pvppoint;
begin
result := pvppoint(flist[flist.count-1]);
end;
function tvpentity.get(index: longint): pvppoint;
begin
result := pvppoint(flist[index]);
end;
function tvpentity.getcount: longint;
begin
result := flist.count;
end;
// tvppath
constructor tvppath.create;
begin
inherited create;
flist := tfplist.create;
fenabled := true;
end;
destructor tvppath.destroy;
begin
clear;
flist.destroy;
inherited destroy;
end;
procedure tvppath.delete(index: longint);
begin
tvpentity(flist[index]).destroy;
flist.delete(index);
end;
procedure tvppath.clear;
var
i: longint;
begin
for i := 0 to flist.count - 1 do
begin
tvpentity(flist[i]).destroy;
end;
flist.clear;
end;
procedure tvppath.reorder;
var
i: longint;
entity: tvpentity;
point: pvppoint = nil;
list1: tfplist;
list2: tfplist;
begin
list1 := tfplist.create;
list2 := tfplist.create;
// move all path to list1
while flist.count > 0 do
begin
list1.add(flist[0]);
flist.delete(0);
end;
// create toolpath
while list1.count > 0 do
begin
if point = nil then
i := 0
else
i := get_near(point, list1);
list2.add(list1[i]);
list1.delete(i);
if not is_closed(tvpentity(list2[0])) then
begin
entity := tvpentity(list2[0]);
repeat
i := get_next(entity.last, list1);
if i <> -1 then
begin
if compare_position(entity.last,
tvpentity(list1[i]).last) then
tvpentity(list1[i]).invert;
entity := tvpentity(list1[i]);
list2.add(entity);
list1.delete(i);
end;
until i = -1;
entity := tvpentity(list2[0]);
repeat
i := get_next(entity.first, list1);
if i <> -1 then
begin
if compare_position(entity.first,
tvpentity(list1[i]).first) then
tvpentity(list1[i]).invert;
entity := tvpentity(list1[i]);
list2.insert(0, entity);
list1.delete(i);
end;
until i = -1;
end;
// move toolpath
point := tvpentity(list2[list2.count-1]).last;
while list2.count > 0 do
begin
flist.add(tvppath(list2[0]));
list2.delete(0);
end;
end;
list2.destroy;
list1.destroy;
end;
procedure tvppath.add(entity: tvpentity);
begin
flist.add(entity);
end;
function tvppath.getcount: longint;
begin
result := flist.count;
end;
function tvppath.get(index: longint): tvpentity;
begin
result := tvpentity(flist[index]);
end;
// tvppaths
constructor tvppaths.create;
begin
inherited create;
flist := tfplist.create;
fpathnames := tstringlist.create;
end;
destructor tvppaths.destroy;
begin
clear;
flist.destroy;
fpathnames.destroy;
inherited destroy;
end;
procedure tvppaths.delete(index: longint);
begin
tvppath(flist[index]).destroy;
flist.delete(index);
fpathnames.delete(index);
end;
procedure tvppaths.clear;
var
i: longint;
begin
for i := 0 to flist.count - 1 do
begin
tvppath(flist[i]).destroy;
end;
flist.clear;
fpathnames.clear;
end;
procedure tvppaths.addline(entity: pvpline; const pathname: string);
var
i: longint;
begin
i := fpathnames.indexof(pathname);
if i = -1 then
begin
i :=
flist .add(tvppath.create);
fpathnames.add(pathname);
end;
tvppath(flist[i]).add(interpolate_line(entity));
end;
procedure tvppaths.addcircle(entity: pvpcircle; const pathname: string);
var
i: longint;
begin
i := fpathnames.indexof(pathname);
if i = -1 then
begin
i :=
flist .add(tvppath.create);
fpathnames.add(pathname);
end;
tvppath(flist[i]).add(interpolate_circle(entity));
end;
procedure tvppaths.addcirclearc(entity: pvpcirclearc; const pathname: string);
var
i: longint;
begin
i := fpathnames.indexof(pathname);
if i = -1 then
begin
i :=
flist .add(tvppath.create);
fpathnames.add(pathname);
end;
tvppath(flist[i]).add(interpolate_circlearc(entity));
end;
procedure tvppaths.addellipse(entity: pvpellipse; const pathname: string);
begin
// ...
end;
procedure tvppaths.zerocenter;
var
i, j, k: longint;
xmin: double;
xmax: double;
ymin: double;
ymax: double;
offsetx: double;
offsety: double;
entity: tvpentity;
path: tvppath;
point: pvppoint;
begin
xmin := + maxint;
xmax := - maxint;
ymin := + maxint;
ymax := - maxint;
for i := 0 to flist.count - 1 do
begin
path := tvppath(flist[i]);
for j := 0 to path.count - 1 do
begin
entity := path.items[j];
for k := 0 to entity.count - 1 do
begin
point := entity.items[k];
xmin := min(xmin, point^.x);
xmax := max(xmax, point^.x);
ymin := min(ymin, point^.y);
ymax := max(ymax, point^.y);
end;
end;
end;
offsetx := - (xmin + xmax) / 2;
offsety := - (ymin + ymax) / 2;
for i := 0 to flist.count - 1 do
begin
path := tvppath(flist[i]);
for j := 0 to path.count - 1 do
begin
entity := path.items[j];
for k := 0 to entity.count - 1 do
begin
point := entity.items[k];
point^.x := point^.x + offsetx;
point^.y := point^.y + offsety;
end;
end;
end;
end;
procedure tvppaths.createtoolpath;
var
i: longint;
begin
for i := 0 to flist.count - 1 do
get(i).reorder;
end;
function tvppaths.getcount: longint;
begin
result := flist.count;
end;
function tvppaths.get(index: longint): tvppath;
begin
result := tvppath(flist[index]);
end;
function tvppaths.getname(index: longint): string;
begin
result := fpathnames[index];
end;
// dxf2paths
procedure dxf2paths(const afilename: string; apaths: tvppaths);
var
reader: tvdxfreader;
begin
reader := tvdxfreader.create;
reader.readfromfile(afilename, apaths);
reader.destroy;
apaths.zerocenter;
apaths.createtoolpath;
end;
end.
|
{******************************************************************************}
{ }
{ ReportBuilder Report Component Library }
{ }
{ Copyright (c) 1996-1998 Digital Metaphors Corporation }
{ }
{******************************************************************************}
Unit XPrevDlg;
Interface
Uses
{$IFDEF WIN32}
Windows, ComCtrls,
{$ELSE}
WinTypes, WinProcs,
{$ENDIF}
SysUtils, Messages, Classes, Graphics, Controls, Forms, ExtCtrls, StdCtrls, Mask, Buttons,
ppForms, ppTypes, ppProd, ppDevice, ppViewr, Dialogs;
type
TXPrintPreview = class(TppCustomPreviewer)
pnlPreviewBar: TPanel;
spbPreviewPrint: TSpeedButton;
spbPreviewWhole: TSpeedButton;
spbPreviewFirst: TSpeedButton;
spbPreviewPrior: TSpeedButton;
spbPreviewNext: TSpeedButton;
spbPreviewLast: TSpeedButton;
mskPreviewPage: TMaskEdit;
spbPreviewWidth: TSpeedButton;
spbPreview100Percent: TSpeedButton;
spbPreviewClose: TSpeedButton;
Bevel1: TBevel;
ppViewer1: TppViewer;
mskPreviewPercentage: TMaskEdit;
procedure spbPreviewPrintClick(Sender: TObject);
procedure spbPreviewWholeClick(Sender: TObject);
procedure spbPreviewFirstClick(Sender: TObject);
procedure spbPreviewPriorClick(Sender: TObject);
procedure spbPreviewNextClick(Sender: TObject);
procedure spbPreviewLastClick(Sender: TObject);
procedure mskPreviewPageKeyPress(Sender: TObject; var Key: Char);
procedure ppViewerPageChange(Sender: TObject);
procedure ppViewerStatusChange(Sender: TObject);
procedure spbPreviewWidthClick(Sender: TObject);
procedure spbPreview100PercentClick(Sender: TObject);
procedure spbPreviewCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure mskPreviewPercentageKeyPress(Sender: TObject; var Key: Char);
procedure ppViewer1PrintStateChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure pnlPreviewBarClick(Sender: TObject);
private
FStatusBar: TStatusBar;
protected
{overriden from TppForm}
procedure Activate; override;
procedure LanguageChanged; override;
procedure ReportAssigned; override;
function GetViewer: TObject; override;
public
end;
{ TXPrintPreview }
var XPrintPreview: TXPrintPreview;
Implementation
{$R *.DFM}
Uses XReports;
{ TppPrintPreview }
Procedure TXPrintPreview.FormCreate(Sender: TObject);
begin
FStatusBar := TStatusBar.Create(Self);
FStatusBar.Parent := Self;
FStatusBar.SimplePanel := True;
FStatusBar.Align := alBottom;
WindowState := wsMaximized;
TppViewer(Viewer).ZoomSetting :=zsPageWidth;
if (Owner is TXDBReport) and Assigned(TXDBReport(Owner).PrintLink) then
with TXDBReport(Owner).PrintLink do begin
if ZoomView>0 then begin
{ TppViewer(Viewer).ZoomSetting :=zsPercentage;}
ppViewer1.ZoomPercentage := ZoomView;
end;
end;
end;
Procedure TXPrintPreview.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
Procedure TXPrintPreview.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key=VK_ESCAPE then spbPreviewCloseClick(Sender);
with ppViewer1 do
if not(ssCtrl in Shift) then begin
if Assigned(ppViewer1.ScrollBox.VertScrollBar) then
with ScrollBox.VertScrollBar do
case Key of
{ Вниз }
VK_Down: Position:=Position+7;
VK_Next: NextPage;
VK_End: Position:=Range;
{ Вверх }
VK_Up: Position:=Position-7;
VK_Prior: PriorPage;
VK_Home: Position:=0;
end;
if Assigned(ppViewer1.ScrollBox.HorzScrollBar) then
with ScrollBox.HorzScrollBar do
case Key of
{ Вправо }
VK_Right: Position:=Position+7;
{ Влево }
VK_Left: Position:=Position-7;
end;
end else
case Key of
VK_Down:
with ScrollBox.VertScrollBar do begin
if Position<Range-ScrollBox.ClientHeight then begin
{ScrollBox.Hide;}
{ScrollBox.AutoScroll:=false;}
{ScrollBox.VertScrollBar.Visible:=false;}
{ScrollBox.ScrollBy(0,-ClientHeight);}
{ScrollBox.VertScrollBar.Visible:=true;}
Position:=Position+ScrollBox.ClientHeight;
{SetScrollPos(ScrollBox.Handle,SB_VERT,Position+ClientHeight,True);}
{ScrollBox.Invalidate;}
end else begin
NextPage;
Position:=0;
end;
end;
VK_Up:
with ScrollBox.VertScrollBar do begin
if Position>0 then Position:=Position-ScrollBox.ClientHeight
else
if AbsolutePageNo>1 then begin
PriorPage;
Position:=Range-ScrollBox.ClientHeight;
end;
end;
VK_Left: ScrollBox.HorzScrollBar.Position:=
ScrollBox.HorzScrollBar.Position-ScrollBox.ClientWidth;
VK_Right:ScrollBox.HorzScrollBar.Position:=
ScrollBox.HorzScrollBar.Position+ScrollBox.ClientWidth;
VK_Home: FirstPage;
VK_End: LastPage;
end;
end;
Procedure TXPrintPreview.ReportAssigned;
begin
if Report is TppProducer then ppViewer1.Report := TppProducer(Report);
end;
Procedure TXPrintPreview.Activate;
begin
Inherited Activate;
spbPreviewWhole.Down:=(ppViewer1.ZoomSetting=zsWholePage);
spbPreviewWidth.Down:=(ppViewer1.ZoomSetting=zsPageWidth);
spbPreview100Percent.Down := (ppViewer1.ZoomSetting=zs100Percent);
end;
{ Разобраться попозже с языком }
Procedure TXPrintPreview.LanguageChanged;
var lBitMap: TBitMap;
begin
{
spbPreviewPrint.Hint:=LoadStr(LanguageIndex + ppMsgPrint);
spbPreviewWhole.Hint:=LoadStr(LanguageIndex + ppMsgWhole);
spbPreviewWidth.Hint:=LoadStr(LanguageIndex + ppMsgPageWidth);
spbPreview100Percent.Hint:=LoadStr(LanguageIndex + ppMsg100Percent);
spbPreviewFirst.Hint:=LoadStr(LanguageIndex + ppMsgFirst);
spbPreviewPrior.Hint:=LoadStr(LanguageIndex + ppMsgPrior);
spbPreviewNext.Hint:=LoadStr(LanguageIndex + ppMsgNext);
spbPreviewLast.Hint:=LoadStr(LanguageIndex + ppMsgLast);
}
{spbPreviewClose.Caption:=LoadStr(LanguageIndex + ppMsgClose);}
spbPreviewClose.Caption:='Закрыть';
{
lBitMap:=TBitMap.Create;
spbPreviewClose.Width:=lBitMap.Canvas.TextWidth(spbPreviewClose.Caption) + 30;
lBitMap.Free;
Caption:=LoadStr(LanguageIndex + ppMsgPrintPreview);
}
end;
Function TXPrintPreview.GetViewer: TObject;
begin
Result := ppViewer1;
end;
Procedure TXPrintPreview.ppViewer1PrintStateChange(Sender: TObject);
var lPosition: TPoint;
begin
if ppViewer1.Busy then begin
mskPreviewPercentage.Enabled:=False;
mskPreviewPage.Enabled:=False;
pnlPreviewBar.Cursor:=crHourGlass;
ppViewer1.PaintBox.Cursor:=crHourGlass;
FStatusbar.Cursor := crHourGlass;
spbPreviewClose.Cursor := crArrow;
spbPreviewClose.Caption := LoadStr(LanguageIndex + ppMsgCancel);
end else begin
mskPreviewPercentage.Enabled := True;
mskPreviewPage.Enabled := True;
pnlPreviewBar.Cursor := crDefault;
ppViewer1.PaintBox.Cursor := crDefault;
FStatusbar.Cursor := crDefault;
spbPreviewClose.Cursor := crDefault;
spbPreviewClose.Caption := LoadStr(LanguageIndex + ppMsgClose);
end;
{this code will force the cursor to update}
GetCursorPos(lPosition);
SetCursorPos(lPosition.X, lPosition.Y);
end;
Procedure TXPrintPreview.spbPreviewCloseClick(Sender: TObject);
begin
if TppProducer(Report).Printing then ppViewer1.Cancel
else Close;
end;
Procedure TXPrintPreview.ppViewerStatusChange(Sender: TObject);
begin
{$IFDEF WIN32}
FStatusbar.SimpleText := ppViewer1.Status;
{$ELSE}
FStatusbar.Caption := ppViewer1.Status;
{$ENDIF}
end;
Procedure TXPrintPreview.ppViewerPageChange(Sender: TObject);
begin
mskPreviewPage.Text:=IntToStr(ppViewer1.AbsolutePageNo);
mskPreviewPercentage.Text:=IntToStr(ppViewer1.CalculatedZoom);
end;
Procedure TXPrintPreview.spbPreviewPrintClick(Sender: TObject);
begin
ppViewer1.Print;
end;
Procedure TXPrintPreview.spbPreviewFirstClick(Sender: TObject);
begin
ppViewer1.FirstPage;
end;
Procedure TXPrintPreview.spbPreviewPriorClick(Sender: TObject);
begin
ppViewer1.PriorPage;
end;
Procedure TXPrintPreview.spbPreviewNextClick(Sender: TObject);
begin
ppViewer1.NextPage;
end;
Procedure TXPrintPreview.spbPreviewLastClick(Sender: TObject);
begin
ppViewer1.LastPage;
end;
Procedure TXPrintPreview.mskPreviewPageKeyPress(Sender: TObject; var Key: Char);
var
liPage: Longint;
begin
if (Key = #13) then begin
liPage:=StrToInt(mskPreviewPage.Text);
ppViewer1.GotoPage(liPage);
end; {if, carriage return pressed}
end;
Procedure TXPrintPreview.spbPreviewWholeClick(Sender: TObject);
begin
ppViewer1.ZoomSetting := zsWholePage;
mskPreviewPercentage.Text := IntToStr(ppViewer1.CalculatedZoom);
{pnlPreviewBar.SetFocus;}
end;
Procedure TXPrintPreview.spbPreviewWidthClick(Sender: TObject);
begin
ppViewer1.ZoomSetting := zsPageWidth;
mskPreviewPercentage.Text := IntToStr(ppViewer1.CalculatedZoom);
{pnlPreviewBar.SetFocus;}
end;
Procedure TXPrintPreview.spbPreview100PercentClick(Sender: TObject);
begin
ppViewer1.ZoomSetting := zs100Percent;
mskPreviewPercentage.Text := IntToStr(ppViewer1.CalculatedZoom);
{pnlPreviewBar.SetFocus;}
end;
Procedure TXPrintPreview.mskPreviewPercentageKeyPress(Sender: TObject; var Key: Char);
var liPercentage: Integer;
begin
if (Key = #13) then begin
liPercentage:=StrToIntDef(mskPreviewPercentage.Text, 100);
ppViewer1.ZoomPercentage:=liPercentage;
spbPreviewWhole.Down:=False;
spbPreviewWidth.Down:=False;
spbPreview100Percent.Down:=False;
mskPreviewPercentage.Text := IntToStr(ppViewer1.CalculatedZoom);
end; {if, carriage return pressed}
end;
{
Initialization
ppRegisterForm(TppCustomPreviewer, TXPrintPreview);}
Procedure TXPrintPreview.pnlPreviewBarClick(Sender: TObject);
begin
ActiveControl:=nil;
end;
end.
|
unit uServidor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent,
IdComponent, IdCustomTCPServer, IdSocksServer, System.Win.ScktComp;
type
TForm1 = class(TForm)
Button1: TButton;
sServer: TServerSocket;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure sServerClientRead(Sender: TObject; Socket: TCustomWinSocket);
procedure sServerClientWrite(Sender: TObject; Socket: TCustomWinSocket);
procedure sServerClientConnect(Sender: TObject; Socket: TCustomWinSocket);
procedure sServerClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
if sServer.Active then
begin
sServer.Active := false;
Memo1.Lines.Add('Servidor desligado!');
end
else
begin
sServer.Active := true;
Memo1.Lines.Add('Servidor iniciado...');
end;
end;
procedure TForm1.sServerClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo1.Lines.Add('Client '+IntToStr(Socket.SocketHandle)+' conectado!');
end;
procedure TForm1.sServerClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo1.Lines.Add('Client '+IntToStr(Socket.SocketHandle)+' desconectado!');
end;
procedure TForm1.sServerClientRead(Sender: TObject; Socket: TCustomWinSocket);
var
cI: LongInt;
str: String;
hClient : HWND;
begin
str := Socket.ReceiveText;
for cI := 0 to sServer.Socket.ActiveConnections -1 do
begin
hClient := sServer.Socket.Connections[cI].Handle;
Memo1.Lines.Add(str);
sServer.Socket.Connections[cI].SendText(TimeToStr(now) + '- '+ str);
end;
end;
procedure TForm1.sServerClientWrite(Sender: TObject; Socket: TCustomWinSocket);
var
str : String;
I: Integer;
begin
//str := Socket.ReceiveText;
//Memo1.Lines.Add(str);
end;
end.
|
unit DelphiSimpleQueue;
interface
uses
System.Generics.Collections
, Classes
, SyncObjs
;
type
TSQTOnComplete<T> = procedure(sender: T; ASuccess: boolean; const AMsg: string) of object;
TSQTOnNotify<T> = procedure(sender: T; const AMsg: string) of object;
TSimpleQueueBundle = class(TObject)
private
FCS: TCriticalSection;
FDict: TDictionary<string, string>;
function GetParam(AName: string): string;
procedure SetParam(AName: string; const Value: string);
public
constructor Create;
destructor Destroy; override;
property Param[AName: string]: string read GetParam write SetParam; default;
end;
TSimpleQueueTask = class
public
procedure Execute(AOnComplete: TSQTOnComplete<TSimpleQueueTask>; ABundle:
TSimpleQueueBundle; AOnNotify: TSQTOnNotify<TSimpleQueueTask>); virtual; abstract;
procedure ExecuteWrapper(AOnComplete: TSQTOnComplete<TSimpleQueueTask>;
ABundle: TSimpleQueueBundle; AOnNotify: TSQTOnNotify<TSimpleQueueTask>); virtual;
function Name: string; virtual;
end;
TSimpleQueue<T: TSimpleQueueTask> = class
private
FActive: Boolean;
FCS: TCriticalSection;
FCurrentTask: T;
FOnComplete: TSQTOnComplete<T>;
FList: TList<T>;
FOnNextTask: TNotifyEvent;
FOnNotify: TSQTOnNotify<TSimpleQueueTask>;
procedure ExecuteTask; virtual;
function GetCount: Integer;
procedure InternalExecuteTask;
function GetNextTask: T;
procedure OnInternalTaskComplete(sender: TSimpleQueueTask; ASuccess: boolean;
const AMsg: string);
procedure SetActive(const Value: Boolean);
protected
FBundle: TSimpleQueueBundle;
public
constructor Create(AOnComplete: TSQTOnComplete<T>);
destructor Destroy; override;
procedure Add(ATask: T);
procedure Clear;
property Active: Boolean read FActive write SetActive;
property Bundle: TSimpleQueueBundle read FBundle;
property Count: Integer read GetCount;
property OnNextTask: TNotifyEvent read FOnNextTask write FOnNextTask;
property OnNotify: TSQTOnNotify<TSimpleQueueTask> read FOnNotify write
FOnNotify;
property OnComplete: TSQTOnComplete<T> read FOnComplete write FOnComplete;
end;
TSimpleQueueThreadTask = class(TSimpleQueueTask)
public
procedure ExecuteWrapper(AOnComplete: TSQTOnComplete<TSimpleQueueTask>;
ABundle: TSimpleQueueBundle; AOnNotify: TSQTOnNotify<TSimpleQueueTask>); override;
end;
TThreadSimpleQueue<T: TSimpleQueueTask> = class(TSimpleQueue<T>)
private
procedure ExecuteTask; override;
public
constructor Create(AOnComplete: TSQTOnComplete<T>);
end;
implementation
uses
SysUtils
;
constructor TSimpleQueue<T>.Create(AOnComplete: TSQTOnComplete<T>);
begin
inherited Create;
FOnComplete := AOnComplete;
FList := TList<T>.Create;
FCS := TCriticalSection.Create;
FBundle := TSimpleQueueBundle.Create;
FActive := True;
end;
destructor TSimpleQueue<T>.Destroy;
begin
FreeAndNil(FBundle);
FreeAndNil(FCS);
FreeAndNil(FList);
inherited;
end;
procedure TSimpleQueue<T>.Add(ATask: T);
begin
FCS.Enter;
try
FList.Add(ATask);
finally
FCS.Leave;
end;
ExecuteTask;
end;
procedure TSimpleQueue<T>.Clear;
var
task: T;
begin
FCS.Enter;
try
for task in FList do
task.free;
FList.Clear;
if Assigned(FCurrentTask) then
FreeAndNil(FCurrentTask);
finally
FCS.Leave;
end;
if Assigned(FOnComplete) then
FOnComplete(nil, True, 'Queue is cleared');
end;
procedure TSimpleQueue<T>.ExecuteTask;
begin
InternalExecuteTask;
end;
function TSimpleQueue<T>.GetCount: Integer;
begin
FCS.Enter;
try
Result := FList.Count;
finally
FCS.Leave;
end;
end;
procedure TSimpleQueue<T>.InternalExecuteTask;
var
task: T;
begin
task := nil;
FCS.Enter;
try
if not FActive then
exit;
if Assigned(FCurrentTask) then
exit;
FCurrentTask := GetNextTask;
task := FCurrentTask;
if not Assigned(FCurrentTask) then
exit;
finally
FCS.Leave;
end;
if Assigned(task) then
begin
if Assigned(FOnNextTask) then
FOnNextTask(task);
task.executeWrapper(OnInternalTaskComplete, FBundle, FOnNotify);
end else
begin
if Assigned(FOnNextTask) then
FOnNextTask(nil);
end;
end;
function TSimpleQueue<T>.GetNextTask: T;
begin
Result := nil;
FCS.Enter;
try
if FList.Count > 0 then
begin
Result := FList[0];
FList.Delete(0);
end;
finally
FCs.Leave;
end;
end;
procedure TSimpleQueue<T>.OnInternalTaskComplete(sender: TSimpleQueueTask;
ASuccess: boolean; const AMsg: string);
begin
if Assigned(FOnComplete) then
FOnComplete(Sender, ASuccess, AMsg);
try
Sender.Free;
except
end;
FCS.Enter;
try
FCurrentTask := nil;
finally
FCS.Leave;
end;
ExecuteTask;
end;
procedure TSimpleQueue<T>.SetActive(const Value: Boolean);
var
execute: Boolean;
begin
if not Assigned(FCS) then
exit;
execute := False;
FCS.Enter;
try
execute := Value and Value <> FActive;
FActive := Value;
finally
FCS.Leave;
end;
if execute then
ExecuteTask;
end;
procedure TSimpleQueueTask.ExecuteWrapper(AOnComplete:
TSQTOnComplete<TSimpleQueueTask>; ABundle: TSimpleQueueBundle; AOnNotify: TSQTOnNotify<TSimpleQueueTask>);
begin
try
Execute(AOnComplete, ABundle, AOnNotify);
except
on E: Exception do
if Assigned(AOnComplete) then
AOnComplete(self, False, E.message);
end;
end;
function TSimpleQueueTask.Name: string;
begin
Result := self.ClassName;
end;
procedure TSimpleQueueThreadTask.ExecuteWrapper(AOnComplete:
TSQTOnComplete<TSimpleQueueTask>; ABundle: TSimpleQueueBundle; AOnNotify: TSQTOnNotify<TSimpleQueueTask>);
begin
TThread.CreateAnonymousThread(procedure()
begin
Execute(AOnComplete, ABundle, AOnNotify);
end).Start;
end;
constructor TThreadSimpleQueue<T>.Create(AOnComplete: TSQTOnComplete<T>);
begin
inherited;
end;
procedure TThreadSimpleQueue<T>.ExecuteTask;
begin
TThread.CreateAnonymousThread(procedure()
begin
InternalExecuteTask;
end).Start;
end;
constructor TSimpleQueueBundle.Create;
begin
FCS := TCriticalSection.Create;
FDict := TDictionary<string,string>.Create;
end;
destructor TSimpleQueueBundle.Destroy;
begin
FDict.Free;
FCS.Free;
end;
function TSimpleQueueBundle.GetParam(AName: string): string;
begin
FCS.Enter;
try
FDict.TryGetValue(AName, Result);
finally
FCS.Leave;
end;
end;
procedure TSimpleQueueBundle.SetParam(AName: string; const Value: string);
begin
FCS.Enter;
try
FDict.AddOrSetValue(AName, Value);
finally
FCS.Leave;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC wait time user interface }
{ }
{ Copyright(c) 2004-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$IFDEF WIN32}
{$HPPEMIT '#pragma link "FireDAC.FMXUI.Wait.obj"'}
{$ELSE}
{$HPPEMIT '#pragma link "FireDAC.FMXUI.Wait.o"'}
{$ENDIF}
unit FireDAC.FMXUI.Wait;
interface
implementation
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
FMX.Types, FMX.Platform, FMX.Forms,
FireDAC.Stan.Factory, FireDAC.Stan.Consts, FireDAC.Stan.Util,
FireDAC.UI.Intf, FireDAC.Comp.UI, FireDAC.UI;
{-------------------------------------------------------------------------------}
{- TFDGUIxFMXWaitCursorImpl -}
{-------------------------------------------------------------------------------}
type
TFDGUIxFMXWaitCursorImpl = class(TFDGUIxVisualWaitCursorImplBase)
private
function CheckGetCursor(out ACrs: TCursor): Boolean;
protected
function CheckCurCursor: Boolean; override;
function InternalHideCursor: Boolean; override;
procedure InternalShowCursor; override;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFMXWaitCursorImpl.CheckGetCursor(out ACrs: TCursor): Boolean;
begin
case FWaitCursor of
gcrDefault: ACrs := crDefault;
gcrHourGlass: ACrs := crHourGlass;
gcrSQLWait: ACrs := crSQLWait;
gcrAppWait: ACrs := crAppStart;
else ACrs := crNone;
end;
Result := ACrs <> crNone;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFMXWaitCursorImpl.CheckCurCursor: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFMXWaitCursorImpl.InternalHideCursor: Boolean;
var
oCrsSrv: IFMXCursorService;
begin
Result := TPlatformServices.Current.SupportsPlatformService(IFMXCursorService, IInterface(oCrsSrv));
if Result then
oCrsSrv.SetCursor(crDefault);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFMXWaitCursorImpl.InternalShowCursor;
var
iCrs: TCursor;
oCrsSrv: IFMXCursorService;
begin
if CheckGetCursor(iCrs) then
if TPlatformServices.Current.SupportsPlatformService(IFMXCursorService, IInterface(oCrsSrv)) then
oCrsSrv.SetCursor(iCrs);
end;
{-------------------------------------------------------------------------------}
function CheckGuiRunning: Boolean;
begin
Result := (Application <> nil) and not Application.Terminated;
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
oFact := TFDSingletonFactory.Create(TFDGUIxFMXWaitCursorImpl, IFDGUIxWaitCursor,
C_FD_GUIxFMXProvider, 'FireDAC.FMXUI.Wait');
GCheckGuiRunning := CheckGuiRunning;
finalization
FDReleaseFactory(oFact);
end.
|
unit base_delphi_utils;
//自编的具有独特功能的调用工具包.
interface
uses SysUtils, Dialogs, registry, Windows;
function strtochar( const sstr: string ): char;
function countsubstring( const str: string; const substr: string )
: integer;
function nformat( var str:string; len:integer ) : boolean ;
function identifilize( var str:string; len:integer ) : boolean ;
function dateformat( var str:string; const separator:string ): boolean ;
procedure logicalexplink( var objectexp:string; const optype:char;
const appendexp:string );//粗放型的.
procedure switchtolongyear(var tstr:string; const separator:string);
procedure switchtoshortyear(var tstr:string; const separator:string);
function gethostname: string;
function getusername: string;
function milliseconddiff(starttime: Tdatetime; endtime: Tdatetime)
: integer;
implementation
//====================================================================
{
function AsciiValue( ch: char ): Byte;
var
b: Byte;
p: Pointer;
begin
p:=@b;
PChar(p)^:=ch;
result:=b;
end;
//--------------------------------------------------------------------
function AsciiChar( code: Byte ): char;
var
b: Byte;
p: Pointer;
begin
b:=code;
p:=@b;
result:=PChar(p)^;
end;
//--------------------------------------------------------------------
}
function strtochar( const sstr: string ): char;
begin
if (sstr='') then //当sstr为空时,返回#0.
result:=#0
else //否则返回sstr的第一个字符.
result:=sstr[1];
end;
//--------------------------------------------------------------------
function countsubstring( const str: string; const substr: string )
: integer;
var
i, len : integer;
stemp: string;
begin
if substr='' then //若substr为空,返回 -1 (视为失败)
begin
result:=-1;
exit;
end;
stemp:=str;
len:=length(substr);
result:=0;
i:=pos(substr, stemp);
while (i<>0) do
begin
result:=result+1;
delete(stemp,1,i+len-1); //清除整个当前子串(不重叠计数).
i:=pos(substr, stemp);
end;
end;
//--------------------------------------------------------------------
function nformat( var str:string; len:integer ) : boolean ;
var
i, l :integer;
ch:string;
allnumflag:boolean;
begin
str:=trim(str); //预先去除目标串的前导空格和后缀空格.
l:=length(str);
if (len<=0) then len:=l; //当len参数<=0时, 视要求为----"自然长度"
if l>len then //目标串超长,视为不合法.
begin
result:=false;
exit;
end;
if l>0 then //目标串不够长,则补充前导零.
for i:=l+1 to len do str:= '0' + str
else //目标串为空串,视为不合法.
begin
result:=false;
exit;
end;
allnumflag:=true; //以下检测目标串是否为全数字串.
l:=1;
while allnumflag and (l<=len) do
begin
ch:=copy(str,l,1);
allnumflag:=( (ch>='0') and (ch<='9') );
l:=l+1;
end;
result:=allnumflag;
end;
//--------------------------------------------------------------------
function dateformat( var str:string; const separator:string ): boolean ;
label invalid;
var // eg. '02/28/1997'
month, day, year, i: integer;
resultstring, stemp, spart: string;
btemp: boolean;
begin
stemp:=str;
i:=countsubstring(stemp, separator);
if i<>2 then goto invalid; //目标串中所含separator数不等于2,必非法.
i:=pos(separator, stemp); //截取月份,测试其合法性.
spart:=copy(stemp, 1, i-1);
btemp:=nformat(spart, 2);
if not(btemp)or(spart='') then goto invalid;
month:=strtoint(spart);
if (month<1) or (month>12) then goto invalid;
resultstring:=spart + separator;//合法:则将经规范过的月份值
delete(stemp, 1, i); // 转移至resultstring.
i:=pos(separator, stemp); //截取日期,初步测试其合法性.
spart:=copy(stemp, 1, i-1);
btemp:=nformat(spart, 2);
if not(btemp)or(spart='') then goto invalid;
day:=strtoint(spart);
if (day<1) or (day>31) then goto invalid;
resultstring:=resultstring+spart+separator;//初步合法:则将经规范过的
delete(stemp, 1, i); //日期值转移至resultstring.
spart:=stemp; //截取年份,测试其合法性.
btemp:=nformat(spart, 4);
if not(btemp)or(spart='') then goto invalid;
year:=strtoint(spart);
resultstring:=resultstring+spart; //合法:则将经规范过的年份值(4位)
stemp:=''; // 转移至resultstring.
if (month=2) then //再次测试在平,闰年条件下日期(尤其在二月时)的合法性.
begin
if day>29 then goto invalid;
if ((year mod 4)<>0)or(((year mod 100)=0)and((year mod 400)<>0)) then
if day>28 then goto invalid;
end
else if (month=4)or(month=6)or(month=9)or(month=11) then
begin
if day>30 then goto invalid;
end;
str:=resultstring;
result:=true;
exit;
invalid:
str:=resultstring+stemp;
result:=false;
exit;
end;
//---------------------------------------------------------------------
function identifilize( var str:string; len:integer ) : boolean ;
var // 使输入字串'广义标识符'化, 以具备'唯一标识'的能力.
i, l :integer;
begin
str:=trim(str); //预先去除目标串的前导空格和后缀空格.
l:=length(str);
i:=pos(' ', str);
result:=((l>0)and(l<=len)and(i=0));
//目标串超长或为空串或内含空格,视为不合法.
if (result) then for i:=l+1 to len do str:=str+' ';
//不够规定长度,则补后缀空格,以保证输出串的格式化.
end;
//---------------------------------------------------------------------
procedure logicalexplink( var objectexp:string; const optype:char;
const appendexp:string );
var anotherexp: string;
begin
objectexp:=trim(objectexp); //尽量缩小字串"体积".
anotherexp:=trim(appendexp);
if (anotherexp='') then //待加串为空串,则目标串加括号(规范)返回.
begin
if (objectexp<>'') then objectexp:='(' + objectexp + ')';
exit;
end;
if (objectexp='') then //目标串原为空串,则取规范后的待加串
begin // 为其新内容.
objectexp:='(' + anotherexp + ')';
exit;
end;
case optype of //两串皆非空,则按 optype 进行逻辑组合.
'&': objectexp:='((' + objectexp + ')AND(' + anotherexp + '))';//与
'|': objectexp:='((' + objectexp + ')OR(' + anotherexp + '))'; //或
'~': objectexp:='(NOT(' + anotherexp + '))'; //非
'^': objectexp:='((' + objectexp + ')XOR(' + anotherexp + '))' //异或
else // optype 异常.
begin
showmessage('LogicalExpLink error: optype mismatch.');
abort;
end;
end; // of case
end;
//------------------------------------------------------------------
procedure switchtolongyear(var tstr:string; const separator:string);
var // 仅尽力将串中'年份'部分由'yy'格式转化为'yyyy',不负责纠错.
i, j: integer;
stemp: string;
begin
stemp:=tstr;
i:=pos(separator, stemp); // 第一个separator
if i=0 then exit; // 原字串无separator(必错),则原样返回.
delete(stemp, i, 1);
i:=pos(separator, stemp); // 第二个separator
if i=0 then exit; // 原字串仅含一个separator(必错),则原样返回.
stemp:=trim( copy(tstr,i+2,length(tstr)-i-2+1) );
j:=length(stemp);
case j of //整理'年份'字串的末 2位.
1 : stemp:='0'+stemp;
2 : ;
else exit; //'年份'字串长度 =0(空串)或 >2(已被视为'yyyy'或非法
// 超长),则原样返回.
end; // of case
delete(tstr, i+2, length(tstr)-i-2+1);
stemp:=copy(formatdatetime('yyyy',now), 1, 2)+stemp;
tstr:=tstr+stemp;
end;
//------------------------------------------------------------------
procedure switchtoshortyear(var tstr:string; const separator:string);
var // 仅尽力将串中'年份'部分由'yyyy'格式转化为'yy',不负责纠错.
i, j: integer; //一般算法流程下, tstr常常已为合法的'mm/dd/yyyy'格式.
stemp: string;
begin
stemp:=tstr;
i:=pos(separator, stemp); // 第一个separator
if i=0 then exit; // 原字串无separator(必错),则原样返回.
delete(stemp, i, 1);
i:=pos(separator, stemp); // 第二个separator
if i=0 then exit; // 原字串仅含一个separator(必错),则原样返回.
stemp:=trim( copy(tstr,i+2,length(tstr)-i-2+1) );
j:=length(stemp);
if (j<=2) then exit;//'年份'字串为空或 1<=长度<=2(已被视为'yy'),则原样返回.
stemp:=copy(stemp, j-1, 2);// 一律取'年份'字串的最后2位作为'yy'.
delete(tstr, i+2, length(tstr)-i-2+1);
tstr:=tstr+stemp;
end;
//------------------------------------------------------------------
function gethostname: string;
var
reg: TRegistry;
tstr: string;
boolvar: boolean;
begin
result:='';
reg:=TRegistry.Create;
reg.RootKey:=HKEY_LOCAL_MACHINE;
tstr:='\System\CurrentControlSet\control\ComputerName\ComputerName';
boolvar:=reg.OpenKey(tstr, false);
if (boolvar) then
begin
boolvar:=reg.ValueExists('ComputerName');
if (boolvar) then result:=reg.ReadString('ComputerName');
end;
reg.Free;
end;
//------------------------------------------------------------------
function getusername: string;
var
reg: TRegistry;
tstr: string;
boolvar: boolean;
begin
result:='';
reg:=TRegistry.Create;
reg.RootKey:=HKEY_LOCAL_MACHINE;
tstr:='\Network\Logon';
boolvar:=reg.OpenKey(tstr, false);
if (boolvar) then
begin
boolvar:=reg.ValueExists('username');
if (boolvar) then result:=result+reg.ReadString('username');
end;
reg.Free;
end;
//------------------------------------------------------------------
function milliseconddiff(starttime: Tdatetime; endtime: Tdatetime)
: integer;
var
days: integer;
sta_hh, sta_mi, sta_ss, sta_ms: Word;
end_hh, end_mi, end_ss, end_ms: Word;
begin
DecodeTime(starttime, sta_hh, sta_mi, sta_ss, sta_ms);
DecodeTime(endtime , end_hh, end_mi, end_ss, end_ms);
days:=trunc(endtime)-trunc(starttime);
result:=(((days*24+end_hh-sta_hh)*60+(end_mi-sta_mi))*60
+(end_ss-sta_ss))*1000+(end_ms-sta_ms);
end;
//------------------------------------------------------------------
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2012 Vincent Parrett }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.Tests.WeakReference;
(*
The idea behind this unit is provide a similar lifecycle to reference counted objects
in delphi as WeakReference does in .NET.
Reference counted objects in delphi have some limitations when it comes to circular references,
where for example TParent references it's children (via IChild), and TChild references it's parent
(via IParent). If we remove any external references to our IParent and IChild instances without first
getting the child to remove it's reference to IParent, we would end up with orphaned objects. This
is because our IChild and IParent instances are holding references to each other, and thus they never
get released.
This unit was borrowed from FinalBuilder 7(with permission), it has been extensively used with
Delphi 2010 and has so far proven to be very reliable.
*)
interface
uses
DUnitX.TestFramework,
DUnitX.WeakReference;
type
ISimpleInterface = interface
['{1A84030F-EEC5-447F-981D-94C4339D8800}']
function GetName : string;
end;
TSimpleInterfacedObject = class(TWeakReferencedObject, ISimpleInterface)
function GetName : string;
end;
IInternalUseInterface = interface
['{B2A2406D-C17D-478C-A194-59AACF40D279}']
function GetName : string;
function GetInternalUseOnly : string;
property Name : string read GetName;
property InternalUseOnly : string read GetInternalUseOnly;
end;
IExternalUseInterface = interface
['{907365C0-2A20-41D0-927B-8B36FB4CB0FD}']
function GetName : string;
property Name : string read GetName;
end;
TExposedObject = class(TWeakReferencedObject, IInternalUseInterface, IExternalUseInterface)
private
FName : string;
protected
function GetName : string;
function GetInternalUseOnly : string;
public
property Name : string read GetName;
constructor Create(const ANewName: string);
end;
{$M+}
[TestFixture]
TDUnitX_WeakReferenceXMLNUnitTests = class
public
[Test]
procedure After_Being_Assigned_To_Another_Interface_Properties_Can_Be_Called;
[Test]
procedure After_Being_Created_Interface_Properties_Can_Be_Called;
[Test]
procedure After_The_Reference_Is_Freed_The_WeakReference_Data_Is_Nill;
[Test]
procedure After_The_Reference_Is_Freed_The_WeakReference_Data_Is_Not_Alive;
end;
implementation
procedure TDUnitX_WeakReferenceXMLNUnitTests.After_Being_Assigned_To_Another_Interface_Properties_Can_Be_Called;
var
mockInternalObj : IInternalUseInterface;
mockExternalObj : IExternalUseInterface;
weakRef : IWeakReference<IExternalUseInterface>;
const
EXPECTED_NAME = 'We can see this exposed!';
begin
//Make sure to create the object and store under the internal interface
mockInternalObj := TExposedObject.Create(EXPECTED_NAME);
//As we know the exposed object stored in internal object interface supports external interface just cast.
mockExternalObj := (mockInternalObj as IExternalUseInterface);
//Get a weak reference to the exposed interace
weakRef := TWeakReference<IExternalUseInterface>.Create(mockExternalObj);
//Check that we have a valid external reference.
Assert.AreEqual(weakRef.Data.Name, EXPECTED_NAME);
end;
procedure TDUnitX_WeakReferenceXMLNUnitTests.After_Being_Created_Interface_Properties_Can_Be_Called;
var
mockInterface : ISimpleInterface;
weakRef : IWeakReference<ISimpleInterface>;
begin
//Setup
mockInterface := TSimpleInterfacedObject.Create;
weakRef := TWeakReference<ISimpleInterface>.Create(mockInterface);
//Check
Assert.AreEqual(weakRef.Data.GetName, mockInterface.GetName);
end;
procedure TDUnitX_WeakReferenceXMLNUnitTests.After_The_Reference_Is_Freed_The_WeakReference_Data_Is_Nill;
var
mockInterface : ISimpleInterface;
weakRef : IWeakReference<ISimpleInterface>;
begin
//Setup
mockInterface := TSimpleInterfacedObject.Create;
weakRef := TWeakReference<ISimpleInterface>.Create(mockInterface);
//Test
mockInterface := nil;
//Check
Assert.IsNull(weakRef.Data);
end;
procedure TDUnitX_WeakReferenceXMLNUnitTests.After_The_Reference_Is_Freed_The_WeakReference_Data_Is_Not_Alive;
var
mockInterface : ISimpleInterface;
weakRef : IWeakReference<ISimpleInterface>;
begin
//Setup
mockInterface := TSimpleInterfacedObject.Create;
weakRef := TWeakReference<ISimpleInterface>.Create(mockInterface);
//Test
mockInterface := nil;
//Check
Assert.IsTrue(not weakRef.IsAlive);
end;
{ TExposedObject }
function TExposedObject.GetName: string;
begin
Result := FName;
end;
constructor TExposedObject.Create(const ANewName: string);
begin
inherited Create;
FName := ANewName;
end;
function TExposedObject.GetInternalUseOnly: string;
begin
Result := 'Only here for completeness!';
end;
{ TSimpleInterfacedObject }
function TSimpleInterfacedObject.GetName: string;
begin
Result := Self.ClassName;
end;
initialization
TDUnitX.RegisterTestFixture(TDUnitX_WeakReferenceXMLNUnitTests);
end.
|
unit TypeList;
interface
uses
SysUtils;
const
FILE_NAME = 'Films';
type
TName = string[30];
TTitle = string[70];
TDirector = record
LastName: TName;
Name: TName;
MiddleName: TName;
end;
TTime = Integer;
TGenre = (Adventure, GAction, Comedy, Detective, Drama, Thriller, Fantasy,
Science_fiction, Horror, Historical, Mystery, Romance, Western, Animation,
Musical, Satire, Social, Other);
TCountry = string[30];
TYear = Integer;
TWords = string[20];
TAwards = string[50];
TBudget = TName;
TBoxOffice = TName;
TRating = 1 .. 10;
TItem = record
Index: Integer;
Title: TTitle;
Director: TDirector;
Genre: TGenre;
Country: TCountry;
Year: TYear;
Duration: TTime;
Words: TWords;
Awards: TAwards;
Budget: TBudget;
BoxOffice: TBoxOffice;
case Ready: Boolean of
True:
(Rating: TRating);
False:
();
end;
PFilm = ^TFilm;
TFilm = record
Item: TItem;
Next: PFilm;
end;
TFilmList = class
EntryPoint: PFilm;
Head: PFilm;
Tail: PFilm;
fICount: Integer;
FileName: string;
public
constructor Create;
destructor Destroy;
procedure DeleteFilm(const FilmIndex: Integer);
procedure CreateFilm(const aItem: TItem);
procedure SaveList(const aFileName: string);
procedure EditFilm(const aItem: TItem; const aIndex: Integer);
function GetFilmByIndex(const aIndex: Integer): PFilm;
procedure RestoreIndexing();
private
procedure UploadFile(const aFileName: string);
procedure AddFilm(const Item: PFilm);
function IsEmpty(): Boolean;
end;
implementation
{ Конструктор создания списка при запуске программы }
constructor TFilmList.Create;
begin
New(EntryPoint);
EntryPoint.Next := nil;
Head := nil;
Tail := nil;
UploadFile(FILE_NAME);
end;
{ Деструктор. Разрушение списка при закрытии программы }
destructor TFilmList.Destroy;
begin
while not IsEmpty() do
begin
DeleteFilm(1);
RestoreIndexing()
end;
Dispose(EntryPoint);
end;
{ Проверка на существования элементов в списке }
function TFilmList.IsEmpty(): Boolean;
begin
Result := EntryPoint.Next = nil;
end;
{ Загрузки фильмов из файла }
procedure TFilmList.UploadFile(const aFileName: string);
var
F: file of TFilm;
ItemTmp: PFilm;
begin
FileName := aFileName;
AssignFile(F, FileName);
if not FileExists(FileName) then
Rewrite(F)
else
begin
Reset(F);
while not EoF(F) do
begin
New(ItemTmp);
Read(F, ItemTmp^);
AddFilm(ItemTmp);
end;
end;
CloseFile(F);
end;
{ Сохранение фильмов в файл }
procedure TFilmList.SaveList(const aFileName: string);
var
F: file of TFilm;
CurrNode: PFilm;
begin
AssignFile(F, aFileName);
Rewrite(F);
CurrNode := Head;
while CurrNode <> nil do
begin
Write(F, CurrNode^);
CurrNode := CurrNode.Next;
end;
CloseFile(F);
end;
{ Создание нового фильма }
procedure TFilmList.CreateFilm(const aItem: TItem);
var
PFilmInfo: PFilm;
begin
New(PFilmInfo);
PFilmInfo^.Item := aItem;
AddFilm(PFilmInfo);
end;
{ Добавление нового фильма в таблицу }
procedure TFilmList.AddFilm(const Item: PFilm);
begin
if EntryPoint.Next = nil then
begin
EntryPoint.Next := Item;
Head := Item;
Tail := Item;
Item.Next := nil;
end
else
begin
Tail.Next := Item;
Tail := Item;
Tail.Next := nil;
end;
Inc(fICount);
end;
{ Редактирование фильма }
procedure TFilmList.EditFilm(const aItem: TItem; const aIndex: Integer);
var
CurrNode: PFilm;
begin
CurrNode := EntryPoint.Next;
while CurrNode.Item.Index <> aIndex + 1 do
CurrNode := CurrNode.Next;
CurrNode^.Item := aItem;
SaveList(FILE_NAME);
end;
{ Удаление фильма из списка }
procedure TFilmList.DeleteFilm(const FilmIndex: Integer);
var
CurrNode, PrevNode: PFilm;
begin
if not IsEmpty() then
begin
PrevNode := EntryPoint;
while PrevNode.Next.Item.Index <> FilmIndex do
PrevNode := PrevNode.Next;
CurrNode := PrevNode.Next;
PrevNode.Next := CurrNode.Next;
if CurrNode = Tail then
Tail := PrevNode;
Dispose(CurrNode);
end;
end;
{ Получение элемента списка по индексу }
function TFilmList.GetFilmByIndex(const aIndex: Integer): PFilm;
var
CurrNode: PFilm;
begin
CurrNode := EntryPoint.Next;
while CurrNode.Item.Index <> aIndex + 1 do
CurrNode := CurrNode.Next;
Result := CurrNode;
end;
{ Переиндексация фильмов }
procedure TFilmList.RestoreIndexing();
var
i: Integer;
CurrNode : PFilm;
begin
i := 1;
CurrNode := EntryPoint.Next;
while CurrNode <> nil do
begin
CurrNode.Item.Index := i;
Inc(i);
CurrNode := CurrNode.Next;
end;
FICount := i - 1;
end;
end.
|
unit SAPOPOReader2;
interface
uses
Classes, SysUtils, ComObj, CommUtils, ADODB;
type
TSAPOPOAlloc = packed record
dQty: Double;
dt: TDateTime;
sMrpAreaNo: string;
end;
PSAPOPOAlloc= ^TSAPOPOAlloc;
TSAPOPOLine = class
private
FList: TList;
function GetCount: Integer;
function GetItems(i: Integer): PSAPOPOAlloc;
public
FNumber: string;
FName: string;
FDate: TDateTime;
FStock: string; // 库存地点
FQty: Double;
FQtyAlloc: Double;
FBillNo: string;
FLine: string;
FPlanLine: string;
FBillDate: TDateTime;
FSupplier: string;
Tag: TObject;
constructor Create;
destructor Destroy; override;
procedure Clear;
function Alloc(dt: TDateTime; var dQty: Double;
const sAreaNo: string): Double;
property Count: Integer read GetCount;
property Items[i: Integer]: PSAPOPOAlloc read GetItems;
end;
TSAPOPOReader2 = class
private
FList: TStringList;
FFile: string;
ExcelApp, WorkBook: Variant;
FLogEvent: TLogEvent;
procedure Open;
procedure Log(const str: string);
function GetCount: Integer;
function GetItems(i: Integer): TSAPOPOLine;
public
constructor Create(const sfile: string; aLogEvent: TLogEvent = nil);
destructor Destroy; override;
procedure Clear;
procedure GetOPOs(slNumber: TStringList; lst: TList);
function Alloc(slNumber: TStringList; dt: TDateTime; dQty: Double): Double;
property Count: Integer read GetCount;
property Items[i: Integer]: TSAPOPOLine read GetItems;
end;
function ListSortCompare_DateTime_PO(Item1, Item2: Pointer): Integer;
implementation
{ TSAPOPOLine }
constructor TSAPOPOLine.Create;
begin
FList := TList.Create;
FQtyAlloc := 0;
end;
destructor TSAPOPOLine.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TSAPOPOLine.Clear;
var
p: PSAPOPOAlloc;
i: Integer;
begin
for i := 0 to FList.Count -1 do
begin
p := PSAPOPOAlloc(FList[i]);
Dispose(p);
end;
FList.Clear;
end;
function TSAPOPOLine.GetCount: Integer;
begin
Result := FList.Count;
end;
function TSAPOPOLine.GetItems(i: Integer): PSAPOPOAlloc;
begin
Result := PSAPOPOAlloc(FList[i]);
end;
function TSAPOPOLine.Alloc(dt: TDateTime; var dQty: Double;
const sAreaNo: string): Double;
var
p: PSAPOPOAlloc;
begin
Result := 0;
if DoubleG( FQty, FQtyAlloc ) then //有可分配
begin
p := New(PSAPOPOAlloc);
FList.Add(p);
if DoubleGE( FQty - FQtyAlloc, dQty ) then //数量够分配
begin
Result := dQty;
FQtyAlloc := FQtyAlloc + dQty;
dQty := 0;
end
else // 数量不够分配
begin
Result := FQty - FQtyAlloc;
FQtyAlloc := FQty;
dQty := dQty - Result;
end;
p^.dQty := Result;
p^.dt := dt;
p^.sMrpAreaNo := sAreaNo;
end;
end;
{ TSAPOPOReader2 }
constructor TSAPOPOReader2.Create(const sfile: string;
aLogEvent: TLogEvent = nil);
begin
FFile := sfile;
FLogEvent := aLogEvent;
FList := TStringList.Create;
Open;
end;
destructor TSAPOPOReader2.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TSAPOPOReader2.Clear;
var
i: Integer;
p: TSAPOPOLine;
begin
for i := 0 to FList.Count - 1 do
begin
p := TSAPOPOLine(FList.Objects[i]);
p.Free;
end;
FList.Clear;
end;
procedure TSAPOPOReader2.GetOPOs(slNumber: TStringList; lst: TList);
var
i: Integer;
begin
for i := 0 to FList.Count - 1 do
begin
if slNumber.IndexOf(FList[i]) >= 0 then
begin
lst.Add( FList.Objects[i] );
end;
end;
end;
function TSAPOPOReader2.GetCount: Integer;
begin
Result := FList.Count;
end;
function TSAPOPOReader2.GetItems(i: Integer): TSAPOPOLine;
begin
Result := TSAPOPOLine(FList.Objects[i]);
end;
function ListSortCompare_DateTime_PO(Item1, Item2: Pointer): Integer;
var
p1, p2: TSAPOPOLine;
begin
p1 := TSAPOPOLine(Item1);
p2 := TSAPOPOLine(Item2);
if DoubleG(p1.FDate, p2.FDate) then
Result := 1
else if DoubleL(p1.FDate, p2.FDate) then
Result := -1
else Result := 0;
end;
function TSAPOPOReader2.Alloc(slNumber: TStringList; dt: TDateTime;
dQty: Double): Double;
var
lst: TList;
i: Integer;
p: TSAPOPOLine;
begin
Result := 0;
lst := TList.Create;
GetOPOs(slNumber, lst); // 找到所有替代料的可用采购订单
lst.Sort(ListSortCompare_DateTime_PO); // 按日期排序
for i := 0 to lst.Count - 1 do
begin
p := TSAPOPOLine(lst[i]);
Result := Result + p.Alloc(dt, dQty, '');
if DoubleE( dQty, 0) then // 需求满足分配了
begin
Break;
end;
end;
lst.Free;
end;
procedure TSAPOPOReader2.Log(const str: string);
begin
savelogtoexe(str);
if Assigned(FLogEvent) then
begin
FLogEvent(str);
end;
end;
function IndexOfCol(ExcelApp: Variant; irow: Integer; const scol: string): Integer;
var
i: Integer;
s: string;
begin
Result := -1;
for i := 1 to 50 do
begin
s := ExcelApp.Cells[irow, i].Value;
if s = scol then
begin
Result := i;
Break;
end;
end;
end;
procedure TSAPOPOReader2.Open;
const
CSNumber = '物料';
CSName = '短文本';
CSColDate = '凭证日期';
CSStock = '库存地点';
CSQty = '计划数量';
CSBillNo = '采购凭证';
CSLine = '项目';
CSPlanLine = '计划行';
var
iSheetCount, iSheet: Integer;
sSheet: string;
stitle1, stitle2, stitle3, stitle4, stitle5, stitle6: string;
stitle: string;
irow: Integer;
snumber: string;
aSAPOPOLine: TSAPOPOLine;
iColNumber: Integer;
iColName: Integer;
iColDate: Integer;
iColStock: Integer;
iColQty: Integer;
iColBillNo: Integer;
iColLine: Integer;
iColPlanLine: Integer;
Conn: TADOConnection;
ADOTabXLS: TADOTable;
s: string;
begin
Clear;
if not FileExists(FFile) then Exit;
ADOTabXLS := TADOTable.Create(nil);
Conn:=TADOConnection.Create(nil);
Conn.ConnectionString:='Provider=Microsoft.ACE.OLEDB.12.0;Data Source="' + FFile + '";Extended Properties=excel 8.0;Persist Security Info=False';
Conn.LoginPrompt:=false;
try
Conn.Connected:=true;
ADOTabXLS.Connection:=Conn;
ADOTabXLS.TableName:='['+'Sheet1'+'$]';
ADOTabXLS.Active:=true;
ADOTabXLS.First;
while not ADOTabXLS.Eof do
begin
snumber := ADOTabXLS.FieldByName('物料').AsString; // ExcelApp.Cells[irow, iColNumber].Value;
if snumber = '' then
begin
ADOTabXLS.Next;
Continue;
end;
s := ADOTabXLS.FieldByName('删除标识').AsString; // ExcelApp.Cells[irow, iColName].Value;
if s = 'L' then
begin
ADOTabXLS.Next;
Continue;
end;
s := ADOTabXLS.FieldByName('工厂').AsString; // ExcelApp.Cells[irow, iColName].Value;
if s <> '1001' then
begin
ADOTabXLS.Next;
Continue;
end;
aSAPOPOLine := TSAPOPOLine.Create;
FList.AddObject(snumber, aSAPOPOLine);
aSAPOPOLine.FNumber := snumber;
aSAPOPOLine.FName := ADOTabXLS.FieldByName('短文本').AsString; // ExcelApp.Cells[irow, iColName].Value;
aSAPOPOLine.FDate := ADOTabXLS.FieldByName('交货日期').AsDateTime; // ExcelApp.Cells[irow, iColDate].Value;
aSAPOPOLine.FStock := ADOTabXLS.FieldByName('库存地点').AsString; // ExcelApp.Cells[irow, iColStock].Value;
aSAPOPOLine.FQty := ADOTabXLS.FieldByName('仍要交货(数量)').AsFloat;
aSAPOPOLine.FBillNo := ADOTabXLS.FieldByName('采购凭证').AsString; // ExcelApp.Cells[irow, iColBillNo].Value;
aSAPOPOLine.FLine := ADOTabXLS.FieldByName('项目').AsString; // ExcelApp.Cells[irow, iColLine].Value;
aSAPOPOLine.FPlanLine := ADOTabXLS.FieldByName('计划行').AsString; // ExcelApp.Cells[irow, iColPlanLine].Value;
aSAPOPOLine.FBillDate := ADOTabXLS.FieldByName('凭证日期').AsDateTime; // ExcelApp.Cells[irow, iColDate].Value;
aSAPOPOLine.FSupplier := ADOTabXLS.FieldByName('供应商/供货工厂').AsString; // ExcelApp.Cells[irow, iColDate].Value;
irow := irow + 1;
snumber := ADOTabXLS.FieldByName('物料').AsString; // ExcelApp.Cells[irow, iColNumber].Value;
ADOTabXLS.Next;
end;
ADOTabXLS.Close;
Conn.Connected := False;
finally
FreeAndNil(Conn);
FreeAndNil(ADOTabXLS);
end;
end;
end.
|
(******************************************************************************
PROYECTO FACTURACION ELECTRONICA
Copyright (C) 2010 - Bambu Code SA de CV - Ing. Luis Carrasco
Metodos para validar los diferentes tipos de datos y como deben de estar
especificados en el archivo XML.
Este archivo pertenece al proyecto de codigo abierto de Bambu Code:
http://bambucode.com/codigoabierto
La licencia de este codigo fuente se encuentra en:
http://github.com/bambucode/bc_facturaelectronica/blob/master/LICENCIA
******************************************************************************)
unit FacturaReglamentacion;
interface
type
TFEReglamentacion = class
/// <summary>Convierte el valor de moneda al formato de dinero requerido por el SAT
/// </summary>
/// <param name="Monto">Monto a convertir al formato aceptado por el SAT</param>
class function ComoMoneda(dMonto: Currency) : String;
class function ComoCadena(sCadena: String) : String;
class function ComoCantidad(dCantidad: Double) : String;
class function ComoFechaHora(dtFecha: TDateTime) : String;
class function ComoFechaAduanera(dtFecha: TDateTime) : String;
class function ComoTasaImpuesto(dTasa: Double) : String;
end;
implementation
uses SysUtils;
// Segun las reglas del SAT:
// "Se expresa en la forma aaaa-mm-ddThh:mm:ss, de acuerdo con la especificación ISO 8601"
class function TFEReglamentacion.ComoFechaHora(dtFecha: TDateTime) : String;
begin
Result := FormatDateTime('yyyy-mm-dd', dtFecha) + 'T' + FormatDateTime('hh:nn:ss', dtFecha);
end;
class function TFEReglamentacion.ComoFechaAduanera(dtFecha: TDateTime) : String;
begin
// Formato sacado del CFDv2.XSD: "Atributo requerido para expresar la fecha de expedición
// del documento aduanero que ampara la importación del bien. Se expresa en el formato aaaa-mm-dd"
Result := FormatDateTime('yyyy-mm-dd', dtFecha);
end;
class function TFEReglamentacion.ComoMoneda(dMonto: Currency) : String;
begin
Result:=FloatToStrF(dMonto,ffFixed,10,2);
end;
class function TFEReglamentacion.ComoTasaImpuesto(dTasa: Double) : String;
begin
Result:=FloatToStrF(dTasa,ffFixed,10,2);
end;
// Las cadenas usadas en el XML deben de escapar caracteres incorrectos
// Ref: http://dof.gob.mx/nota_detalle.php?codigo=5146699&fecha=15/06/2010
class function TFEReglamentacion.ComoCadena(sCadena: String) : String;
var
sCadenaEscapada: String;
begin
sCadenaEscapada:=sCadena;
// Las siguientes validaciones las omitimos ya que las mismas clases
// de Delphi lo hacen por nosotros:
// En el caso del & se deberá usar la secuencia &
// En el caso del “ se deberá usar la secuencia "
// En el caso del < se deberá usar la secuencia <
// En el caso del > se deberá usar la secuencia >
// En el caso del ‘ se deberá usar la secuencia '
// Si se presentan nuevas reglas para los Strings en el XML, incluirlas aqui
Result:=sCadenaEscapada;
end;
class function TFEReglamentacion.ComoCantidad(dCantidad: Double) : String;
begin
// Las cantidades cerradas las regresamos sin decimales
// las que tienen fracciones con 2 digitos decimales...
if Frac(dCantidad) > 0 then
Result:=FloatToStrF(dCantidad,ffFixed,10,2)
else
Result:=IntToStr(Round(dCantidad));
end;
end.
|
{***************************************************************************}
{ }
{ DelphiUIAutomation }
{ }
{ Copyright 2015-16 JHC Systems Limited }
{ }
{***************************************************************************}
{ }
{ 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 DelphiUIAutomation.TabItem;
interface
uses
DelphiUIAutomation.Base,
UIAutomationClient_TLB;
type
IAutomationTabItem = interface (IAutomationBase)
['{6FC85416-87FD-4FE6-91C5-3D465F73DBD5}']
/// <summary>
/// Selects this tabitem
/// </summary>
procedure Select;
end;
/// <summary>
/// Represents a tab item
/// </summary>
TAutomationTabItem = class (TAutomationBase, IAutomationTabItem)
private
FSelectionItemPattern: IUIAutomationSelectionItemPattern;
public
/// <summary>
/// Selects this tabitem
/// </summary>
procedure Select;
/// <summary>
/// Constructor for tab items.
/// </summary>
constructor Create(element : IUIAutomationElement); override;
end;
implementation
uses
DelphiUIAutomation.Automation,
DelphiUIAutomation.PatternIDs;
{ TAutomationTabItem }
constructor TAutomationTabItem.Create(element: IUIAutomationElement);
begin
inherited;
FSelectionItemPattern := GetSelectionItemPattern;
end;
procedure TAutomationTabItem.Select;
begin
FSelectionItemPattern.Select;
end;
end.
|
unit TSTOPackageList;
Interface
Uses Classes, SysUtils, HsInterfaceEx,
TSTODlcIndex, TSTOZero.Bin;
Type
ITSTOPackageNode = Interface(IInterfaceEx)
['{4B61686E-29A0-2112-BC4D-DD271C9712F2}']
Function GetPlatform() : Widestring;
Function GetMinVersion() : Widestring;
Function GetTier() : Widestring;
Function GetVersion() : Widestring;
Function GetFileName() : Widestring;
Function GetLanguage() : Widestring;
Function GetZeroFile() : IBinZeroFile;
Function GetFileSize() : Integer;
Function GetFileExist() : Boolean;
Procedure SetFileExist(Const AExist : Boolean);
Property PkgPlatform : Widestring Read GetPlatform;
Property MinVersion : Widestring Read GetMinVersion;
Property Tier : Widestring Read GetTier;
Property Version : Widestring Read GetVersion;
Property FileName : Widestring Read GetFileName;
Property Language : Widestring Read GetLanguage;
Property ZeroFile : IBinZeroFile Read GetZeroFile;
Property FileSize : Integer Read GetFileSize;
Property FileExist : Boolean Read GetFileExist Write SetFileExist;
End;
ITSTOPackageNodes = Interface(IInterfaceListEx)
['{4B61686E-29A0-2112-933E-646D8525F8F1}']
Function Get(Index : Integer) : ITSTOPackageNode;
Procedure Put(Index : Integer; Const Item : ITSTOPackageNode);
Function Add(Const AItem : ITSTOPackageNode) : Integer; OverLoad;
Procedure Sort();
Property Items[Index : Integer] : ITSTOPackageNode Read Get Write Put; Default;
End;
ITSTOTierPackageNode = Interface(IInterfaceEx)
['{4B61686E-29A0-2112-8E51-2E83B9C72A7B}']
Function GetTierName() : String;
Procedure SetTierName(Const ATierName : String);
Function GetOnLoadPackage() : TNotifyEvent;
Procedure SetOnLoadPackage(Const AOnLoadPackage : TNotifyEvent);
Function GetPackages() : ITSTOPackageNodes;
Property TierName : String Read GetTierName Write SetTierName;
Property OnLoadPackage : TNotifyEvent Read GetOnLoadPackage Write SetOnLoadPackage;
Property Packages : ITSTOPackageNodes Read GetPackages;
End;
ITSTOTierPackageNodes = Interface(IInterfaceListEx)
['{4B61686E-29A0-2112-B41A-11EF807627D2}']
Function Get(Index : Integer) : ITSTOTierPackageNode;
Procedure Put(Index : Integer; Const Item : ITSTOTierPackageNode);
Function Add() : ITSTOTierPackageNode; OverLoad;
Function Add(Const AItem : ITSTOTierPackageNode) : Integer; OverLoad;
Function IndexOf(Const ATierName: String) : Integer;
Property Items[Index : Integer] : ITSTOTierPackageNode Read Get Write Put; Default;
End;
ITSTOPlatformPackageNode = Interface;
TLoadTierPkg = Procedure(APlatform : ITSTOPlatformPackageNode; ATier : ITSTOTierPackageNode) Of Object;
ITSTOPlatformPackageNode = Interface(IInterfaceEx)
['{4B61686E-29A0-2112-8C64-EF6DDD860AFE}']
Function GetPlatformName() : String;
Procedure SetPlatformName(Const APlatformName : String);
Function GetOnLoadTier() : TNotifyEvent;
Procedure SetOnLoadTier(Const AOnLoadTier : TNotifyEvent);
Function GetOnLoadTierPkg() : TLoadTierPkg;
Procedure SetOnLoadTierPkg(Const AOnLoadTierPkg : TLoadTierPkg);
Function GetTiers() : ITSTOTierPackageNodes;
Property PlatformName : String Read GetPlatformName Write SetPlatformName;
Property OnLoadTier : TNotifyEvent Read GetOnLoadTier Write SetOnLoadTier;
Property OnLoadTierPkg : TLoadTierPkg Read GetOnLoadTierPkg Write SetOnLoadTierPkg;
Property Tiers : ITSTOTierPackageNodes Read GetTiers;
End;
ITSTOPlatformPackageNodes = Interface(IInterfaceListEx)
['{4B61686E-29A0-2112-974A-A19BD02C90C4}']
Function Get(Index : Integer) : ITSTOPlatformPackageNode;
Procedure Put(Index : Integer; Const Item : ITSTOPlatformPackageNode);
Function Add() : ITSTOPlatformPackageNode; OverLoad;
Function Add(Const AItem : ITSTOPlatformPackageNode) : Integer; OverLoad;
Procedure Load(APackages : ITSTOXmlPackageList); OverLoad;
Procedure Load(AXmlPackages : String); OverLoad;
Property Items[Index : Integer] : ITSTOPlatformPackageNode Read Get Write Put; Default;
End;
(******************************************************************************)
TTSTOPackageNode = Class(TInterfacedObjectEx, ITSTOPackageNode)
Private
FPlatform : Widestring;
FMinVersion : Widestring;
FTier : Widestring;
FVersion : Widestring;
FFileName : Widestring;
FLanguage : Widestring;
FZeroFile : IBinZeroFile;
FFileSize : Integer;
FFileExist : Boolean;
Protected
Function GetPlatform() : Widestring;
Function GetMinVersion() : Widestring;
Function GetTier() : Widestring;
Function GetVersion() : Widestring;
Function GetFileName() : Widestring;
Function GetLanguage() : Widestring;
Function GetZeroFile() : IBinZeroFile;
Function GetFileSize() : Integer;
Function GetFileExist() : Boolean;
Procedure SetFileExist(Const AExist : Boolean);
Public
Constructor Create(ANode : ITSTOXmlPackage); ReIntroduce;
End;
TTSTOPackageNodes = Class(TInterfaceListEx, ITSTOPackageNodes)
Private
Function InternalSort(Item1, Item2 : IInterfaceEx) : Integer;
Protected
Function Get(Index : Integer) : ITSTOPackageNode; OverLoad;
Procedure Put(Index : Integer; Const Item : ITSTOPackageNode); OverLoad;
Function Add(Const AItem : ITSTOPackageNode) : Integer; OverLoad;
Procedure Sort();
End;
TTSTOTierPackageNode = Class(TInterfacedObjectEx, ITSTOTierPackageNode)
Private
FTierName : String;
FOnLoadPackage : TNotifyEvent;
FPackages : ITSTOPackageNodes;
Protected
Function GetTierName() : String;
Procedure SetTierName(Const ATierName : String);
Function GetOnLoadPackage() : TNotifyEvent;
Procedure SetOnLoadPackage(Const AOnLoadPackage : TNotifyEvent);
Function GetPackages() : ITSTOPackageNodes;
Procedure Clear();
Public
Destructor Destroy(); OverRide;
End;
TTierPackageNodes = Class(TInterfaceListEx, ITSTOTierPackageNodes)
Protected
Function GetItemClass() : TInterfacedObjectExClass; OverRide;
Function Get(Index : Integer) : ITSTOTierPackageNode; OverLoad;
Procedure Put(Index : Integer; Const Item : ITSTOTierPackageNode); OverLoad;
Function Add() : ITSTOTierPackageNode; ReIntroduce; OverLoad;
Function Add(Const AItem : ITSTOTierPackageNode) : Integer; ReIntroduce; OverLoad;
Function IndexOf(Const ATierName: String) : Integer; ReIntroduce; OverLoad;
Property Items[Index : Integer] : ITSTOTierPackageNode Read Get Write Put; Default;
End;
TTSTOPlatformPackageNode = Class(TInterfacedObjectEx, ITSTOPlatformPackageNode)
Private
FPlatformName : String;
FOnLoadTier : TNotifyEvent;
FOnLoadTierPkg : TLoadTierPkg;
FTiers : ITSTOTierPackageNodes;
Procedure DoOnLoadPackage(Sender : TObject);
Protected
Function GetPlatformName() : String;
Procedure SetPlatformName(Const APlatformName : String);
Function GetOnLoadTier() : TNotifyEvent;
Procedure SetOnLoadTier(Const AOnLoadTier : TNotifyEvent);
Function GetOnLoadTierPkg() : TLoadTierPkg;
Procedure SetOnLoadTierPkg(Const AOnLoadTierPkg : TLoadTierPkg);
Function GetTiers() : ITSTOTierPackageNodes;
Procedure Clear();
Public
Destructor Destroy(); OverRide;
End;
TTSTOPlatformPackageNodes = Class(TInterfaceListEx, ITSTOPlatformPackageNodes)
Private
FXmlData : String;
Procedure DoOnLoadTier(Sender : TObject);
Procedure DoOnLoadTierPkg(APlatform : ITSTOPlatformPackageNode; ATier : ITSTOTierPackageNode);
Protected
Function GetItemClass() : TInterfacedObjectExClass; OverRide;
Function Get(Index : Integer) : ITSTOPlatformPackageNode; OverLoad;
Procedure Put(Index : Integer; Const Item : ITSTOPlatformPackageNode); OverLoad;
Function Add() : ITSTOPlatformPackageNode; ReIntroduce; OverLoad;
Function Add(Const AItem : ITSTOPlatformPackageNode) : Integer; ReIntroduce; OverLoad;
Function IndexOf(Const APlatformName : String) : Integer; ReIntroduce; OverLoad;
Procedure Load(APackages : ITSTOXmlPackageList); OverLoad;
Procedure Load(AXmlPackages : String); OverLoad;
Property Items[Index : Integer] : ITSTOPlatformPackageNode Read Get Write Put; Default;
End;
Implementation
Uses XmlDoc, Dialogs,
HsXmlDocEx;
Constructor TTSTOPackageNode.Create(ANode : ITSTOXmlPackage);
Begin
InHerited Create(True);
FPlatform := ANode.PkgPlatform;
FMinVersion := ANode.MinVersion;
FTier := ANode.Tier;
FVersion := IntToStr(ANode.Version.Val);
FFileName := ANode.FileName.Path + '\' + ANode.FileName.FileName;
FLanguage := ANode.Language.Val;
FFileSize := ANode.FileSize.Val;
End;
Function TTSTOPackageNode.GetPlatform() : Widestring;
Begin
Result := FPlatform;
End;
Function TTSTOPackageNode.GetMinVersion() : Widestring;
Begin
Result := FMinVersion;
End;
Function TTSTOPackageNode.GetTier() : Widestring;
Begin
Result := FTier;
End;
Function TTSTOPackageNode.GetVersion() : Widestring;
Begin
Result := FVersion;
End;
Function TTSTOPackageNode.GetFileName() : Widestring;
Begin
Result := FFileName;
End;
Function TTSTOPackageNode.GetLanguage() : Widestring;
Begin
Result := FLanguage;
End;
Function TTSTOPackageNode.GetZeroFile() : IBinZeroFile;
Begin
If Not Assigned(FZeroFile) Then
FZeroFile := TBinZeroFile.CreateBinZeroFile();
Result := FZeroFile;
End;
Function TTSTOPackageNode.GetFileSize() : Integer;
Begin
Result := FFileSize;
End;
Function TTSTOPackageNode.GetFileExist() : Boolean;
Begin
Result := FFileExist;
End;
Procedure TTSTOPackageNode.SetFileExist(Const AExist : Boolean);
Begin
FFileExist := AExist;
End;
Function TTSTOPackageNodes.InternalSort(Item1, Item2 : IInterfaceEx) : Integer;
Var lItem1, lItem2 : ITSTOPackageNode;
Begin
If Supports(Item1, ITSTOPackageNode, lItem1) And
Supports(Item2, ITSTOPackageNode, lItem2) Then
Result := CompareText(ExtractFileName(lItem1.FileName), ExtractFileName(lItem2.FileName))
Else
Raise Exception.Create('Invalid interface type');
End;
Procedure TTSTOPackageNodes.Sort();
Begin
InHerited Sort(InternalSort);
End;
Function TTSTOPackageNodes.Get(Index : Integer) : ITSTOPackageNode;
Begin
Result := InHerited Items[Index] As ITSTOPackageNode;
End;
Procedure TTSTOPackageNodes.Put(Index : Integer; Const Item : ITSTOPackageNode);
Var lItem : IInterfaceEx;
Begin
If Supports(Item, IInterfaceEx, lItem) Then
InHerited Items[Index] := lItem;
End;
Function TTSTOPackageNodes.Add(Const AItem : ITSTOPackageNode) : Integer;
Var lItem : IInterfaceEx;
Begin
If Supports(AItem, IInterfaceEx, lItem) Then
Result := InHerited Add(lItem)
Else
Result := -1;
End;
Procedure TTSTOTierPackageNode.Clear();
Begin
FTierName := '';
End;
Destructor TTSTOTierPackageNode.Destroy();
Begin
FPackages := Nil;
InHerited Destroy();
End;
Function TTSTOTierPackageNode.GetTierName() : String;
Begin
Result := FTierName;
End;
Procedure TTSTOTierPackageNode.SetTierName(Const ATierName : String);
Begin
FTierName := ATierName;
End;
Function TTSTOTierPackageNode.GetOnLoadPackage() : TNotifyEvent;
Begin
Result := FOnLoadPackage;
End;
Procedure TTSTOTierPackageNode.SetOnLoadPackage(Const AOnLoadPackage : TNotifyEvent);
Begin
FOnLoadPackage := AOnLoadPackage;
End;
Function TTSTOTierPackageNode.GetPackages() : ITSTOPackageNodes;
Begin
If Not Assigned(FPackages) Then
Begin
FPackages := TTSTOPackageNodes.Create();
If Assigned(FOnLoadPackage) Then
FOnLoadPackage(Self);
End;
Result := FPackages;
End;
Function TTierPackageNodes.GetItemClass() : TInterfacedObjectExClass;
Begin
Result := TTSTOTierPackageNode;
End;
Function TTierPackageNodes.Get(Index : Integer) : ITSTOTierPackageNode;
Begin
Result := InHerited Items[Index] As ITSTOTierPackageNode;
End;
Procedure TTierPackageNodes.Put(Index : Integer; Const Item : ITSTOTierPackageNode);
Begin
InHerited Items[Index] := Item;
End;
Function TTierPackageNodes.Add() : ITSTOTierPackageNode;
Begin
Result := InHerited Add() As ITSTOTierPackageNode;
End;
Function TTierPackageNodes.Add(Const AItem : ITSTOTierPackageNode) : Integer;
Begin
Result := InHerited Add(AItem);
End;
Function TTierPackageNodes.IndexOf(Const ATierName : String) : Integer;
Var X : Integer;
Begin
Result := -1;
For X := 0 To Count - 1 Do
If SameText(Items[X].TierName, ATierName) Then
Begin
Result := X;
Break;
End;
End;
Destructor TTSTOPlatformPackageNode.Destroy();
Begin
FTiers := Nil;
InHerited Destroy();
End;
Procedure TTSTOPlatformPackageNode.DoOnLoadPackage(Sender : TObject);
Var lTier : ITSTOTierPackageNode;
Begin
If Supports(Sender, ITSTOTierPackageNode, lTier) And Assigned(FOnLoadTierPkg) Then
FOnLoadTierPkg(Self, lTier);
End;
Procedure TTSTOPlatformPackageNode.Clear();
Begin
FPlatformName := '';
End;
Function TTSTOPlatformPackageNode.GetPlatformName() : String;
Begin
Result := FPlatformName;
End;
Procedure TTSTOPlatformPackageNode.SetPlatformName(Const APlatformName : String);
Begin
FPlatformName := APlatformName;
End;
Function TTSTOPlatformPackageNode.GetOnLoadTier() : TNotifyEvent;
Begin
Result := FOnLoadTier;
End;
Procedure TTSTOPlatformPackageNode.SetOnLoadTier(Const AOnLoadTier : TNotifyEvent);
Begin
FOnLoadTier := AOnLoadTier;
End;
Function TTSTOPlatformPackageNode.GetOnLoadTierPkg() : TLoadTierPkg;
Begin
Result := FOnLoadTierPkg;
End;
Procedure TTSTOPlatformPackageNode.SetOnLoadTierPkg(Const AOnLoadTierPkg : TLoadTierPkg);
Begin
FOnLoadTierPkg := AOnLoadTierPkg;
End;
Function TTSTOPlatformPackageNode.GetTiers() : ITSTOTierPackageNodes;
Var X : Integer;
Begin
If Not Assigned(FTiers) Then
Begin
FTiers := TTierPackageNodes.Create();
If Assigned(FOnLoadTier) Then
Begin
FOnLoadTier(Self);
For X := 0 To FTiers.Count - 1 Do
FTiers[X].OnLoadPackage := DoOnLoadPackage;
End;
End;
Result := FTiers;
End;
Function TTSTOPlatformPackageNodes.GetItemClass() : TInterfacedObjectExClass;
Begin
Result := TTSTOPlatformPackageNode;
End;
Function TTSTOPlatformPackageNodes.Get(Index : Integer) : ITSTOPlatformPackageNode;
Begin
Result := InHerited Items[Index] As ITSTOPlatformPackageNode;
End;
Procedure TTSTOPlatformPackageNodes.Put(Index : Integer; Const Item : ITSTOPlatformPackageNode);
Begin
InHerited Items[Index] := Item;
End;
Procedure TTSTOPlatformPackageNodes.DoOnLoadTier(Sender : TObject);
Var lPlatform : ITSTOPlatformPackageNode;
lNodes : IXmlNodeListEx;
X : Integer;
Begin
If Supports(Sender, ITSTOPlatformPackageNode, lPlatform) Then
Try
With lPlatform Do
Begin
lNodes := LoadXmlData(FXmlData).SelectNodes(
'Package[@platform="' + PlatformName + '"][' +
' not(@tier = following-sibling::Package[@platform="' + PlatformName + '"]/@tier)' +
']/@tier'
);
If Assigned(lNodes) Then
Try
For X := 0 To lNodes.Count - 1 Do
lPlatform.Tiers.Add().TierName := lNodes[X].Text;
Finally
lNodes := Nil;
End;
End;
Finally
lPlatform := Nil;
End;
End;
Procedure TTSTOPlatformPackageNodes.DoOnLoadTierPkg(APlatform : ITSTOPlatformPackageNode; ATier : ITSTOTierPackageNode);
Var lXmlNodeCls : TXmlNodeClass;
lNodes : IXmlNodeListEx;
lXmlNode : ITSTOXmlPackage;
lPkg : ITSTOPackageNode;
X : Integer;
Begin
lXmlNodeCls := Nil;
With (NewDlcIndex() As IXmlNodeAccess) Do
For X := Low(ChildNodeClasses) To High(ChildNodeClasses) Do
Begin
If SameText(ChildNodeClasses[X].NodeName, 'Package') Then
Begin
lXmlNodeCls := ChildNodeClasses[X].NodeClass;
Break;
End;
End;
If Assigned(lXmlNodeCls) Then
Begin
With APlatform, ATier Do
Begin
lNodes := LoadXmlData(FXmlData).SelectNodes(
'Package[@platform="' + PlatformName +
'" and @tier="' + TierName + '"]'
);
If Assigned(lNodes) Then
Try
For X := 0 To lNodes.Count - 1 Do
Begin
lXmlNode := lXmlNodeCls.Create(
lNodes[X].DOMNode, Nil,
(lNodes[X].OwnerDocument As IXmlDocumentAccess).DocumentObject
) As ITSTOXmlPackage;
lPkg := TTSTOPackageNode.Create(lXmlNode);
//@@Kahn lPkg.FileExist := FileExists(FPrj.Settings.DLCPath + lPkg.FileName);
ATier.Packages.Add(lPkg);
End;
Finally
lNodes := Nil;
End;
End;
End;
End;
Function TTSTOPlatformPackageNodes.Add() : ITSTOPlatformPackageNode;
Begin
Result := InHerited Add() As ITSTOPlatformPackageNode;
End;
Function TTSTOPlatformPackageNodes.Add(Const AItem : ITSTOPlatformPackageNode) : Integer;
Begin
Result := InHerited Add(AItem);
End;
Function TTSTOPlatformPackageNodes.IndexOf(Const APlatformName : String) : Integer;
Var X : Integer;
Begin
Result := -1;
For X := 0 To Count - 1 Do
If SameText(Items[X].PlatformName, APlatformName) Then
Begin
Result := X;
Break;
End;
End;
Procedure TTSTOPlatformPackageNodes.Load(APackages : ITSTOXmlPackageList);
Var X : Integer;
lNodes : IXmlNodeListEx;
Begin
Load(APackages.OwnerDocument.Xml.Text);
Exit;
FXmlData := APackages.OwnerDocument.Xml.Text;
lNodes := LoadXmlData(FXmlData).SelectNodes(
'Package[not(@platform = following-sibling::Package/@platform)]/@platform'
);
If Assigned(lNodes) Then
Try
For X := 0 To lNodes.Count - 1 Do
Begin
With Add() Do
Begin
PlatformName := lNodes[X].Text;
OnLoadTier := DoOnLoadTier;
OnLoadTierPkg := DoOnLoadTierPkg;
End;
End;
Finally
lNodes := Nil;
End;
End;
Procedure TTSTOPlatformPackageNodes.Load(AXmlPackages : String);
Var lXml : IXmlDocumentEx;
lNodes : IXmlNodeListEx;
X : Integer;
Begin
lXml := LoadXmlData(AXmlPackages);
Try
//Remove useless packages
lNodes := lXml.SelectNodes('(//InitialPackages | //TutorialPackages)');
If Assigned(lNodes) Then
Try
For X := 0 To lNodes.Count - 1 Do
With lNodes[X] Do
DOMNode.parentNode.removeChild(DOMNode);
Finally
lNodes := Nil;
End;
//Remove useless attributes from remaining packages
lNodes := lXml.SelectNodes('//Package');
If Assigned(lNodes) Then
Try
For X := 0 To lNodes.Count - 1 Do
With lNodes[X].DOMNode.attributes Do
Begin
removeNamedItem('unzip');
removeNamedItem('xml');
removeNamedItem('type');
removeNamedItem('ignore');
End;
Finally
lNodes := Nil;
End;
//Remove useless nodes from remaining packages
lNodes := lXml.SelectNodes(
'(' +
' //LocalDir | ' + //FileSize | ' +
' //IndexFileCRC | //IndexFileSig' +
')'
);
If Assigned(lNodes) Then
Try
For X := 0 To lNodes.Count - 1 Do
With lNodes[X] Do
DOMNode.parentNode.removeChild(DOMNode);
Finally
lNodes := Nil;
End;
lNodes := lXml.SelectNodes(
'Package[not(@platform = following-sibling::Package/@platform)]/@platform'
);
If Assigned(lNodes) Then
Try
For X := 0 To lNodes.Count - 1 Do
Begin
With Add() Do
Begin
PlatformName := lNodes[X].Text;
OnLoadTier := DoOnLoadTier;
OnLoadTierPkg := DoOnLoadTierPkg;
End;
End;
Finally
lNodes := Nil;
End;
FXmlData := lXml.Xml.Text;
Finally
lXml := Nil;
End;
End;
Initialization
RegisterInterface('ITSTOPackageNode', ITSTOPackageNode);
RegisterInterface('ITSTOPackageNodes', ITSTOPackageNodes);
RegisterInterface('ITSTOTierPackageNode', ITSTOTierPackageNode);
RegisterInterface('ITSTOTierPackageNodes', ITSTOTierPackageNodes);
RegisterInterface('ITSTOPlatformPackageNode', ITSTOPlatformPackageNode);
RegisterInterface('ITSTOPlatformPackageNodes', ITSTOPlatformPackageNodes);
End.
|
unit ujczxingbarcodescan;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, {And_jni_Bridge,} AndroidWidget;
type
TZXingCodeFormat = (zxfUPC_A, zxfUPC_E, zxfEAN_8,zxfEAN_13, zxfRSS_14, //Product Codes
zxfCODE_39, zxfCODE_93, zxfCODE_128, zxfITF, zxfRSS_EXPANDED, //Other 1D
zxfQR_CODE, zxfDATA_MATRIX, zxfPDF_417); //2D codes
{Draft Component code by "LAMW: Lazarus Android Module Wizard" [3/12/2023 20:23:51]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jControl template}
jcZXingBarcodeScan = class(jControl)
private
FPrompt: string;
FCameraId: integer;
FBeepEnabled: boolean;
FOrientationLocked: boolean;
FBarcodeFormat: TZXingCodeFormat;
FRequestCodeForResult: integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
function jCreate(): jObject;
procedure jFree();
procedure ScanForResult(_barcodeFormat: TZXingCodeFormat; _requestCodeForResult: integer); overload;
procedure ScanForResult(_barcodeFormat: TZXingCodeFormat); overload;
procedure ScanForResult(); overload;
function GetContentFromResult(_intentData: jObject): string;
procedure SetPrompt(_msg: string);
procedure SetCameraId(_id: integer);
procedure SetBeepEnabled(_value: boolean);
procedure SetOrientationLocked(_value: boolean);
procedure SetBarcodeFormat(_barcodeFormat: TZXingCodeFormat);
procedure SetRequestCodeForResult(_requestCode: integer);
published
property Prompt: string read FPrompt write SetPrompt;
property CameraId: integer read FCameraId write SetCameraId;
property BeepEnabled: boolean read FBeepEnabled write SetBeepEnabled;
property OrientationLocked: boolean read FOrientationLocked write SetOrientationLocked;
property BarcodeFormat: TZXingCodeFormat read FBarcodeFormat write SetBarcodeFormat;
property RequestCodeForResult: integer read FRequestCodeForResult write SetRequestCodeForResult;
end;
function jcZXingBarcodeScan_jCreate(env: PJNIEnv;_self: int64; this: jObject): jObject;
procedure jcZXingBarcodeScan_jFree(env: PJNIEnv; _jczxingbarcodescan: JObject);
procedure jcZXingBarcodeScan_ScanForResult(env: PJNIEnv; _jczxingbarcodescan: JObject; _barcodeFormat: integer; _requestCodeForResult: integer);
function jcZXingBarcodeScan_GetContentFromResult(env: PJNIEnv; _jczxingbarcodescan: JObject; _requestCode: integer; _resultCode: integer; _intentData: jObject): string;
procedure jcZXingBarcodeScan_SetPrompt(env: PJNIEnv; _jczxingbarcodescan: JObject; _msg: string);
procedure jcZXingBarcodeScan_SetCameraId(env: PJNIEnv; _jczxingbarcodescan: JObject; _id: integer);
procedure jcZXingBarcodeScan_SetBeepEnabled(env: PJNIEnv; _jczxingbarcodescan: JObject; _value: boolean);
procedure jcZXingBarcodeScan_SetOrientationLocked(env: PJNIEnv; _jczxingbarcodescan: JObject; _value: boolean);
procedure jcZXingBarcodeScan_SetBarcodeFormat(env: PJNIEnv; _jczxingbarcodescan: JObject; _barcodeFormat: integer);
procedure jcZXingBarcodeScan_SetRequestCodeForResult(env: PJNIEnv; _jczxingbarcodescan: JObject; _requestCode: integer);
implementation
{--------- jcZXingBarcodeScan --------------}
constructor jcZXingBarcodeScan.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//your code here....
FPrompt:= 'Scanning...';
FBarcodeFormat:= zxfQR_CODE;
FRequestCodeForResult:= 49374; //default
FCameraId:= 0;
FBeepEnabled:= False;
FOrientationLocked:= False;
end;
destructor jcZXingBarcodeScan.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jcZXingBarcodeScan.Init;
begin
if FInitialized then Exit;
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jCreate(); //jSelf !
if FjObject = nil then exit;
if FCameraId <> 0 then
jcZXingBarcodeScan_SetCameraId(gApp.jni.jEnv, FjObject, FCameraId);
if FBeepEnabled <> False then
jcZXingBarcodeScan_SetBeepEnabled(gApp.jni.jEnv, FjObject, FBeepEnabled);
if FOrientationLocked <> False then
jcZXingBarcodeScan_SetOrientationLocked(gApp.jni.jEnv, FjObject, FOrientationLocked);
if FPrompt <> 'Scanning...' then
jcZXingBarcodeScan_SetPrompt(gApp.jni.jEnv, FjObject, FPrompt);
if FBarcodeFormat <> zxfQR_CODE then
jcZXingBarcodeScan_SetBarcodeFormat(gApp.jni.jEnv, FjObject, Ord(FBarcodeFormat));
if FRequestCodeForResult <> 49374 then
jcZXingBarcodeScan_SetRequestCodeForResult(gApp.jni.jEnv, FjObject, FRequestCodeForResult);
FInitialized:= True;
end;
function jcZXingBarcodeScan.jCreate(): jObject;
begin
Result:= jcZXingBarcodeScan_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
end;
procedure jcZXingBarcodeScan.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jcZXingBarcodeScan_jFree(gApp.jni.jEnv, FjObject);
end;
procedure jcZXingBarcodeScan.ScanForResult(_barcodeFormat: TZXingCodeFormat; _requestCodeForResult: integer);
begin
//in designing component state: set value here...
FBarcodeFormat:= _barcodeFormat;
FRequestCodeForResult:= _requestCodeForResult;
if FInitialized then
jcZXingBarcodeScan_ScanForResult(gApp.jni.jEnv, FjObject, Ord(FBarcodeFormat), FRequestCodeForResult);
end;
procedure jcZXingBarcodeScan.ScanForResult(_barcodeFormat: TZXingCodeFormat);
begin
//in designing component state: set value here...
FBarcodeFormat:= _barcodeFormat;
if FInitialized then
jcZXingBarcodeScan_ScanForResult(gApp.jni.jEnv, FjObject, Ord(FBarcodeFormat), FRequestCodeForResult);
end;
procedure jcZXingBarcodeScan.ScanForResult();
begin
//in designing component state: set value here...
if FInitialized then
jcZXingBarcodeScan_ScanForResult(gApp.jni.jEnv, FjObject, Ord(FBarcodeFormat), FRequestCodeForResult);
end;
function jcZXingBarcodeScan.GetContentFromResult( _intentData: jObject): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jcZXingBarcodeScan_GetContentFromResult(gApp.jni.jEnv, FjObject, FRequestCodeForResult , Ord(RESULT_OK) ,_intentData);
end;
procedure jcZXingBarcodeScan.SetPrompt(_msg: string);
begin
//in designing component state: set value here...
FPrompt:= _msg;
if FInitialized then
jcZXingBarcodeScan_SetPrompt(gApp.jni.jEnv, FjObject, _msg);
end;
procedure jcZXingBarcodeScan.SetCameraId(_id: integer);
begin
//in designing component state: set value here...
FCameraId:= _id;
if FInitialized then
jcZXingBarcodeScan_SetCameraId(gApp.jni.jEnv, FjObject, _id);
end;
procedure jcZXingBarcodeScan.SetBeepEnabled(_value: boolean);
begin
//in designing component state: set value here...
FBeepEnabled:= _value;
if FInitialized then
jcZXingBarcodeScan_SetBeepEnabled(gApp.jni.jEnv, FjObject, _value);
end;
procedure jcZXingBarcodeScan.SetOrientationLocked(_value: boolean);
begin
//in designing component state: set value here...
FOrientationLocked:= _value;
if FInitialized then
jcZXingBarcodeScan_SetOrientationLocked(gApp.jni.jEnv, FjObject, _value);
end;
procedure jcZXingBarcodeScan.SetBarcodeFormat(_barcodeFormat: TZXingCodeFormat);
begin
//in designing component state: set value here...
FBarcodeFormat:= _barcodeFormat;
if FInitialized then
jcZXingBarcodeScan_SetBarcodeFormat(gApp.jni.jEnv, FjObject, Ord(FBarcodeFormat));
end;
procedure jcZXingBarcodeScan.SetRequestCodeForResult(_requestCode: integer);
begin
//in designing component state: set value here...
FRequestCodeForResult:= _requestCode;
if FInitialized then
jcZXingBarcodeScan_SetRequestCodeForResult(gApp.jni.jEnv, FjObject, FRequestCodeForResult);
end;
{-------- jcZXingBarcodeScan_JNI_Bridge ----------}
function jcZXingBarcodeScan_jCreate(env: PJNIEnv;_self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
Result := nil;
if (env = nil) or (this = nil) then exit;
jCls:= Get_gjClass(env);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'jcZXingBarcodeScan_jCreate', '(J)Ljava/lang/Object;');
if jMethod = nil then goto _exceptionOcurred;
jParams[0].j:= _self;
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
_exceptionOcurred: if jni_ExceptionOccurred(env) then result := nil;
end;
procedure jcZXingBarcodeScan_jFree(env: PJNIEnv; _jczxingbarcodescan: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
if (env = nil) or (_jczxingbarcodescan = nil) then exit;
jCls:= env^.GetObjectClass(env, _jczxingbarcodescan);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
env^.CallVoidMethod(env, _jczxingbarcodescan, jMethod);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: jni_ExceptionOccurred(env);
end;
function jcZXingBarcodeScan_GetContentFromResult(env: PJNIEnv; _jczxingbarcodescan: JObject; _requestCode: integer; _resultCode: integer; _intentData: jObject): string;
var
jStr: JString;
//jBoo: JBoolean;
jParams: array[0..2] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
if (env = nil) or (_jczxingbarcodescan = nil) then exit;
jCls:= env^.GetObjectClass(env, _jczxingbarcodescan);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'GetContentFromResult', '(IILandroid/content/Intent;)Ljava/lang/String;');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
jParams[0].i:= _requestCode;
jParams[1].i:= _resultCode;
jParams[2].l:= _intentData;
jStr:= env^.CallObjectMethodA(env, _jczxingbarcodescan, jMethod, @jParams);
Result:= GetPStringAndDeleteLocalRef(env, jStr);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: jni_ExceptionOccurred(env);
end;
procedure jcZXingBarcodeScan_SetPrompt(env: PJNIEnv; _jczxingbarcodescan: JObject; _msg: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
if (env = nil) or (_jczxingbarcodescan = nil) then exit;
jCls:= env^.GetObjectClass(env, _jczxingbarcodescan);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'SetPrompt', '(Ljava/lang/String;)V');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
jParams[0].l:= env^.NewStringUTF(env, PChar(_msg));
env^.CallVoidMethodA(env, _jczxingbarcodescan, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: jni_ExceptionOccurred(env);
end;
procedure jcZXingBarcodeScan_SetCameraId(env: PJNIEnv; _jczxingbarcodescan: JObject; _id: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
if (env = nil) or (_jczxingbarcodescan = nil) then exit;
jCls:= env^.GetObjectClass(env, _jczxingbarcodescan);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'SetCameraId', '(I)V');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
jParams[0].i:= _id;
env^.CallVoidMethodA(env, _jczxingbarcodescan, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: jni_ExceptionOccurred(env);
end;
procedure jcZXingBarcodeScan_SetBeepEnabled(env: PJNIEnv; _jczxingbarcodescan: JObject; _value: boolean);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
if (env = nil) or (_jczxingbarcodescan = nil) then exit;
jCls:= env^.GetObjectClass(env, _jczxingbarcodescan);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'SetBeepEnabled', '(Z)V');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
jParams[0].z:= JBool(_value);
env^.CallVoidMethodA(env, _jczxingbarcodescan, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: jni_ExceptionOccurred(env);
end;
procedure jcZXingBarcodeScan_SetOrientationLocked(env: PJNIEnv; _jczxingbarcodescan: JObject; _value: boolean);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
if (env = nil) or (_jczxingbarcodescan = nil) then exit;
jCls:= env^.GetObjectClass(env, _jczxingbarcodescan);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'SetOrientationLocked', '(Z)V');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
jParams[0].z:= JBool(_value);
env^.CallVoidMethodA(env, _jczxingbarcodescan, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: jni_ExceptionOccurred(env);
end;
procedure jcZXingBarcodeScan_SetBarcodeFormat(env: PJNIEnv; _jczxingbarcodescan: JObject; _barcodeFormat: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
if (env = nil) or (_jczxingbarcodescan = nil) then exit;
jCls:= env^.GetObjectClass(env, _jczxingbarcodescan);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'SetBarcodeFormat', '(I)V');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
jParams[0].i:= _barcodeFormat;
env^.CallVoidMethodA(env, _jczxingbarcodescan, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: jni_ExceptionOccurred(env);
end;
procedure jcZXingBarcodeScan_SetRequestCodeForResult(env: PJNIEnv; _jczxingbarcodescan: JObject; _requestCode: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
if (env = nil) or (_jczxingbarcodescan = nil) then exit;
jCls:= env^.GetObjectClass(env, _jczxingbarcodescan);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'SetRequestCodeForResult', '(I)V');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
jParams[0].i:= _requestCode;
env^.CallVoidMethodA(env, _jczxingbarcodescan, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: jni_ExceptionOccurred(env);
end;
procedure jcZXingBarcodeScan_ScanForResult(env: PJNIEnv; _jczxingbarcodescan: JObject; _barcodeFormat: integer; _requestCodeForResult: integer);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
if (env = nil) or (_jczxingbarcodescan = nil) then exit;
jCls:= env^.GetObjectClass(env, _jczxingbarcodescan);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'ScanForResult', '(II)V');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
jParams[0].i:= _barcodeFormat;
jParams[1].i:= _requestCodeForResult;
env^.CallVoidMethodA(env, _jczxingbarcodescan, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: jni_ExceptionOccurred(env);
end;
end.
|
//****************************************************************************
//
// Program Name : - AT Library -
// Program Version: 1.00
// Filenames : AT.Windows.Graphics.pas
// File Version : 1.00
// Date Created : 28-JAN-2014
// Author : Matthew S. Vesperman
//
// Description:
//
// Angelic Tech generic graphics operations... (Migrated from SSGraphics.pas)
//
// Revision History:
//
// v1.00 : Initial version for Delphi XE5.
//
//****************************************************************************
//
// COPYRIGHT © 2013-Present Angelic Technology
// ALL RIGHTS RESERVED WORLDWIDE
//
//****************************************************************************
//TODO: Convert routines to use faster bit manipulations.
unit AT.Windows.Graphics;
interface
uses
System.Types, Vcl.Graphics;
/// <summary>
/// Converts a Font Style set into an integer value.
/// </summary>
/// <param name="AStyles">
/// The font style to convert.
/// </param>
/// <returns>
/// An integer where each value in AStyles is represented by a bit position.
/// </returns>
/// <remarks>
/// <para>
/// Bit positions are set as follows.
/// </para>
/// <para>
/// fsBold : Bit position 0
/// </para>
/// <para>
/// fsItalic : Bit position 1
/// </para>
/// <para>
/// fsUnderline : Bit position 2
/// </para>
/// <para>
/// fsStrikeout : Bit position 4
/// </para>
/// </remarks>
function FontStyleToInt(const AStyles: TFontStyles): Integer;
/// <summary>
/// Converts an integer value into a Font Style set.
/// </summary>
/// <param name="AValue">
/// The value to convert.
/// </param>
/// <returns>
/// Returns a font style set containing font styles whos bits were set in
/// AValue.
/// </returns>
/// <remarks>
/// <para>
/// The set contains font styles based on which bits are set in AValue.
/// </para>
/// <para>
/// Bit position 0 : fsBold
/// </para>
/// <para>
/// Bit position 1 : fsItalic
/// </para>
/// <para>
/// Bit position 2 : fsUnderline
/// </para>
/// <para>
/// Bit position 4 : fsStrikeout
/// </para>
/// </remarks>
function IntToFontStyles(const AValue: Integer): TFontStyles;
/// <summary>
/// Determines if a point is inside a rectangle.
/// </summary>
/// <param name="APoint">
/// The point to check for.
/// </param>
/// <param name="ARect">
/// The rectangle to check.
/// </param>
/// <returns>
/// Returns TRUE if APoint lies inside ARect, FALSE otherwise.
/// </returns>
function PointInRect(const APoint: TPoint; const ARect: TRect): Boolean;
/// <summary>
/// Converts a color specified by RGB values to TColor format.
/// </summary>
/// <param name="R">
/// The red value.
/// </param>
/// <param name="G">
/// The green value.
/// </param>
/// <param name="B">
/// The blue value.
/// </param>
/// <returns>
/// The RGB values converted to a TColor.
/// </returns>
function RGBToTColor(const R, G, B: Integer): TColor;
/// <summary>
/// Converts a TColor to its RGB values.
/// </summary>
/// <param name="AColor">
/// A color in TColor format.
/// </param>
/// <param name="R">
/// A variable to receive the red value.
/// </param>
/// <param name="G">
/// A variable to receive the green value.
/// </param>
/// <param name="B">
/// A variable to receive the blue value.
/// </param>
procedure TColorToRGB(const AColor: TColor; var R, G, B: Integer);
implementation
uses
System.UITypes;
const
iFSBold = 1;
iFSItalic = 2;
iFSUnderline = 4;
iFSStrikeOut = 8;
function FontStyleToInt(const AStyles: TFontStyles): Integer;
begin
Result := 0;
if (fsBold IN AStyles) then
Inc(Result, iFSBold);
if (fsItalic IN AStyles) then
Inc(Result, iFSItalic);
if (fsUnderline IN AStyles) then
Inc(Result, iFSUnderline);
if (fsStrikeOut IN AStyles) then
Inc(Result, iFSStrikeOut);
end;
function IntToFontStyles(const AValue: Integer): TFontStyles;
begin
Result := [];
if ((iFSBold AND AValue) = iFSBold) then
Result := Result + [fsBold];
if ((iFSItalic AND AValue) = iFSItalic) then
Result := Result + [fsItalic];
if ((iFSUnderline AND AValue) = iFSUnderline) then
Result := Result + [fsUnderline];
if ((iFSStrikeOut AND AValue) = iFSStrikeOut) then
Result := Result + [fsStrikeOut];
end;
function PointInRect(const APoint: TPoint; const ARect: TRect): Boolean;
begin
Result := (APoint.X >= ARect.Left) AND (APoint.X <= ARect.Right) AND
(APoint.Y >= ARect.Top) AND (APoint.Y <= ARect.Bottom);
end;
function RGBToTColor(const R, G, B: Integer): TColor;
begin
Result := R OR (G SHL 8) OR (B SHL 16);
end;
procedure TColorToRGB(const AColor: TColor; var R, G, B: Integer);
begin
R := AColor AND $000000FF;
G := (AColor SHR 8) AND $000000FF;
B := (AColor SHR 16) AND $000000FF;
end;
end.
|
unit ULoadCoupons;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TFLoadCoupons = class(TForm)
panelFile: TPanel;
FileOpenDialog1: TFileOpenDialog;
btnOpenFile: TButton;
edtFilePath: TEdit;
panelFileData: TPanel;
panelButtons: TPanel;
btnClose: TButton;
gpVistaPrevia: TGroupBox;
Memo1: TMemo;
btnAddCoupons: TButton;
GroupBox1: TGroupBox;
Label1: TLabel;
edtCouponValue: TEdit;
procedure btnOpenFileClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure load_coupons_file_to_string_list;
procedure btnCloseClick(Sender: TObject);
procedure errorOnActivate(message: string);
procedure btnAddCouponsClick(Sender: TObject);
function get_key(line: string): string;
function get_value(line: string): string;
procedure save_coupons_file;
private
{ Private declarations }
public
{ Public declarations }
end;
var
FLoadCoupons: TFLoadCoupons;
slCouponsFile: TStringList;
implementation
{$R *.dfm}
uses UFunctions;
procedure TFLoadCoupons.btnAddCouponsClick(Sender: TObject);
var
sl_aux: TStringList;
I: Integer;
line: string;
key: string;
value: string;
valor: Integer;
ok: Boolean;
begin
if edtCouponValue.Text <> '' then
begin
try
valor := StrToInt(edtCouponValue.Text);
ok := true;
except
MessageDlg('Debe indicar un valor entero para el cupon', mtError, [mbOk], 0 );
ok := false;
end;
if ok and (edtFilePath.Text <> '') then
begin
if FileExists(edtFilePath.Text) then
begin
btnAddCoupons.Enabled := false;
sl_aux := TStringList.Create;
sl_aux.LoadFromFile(edtFilePath.Text);
for I := 0 to sl_aux.Count - 1 do
begin
line := sl_aux[I];
key := get_key(line);
value := get_value(line);
slCouponsFile.Values[key] := value + ',' + IntToStr(valor);
end;
save_coupons_file;
sl_aux.Free;
end;
end;
end
else
begin
MessageDlg('Debe indicar un valor de cupon', mtError, [mbOk], 0 );
end;
end;
procedure TFLoadCoupons.btnCloseClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TFLoadCoupons.btnOpenFileClick(Sender: TObject);
var
sl_aux: TStringList;
begin
if FileOpenDialog1.Execute then
begin
edtFilePath.Text := FileOpenDialog1.FileName;
sl_aux := TStringList.Create;
sl_aux.LoadFromFile(FileOpenDialog1.FileName);
Memo1.Clear;
Memo1.Text := sl_aux.Text;
btnAddCoupons.Enabled := True;
sl_aux.Free;
end
else
begin
edtFilePath.Text := '';
btnAddCoupons.Enabled := False;
Memo1.Clear;
end;
end;
procedure TFLoadCoupons.FormActivate(Sender: TObject);
begin
slCouponsFile := TStringList.Create;
load_coupons_file_to_string_list;
end;
procedure TFLoadCoupons.FormClose(Sender: TObject; var Action: TCloseAction);
begin
slCouponsFile.Free;
end;
procedure TFLoadCoupons.load_coupons_file_to_string_list;
var
file_path: string;
sl_aux: TStringList;
ok: Boolean;
I: Integer;
line: string;
key: string;
value: string;
begin
file_path := ini_read_string('Conf', 'COUPONS_FILE_PATH', '');
if file_path = '' then
begin
errorOnActivate('Debe configurar el path del arvhivo de coupones para Winfarma')
end
else
begin
ok := false;
sl_aux := TStringList.Create;
if FileExists(file_path) then
begin
try
sl_aux.LoadFromFile(file_path);
ok := true;
except
errorOnActivate('No tiene permisos para leer: ' + file_path);
end;
end
else
begin
try
sl_aux.SaveToFile(file_path);
ok := true;
except
errorOnActivate('No tiene permisos para escribir: ' + file_path);
end;
end;
if ok then
begin
//en sl_aux pude levantar el archivo de cupones
//ahora lo paso al string list global
for I := 0 to sl_aux.Count - 1 do
begin
line := sl_aux[I];
key := get_key(line);
value := get_value(line);
slCouponsFile.Values[key] := value;
end;
end;
sl_aux.Free;
end;
end;
procedure TFLoadCoupons.save_coupons_file;
var
file_path: string;
sl_aux: TStringList;
I: Integer;
begin
//salva el stringlist como si fuera csv.
file_path := ini_read_string('Conf', 'COUPONS_FILE_PATH', '');
if file_path <> '' then
begin
sl_aux := TStringList.Create;
for I := 0 to slCouponsFile.Count - 1 do
begin
if UpperCase(slCouponsFile.Names[I]) <> UpperCase('Codigo') then
begin
sl_aux.Add(StringReplace(slCouponsFile[I], '=', ',', []));
end;
end;
try
sl_aux.SaveToFile(file_path);
MessageDlg('Se incorporaron los cupones a Winfarma con exito: ' + file_path, mtInformation, [mbOk], 0 );
except
MessageDlg('No se pudo grabar el archivo: ' + file_path, mtError, [mbOk], 0 );
end;
sl_aux.Free;
end;
end;
function TFLoadCoupons.get_key(line: string): string;
var
posi: Integer;
begin
posi := pos(',', line);
Result := copy(line, 0, posi-1);
end;
function TFLoadCoupons.get_value(line: string): string;
var
posi: Integer;
begin
posi := pos(',', line);
Result := copy(line, posi+1, 1000);
end;
procedure TFLoadCoupons.errorOnActivate(message: string);
begin
MessageDlg(message, mtError, [mbOk], 0 );
btnOpenFile.Enabled := false;
panelFileData.Visible := false;
end;
end.
|
unit Unit1;
interface
uses
System.Types, SmartCL.System, SmartCL.Components, SmartCL.Application, SmartCL.Game,
SmartCL.GameApp, SmartCL.Graphics, SmartCL.Touch, SmartCL.Controls.Button, SmartCL.Sprite3D;
type
TCanvasProject = class(TW3CustomGameApplication)
private
const SCENE_WIDTH = 300;
const SCENE_HEIGHT = 250;
const X_SPEED = 2;
const Y_SPEED = 2;
const SPRITE_SCALE_FACTOR = 0.9;
Mob: TW3Sprite;
Scene: TRect;
btnLeft, btnRight, btnUp, btnDown, btnRotX, btnRotY, btnRotZ: TW3Button;
protected
procedure SetupGameButton(Btn: TW3Button; Capt: string;
W, L, T: integer; var Pressed: Boolean);
procedure ApplicationStarting; override;
procedure ApplicationClosing; override;
procedure PaintView(Canvas: TW3Canvas); override;
end;
implementation
var
MovingLeft, MovingRight, MovingUp, MovingDown, RotatingX, RotatingY, RotatingZ: Boolean;
procedure TCanvasProject.SetupGameButton(Btn: TW3Button; Capt: string;
W, L, T: integer; var Pressed: Boolean);
begin
Pressed := False;
Btn.Caption := Capt;
Btn.Width := W;
Btn.Left := L;
Btn.Top := T;
Btn.OnMouseDown := lambda Pressed := True; end;
btn.OnMouseUp := lambda Pressed := False; end;
btn.OnTouchBegin := lambda Pressed := True; end;
btn.OnTouchEnd := lambda Pressed := False; end;
end;
procedure TCanvasProject.ApplicationStarting;
begin
inherited;
GameView.Delay := 5;
Scene := TRect.CreateSized(0, 0, SCENE_WIDTH, SCENE_HEIGHT);
Mob := TW3Sprite.Create(Document);
Mob.Background.fromURL('res/GroundEnemy.png');
Mob.Width := 72;
Mob.Height := 70;
Mob.X := 50;
Mob.Y := 50;
Mob.SetTransformFlags(CNT_USE_POS or CNT_USE_ROTX or CNT_USE_ROTY or
CNT_USE_ROTZ or CNT_USE_SCALE);
btnLeft := TW3Button.Create(Document);
SetupGameButton(btnLeft, '←', 40, 5, SCENE_HEIGHT + 5, MovingLeft);
btnRight := TW3Button.Create(Document);
SetupGameButton(btnRight, '→', 40, 55, SCENE_HEIGHT + 5, MovingRight);
btnUp := TW3Button.Create(Document);
SetupGameButton(btnUp, '↑', 40, 105, SCENE_HEIGHT + 5, MovingUp);
btnDown := TW3Button.Create(Document);
SetupGameButton(btnDown, '↓', 40, 155, SCENE_HEIGHT + 5, MovingDown);
btnRotX := TW3Button.Create(Document);
SetupGameButton(btnRotX, 'RotateX', 80, SCENE_WIDTH + 5, 0, RotatingX);
btnRotY := TW3Button.Create(Document);
SetupGameButton(btnRotY, 'RotateY', 80, SCENE_WIDTH + 5, 50, RotatingY);
btnRotZ := TW3Button.Create(Document);
SetupGameButton(btnRotZ, 'RotateZ', 80, SCENE_WIDTH + 5, 100, RotatingZ);
GameView.StartSession(False);
end;
procedure TCanvasProject.ApplicationClosing;
begin
GameView.EndSession;
inherited;
end;
procedure TCanvasProject.PaintView(Canvas: TW3Canvas);
begin
// Clear background of scene
Canvas.FillStyle := 'rgb(0, 0, 99)';
Canvas.FillRectF(Scene);
// Move mob if button pressed and if a move would not take it outside the scene
Canvas.FillStyle := 'rgb(99, 0, 0)';
if MovingLeft and (Mob.X > X_SPEED) then
Mob.MoveX(-X_SPEED)
else if MovingRight and (Mob.X + Mob.Width + X_SPEED < SCENE_WIDTH) then
Mob.MoveX(X_SPEED)
else if MovingUp and (Mob.Y > Y_SPEED) then
Mob.MoveY(-Y_SPEED)
else if MovingDown and (Mob.Y + Mob.Height + Y_SPEED < SCENE_HEIGHT) then
Mob.MoveY(Y_SPEED);
if RotatingX then
Mob.RotateX(1);
if RotatingY then
Mob.RotateY(1);
if RotatingZ then
Mob.RotateZ(-1);
Mob.Scale(SPRITE_SCALE_FACTOR);
Mob.Update3D;
end;
end.
|
unit ViewModel.Main;
interface
uses Model.Main, Model.Declarations, Model.Interfaces;
function CreateMainViewModelClass: IMainViewModelInterface;
implementation
uses
System.SysUtils;
type
TMainViewModel = class(TInterfacedObject, IMainViewModelInterface)
private
fModel: IMainModelInterface;
fLabelsText: TMainFormLabelsText;
fTotalSalesValue: Currency;
function GetModel: IMainModelInterface;
procedure SetModel (const newModel: IMainModelInterface);
function GetLabelsText: TMainFormLabelsText;
public
property Model: IMainModelInterface read fModel write SetModel;
property LabelsText: TMainFormLabelsText read GetlabelsText;
function GetTotalSalesValue: string;
end;
function CreateMainViewModelClass: IMainViewModelInterface;
begin
result:=TMainViewModel.Create;
end;
{ TMainViewModel }
function TMainViewModel.GetLabelsText: TMainFormLabelsText;
begin
fLabelsText:=fModel.GetMainFormLabelsText;
result:=fLabelsText;
end;
function TMainViewModel.GetModel: IMainModelInterface;
begin
result:=fModel;
end;
function TMainViewModel.GetTotalSalesValue: string;
begin
fTotalSalesValue:=fModel.GetTotalSales;
result:=Format('%10.2f',[fTotalSalesValue]);
end;
procedure TMainViewModel.SetModel(const newModel: IMainModelInterface);
begin
fModel:=newModel;
end;
end.
|
unit BaseExcelReportCreatorUnit;
interface
uses ComObj, SysUtils, Windows, Dialogs, Classes, Graphics, Variants;
type
TReportOutputType = (roFile, roPrinter);
TReportPageOrientation = (poPortrait = 1, poLandscape = 2);
TCreateReportStatus = (crOk, crFailed, crDiscarded);
TBaseExcelReportCreator = class
strict protected
FReportName: string;
FColumns: TStrings;
FReportData: TList;
FFileName: string;
FReportNameFont: TFont;
FColumnsFont: TFont;
FReportDataFont: TFont;
FReportOutputType: TReportOutputType;
FPrintCopyCount: integer;
FPrinterName: string;
FPageOrientation: TReportPageOrientation;
function ActivateExcelApp: Variant;
procedure InsertTitle(excelApp: Variant);
procedure InsertColumns(excelApp: Variant);
procedure InsertReportData(excelApp: Variant);
procedure ResizeToContent(excelApp: Variant);
procedure SaveToFile(excelApp: Variant);
procedure Print(excelApp: Variant);
procedure OutputReportData(excelApp: Variant);
procedure DeactivateExcelApp(excelApp: Variant);
function CreateFont(const Size: integer;
const Style: TFontStyles; const Name: TFontName; const Color: TColor = clBlack): TFont;
public
destructor Destroy; override;
constructor Create(const ReportOutputType: TReportOutputType = roFile); overload;
constructor Create(const ReportName: string; const ReportOutputType: TReportOutputType = roFile); overload;
constructor Create(const ReportName: string; Columns: TStrings; const ReportOutputType: TReportOutputType = roFile); overload;
constructor Create(const ReportName: string; Columns: TStrings;
ReportData: TList; const ReportOutputType: TReportOutputType = roFile); overload;
property ReportName: string read FReportName write FReportName;
property Columns: TStrings read FColumns;
property ReportData: TList read FReportData;
property ReportNameFont: TFont read FReportNameFont write FReportNameFont;
property ColumnsFont: TFont read FReportNameFont write FReportNameFont;
property ReportDataFont: TFont read FReportNameFont write FReportNameFont;
property FileName : string read FFileName write FFileName;
property ReportOutputType : TReportOutputType read FReportOutputType write FReportOutputType;
property PrintCopyCount: integer read FPrintCopyCount write FPrintCopyCount;
property PrinterName: string read FPrinterName write FPrinterName;
property PageOrientation: TReportPageOrientation read FPageOrientation write FPageOrientation;
function AddReportDataRows(ReportDataRows: TList): integer;
function AddReportDataRow(ReportDataRow: TStrings): integer; overload;
function AddReportDataRow(ReportDataRow: array of string): integer; overload;
function RemoveReportDataRow(const RowIdx: integer): boolean;
function CreateReport: TCreateReportStatus;
function RemoveColumn(const ColIdx: integer): boolean;
function AddColumn(Column: string): integer;
function AddColumns(Columns: TStrings): integer; overload;
function AddColumns(Columns: array of string): integer; overload;
procedure ClearReportData;
procedure ClearColumns;
end;
implementation
{ TBaseExcelReportCreator }
procedure TBaseExcelReportCreator.ClearColumns;
begin
FColumns.Clear;
end;
// удаляет данные для построения отчета Excel
procedure TBaseExcelReportCreator.ClearReportData;
var row: TStrings;
idx: integer;
begin
for idx := 0 to FReportData.Count - 1 do begin
row := TStrings(FReportData[idx]);
row.Free;
end;
FReportData.Clear;
end;
constructor TBaseExcelReportCreator.Create(const ReportOutputType: TReportOutputType);
begin
inherited Create;
FColumns := TStringList.Create;
FReportData := TList.Create;
FReportNameFont := CreateFont(14, [fsBold], 'Arial');
FColumnsFont := CreateFont(12, [fsBold], 'Arial');
FReportDataFont := CreateFont(12, [], 'Arial');
FReportOutputType := ReportOutputType;
FPageOrientation := poPortrait;
end;
constructor TBaseExcelReportCreator.Create(const ReportName: string;
Columns: TStrings; const ReportOutputType: TReportOutputType);
begin
Create(ReportName, ReportOutputType);
FColumns := Columns;
end;
constructor TBaseExcelReportCreator.Create(const ReportName: string;
Columns: TStrings; ReportData: TList; const ReportOutputType: TReportOutputType);
begin
Create(ReportName, Columns, ReportOutputType);
FReportData := ReportData;
end;
function TBaseExcelReportCreator.CreateFont(const Size: integer;
const Style: TFontStyles; const Name: TFontName; const Color: TColor): TFont;
begin
result := TFont.Create;
result.Style := Style;
result.Size := Size;
result.Name := Name;
result.Color := Color;
end;
function TBaseExcelReportCreator.CreateReport: TCreateReportStatus;
var excelApp: Variant;
begin
try
try
excelApp := ActivateExcelApp;
InsertTitle(excelApp);
InsertColumns(excelApp);
InsertReportData(excelApp);
ResizeToContent(excelApp);
OutputReportData(excelApp);
result := crOk;
except
on e: EOleException do begin
if e.ErrorCode = -2146827284 then begin
result := crDiscarded;
excelApp.WorkBooks[1].Close(SaveChanges := false);
end
else result := crFailed;
end;
on e: Exception do
result := crFailed;
end;
finally
if not VarIsNull(excelApp) then begin
DeactivateExcelApp(excelApp);
end;
end;
end;
procedure TBaseExcelReportCreator.DeactivateExcelApp(excelApp: Variant);
begin
excelApp.Quit;
excelApp := 0;
end;
destructor TBaseExcelReportCreator.Destroy;
begin
FreeAndNil(FColumns);
ClearReportData;
FreeAndNil(FReportData);
inherited;
end;
function TBaseExcelReportCreator.ActivateExcelApp: Variant;
begin
result := CreateOleObject('Excel.Application');
result.Workbooks.Add;
result.Visible := false;
end;
function TBaseExcelReportCreator.AddColumn(Column: string): integer;
begin
result := FColumns.Add(Column);
end;
function TBaseExcelReportCreator.AddColumns(Columns: array of string): integer;
var col_name: string;
begin
result := -1;
for col_name in Columns do
result := FColumns.Add(col_name);
end;
function TBaseExcelReportCreator.AddColumns(Columns: TStrings): integer;
begin
FColumns.AddStrings(Columns);
result := FColumns.Count - 1;
end;
function TBaseExcelReportCreator.AddReportDataRow(ReportDataRow: TStrings): integer;
begin
result := FReportData.Add(ReportDataRow);
end;
function TBaseExcelReportCreator.AddReportDataRow(
ReportDataRow: array of string): integer;
var aux: TStrings;
cell: string;
begin
aux := nil;
try
try
aux := TStringList.Create;
for cell in ReportDataRow do
aux.Add(cell);
result := FReportData.Add(Pointer(aux));
except
result := -1;
end;
finally
end;
end;
function TBaseExcelReportCreator.AddReportDataRows(
ReportDataRows: TList): integer;
var row: TStrings;
idx: integer;
last_inserted: integer;
begin
result := -1;
for idx := 0 to ReportDataRows.Count - 1 do begin
row := TStrings(ReportDataRows[idx]);
last_inserted := FReportData.Add(Pointer(row));
end;
result := last_inserted;
end;
procedure TBaseExcelReportCreator.InsertColumns(excelApp: Variant);
var Sheet: Variant;
idx, col_count: integer;
begin
Sheet := excelApp.Workbooks[1].WorkSheets[1];
col_count := FColumns.Count;
Sheet.Rows[2].Font.Bold := fsBold in FColumnsFont.Style;
Sheet.Rows[2].Font.Size := FColumnsFont.Size;
Sheet.Rows[2].Font.Color := FColumnsFont.Color;
Sheet.Rows[2].Font.Name := FColumnsFont.Name;
for idx := 0 to col_count - 1 do begin
Sheet.Cells[2,idx + 1] := FColumns[idx];
end;
end;
procedure TBaseExcelReportCreator.InsertReportData(excelApp: Variant);
var Sheet: Variant;
idx, row_idx, col_idx: integer;
row_cells: TStrings;
begin
Sheet := excelApp.Workbooks[1].WorkSheets[1];
row_idx := 3;
for idx := 0 to FReportData.Count - 1 do begin
Sheet.Rows[row_idx].Font.Bold := fsBold in FReportDataFont.Style;
Sheet.Rows[row_idx].Font.Size := FReportDataFont.Size;
Sheet.Rows[row_idx].Font.Color := FReportDataFont.Color;
Sheet.Rows[row_idx].Font.Name := FReportDataFont.Name;
row_cells := TStrings(FReportData[idx]);
for col_idx := 0 to row_cells.Count - 1 do begin
Sheet.Cells[row_idx, col_idx + 1] := row_cells[col_idx];
end;
inc(row_idx);
end;
end;
procedure TBaseExcelReportCreator.InsertTitle(excelApp: Variant);
var Sheet: Variant;
titleIdx: integer;
begin
Sheet := excelApp.Workbooks[1].WorkSheets[1];
titleIdx := (FColumns.Count shr 1) + (FColumns.Count and 1);
Sheet.Rows[1].Font.Bold := fsBold in FReportNameFont.Style;;
Sheet.Rows[1].Font.Size := FReportNameFont.Size;
Sheet.Rows[1].Font.Color := FReportNameFont.Color;
Sheet.Rows[1].Font.Name := FReportNameFont.Name;
Sheet.Cells[1,titleIdx] := FReportName;
end;
procedure TBaseExcelReportCreator.OutputReportData(excelApp: Variant);
begin
if FReportOutputType = roFile then
SaveToFile(excelApp)
else if FReportOutputType = roPrinter then
Print(excelApp);
end;
procedure TBaseExcelReportCreator.Print(excelApp: Variant);
var WorkBook, Sheet: Variant;
begin
WorkBook := excelApp.WorkBooks[1];
Sheet := WorkBook.WorkSheets[1];
Sheet.PageSetup.Orientation := FPageOrientation;
Sheet.PrintOut(Copies := FPrintCopyCount, ActivePrinter := FPrinterName);
WorkBook.Close(SaveChanges := false);
end;
constructor TBaseExcelReportCreator.Create(const ReportName: string; const ReportOutputType: TReportOutputType);
begin
Create(ReportOutputType);
FReportName := ReportName;
end;
function TBaseExcelReportCreator.RemoveColumn(const ColIdx: integer): boolean;
begin
try
FColumns.Delete(ColIdx);
result := true;
except
result := false;
end;
end;
function TBaseExcelReportCreator.RemoveReportDataRow(
const RowIdx: integer): boolean;
begin
try
FReportData.Delete(RowIdx);
result := true;
except
result := false;
end;
end;
procedure TBaseExcelReportCreator.ResizeToContent(excelApp: Variant);
var Sheet, Range, startCell, endCell: Variant;
begin
Sheet := excelApp.Workbooks[1].WorkSheets[1];
startCell := Sheet.Cells[2,1];
endCell := Sheet.Cells[3 + FReportData.Count - 1,FColumns.Count];
Range := Sheet.Range[startCell, endCell];
Range.Columns.AutoFit;
end;
procedure TBaseExcelReportCreator.SaveToFile(excelApp: Variant);
begin
excelApp.Workbooks[1].SaveAs(FFileName);
end;
end.
|
unit UButtonTest;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ActnList,
System.ImageList, Vcl.ImgList, IconFontsImageList, Vcl.StdCtrls, Vcl.ExtCtrls,
SVGIconImageList, SVGIconImageListBase, IconFontsImageListBase;
type
TForm22 = class(TForm)
Button: TButton;
IconFontsImageList: TIconFontsImageList;
ActionList1: TActionList;
Action: TAction;
SelectThemeRadioGroup: TRadioGroup;
Button1: TButton;
ActionList2: TActionList;
Action2: TAction;
ImageList: TImageList;
Button2: TButton;
SVGIconImageList: TSVGIconImageList;
ActionList3: TActionList;
Action3: TAction;
procedure ActionExecute(Sender: TObject);
procedure RadioGroup1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SelectThemeRadioGroupClick(Sender: TObject);
private
procedure UpdateGUI;
public
{ Public declarations }
end;
var
Form22: TForm22;
implementation
{$R *.dfm}
uses
Themes
, IconFontsUtils;
procedure TForm22.ActionExecute(Sender: TObject);
begin
showmessage('click');
end;
procedure TForm22.FormCreate(Sender: TObject);
var
I: Integer;
begin
//Build available VCL Styles
SelectThemeRadioGroup.Items.Clear;
for I := 0 to High(TStyleManager.StyleNames) do
SelectThemeRadioGroup.Items.Add(TStyleManager.StyleNames[I]);
UpdateGUI;
end;
procedure TForm22.RadioGroup1Click(Sender: TObject);
begin
;
end;
procedure TForm22.SelectThemeRadioGroupClick(Sender: TObject);
var
LStyleName: string;
begin
Screen.Cursor := crHourGlass;
try
LStyleName := SelectThemeRadioGroup.Items[SelectThemeRadioGroup.ItemIndex];
TStyleManager.TrySetStyle(LStyleName);
//Override default: use Windows 10 blue color for Windows and Windows10 Style
if SameText(LStyleName,'Windows10') then
IconFontsImageList.UpdateIconsAttributes(RGB(0, 120, 215), clBtnFace)
else
UpdateIconFontsColorByStyle(IconFontsImageList);
SVGIconImageList.FixedColor := IconFontsImageList.FontColor;
UpdateGUI;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TForm22.UpdateGUI;
begin
Button.Action := Action;
end;
end.
|
unit EventInterceptor;
/// <summary> Log all TNotifyEvents (e.g. OnChange, OnEnter, OnExit) to the Delphi Event Log in the debug window.
/// All child controls are monitored as well.
/// Alternatively, provide your own code to execute on these events (e.g. write to a file)
/// To use:
/// * Add the EventInterceptor Unit to the Uses clause
/// * Add this line somewhere in your code for each form you want to track.
/// "AddEventInterceptors(MyForm);"
/// MyForm can be any TControl (e.g. a form, a control etc.)
///
/// To do something different on an event (e.g. write to standard out) provide a callback.
/// AddEventInterceptors(self,procedure (Sender: TObject; Control:TControl; EventName:string) begin
/// WriteLn(Control.Name+'.'+EventName); end);
///
/// Possible improvements:
/// Track other types of events besides TNotifyEvent e.g. Click Events.
/// </summary>
interface
uses Classes, Controls, Generics.Collections, Rtti;
type TInterceptEvent=reference to procedure(Sender: TObject; Control:TControl; EventName:string);
type TEventInterceptor=class(TComponent)
private
EventName:string;
Control:TControl;
originalEvent:TNotifyEvent;
newEvent:TInterceptEvent;
class procedure RecurseControls(Control: TControl; ExaminedControls: TList<TControl>; context:TRttiContext; InterceptEvent:TInterceptEvent);
public
procedure HandleEvent(Sender: TObject);
constructor Create(Control:TControl; EventName:string; OriginalEvent:TNotifyEvent; InterceptEvent:TInterceptEvent);
end;
/// <summary> Track events on a TControl and all it's child controls. By default, all events are logged to the Delphi
/// Event Log</summary>
/// <param> Control Log all events that occurr on this Control or any of its Children. Note that any Form is a TControl.</param>
/// <param> InterceptEvent Optional. Code to execute each time an event is intercepted</param>
procedure AddEventInterceptors(Control:TControl; InterceptEvent:TInterceptEvent=nil);
implementation
uses TypInfo, SysUtils, Windows;
constructor TEventInterceptor.Create(Control:TControl; EventName: string; OriginalEvent: TNotifyEvent; InterceptEvent:TInterceptEvent);
begin
inherited Create(Control);
self.Control:=Control;
self.EventName:=EventName;
self.originalEvent:=OriginalEvent;
self.newEvent:=InterceptEvent;
end;
procedure TEventInterceptor.HandleEvent(Sender: TObject);
begin
newEvent(Sender,Control,EventName);
originalEvent(Sender);
end;
class procedure TEventInterceptor.RecurseControls(Control: TControl; ExaminedControls: TList<TControl>; context:TRttiContext; InterceptEvent:TInterceptEvent);
var
theTypeInfo: TRttiInstanceType;
theProperty: TRttiProperty;
interceptor: TEventInterceptor;
theEvent: TNotifyEvent;
theValue: TValue;
field: TRttiField;
newControl: TControl;
instanceType: TRTTIInstanceType;
begin
ExaminedControls.add(Control);
theTypeInfo:=context.GetType(Control.ClassInfo) as TRttiInstanceType;
for theProperty in theTypeInfo.GetProperties do
begin
if (theProperty.PropertyType.ToString='TNotifyEvent') and theProperty.IsWritable then
begin
theValue:=theProperty.GetValue(Control);
theEvent:=nil;
if not theValue.IsEmpty then theEvent:=theValue.AsType<TNotifyEvent>();
if Assigned(theEvent) then
begin
interceptor:=TEventInterceptor.Create(Control,theProperty.Name, theEvent, InterceptEvent );
theProperty.SetValue(Control,TValue.From<TNotifyEvent>(interceptor.HandleEvent));
end;
end
end;
try
for field in theTypeInfo.GetFields do
begin
if field.FieldType.TypeKind=tkClass then
begin
instanceType:=field.FieldType As TRttiInstanceType;
if instanceType.MetaclassType.InheritsFrom(TControl) then
begin
newControl:=nil;
theValue:=field.GetValue(Control);
if not theValue.IsEmpty then newControl:=theValue.AsType<TControl>;
if Assigned(newControl) then if not ExaminedControls.Contains(newControl) then
RecurseControls(newControl, ExaminedControls, context, InterceptEvent);
end;
end;
end;
except on E:EAccessViolation do
// For some reason we can get an AccessViolation while looping through the fields. Seemed to happen
// on ParentControl.
end;
end;
procedure AddEventInterceptors(Control:TControl; InterceptEvent:TInterceptEvent=nil);
var
examinedObjects: TList<TControl>;
begin
examinedObjects:=TList<TControl>.Create;
examinedObjects.add(Control);
if Not Assigned(InterceptEvent) then InterceptEvent:=procedure(Sender: TObject; Control:TControl; EventName:string)
begin
OutputDebugString(PWideChar(Control.Name+'.'+EventName));
end;
TEventInterceptor.RecurseControls(Control, examinedObjects, TRttiContext.Create, InterceptEvent);
examinedObjects.Free;
end;
end.
|
unit u_VectorItemLonLat;
interface
uses
Classes,
i_LonLatRect,
i_EnumDoublePoint,
i_Datum,
i_VectorItemLonLat;
type
TLonLatLineSet = class(TInterfacedObject)
private
FList: IInterfaceList;
FBounds: ILonLatRect;
private
function GetCount: Integer;
function GetBounds: ILonLatRect;
public
constructor Create(
const ABounds: ILonLatRect;
const AList: IInterfaceList
);
end;
TLonLatPath = class(TLonLatLineSet, ILonLatPath)
private
function GetEnum: IEnumLonLatPoint;
function IsSame(const APath: ILonLatPath): Boolean;
function CalcLength(const ADatum: IDatum): Double;
function GetItem(AIndex: Integer): ILonLatPathLine;
end;
TLonLatPolygon = class(TLonLatLineSet, ILonLatPolygon)
private
function GetEnum: IEnumLonLatPoint;
function IsSame(const APolygon: ILonLatPolygon): Boolean;
function CalcPerimeter(const ADatum: IDatum): Double;
function CalcArea(const ADatum: IDatum): Double;
function GetItem(AIndex: Integer): ILonLatPolygonLine;
end;
TLonLatPathOneLine = class(TInterfacedObject, ILonLatPath)
private
FLine: ILonLatPathLine;
private
function GetCount: Integer;
function GetEnum: IEnumLonLatPoint;
function IsSame(const APath: ILonLatPath): Boolean;
function CalcLength(const ADatum: IDatum): Double;
function GetBounds: ILonLatRect;
function GetItem(AIndex: Integer): ILonLatPathLine;
public
constructor Create(
const ALine: ILonLatPathLine
);
end;
TLonLatPolygonOneLine = class(TInterfacedObject, ILonLatPolygon)
private
FLine: ILonLatPolygonLine;
private
function GetCount: Integer;
function GetEnum: IEnumLonLatPoint;
function IsSame(const APolygon: ILonLatPolygon): Boolean;
function CalcPerimeter(const ADatum: IDatum): Double;
function CalcArea(const ADatum: IDatum): Double;
function GetBounds: ILonLatRect;
function GetItem(AIndex: Integer): ILonLatPolygonLine;
public
constructor Create(
const ALine: ILonLatPolygonLine
);
end;
implementation
uses
SysUtils,
u_EnumDoublePointByLineSet;
{ TLonLatLineSet }
constructor TLonLatLineSet.Create(
const ABounds: ILonLatRect;
const AList: IInterfaceList
);
begin
inherited Create;
FBounds := ABounds;
FList := AList;
end;
function TLonLatLineSet.GetBounds: ILonLatRect;
begin
Result := FBounds;
end;
function TLonLatLineSet.GetCount: Integer;
begin
Result := FList.Count;
end;
{ TLonLatPath }
function TLonLatPath.CalcLength(const ADatum: IDatum): Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FList.Count - 1 do begin
Result := Result + GetItem(i).CalcLength(ADatum);
end;
end;
function TLonLatPath.GetEnum: IEnumLonLatPoint;
begin
Result := TEnumLonLatPointByPath.Create(Self);
end;
function TLonLatPath.GetItem(AIndex: Integer): ILonLatPathLine;
begin
if not Supports(FList[AIndex], ILonLatPathLine, Result) then begin
Result := nil;
end;
end;
function TLonLatPath.IsSame(const APath: ILonLatPath): Boolean;
var
i: Integer;
VLine: ILonLatPathLine;
begin
if APath = ILonLatPath(Self) then begin
Result := True;
Exit;
end;
if FList.Count <> APath.Count then begin
Result := False;
Exit;
end;
for i := 0 to FList.Count - 1 do begin
VLine := GetItem(i);
if VLine = nil then begin
Result := False;
Exit;
end;
if not VLine.IsSame(APath.Item[i]) then begin
Result := False;
Exit;
end;
end;
Result := True;
end;
{ TLonLatPolygon }
function TLonLatPolygon.CalcArea(const ADatum: IDatum): Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FList.Count - 1 do begin
Result := Result + GetItem(i).CalcArea(ADatum);
end;
end;
function TLonLatPolygon.CalcPerimeter(const ADatum: IDatum): Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FList.Count - 1 do begin
Result := Result + GetItem(i).CalcPerimeter(ADatum);
end;
end;
function TLonLatPolygon.GetEnum: IEnumLonLatPoint;
begin
Result := TEnumLonLatPointByPolygon.Create(Self);
end;
function TLonLatPolygon.GetItem(AIndex: Integer): ILonLatPolygonLine;
begin
if not Supports(FList[AIndex], ILonLatPolygonLine, Result) then begin
Result := nil;
end;
end;
function TLonLatPolygon.IsSame(const APolygon: ILonLatPolygon): Boolean;
var
i: Integer;
VLine: ILonLatPolygonLine;
begin
if APolygon = ILonLatPolygon(Self) then begin
Result := True;
Exit;
end;
if FList.Count <> APolygon.Count then begin
Result := False;
Exit;
end;
for i := 0 to FList.Count - 1 do begin
VLine := GetItem(i);
if VLine = nil then begin
Result := False;
Exit;
end;
if not VLine.IsSame(APolygon.Item[i]) then begin
Result := False;
Exit;
end;
end;
Result := True;
end;
{ TLonLatPathOneLine }
function TLonLatPathOneLine.CalcLength(const ADatum: IDatum): Double;
begin
Result := FLine.CalcLength(ADatum);
end;
constructor TLonLatPathOneLine.Create(const ALine: ILonLatPathLine);
begin
inherited Create;
FLine := ALine;
end;
function TLonLatPathOneLine.GetBounds: ILonLatRect;
begin
Result := FLine.Bounds;
end;
function TLonLatPathOneLine.GetCount: Integer;
begin
Result := 1;
end;
function TLonLatPathOneLine.GetEnum: IEnumLonLatPoint;
begin
Result := FLine.GetEnum;
end;
function TLonLatPathOneLine.GetItem(AIndex: Integer): ILonLatPathLine;
begin
if AIndex = 0 then begin
Result := FLine;
end else begin
Result := nil;
end;
end;
function TLonLatPathOneLine.IsSame(const APath: ILonLatPath): Boolean;
begin
if APath.Count <> 1 then begin
Result := False;
Exit;
end;
Result := FLine.IsSame(APath.Item[0]);
end;
{ TLonLatPolygonOneLine }
function TLonLatPolygonOneLine.CalcArea(const ADatum: IDatum): Double;
begin
Result := FLine.CalcArea(ADatum);
end;
function TLonLatPolygonOneLine.CalcPerimeter(const ADatum: IDatum): Double;
begin
Result := FLine.CalcPerimeter(ADatum);
end;
constructor TLonLatPolygonOneLine.Create(const ALine: ILonLatPolygonLine);
begin
inherited Create;
FLine := ALine;
end;
function TLonLatPolygonOneLine.GetBounds: ILonLatRect;
begin
Result := FLine.Bounds;
end;
function TLonLatPolygonOneLine.GetCount: Integer;
begin
Result := 1;
end;
function TLonLatPolygonOneLine.GetEnum: IEnumLonLatPoint;
begin
Result := FLine.GetEnum;
end;
function TLonLatPolygonOneLine.GetItem(AIndex: Integer): ILonLatPolygonLine;
begin
if AIndex = 0 then begin
Result := FLine;
end else begin
Result := nil;
end;
end;
function TLonLatPolygonOneLine.IsSame(const APolygon: ILonLatPolygon): Boolean;
begin
if APolygon.Count <> 1 then begin
Result := False;
Exit;
end;
Result := FLine.IsSame(APolygon.Item[0]);
end;
end.
|
unit dmSistemaStorage;
interface
uses
Windows, SysUtils, Classes, JvComponentBase, JvAppStorage, JvAppDBStorage,
IBCustomDataSet, IBUpdateSQL, DB, IBQuery, UtilDB, IBDatabase;
type
TSistemaStorage = class(TDataModule)
qSistema: TIBQuery;
qSistemaOID_SISTEMA: TIntegerField;
qSistemaSECCION: TIBStringField;
qSistemaNOMBRE: TIBStringField;
qSistemaVALOR: TMemoField;
uSistema: TIBUpdateSQL;
IBTransaction: TIBTransaction;
IBDatabaseUsuario: TIBDatabase;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
OIDGenerator: TOIDGenerator;
criticalSection: TRTLCriticalSection;
procedure Write(const seccion: string; const clave: string; const valor: Variant);
public
procedure DeleteSeccion(const seccion: string);
procedure Delete(const seccion, clave: string);
procedure DeleteSubseccion(const subseccion: string);
function ReadCurrency(const seccion: string; const clave: string; const default: currency): currency;
function ReadString(const seccion: string; const clave: string; const default: string): string;
function ReadInteger(const seccion: string; const clave: string; const default: integer): integer;
function ReadBoolean(const seccion: string; const clave: string; const default: boolean): boolean;
function ReadDateTime(const seccion: string; const clave: string; const default: TDateTime): TDateTime;
procedure WriteCurrency(const seccion: string; const clave: string; const valor: currency);
procedure WriteString(const seccion: string; const clave: string; const valor: string);
procedure WriteInteger(const seccion: string; const clave: string; const valor: integer);
procedure WriteBoolean(const seccion: string; const clave: string; const valor: boolean);
procedure WriteDateTime(const seccion: string; const clave: string; const valor: TDateTime);
end;
implementation
uses dmBD, StrUtils, Variants;
{$R *.dfm}
{ TSistemaStorage }
function TSistemaStorage.ReadBoolean(const seccion, clave: string;
const default: boolean): boolean;
begin
EnterCriticalSection(criticalSection);
try
if qSistema.Locate('SECCION;NOMBRE', VarArrayOf([seccion, clave]), []) then
result := StrToBool(qSistemaVALOR.Value)
else
result := default;
finally
LeaveCriticalSection(criticalSection);
end;
end;
function TSistemaStorage.ReadInteger(const seccion, clave: string;
const default: integer): integer;
begin
EnterCriticalSection(criticalSection);
try
if qSistema.Locate('SECCION;NOMBRE', VarArrayOf([seccion, clave]), []) then
result := StrToInt(qSistemaVALOR.Value)
else
result := default;
finally
LeaveCriticalSection(criticalSection);
end;
end;
function TSistemaStorage.ReadString(const seccion, clave,
default: string): string;
begin
EnterCriticalSection(criticalSection);
try
if qSistema.Locate('SECCION;NOMBRE', VarArrayOf([seccion, clave]), []) then
result := qSistemaVALOR.AsString
else
result := default;
finally
LeaveCriticalSection(criticalSection);
end;
end;
procedure TSistemaStorage.Write(const seccion, clave: string;
const valor: Variant);
begin
EnterCriticalSection(criticalSection);
try
try
IBTransaction.Active := true;
if qSistema.Locate('SECCION;NOMBRE', VarArrayOf([seccion, clave]), []) then begin
qSistema.Edit;
end
else begin
qSistema.Append;
qSistemaOID_SISTEMA.Value := OIDGenerator.NextOID;
qSistemaSECCION.Value := seccion;
qSistemaNOMBRE.Value := clave;
end;
qSistemaVALOR.AsVariant := valor;
qSistema.Post;
IBTransaction.CommitRetaining;
except
IBTransaction.RollbackRetaining;
raise;
end;
finally
LeaveCriticalSection(criticalSection);
end;
end;
procedure TSistemaStorage.WriteBoolean(const seccion, clave: string;
const valor: boolean);
begin
Write(seccion, clave, valor);
end;
procedure TSistemaStorage.WriteInteger(const seccion, clave: string;
const valor: integer);
begin
Write(seccion, clave, valor);
end;
procedure TSistemaStorage.WriteString(const seccion, clave, valor: string);
begin
Write(seccion, clave, valor);
end;
procedure TSistemaStorage.DataModuleCreate(Sender: TObject);
begin
BD.ConfigureDatabase(IBDatabaseUsuario, bddDiaria);
OpenDatabase(IBDatabaseUsuario);
InitializeCriticalSection(criticalSection);
OIDGenerator := TOIDGenerator.Create(IBDatabaseUsuario, 'SISTEMA');
qSistema.Open;
end;
procedure TSistemaStorage.DataModuleDestroy(Sender: TObject);
begin
DeleteCriticalSection(criticalSection);
OIDGenerator.Free;
end;
procedure TSistemaStorage.Delete(const seccion, clave: string);
begin
EnterCriticalSection(criticalSection);
try
if qSistema.Locate('SECCION;NOMBRE', VarArrayOf([seccion, clave]), []) then
qSistema.Delete;
finally
LeaveCriticalSection(criticalSection);
end;
end;
procedure TSistemaStorage.DeleteSeccion(const seccion: string);
begin
EnterCriticalSection(criticalSection);
try
while qSistema.Locate('SECCION', seccion, []) do
qSistema.Delete;
finally
LeaveCriticalSection(criticalSection);
end;
end;
procedure TSistemaStorage.DeleteSubseccion(const subseccion: string);
begin
EnterCriticalSection(criticalSection);
try
qSistema.First;
while not qSistema.Eof do begin
if StartsText(subseccion, qSistemaSECCION.Value) then
qSistema.Delete
else
qSistema.Next;
end;
finally
LeaveCriticalSection(criticalSection);
end;
end;
function TSistemaStorage.ReadCurrency(const seccion, clave: string;
const default: currency): currency;
begin
EnterCriticalSection(criticalSection);
try
if qSistema.Locate('SECCION;NOMBRE', VarArrayOf([seccion, clave]), []) then
result := StrToCurr(qSistemaVALOR.Value)
else
result := default;
finally
LeaveCriticalSection(criticalSection);
end;
end;
function TSistemaStorage.ReadDateTime(const seccion, clave: string;
const default: TDateTime): TDateTime;
begin
EnterCriticalSection(criticalSection);
try
if qSistema.Locate('SECCION;NOMBRE', VarArrayOf([seccion, clave]), []) then
result := StrToDateTime(qSistemaVALOR.Value)
else
result := default;
finally
LeaveCriticalSection(criticalSection);
end;
end;
procedure TSistemaStorage.WriteCurrency(const seccion, clave: string;
const valor: currency);
begin
Write(seccion, clave, valor);
end;
procedure TSistemaStorage.WriteDateTime(const seccion, clave: string;
const valor: TDateTime);
begin
Write(seccion, clave, valor);
end;
end.
|
unit UDefault;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UConexao;
type
TFDefault = class(TForm)
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
function getConn: TConexao;
public
property Conn: TConexao read getConn;
end;
var
FDefault: TFDefault;
implementation
{$R *.dfm}
procedure TFDefault.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFDefault.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
Key := #0;
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end;
function TFDefault.getConn: TConexao;
begin
Result := TConexao.Instance;
end;
end.
|
unit UPortGeolocator;
{$WARN UNIT_PLATFORM OFF}
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2005 by Bradford Technologies, Inc. }
interface
uses
Windows, Messages, contnrs, classes, UWinUtils,
UPortBase;
const
GeoLocQuitMsgID = 'GeoLocatorQuitMessage';
type
TGeolocatorPort = class(TPortMapper)
private
FWorkDir: String;
FMapRes: Integer;
FMapColor: Integer;
// FMapSize: Integer;
FQuitMsgID: LongWord;
function GetWorkDir: String;
procedure CleanOutWorkDir;
procedure SetupConfigFile;
procedure SetupViewConfigFile;
procedure SetupFormatLegendFile;
public
constructor Create; override;
procedure Launch; override;
function ExportAddresses: Boolean; override;
// function RemoveLabelID(strLabel: String): String;
function ImportResults: Boolean;
property GeoQuitMsg: LongWord read FQuitMsgID write FQuitMsgID;
property WorkDir: String read GetWorkDir write FWorkDir;
property MapResolution: Integer read FMapRes write FMapRes;
property MapColor: Integer read FMapColor write FMapColor;
// property MapSize: Integer read FMapSize write FMapSize;
end;
var
WM_GeoQuitMsgID: LongWord;
implementation
uses
Forms, SysUtils,UGlobals,Inifiles,fileCtrl,ShellApi,Dialogs,clipbrd,
UStrings, UStatus, UUtil1;
const
//in Geo's Config file set these parameters to T or F
strTrue = 'TRUE';
strFalse = 'FALSE';
strConfirmExportFile = 'ConfirmExportFile=';
strExportOnExit = 'ExportOnExit=';
strConfirmExportOnExit = 'ConfirmExportOnExit=';
strPrintHeader = 'PrintHeader=';
strPrintLegend = 'PrintLegend=';
strPageView = 'PageView=';
strLegendFormat = 'LegendFormat=';
strExportFormat = 'ExportFormat=';
strExportRes = 'ExportRes=';
strExportViewsFile = 'ExportViewsFile=';
strOnQuitNotify = 'Notify=';
//GeoLocator parameters for producing a map
GeoLocNoColor = 'TIFMono';
GeoLocColor = 'TIFColor';
GeoLocLowRes = 'LOW';
GeoLocMediumRes = 'MEDIUM';
GeoLocHighRes = 'HIGH';
cMapResHigh = 0;
cMapResMed = 1;
cMapResLow = 2;
cMapIsColor = 0;
cMapNoColor = 1;
// cMapLegalSize = 0;
// cMapLetterSize= 1;
// cMapHalfPgSize= 2;
//Dir in Tools where Geo stuff is located
cGeoFolder = 'Mapping\GeoLocator\';
//NOTE: Geo is 16-bit, so KEEP the file/folder names to 8.3 in length
cGeoLocWorkDir = 'ToolBox'; //this where data files are stored in Geo's folder
cGeoLocCfgFile = 'TBXCfig.cfg'; //parameters and file names (main setup file)
cGeoLocViewFile = 'TBXG1Vue.dat'; //view parameters for returned map
cGeoLocInputFile = 'TBXGlMap.mif'; //property records to map: input
cGeoLocOutputFile = 'TBXGlMap.mdf'; //property records to map: output
cGeoLocProxFile = 'TBXGlMap.pof'; //returned proximity info is stored here
cGeoLocImagefile = 'TBXGlMap.tif'; //returned map image has this name
cGeoLocLegend = 'TBXGlLGD.frm'; //name of file for Geo to look for Legend inof needed for Prox's
StdLegenFormatFile = 'cma.frm';
//These are the map size definition files that are installed
cLegalViewFile = 'GeoLocatorLegalView.dat';
cLetterViewfile= 'GeoLocatorLetterView.dat';
cHalfPgViewFile= 'GeoLocatorHalfPgView.dat';
cFormatLegend = 'GeoLocatorLegend.frm';
// GeoLocCmdLineFmt = '-U "%s" -a %s -i %s %s pof'; //YAKOV WHY?
GeoLocCmdLineFmt = '-U %s -a %s -i %s %s pof';
GeoLocAddressFmtStr = '"%s","","%s","%s","","%s","","","%s","%s","","",' +
'"%s","","","","","","",';
// GeoLocCompLabel = '"PASTE01;0.50;0.00;%Type+%ID"';
// GeoLocCompLabel = '"PASTE01;0.50;0.00;%Type"';
GeoLocCompLabel = '"PASTE01;0.50;0.00;';
GeoLocSubjLabel = '"PASTE01;0.50;0.00;%Type"';
cSubjectPropID = 'S';
MaxProximityLen = 50;
constructor TGeoLocatorPort.Create;
begin
Inherited Create;
MapSizeIndex := cMapLegalSize;
FWorkDir := '';
FMapRes := cMapResMed;
FMapColor := cMapIsColor;
FQuitMsgID := 0;
end;
//Main call, make sure parameters have been set before calling Launch
procedure TGeolocatorPort.Launch;
var
cmdLine: String;
begin
try
CleanOutWorkDir; //setup WorkDir = geoLocator/ClickForms
SetupFormatLegendFile; //needed to get proximity results
SetupViewConfigFile; //copies the View.dat file to GeoLocator ClickForms folder
SetupConfigFile;
ExportAddresses;
CmdLine := Format(GeoLocCmdLineFmt,[IncludeTrailingPathDelimiter(WorkDir),
cGeoLocCfgFile,cGeoLocInputFile,cGeoLocOutputFile]);
if ShellExecute(Owner.Handle,'open',PChar(ApplicationPath),PChar(CmdLine),nil,SW_SHOWNORMAL) <= 32 then
raise EFCreateError.CreateFmt(errCannotRunTool,[ExtractFileName(ApplicationPath)]);
except
ShowNotice('There was a problem launching GeoLocator. Please ensure GeoLocator is properly installed.');
end;
end;
procedure TGeolocatorPort.SetupFormatLegendFile;
var
SrcFilePath,DstFilePath: String;
begin
if not FileExists(IncludeTrailingPathDelimiter(WorkDir)+cGeoLocLegend) then //its not there
begin
SrcFilePath := IncludeTrailingPathDelimiter(appPref_DirTools)+ cGeoFolder + cFormatLegend;
if not FileExists(SrcFilePath) then
begin
ShowNotice('The GeoLocator format file cannot be located. Please install in the Tool/Mapping/GeoLocator folder');
Exit;
end;
DstFilePath := IncludeTrailingPathDelimiter(workDir) + cGeoLocLegend;
try
CopyFile(Pchar(SrcFilePath), PChar(dstFilePath), False);
except
ShowNotice('There was a problem writing the GeoLocator format legend file.');
end;
end;
end;
procedure TGeolocatorPort.SetupConfigFile; //Create the alternate Geolocator Config File
var
cfgFile: TextFile;
cfgFilePath: String;
strResolution, strNotifyParam: String;
strColor: String;
begin
case MapColor of
cMapIsColor: strColor := GeoLocColor;
cMapNoColor: strColor := GeoLocNoColor;
end;
case MapResolution of
cMapResHigh: strResolution := GeoLocHighRes;
cMapResMed: strResolution := GeoLocMediumRes;
cMapResLow: strResolution := GeoLocLowRes;
end;
//This is WM_MSG we get back from Geo when its done
strNotifyParam := Format('%d(%d)',[Owner.Handle, WM_GeoQuitMsgID]);
try
try
cfgFilePath := IncludeTrailingPathDelimiter(WorkDir) + cGeoLocCfgFile;
Rewrite(cfgFile,cfgFilePath);
WriteLn(cfgFile,strConfirmExportFile + strFalse);
WriteLn(cfgFile,strConfirmExportOnExit + strTrue);
WriteLn(cfgFile,strExportOnExit + strTrue);
WriteLn(cfgFile,strPrintHeader + strFalse);
WriteLn(cfgFile,strPrintLegend + strFalse);
WriteLn(cfgFile,strPageView + strTrue);
// WriteLn(cfgFile,strLegendFormat + StdLegenFormatFile);
WriteLn(cfgFile,strLegendFormat + IncludeTrailingPathDelimiter(workDir)+ cGeoLocLegend);
WriteLn(cfgFile,strExportFormat + strColor);
WriteLn(cfgFile,strExportRes + strResolution);
WriteLn(cfgFile,strExportViewsFile + IncludeTrailingPathDelimiter(workDir) + cGeoLocViewFile);
WriteLn(cfgFile,strOnQuitNotify + strNotifyParam);
finally
Flush(cfgFile);
CloseFile(cfgFile);
end;
except
ShowNotice('There was a problem writing the GeoLocator configuration file.');
end;
end;
procedure TGeolocatorPort.SetupViewConfigFile;
var
SrcFilePath,DstFilePath: String;
begin
SrcFilePath := IncludeTrailingPathDelimiter(appPref_DirTools)+ cGeoFolder;
DstFilePath := IncludeTrailingPathDelimiter(workDir) + cGeoLocViewFile;
case MapSizeIndex of
cMapLegalSize : SrcFilePath := SrcFilePath + cLegalViewFile;
cMapLetterSize : SrcFilePath := SrcFilePath + cLetterViewfile;
cMapHalfPgSize : SrcFilePath := SrcFilePath + cHalfPgViewFile;
end;
try
CopyFile(Pchar(SrcFilePath), PChar(dstFilePath), False);
except
ShowNotice('There was a problem writing the GeoLocator view configuration file.');
end;
end;
(*
function TGeoLocatorPort.RemoveLabelID(strLabel: String): String;
var
i,n: Integer;
begin
n := length(strLabel);
for i := n downto 1 do
if strLabel[i] in ['0'..'9'] then
delete(strLabel, i,1);
Strlabel := Trim(Strlabel); //no spaces
//GeoLocator cannot handle Sales, needs Comps
i := POS('SALE',strLabel);
if i > 0 then
begin
Delete(strLabel, i, i+3);
Insert('COMP', strLabel, i);
end;
result := 'COMP'; //Strlabel;
end;
*)
function TGeolocatorPort.ExportAddresses: Boolean;
var
mifFile: TextFile;
mifFilePath: String;
n,i: Integer;
strProperty, strPropertyID: String;
begin
result := False;
if Addresses <> nil then //we have some addresses to map
begin
n := Addresses.count;
mifFilePath := IncludeTrailingPathDelimiter(workDir) + cGeoLocInputFile;
if n > 0 then
try
Rewrite(mifFile,mifFilePath);
for i := 0 to n-1 do
with TAddressData(Addresses[i]) do
begin
strPropertyID := IntToStr(i);
if (i=0) then //handle subject differently
strProperty := Format(GeoLocAddressFmtStr,[
cSubjectPropID,
FStreetNo,FStreetName,FCity,FState,FZip,
FLabel]) + GeoLocSubjLabel
else
strProperty := Format(GeoLocAddressFmtStr,[
strPropertyID,
FStreetNo,FStreetName,FCity,FState,FZip,
// FLabel]) + GeoLocCompLabel;
// RemoveLabelID(FLabel)]) + GeoLocCompLabel + FLabel +'"';
'COMP' ]) + GeoLocCompLabel + FLabel +'"';
WriteLn(mifFile,strProperty);
end;
finally
Flush(mifFile);
CloseFile(mifFile);
end;
result := FileExists(mifFilePath);
end;
end;
function WaitUntilFileIsThere(fName: String): Boolean;
var
i: integer;
begin
i := 1;
repeat
// if i = 10000 then showNotice('file not ready '+ fName);
result := FileExists(FName);
Application.ProcessMessages;
inc(i);
until (result = true) or (i > 10000);
end;
//when the ToolMgr gets the quit msg, it calls Geo's ImportResults.
//Now the ToolMgr can get the data and do what it wants
function TGeolocatorPort.ImportResults: Boolean;
var
pofFilePath: String; //resulting proximity file
ProxRecs: TStringList;
StrID: String;
n,i,k: Integer;
begin
//get the map image file
FileDataPath := IncludeTrailingPathDelimiter(workDir) + cGeoLocImagefile;
result := WaitUntilFileIsThere(FileDataPath);
// result := FileExists(FileDataPath);
if not result then //the map image file does not exist
begin
ShowNotice('A map file was not created.');
Exit;
end;
//get the proximity records
pofFilePath := IncludeTrailingPathDelimiter(workDir) + cGeoLocProxFile;
if FileExists(pofFilePath) then
begin
//place results into Address object, its owned by ToolMapMgr.
//GeoLocator does not garantee the record order in the POF file
//so have to get id first, then match up with address order
ProxRecs := TStringList.Create;
try
ProxRecs.LoadFromFile(pofFilePath);
n := ProxRecs.count;
for i := 0 to n-1 do
begin
StrID := GetFirstCommaDelimitedField(ProxRecs[i]);
if StrID = 'S' then continue; //skip the subject
//k := StrToInt(GetFirstCommaDelimitedField(ProxRecs[i]));
k := StrToIntDef(GetFirstCommaDelimitedField(ProxRecs[i]),0);
if (k > 0) and (k < Addresses.count) then
begin
TAddressData(Addresses[k]).FProximity := AnsiDequotedStr(GetCommaDelimitedField(2, ProxRecs[i]),'"')
// TAddressData(Addresses[k]).FProximity := GetCommaDelimitedField(2, ProxRecs[i]);
end;
end;
finally
ProxRecs.Free;
end;
end;
end;
//setup the GeoLocator Working Directory
function TGeolocatorPort.GetWorkDir: String;
begin
result := FWorkDir;
if result = '' then
try
result := GetWindowsTempDirectory + '\' + cGeoLocWorkDir; //use the local hard disk's temp directory -- helps the network Geo users
//result := IncludeTrailingPathDelimiter(ExtractFileDir(ApplicationPath)) + cGeoLocWorkDir;
if not DirectoryExists(result) then
CreateDir(result);
FWorkDir := result; //remember it
except
ShowNotice('Could not create a working directory for GeoLocator.');
end;
end;
//Cleanout and previously existing data files
procedure TGeolocatorPort.CleanOutWorkDir;
begin
DeleteFile(IncludeTrailingPathDelimiter(workDir) + cGeoLocCfgFile);
DeleteFile(IncludeTrailingPathDelimiter(workDir) + cGeoLocViewFile);
DeleteFile(IncludeTrailingPathDelimiter(workDir) + cGeoLocInputFile);
DeleteFile(IncludeTrailingPathDelimiter(workDir) + cGeoLocOutputFile);
DeleteFile(IncludeTrailingPathDelimiter(workDir) + cGeoLocProxFile);
DeleteFile(IncludeTrailingPathDelimiter(workDir) + cGeoLocImagefile);
end;
initialization
WM_GeoQuitMsgID := RegisterWindowMessage(GeoLocQuitMsgID);
end.
|
unit OAuth2.Grant.AbstractGrant;
interface
uses
Web.HTTPApp,
OAuth2.Contract.Grant.GrantType,
OAuth2.Contract.ResponseType,
OAuth2.Contract.Repository.Client,
OAuth2.Contract.Repository.AccessToken,
OAuth2.Contract.Repository.Scope,
OAuth2.Contract.Repository.AuthCode,
OAuth2.Contract.Repository.RefreshToken,
OAuth2.Contract.Repository.User,
OAuth2.Contract.Entity.Client,
OAuth2.Contract.Entity.Scope,
OAuth2.Contract.Entity.AccessToken,
OAuth2.Contract.Entity.AuthCode,
OAuth2.Contract.Entity.RefreshToken,
OAuth2.RequestType.AuthorizationRequest,
OAuth2.CryptKey;
type
TBasicAuthCredentials = record
private
FBasicAuthUser: string;
FBasicAuthPassword: string;
public
constructor Create(ABasicAuthUser: string; ABasicAuthPassword: string);
function GetBasicAuthUser: string;
function GetBasicAuthPassword: string;
end;
TClientCredentials = record
private
FClientId: string;
FClientSecret: string;
public
constructor Create(AClientId: string; AClientSecret: string);
function GetClientId: string;
function GetClientSecret: string;
end;
TOAuth2AbstractGrant = class(TInterfacedObject, IOAuth2GrantTypeGrant)
private
{ private declarations }
FClientRepository: IOAuth2ClientRepository;
FAccessTokenRepository: IOAuth2AccessTokenRepository;
FScopeRepository: IOAuth2ScopeRepository;
FAuthCodeRepository: IOAuth2AuthCodeRepository;
FRefreshTokenRepository: IOAuth2RefreshTokenRepository;
FUserRepository: IOAuth2UserRepository;
FRefreshTokenTTL: Int64;
FPrivateKey: TOAuth2CryptKey;
FDefaultScope: string;
FEncryptionKey: string;
protected
const
MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS = 10;
SCOPE_DELIMITER_STRING = ' ';
protected
{ protected declarations }
procedure ValidateRedirectUri(ARedirectUri: string; AClient: IOAuth2ClientEntity; ARequest: TWebRequest);
function ValidateClient(ARequest: TWebRequest): IOAuth2ClientEntity;
function GetBasicAuthCredentials(ARequest: TWebRequest): TBasicAuthCredentials;
function GetClientCredentials(ARequest: TWebRequest): TClientCredentials;
function GetClientEntityOrFail(AClientId: string; ARequest: TWebRequest): IOAuth2ClientEntity;
function ValidateScopes(AScopes: string; const ARedirectUri: string = ''): TArray<IOAuth2ScopeEntity>;
function GetRequestParameter(AParameter: string; ARequest: TWebRequest; const ADefault: string = ''): string;
function GetQueryStringParameter(AParameter: string; ARequest: TWebRequest; const ADefault: string = ''): string;
function GetCookieParameter(AParameter: string; ARequest: TWebRequest; const ADefault: string = ''): string;
function GenerateUniqueIdentifier(const ALength: Integer = 40): string;
function IssueAccessToken(AAccessTokenTTL: Int64; AClient: IOAuth2ClientEntity; AUserIdentifier: string; AScopes: TArray<IOAuth2ScopeEntity>): IOAuth2AccessTokenEntity;
function IssueAuthCode(AAuthCodeTTL: Int64; AClient: IOAuth2ClientEntity; AUserIdentifier: string; ARedirectUri: string; AScopes: TArray<IOAuth2ScopeEntity>)
: IOAuth2AuthCodeEntity;
function IssueRefreshToken(AAccessToken: IOAuth2AccessTokenEntity): IOAuth2RefreshTokenEntity;
function ConvertScopesQueryStringToArray(AScopes: string): TArray<string>;
function GetEncryptionKey: string;
function GetScopeRepository: IOAuth2ScopeRepository;
function GetAuthCodeRepository: IOAuth2AuthCodeRepository;
function GetUserRepository: IOAuth2UserRepository;
function GetRefreshTokenRepository: IOAuth2RefreshTokenRepository;
function GetAccessTokenRepository: IOAuth2AccessTokenRepository;
function GetDefaultScope: string;
public
{ public declarations }
function GetIdentifier: string; virtual;
function RespondToAccessTokenRequest(ARequest: TWebRequest; AResponseType: IOAuth2ResponseType; AAccessTokenTTL: Int64): IOAuth2ResponseType; virtual;
function CanRespondToAuthorizationRequest(ARequest: TWebRequest): Boolean; virtual;
function ValidateAuthorizationRequest(ARequest: TWebRequest): TOAuth2AuthorizationRequest; virtual;
function CompleteAuthorizationRequest(AAuthorizationRequest: TOAuth2AuthorizationRequest): IOAuth2ResponseType; virtual;
function CanRespondToAccessTokenRequest(ARequest: TWebRequest): Boolean; virtual;
procedure SetRefreshTokenTTL(ARefreshTokenTTL: Int64); virtual;
procedure SetClientRepository(AClientRepository: IOAuth2ClientRepository);
procedure SetAccessTokenRepository(AAccessTokenRepository: IOAuth2AccessTokenRepository);
procedure SetScopeRepository(AScopeRepository: IOAuth2ScopeRepository);
procedure SetRefreshTokenRepository(ARefreshTokenRepository: IOAuth2RefreshTokenRepository); virtual;
procedure SetAuthCodeRepository(AAuthCodeRepository: IOAuth2AuthCodeRepository);
procedure SetUserRepository(AUserRepository: IOAuth2UserRepository);
procedure SetDefaultScope(ADefaultScope: string);
procedure SetPrivateKey(APrivateKey: TOAuth2CryptKey);
procedure SetEncryptionKey(AKey: string);
end;
implementation
uses
System.Hash,
System.StrUtils,
System.NetEncoding,
System.SysUtils,
System.DateUtils,
OAuth2.Exception.ServerException;
{ TOAuth2AbstractGrant }
function TOAuth2AbstractGrant.CanRespondToAccessTokenRequest(ARequest: TWebRequest): Boolean;
begin
Result := (ARequest.ContentFields.IndexOfName('grant_type') > -1) and (ARequest.ContentFields.Values['grant_type'] = GetIdentifier);
end;
function TOAuth2AbstractGrant.CanRespondToAuthorizationRequest(ARequest: TWebRequest): Boolean;
begin
Result := False;
end;
function TOAuth2AbstractGrant.CompleteAuthorizationRequest(AAuthorizationRequest: TOAuth2AuthorizationRequest): IOAuth2ResponseType;
begin
raise Exception.Create('This grant cannot complete an authorization request');
end;
function TOAuth2AbstractGrant.ConvertScopesQueryStringToArray(AScopes: string): TArray<string>;
begin
Result := AScopes.Split([SCOPE_DELIMITER_STRING]);
end;
function TOAuth2AbstractGrant.GenerateUniqueIdentifier(const ALength: Integer = 40): string;
begin
Result := THash.GetRandomString(ALength);
end;
function TOAuth2AbstractGrant.GetAccessTokenRepository: IOAuth2AccessTokenRepository;
begin
Result := FAccessTokenRepository;
end;
function TOAuth2AbstractGrant.GetAuthCodeRepository: IOAuth2AuthCodeRepository;
begin
Result := FAuthCodeRepository;
end;
function TOAuth2AbstractGrant.GetBasicAuthCredentials(ARequest: TWebRequest): TBasicAuthCredentials;
var
LAuthorizationHeader: string;
LDecodedBasicAuth: string;
LExplodedBasicAuth: TArray<string>;
begin
LAuthorizationHeader := ARequest.Authorization;
if LAuthorizationHeader = EmptyStr then
Exit(TBasicAuthCredentials.Create(EmptyStr, EmptyStr));
if not LAuthorizationHeader.StartsWith('Basic ') then
Exit(TBasicAuthCredentials.Create(EmptyStr, EmptyStr));
try
LDecodedBasicAuth := TNetEncoding.Base64.Decode(LAuthorizationHeader.Replace('Basic ', ''));
except
Exit(TBasicAuthCredentials.Create(EmptyStr, EmptyStr));
end;
LExplodedBasicAuth := LDecodedBasicAuth.Split([':']);
Exit(TBasicAuthCredentials.Create(LExplodedBasicAuth[0], LExplodedBasicAuth[1]));
end;
function TOAuth2AbstractGrant.GetClientCredentials(ARequest: TWebRequest): TClientCredentials;
var
LBasicAuthCredentials: TBasicAuthCredentials;
LClientId: string;
LClientSecret: string;
begin
LBasicAuthCredentials := GetBasicAuthCredentials(ARequest);
LClientId := GetRequestParameter('client_id', ARequest, LBasicAuthCredentials.GetBasicAuthUser);
if LClientId.IsEmpty then
raise EOAuth2ServerException.InvalidRequest('client_id');
LClientSecret := GetRequestParameter('client_secret', ARequest, LBasicAuthCredentials.GetBasicAuthPassword);
Exit(TClientCredentials.Create(LClientId, LClientSecret));
end;
function TOAuth2AbstractGrant.GetClientEntityOrFail(AClientId: string; ARequest: TWebRequest): IOAuth2ClientEntity;
begin
Result := FClientRepository.GetClientEntity(AClientId);
if Result = nil then
raise EOAuth2ServerException.InvalidClient(ARequest);
end;
function TOAuth2AbstractGrant.GetCookieParameter(AParameter: string; ARequest: TWebRequest; const ADefault: string): string;
begin
if ARequest.CookieFields.IndexOfName(AParameter) = -1 then
Exit(ADefault);
Exit(ARequest.CookieFields.Values[AParameter]);
end;
function TOAuth2AbstractGrant.GetDefaultScope: string;
begin
Result := FDefaultScope;
end;
function TOAuth2AbstractGrant.GetEncryptionKey: string;
begin
Result := FEncryptionKey;
end;
function TOAuth2AbstractGrant.GetIdentifier: string;
begin
end;
function TOAuth2AbstractGrant.GetQueryStringParameter(AParameter: string; ARequest: TWebRequest; const ADefault: string): string;
begin
if ARequest.QueryFields.IndexOfName(AParameter) = -1 then
Exit(ADefault);
Exit(ARequest.QueryFields.Values[AParameter]);
end;
function TOAuth2AbstractGrant.GetRefreshTokenRepository: IOAuth2RefreshTokenRepository;
begin
Result := FRefreshTokenRepository;
end;
function TOAuth2AbstractGrant.GetRequestParameter(AParameter: string; ARequest: TWebRequest; const ADefault: string = ''): string;
begin
if ARequest.ContentFields.IndexOfName(AParameter) = -1 then
Exit(ADefault);
Exit(ARequest.ContentFields.Values[AParameter]);
end;
function TOAuth2AbstractGrant.GetScopeRepository: IOAuth2ScopeRepository;
begin
Result := FScopeRepository;
end;
function TOAuth2AbstractGrant.GetUserRepository: IOAuth2UserRepository;
begin
Result := FUserRepository;
end;
function TOAuth2AbstractGrant.IssueAccessToken(AAccessTokenTTL: Int64; AClient: IOAuth2ClientEntity; AUserIdentifier: string; AScopes: TArray<IOAuth2ScopeEntity>)
: IOAuth2AccessTokenEntity;
var
LMaxGenerationAttempts: Integer;
begin
LMaxGenerationAttempts := MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
Result := FAccessTokenRepository.GetNewToken(AClient, AScopes, AUserIdentifier);
Result.SetExpiryDateTime(IncSecond(Now(), AAccessTokenTTL));
Result.SetPrivateKey(FPrivateKey);
while LMaxGenerationAttempts > 0 do
begin
Dec(LMaxGenerationAttempts);
Result.SetIdentifier(GenerateUniqueIdentifier);
try
FAccessTokenRepository.PersistNewAccessToken(Result);
Break;
except
on E: Exception do
begin
if LMaxGenerationAttempts = 0 then
raise E
else
continue;
end;
end;
end;
end;
function TOAuth2AbstractGrant.IssueAuthCode(AAuthCodeTTL: Int64; AClient: IOAuth2ClientEntity; AUserIdentifier: string; ARedirectUri: string; AScopes: TArray<IOAuth2ScopeEntity>)
: IOAuth2AuthCodeEntity;
var
LMaxGenerationAttempts: Integer;
LScope: IOAuth2ScopeEntity;
begin
LMaxGenerationAttempts := MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
Result := FAuthCodeRepository.GetNewAuthCode;
Result.SetExpiryDateTime(IncSecond(Now(), AAuthCodeTTL));
Result.SetClient(AClient);
Result.SetUserIdentifier(AUserIdentifier);
Result.SetRedirectUri(ARedirectUri);
for LScope in AScopes do
Result.AddScope(LScope);
while LMaxGenerationAttempts > 0 do
begin
Dec(LMaxGenerationAttempts);
Result.SetIdentifier(GenerateUniqueIdentifier);
try
FAuthCodeRepository.PersistNewAuthCode(Result);
Break;
except
on E: Exception do
begin
if LMaxGenerationAttempts = 0 then
raise E;
continue;
end;
end;
end;
end;
function TOAuth2AbstractGrant.IssueRefreshToken(AAccessToken: IOAuth2AccessTokenEntity): IOAuth2RefreshTokenEntity;
var
LMaxGenerationAttempts: Integer;
begin
Result := FRefreshTokenRepository.GetNewRefreshToken;
if Result = nil then
Exit;
Result.SetExpiryDateTime(IncSecond(Now(), FRefreshTokenTTL));
Result.SetAccessToken(AAccessToken);
LMaxGenerationAttempts := MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
while LMaxGenerationAttempts > 0 do
begin
Dec(LMaxGenerationAttempts);
Result.SetIdentifier(GenerateUniqueIdentifier);
try
FRefreshTokenRepository.PersistNewRefreshToken(Result);
Break;
except
on E: Exception do
begin
if LMaxGenerationAttempts = 0 then
raise E;
continue;
end;
end;
end;
end;
function TOAuth2AbstractGrant.RespondToAccessTokenRequest(ARequest: TWebRequest; AResponseType: IOAuth2ResponseType; AAccessTokenTTL: Int64): IOAuth2ResponseType;
begin
end;
procedure TOAuth2AbstractGrant.SetAccessTokenRepository(AAccessTokenRepository: IOAuth2AccessTokenRepository);
begin
FAccessTokenRepository := AAccessTokenRepository;
end;
procedure TOAuth2AbstractGrant.SetAuthCodeRepository(AAuthCodeRepository: IOAuth2AuthCodeRepository);
begin
FAuthCodeRepository := AAuthCodeRepository;
end;
procedure TOAuth2AbstractGrant.SetClientRepository(AClientRepository: IOAuth2ClientRepository);
begin
FClientRepository := AClientRepository;
end;
procedure TOAuth2AbstractGrant.SetDefaultScope(ADefaultScope: string);
begin
FDefaultScope := ADefaultScope;
end;
procedure TOAuth2AbstractGrant.SetEncryptionKey(AKey: string);
begin
FEncryptionKey := AKey;
end;
procedure TOAuth2AbstractGrant.SetPrivateKey(APrivateKey: TOAuth2CryptKey);
begin
FPrivateKey := APrivateKey;
end;
procedure TOAuth2AbstractGrant.SetRefreshTokenRepository(ARefreshTokenRepository: IOAuth2RefreshTokenRepository);
begin
FRefreshTokenRepository := ARefreshTokenRepository;
end;
procedure TOAuth2AbstractGrant.SetRefreshTokenTTL(ARefreshTokenTTL: Int64);
begin
FRefreshTokenTTL := ARefreshTokenTTL;
end;
procedure TOAuth2AbstractGrant.SetScopeRepository(AScopeRepository: IOAuth2ScopeRepository);
begin
FScopeRepository := AScopeRepository;
end;
procedure TOAuth2AbstractGrant.SetUserRepository(AUserRepository: IOAuth2UserRepository);
begin
FUserRepository := AUserRepository;
end;
function TOAuth2AbstractGrant.ValidateAuthorizationRequest(ARequest: TWebRequest): TOAuth2AuthorizationRequest;
begin
raise Exception.Create('This grant cannot validate an authorization request');
end;
function TOAuth2AbstractGrant.ValidateClient(ARequest: TWebRequest): IOAuth2ClientEntity;
var
LClientCredentials: TClientCredentials;
LClient: IOAuth2ClientEntity;
LRedirectUri: string;
begin
LClientCredentials := GetClientCredentials(ARequest);
if (not FClientRepository.ValidateClient(LClientCredentials.GetClientId, LClientCredentials.GetClientSecret, GetIdentifier)) then
raise EOAuth2ServerException.InvalidClient(ARequest);
LClient := GetClientEntityOrFail(LClientCredentials.GetClientId, ARequest);
LRedirectUri := GetRequestParameter('redirect_uri', ARequest, EmptyStr);
if not LRedirectUri.IsEmpty then
begin
ValidateRedirectUri(LRedirectUri, LClient, ARequest);
end;
Exit(LClient)
end;
procedure TOAuth2AbstractGrant.ValidateRedirectUri(ARedirectUri: string; AClient: IOAuth2ClientEntity; ARequest: TWebRequest);
begin
if (Length(AClient.GetRedirectUri) > 0) and (IndexStr(ARedirectUri, AClient.GetRedirectUri) = -1) then
raise EOAuth2ServerException.InvalidClient(ARequest);
end;
function TOAuth2AbstractGrant.ValidateScopes(AScopes: string; const ARedirectUri: string): TArray<IOAuth2ScopeEntity>;
var
LScopes: TArray<string>;
LScopeItem: string;
LScope: IOAuth2ScopeEntity;
LValidScopes: TArray<IOAuth2ScopeEntity>;
I: Integer;
begin
Result := [];
LValidScopes := [];
LScopes := ConvertScopesQueryStringToArray(AScopes);
for I := Low(LScopes) to High(LScopes) do
begin
LScopeItem := LScopes[I];
LScope := FScopeRepository.GetScopeEntityByIdentifier(LScopeItem);
if LScope = nil then
raise EOAuth2ServerException.InvalidScope(LScopeItem, ARedirectUri);
LValidScopes := LValidScopes + [LScope];
end;
Result := LValidScopes;
end;
{ TBasicAuthCredentials }
function TBasicAuthCredentials.GetBasicAuthPassword: string;
begin
Result := FBasicAuthPassword;
end;
function TBasicAuthCredentials.GetBasicAuthUser: string;
begin
Result := FBasicAuthUser;
end;
constructor TBasicAuthCredentials.Create(ABasicAuthUser, ABasicAuthPassword: string);
begin
FBasicAuthUser := ABasicAuthUser;
FBasicAuthPassword := ABasicAuthPassword;
end;
{ TClientCredentials }
constructor TClientCredentials.Create(AClientId: string; AClientSecret: string);
begin
FClientId := AClientId;
FClientSecret := AClientSecret;
end;
function TClientCredentials.GetClientId: string;
begin
Result := FClientId;
end;
function TClientCredentials.GetClientSecret: string;
begin
Result := FClientSecret;
end;
end.
|
unit FindDialogUnit;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{$IFnDEF FPC}
Windows,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons, SynEdit, SynEditTypes ;
type
TFindDialog = class(TForm)
editFindText: TComboBox;
lblTextToFind: TLabel;
btnFind: TBitBtn;
btnCancel: TBitBtn;
Direction: TRadioGroup;
cbMatchWord: TCheckBox;
cbbMatchCase: TCheckBox;
cbFromCursor: TCheckBox;
procedure btnFindClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure editFindTextExit(Sender: TObject);
private
{ Private declarations }
FSynEdit :TSynEdit;
FNextCan :boolean;
function GetFindText :string;
procedure SetFindText(value :string);
procedure DoFindText;
public
{ Public declarations }
Options: TSynSearchOptions;
procedure FindNext;
procedure Execute(ASynEdit :TSynEdit);
property NextCan :boolean read FNextCan;
property FindText :string read GetFindText write SetFindText;
property SynEdit :TSynEdit read FSynEdit write FSynEdit;
end;
var
FindDialog: TFindDialog;
RecoverText :string;
Found:boolean;
implementation
{$R *.dfm}
uses MainUnit;
function TFindDialog.GetFindText :string;
begin
Result := editFindText.Text
end;
procedure TFindDialog.SetFindText(value :string);
begin
editFindText.Text := value;
EditFindText.SelectAll ;
RecoverText := value;
end;
procedure TFindDialog.Execute(ASynEdit :TSynEdit);
begin
FSynEdit := ASynEdit ;
if fSynEdit<>nil then
if FSynEdit.SelText <> '' then
editFindText.Text := FSynEdit.SelText;
Visible := true;
end;
procedure TFindDialog.DoFindText;
var
sSearch: string;
begin
sSearch := FindText;
if FSynEdit <> nil then
if FSynEdit.SelText <> '' then
editFindText.Text := FSynEdit.SelText;
if (sSearch = '') and (Visible = false) then
sSearch := RecoverText;
if Length(sSearch) = 0 then begin
Beep;
MessageDlg( 'Wrong word. Can''t be wide one.',mtInformation,[mbok],0);
FNextCan := false;
end else begin
Options := [];
if Direction.ItemIndex = 1 then
Include(Options, ssoBackwards);
if cbbMatchCase.Checked then
Include(Options, ssoMatchCase);
if cbMatchWord.Checked then
Include(Options, ssoWholeWord);
if cbFromCursor.Checked then begin
Include(Options, ssoEntireScope);
if SynEdit.SelAvail and (SynEdit.BlockBegin.Line = SynEdit.BlockEnd.Line) then
sSearch := SynEdit.SelText
else
sSearch := SynEdit.GetWordAtRowCol(SynEdit.CaretXY);
end;
RecoverText := sSearch;
if FSynEdit.SearchReplace(sSearch, '', Options) = 0 then begin
MessageBeep(MB_ICONASTERISK);
if ssoBackwards in Options then
SynEdit.BlockEnd := SynEdit.BlockBegin
else
SynEdit.BlockBegin := SynEdit.BlockEnd;
SynEdit.CaretXY := SynEdit.BlockBegin;
MessageDlg(format('Wrong %s. can''t be wide.',[sSearch]),mtInformation,[mbok],0);
FNextCan := false;
end else
FNextCan := true;
end;
end;
procedure TFindDialog.btnFindClick(Sender: TObject);
begin
if FSynEdit <> nil then
DoFindText
end;
procedure TFindDialog.btnCancelClick(Sender: TObject);
begin
Close
end;
procedure TFindDialog.FormShow(Sender: TObject);
begin
Found:=false;
if fSynEdit=nil then
if ActiveEditor<>nil then
fSynEdit:=ActiveEditor.Frame.Edit;
if fSynEdit<>nil then
if FSynEdit.SelText <> '' then
editFindText.Text := FSynEdit.SelText;
btnFind.Enabled:=fSynEdit<>nil;
end;
procedure TFindDialog.FindNext;
begin
DoFindText;
end;
procedure TFindDialog.editFindTextExit(Sender: TObject);
begin
if editFindText.Items.IndexOf(editFindText.Text) = -1 then
editFindText.Items.Add(editFindText.Text)
end;
end.
|
{***************************************************************************}
{ }
{ DelphiUIAutomation }
{ }
{ Copyright 2015 JHC Systems Limited }
{ }
{***************************************************************************}
{ }
{ 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 DelphiUIAutomation.Container;
interface
uses
DelphiUIAutomation.Tab.Intf,
DelphiUIAutomation.EditBox,
DelphiUIAutomation.TextBox,
DelphiUIAutomation.CheckBox,
DelphiUIAutomation.Container.Intf,
DelphiUIAutomation.panel.Intf,
DelphiUIAutomation.RadioButton,
DelphiUIAutomation.ComboBox,
DelphiUIAutomation.Button,
DelphiUIAutomation.Panel,
DelphiUIAutomation.Menu,
DelphiUIAutomation.Base,
DelphiUIAutomation.TreeView,
DelphiUIAutomation.StringGrid,
UIAutomationClient_TLB;
type
/// <summary>
/// Finds the tab
/// </summary>
TAutomationContainer = class (TAutomationBase, IAutomationContainer)
protected
function GetControlByControlType (index : integer; id : word) : IUIAutomationElement; overload;
function GetControlByControlType (index : integer; id: word; controlType : string) : IUIAutomationElement; overload;
// function GetControlByControlType (title : string; id : word) : IUIAutomationElement; overload;
function GetControlByControlType1 (title : string; id : word) : IUIAutomationElement; overload;
public
/// <summary>
/// Finds the tab
/// </summary>
function GetTabByIndex (index : integer) : IAutomationTab;
/// <summary>
/// Finds the editbox, by index
/// </summary>
function GetEditBoxByIndex (index : integer) : IAutomationEditBox;
/// <summary>
/// Finds the textbox, by index
/// </summary>
function GetTextBoxByIndex(index: integer): IAutomationTextBox;
/// <summary>
/// Finds the combobox, by index
/// </summary>
function GetComboboxByIndex (index : integer) : IAutomationComboBox;
/// <summary>
/// Finds the stringgrid, by index
/// </summary>
function GetStringGridByIndex (index : integer) : IAutomationStringGrid;
/// <summary>
/// Finds the checkbox, by index
/// </summary>
function GetCheckboxByIndex (index : integer) : IAutomationCheckBox;
/// <summary>
/// Finds a panel, by index
/// </summary>
function GetPanelByIndex (index : integer) : IAutomationPanel;
/// <summary>
/// Finds the checkbox, by name
/// </summary>
function GetCheckboxByName(const value: string): IAutomationCheckBox;
/// <summary>
/// Finds the checkbox, by index
/// </summary>
function GetRadioButtonByIndex (index : integer) : IAutomationRadioButton;
/// <summary>
/// Finds the button with the title supplied
/// </summary>
function GetButton (const title : string) : IAutomationButton;
/// <summary>
/// Finds the editbox, by name
/// </summary>
function GetEditBoxByName (name: String) : IAutomationEditBox;
/// <summary>
/// Finds the combobox, by name
/// </summary>
function GetComboboxByName (name : String) : IAutomationComboBox;
/// <summary>
/// Finds the treeview, by index
/// </summary>
function GetTreeViewByIndex (index: Integer): IAutomationTreeView;
end;
implementation
uses
windows,
sysutils,
ActiveX,
DelphiUIAutomation.Tab,
DelphiUIAutomation.Condition,
DelphiUIAutomation.PropertyIDs,
DelphiUIAutomation.ControlTypeIDs,
DelphiUIAutomation.Exception,
DelphiUIAutomation.Automation;
function TAutomationContainer.GetCheckboxByName(const value: string): IAutomationCheckBox;
begin
result := TAutomationCheckBox.Create(GetControlByControlType1(value, UIA_CheckBoxControlTypeId));
end;
function TAutomationContainer.GetEditBoxByIndex(index: integer): IAutomationEditBox;
var
eb : IUIAutomationElement;
begin
eb := GetControlByControlType(index, UIA_EditControlTypeId);
result := TAutomationEditBox.Create(eb);
end;
function TAutomationContainer.GetPanelByIndex(index: integer): IAutomationPanel;
var
tb : IUIAutomationElement;
begin
tb := GetControlByControlType(index, UIA_PaneControlTypeId);
result := TAutomationPanel.Create(tb);
end;
function TAutomationContainer.GetTextBoxByIndex(index: integer): IAutomationTextBox;
var
tb : IUIAutomationElement;
begin
tb := GetControlByControlType(index, UIA_TextControlTypeId);
result := TAutomationTextBox.Create(tb);
end;
function TAutomationContainer.GetTreeViewByIndex(
index: Integer): IAutomationTreeView;
var
treeView : IUIAutomationElement;
begin
treeView := GetControlByControlType(0, UIA_TreeControlTypeId);
result := TAutomationTreeView.Create(treeView);
end;
function TAutomationContainer.GetButton(const title: string): IAutomationButton;
var
btn : IUIAutomationElement;
begin
btn := GetControlByControlType1(title, UIA_ButtonControlTypeId);
result := TAutomationButton.Create(btn);
end;
function TAutomationContainer.GetCheckboxByIndex(index: integer): IAutomationCheckBox;
begin
result := TAutomationCheckBox.Create(GetControlByControlType(index, UIA_CheckBoxControlTypeId));
end;
function TAutomationContainer.GetComboboxByIndex (index : integer) : IAutomationComboBox;
begin
result := TAutomationComboBox.Create(GetControlByControlType(index, UIA_ComboBoxControlTypeId));
end;
function TAutomationContainer.GetControlByControlType1(title: string; id: word): IUIAutomationElement;
var
condition, condition1, condition2: ICondition;
element : IUIAutomationElement;
begin
condition1 := TuiAuto.createNameCondition(title);
condition2 := TuiAuto.createControlTypeCondition(id);
condition := TUIAuto.createAndCondition(condition1, condition2);
self.FElement.FindFirst(TreeScope_Descendants, condition.getCondition, element);
result := element;
end;
function TAutomationContainer.GetControlByControlType(index: integer; id: word;
controlType: string): IUIAutomationElement;
var
element : IUIAutomationElement;
collection : IUIAutomationElementArray;
condition : IUIAutomationCondition;
count : integer;
length : integer;
counter : integer;
varProp : OleVariant;
CName : WideString;
begin
element := nil;
TVariantArg(varProp).vt := VT_I4;
TVariantArg(varProp).lVal := id; // At the moment it is always a pane
UIAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, varProp, condition);
// Find the element
self.FElement.FindAll(TreeScope_Descendants, condition, collection);
collection.Get_Length(length);
counter := 0;
for count := 0 to length -1 do
begin
collection.GetElement(count, element);
element.Get_CurrentClassName(CName);
if CName = controlType then
begin
if counter = index then
begin
result := element;
break;
end;
inc (counter);
end;
end;
// if result = nil then
// raise EDelphiAutomationException.Create('Unable to find control');
end;
function TAutomationContainer.GetControlByControlType(index : integer; id: word): IUIAutomationElement;
var
element : IUIAutomationElement;
collection : IUIAutomationElementArray;
condition : IUIAutomationCondition;
count : integer;
length : integer;
counter : integer;
varProp : OleVariant;
// For debugging
name : WideString;
begin
element := nil;
TVariantArg(varProp).vt := VT_I4;
TVariantArg(varProp).lVal := id;
UIAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, varProp, condition);
// Find the element
self.FElement.FindAll(TreeScope_Descendants, condition, collection);
collection.Get_Length(length);
counter := 0;
for count := 0 to length -1 do
begin
collection.GetElement(count, element);
element.Get_CurrentName(name);
OutputDebugString(pwidechar(name));
if counter = index then
begin
result := element;
break;
end;
inc (counter);
end;
// if result = nil then
// raise EDelphiAutomationException.Create('Unable to find control');
end;
function TAutomationContainer.GetRadioButtonByIndex(index: integer): IAutomationRadioButton;
begin
result := TAutomationRadioButton.Create(GetControlByControlType(index, UIA_RadioButtonControlTypeId));
end;
function TAutomationContainer.GetStringGridByIndex(index: integer): IAutomationStringGrid;
begin
result := TAutomationStringGrid.Create(GetControlByControlType(index, UIA_DataGridControlTypeId, 'TAutomationStringGrid'));
end;
function TAutomationContainer.GetTabByIndex (index : integer) : IAutomationTab;
begin
result := TAutomationTab.Create(GetControlByControlType(index, UIA_TabControlTypeId));
end;
function TAutomationContainer.GetEditBoxByName(
name: String): IAutomationEditBox;
var
eb : IUIAutomationElement;
begin
eb := GetControlByControlType1(name, UIA_EditControlTypeId);
result := TAutomationEditBox.Create(eb);
end;
function TAutomationContainer.GetComboboxByName(
name: String): IAutomationComboBox;
var
cb : IUIAutomationElement;
begin
cb := GetControlByControlType1(name, UIA_ComboBoxControlTypeId);
result := TAutomationComboBox.Create(cb);
end;
end.
|
unit UDPdiscover;
{
TUDPDiscover odpovida na UDP discover pozadavky a informauje zarizeni v siti
o existenci hJOPserveru. TUDPDiscover posila data na broadcast, predpoklada
se, ze prijmuta budou taky z broadcastu, ale to neni nutnou podminkou.
}
{
Format informacni zpravy je totozny pro pozadavek i pro odpoved:
textovy retezec ukonceny znaky #13#10 (novy radek) obsahujici informace
oddelene znakem ";":
Verze protokolu 1.0:
"hJOP";verze_protokolu;typ_zarizeni;server_nazev;server_ip;server_port;
server_status;server_popis
\typ_zarizeni:
a) "server"
b) "panel"
c) "regulator"
\server_status
a) off
b) on
}
{
hJOPserver odpovida na pozadavky, ktere \typ_zarizeni != "server",
tedy napriklad na pozadavek "hJOP;1.0;regulator;;192.168.5.13;" od regualtoru.
}
interface
uses IdUDPServer, IdUDPClient, Classes, IdSocketHandle, SysUtils,
Generics.Collections, ExtCtrls;
const
_DISC_DEFAULT_PORT = 5880;
_DISC_PROTOCOL_VERSION = '1.0';
_DISC_REPEAT = 2;
_DISC_PORT_RANGE = 2;
type
TUDPDiscover = class
private
UDPserver : TIdUDPServer;
fPort:Word;
fName, fDescription:string;
parsed:TStrings;
broadcasts:TDictionary<string, string>;
updateBindTimer:TTimer;
procedure OnUDPServerRead(AThread: TIdUDPListenerThread;
AData: TBytes; ABinding: TIdSocketHandle);
procedure SendDisc(ABinding: TIdSocketHandle; port:Word);
procedure SetName(name:string);
procedure SetDescription(desc:string);
procedure UpdateBindings();
procedure OnUpdateBindTimer(Sender:TObject);
public
constructor Create(port:Word; name:string; description:string);
destructor Destroy(); override;
procedure SendDiscover();
property port:Word read fPort write fPort;
property name:string read fName write SetName;
property description:string read fDescription write SetDescription;
end;
var
UDPdisc : TUDPDiscover;
implementation
uses TCPServerOR, ownStrUtils, Logging, USock;
////////////////////////////////////////////////////////////////////////////////
constructor TUDPDiscover.Create(port:Word; name:string; description:string);
begin
inherited Create();
Self.updateBindTimer := TTimer.Create(nil);
Self.updateBindTimer.Interval := 60000;
Self.updateBindTimer.OnTimer := Self.OnUpdateBindTimer;
Self.updateBindTimer.Enabled := true;
Self.broadcasts := TDictionary<string, string>.Create();
Self.parsed := TStringList.Create();
Self.fPort := port;
Self.fName := name;
Self.fDescription := description;
try
Self.UDPserver := TIdUDPServer.Create(nil);
Self.UDPserver.OnUDPRead := Self.OnUDPServerRead;
Self.SendDiscover();
except
on E:Exception do
begin
writelog('Nelze vytvorit discover UDPserver : '+E.Message, WR_ERROR);
end;
end;
end;
destructor TUDPDiscover.Destroy();
begin
Self.UDPserver.Free();
Self.parsed.Free();
Self.broadcasts.Free();
inherited;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUDPDiscover.OnUDPServerRead(AThread: TIdUDPListenerThread;
AData: TBytes; ABinding: TIdSocketHandle);
var
Msg: String;
i, j:Integer;
begin
try
msg := '';
for i := 0 to Length(AData)-1 do
msg := msg + Chr(AData[i]);
Self.parsed.Clear();
ExtractStringsEx([';'], [], msg, parsed);
if (parsed[2] <> 'server') then
begin
for i := 0 to _DISC_PORT_RANGE-1 do
for j := 0 to _DISC_REPEAT-1 do
Self.SendDisc(ABinding, Self.port+i);
end;
except
on E:Exception do
writelog('Vyjimka TUDPDiscover.OnUDPServerRead : '+E.Message, WR_ERROR);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUDPDiscover.SendDisc(ABinding: TIdSocketHandle; port:Word);
var msg:string;
begin
if (ABinding.IP = '0.0.0.0') then Exit();
msg := 'hJOP;' + _DISC_PROTOCOL_VERSION + ';server;' + Self.name + ';' +
ABinding.IP + ';' + IntToStr(ORTCPServer.port) + ';';
case (ORTCPServer.openned) of
false : msg := msg + 'off;';
true : msg := msg + 'on;';
end;
msg := msg + Self.description + ';';
if (not broadcasts.ContainsKey(ABinding.IP)) then Self.UpdateBindings();
try
ABinding.Broadcast(msg, port, broadcasts[ABinding.IP]);
except
on E:Exception do
writelog('Vyjimka TUDPDiscover.SendDisc : '+E.Message, WR_ERROR);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUDPDiscover.SetName(name:string);
begin
if (Self.fName = name) then Exit();
Self.fName := name;
Self.SendDiscover();
end;
procedure TUDPDiscover.SetDescription(desc:string);
begin
if (Self.fDescription = desc) then Exit();
Self.fDescription := desc;
Self.SendDiscover();
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUDPDiscover.UpdateBindings();
var i: Integer;
ifaces: tNetworkInterfaceList;
binding: TIdSocketHandle;
begin
try
GetNetworkInterfaces(ifaces);
Self.UDPserver.Active := false;
Self.UDPserver.Bindings.Clear();
Self.broadcasts.Clear();
for i := 0 to Length(ifaces)-1 do
begin
if ((ifaces[i].IsLoopback) or (not ifaces[i].IsInterfaceUp) or (not ifaces[i].BroadcastSupport)) then continue;
binding := Self.UDPserver.Bindings.Add;
binding.Port := port;
binding.IP := ifaces[i].AddrIP;
Self.broadcasts.Add(binding.IP, ifaces[i].AddrDirectedBroadcast);
end;
Self.UDPserver.Active := true;
except
on E:Exception do
writelog('Vyjimka TUDPDiscover.UpdateBindings : '+E.Message, WR_ERROR);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUDPDiscover.SendDiscover();
var i, j, k:Integer;
begin
Self.UpdateBindings();
for i := 0 to Self.UDPserver.Bindings.Count-1 do
for j := 0 to _DISC_PORT_RANGE-1 do
for k := 0 to _DISC_REPEAT-1 do
Self.SendDisc(Self.UDPserver.Bindings.Items[i], Self.port+j);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUDPDiscover.OnUpdateBindTimer(Sender:TObject);
begin
Self.UpdateBindings();
end;
////////////////////////////////////////////////////////////////////////////////
initialization
finalization
UDPdisc.Free();
end.
|
unit BuilderPizzaExample.Domain.IPizza;
interface
uses
BuilderPizzaExample.Domain.Edge,
BuilderPizzaExample.Domain.ValueObject.PizzaSize;
type
IPizza = interface
['{A088D7E9-B7A7-4569-961C-FCBFE499AA74}']
function GetWithEdge: Boolean;
function GetEdge: TEdge;
function GetFlavor: string;
function GetTimeOnStove: Integer;
function GetPrice: double;
function GetPizzaSize: TPizzaSize;
end;
implementation
end.
|
{$ifdef license}
(*
Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com )
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be
used to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
{$endif}
unit cwtest.testsuite.custom;
{$ifdef fpc}{$mode delphiunicode}{$endif}
interface
uses
cwTest
;
type
TArrayOfMethodName = array of string;
TCustomTestSuite = class( TInterfacedObject, ITestSuite )
private
fRegisteredTestCases: array of TTestCaseClass;
fTestCaseCount: nativeuint;
private
procedure ReportBeginTestSuite(const TestSuite: string; const TestReports: array of ITestReport);
procedure ReportEndTestSuite(const TestReports: array of ITestReport);
procedure ReportBeginTestCase(const TestCase: string; const TestReports: array of ITestReport);
procedure ReportEndTestCase(const TestReports: array of ITestReport);
procedure ReportTest(const Test: string; const TestResult: TTestResult; const Reason: string; const TestReports: array of ITestReport);
function RunTest(const TestCaseClass: TTestCaseClass; const aMethodName: string; const WithSetup: boolean; const WithTearDown: boolean; out Reason: string ): TTestResult;
protected //- ITestSuite -//
procedure RegisterTestCase( const TestCase: TTestCaseClass );
function Run( const SuiteName: string; const TestReports: array of ITestReport ): nativeuint;
protected //- override -//
function GetTestMethods( const TestCaseClass: TTestCaseClass; out HasSetup: boolean; out HasTearDown: boolean ): TArrayOfMethodName; virtual; abstract;
function ExecuteTestMethod( const TestCaseClass: TTestCaseClass; const aMethodName: string; const WithSetup: boolean; const WithTeardown: boolean; out Reason: string ): TTestResult; virtual; abstract;
public
constructor Create; reintroduce;
destructor Destroy; override;
end;
implementation
uses
sysutils //- For Exception
;
const
cTestCaseGranularity = 32;
constructor TCustomTestSuite.Create;
begin
inherited Create;
fTestCaseCount := 0;
SetLength(fRegisteredTestCases,cTestCaseGranularity)
end;
destructor TCustomTestSuite.Destroy;
begin
SetLength(fRegisteredTestCases,0);
inherited Destroy;
end;
procedure TCustomTestSuite.RegisterTestCase(const TestCase: TTestCaseClass);
var
L: nativeuint;
begin
L := Length(fRegisteredTestCases);
if fTestCaseCount>=L then begin
SetLength(fRegisteredTestCases,Length(fRegisteredTestCases)+cTestCaseGranularity);
end;
fRegisteredTestCases[fTestCaseCount] := TestCase;
inc(fTestCaseCount);
end;
procedure TCustomTestSuite.ReportBeginTestSuite( const TestSuite: string; const TestReports: array of ITestReport );
var
idx: nativeuint;
begin
if Length(TestReports)=0 then begin
exit;
end;
for idx := 0 to pred(Length(TestReports)) do begin
TestReports[idx].BeginTestSuite(TestSuite);
end;
end;
procedure TCustomTestSuite.ReportEndTestSuite( const TestReports: array of ITestReport );
var
idx: nativeuint;
begin
if Length(TestReports)=0 then begin
exit;
end;
for idx := 0 to pred(Length(TestReports)) do begin
TestReports[idx].EndTestSuite;
end;
end;
procedure TCustomTestSuite.ReportBeginTestCase( const TestCase: string; const TestReports: array of ITestReport );
var
idx: nativeuint;
begin
if Length(TestReports)=0 then begin
exit;
end;
for idx := 0 to pred(Length(TestReports)) do begin
TestReports[idx].BeginTestCase(TestCase);
end;
end;
procedure TCustomTestSuite.ReportEndTestCase( const TestReports: array of ITestReport );
var
idx: nativeuint;
begin
if Length(TestReports)=0 then begin
exit;
end;
for idx := 0 to pred(Length(TestReports)) do begin
TestReports[idx].EndTestCase;
end;
end;
procedure TCustomTestSuite.ReportTest( const Test: string; const TestResult: TTestResult; const Reason: string; const TestReports: array of ITestReport );
var
idx: nativeuint;
begin
if Length(TestReports)=0 then begin
exit;
end;
for idx := 0 to pred(Length(TestReports)) do begin
TestReports[idx].RecordTestResult(Test,TestResult,Reason);
end;
end;
function TCustomTestSuite.RunTest(const TestCaseClass: TTestCaseClass; const aMethodName: string; const WithSetup: boolean; const WithTearDown: boolean; out Reason: string ): TTestResult;
begin
try
Result := ExecuteTestMethod( TestCaseClass, aMethodName, WithSetup, WithTearDown, Reason );
except
on E: Exception do begin
Reason := string(E.Message);
Result := TTestResult.trError;
end else begin
Result := TTestResult.trError;
end;
end;
end;
function TCustomTestSuite.Run(const SuiteName: string; const TestReports: array of ITestReport): nativeuint;
var
TestCaseIndex: nativeuint;
MethodIndex: nativeuint;
MethodNames: TArrayOfMethodName;
TestResult: TTestResult;
HasSetup: boolean;
HasTeardown: boolean;
Reason: string;
begin
Result := 0;
TestResult := trError;
// Report test suite name
ReportBeginTestSuite( SuiteName, TestReports );
try
//- If there are no test cases to run, we exit with no reports.
if fTestCaseCount=0 then begin
exit;
end;
//- Loop the methos to run them
for TestCaseIndex := 0 to pred(fTestCaseCount) do begin
ReportBeginTestCase( string(fRegisteredTestCases[TestCaseIndex].ClassName), TestReports );
try
//- Get the test case and begin calling methods.
MethodNames := GetTestMethods( fRegisteredTestCases[TestCaseIndex], HasSetup, HasTearDown );
if Length(MethodNames)=0 then begin
continue;
end;
//- Loop through methods to execute them
for MethodIndex := 0 to pred(Length(MethodNames)) do begin
try
//- Run test method.
Reason := '';
TestResult := RunTest(fRegisteredTestCases[TestCaseIndex], MethodNames[MethodIndex], HasSetup, HasTearDown, Reason );
if (TestResult<>trSucceeded) then begin
inc(result);
end;
finally
ReportTest( MethodNames[MethodIndex], TestResult, Reason, TestReports );
end;
end;
finally
ReportEndTestCase( TestReports );
end;
end;
finally
ReportEndTestSuite( TestReports );
end;
end;
end.
|
unit UAMC_SendPak_StreetLinks;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
{ This is specific unit that knowns how to send the 'Appraisal Package' }
{ to Streetlinks. Each AMC is slightly different. so we have a unique }
{ TWorkflowBaseFrame for each AMC. }
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, MSXML6_TLB, WinHTTP_TLB,
UContainer, UAMC_Globals, UAMC_Base, UAMC_WorkflowBaseFrame, CheckLst;
type
TAMC_SendPak_StreetLinks = class(TWorkflowBaseFrame)
btnUpload: TButton;
StaticText1: TStaticText;
chkBxList: TCheckListBox;
procedure btnUploadClick(Sender: TObject);
private
FOrderID: String; //this is the associated OrderID
FAppraiserHash: String; //this is the session associated with appraiser
FUploaded: Boolean; //have the files been uploaded?
public
constructor CreateFrame(AOwner: TComponent; ADoc: TContainer; AData: TDataPackage); override;
procedure InitPackageData; override;
function ProcessedOK: Boolean; override;
procedure UploadAppraisalPackage;
procedure PrepFileForUploading(ADataFile: TDataFile; var fData, fDataID: String);
function UploadAppraisalFile(ADataFile: TDataFile; GroupID: String): Boolean;
function UploadDataFile(dataFile, dataFmt, groupID: String): Boolean;
function CreateGroupIDRequestXML: String;
function GetAppraisalGroupIDFromXML(respStr: String): String;
function GetAppraisalGroupID: String;
function ConvertToStreetLinksType(fType: String): String;
end;
implementation
{$R *.dfm}
uses
UWebConfig, UAMC_Utils, UWindowsInfo, UStatus, UBase64, UAMC_Delivery;
//streetlink data format identifiers
const
fmtPDF = 'PDF';
fmtMISMO26 = 'MISMO';
fmtMISMO26GSE = 'MISMOGSE';
fmtENV = 'ENV';
{ TAMC_SendPak_StreetLinks }
constructor TAMC_SendPak_StreetLinks.CreateFrame(AOwner: TComponent; ADoc: TContainer; AData: TDataPackage);
begin
inherited;
FOrderID := ''; //no orderID yet
end;
//Display the package contents to be uploaded
procedure TAMC_SendPak_StreetLinks.InitPackageData;
var
fileType, strDesc: String;
n: integer;
begin
FUploaded := False;
btnUpload.Enabled := True;
StaticText1.Caption :=' Appraisal Package files to Upload:';
//get Streetlinks specific data
if assigned(PackageData.FAMCData) then
begin
FOrderID := TAMCData_StreetLinks(PackageData.FAMCData).FOrderID;
FAppraiserHash := TAMCData_StreetLinks(PackageData.FAMCData).FAppraiserHash;
end;
//display the file types that will be uploaded
chkBxList.Clear; //incase we are entering multiple times
with PackageData.DataFiles do
for n := 0 to count-1 do
begin
fileType := TDataFile(Items[n]).FType;
strDesc := DataFileDescriptionText(fileType);
chkBxList.items.Add(strDesc);
end;
end;
function TAMC_SendPak_StreetLinks.ProcessedOK: Boolean;
begin
PackageData.FGoToNextOk := FUploaded;
PackageData.FAlertMsg := 'Appraisal files successfully uploaded'; //ending msg to user
PackageData.FHardStop := not FUploaded;
PackageData.FAlertMsg := '';
if not FUploaded then
PackageData.FAlertMsg := 'Please upload the files before moving to the next step.';
result := PackageData.FGoToNextOk;
end;
procedure TAMC_SendPak_StreetLinks.btnUploadClick(Sender: TObject);
begin
UploadAppraisalPackage;
end;
function TAMC_SendPak_StreetLinks.ConvertToStreetLinksType(fType: String): String;
begin
if compareText(fType, fTypXML26) = 0 then
result := fmtMISMO26
else if compareText(fType, fTypXML26GSE) = 0 then
result := fmtMISMO26GSE
else if compareText(fType, fTypPDF) = 0 then
result := fmtPDF
else if compareText(fType, fTypENV) = 0 then
result := fmtENV
else
result := 'UNKNOWN'; //this should NEVER happen
end;
function TAMC_SendPak_StreetLinks.GetAppraisalGroupIDFromXML(respStr: String): String;
const
xpAppraisalGroup = '/appraisalGroup/reportGroupId';
var
xmlDoc: IXMLDOMDocument2;
Node: IXMLDOMNode;
begin
result := '';
xmlDoc := CoDomDocument60.Create;
with xmlDoc do
begin
async := false;
SetProperty('SelectionLanguage', 'XPath');
LoadXML(respStr);
if parseError.errorCode <> 0 then
begin
ShowNotice('Invalid response Appraisal Group XML');
exit;
end;
node := SelectsingleNode(xpAppraisalGroup);
if assigned(node) then
result := node.text;
end;
end;
function TAMC_SendPak_StreetLinks.CreateGroupIDRequestXML: String;
const
tagOrderId = 'orderId';
tagAppraisalGroup = 'appraisalGroup';
tagAppraisalFormats = 'appraisalFormats';
tagAppraisalFormat = 'appraisalFormat';
fnAppraisalGroup = 'orders/%s/appraisalgroup';
tagReportGroupID = 'reportGroupID';
var
xmlDoc: IXMLDOMDocument2;
FormatsNode, FormatNode, OrderNode, GroupNode: IXMLDOMNode;
n: Integer;
fileFmt, stFileTyp: String;
begin
xmlDoc := CoDomDocument60.Create;
try
with xmlDoc do
begin
documentElement := CreateElement(tagAppraisalGroup); //root element
FormatsNode := CreateNode(NODE_ELEMENT, tagAppraisalFormats,'');
documentElement.appendChild(FormatsNode);
with PackageData do
for n := 0 to DataFiles.count -1 do
begin
fileFmt := TDataFile(DataFiles.Items[n]).FType;
stFileTyp := ConvertToStreetLinksType(fileFmt);
FormatNode := xmlDoc.CreateNode(NODE_ELEMENT, tagAppraisalFormat, '');
FormatNode.appendChild(xmlDoc.CreateTextNode(stFileTyp));
FormatsNode.appendChild(FormatNode);
end;
//add in the order node
OrderNode := CreateNode(NODE_ELEMENT,tagOrderId,'');
OrderNode.appendChild(xmlDoc.CreateTextNode(FOrderID));
documentElement.appendChild(OrderNode);
GroupNode := CreateNode(NODE_ELEMENT,tagReportGroupID,''); //empty node
documentElement.appendChild(GroupNode);
result := xmlDoc.xml;
end;
except
ShowNotice('There is a problem creating the GroupRequest ID XML');
end;
end;
function TAMC_SendPak_StreetLinks.GetAppraisalGroupID: String;
var
URL, requestStr, responseStr: String;
theServer: String;
fnGroupIDStr: String;
httpRequest: IWinHTTPRequest;
begin
result := '';
requestStr := CreateGroupIDRequestXML; //Create the XML Request
theServer := GetURLForStreetLinksServer;
fnGroupIDStr := theServer + 'orders/%s/appraisalgroup/';
URL := format(fnGroupIDStr,[FOrderID]);
httpRequest := CoWinHTTPRequest.Create;
with httpRequest do
begin
Open('POST',URL, False);
SetTimeouts(600000,600000,600000,600000); //10 minute for everything
// Option[WinHttpRequestOption_EnableTracing] := True; //###just for debuging
SetRequestHeader('Authorization', FAppraiserHash);
SetRequestHeader('Content-type','text/xml');
SetRequestHeader('Content-length', IntToStr(length(requestStr)));
PushMouseCursor(crHourGlass);
try
try
httpRequest.send(requestStr); //send the request
responseStr := httpRequest.responseText; //get the response
result := GetAppraisalGroupIDFromXML(responseStr); //get the groupID
except
on e:Exception do
begin
PopMouseCursor;
ShowAlert(atWarnAlert, e.Message);
end;
end;
finally
PopMouseCursor;
end;
if status <> httpRespOK then
ShowAlert(atWarnAlert, 'The Upload GroupID request status is: ' + IntToStr(status));
end;
end;
procedure TAMC_SendPak_StreetLinks.UploadAppraisalPackage;
var
GroupID: String;
n: Integer;
begin
StaticText1.Caption :=' Uploading Appraisal Package files';
btnUpload.Enabled := False;
GroupID := GetAppraisalGroupID;
if length(groupID) > 0 then
with PackageData do
for n := 0 to DataFiles.count -1 do
begin
if UploadAppraisalFile(TDataFile(DataFiles[n]), GroupID) then
chkBxList.Checked[n] := True;
end;
FUploaded := True;
for n := 0 to chkBxList.items.count-1 do
FUploaded := FUploaded and chkBxList.Checked[n];
if FUploaded then
StaticText1.Caption :=' All Appraisal Package files Uploaded'
else
begin
btnUpload.Enabled := True;
StaticText1.Caption :=' Appraisal Package files to Upload:';
end;
// AdvanceToNextStep
end;
function TAMC_SendPak_StreetLinks.UploadAppraisalFile(ADataFile: TDataFile; GroupID: String): Boolean;
var
fData: String;
fDataTyp: String;
begin
PrepFileForUploading(ADataFile, fData, fDataTyp);
result := UploadDataFile(fData, fDataTyp, GroupID);
end;
procedure TAMC_SendPak_StreetLinks.PrepFileForUploading(ADataFile: TDataFile; var fData, fDataID: String);
begin
//extract the data
fData := ADataFile.FData;
//get StreetLinks format identifier
fDataID := ConvertToStreetLinksType(ADataFile.FType);
//should it be base64 encoded?
if (CompareText(fDataID, fmtPDF) = 0) OR (CompareText(fDataID, fmtENV) = 0) then
fData := Base64Encode(fData);
end;
function TAMC_SendPak_StreetLinks.UploadDataFile(dataFile, dataFmt, groupID: String): Boolean;
var
URL: String;
theServer: String;
fnUploadStr: String;
httpRequest: IWinHTTPRequest;
begin
result := False;
theServer := GetURLForStreetLinksServer;
fnUploadStr := theServer + 'Orders/%s/appraisal/?aprFormat=%s&reportGroupId=%s';
URL := format(fnUploadStr,[FOrderID, dataFmt, groupID]);
httpRequest := CoWinHTTPRequest.Create;
with httpRequest do
begin
Open('POST',URL, False);
SetTimeouts(600000,600000,600000,600000); //10 minute for everything
// Option[WinHttpRequestOption_EnableTracing] := True; //###just for debuging
SetRequestHeader('Authorization', FAppraiserHash);
//if not XML then set Content-type = pplication/octet-stream
if (CompareText(dataFmt,fmtMISMO26) <> 0) and (CompareText(dataFmt,fmtMISMO26GSE) <> 0) then
SetRequestHeader('Content-type','application/octet-stream')
else
SetRequestHeader('Content-type','text/plain');
SetRequestHeader('Content-length', IntToStr(length(dataFile)));
PushMouseCursor(crHourGlass);
try
try
httpRequest.send(dataFile);
except
on e:Exception do
begin
PopMouseCursor;
ShowAlert(atWarnAlert, e.Message);
end;
end;
finally
PopMouseCursor;
end;
if status <> httpRespOK then
begin
ShowAlert(atWarnAlert, 'The ' + dataFmt + ' file was not uploaded successfully.');
exit;
end
end;
result := True;
end;
end.
|
unit TNsRemotePublish.Domain.Models.Publish;
interface
type
TPublish = class(TInterfacedObject)
private
fpublishpath : string;
fprojectname : string;
fartifactname : string;
fslotname : string;
fslotpath : string;
fservername : string;
freleasename : string;
fisawebsite : Boolean;
public
property PublishPath : string read fpublishpath write fpublishpath;
property ProjectName : string read fprojectname write fprojectname;
property ArtifactName : string read fartifactname write fartifactname;
property SlotName : string read fslotname write fslotname;
property SlotPath : string read fslotpath write fslotpath;
property ServerName : string read fservername write fservername;
property ReleaseName : string read freleasename write freleasename;
property IsAWebsite : Boolean read fisawebsite write fisawebsite;
end;
implementation
end.
|
unit BomD2Reader2;
interface
uses
Classes, SysUtils, ComObj, CommUtils, ProjNameReader, BomD2Reader, ADODB;
type
TBomD2Reader2 = class
private
FProjNameReader: TProjNameReader;
FFile: string;
ExcelApp, WorkBook: Variant;
FLogEvent: TLogEvent;
FReadOk: Boolean;
procedure Open;
procedure Log(const str: string);
function GetCount: Integer;
function GetItems(i: Integer): TBomD2;
public
FNumbers: TStringList;
FList: TStringList;
constructor Create(const sfile: string; aProjNameReader: TProjNameReader;
aLogEvent: TLogEvent = nil);
destructor Destroy; override;
procedure Clear;
function GetWhereUse(const snumber_child: string): string;
function BomByNumber(const snumber: string): TBomD2;
property ReadOk: Boolean read FReadOk;
property Count: Integer read GetCount;
property Items[i: Integer]: TBomD2 read GetItems;
end;
implementation
{ TBomD2Reader2 }
constructor TBomD2Reader2.Create(const sfile: string;
aProjNameReader: TProjNameReader; aLogEvent: TLogEvent = nil);
begin
FProjNameReader := aProjNameReader;
FFile := sfile;
FLogEvent := aLogEvent;
FList := TStringList.Create;
FNumbers := TStringList.Create;
Open;
end;
destructor TBomD2Reader2.Destroy;
begin
Clear;
FList.Free;
FNumbers.Free;
inherited;
end;
procedure TBomD2Reader2.Clear;
var
i: Integer;
aBomD2: TBomD2;
begin
FNumbers.Clear; //要放在前面,因为引用了BOM的Item指针
for i := 0 to FList.Count - 1 do
begin
aBomD2 := TBomD2(FList.Objects[i]);
aBomD2.Free;
end;
FList.Clear;
end;
function TBomD2Reader2.GetWhereUse(const snumber_child: string): string;
var
i: Integer;
aBomD2: TBomD2;
sprojs: string;
begin
for i := 0 to FList.Count - 1 do
begin
aBomD2 := TBomD2(FList.Objects[i]);
if aBomD2.ChildExists(snumber_child) then
begin
if Pos(aBomD2.fproj, sprojs) <= 0 then
begin
if sprojs = '' then
begin
sprojs := aBomD2.fproj;
end
else
begin
sprojs := sprojs + ',' + aBomD2.fproj;
end;
end;
end;
end;
Result := sprojs;
end;
function TBomD2Reader2.BomByNumber(const snumber: string): TBomD2;
var
i: Integer;
aBomD2: TBomD2;
begin
Result := nil;
for i := 0 to FList.Count - 1 do
begin
aBomD2 := TBomD2(FList.Objects[i]);
if aBomD2.fnumber = snumber then
begin
Result := aBomD2;
Break;
end;
end;
end;
procedure TBomD2Reader2.Log(const str: string);
begin
savelogtoexe(str);
if Assigned(FLogEvent) then
begin
FLogEvent(str);
end;
end;
function TBomD2Reader2.GetCount: Integer;
begin
Result := FList.Count;
end;
function TBomD2Reader2.GetItems(i: Integer): TBomD2;
begin
Result := TBomD2(FList[i]);
end;
procedure TBomD2Reader2.Open;
var
snumber: string;
snumber_child: string;
p: PBomD2Item;
aBomD2: TBomD2;
sproj: string;
Conn: TADOConnection;
ADOTabXLS: TADOTable;
begin
Clear;
if not FileExists(FFile) then Exit;
ADOTabXLS := TADOTable.Create(nil);
Conn:=TADOConnection.Create(nil);
Conn.ConnectionString:='Provider=Microsoft.ACE.OLEDB.12.0;Data Source="' + FFile + '";Extended Properties=excel 8.0;Persist Security Info=False';
Conn.LoginPrompt:=false;
try
Conn.Connected:=true;
ADOTabXLS.Connection:=Conn;
ADOTabXLS.TableName:='['+'Sheet1'+'$]';
ADOTabXLS.Active:=true;
aBomD2 := nil;
ADOTabXLS.First;
while not ADOTabXLS.Eof do
begin
snumber_child := ADOTabXLS.FieldByName('子件物料编码').AsString; // ExcelApp.Cells[irow, iColNumber].Value;
if snumber_child = '' then Break;
snumber := ADOTabXLS.FieldByName('母件物料编码').AsString;
snumber := Trim(snumber);
if snumber <> '' then
begin
sproj := FProjNameReader.ProjOfNumber(snumber);
aBomD2 := TBomD2.Create(snumber, sproj);
FList.AddObject(snumber, aBomD2);
end;
p := New(PBomD2Item);
p^.snumber := snumber;
p^.sname := ADOTabXLS.FieldByName('母件物料描述').AsString;
p^.snumber_child := snumber_child;
p^.sname_child := ADOTabXLS.FieldByName('子件物料描述').AsString;
p^.snumber_p := ADOTabXLS.FieldByName('层级').AsString;
p^.dusage := ADOTabXLS.FieldByName('子件用量').AsFloat;
p^.sabc := ADOTabXLS.FieldByName('ABC标识').AsString;
p^.sptype := ADOTabXLS.FieldByName('采购类型').AsString;
p^.slt := ADOTabXLS.FieldByName('L/T').AsFloat;
p^.dper := ADOTabXLS.FieldByName('使用可能性').AsFloat;
p^.sgroup := ADOTabXLS.FieldByName('替代项目组').AsString;
p^.sparent := ADOTabXLS.FieldByName('上层物料编码').AsString;
aBomD2.FList.Add(p);
if FNumbers.IndexOf(snumber_child) < 0 then
begin
FNumbers.AddObject(snumber_child, TObject(p));
end;
ADOTabXLS.Next;
end;
ADOTabXLS.Close;
Conn.Connected := False;
finally
FreeAndNil(Conn);
FreeAndNil(ADOTabXLS);
end;
end;
end.
|
unit html_utils;
interface
uses
Classes, Sysutils,
define_htmldom;
type
DomException = class(Exception)
public
FCode: Integer;
public
constructor Create(code: Integer);
property code: Integer read FCode;
end;
const
ERR_INDEX_SIZE = 1;
ERR_DOMSTRING_SIZE = 2;
ERR_HIERARCHY_REQUEST = 3;
ERR_WRONG_DOCUMENT = 4;
ERR_INVALID_CHARACTER = 5;
ERR_NO_DATA_ALLOWED = 6;
ERR_NO_MODIFICATION_ALLOWED = 7;
ERR_NOT_FOUND = 8;
ERR_NOT_SUPPORTED = 9;
ERR_INUSE_ATTRIBUTE = 10;
ERR_INVALID_STATE = 11;
ERR_SYNTAX = 12;
ERR_INVALID_MODIFICATION = 13;
ERR_NAMESPACE = 14;
ERR_INVALID_ACCESS = 15;
function CharacterDataNodeGetLength(AHtmlDomNode: PHtmlDomNode): Integer;
function AttrGetOwnerElement(AttribNode: PHtmlAttribDomNode): PHtmlElementDomNode;
function AttrGetLength(AttribNode: PHtmlAttribDomNode): Integer;
function createEmptyDocument(doctype: PHtmlDocTypeDomNode): PHtmlDocDomNode;
function createDocumentType(const qualifiedName, publicId, systemId: WideString): PHtmlDocTypeDomNode;
function CheckOutHtmlDomNode(ANodeType: Integer; ownerDocument: PHtmlDocDomNode; const namespaceURI, qualifiedName: WideString; withNS: Boolean): PHtmlDomNode; overload;
function CheckOutElementDomNode(ownerDocument: PHtmlDocDomNode; const namespaceURI, qualifiedName: WideString; withNS: Boolean): PHtmlElementDomNode;
function CheckOutTextDomNode(ANodeType: Integer; ownerDocument: PHtmlDocDomNode; data: WideString): PHtmlDomNode; overload;
function CheckOutEntityReferenceNode(ownerDocument: PHtmlDocDomNode; const name: WideString): PHtmlDomNode;
procedure HtmlDomNodeFree(var ADomNode: PHtmlDomNode);
function HtmlDomNodeGetName(AHtmlDomNode: PHtmlDomNode): WideString;
function HtmlDomNodeAppendChild(AHtmlDomNode, newChild: PHtmlDomNode): PHtmlDomNode;
function NodeGetParentDomNode(AHtmlDomNode: PHtmlDomNode): PHtmlDomNode;
procedure HtmlDocSetDocType(ADocument: PHtmlDocDomNode; value: PHtmlDocTypeDomNode{TDocumentTypeObj});
function HtmlDocGetDocumentElement(ADocument: PHtmlDocDomNode): PHtmlElementDomNode;
function DecValue(const Digit: WideChar): Word;
function HexValue(const HexChar: WideChar): Word;
implementation
uses
html_helperclass, html_entity, define_htmltag;
const
ExceptionMsg: array[ERR_INDEX_SIZE..ERR_INVALID_ACCESS] of String = (
'Index or size is negative, or greater than the allowed value',
'The specified range of text does not fit into a DOMString',
'Node is inserted somewhere it doesn''t belong ',
'Node is used in a different document than the one that created it',
'Invalid or illegal character is specified, such as in a name',
'Data is specified for a node which does not support data',
'An attempt is made to modify an object where modifications are not allowed',
'An attempt is made to reference a node in a context where it does not exist',
'Implementation does not support the requested type of object or operation',
'An attempt is made to add an attribute that is already in use elsewhere',
'An attempt is made to use an object that is not, or is no longer, usable',
'An invalid or illegal string is specified',
'An attempt is made to modify the type of the underlying object',
'An attempt is made to create or change an object in a way which is incorrect with regard to namespaces',
'A parameter or an operation is not supported by the underlying object'
);
constructor DomException.Create(code: Integer);
begin
inherited Create(ExceptionMsg[code]);
FCode := code
end;
function DecValue(const Digit: WideChar): Word;
begin
Result := Ord(Digit) - Ord('0')
end;
function HexValue(const HexChar: WideChar): Word;
var
C: Char;
begin
if Ord(HexChar) in define_htmltag.decDigit then
Result := Ord(HexChar) - Ord('0')
else
begin
C := UpCase(Chr(Ord(HexChar)));
Result := Ord(C) - Ord('A')
end
end;
procedure HtmlDomNodeFree(var ADomNode: PHtmlDomNode);
var
i: integer;
tmpNode: PHtmlDomNode;
begin
if nil = ADomNode then
exit;
//Windows.InterlockedDecrement(GlobalTestNodeCount);
if nil <> ADomNode.OwnerDocument then
begin
if (nil <> ADomNode.OwnerDocument.AllOwnedNodes) then
begin
i := ADomNode.OwnerDocument.AllOwnedNodes.IndexOf(ADomNode);
if 0 <= i then
ADomNode.OwnerDocument.AllOwnedNodes.Delete(i);
end;
end;
if (nil <> ADomNode.ChildNodes) then
begin
ADomNode.ChildNodes.NodeListClear(true);
ADomNode.ChildNodes.Free;
ADomNode.ChildNodes := nil;
end;
if (nil <> ADomNode.Attributes) then
begin
ADomNode.Attributes.NodeListClear(true);
ADomNode.Attributes.Free;
ADomNode.Attributes := nil;
end;
if HTMLDOM_NODE_DOCUMENT = ADomNode.NodeType then
begin
if nil <> PHtmlDocDomNode(ADomNode).DocTypeDomNode then
begin
HtmlDomNodeFree(PHtmlDomNode(PHtmlDocDomNode(ADomNode).DocTypeDomNode));
end;
if nil <> PHtmlDocDomNode(ADomNode).AllOwnedNodes then
begin
while 0 < PHtmlDocDomNode(ADomNode).AllOwnedNodes.Count do
begin
tmpNode := PHtmlDocDomNode(ADomNode).AllOwnedNodes.Items[0];
HtmlDomNodeFree(tmpNode);
end;
PHtmlDocDomNode(ADomNode).AllOwnedNodes.Free;
end;
PHtmlDocDomNode(ADomNode).NamespaceURIList.Free;
PHtmlDocDomNode(ADomNode).SearchNodeLists.Free;
end;
FreeMem(ADomNode);
ADomNode := nil;
end;
procedure HtmlDocSetDocType(ADocument: PHtmlDocDomNode; value: PHtmlDocTypeDomNode{TDocumentTypeObj});
begin
if (nil <> ADocument.DocTypeDomNode) then
begin
HtmlDomNodeFree(PHtmlDomNode(ADocument.DocTypeDomNode));
end;
ADocument.DocTypeDomNode := value;
end;
function CharacterDataNodeGetLength(AHtmlDomNode: PHtmlDomNode): Integer;
begin
Result := System.Length(AHtmlDomNode.NodeValue)
end;
function AttrGetOwnerElement(AttribNode: PHtmlAttribDomNode): PHtmlElementDomNode;
begin
if nil = AttribNode.ParentDomNode then
begin
Result := nil;
end else
begin
Result := PHtmlElementDomNode(AttribNode.ParentDomNode);
end;
end;
function AttrGetLength(AttribNode: PHtmlAttribDomNode): Integer;
var
Node: PHtmlDomNode;
I: Integer;
begin
Result := 0;
for I := 0 to AttribNode.childNodes.length - 1 do
begin
Node := AttribNode.childNodes.item(I);
if Node.NodeType = HTMLDOM_NODE_TEXT then
Inc(Result, CharacterDataNodeGetLength(Node))
else
if Node.NodeType = HTMLDOM_NODE_ENTITY_REFERENCE then
Inc(Result)
end
end;
procedure HtmlDomNodeSetNamespaceURI(AHtmlDomNode: PHtmlDomNode; const value: WideString);
begin
if value <> '' then
//TODO validate
AHtmlDomNode.NamespaceURI := AHtmlDomNode.ownerDocument.namespaceURIList.Add(value)
end;
function IsNCName(const Value: WideString): Boolean;
begin
//TODO
Result := true
end;
procedure HtmlDomNodeSetPrefix(AHtmlDomNode: PHtmlDomNode; const value: WideString);
begin
if not IsNCName(value) then
raise DomException.Create(ERR_INVALID_CHARACTER);
AHtmlDomNode.Prefix := value
end;
procedure HtmlDomNodeSetLocalName(AHtmlDomNode: PHtmlDomNode; const value: WideString);
begin
if not IsNCName(value) then
raise DomException.Create(ERR_INVALID_CHARACTER);
AHtmlDomNode.NodeName := value
end;
procedure DomNodeInitialize(AHtmlDomNode: PHtmlDomNode; ANodeType: Integer; ownerDocument: PHtmlDocDomNode; const namespaceURI, qualifiedName: WideString; withNS: Boolean);
var
I: Integer;
begin
AHtmlDomNode.NodeType := ANodeType;
AHtmlDomNode.OwnerDocument := ownerDocument;
HtmlDomNodeSetNamespaceURI(AHtmlDomNode, namespaceURI);
if withNS then
begin
I := Pos(':', qualifiedName);
if I <> 0 then
begin
HtmlDomNodeSetPrefix(AHtmlDomNode, Copy(qualifiedName, 1, I - 1));
HtmlDomNodeSetLocalName(AHtmlDomNode, Copy(qualifiedName, I + 1, Length(qualifiedName) - I))
end else
begin
HtmlDomNodeSetLocalName(AHtmlDomNode, qualifiedName)
end;
end else
begin
HtmlDomNodeSetLocalName(AHtmlDomNode, qualifiedName);
end;
AHtmlDomNode.ChildNodes := TNodeList.Create(AHtmlDomNode);
end;
function CheckOutHtmlDomNode(ANodeType: Integer; ownerDocument: PHtmlDocDomNode; const namespaceURI, qualifiedName: WideString; withNS: Boolean): PHtmlDomNode; overload;
begin
Result := System.New(PHtmlDomNode);
FillChar(Result^, SizeOf(THtmlDomNode), 0);
//Windows.InterlockedIncrement(GlobalTestNodeCount);
ownerDocument.AllOwnedNodes.Add(Result);
DomNodeInitialize(Result, ANodeType, ownerDocument, namespaceURI, qualifiedName, withNS);
end;
function CheckOutHtmlDomNode(ownerDocument: PHtmlDocDomNode): PHtmlDomNode; overload;
begin
Result := System.New(PHtmlDomNode);
FillChar(Result^, SizeOf(THtmlDomNode), 0);
//Windows.InterlockedIncrement(GlobalTestNodeCount);
ownerDocument.AllOwnedNodes.Add(Result);
end;
function CheckOutEntityReferenceNode(ownerDocument: PHtmlDocDomNode; const name: WideString): PHtmlDomNode;
begin
Result := CheckOutHtmlDomNode(ownerDocument);
DomNodeInitialize(Result, HTMLDOM_NODE_ENTITY_REFERENCE, ownerDocument, '', name, false);
end;
//constructor TCharacterDataNode.Create(ANodeType: Integer; ownerDocument: PHtmlDocDomNode; const data: WideString);
//begin
// inherited Create(ANodeType, ownerDocument, '', '', false);
// NodeSetValue(@fNodeData, data);
//end;
function HtmlDomNodeGetFirstChild(AHtmlDomNode: PHtmlDomNode): PHtmlDomNode;
begin
if AHtmlDomNode.childNodes.length <> 0 then
begin
Result := PHtmlDomNode(AHtmlDomNode.childNodes.item(0));
end else
begin
Result := nil
end;
end;
function HtmlDocGetDocumentElement(ADocument: PHtmlDocDomNode): PHtmlElementDomNode;
var
Child: PHtmlDomNode;
I: Integer;
begin
for I := 0 to ADocument.BaseDomNode.childNodes.length - 1 do
begin
Child := ADocument.BaseDomNode.childNodes.item(I);
if HTMLDOM_NODE_ELEMENT = Child.NodeType then
begin
Result := PHtmlElementDomNode(Child);
Exit
end
end;
Result := nil
end;
function NodeIsCanInsert(AOwnerNode, AChildNode: PHtmlDomNode): Boolean;
begin
Result := false;
if HTMLDOM_NODE_ATTRIBUTE = AOwnerNode.NodeType then
begin
Result := AChildNode.NodeType in [HTMLDOM_NODE_ENTITY_REFERENCE, HTMLDOM_NODE_TEXT];
exit;
end;
if HTMLDOM_NODE_ELEMENT = AOwnerNode.NodeType then
begin
Result := not (AChildNode.NodeType in [HTMLDOM_NODE_ENTITY, HTMLDOM_NODE_DOCUMENT, HTMLDOM_NODE_DOCUMENT_TYPE, HTMLDOM_NODE_NOTATION]);
exit;
end;
if HTMLDOM_NODE_DOCUMENT_FRAGMENT = AOwnerNode.NodeType then
begin
Result := not (AChildNode.NodeType in [HTMLDOM_NODE_ENTITY, HTMLDOM_NODE_DOCUMENT, HTMLDOM_NODE_DOCUMENT_TYPE, HTMLDOM_NODE_NOTATION]);
exit;
end;
if HTMLDOM_NODE_DOCUMENT = AOwnerNode.NodeType then
begin
Result := (AChildNode.NodeType in [HTMLDOM_NODE_TEXT, HTMLDOM_NODE_COMMENT, HTMLDOM_NODE_PROCESSING_INSTRUCTION]) or
(AChildNode.NodeType = HTMLDOM_NODE_ELEMENT) and (HtmlDocGetDocumentElement(PHtmlDocDomNode(AOwnerNode)) = nil);
end;
end;
function NodeGetParentDomNode(AHtmlDomNode: PHtmlDomNode): PHtmlDomNode;
begin
Result := nil;
if nil <> AHtmlDomNode then
begin
if HTMLDOM_NODE_ATTRIBUTE = AHtmlDomNode.NodeType then
begin
Result := nil;
end else
begin
Result := AHtmlDomNode.ParentDomNode;
end;
end;
end;
function HtmlDomNodeIsAncestorOf(AHtmlDomNode: PHtmlDomNode; node: PHtmlDomNode): Boolean;
var
tmpDomNode: PHtmlDomNode;
begin
tmpDomNode := node;
while (nil <> tmpDomNode) do
begin
if tmpDomNode = AHtmlDomNode then
begin
Result := true;
Exit
end;
tmpDomNode := NodeGetParentDomNode(tmpDomNode);
end;
Result := false;
end;
procedure HtmlDocInvalidateSearchNodeLists(ADocument: PHtmlDocDomNode);
var
I: Integer;
begin
for I := 0 to ADocument.SearchNodeLists.Count - 1 do
TSearchNodeList(ADocument.SearchNodeLists[I]).Invalidate
end;
function HtmlDomNodeRemoveChild(AHtmlDomNode, oldChild: PHtmlDomNode): PHtmlDomNode;
var
I: Integer;
begin
I := AHtmlDomNode.ChildNodes.NodeListIndexOf(oldChild);
if I < 0 then
raise DomException.Create(ERR_NOT_FOUND);
AHtmlDomNode.ChildNodes.NodeListDelete(I);
oldChild.ParentDomNode := nil;
Result := oldChild;
if (nil <> AHtmlDomNode.ownerDocument) then
HtmlDocInvalidateSearchNodeLists(AHtmlDomNode.ownerDocument)
end;
function HtmlDomNodeInsertSingleNode(AHtmlDomNode, newChild, refChild: PHtmlDomNode): PHtmlDomNode;
var
I: Integer;
tmpNode: PHtmlDomNode;
begin
if not NodeIsCanInsert(AHtmlDomNode, newChild) or HtmlDomNodeIsAncestorOf(newChild, AHtmlDomNode) then
raise DomException.Create(ERR_HIERARCHY_REQUEST);
if newChild <> refChild then
begin
if (nil <> refChild) then
begin
I := AHtmlDomNode.ChildNodes.NodeListIndexOf(refChild);
if I < 0 then
raise DomException.Create(ERR_NOT_FOUND);
AHtmlDomNode.ChildNodes.NodeListInsert(I, newChild)
end else
begin
AHtmlDomNode.ChildNodes.NodeListAdd(newChild);
end;
tmpNode := NodeGetParentDomNode(newChild);
if (nil <> tmpNode) then
HtmlDomNoderemoveChild(tmpNode, newChild);
newChild.ParentDomNode := AHtmlDomNode;
end;
Result := newChild
end;
function HtmlDomNodeinsertBefore(AHtmlDomNode, newChild, refChild: PHtmlDomNode): PHtmlDomNode;
var
tmpDomNode: PHtmlDomNode;
begin
if newChild.ownerDocument <> AHtmlDomNode.ownerDocument then
raise DomException.Create(ERR_WRONG_DOCUMENT);
if newChild.NodeType = HTMLDOM_NODE_DOCUMENT_FRAGMENT then
begin
tmpDomNode := HtmlDomNodeGetfirstChild(newChild);
while (nil <> tmpDomNode) do
begin
HtmlDomNodeInsertSingleNode(AHtmlDomNode, tmpDomNode, refChild);
tmpDomNode := HtmlDomNodeGetfirstChild(newChild);
end;
Result := newChild
end else
begin
Result := HtmlDomNodeInsertSingleNode(AHtmlDomNode, newChild, refChild);
end;
if (nil <> AHtmlDomNode.ownerDocument) then
HtmlDocInvalidateSearchNodeLists(AHtmlDomNode.ownerDocument)
end;
function HtmlDomNodeAppendChild(AHtmlDomNode, newChild: PHtmlDomNode): PHtmlDomNode;
begin
Result := HtmlDomNodeinsertBefore(AHtmlDomNode, newChild, nil);
if (nil <> AHtmlDomNode.ownerDocument) then
HtmlDocInvalidateSearchNodeLists(AHtmlDomNode.ownerDocument)
end;
function HtmlDomNodeGetName(AHtmlDomNode: PHtmlDomNode): WideString;
begin
if HTMLDOM_NODE_CDATA_SECTION = AHtmlDomNode.NodeType then
begin
Result := '#cdata-section';
exit;
end;
if HTMLDOM_NODE_COMMENT = AHtmlDomNode.NodeType then
begin
Result := '#comment';
exit;
end;
if HTMLDOM_NODE_TEXT = AHtmlDomNode.NodeType then
begin
Result := '#text';
exit;
end;
if HTMLDOM_NODE_DOCUMENT_FRAGMENT = AHtmlDomNode.NodeType then
begin
Result := '#document-fragment';
exit;
end;
if HTMLDOM_NODE_DOCUMENT = AHtmlDomNode.NodeType then
begin
Result := '#document';
Exit;
end;
if AHtmlDomNode.Prefix <> '' then
begin
Result := AHtmlDomNode.Prefix + ':' + AHtmlDomNode.NodeName;
end else
begin
Result := AHtmlDomNode.NodeName;
end;
end;
function NodeGetValue(AHtmlDomNode: PHtmlDomNode): WideString;
var
Node: PHtmlDomNode;
Len, Pos, I, J: Integer;
begin
Result := '';
if nil = AHtmlDomNode then
exit;
if HTMLDOM_NODE_ATTRIBUTE = AHtmlDomNode.NodeType then
begin
Len := AttrGetLength(PHtmlAttribDomNode(AHtmlDomNode));
SetLength(Result, Len);
Pos := 0;
for I := 0 to AHtmlDomNode.childNodes.length - 1 do
begin
Node := AHtmlDomNode.childNodes.item(I);
if Node.NodeType = HTMLDOM_NODE_TEXT then
begin
for J := 1 to CharacterDataNodeGetLength(Node) do
begin
Inc(Pos);
Result[Pos] := Node.NodeValue[J]
end
end else if Node.NodeType = HTMLDOM_NODE_ENTITY_REFERENCE then
begin
Inc(Pos);
Result[Pos] := html_entity.GetEntValue(HtmlDomNodeGetName(Node))
end
end
end else
begin
Result := AHtmlDomNode.NodeValue;
end;
end;
procedure NodeSetValue(AHtmlDomNode: PHtmlDomNode; const value: WideString);
begin
if HTMLDOM_NODE_ATTRIBUTE = AHtmlDomNode.NodeType then
begin
AHtmlDomNode.ChildNodes.NodeListClear(false);
HtmlDomNodeappendChild(AHtmlDomNode, CheckOutTextDomNode(HTMLDOM_NODE_TEXT, AHtmlDomNode.ownerDocument, value));
exit;
end;
if (HTMLDOM_NODE_TEXT = AHtmlDomNode.NodeType) or
(HTMLDOM_NODE_COMMENT = AHtmlDomNode.NodeType) or
(HTMLDOM_NODE_CDATA_SECTION = AHtmlDomNode.NodeType) then
begin
// charset node
AHtmlDomNode.NodeValue := value
end;
end;
function CheckOutTextDomNode(ANodeType: Integer; ownerDocument: PHtmlDocDomNode; data: WideString): PHtmlDomNode; overload;
begin
Result := System.New(PHtmlDomNode);
FillChar(Result^, SizeOf(THtmlDomNode), 0);
//Windows.InterlockedIncrement(GlobalTestNodeCount);
ownerDocument.AllOwnedNodes.Add(Result);
DomNodeInitialize(Result, ANodeType, ownerDocument, '', '', false);
NodeSetValue(Result, data);
end;
function CheckOutElementDomNode(ownerDocument: PHtmlDocDomNode; const namespaceURI, qualifiedName: WideString; withNS: Boolean): PHtmlElementDomNode;
begin
Result := System.New(PHtmlElementDomNode);
FillChar(Result^, SizeOf(THtmlElementDomNode), 0);
//Windows.InterlockedIncrement(GlobalTestNodeCount);
ownerDocument.AllOwnedNodes.Add(Result);
DomNodeInitialize(PHtmlDomNode(Result), HTMLDOM_NODE_ELEMENT, ownerDocument, namespaceURI, qualifiedName, withNS);
Result.BaseDomNode.Attributes := TNamedNodeMap.Create(Result);
end;
function CheckOutDocTypeDomNode(ownerDocument: PHtmlDocDomNode; const name, publicId, systemId: WideString): PHtmlDocTypeDomNode;
begin
Result := System.New(PHtmlDocTypeDomNode);
FillChar(Result^, SizeOf(THtmlDocTypeDomNode), 0);
//Windows.InterlockedIncrement(GlobalTestNodeCount);
ownerDocument.AllOwnedNodes.Add(Result);
DomNodeInitialize(PHtmlDomNode(Result), HTMLDOM_NODE_DOCUMENT_TYPE, ownerDocument, '', name, false);
Result.PublicID := publicId;
Result.SystemID := systemId;
end;
function createDocumentType(const qualifiedName, publicId, systemId: WideString): PHtmlDocTypeDomNode;
begin
Result := CheckOutDocTypeDomNode(nil, qualifiedName, publicId, systemId);
end;
function CheckOutDocDomNode(doctype: PHtmlDocTypeDomNode): PHtmlDocDomNode;
begin
Result := System.New(PHtmlDocDomNode);
FillChar(Result^, SizeOf(THtmlDocDomNode), 0);
//Windows.InterlockedIncrement(GlobalTestNodeCount);
Result.AllOwnedNodes := TList.Create;
DomNodeInitialize(PHtmlDomNode(Result), HTMLDOM_NODE_DOCUMENT, Result, '', '', false);
if nil <> doctype then
begin
Result.DocTypeDomNode := doctype;
end;
if (nil <> Result.DocTypeDomNode) then
Result.DocTypeDomNode.BaseDomNode.OwnerDocument := Result;
Result.NamespaceURIList := TNamespaceURIList.Create;
Result.SearchNodeLists := TList.Create;
end;
function createEmptyDocument(doctype: PHtmlDocTypeDomNode): PHtmlDocDomNode;
begin
Result := nil;
if (nil <> doctype) and (nil <> doctype.BaseDomNode.ownerDocument) then
begin
// raise DomException.Create(ERR_WRONG_DOCUMENT);
end;
Result := CheckOutDocDomNode(doctype);
end;
end.
|
unit UDMAtalhos;
interface
uses
Winapi.Windows, Winapi.ShellAPI,
System.SysUtils, System.Classes, System.StrUtils,
Data.DB, Datasnap.DBClient,
Vcl.Menus, Vcl.ExtCtrls, Vcl.Forms, Vcl.Dialogs;
type
TDMAtalhos = class(TDataModule)
CDSAtalhos: TClientDataSet;
CDSAtalhosAtalho: TStringField;
CDSAtalhosDiretorio: TStringField;
DSAtalhos: TDataSource;
tiTrayManager: TTrayIcon;
popShortcuts: TPopupMenu;
N2: TMenuItem;
miCreateShortcut: TMenuItem;
btRemoveShortcut: TMenuItem;
N1: TMenuItem;
miCloseApplication: TMenuItem;
miOpcoes: TMenuItem;
procedure CDSAtalhosAfterPost(DataSet: TDataSet);
procedure CDSAtalhosBeforeDelete(DataSet: TDataSet);
procedure miClick(Sender: TObject);
procedure miCreateShortcutClick(Sender: TObject);
procedure btRemoveShortcutClick(Sender: TObject);
procedure miCloseApplicationClick(Sender: TObject);
procedure tiTrayManagerDblClick(Sender: TObject);
procedure CDSAtalhosAfterDelete(DataSet: TDataSet);
private
{ Private declarations }
procedure AddAtalho(_Shortcut, _Diretorio: String);
public
{ Public declarations }
procedure LoadShortcut;
procedure ReloadShortcut;
procedure SaveShortcut(Shortcut: String; Directory: String);
procedure DeleteShortcut(Shortcut: String);
procedure ExportShortcut;
procedure ImportShortcut;
end;
TFileOperation = (Edit, Explore, Find, Open, Print, NULL, RunAs);
const
cFileOperation : array[TFileOperation] of string = ('edit', 'explore', 'find', 'open', 'print', 'NULL', 'runas');
const
RegistryKey = 'SOFTWARE\ShortcutMaster\List';
var
DMAtalhos: TDMAtalhos;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses Utils.Registry, UMain, UShortcutManager;
{$R *.dfm}
{ TDMAtalhos }
procedure TDMAtalhos.btRemoveShortcutClick(Sender: TObject);
begin
Application.CreateForm(TFShortcutManager, FShortcutManager);
FShortcutManager.setActiveCard(FShortcutManager.cdRemoveShortcut);
FShortcutManager.Show;
end;
procedure TDMAtalhos.CDSAtalhosAfterDelete(DataSet: TDataSet);
begin
ReloadShortcut;
end;
procedure TDMAtalhos.CDSAtalhosAfterPost(DataSet: TDataSet);
begin
if not(RegistryValueExists(CurrentUser, RegistryKey, False, CDSAtalhosAtalho.AsString)) then
WriteToRegistry(CurrentUser, RegistryKey, True, CDSAtalhosAtalho.AsString, CDSAtalhosDiretorio.AsString);
end;
procedure TDMAtalhos.CDSAtalhosBeforeDelete(DataSet: TDataSet);
begin
DeleteValueFromRegistry(CurrentUser, RegistryKey, False, CDSAtalhosAtalho.AsString);
end;
procedure TDMAtalhos.DeleteShortcut(Shortcut: String);
begin
if Assigned(CDSAtalhos) then
if CDSAtalhos.Locate('Atalho', Shortcut, []) then
CDSAtalhos.Delete;
end;
procedure TDMAtalhos.ExportShortcut;
var
Dialog: TFileOpenDialog;
begin
if CDSAtalhos.IsEmpty then
Exit;
Dialog := TFileOpenDialog.Create(Application);
Dialog.OkButtonLabel := 'Selecionar';
Dialog.Options := Dialog.Options + [fdoDontAddToRecent];
with Dialog.FileTypes.Add do
begin
FileMask := '*.SMconfigs';
DisplayName := 'Arquivo de configuração do Shortcut Master v1';
end;
Dialog.Title := Application.Title;
if Dialog.Execute then
CDSAtalhos.SaveToFile(IfThen(ExtractFileExt(Dialog.FileName) = '', Dialog.FileName+'.SMConfigs'), dfXML);
FreeAndNil(Dialog);
end;
procedure TDMAtalhos.ImportShortcut;
var
Dialog: TFileOpenDialog;
begin
if not(CDSAtalhos.IsEmpty) then
CDSAtalhos.EmptyDataSet;
Dialog := TFileOpenDialog.Create(Application);
Dialog.OkButtonLabel := 'Selecionar';
Dialog.Options := Dialog.Options + [fdoFileMustExist, fdoDontAddToRecent];
with Dialog.FileTypes.Add do
begin
FileMask := '*.SMconfigs';
DisplayName := 'Arquivo de configuração do Shortcut Master v1';
end;
Dialog.Title := Application.Title;
if Dialog.Execute then
CDSAtalhos.LoadFromFile(Dialog.FileName);
CDSAtalhos.First;
while not(CDSAtalhos.Eof) do
begin
CDSAtalhos.Edit;
CDSAtalhos.Post;
CDSAtalhos.Next;
end;
FreeAndNil(Dialog);
ReloadShortcut;
end;
procedure TDMAtalhos.miClick(Sender: TObject);
var
MenuHint: String;
begin
MenuHint := TMenuItem(Sender).Hint;
if MenuHint.IsEmpty then
Exit;
if DirectoryExists(MenuHint) then
ShellExecute(0, PWideChar(cFileOperation[Explore]), PWideChar(MenuHint), '', nil, SW_SHOWNORMAL)
else
if FileExists(MenuHint) then
ShellExecute(0, PWideChar(cFileOperation[Open]), PWideChar(MenuHint), '', PWideChar(ExtractFileDir(MenuHint)), SW_SHOW);
end;
procedure TDMAtalhos.miCloseApplicationClick(Sender: TObject);
begin
FMain.Close;
end;
procedure TDMAtalhos.miCreateShortcutClick(Sender: TObject);
begin
Application.CreateForm(TFShortcutManager, FShortcutManager);
FShortcutManager.setActiveCard(FShortcutManager.cdNewShortcut);
FShortcutManager.Show;
end;
procedure TDMAtalhos.ReloadShortcut;
var
I: Integer;
begin
CDSAtalhos.EmptyDataSet;
for I := popShortcuts.Items.Count-1 downto 0 do
begin
if popShortcuts.Items[i].Tag = 1 then
popShortcuts.Items.Delete(i);
end;
LoadShortcut;
end;
procedure TDMAtalhos.AddAtalho(_Shortcut: String; _Diretorio: String);
var
popItem: TMenuItem;
begin
CDSAtalhos.Open;
CDSAtalhos.Append;
CDSAtalhosAtalho.AsString := _Shortcut;
CDSAtalhosDiretorio.AsString := _Diretorio;
CDSAtalhos.Post;
popItem := TMenuItem.Create(popShortcuts);
popItem.Caption := _Shortcut;
popItem.Hint := _Diretorio;
popItem.Tag := 1;
popItem.OnClick := miClick;
popShortcuts.Items.Add(popItem);
end;
procedure TDMAtalhos.LoadShortcut;
var
ShortcutList: TKeyListValues;
i: Integer;
begin
try
ShortcutList := ReadFromRegistry(CurrentUser, RegistryKey);
finally
if ShortcutList.Count >= 0 then
begin
for i := 0 to ShortcutList.Count-1 do
begin
AddAtalho(ShortcutList.Names[i], ShortcutList.Values[i]);
end;
end;
end;
end;
procedure TDMAtalhos.SaveShortcut(Shortcut, Directory: String);
begin
if Assigned(CDSAtalhos) then
AddAtalho(Shortcut, Directory);
end;
procedure TDMAtalhos.tiTrayManagerDblClick(Sender: TObject);
begin
FMain.Show;
end;
end.
|
procedure VulArrayMetRandomIntegers(var pArr: array of integer; min, max: integer);
var teller: integer;
begin
RANDOMIZE;
for teller := 0 to LENGTH(pArr) - 1 do
begin
pArr[teller] := RANDOM(max) + min;
end;
end;
|
(*
ENUNCIADO
Uma matriz inteira A n×n é considerada uma matriz de permutação se em cada linha e em cada coluna
houver n - 1 elementos nulos e um único elemento igual a 1.
Um exemplo de Matriz de permutação:
//Devia ter uma imagem aqui
Um exemplo de Matriz que não é de permutação:
//Devia ter uma imagem aqui
Faça um programa em Free Pascal que leia um inteiro positivo n, sendo 1 ≤ m, n ≤ 100, e uma matriz
inteira A n×n . O programa deve imprimir “sim” caso a matriz A seja de permutação, caso contrário deve
imprimir “nao”.
Nos casos de teste cada elemento x da matriz A é definido por 0 ≤ x ≤ 100.
Exemplo de entrada 1:
3
1 0 0
0 1 0
0 0 1
Saı́da esperada para o exemplo acima:
sim
Exemplo de entrada 2:
3
1 0 0
1 0 0
0 1 0
Saı́da esperada para o exemplo acima:
nao
*)
program 3permutacaoemmatriz;
const
max = 100;
type
matriz = array [1 .. max,1 .. max] of longint;
function verlin(mat:matriz; n,l:longint):boolean;
var
cont,soma:longint;
begin
verlin:=true;
cont:=0;
soma:=0;
while (cont<n) and (verlin=true) do
begin
cont:=cont+1;
soma:=soma+mat[l,cont];
end;
if soma <> 1 then
verlin:=false;
end;
function vercol(mat:matriz; n,c:longint):boolean;
var
cont,soma:longint;
begin
vercol:=true;
cont:=0;
soma:=0;
while (cont<n) and (vercol=true) do
begin
cont:=cont+1;
soma:=soma+mat[cont,c];
end;
if soma <> 1 then
vercol:=false;
end;
function vernum(mat:matriz; n:longint):boolean;
var
lin,col:longint;
begin
vernum:=false;
lin:=0;
while (lin<n) and (vernum=false) do
begin
lin:=lin+1;
col:=0;
while (col<n) and (vernum=false) do
begin
col:=col+1;
if (mat[lin,col]<>0)and(mat[lin,col]<>1) then
vernum:=true;
end;
end;
end;
procedure ler(var mat:matriz; n:longint);
var
l,c:longint;
begin
for l:=1 to n do
for c:=1 to n do
read(mat[l,c]);
end;
var
n,lin,col:longint;
flag1,flag2,difer:boolean;
mat:matriz;
begin
read(n);
ler(mat,n);
difer:=vernum(mat,n);
if (difer = true) then
writeln('nao')
else
begin
col:=0;
repeat
col:=col+1;
flag1:=vercol(mat,n,col);
until (col=n) or (flag1=false);
lin:=0;
repeat
lin:=lin+1;
flag2:=verlin(mat,n,lin);
until (lin=n) or (flag2=false);
if (flag1=false) or (flag2=false) then
writeln('nao')
else
writeln('sim');
end;
end.
|
//************************************************************************
//
// Program Name : AT Library
// Platform(s) : Android, iOS, Linux, MacOS, Windows
// Framework : Console, FMX, VCL
//
// Filename : AT.Config.Storage.INI.pas
// Date Created : 01-AUG-2014
// Author : Matthew Vesperman
//
// Description:
//
// INI config storage class.
//
// Revision History:
//
// v1.00 : Initial version
// v1.10 : Added DeleteSection method
//
//************************************************************************
//
// COPYRIGHT © 2014 Angelic Technology
// ALL RIGHTS RESERVED WORLDWIDE
//
//************************************************************************
/// <summary>
/// INI file based configuration storage class.
/// </summary>
unit AT.Config.Storage.INI;
interface
uses
System.Classes, AT.Config.Storage.Custom, System.SysUtils,
System.IniFiles, AT.Config.Storage.Intf;
type
TATConfigIniStorage = class(TATCustomConfigStorage,
ICfgStgDelete, ICfgStgQuery, ICfgStgRead, ICfgStgWrite)
strict private
FFileName: TFileName;
function CreateIni: TIniFile; virtual;
strict protected
procedure WriteCfgHeaderComment(const AHandle: Integer; const AValue:
String); virtual;
public
constructor Create; overload; override;
constructor Create(const sFileName: TFileName); overload; virtual;
destructor Destroy; override;
procedure DeleteEntry(const sSection: String; const sEntry: String);
override;
procedure DeleteSection(const sSection: String); override;
function HasEntry(const sSection: String; const
sEntry: String): Boolean;
function HasSection(const sSection: String): Boolean;
function ReadBoolean(const sSection: String; const sEntry: String; const
bDefault: Boolean): Boolean; override;
function ReadCurrency(const sSection: String; const sEntry: String; const
cDefault: Currency): Currency; override;
function ReadDate(const sSection: String; const sEntry: String; const
dtDefault: TDateTime): TDateTime; override;
function ReadDateTime(const sSection: String; const sEntry: String; const
dtDefault: TDateTime): TDateTime; override;
function ReadDouble(const sSection: String; const sEntry: String; const
rDefault: Double): Double; override;
function ReadInteger(const sSection: String; const sEntry: String; const
iDefault: Integer): Integer; override;
function ReadString(const sSection, sEntry, sDefault: String): string; override;
function ReadTime(const sSection: String; const sEntry: String; const
dtDefault: TDateTime): TDateTime; override;
procedure WriteBoolean(const sSection: String; const sEntry: String; const
bValue: Boolean); override;
procedure WriteCurrency(const sSection: String; const sEntry: String; const
cValue: Currency); override;
procedure WriteDate(const sSection: String; const sEntry: String; const
dtValue: TDateTime); override;
procedure WriteDateTime(const sSection: String; const sEntry: String; const
dtValue: TDateTime); override;
procedure WriteDouble(const sSection: String; const sEntry: String; const
rValue: Double); override;
procedure WriteInteger(const sSection: String; const sEntry: String; const
iValue: Integer); override;
procedure WriteString(const sSection: String; const sEntry: String; const
sValue: String); override;
procedure WriteTime(const sSection: String; const sEntry: String; const
dtValue: TDateTime); override;
published
property FileName: TFileName read FFileName write FFileName;
end;
implementation
{$IF Defined(MSWINDOWS)}
uses
Winapi.Windows;
{$ENDIF}
{
***************************** TATConfigIniStorage ******************************
}
constructor TATConfigIniStorage.Create;
begin
inherited Create;
end;
constructor TATConfigIniStorage.Create(const sFileName: TFileName);
resourcestring
resCfgHdrComnt1 = '; **********************************************************************************' + #13#10;
resCfgHdrComnt2 = '; UNLESS INSTRUCTED TO DO SO, DO NOT MAKE ANY MANUAL CHANGES TO THIS FILE. ' + #13#10;
resCfgHdrComnt3 = '; DOING SO CAN MAKE YOUR SOFTWARE RUN INCORRECTLY, OR COULD EVEN MAKE IT UNUSABLE. ' + #13#10;
resCfgHdrComnt4 = '; IF YOU MAKE MANUAL CHANGES YOU DO SO AT YOUR OWN RISK! ' + #13#10;
resCfgHdrComnt5 = '; **********************************************************************************' + #13#10;
var
aHandle: Integer;
begin
Self.Create;
Self.FileName := sFileName;
if (NOT FileExists(Self.FileName)) then
begin
aHandle := FileCreate(Self.FileName);
WriteCfgHeaderComment(aHandle, resCfgHdrComnt1);
WriteCfgHeaderComment(aHandle, resCfgHdrComnt2);
WriteCfgHeaderComment(aHandle, resCfgHdrComnt3);
WriteCfgHeaderComment(aHandle, resCfgHdrComnt4);
WriteCfgHeaderComment(aHandle, resCfgHdrComnt5);
FileClose(aHandle);
end;
end;
destructor TATConfigIniStorage.Destroy;
begin
inherited Destroy;
end;
function TATConfigIniStorage.HasEntry(const sSection,
sEntry: String): Boolean;
begin
var AFileName: String := FileName;
if ( AFileName.IsEmpty ) then
exit (False);
var Ini := CreateIni;
try
if (Assigned(Ini)) then
begin
Result := Ini.ValueExists(sSection, sEntry);
end
else
Result := False;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.HasSection(
const sSection: String): Boolean;
begin
var AFileName: String := FileName;
if ( AFileName.IsEmpty ) then
exit (False);
var Ini := CreateIni;
try
if (Assigned(Ini)) then
begin
Result := Ini.SectionExists(sSection);
end
else
Result := False;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.CreateIni: TIniFile;
begin
if (Self.FileName <> '') then
begin
Result := TIniFile.Create(Self.FileName);
end
else
Result := NIL;
end;
procedure TATConfigIniStorage.DeleteEntry(const sSection: String; const sEntry:
String);
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
if (Assigned(Ini)) then
begin
Ini.DeleteKey(sSection, sEntry);
end;
finally
Ini.Free;
end;
end;
procedure TATConfigIniStorage.DeleteSection(const sSection: String);
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
if (Assigned(Ini)) then
begin
Ini.EraseSection(sSection);
end;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.ReadBoolean(const sSection: String; const sEntry:
String; const bDefault: Boolean): Boolean;
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
Result := bDefault;
if (Assigned(Ini)) then
begin
Result := Ini.ReadBool(sSection, sEntry, bDefault);
end;
except
Result := bDefault;
end;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.ReadCurrency(const sSection: String; const sEntry:
String; const cDefault: Currency): Currency;
var
Ini: TIniFile;
sVal: string;
begin
Ini := CreateIni;
try
try
Result := cDefault;
if (Assigned(Ini)) then
begin
sVal := CurrToStr(cDefault);
sVal := Ini.ReadString(sSection, sEntry, sVal);
Result := StrToCurr(sVal);
end;
except
Result := cDefault;
end;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.ReadDate(const sSection: String; const sEntry:
String; const dtDefault: TDateTime): TDateTime;
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
Result := dtDefault;
if (Assigned(Ini)) then
begin
Result := Ini.ReadDate(sSection, sEntry, dtDefault);
end;
except
Result := dtDefault;
end;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.ReadDateTime(const sSection: String; const sEntry:
String; const dtDefault: TDateTime): TDateTime;
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
Result := dtDefault;
if (Assigned(Ini)) then
begin
Result := Ini.ReadDateTime(sSection, sEntry, dtDefault);
end;
except
Result := dtDefault;
end;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.ReadDouble(const sSection: String; const sEntry:
String; const rDefault: Double): Double;
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
Result := rDefault;
if (Assigned(Ini)) then
begin
Result := Ini.ReadFloat(sSection, sEntry, rDefault);
end;
except
Result := rDefault;
end;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.ReadInteger(const sSection: String; const sEntry:
String; const iDefault: Integer): Integer;
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
Result := iDefault;
if (Assigned(Ini)) then
begin
Result := Ini.ReadInteger(sSection, sEntry, iDefault);
end;
except
Result := iDefault;
end;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.ReadString(const sSection, sEntry,
sDefault: String): string;
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
Result := sDefault;
if (Assigned(Ini)) then
begin
Result := Ini.ReadString(sSection, sEntry, sDefault);
end;
except
Result := sDefault;
end;
finally
Ini.Free;
end;
end;
function TATConfigIniStorage.ReadTime(const sSection: String; const sEntry:
String; const dtDefault: TDateTime): TDateTime;
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
Result := dtDefault;
if (Assigned(Ini)) then
begin
Result := Ini.ReadTime(sSection, sEntry, dtDefault);
end;
except
Result := dtDefault;
end;
finally
Ini.Free;
end;
end;
procedure TATConfigIniStorage.WriteBoolean(const sSection: String; const
sEntry: String; const bValue: Boolean);
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
if (Assigned(Ini)) then
begin
Ini.WriteBool(sSection, sEntry, bValue);
end;
except
end;
finally
Ini.Free;
end;
end;
procedure TATConfigIniStorage.WriteCfgHeaderComment(const AHandle: Integer;
const AValue: String);
var
sValue: String;
begin
sValue := AValue;
FileWrite(AHandle, sValue[1], Length(sValue));
end;
procedure TATConfigIniStorage.WriteCurrency(const sSection: String; const
sEntry: String; const cValue: Currency);
var
Ini: TIniFile;
sVal: string;
begin
Ini := CreateIni;
try
try
if (Assigned(Ini)) then
begin
sVal := CurrToStr(cValue);
Ini.WriteString(sSection, sEntry, sVal);
end;
except
end;
finally
Ini.Free;
end;
end;
procedure TATConfigIniStorage.WriteDate(const sSection: String; const sEntry:
String; const dtValue: TDateTime);
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
if (Assigned(Ini)) then
begin
Ini.WriteDate(sSection, sEntry, dtValue);
end;
except
end;
finally
Ini.Free;
end;
end;
procedure TATConfigIniStorage.WriteDateTime(const sSection: String; const
sEntry: String; const dtValue: TDateTime);
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
if (Assigned(Ini)) then
begin
Ini.WriteDateTime(sSection, sEntry, dtValue);
end;
except
end;
finally
Ini.Free;
end;
end;
procedure TATConfigIniStorage.WriteDouble(const sSection: String; const sEntry:
String; const rValue: Double);
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
if (Assigned(Ini)) then
begin
Ini.WriteFloat(sSection, sEntry, rValue);
end;
except
end;
finally
Ini.Free;
end;
end;
procedure TATConfigIniStorage.WriteInteger(const sSection: String; const
sEntry: String; const iValue: Integer);
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
if (Assigned(Ini)) then
begin
Ini.WriteInteger(sSection, sEntry, iValue);
end;
except
end;
finally
Ini.Free;
end;
end;
procedure TATConfigIniStorage.WriteString(const sSection: String; const sEntry:
String; const sValue: String);
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
if (Assigned(Ini)) then
begin
Ini.WriteString(sSection, sEntry, sValue);
end;
except
end;
finally
Ini.Free;
end;
end;
procedure TATConfigIniStorage.WriteTime(const sSection: String; const sEntry:
String; const dtValue: TDateTime);
var
Ini: TIniFile;
begin
Ini := CreateIni;
try
try
if (Assigned(Ini)) then
begin
Ini.WriteTime(sSection, sEntry, dtValue);
end;
except
end;
finally
Ini.Free;
end;
end;
end.
|
{
4.Даны векторы X[10], Y[20] и величина T.
Если хотя бы одна компонента вектора X больше значения T,
то все его отрицательные компоненты заменить на значение T.
Если у вектора Y есть хотя бы одна положительная компонента,
то все его отрицательные компоненты заменить максимальной
компонентой этого вектора
}
program task_1_1;
uses crt;
type
vector = array[1..20] of real;
var
X, Y: vector;
T, number: real;
i: integer;
procedure input(var arr: vector; quantity: byte);
begin
writeln;
for i := 1 to quantity do
begin
write('Введите ', i ,' элемент вектора:');
readln(arr[i]);
end;
writeln;
end;
procedure echo(var arr:vector; quantity: byte);
begin
writeln;
for i := 1 to quantity do
begin
write(arr[i]:8:4);
end;
writeln;
end;
procedure replace(var arr: vector; sub: real; quantity: byte);
begin
for i := 1 to quantity do
begin
if arr[i] < 0 then arr[i] := sub;
end
end;
function max(arr: vector; quantity: byte): real;
var max_element: real;
begin
max_element := arr[1];
for i := 2 to quantity do
begin
if arr[i] > max_element then max_element := arr[i];
end;
max := max_element;
end;
procedure compare(var arr: vector; quantity: byte; value: real; sub: real);
var flag: boolean;
begin
flag := false;
for i := 1 to quantity do
begin
if arr[i] > value then
begin
flag := true;
break;
end;
end;
if flag then replace(arr, sub, quantity);
end;
begin
write('Введите величину T:');
readln(T);
write('Ввод вектора X');
input(X, 5);
echo(X, 5);
write('Ввод вектора Y');
input(Y, 5);
compare(X, 5, T, T);
compare(Y, 5, 0, max(Y, 5));
write('Вывод вектора X');
echo(X, 5);
write('Вывод вектора Y');
echo(Y, 5);
end. |
{**************************************************************************}
{ }
{ This Source Code Form is subject to the terms of the Mozilla Public }
{ License, v. 2.0. If a copy of the MPL was not distributed with this }
{ file, You can obtain one at http://mozilla.org/MPL/2.0/. }
{ }
{ 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. }
{ }
{ Copyright Eric Grange / Creative IT }
{ }
{**************************************************************************}
unit dwsJIT;
{$I ../dws.inc}
interface
uses
Classes, SysUtils,
dwsExprs, dwsExprList, dwsSymbols, dwsErrors, dwsUtils, dwsCoreExprs, dwsXPlatform,
dwsRelExprs, dwsMagicExprs, dwsJITFixups;
type
DWORD = Cardinal;
TdwsJIT = class;
TdwsJITOption = (jitoDoStep, jitoRangeCheck,
jitoNoBranchAlignment);
TdwsJITOptions = set of TdwsJITOption;
TdwsJITter = class (TRefCountedObject)
private
Fjit : TdwsJIT;
protected
property jit : TdwsJIT read Fjit;
public
constructor Create(aJIT : TdwsJIT);
function IncRefCount : TdwsJITter; {inline;}
procedure CompileStatement(expr : TExprBase); virtual;
function CompileFloat(expr : TTypedExpr) : Integer; virtual;
function CompileInteger(expr : TTypedExpr) : Integer; virtual;
function CompileBooleanValue(expr : TTypedExpr) : Integer; virtual;
procedure CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); virtual;
function CompileScriptObj(expr : TTypedExpr) : Integer; virtual;
procedure CompileAssignFloat(expr : TTypedExpr; source : Integer); virtual;
procedure CompileAssignInteger(expr : TTypedExpr; source : Integer); virtual;
procedure CompileAssignBoolean(expr : TTypedExpr; source : Integer); virtual;
end;
TdwsRegisteredJITter = class (TRefCountedObject)
public
Expr : TClass;
JIT : TdwsJITter;
destructor Destroy; override;
end;
TdwsRegisteredJITterListBase = TSortedList<TdwsRegisteredJITter>;
TdwsRegisteredJITterList = class(TdwsRegisteredJITterListBase)
protected
function Compare(const item1, item2 : TdwsRegisteredJITter) : Integer; override;
end;
TdwsJITCodeBlock = record
public
Code : Pointer;
SubAllocator : TRefCountedObject;
Steppable : Boolean;
procedure Free;
end;
TJITTedProgramExpr = class (TNoResultExpr)
private
FOriginal : TProgramExpr;
protected
FCode : TdwsJITCodeBlock;
function GetSubExpr(i : Integer) : TExprBase; override;
function GetSubExprCount : Integer; override;
public
constructor Create(original : TProgramExpr; const code : TdwsJITCodeBlock); virtual;
destructor Destroy; override;
procedure EvalNoResult(exec : TdwsExecution); override;
property Original : TProgramExpr read FOriginal write FOriginal;
end;
TJITTedProgramExprClass = class of TJITTedProgramExpr;
TJITTedTypedExpr = class (TTypedExpr)
private
FOriginal : TTypedExpr;
protected
FCode : TdwsJITCodeBlock;
function GetSubExpr(i : Integer) : TExprBase; override;
function GetSubExprCount : Integer; override;
public
constructor Create(original : TTypedExpr; const code : TdwsJITCodeBlock); virtual;
destructor Destroy; override;
function ScriptPos : TScriptPos; override;
property Original : TTypedExpr read FOriginal write FOriginal;
end;
TJITTedFloatExpr = class (TJITTedTypedExpr)
public
function Eval(exec : TdwsExecution) : Variant; override;
procedure EvalAsVariant(exec : TdwsExecution; var Result : Variant); override;
end;
TJITTedFloatExprClass = class of TJITTedFloatExpr;
TJITTedIntegerExpr = class (TJITTedTypedExpr)
public
function Eval(exec : TdwsExecution) : Variant; override;
procedure EvalAsVariant(exec : TdwsExecution; var Result : Variant); override;
end;
TJITTedIntegerExprClass = class of TJITTedIntegerExpr;
TQueuedJITGreed = class
public
Next : TQueuedJITGreed;
Expr : TExprBase;
Prog : TdwsProgram;
end;
TJITLoopContext = class
public
TargetContinue : TFixup;
TargetExit : TFixup;
Exited : Boolean;
Prev : TJITLoopContext;
end;
TSymbolHash = TSimpleObjectHash<TSymbol>;
TdwsJIT = class
public
FRegistered : TdwsRegisteredJITterList;
private
FTempReg : TdwsRegisteredJITter;
FOutput : TWriteOnlyBlockStream;
FOutputFailedOn : TExprBase;
FSeenByGreedy : TSymbolHash;
FQueuedGreed : TQueuedJITGreed;
FFixups : TFixupLogic;
FLoopContext : TJITLoopContext;
FExitTarget : TFixupTarget;
FJITTedProgramExprClass : TJITTedProgramExprClass;
FJITTedFloatExprClass : TJITTedFloatExprClass;
FJITTedIntegerExprClass : TJITTedIntegerExprClass;
FOptions : TdwsJITOptions;
protected
function CreateOutput : TWriteOnlyBlockStream; virtual;
function CreateFixupLogic : TFixupLogic; virtual;
procedure SetOutputFailedOn(e : TExprBase);
procedure StartJIT(expr : TExprBase; exitable : Boolean); virtual;
procedure EndJIT; virtual;
procedure EndFloatJIT(resultHandle : Integer); virtual;
procedure EndIntegerJIT(resultHandle : Integer); virtual;
function GetLocation : Integer;
property JITTedProgramExprClass : TJITTedProgramExprClass read FJITTedProgramExprClass write FJITTedProgramExprClass;
property JITTedFloatExprClass : TJITTedFloatExprClass read FJITTedFloatExprClass write FJITTedFloatExprClass;
property JITTedIntegerExprClass : TJITTedIntegerExprClass read FJITTedIntegerExprClass write FJITTedIntegerExprClass;
public
constructor Create; virtual;
destructor Destroy; override;
procedure RegisterJITter(exprClass : TClass; jitter : TdwsJITter);
function FindJITter(exprClass : TClass) : TdwsJITter; overload;
function FindJITter(expr : TExprBase) : TdwsJITter; overload;
function JITStatement(expr : TProgramExpr; exitable : Boolean) : TJITTedProgramExpr;
function JITFloat(expr : TTypedExpr) : TJITTedFloatExpr;
function JITInteger(expr : TTypedExpr) : TJITTedIntegerExpr;
procedure CompileStatement(expr : TExprBase);
function CompileFloat(expr : TTypedExpr) : Integer;
function CompileInteger(expr : TTypedExpr) : Integer;
function CompileBooleanValue(expr : TTypedExpr) : Integer;
procedure CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
function CompileScriptObj(expr : TTypedExpr) : Integer;
procedure CompileAssignFloat(expr : TTypedExpr; source : Integer);
procedure CompileAssignInteger(expr : TTypedExpr; source : Integer);
procedure CompileAssignBoolean(expr : TTypedExpr; source : Integer);
function IsFloat(expr : TTypedExpr) : Boolean; overload; inline;
function IsFloat(typ : TTypeSymbol) : Boolean; overload;
function IsInteger(expr : TTypedExpr) : Boolean; overload;
function IsBoolean(expr : TTypedExpr) : Boolean; overload;
property LoopContext : TJITLoopContext read FLoopContext;
property ExitTarget : TFixupTarget read FExitTarget;
procedure EnterLoop(targetContinue, targetExit : TFixup);
procedure LeaveLoop;
property Fixups : TFixupLogic read FFixups;
property Options : TdwsJITOptions read FOptions write FOptions;
function CompiledOutput : TdwsJITCodeBlock; virtual; abstract;
procedure Clear;
procedure GreedyJIT(expr : TExprBase); overload;
procedure GreedyJIT(prog : TdwsProgram); overload;
procedure GreedyJITParameters(funcExpr : TFuncExprBase);
procedure DeQueueGreed;
procedure QueueGreed(expr : TExprBase); overload;
procedure QueueGreed(prog : TdwsProgram); overload;
property Output : TWriteOnlyBlockStream read FOutput;
property OutputFailedOn : TExprBase read FOutputFailedOn write SetOutputFailedOn;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TdwsJITter ------------------
// ------------------
// Create
//
constructor TdwsJITter.Create(aJIT : TdwsJIT);
begin
Fjit:=aJIT;
end;
// IncRefCount
//
function TdwsJITter.IncRefCount : TdwsJITter;
begin
inherited IncRefCount;
Result:=Self;
end;
// CompileFloat
//
function TdwsJITter.CompileFloat(expr : TTypedExpr) : Integer;
begin
jit.OutputFailedOn:=expr;
Result:=0;
end;
// CompileInteger
//
function TdwsJITter.CompileInteger(expr : TTypedExpr) : Integer;
begin
jit.OutputFailedOn:=expr;
Result:=0;
end;
// CompileBooleanValue
//
function TdwsJITter.CompileBooleanValue(expr : TTypedExpr) : Integer;
begin
jit.OutputFailedOn:=expr;
Result:=0;
end;
// CompileBoolean
//
procedure TdwsJITter.CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
begin
jit.OutputFailedOn:=expr;
end;
// CompileScriptObj
//
function TdwsJITter.CompileScriptObj(expr : TTypedExpr) : Integer;
begin
jit.OutputFailedOn:=expr;
Result:=0;
end;
// CompileAssignFloat
//
procedure TdwsJITter.CompileAssignFloat(expr : TTypedExpr; source : Integer);
begin
jit.OutputFailedOn:=expr;
end;
// CompileAssignInteger
//
procedure TdwsJITter.CompileAssignInteger(expr : TTypedExpr; source : Integer);
begin
jit.OutputFailedOn:=expr;
end;
// CompileAssignBoolean
//
procedure TdwsJITter.CompileAssignBoolean(expr : TTypedExpr; source : Integer);
begin
jit.OutputFailedOn:=expr;
end;
// CompileStatement
//
procedure TdwsJITter.CompileStatement(expr : TExprBase);
begin
jit.OutputFailedOn:=expr;
end;
// ------------------
// ------------------ TdwsRegisteredJITter ------------------
// ------------------
// Destroy
//
destructor TdwsRegisteredJITter.Destroy;
begin
inherited;
JIT.Free;
end;
// ------------------
// ------------------ TdwsRegisteredJITterList ------------------
// ------------------
// Compare
//
function TdwsRegisteredJITterList.Compare(const item1, item2 : TdwsRegisteredJITter) : Integer;
var
i1, i2 : Integer;
begin
i1:=NativeInt(item1.Expr);
i2:=NativeInt(item2.Expr);
if i1<i2 then
Result:=-1
else if i1=i2 then
Result:=0
else Result:=1;
end;
// ------------------
// ------------------ TdwsJITCodeBlock ------------------
// ------------------
// Free
//
procedure TdwsJITCodeBlock.Free;
begin
SubAllocator.DecRefCount;
Code:=nil;
SubAllocator:=nil;
end;
// ------------------
// ------------------ TdwsJITter ------------------
// ------------------
// Create
//
constructor TdwsJIT.Create;
begin
inherited;
FRegistered:=TdwsRegisteredJITterList.Create;
FTempReg:=TdwsRegisteredJITter.Create;
FOutput:=CreateOutput;
FSeenByGreedy:=TSymbolHash.Create;
FFixups:=CreateFixupLogic;
FFixups.OnNeedLocation:=GetLocation;
end;
// Destroy
//
destructor TdwsJIT.Destroy;
begin
inherited;
FFixups.Free;
FRegistered.Clean;
FRegistered.Free;
FTempReg.Free;
FOutput.Free;
FSeenByGreedy.Free;
end;
// CreateOutput
//
function TdwsJIT.CreateOutput : TWriteOnlyBlockStream;
begin
Result:=TWriteOnlyBlockStream.Create;
end;
// CreateFixupLogic
//
function TdwsJIT.CreateFixupLogic : TFixupLogic;
begin
Result:=TFixupLogic.Create;
end;
// SetOutputFailedOn
//
procedure TdwsJIT.SetOutputFailedOn(e : TExprBase);
begin
FOutputFailedOn:=e;
end;
// RegisterJITter
//
procedure TdwsJIT.RegisterJITter(exprClass : TClass; jitter : TdwsJITter);
var
reg : TdwsRegisteredJITter;
begin
reg:=TdwsRegisteredJITter.Create;
reg.Expr:=exprClass;
reg.JIT:=jitter;
FRegistered.Add(reg);
end;
// FindJITter
//
function TdwsJIT.FindJITter(exprClass : TClass) : TdwsJITter;
var
i : Integer;
begin
if exprClass.InheritsFrom(TJITTedProgramExpr) then
FTempReg.Expr:=exprClass;
FTempReg.Expr:=exprClass;
if FRegistered.Find(FTempReg, i) then
Result:=FRegistered.Items[i].JIT
else Result:=nil;
end;
// FindJITter
//
function TdwsJIT.FindJITter(expr : TExprBase) : TdwsJITter;
begin
Assert(Assigned(expr));
Result:=Self.FindJITter(expr.ClassType);
end;
// JITStatement
//
function TdwsJIT.JITStatement(expr : TProgramExpr; exitable : Boolean) : TJITTedProgramExpr;
var
jit : TdwsJITter;
begin
Result:=nil;
jit:=Self.FindJITter(expr);
if jit=nil then begin
OutputDebugString(expr.ClassName);
Exit;
end;
StartJIT(expr, exitable);
jit.CompileStatement(expr);
EndJIT;
if OutputFailedOn=nil then
Result:=JITTedProgramExprClass.Create(expr, CompiledOutput)
else begin
OutputDebugString(OutputFailedOn.ClassName);
GreedyJIT(expr);
end;
end;
// JITFloat
//
function TdwsJIT.JITFloat(expr : TTypedExpr) : TJITTedFloatExpr;
var
outcome : Integer;
begin
Result:=nil;
StartJIT(expr, False);
outcome:=CompileFloat(expr);
EndFloatJIT(outcome);
if (OutputFailedOn=nil) then
Result:=JITTedFloatExprClass.Create(expr, CompiledOutput)
else OutputDebugString(OutputFailedOn.ClassName);
end;
// JITInteger
//
function TdwsJIT.JITInteger(expr : TTypedExpr) : TJITTedIntegerExpr;
var
outcome : Integer;
begin
Result:=nil;
StartJIT(expr, False);
outcome:=CompileInteger(expr);
EndIntegerJIT(outcome);
if (OutputFailedOn=nil) then
Result:=JITTedIntegerExprClass.Create(expr, CompiledOutput)
else OutputDebugString(OutputFailedOn.ClassName);
end;
// CompileStatement
//
procedure TdwsJIT.CompileStatement(expr : TExprBase);
var
jit : TdwsJITter;
begin
jit:=FindJITter(expr);
if jit<>nil then
jit.CompileStatement(expr)
else OutputFailedOn:=expr;
end;
// CompileFloat
//
function TdwsJIT.CompileFloat(expr : TTypedExpr) : Integer;
var
jit : TdwsJITter;
begin
jit:=FindJITter(expr);
if jit=nil then begin
OutputFailedOn:=expr;
Result:=0;
end else begin
Result:=jit.CompileFloat(expr);
end;
end;
// CompileInteger
//
function TdwsJIT.CompileInteger(expr : TTypedExpr) : Integer;
var
jit : TdwsJITter;
begin
jit:=FindJITter(expr);
if jit=nil then begin
OutputFailedOn:=expr;
Result:=0;
end else begin
Result:=jit.CompileInteger(expr);
end;
end;
// CompileBooleanValue
//
function TdwsJIT.CompileBooleanValue(expr : TTypedExpr) : Integer;
var
jit : TdwsJITter;
begin
jit:=FindJITter(expr);
if jit=nil then begin
OutputFailedOn:=expr;
Result:=0;
end else Result:=jit.CompileBooleanValue(expr);
end;
// CompileBoolean
//
procedure TdwsJIT.CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
jit : TdwsJITter;
begin
jit:=FindJITter(expr);
if jit=nil then
OutputFailedOn:=expr
else jit.CompileBoolean(expr, targetTrue, targetFalse);
end;
// CompileScriptObj
//
function TdwsJIT.CompileScriptObj(expr : TTypedExpr) : Integer;
var
jit : TdwsJITter;
begin
jit:=FindJITter(expr);
if jit=nil then begin
OutputFailedOn:=expr;
Result:=0;
end else Result:=jit.CompileScriptObj(expr);
end;
// CompileAssignFloat
//
procedure TdwsJIT.CompileAssignFloat(expr : TTypedExpr; source : Integer);
var
jit : TdwsJITter;
begin
jit:=FindJITter(expr);
if jit=nil then
OutputFailedOn:=expr
else jit.CompileAssignFloat(expr, source);
end;
// CompileAssignInteger
//
procedure TdwsJIT.CompileAssignInteger(expr : TTypedExpr; source : Integer);
var
jit : TdwsJITter;
begin
jit:=FindJITter(expr);
if jit=nil then
OutputFailedOn:=expr
else jit.CompileAssignInteger(expr, source);
end;
// CompileAssignBoolean
//
procedure TdwsJIT.CompileAssignBoolean(expr : TTypedExpr; source : Integer);
var
jit : TdwsJITter;
begin
jit:=FindJITter(expr);
if jit=nil then
OutputFailedOn:=expr
else jit.CompileAssignBoolean(expr, source);
end;
// IsFloat
//
function TdwsJIT.IsFloat(expr : TTypedExpr) : Boolean;
begin
Result:=IsFloat(expr.Typ);
end;
// IsFloat
//
function TdwsJIT.IsFloat(typ : TTypeSymbol) : Boolean;
begin
Result:=(typ.UnAliasedType.ClassType=TBaseFloatSymbol);
end;
// IsInteger
//
function TdwsJIT.IsInteger(expr : TTypedExpr) : Boolean;
begin
Result:=(expr.Typ.UnAliasedType.ClassType=TBaseIntegerSymbol);
end;
// IsBoolean
//
function TdwsJIT.IsBoolean(expr : TTypedExpr) : Boolean;
begin
Result:=(expr.Typ.UnAliasedType.ClassType=TBaseBooleanSymbol);
end;
// EnterLoop
//
procedure TdwsJIT.EnterLoop(targetContinue, targetExit : TFixup);
var
context : TJITLoopContext;
begin
context:=TJITLoopContext.Create;
context.TargetContinue:=targetContinue;
context.TargetExit:=targetExit;
context.Prev:=FLoopContext;
FLoopContext:=context;
end;
// LeaveLoop
//
procedure TdwsJIT.LeaveLoop;
var
context : TJITLoopContext;
begin
context:=FLoopContext;
FLoopContext:=context.Prev;
context.Free;
end;
// StartJIT
//
procedure TdwsJIT.StartJIT(expr : TExprBase; exitable : Boolean);
begin
FOutput.Clear;
FOutputFailedOn:=nil;
if exitable then
FExitTarget:=Fixups.NewHangingTarget(False);
end;
// EndJIT
//
procedure TdwsJIT.EndJIT;
begin
if FExitTarget<>nil then begin
Fixups.AddFixup(FExitTarget);
FExitTarget:=nil;
end;
// nothing
end;
// EndFloatJIT
//
procedure TdwsJIT.EndFloatJIT(resultHandle : Integer);
begin
EndJIT;
end;
// EndIntegerJIT
//
procedure TdwsJIT.EndIntegerJIT(resultHandle : Integer);
begin
EndJIT;
end;
// GetLocation
//
function TdwsJIT.GetLocation : Integer;
begin
Result:=Output.Position;
end;
// Clear
//
procedure TdwsJIT.Clear;
begin
FSeenByGreedy.Clear;
end;
// GreedyJIT
//
procedure TdwsJIT.GreedyJIT(expr : TExprBase);
var
i : Integer;
block : TBlockExprBase;
subExpr : TExprBase;
statementJIT : TJITTedProgramExpr;
floatJIT : TJITTedFloatExpr;
funcSym : TFuncSymbol;
funcExpr : TFuncExprBase;
executable : IExecutable;
execObject : TObject;
assignExpr : TAssignExpr;
composite : TCompositeTypeSymbol;
begin
if expr is TBlockExprBase then begin
block:=TBlockExprBase(expr);
for i:=0 to block.SubExprCount-1 do begin
subExpr:=block.SubExpr[i];
if subExpr is TFuncExprBase then
GreedyJIT(subExpr)
else if subExpr is TProgramExpr then begin
statementJIT:=JITStatement(TProgramExpr(subExpr), False);
if statementJIT<>nil then begin
block.ReplaceStatement(i, statementJIT);
continue;
end;
GreedyJIT(subExpr);
end;
end;
end else if expr.ClassType=TAssignExpr then begin
assignExpr:=TAssignExpr(expr);
if assignExpr.Left.Typ.UnAliasedType.ClassType=TBaseFloatSymbol then begin
floatJIT:=JITFloat(assignExpr.Right);
if floatJIT<>nil then begin
assignExpr.Right.Free;
assignExpr.Right:=floatJIT;
end;
end;
end else if expr is TFuncExprBase then begin
funcExpr:=TFuncExprBase(expr);
funcSym:=funcExpr.FuncSym;
if (funcSym is TSourceFuncSymbol) and not FSeenByGreedy.Contains(funcSym) then begin
FSeenByGreedy.Add(funcSym);
executable:=funcSym.Executable;
if executable<>nil then begin
execObject:=executable.GetSelf;
if execObject is TdwsProgram then
QueueGreed(TdwsProgram(execObject));
end;
end else if funcSym is TSourceMethodSymbol then begin
composite:=TSourceMethodSymbol(funcSym).StructSymbol;
while (composite<>nil) and not FSeenByGreedy.Contains(composite) do begin
FSeenByGreedy.Add(composite);
for i:=0 to composite.Members.Count-1 do begin
if composite.Members[i] is TSourceMethodSymbol then begin
funcSym:=TSourceMethodSymbol(composite.Members[i]);
executable:=funcSym.Executable;
if executable<>nil then begin
execObject:=executable.GetSelf;
if execObject is TdwsProgram then
QueueGreed(TdwsProgram(execObject));
end;
end;
end;
composite:=composite.Parent;
end;
end;
GreedyJITParameters(funcExpr);
end else begin
for i:=0 to expr.SubExprCount-1 do begin
subExpr:=expr.SubExpr[i];
if subExpr<>nil then
GreedyJIT(subExpr);
end;
end;
end;
// GreedyJITParameters
//
procedure TdwsJIT.GreedyJITParameters(funcExpr : TFuncExprBase);
var
i : Integer;
jitted : TJITTedTypedExpr;
funcSym : TFuncSymbol;
p : TParamSymbol;
paramTyp : TTypeSymbol;
argExpr : TExprBase;
begin
funcSym:=funcExpr.FuncSym;
if funcSym=nil then Exit;
if funcExpr is TMagicFuncExpr then begin
for i:=0 to funcExpr.Args.Count-1 do begin
p:=funcSym.Params[i];
if p.ClassType<>TParamSymbol then continue;
argExpr:=funcExpr.Args[i];
if not (argExpr is TJITTedTypedExpr) then begin
paramTyp:=p.Typ.UnAliasedType;
if paramTyp is TBaseIntegerSymbol then
jitted:=JITInteger(argExpr as TTypedExpr)
else if paramTyp is TBaseFloatSymbol then
jitted:=JITFloat(argExpr as TTypedExpr)
else jitted:=nil;
if jitted<>nil then begin
funcExpr.Args[i].Free;
funcExpr.Args[i]:=jitted;
end else GreedyJIT(argExpr);
end;
end;
end else begin
for i:=0 to funcExpr.SubExprCount-1 do begin
argExpr:=funcExpr.SubExpr[i];
if argExpr is TFuncExprBase then
QueueGreed(argExpr);
end;
end;
end;
// DeQueueGreed
//
procedure TdwsJIT.DeQueueGreed;
var
greed : TQueuedJITGreed;
begin
while FQueuedGreed<>nil do begin
greed:=FQueuedGreed;
FQueuedGreed:=greed.Next;
try
if greed.Expr<>nil then
GreedyJIT(greed.Expr)
else GreedyJIT(greed.Prog);
finally
greed.Free;
end;
end;
end;
// QueueGreed
//
procedure TdwsJIT.QueueGreed(expr : TExprBase);
var
greed : TQueuedJITGreed;
begin
greed:=TQueuedJITGreed.Create;
greed.Expr:=expr;
greed.Next:=FQueuedGreed;
FQueuedGreed:=greed;
end;
// QueueGreed
//
procedure TdwsJIT.QueueGreed(prog : TdwsProgram);
var
greed : TQueuedJITGreed;
begin
greed:=TQueuedJITGreed.Create;
greed.Prog:=prog;
greed.Next:=FQueuedGreed;
FQueuedGreed:=greed;
end;
// GreedyJIT
//
procedure TdwsJIT.GreedyJIT(prog : TdwsProgram);
var
statementJIT : TJITTedProgramExpr;
begin
if prog.Expr is TProgramExpr then
begin
statementJIT:=Self.JITStatement(prog.Expr, True);
if statementJIT<>nil then begin
prog.Expr.Free;
prog.Expr:=statementJIT;
end;
end;
DeQueueGreed;
end;
// ------------------
// ------------------ TJITTedProgramExpr ------------------
// ------------------
// Create
//
constructor TJITTedProgramExpr.Create(original : TProgramExpr; const code : TdwsJITCodeBlock);
begin
inherited Create(original.ScriptPos);
FCode:=code;
FOriginal:=original;
FOriginal.IncRefCount;
end;
// Destroy
//
destructor TJITTedProgramExpr.Destroy;
begin
inherited;
FOriginal.Free;
FCode.Free;
end;
// EvalNoResult
//
procedure TJITTedProgramExpr.EvalNoResult(exec : TdwsExecution);
begin
FOriginal.EvalNoResult(exec);
end;
// GetSubExpr
//
function TJITTedProgramExpr.GetSubExpr(i : Integer) : TExprBase;
begin
Result:=FOriginal.SubExpr[i];
end;
// GetSubExprCount
//
function TJITTedProgramExpr.GetSubExprCount : Integer;
begin
if FCode.Steppable then
Result:=FOriginal.SubExprCount
else Result:=0;
end;
// ------------------
// ------------------ TJITTedTypedExpr ------------------
// ------------------
// Create
//
constructor TJITTedTypedExpr.Create(original : TTypedExpr; const code : TdwsJITCodeBlock);
begin
inherited Create;
FCode:=code;
FOriginal:=original;
FOriginal.IncRefCount;
end;
// Destroy
//
destructor TJITTedTypedExpr.Destroy;
begin
inherited;
FOriginal.Free;
FCode.Free;
end;
// ScriptPos
//
function TJITTedTypedExpr.ScriptPos : TScriptPos;
begin
Result:=Original.ScriptPos;
end;
// GetSubExpr
//
function TJITTedTypedExpr.GetSubExpr(i : Integer) : TExprBase;
begin
Result:=FOriginal.SubExpr[i];
end;
// GetSubExprCount
//
function TJITTedTypedExpr.GetSubExprCount : Integer;
begin
if FCode.Steppable then
Result:=FOriginal.SubExprCount
else Result:=0;
end;
// ------------------
// ------------------ TJITTedFloatExpr ------------------
// ------------------
// Eval
//
function TJITTedFloatExpr.Eval(exec : TdwsExecution) : Variant;
begin
Result:=EvalAsFloat(exec);
end;
// EvalAsVariant
//
procedure TJITTedFloatExpr.EvalAsVariant(exec : TdwsExecution; var Result : Variant);
begin
result:=EvalAsFloat(exec);
end;
// ------------------
// ------------------ TJITTedIntegerExpr ------------------
// ------------------
// Eval
//
function TJITTedIntegerExpr.Eval(exec : TdwsExecution) : Variant;
begin
Result:=EvalAsInteger(exec);
end;
// EvalAsVariant
//
procedure TJITTedIntegerExpr.EvalAsVariant(exec : TdwsExecution; var Result : Variant);
begin
Result:=EvalAsInteger(exec);
end;
end.
|
unit IdHeaderCoderUTF;
interface
{$i IdCompilerDefines.inc}
uses
IdGlobal, IdHeaderCoderBase;
type
TIdHeaderCoderUTF = class(TIdHeaderCoder)
public
class function Decode(const ACharSet: string; const AData: TIdBytes): String; override;
class function Encode(const ACharSet, AData: String): TIdBytes; override;
class function CanHandle(const ACharSet: String): Boolean; override;
end;
// RLebeau 4/17/10: this forces C++Builder to link to this unit so
// RegisterHeaderCoder can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdHeaderCoderUTF"'*)
implementation
uses
SysUtils;
class function TIdHeaderCoderUTF.Decode(const ACharSet: string; const AData: TIdBytes): String;
var
LEncoding: TIdTextEncoding;
LBytes: TIdBytes;
begin
Result := '';
LBytes := nil;
if TextIsSame(ACharSet, 'UTF-7') then begin {do not localize}
LEncoding := TIdTextEncoding.UTF7;
end
else if TextIsSame(ACharSet, 'UTF-8') then begin {do not localize}
LEncoding := TIdTextEncoding.UTF8;
end else
begin
Exit;
end;
LBytes := TIdTextEncoding.Convert(
LEncoding,
TIdTextEncoding.Unicode,
AData);
Result := TIdTextEncoding.Unicode.GetString(LBytes, 0, Length(LBytes));
end;
class function TIdHeaderCoderUTF.Encode(const ACharSet, AData: String): TIdBytes;
var
LEncoding: TIdTextEncoding;
begin
Result := nil;
if TextIsSame(ACharSet, 'UTF-7') then begin {do not localize}
LEncoding := TIdTextEncoding.UTF7;
end
else if TextIsSame(ACharSet, 'UTF-8') then begin {do not localize}
LEncoding := TIdTextEncoding.UTF8;
end else
begin
Exit;
end;
Result := TIdTextEncoding.Convert(
TIdTextEncoding.Unicode,
LEncoding,
TIdTextEncoding.Unicode.GetBytes(AData));
end;
class function TIdHeaderCoderUTF.CanHandle(const ACharSet: String): Boolean;
begin
Result := PosInStrArray(ACharSet, ['UTF-7', 'UTF-8'], False) > -1; {do not localize}
end;
initialization
RegisterHeaderCoder(TIdHeaderCoderUTF);
finalization
UnregisterHeaderCoder(TIdHeaderCoderUTF);
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Membuf;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure VerifyMembuf(Membuf: TMembuf; Offset: Integer; Bytes: array of Byte; Desc: String = '');
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.VerifyMembuf(Membuf: TMembuf; Offset: Integer; Bytes: array of Byte; Desc: String = '');
begin
if Membuf.VerifyBytes(Offset, Bytes) then begin
Memo1.Lines.Add('Membuf Verify OKú║' + Desc);
end else begin
Memo1.Lines.Add('Membuf Verify FAIL: ' + Desc + ' !!!!!!!!!!!!!');
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
buf1: TMembuf;
i: Integer;
ExceptionRaised: Boolean;
begin
buf1 := TMembuf.Create(0, [0,1,2,3,4]);
VerifyMembuf(buf1, 0, [0,1,2,3,4], 'init');
buf1.AppendBytes([7,8,9]);
VerifyMembuf(buf1, 0, [0,1,2,3,4, 7,8,9], 'append');
buf1.AppendBytes([]);
VerifyMembuf(buf1, 0, [0,1,2,3,4, 7,8,9], 'append []');
buf1.InsertBytes(5, [5,6]);
VerifyMembuf(buf1, 0, [0,1,2,3,4, 5,6, 7,8,9], 'insert');
buf1.AppendBytes([101, 102, 103, 104, 105, 106]);
VerifyMembuf(buf1, 10, [101, 102, 103, 104, 105, 106], 'append2,realloc');
buf1.Remove(0, 10);
VerifyMembuf(buf1, 0, [101, 102, 103, 104, 105, 106], 'remove');
buf1.AppendByte(108);
VerifyMembuf(buf1, 0, [101, 102, 103, 104, 105, 106, 108], 'append byte');
buf1.InsertByte(6, 107);
VerifyMembuf(buf1, 0, [101, 102, 103, 104, 105, 106, 107, 108], 'insert byte');
buf1.InsertByte(8, 109);
VerifyMembuf(buf1, 0, [101, 102, 103, 104, 105, 106, 107, 108, 109], 'insert byte tail');
assert(buf1.Size() = 9);
// test remove
buf1.Clear();
VerifyMembuf(buf1, 0, [], 'clear');
buf1.AppendBytes([0,1,2,3,4,5,6,7,8,9]);
buf1.Remove(8, 2);
VerifyMembuf(buf1, 0, [0,1,2,3,4,5,6,7], 'remove tail');
buf1.Remove(4, 3);
VerifyMembuf(buf1, 0, [0,1,2,3,7], 'remove mid');
buf1.Remove(0, 4);
VerifyMembuf(buf1, 0, [7], 'remove head');
assert(buf1.Size() = 1);
// test insert
buf1.Clear();
buf1.AppendBytes([1,2,3]);
buf1.InsertBytes(0, [0]);
VerifyMembuf(buf1, 0, [0, 1,2,3], 'insert head');
buf1.InsertBytes(4, [4]);
VerifyMembuf(buf1, 0, [0,1,2,3, 4], 'insert tail');
buf1.InsertBytes(2, [9,9,9]);
VerifyMembuf(buf1, 0, [0,1, 9,9,9, 2,3,4], 'insert mid');
assert(buf1.Size() = 8);
// test ByteAt(), ByteSet()
buf1.Clear();
buf1.AppendBytes([6, 6, 6]);
assert(buf1.ByteSet(0, 0));
assert(buf1.ByteAt(0) = 0);
assert(buf1.ByteSet(1, 1));
assert(buf1.ByteAt(1) = 1);
assert(buf1.ByteSet(2, 2));
assert(buf1.ByteAt(2) = 2);
ExceptionRaised := false;
try
buf1.ByteAt(3);
except
on e: ERangeError do begin
ExceptionRaised := true;
Memo1.Lines.Add('Expected ERangeError OK: ' + e.Message);
end;
end;
assert(ExceptionRaised, 'invalid offset');
assert(not buf1.ByteSet(3, 6), 'invalid offset');
assert(not buf1.ByteSet(-1, 6), 'invalid offset');
VerifyMembuf(buf1, 0, [0, 1, 2], 'ByteAt ByteSet');
assert(buf1.Size() = 3);
// test SearchByte
buf1.Clear();
buf1.AppendBytes([0,1,2,3,0, 1,9]);
assert(buf1.SearchByte(0, 0) = 0, 'search head');
assert(buf1.SearchByte(0, 1) = 1, 'search normal');
assert(buf1.SearchByte(1, 1) = 1, 'search at the offset');
assert(buf1.SearchByte(2, 1) = 5, 'search the second 1');
assert(buf1.SearchByte(0, 9) = 6, 'search tail');
assert(buf1.SearchByte(0, 4) = -1, 'value not exist');
assert(buf1.SearchByte(-1, 0) = -1, 'invalid offset');
VerifyMembuf(buf1, 0, [0,1,2,3,0, 1,9], 'search not change the buf');
assert(buf1.Size() = 7);
// append many bytes
buf1.Clear();
for i:=0 to 10000 do begin
buf1.AppendBytes([i mod 256]);
end;
VerifyMembuf(buf1, 0, [0,1,2,3], 'big loop 0');
VerifyMembuf(buf1, 99, [99,100,101], 'big loop 99');
VerifyMembuf(buf1, 255, [255,0,1,2], 'big loop 255');
VerifyMembuf(buf1, 4096, [0,1,2], 'big loop 496');
assert(buf1.Size() = 10001);
buf1.Free();
end;
end.
|
unit Module.Ports;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Winsock, Winsock2, ComCtrls, CMW.Utils,
CMW.ModuleStruct, CMW.OSInfo, Vcl.Grids, Vcl.ValEdit, Vcl.ExtCtrls;
type
//Общая структура для ListView-элементов
TPortRowType = (ptTCP, ptUDP, ptTCPEx, ptUDPEx);
TCOMMONROW = packed record
dwType: TPortRowType;
dwState: DWORD;
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwRemoteAddr: DWORD;
dwRemotePort: DWORD;
dwProcessID: DWORD;
dwProcessName:string[255];
dwLocalAddrStr:string[255];
dwRemoteAddrStr:string[255];
end;
// структуры для старых функций
PMIB_TCPROW = ^MIB_TCPROW;
MIB_TCPROW = record
dwState: DWORD;
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwRemoteAddr: DWORD;
dwRemotePort: DWORD;
end;
PMIB_TCPTABLE = ^MIB_TCPTABLE;
MIB_TCPTABLE = record
dwNumEntries: DWORD;
table: array [0..0] of MIB_TCPROW;
end;
PMIB_UDPROW = ^MIB_UDPROW;
MIB_UDPROW = record
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
end;
PMIB_UDPTABLE = ^MIB_UDPTABLE;
MIB_UDPTABLE = record
dwNumEntries: DWORD;
table: array[0..0] of MIB_UDPROW;
end;
// структуры для расширенных функций
// TCP ROW
PMIB_TCPEXROW = ^TMIB_TCPEXROW;
TMIB_TCPEXROW = packed record
dwState: DWORD;
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwRemoteAddr: DWORD;
dwRemotePort: DWORD;
dwProcessID: DWORD;
end;
// TCP Table
PMIB_TCPEXTABLE = ^TMIB_TCPEXTABLE;
TMIB_TCPEXTABLE = packed record
dwNumEntries: DWORD;
Table: array[0..0] of TMIB_TCPEXROW;
end;
// UDP ROW
PMIB_UDPEXROW = ^TMIB_UDPEXROW;
TMIB_UDPEXROW = packed record
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwProcessID: DWORD;
end;
// UDP Table
PMIB_UDPEXTABLE = ^TMIB_UDPEXTABLE;
TMIB_UDPEXTABLE = packed record
dwNumEntries: DWORD;
Table: array[0..0] of TMIB_UDPEXROW;
end;
TCP_TABLE_CLASS =
(TCP_TABLE_BASIC_LISTENER,
TCP_TABLE_BASIC_CONNECTIONS,
TCP_TABLE_BASIC_ALL,
TCP_TABLE_OWNER_PID_LISTENER,
TCP_TABLE_OWNER_PID_CONNECTIONS,
TCP_TABLE_OWNER_PID_ALL,
TCP_TABLE_OWNER_MODULE_LISTENER,
TCP_TABLE_OWNER_MODULE_CONNECTIONS,
TCP_TABLE_OWNER_MODULE_ALL);
UDP_TABLE_CLASS =
(UDP_TABLE_BASIC,
UDP_TABLE_OWNER_PID,
UDP_TABLE_OWNER_MODULE);
TFormPorts = class(TForm)
EditDisplayName: TEdit;
Panel1: TPanel;
Bevel1: TBevel;
LabelPermission: TLabel;
ButtonClose: TButton;
ValueListEditor1: TValueListEditor;
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
TPortsUnit = class(TSystemUnit)
private
FDisableIcon:TIcon;
public
FImageList:TImageList;
function FGet:TGlobalState; override;
procedure OnChanged; override;
procedure Initialize; override;
procedure ShowInfo;
procedure Stop; override;
constructor Create; override;
destructor Destroy; override;
property DisableIcon:TIcon read FDisableIcon write FDisableIcon;
end;
const
TCPState: array [0..12] of String = (
'Неизвестно',
'Закрыт. Сокет не используется.',
'Ожидает входящих соединений.',
'Активно пытается установить соединение.',
'Идет начальная синхронизация соединения.',
'Соединение установлено.',
'Сокет закрыт; отключение соединения.',
'Сокет закрыт; ожидание отключения удаленной стороны.',
'Удаленная сторона отключилась; ожидание закрытия сокета.',
'Сокет закрыт, затем удаленная сторона отключилась; ожидание подтверждения.',
'Удаленная сторона отключилась, затем сокет закрыт; ожидание подтверждения.',
'Сокет закрыт, но ожидает пакеты, ещё находящиеся в сети для обработки',
'DELETE TCB');
ConTypeStr:array[0..3] of string = ('UDP', 'TCP', 'UDP', 'TCP');
var
FormPorts: TFormPorts;
HIpHlpApi:THandle = 0;
TargetIP, ResIP:string;
ResID:Byte;
dwSize:DWORD;
// старые функции
GetTcpTable: function (pTcpTable: PMIB_TCPTABLE; var pdwSize: DWORD; bOrder: BOOL): DWORD; stdcall;
{$EXTERNALSYM GetTcpTable}
GetUdpTable: function (pUdpTable: PMIB_UDPTABLE; var pdwSize: DWORD; bOrder: BOOL): DWORD; stdcall;
{$EXTERNALSYM GetUdpTable}
// новые функции
GetExtendedTcpTable: function (pTcpTable: PMIB_TCPEXTABLE; var pdwSize: DWORD;
bOrder: BOOL; ulAf: ULONG; TableClass: TCP_TABLE_CLASS;
Reserved: ULONG): DWORD; stdcall;
{$EXTERNALSYM GetExtendedTcpTable}
GetExtendedUdpTable: function (pTcpTable: PMIB_UDPEXTABLE; var pdwSize: DWORD;
bOrder: BOOL; ulAf: ULONG; TableClass: UDP_TABLE_CLASS;
Reserved: ULONG): DWORD; stdcall;
{$EXTERNALSYM GetExtendedUdpTable}
function GetExConnections(LV:TListView):Boolean;
procedure SelectPortsByPID(LV:TListView; PID:integer);
function SetRIPInfo(LV:TListView):Boolean;
function GetNameFromIP(Const IP:string):string;
procedure GetNameFromIPProc;
function ToCommonRow(PortData:MIB_TCPROW):TCOMMONROW; overload;
function ToCommonRow(PortData:MIB_UDPROW):TCOMMONROW; overload;
function ToCommonRow(PortData:TMIB_TCPEXROW):TCOMMONROW; overload;
function ToCommonRow(PortData:TMIB_UDPEXROW):TCOMMONROW; overload;
implementation
uses Vcl.ImgList, CMW.Main, IniFiles, Module.WinProcesses;
{$R *.dfm}
{
var i:Integer;
Ini:TIniFile;
begin
Result:=False;
if not Assigned(LV) then Exit;
if LV.Items.Count <=0 then Exit;
try
Ini:=TIniFile.Create(CurrentDir+'Data\Ports.inf');
except
begin
Log(['Ошибка открытия файла', CurrentDir+'Data\Ports.inf', GetLastError]);
Exit;
end;
end;
for i:=0 to LV.Items.Count - 1 do
begin
LV.Items[i].SubItems[7]:=Ini.ReadString(LV.Items[i].Caption, LV.Items[i].SubItems[0], '');
LV.Items[i].SubItems[8]:=Ini.ReadString(LV.Items[i].Caption, LV.Items[i].SubItems[5], '');
if Stopping then Exit;
end;
Ini.Free;
Result:=True;
}
procedure ShowData(PD:TCOMMONROW);
var Old:Integer;
Ini:TIniFile;
begin
with FormPorts, PD do
begin
{ IsRegType:Boolean;
DisplayName:string;
Cmd:string;
RegPath:string;
RegName:string;
RegRoot:HKEY;
Exists:Boolean}
try
Ini:=TIniFile.Create(CurrentDir+'Data\Ports.inf');
except
begin
Log(['Ошибка открытия файла', CurrentDir+'Data\Ports.inf', GetLastError]);
Exit;
end;
end;
ValueListEditor1.Strings.Clear;
AddToValueEdit(ValueListEditor1, 'Тип соединения', ConTypeStr[Integer(dwType)], 'Не известно');
AddToValueEdit(ValueListEditor1, 'Локальный адрес', PD.dwLocalAddrStr+':'+IntToStr(PD.dwLocalPort), '');
AddToValueEdit(ValueListEditor1, 'Удалённый адрес', PD.dwLocalAddrStr+':'+IntToStr(PD.dwRemotePort), '');
AddToValueEdit(ValueListEditor1, 'Локальный порт', Ini.ReadString(ConTypeStr[Integer(dwType)], IntToStr(dwLocalPort), ''), '');
AddToValueEdit(ValueListEditor1, 'Удалённый порт', Ini.ReadString(ConTypeStr[Integer(dwType)], IntToStr(dwRemotePort), ''), '');
AddToValueEdit(ValueListEditor1, 'Состояние', TCPState[dwState], 'Не известно');
if ValueListEditor1.Strings.Count * ValueListEditor1.RowHeights[0] + 6 <= 400 then
ValueListEditor1.Height:=ValueListEditor1.Strings.Count * ValueListEditor1.RowHeights[0] + 6
else ValueListEditor1.Height:=400;
Old:=ValueListEditor1.Height;
ClientHeight:=ValueListEditor1.Top + ValueListEditor1.Height + 60;
ValueListEditor1.Height:=Old+10;
LabelPermission.Visible:=False;
EditDisplayName.Text:=IntToStr(PD.dwProcessID)+':'+PD.dwProcessName;
Ini.Free;
ShowModal;
end;
end;
function ToCommonRow(PortData:MIB_TCPROW):TCOMMONROW;
begin
with Result do
begin
dwType:=ptTCP;
dwState:=PortData.dwState;
dwLocalAddr:=PortData.dwLocalAddr;
dwLocalPort:=PortData.dwLocalPort;
dwRemoteAddr:=PortData.dwRemoteAddr;
dwRemotePort:=PortData.dwRemotePort;
dwRemoteAddrStr:=inet_ntoa(TInAddr(dwRemoteAddr));
dwLocalAddrStr:=inet_ntoa(TInAddr(dwLocalAddr));
dwProcessID:=0;
end;
end;
function ToCommonRow(PortData:MIB_UDPROW):TCOMMONROW;
begin
with Result do
begin
dwType:=ptUDP;
dwState:=0;
dwLocalAddr:=PortData.dwLocalAddr;
dwLocalPort:=PortData.dwLocalPort;
dwRemoteAddr:=0;
dwRemotePort:=0;
dwRemoteAddrStr:='';
dwLocalAddrStr:=inet_ntoa(TInAddr(dwLocalAddr));
dwProcessID:=0;
end;
end;
function ToCommonRow(PortData:TMIB_TCPEXROW):TCOMMONROW;
begin
with Result do
begin
dwType:=ptTCPEx;
dwState:=PortData.dwState;
dwLocalAddr:=PortData.dwLocalAddr;
dwLocalPort:=PortData.dwLocalPort;
dwRemoteAddr:=PortData.dwRemoteAddr;
dwRemotePort:=PortData.dwRemotePort;
dwRemoteAddrStr:=inet_ntoa(TInAddr(dwRemoteAddr));
dwLocalAddrStr:=inet_ntoa(TInAddr(dwLocalAddr));
dwProcessID:=PortData.dwProcessID;
end;
end;
function ToCommonRow(PortData:TMIB_UDPEXROW):TCOMMONROW;
begin
with Result do
begin
dwType:=ptUDPEx;
dwState:=0;
dwLocalAddr:=PortData.dwLocalAddr;
dwLocalPort:=PortData.dwLocalPort;
dwRemoteAddr:=0;
dwRemotePort:=0;
dwRemoteAddrStr:='';
dwLocalAddrStr:=inet_ntoa(TInAddr(dwLocalAddr));
dwProcessID:=PortData.dwProcessID;
end;
end;
procedure TPortsUnit.ShowInfo;
begin
if FListView.Selected = nil then Exit;
if FListView.Selected.Data = nil then Exit;
ShowData(TCOMMONROW(FListView.Selected.Data^));
end;
procedure TPortsUnit.Initialize;
begin
//
end;
procedure TPortsUnit.OnChanged;
begin
inherited;
OnListViewSort;
end;
procedure TPortsUnit.Stop;
begin
inherited;
end;
function TPortsUnit.FGet:TGlobalState;
var IconN:TIcon;
begin
Inform(LangText(-1, 'Построение списка активных TCP/UDP портов ...'));
Result:=gsProcess;
ListView.Items.BeginUpdate;
ListView.Items.Clear;
ListView.Groups.Clear;
ListView.GroupView:=FGrouping;
ListView.Groups.Add.Header:='TCP-подключения';
ListView.Groups.Add.Header:='UDP-подключения';
if ListView.SmallImages <> nil then ListView.SmallImages.Clear
else
begin
ListView.SmallImages:=TImageList.CreateSize(16, 16);
ListView.SmallImages.ColorDepth:=cd32Bit;
end;
IconN:=TIcon.Create;
FImageList.GetIcon(0, IconN);
ListView.SmallImages.AddIcon(IconN);
FImageList.GetIcon(1, IconN);
ListView.SmallImages.AddIcon(IconN);
IconN.Free;
if (@GetExtendedTcpTable = nil) and (@GetTcpTable = nil) and
(@GetExtendedUdpTable = nil) and (@GetUdpTable = nil)
then
begin
Log(['API портов операционной системы не может быть использовоно']);
Exit(gsError);
end;
if not GetExConnections(ListView) then Result:=gsError else Result:=gsFinished;
if Result = gsFinished then
Inform(LangText(-1, 'Список активных портов успешно получен.'))
else Inform(LangText(-1, 'Список активных портов не получен.'));
OnChanged;
end;
constructor TPortsUnit.Create;
begin
inherited;
FImageList:=TImageList.CreateSize(16, 16);
FImageList.ColorDepth:=cd32Bit;
end;
destructor TPortsUnit.Destroy;
begin
inherited;
end;
function GetNameFromIP(Const IP:string):string;
var ThreadLogID:Cardinal;
begin
if IP.Length <= 3 then Exit(IP);
TargetIP:=IP;
ResIP:=IP;
ResID:=0;
CreateThread(nil, 0, @GetNameFromIPProc, nil, 0, ThreadLogID);
while ResID <= 0 do Application.ProcessMessages;
Result:=ResIP;
end;
procedure GetNameFromIPProc;
Const
ERR_INADDR = 'Не могу получить IP из in_addr.';
ERR_HOST = 'Не могу получить информацию о хосте:';
ERR_WSA = 'НЕ смог инициализировать WSA.';
WSA_Type = $101; //$202;
var
WSA:Winsock.TWSAData;
Host:Winsock.PHostEnt;
Addr:Integer;
Err:Integer;
IP:string;
Begin
IP:=TargetIP;
ResIP:=IP;
Err:=Winsock.WSAStartup(WSA_Type, WSA);
if Err <> 0 Then
Begin
Log([ERR_WSA, Err, SysErrorMessage(GetLastError)]);
ResID:=1;
Exit;
End;
Addr:=Winsock.inet_addr(PAnsiChar(AnsiString(IP)));
if Addr = Int(INADDR_NONE) Then
Begin
Log([ERR_INADDR, 'Winsock.inet_addr(PAnsiChar(AnsiString(',IP,'))) =', Addr, SysErrorMessage(GetLastError)]);
Winsock.WSACleanup;
ResID:=1;
Exit;
End;
Host:=Winsock.gethostbyaddr(@Addr, SizeOf(Addr), PF_INET);
if Assigned(Host) then ResIP:=Host.h_name+' ('+IP+')'
else Log([ERR_HOST, IP, SysErrorMessage(GetLastError)]);
Winsock.WSACleanup;
ResID:=2;
End;
function SetRIPInfo(LV:TListView):Boolean;
var i:Integer;
begin
Result:=False;
if not Assigned(LV) then Exit;
if LV.Items.Count <=0 then Exit;
for i:=0 to LV.Items.Count - 1 do
begin
LV.Items[i].SubItems[1]:=GetNameFromIP(TCOMMonROW(LV.Items[i].Data^).dwLocalAddrStr)+':'+IntToStr(TCOMMonROW(LV.Items[i].Data^).dwLocalPort);
LV.Items[i].SubItems[2]:=GetNameFromIP(TCOMMonROW(LV.Items[i].Data^).dwRemoteAddrStr)+':'+IntToStr(TCOMMonROW(LV.Items[i].Data^).dwRemotePort);
if Stopping then Exit;
end;
Result:=True;
end;
procedure SelectPortsByPID(LV:TListView; PID:integer);
var i:Integer;
begin
if LV.Items.Count <= 0 then Exit;
for i:= 0 to LV.Items.Count - 1 do
begin
LV.Items[i].Selected:=LV.Items[i].SubItems[1] = IntToStr(PID);
end;
if LV.Selected <> nil then LV.Selected.MakeVisible(True);
end;
function GetExConnections(LV:TListView):Boolean;
var TCPExTable:PMIB_TCPEXTABLE;
UDPExTable:PMIB_UDPEXTABLE;
TCPTable:PMIB_TCPTABLE;
UDPTable:PMIB_UDPTABLE;
i:Integer;
local_name:array[0..255] of Char;
Er:DWORD;
FullName:string;
II:Word;
p:Cardinal;
siPID:Integer;
siLoc:Integer;
siRem:Integer;
siSta:Integer;
Step:Boolean;
begin
Result:=False;
Step:=False;
try
try
//Расширенная информация о TCP-подключениях
if @GetExtendedTcpTable <> nil then
begin
TCPExTable:=nil;
dwSize:=0;
Er:=GetExtendedTcpTable(TCPExTable, dwSize, False, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
IntToStr(Er);
if (Er <> ERROR_INSUFFICIENT_BUFFER) or (dwSize = 0) then
begin
ShowMessage(IntToStr(Er)+ ' (Er <> ERROR_INSUFFICIENT_BUFFER) or (dwSize = 0)');
Log(['TCPEx', SysErrorMessage(Er), '(Er <> ERROR_INSUFFICIENT_BUFFER) or (dwSize = 0)', Er <> ERROR_INSUFFICIENT_BUFFER, dwSize = 0]);
Step:=False;
end
else
begin
//TCPExTable:=GetMemory(dwSize);
//ZeroMemory(TCPExTable, dwSize);
New(TCPExTable);
ReallocMem(TCPExTable, dwSize);
Er:=GetExtendedTcpTable(TCPExTable, dwSize, False, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
if Er = NO_ERROR then
begin
for i:=0 to TCPExTable^.dwNumEntries - 1 do
begin
with LV.Items.Add do
begin
Data:=AllocMem(SizeOf(TCOMMONROW));
TCOMMONROW(Data^):=ToCommonRow(TCPExTable^.Table[i]);
siPID:=SubItems.Add('');
siLoc:=SubItems.Add('');
siRem:=SubItems.Add('');
siSta:=SubItems.Add('');
p:=TCPExTable^.Table[i].dwProcessId;
SubItems[siPID]:=IntToStr(p);
FullName:=GetProcessName(p);
NormFileName(FullName);
try
if FileExists(FullName) then
begin
if GetFileIcon(FullName, is16, TListView(ListView).SmallImages, II) > 0 then ImageIndex:=II
end
else ImageIndex:=0;
except
Log(['Не смог загрузить иконку из файла:', FullName, GetLastError]);
end;
Caption:=ExtractFileName(FullName);
TCOMMONROW(Data^).dwProcessName:=Caption;
SubItems[siLoc]:=inet_ntoa(TInAddr(TCPExTable^.Table[I].dwLocalAddr ))+':'+IntToStr(ntohs(TCPExTable^.Table[I].dwLocalPort ));
if TCPExTable^.Table[I].dwState <> 2 then
SubItems[siRem]:=inet_ntoa(TInAddr(TCPExTable^.Table[I].dwRemoteAddr))+':'+IntToStr(ntohs(TCPExTable^.Table[I].dwRemotePort));
SubItems[siSta]:=TCPState[TCPExTable^.Table[I].dwState];
GroupID:=0;
end;
end;
Step:=True;
end
else
begin
Log(['Не смог получить более подробную информацию о TCP-подключениях.', SysErrorMessage(Er)]);
Step:=False;
end;
end;
end
else Step:=False;
//Если не смог получить подробную инфу о подключениях, пробуем общую получить
if not Step then
begin
if @GetTcpTable <> nil then
begin
dwSize:=0;
Er:=GetTcpTable(nil, &dwSize, True);
if (Er <> ERROR_INSUFFICIENT_BUFFER) then Step:=False
else
begin
New(TCPTable);
ReallocMem(TCPTable, dwSize);
Er:=GetTcpTable(TCPTable, &dwSize, True);
if Er = NO_ERROR then
begin
for i:= 0 to TCPTable.dwNumEntries - 1 do
begin
with LV.Items.Add do
begin
ImageIndex:=0;
Data:=AllocMem(SizeOf(TCOMMONROW));
TCOMMONROW(Data^):=ToCommonRow(TCPTable^.Table[i]);
siPID:=SubItems.Add('');
siLoc:=SubItems.Add('');
siRem:=SubItems.Add('');
siSta:=SubItems.Add('');
Caption:='<Нет данных>';
TCOMMONROW(Data^).dwProcessName:=Caption;
SubItems[siLoc]:=inet_ntoa(TInAddr(TCPTable^.Table[I].dwLocalAddr ))+':'+IntToStr(ntohs(TCPTable^.Table[I].dwLocalPort ));
if TCPTable^.Table[I].dwState <> 2 then
SubItems[siRem]:=inet_ntoa(TInAddr(TCPTable^.Table[I].dwRemoteAddr))+':'+IntToStr(ntohs(TCPTable^.Table[I].dwRemotePort));
SubItems[siSta]:=TCPState[TCPTable^.Table[I].dwState];
GroupID:=0;
end;
end;
Step:=True;
end
else Step:=False;
end;
end
else Step:=False;
end;
if not Step then Log(['Не смог получить любую информацию о TCP-подключениях']);
//UDP
if @GetExtendedUdpTable <> nil then
begin
Step:=False;
UDPExTable:=nil;
dwSize:=0;
Er:=GetExtendedUdpTable(nil, dwSize, False, AF_INET, UDP_TABLE_OWNER_PID, 0);
if (Er <> ERROR_INSUFFICIENT_BUFFER) or (dwSize = 0) then
begin
Log(['UDPEx', SysErrorMessage(Er), '(Er <> ERROR_INSUFFICIENT_BUFFER) or (dwSize = 0)', Er <> ERROR_INSUFFICIENT_BUFFER, dwSize = 0]);
Step:=False;
end
else
begin
//UdpExTable:=GetMemory(dwSize);
//ZeroMemory(UdpExTable, dwSize);
New(UdpExTable);
ReallocMem(UdpExTable, dwSize);
Er:=GetExtendedUdpTable(UdpExTable, dwSize, False, AF_INET, UDP_TABLE_OWNER_PID, 0);
if Er = NO_ERROR then
begin
for i:= 0 to UDPExTable^.dwNumEntries - 1 do
begin
with LV.Items.Add do
begin
Data:=AllocMem(SizeOf(TCOMMONROW));
TCOMMONROW(Data^):=ToCommonRow(UDPExTable^.Table[i]);
siPID:=SubItems.Add('');
siLoc:=SubItems.Add('');
siRem:=SubItems.Add('');
siSta:=SubItems.Add('');
p:=UDPExTable^.Table[i].dwProcessId;
SubItems[siPID]:=IntToStr(p);
FullName:=GetProcessName(p);
NormFileName(FullName);
try
if FileExists(FullName) then
begin
if GetFileIcon(FullName, is16, TListView(ListView).SmallImages, II) > 0 then ImageIndex:=II
end
else ImageIndex:=0;
except
Log(['Не смог загрузить иконку из файла:', FullName, GetLastError]);
end;
Caption:=ExtractFileName(FullName);
TCOMMONROW(Data^).dwProcessName:=Caption;
SubItems[siLoc]:=inet_ntoa(TInAddr(UDPExTable^.Table[I].dwLocalAddr))+':'+IntToStr(ntohs(UDPExTable^.Table[I].dwLocalPort));
SubItems[siRem]:='';
//gethostname(PAnsiChar(AnsiString(StrPas(local_name))), 255);
GroupID:=1;
end;
end;
Step:=True;
end
else Step:=False;
end;
end
else Step:=False;
if not Step then
begin
if @GetUdpTable <> nil then
begin
dwSize:=0;
Er:=GetUDPTable(nil, &dwSize, True);
if (Er <> ERROR_INSUFFICIENT_BUFFER) then Step:=False
else
begin
New(UDPTable);
ReallocMem(UDPTable, dwSize);
Er:=GetUdpTable(UDPTable, &dwSize, True);
if Er = NO_ERROR then
begin
for i:= 0 to UDPTable.dwNumEntries - 1 do
begin
with LV.Items.Add do
begin
ImageIndex:=1;
Data:=AllocMem(SizeOf(TCOMMONROW));
TCOMMONROW(Data^):=ToCommonRow(UDPTable^.Table[i]);
siPID:=SubItems.Add('');
siLoc:=SubItems.Add('');
siRem:=SubItems.Add('');
siSta:=SubItems.Add('');
Caption:='<Нет данных>';
TCOMMONROW(Data^).dwProcessName:=Caption;
SubItems[siLoc]:=inet_ntoa(TInAddr(UDPTable^.Table[I].dwLocalAddr ))+':'+IntToStr(ntohs(UDPTable^.Table[I].dwLocalPort ));
GroupID:=1;
end;
end;
Step:=True;
end
else Step:=False;
end;
end
else Step:=False;
end;
if not Step then Log(['Не смог получить любую информацию о TCP-подключениях']);
Result:=True;
except
begin
Result:=False;
Log(['Ошибка при получении информации о TCP/UDP-подключениях', SysErrorMessage(GetLastError)]);
end;
end;
finally
FreeMemory(TCPExTable);
FreeMemory(UDPExTable);
end;
end;
function LoadAPIHelpAPI:Boolean;
begin
Result:=False;
if HIphlpapi = 0 then HIpHlpApi:=LoadLibrary('iphlpapi.dll');
if HIpHlpApi > HINSTANCE_ERROR then
begin
try
@GetTcpTable:=GetProcAddress(HIpHlpApi, 'GetTcpTable');
@GetUdpTable:=GetProcAddress(HIpHlpApi, 'GetUdpTable');
except
begin
@GetTcpTable:=nil;
@GetUdpTable:=nil;
end;
end;
try
@GetExtendedTcpTable:=GetProcAddress(HIpHlpApi, 'GetExtendedTcpTable');
@GetExtendedUdpTable:=GetProcAddress(HIpHlpApi, 'GetExtendedUdpTable');
except
begin
@GetExtendedTcpTable:=nil;
@GetExtendedUdpTable:=nil;
end;
end;
Result:=True;
end;
end;
procedure FreeAPIHelpAPI;
begin
if HIpHlpApi <> 0 then FreeLibrary(HIpHlpApi);
HIpHlpApi:=0;
end;
procedure TFormPorts.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_ESCAPE: Close;
end;
end;
initialization
LoadAPIHelpAPI;
finalization
FreeAPIHelpAPI;
end.
|
unit uListagemObras;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
cxGridCustomView, cxGrid, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask,
AdvSmoothEdit, AdvSmoothEditButton, AdvSmoothDatePicker, uCadastroObras,
uDmDados, uModelObra, uObrasService, uModelPessoa, uPessoaService;
type
TfrmListagemObras = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
cxGridListagemObras: TcxGrid;
cxGridListagemObrasDBTableView1: TcxGridDBTableView;
cxGridListagemObrasLevel1: TcxGridLevel;
Label7: TLabel;
btnNovo: TSpeedButton;
btnEditar: TSpeedButton;
btnLimparFiltros: TSpeedButton;
btnPesquisar: TSpeedButton;
Label11: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
Label20: TLabel;
Label21: TLabel;
Label22: TLabel;
Label23: TLabel;
Label24: TLabel;
Label25: TLabel;
Label26: TLabel;
Label27: TLabel;
Label42: TLabel;
edtListCodCliente: TEdit;
edtListCEPObra: TEdit;
edtListClienteObra: TEdit;
edtListCodObra: TEdit;
edtListLogradouroObra: TEdit;
btnPesquisarCliente: TBitBtn;
dtInicialCriacaoObra: TAdvSmoothDatePicker;
dtFinalCriacaoObra: TAdvSmoothDatePicker;
edtListBairroObra: TEdit;
dtInicialPrevisaoObra: TAdvSmoothDatePicker;
dtFIMPrevisaoObra: TAdvSmoothDatePicker;
edtListArtObra: TEdit;
edtListAlvaraObra: TEdit;
edtListMunicObra: TEdit;
cbStatusObras: TComboBox;
cxGridListagemObrasDBTableView1Codigo: TcxGridDBColumn;
cxGridListagemObrasDBTableView1DataCriacao: TcxGridDBColumn;
cxGridListagemObrasDBTableView1CodCliente: TcxGridDBColumn;
cxGridListagemObrasDBTableView1DataPrevisao: TcxGridDBColumn;
cxGridListagemObrasDBTableView1CEP: TcxGridDBColumn;
cxGridListagemObrasDBTableView1Logradouro: TcxGridDBColumn;
cxGridListagemObrasDBTableView1Quadra: TcxGridDBColumn;
cxGridListagemObrasDBTableView1Lote: TcxGridDBColumn;
cxGridListagemObrasDBTableView1Bairro: TcxGridDBColumn;
cxGridListagemObrasDBTableView1Cidade: TcxGridDBColumn;
cxGridListagemObrasDBTableView1UF: TcxGridDBColumn;
cxGridListagemObrasDBTableView1StatusObra: TcxGridDBColumn;
cxGridListagemObrasDBTableView1NumeroART: TcxGridDBColumn;
cxGridListagemObrasDBTableView1Alvara: TcxGridDBColumn;
cxGridListagemObrasDBTableView1Inscricaomunicipal: TcxGridDBColumn;
cxGridListagemObrasDBTableView1UsoDeSolo: TcxGridDBColumn;
cxGridListagemObrasDBTableView1Cliente: TcxGridDBColumn;
cxGridListagemObrasDBTableView1ValorTotal: TcxGridDBColumn;
procedure btnNovoClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure PesquisaObras;
function ConsultaContatoCodigo(pCodigo : String): String;
end;
var
frmListagemObras: TfrmListagemObras;
implementation
{$R *.dfm}
function TfrmListagemObras.ConsultaContatoCodigo(pCodigo: String): String;
var
pContato : TPessoa;
pServiceContato : TPessoaService;
begin
pContato := TPessoa.Create;
try
pContato.Codigo := StrToFloat(pCodigo);
pServiceContato := TPessoaService.Create(pContato);
for pContato in pServiceContato.Consultar(pContato) do
begin
Result := pContato.NomeFantasia;
end;
finally
FreeAndNil(pContato);
FreeAndNil(pServiceContato);
end;
end;
procedure TfrmListagemObras.PesquisaObras;
var
pObra , Obra : TObra;
pServiceObra : TObrasService;
begin
pObra := TObra.Create;
Obra := TObra.Create;
pServiceObra := TObrasService.Create(pObra);
try
dmDados.CdsObra.DisableControls;
dmDados.CdsObra.EmptyDataSet;
pObra.Codigo := StrToFloatDef(edtListCodObra.Text, 0);
pObra.CodCliente := StrToFloatDef(edtListCodCliente.Text,0);
pObra.CEP := edtListCEPObra.Text;
pObra.Logradouro := edtListLogradouroObra.Text;
pObra.Bairro := edtListBairroObra.Text;
pObra.NumeroART := edtListArtObra.Text;
pObra.InscricaoMunicipal := edtListMunicObra.Text;
pObra.Alvara := edtListAlvaraObra.Text;
if cbStatusObras.ItemIndex = 0 then
pObra.StatusObra := soTodos;
if cbStatusObras.ItemIndex = 1 then
pObra.StatusObra := soAguardandoPlanejamento;
if cbStatusObras.ItemIndex = 2 then
pObra.StatusObra := soEmAndamento;
if cbStatusObras.ItemIndex = 3 then
pObra.StatusObra := soFinalizado;
for Obra in pServiceObra.ConsultarTodos(pObra) do
begin
dmDados.CdsObra.Append;
dmDados.CdsObraCODIGO.AsFloat := Obra.Codigo;
dmDados.CdsObraDATACRIACAO.AsDateTime := Obra.DataCriacao;
dmDados.CdsObraCODCLIENTE.AsFloat := Obra.CodCliente;
dmDados.CdsObraCLIENTE.AsString := ConsultaContatoCodigo(FloatToStr(Obra.CodCliente));
dmDados.CdsObraDATAPREVISAO.AsDateTime := Obra.DataPrevisao;
dmDados.CdsObraCEP.AsString := Obra.CEP;
dmDados.CdsObraLOGRADOURO.AsString := Obra.Logradouro;
dmDados.CdsObraQUADRA.AsString := Obra.Quadra;
dmDados.CdsObraLOTE.AsString := Obra.Lote;
dmDados.CdsObraBAIRRO.AsString := Obra.Bairro;
dmDados.CdsObraCIDADE.AsString := Obra.Cidade;
dmDados.CdsObraUF.AsString := Obra.UF;
dmDados.CdsObraNUMEROART.AsString := Obra.NumeroART;
dmDados.CdsObraALVARA.AsString := Obra.Alvara;
dmDados.CdsObraINSCRICAOMUNICIPAL.AsString := Obra.InscricaoMunicipal;
DmDados.CdsObra.post;
end;
DmDados.CdsObra.EnableControls;
finally
FreeAndNil(Obra);
FreeAndNil(pObra);
FreeAndNil(pServiceObra);
cxGridListagemObras.Focused;
//lblQtdlistadaObras.Caption := IntToStr(dmDados.CdsObra.RecordCount);
end;
end;
procedure TfrmListagemObras.btnNovoClick(Sender: TObject);
var
frmCadastroObras : TfrmCadastroObras;
begin
frmCadastroObras := TfrmCadastroObras.Create(nil);
try
frmCadastroObras.AcaoCadastro := acIncluir;
frmCadastroObras.ShowModal;
finally
FreeAndNil(frmCadastroObras);
end;
end;
procedure TfrmListagemObras.btnPesquisarClick(Sender: TObject);
begin
PesquisaObras;
end;
end.
|
unit core_terrain_generator;
{$mode objfpc}{$H+}
//This is required with Lazarus on x86:
interface
uses
Classes, SysUtils,graphics,core_types,core_chunk,TypInfo,inifiles,
core_utils,VectorTypes,VectorGeometry,core_classes,perlinnoise,
core_noise, core_camera, core_atmosphere//,core_main
{$IFNDEF SERVER},core_lights,core_block_brush{$ENDIF};
//const aoStep = 0.05;
type
//8 block neighbours
eSasiedzi = (sN,sNE,sE,sSE,sS,sSW,sW,sNW);
TSasiedzi = set of eSasiedzi;
pSasiedzi = ^TSasiedzi;
eFaces = (fTop,fBottom,fLeft,fRight,fFront,fBack);
//used to inform core about new map size in MIDDLE of loading it
TMapSetSizeCallback = procedure (chunkW,chunkH,mapW,mapH:integer) of object;
{ TTerrainGenerator }
TTerrainGenerator = class (TUpdateable)
bmpBuffer : tbitmap;
lastOscColour:tvector3f;//last colour value from oscilator
//used by chunk culling in round robin
lastCulledChunk:integer;
oscUp:boolean;//does oscilator tint rise or fall?
//set to last chunk passed to cullBlocksInChunk. used by perlin color oscilator
currentChunkOff:tvector2i;
private
cullChunksQueue: array of array of boolean;
fileHeaderSize:integer; //size of header info, after this world data starts
vboDumpCount:cardinal;
//ambient occlusion values
procedure aoPass(chunk: pChunk);
public
//will be stored in header. probably
maxPlayers:byte;
description:string;
mapFileName:string;
mapSizeCallback:TMapSetSizeCallback;
//map size in blocks
mapSize:TAffinevector;
constructor create;
destructor destroy; override;
procedure setMapSize;
procedure perlin(w,h:integer);
procedure loadFromImage(FileName:string);
procedure freeBufferBmp;
//compresses & saves given sector of active_chunk_w*h size to a matching file
procedure saveSector;
procedure loadBlockColors(fiile: string);
procedure saveBlockColors(fiile: string);
procedure CpyFromBmpBufferToChunkBuffer(blocks: PBlocksBuffer;chunkX,chunkZ:integer);
//generates optimized mesh by merging neigbourhing cube sides
procedure cullBlocksInChunk(chunks:PChunksArray;chunkX,chunkY:integer;executeNow:boolean=false);
procedure cullAllChunks;
//calculates light strength at given face
function calculateAO(xx, yy, zz: integer; dir: eFaces): single;
//set block and cull chunk. takes coordinates starting at 0,0 center
procedure setBlockAndCull(pos:TAffineVector;blokType:eBlockTypes);
//set blok in world coordinates either starting at world 0,0 or at array 0,0
procedure setBlockInWorld(x, y, z: integer; blok: eBlockTypes; centered,
cull: boolean);
function getBlockInWorld(x, y, z: integer;centered:boolean):pBlockType;
procedure saveMap(filename:string);
procedure loadMap(filename:string);
//fills map with a big cross
procedure initMap(empty: boolean);
procedure generateMap(flatness: single; cutoff: integer; xyScale: single;
hangover: single; mineral1, mineral2, mineralBottom,
mineralBottom2: eBlockTypes);
//color tint acros terrain can change back and forth
procedure colorOscilator(var r,g,b:single);
//color variation based on pre generated perlin map
function perlinOscilator(const x,y,z:single):single;
{$IFNDEF SERVER}
//saves whole map as brush file
procedure saveMapAsBrush(const filename:string);
{$ENDIF}
//global iterator service
procedure ForEachBlockInChunk(chunk: pChunk; const operation: TBlockMutator;
cullAfter: boolean);
procedure ForEachBlockInWorld(const operation: TBlockMutator;
optimize: boolean; cullAfter: boolean);
//convert form 'minus' coordinates to array
function fromWorldToArray(pos:TAffineVector):TVector3i;
//match block mutator signature
procedure MutatorBlockAssignValue(block: PBlockType);
procedure MutatorZeroBlocks(block: PBlockType);
//processes queued tasks like chunks culling
procedure Update;override;
//saves effect of chunk last culling to file
procedure saveVboBuffToFile(const filename: string);
end;
//set block at absolute position
procedure setBlockAt(pos:TAffineVector;blok:eblocktypes);inline;
procedure setBlockAt(pos:TVector3i;blok:eblocktypes;cullChunk:boolean);inline;
procedure setBlockAtFast(x,y,z:integer;blok:eblocktypes;cullChunk:boolean);inline;
var terrain:TTerrainGenerator;
//color change across x-z plane
colorScilatorTint:single = 0.0001;
//how fast color changes:
colorScilatorStep:single = 0.000002;
//color lighten with height. block.color+=block.y / heightTint
heightTint:single = 500;
implementation
procedure setBlockAtFast(x, y, z: integer; blok: eblocktypes; cullChunk: boolean);
var xx,yy:integer;
begin
xx:=x div chunk_width;
yy:=y div chunk_width;
chunksPointer^[xx,yy].blocks[x mod chunk_width,y,z mod chunk_width]:=byte(blok);
//chunksPointer^[xx,yy].blocks[x mod chunk_width,y,z mod chunk_width]:=byte(blok);
if cullChunk then terrain.cullBlocksInChunk(chunksPointer,xx,yy,false);
end;
procedure setBlockAt(pos: TAffineVector; blok: eblocktypes);
var
ch:TVector2i;
blokpos:TVector3b;
begin
//chances are this is fucked up
blokpos:=absolutePositionToChunkBlok(ch,pos);
if (ch[0]<active_chunks_w) and (ch[1]<active_chunks_h) and (blokpos[1]<chunk_height)
then begin
chunksPointer^[ch[0],ch[1]].blocks[blokPos[0],blokPos[1],blokPos[2]]:=byte(blok);
terrain.cullBlocksInChunk(chunksPointer,ch[0],ch[1],false);
// chunksPointer^[ch[0],ch[1]].blocks[blokPos[0],blokPos[1],blokPos[2]].
end
else
log('setBlockAt:: out of bounds');
end;
procedure setBlockAt(pos: TVector3i; blok: eblocktypes;cullChunk:boolean);
var x,y:integer;
begin
//chances are this is fucked up
if pos[1]<0 then pos[1]:=chunk_height+pos[1];
x:=pos[0] div chunk_width;
y:=pos[2] div chunk_width;
chunksPointer^[x,y].blocks[pos[0] mod chunk_width,pos[1],pos[2] mod chunk_width]:=byte(blok);
if cullChunk then terrain.cullBlocksInChunk(chunksPointer,x,y,false);
end;
var fileBuf:array of TBlockType;
bufPosition:cardinal;//current position in chunksBuffer
topFaces,frontFaces,backFaces : array of eBlockTypes;
//<<Noise Routines
procedure TTerrainGenerator.saveMap(filename:string);
var
x,y,z,w,h:integer;
fileStream:TFilestream;
begin
try
if filename='' then begin
log('achtung! saveMap::no file specified');
exit;
end;
//compressed map?
if ExtractFileExt(filename)='.lemap' then begin
exit;
end;
if atmosphere<>nil then atmosphere.pause;
fileStream:=tfilestream.Create(filename,fmOpenWrite or fmCreate);
mapFileName:=filename;
filestream.Seek(0,soFromBeginning);
//map dimensions
fileStream.Write(active_chunks_w,sizeof(active_chunks_w));
fileStream.Write(active_chunks_h,sizeof(active_chunks_h));
//chunk dimensions
fileStream.Write(chunk_width,sizeof(chunk_width));
fileStream.Write(chunk_height,sizeof(chunk_height));
//save chunks data
if length(filebuf)<>chunk_height then
setlength(filebuf,chunk_height);
for w:=0 to active_chunks_h-1 do
for h:=0 to active_chunks_w-1 do
for z:=0 to chunk_width-1 do
for x:=0 to chunk_width-1 do begin
for y:=0 to chunk_height-1 do begin
filebuf[y]:= chunksPointer^[w,h].pblocks[x,y,z]^;
//filebuf[y]:=core.chunks[w,h].blocks[x,y,z];
end;
filestream.WriteBuffer(filebuf[0],length(filebuf));
end;
filestream.free;
{$IFNDEF SERVER}
//save lights. should be moved to renderer to remove dependency
{
filename:=ChangeFileExt(filename,'.lights');
fileStream:=tfilestream.Create(filename,fmOpenWrite or fmCreate);
//directional
fileStream.Write(renderer.dirLight.color,sizeof(renderer.dirLight.color));
fileStream.Write(renderer.dirLight.direction,sizeof(renderer.dirLight.direction));
fileStream.Write(renderer.dirLight.ambientIntensity,sizeof(renderer.dirLight.ambientIntensity));
fileStream.Write(renderer.dirLight.diffuseIntensity ,sizeof(renderer.dirLight.diffuseIntensity));
//point lights
fileStream.Write(renderer.getLevelLightsCount,sizeof(integer));
for i:=0 to renderer.pointLightsDS.Count-1 do if renderer.pointLightsDS[i].staticLight then
with renderer.pointLightsDS[i] do begin
fileStream.Write(color,sizeof(color));
fileStream.Write(position,sizeof(position));
fileStream.Write(ambientIntensity,sizeof(ambientIntensity));
fileStream.Write(diffuseIntensity,sizeof(diffuseIntensity));
fileStream.Write(attenuation,sizeof(attenuation));
end;
filestream.Free;}
{$ELSE}
log('achtung! map lights are not saved with map data in server mode');
{$ENDIF}
//save palette
filename:=ChangeFileExt(filename,'.palette');
saveBlockColors(filename);
finally
if atmosphere<>nil then atmosphere.resume;
end;
end;
procedure TTerrainGenerator.loadMap(filename:string);
var
x,y,z,w,h:integer;
c:longint;
fileStream:TFilestream;
position,color:TAffineVector;
ambientIntensity,diffuseIntensity:single;
{$IFNDEF SERVER}
attenuation:rAttenuation;
l:tpointlight;
{$ENDIF}
begin
try
//compressed map?
if ExtractFileExt(filename)='.lemap' then begin
exit;
end;
//om.addOrder(orMapLoad,0,0);
if atmosphere<>nil then atmosphere.pause;
fileStream:=tfilestream.Create(filename,fmOpenRead);
mapFileName:=filename;
filestream.Seek(0,soFromBeginning);
//map dimensions
fileStream.Read(w,sizeof(w));
fileStream.Read(h,sizeof(h));
//chunk dimensions
fileStream.Read(x,sizeof(x));
fileStream.Read(y,sizeof(y));
setVector(mapSize,w*x,h*x,y);
//core.setMapSize(x,y,w,h);
mapSizeCallback(x,y,w,h);
setmapsize;
if atmosphere<>nil then atmosphere.resize(w*x,y,h*x);
//fill them with something more usefull;
if length(filebuf)<>chunk_height then
setlength(filebuf,chunk_height);
for w:=0 to active_chunks_h-1 do
for h:=0 to active_chunks_w-1 do
for z:=0 to chunk_width-1 do
for x:=0 to chunk_width-1 do begin
filestream.ReadBuffer(filebuf[0],length(filebuf));
//copy(core.chunks[w,h].pblocks[x,0,z]^ ,0,chunk_height);
for y:=0 to chunk_height-1 do begin
//core.chunks[w,h].blocks[x,y,z]:=filebuf[y];
chunksPointer^[w,h].pBlocks[x,y,z]^:=filebuf[y];
end;
end;
for x:=0 to active_chunks_h-1 do
for y:=0 to active_chunks_w-1 do
cullBlocksInChunk(chunksPointer,y,x);
filestream.free;
{$IFNDEF SERVER}
//load ligths-- should be moved to renderer
{
renderer.removeLights;
filename:=ChangeFileExt(filename,'.lights');
fileStream:=tfilestream.Create(filename,fmOpenReadWrite);
//load dir light
fileStream.Read(renderer.dirLight.color,sizeof(renderer.dirLight.color));
fileStream.Read(renderer.dirLight.direction,sizeof(renderer.dirLight.direction));
fileStream.read(renderer.dirLight.ambientIntensity,sizeof(renderer.dirLight.ambientIntensity));
fileStream.read(renderer.dirLight.diffuseIntensity ,sizeof(renderer.dirLight.diffuseIntensity));
//read number of pointlights
fileStream.read(y,sizeof(y));
//load point lights
for x:=0 to y-1 do begin
fileStream.Read(color,sizeof(color));
fileStream.Read(position,sizeof(position));
fileStream.Read(ambientIntensity,sizeof(ambientIntensity));
fileStream.Read(diffuseIntensity,sizeof(diffuseIntensity));
fileStream.Read(attenuation,sizeof(attenuation));
l:=tpointlight.create(color,position,diffuseIntensity,attenuation.constant,
attenuation.linear,attenuation.exp);
renderer.addPointLight(l);
end;
filestream.Free;}
{$ELSE}
log('achtung! map lights are not loaded in server mode');
{$ENDIF}
//load palette
filename:=ChangeFileExt(filename,'.palette');
loadBlockColors(filename);
finally
showLoadingScreen:=false;
if atmosphere<>nil then atmosphere.resume;
end;
end;
procedure TTerrainGenerator.initMap(empty:boolean);
var
chx,chy,x,y,z,i,j,xx,yy,zz:integer;
pBlok:pBlockType;
begin
if atmosphere<>nil then atmosphere.pause;
setMapSize;
if atmosphere<>nil then atmosphere.resize(world_width,chunk_height,world_depth);
ForEachBlockInWorld(@MutatorZeroBlocks,true,false);
y:=chunk_height div 4;
for z:=0 to world_depth-1 do begin
for x:=0 to world_width-1 do begin
chx:=x div chunk_width;
chy:=z div chunk_width;
xx:=x mod chunk_width;
yy:=y;
zz:=z mod chunk_width;
pBlok:=chunksPointer^[chx,chy].pblocks[xx,yy,zz];
pBlok^:=byte(btStone);
if (x=z) or (z=world_width-x) then pBlok^:=byte(btRedRock);
if empty then if (x<-1+world_width2) or (x>1+world_width2)
or (z<-1+world_width2) or (z>1+world_width2) then pBlok^:=byte(btNone);
end;
end;
for z:=0 to active_chunks_h-1 do
for x:=0 to active_chunks_w-1 do
cullBlocksInChunk(chunksPointer,x,z);
// loadBlockColors(appPath+'terrain\blockColorDefs.palette');
camera.setTarget(0,chunk_height2 div 2,0);
camera.setOrigin(0,chunk_height,80);
if atmosphere<>nil then atmosphere.resume;
end;
procedure TTerrainGenerator.generateMap(flatness: single; cutoff: integer;
xyScale:single;hangover:single;mineral1,mineral2,mineralBottom,mineralBottom2:eBlockTypes);
var
chx,chy,x,y,z,xx,yy,zz:integer;
//big masses. from bottom up
scale,noise,noise2:single;
t1,t2:single;
pBlok:pBlockType;
begin
try
if atmosphere<>nil then atmosphere.pause;
t1:=1.1;
for y:=0 to chunk_height-1 do begin
// log(floattostr(t1)+' < '+floattostr(noise));
for z:=0 to world_depth-1 do begin
for x:=0 to world_width-1 do begin
chx:=x div chunk_width;
chy:=z div chunk_width;
xx:=x mod chunk_width;
yy:=y;
zz:=z mod chunk_width;
pBlok:=chunksPointer^[chx,chy].pblocks[xx,yy,zz];
//zero the block. will get filled in next step and then will be used in boolean cut
pBlok^:=byte(btNone);
scale:=10;
//underground
if
// (chy<active_chunks_h-1) and
(y<chunk_height2) then begin
// (btIron,mineralBottom,btQuartzite,mineral1)
//bottomest layer
t1:=(y/cutoff*0.234);
noise:=simplex_Noise(1,x/scale,y/scale*2,z/scale);
//simplex_Noise(1,x/scale,y/scale*1.5,z/scale);
if (t1>noise) then chunksPointer^[chx,chy].setBlock(xx,yy,zz,mineralBottom)
else chunksPointer^[chx,chy].setBlock(xx,yy,zz,mineralBottom2);//bottom
t2:=(y/cutoff*0.39);
noise:=simplex_Noise(1,x/scale,y/scale*2,z/scale);
if (t2>noise) then pBlok^:=byte(mineralBottom2);
t2:=(y/(cutoff*0.625));
noise:=simplex_Noise(1,x/(2*scale),y/(4*scale),z/(2*scale));
if (t2>noise) then pBlok^:=byte(mineral1);
end;
//near surface
if
//(chy<active_chunks_h-1) and
(y>cutoff*0.75) then begin
t2:=(y/cutoff);
noise:=simplex_Noise(1,x/(1.5*scale),y/(4*scale),z/(1.5*scale));
// if (t2<noise) then if pblok^=btNone then pBlok^:=btRedSlab;
if (t2>noise) then pBlok^:=byte(mineral2) else pBlok^:=byte(mineral1);
end;
end;
end;
end;
//add some perlin mountains. this time iterating up each column
for z:=0 to world_depth-1 do begin
//log(floattostr(noise));
for x:=0 to world_width-1 do
for y:=0 to chunk_height-1 do begin
chx:=x div chunk_width;
chy:=z div chunk_width;
xx:=x mod chunk_width;
yy:=y;
zz:=z mod chunk_width;
pBlok:=chunksPointer^[chx,chy].pblocks[xx,yy,zz];
noise:=-perlin3DNoise.noise(x/512*4*xyScale,z/512*4*xyScale)*flatness+cutoff;
noise2:=-perlin3DNoise.noise(x/256*4*xyScale,y/256*6*xyScale,z/256*4*xyScale)*hangover*5;
if y>noise+noise2 then pBlok^:=byte(btNone);// else pBlok^:=mineral1;
//add poziome distortion to surface
if y>cutoff then begin
//noise:=-perlin3DNoise.noise(x/512*4*xyScale,y/512*4*xyScale,z/512*4*xyScale)*hangover+cutoff;
//if y>noise then pBlok^:=btNone;
end;
end;
end;
//cull blocks
for z:=0 to active_chunks_h-1 do
for x:=0 to active_chunks_w-1 do
cullBlocksInChunk(chunksPointer,x,z);
finally
if atmosphere<>nil then atmosphere.resume;
end;
end;
procedure TTerrainGenerator.colorOscilator(var r, g, b: single);
begin
//perlin3DNoise.Noise();
if oscUp then begin
r:=r+colorScilatorTint;
g:=g+colorScilatorTint;
b:=b+colorScilatorTint;
colorScilatorTint:=colorScilatorTint+colorScilatorStep;
if colorScilatorTint>0.001 then oscUp:=false;
end else begin
r:=r-colorScilatorTint;
g:=g-colorScilatorTint;
b:=b-colorScilatorTint;
colorScilatorTint:=colorScilatorTint-colorScilatorStep;
if colorScilatorTint<0.001 then oscUp:=true;
end;
end;
function fmod(x,y:single):single;
begin
result:= x - int(x/y) * y;
end;
function TTerrainGenerator.perlinOscilator(const x, y, z: single): single;
begin
// currentChunkOff[0]*chunk
if bmpBuffer=nil then
perlin(world_width,world_depth);
{ TODO -copti : guess 2d byte array could be faster to access than canvas pixels }
result:=(bmpBuffer.Canvas.Pixels[round(x+currentChunkOff[0]),round(z+currentChunkOff[1])] mod $ff);
// result:=perlin3DNoise.Noise(fmod(x+fmod(currentChunkOff[0],60),1),y/chunk_height,fmod(z+currentChunkOff[1],60));
end;
{$IFNDEF SERVER}
procedure TTerrainGenerator.saveMapAsBrush(const filename: string);
var
x,y,z,chx,chy,xx,yy,zz:integer;
brush:TBlockBrush;
pBlok:pBlockType;
begin
if atmosphere<>nil then atmosphere.pause;
brush:=TBlockBrush.create;
for z:=0 to world_depth-1 do begin
chy:=z div chunk_width;
zz:=z mod chunk_width;
for x:=0 to world_width-1 do begin
chx:=x div chunk_width;
xx:=x mod chunk_width;
for y:=0 to chunk_height-1 do begin
yy:=y;
zz:=z mod chunk_width;
pBlok:=chunksPointer^[chx,chy].pblocks[xx,yy,zz];
if pblok^<>byte(btNone) then brush.addBlok(vector3fmake(x,y,z),eBlockTypes(pblok^));
end;
end;
end;
brush.saveAs(filename);
brush.destroy;
if atmosphere<>nil then atmosphere.resume;
end;
{$ENDIF}
procedure TTerrainGenerator.ForEachBlockInChunk(chunk: pChunk;
const operation: TBlockMutator; cullAfter:boolean);
var
pBlok: pBlockType;
x: Integer;
y: Integer;
z: Integer;
begin
//for each block do operation, 3loops, 26ops
for x:=0 to chunk_width-1 do
for y:=0 to chunk_height-1 do
for z:=0 to chunk_width-1 do begin
pBlok := Chunk^.pblocks[x, y, z];
operation(pBlok);
end;
if cullAfter then cullBlocksInChunk(chunksPointer,chunk^.xID,chunk^.yID,false);
end;
procedure TTerrainGenerator.ForEachBlockInWorld(const operation: TBlockMutator;
optimize:boolean;cullAfter: boolean);
var
pBlok: pBlockType;
x: Integer;
y: Integer;
z: Integer;
chx,chy,zz,xx: Integer;
begin
//process blocks chunk by chunk. should be faster.
if optimize then begin
for chY:=0 to active_chunks_h-1 do
for chX:=0 to active_chunks_w-1 do
for y:=0 to chunk_height-1 do
for z:=0 to chunk_width-1 do
for x:=0 to chunk_width-1 do begin
pBlok := chunksPointer^[chx,chy].pblocks[x, y, z];
operation(pBlok);
end;
end
else begin
//process world row by row
for y:=0 to chunk_height-1 do begin
chx:=x div chunk_width;
chy:=z div chunk_width;
for z:=0 to world_depth-1 do begin
zz:=z mod chunk_width;
for x:=0 to world_width-1 do begin
xx:=x mod chunk_width;
pBlok:=chunksPointer^[chx,chy].pblocks[xx,y,zz];
operation(pBlok);
end;
end;
end;
end;
end;
function TTerrainGenerator.fromWorldToArray(pos: TAffineVector): TVector3i;
var
chX,chY:integer;
begin
chX:=round(pos[0]+world_width2) div( chunk_width);
chY:=round(pos[2]+world_depth2) div ( chunk_width);
//log an error?
if chX>=active_chunks_w then chX:=active_chunks_w-1;
if chY>=active_chunks_h then chY:=active_chunks_h-1;
result:=vector3imake(abs(round(pos[0]+world_width2)) mod (chunk_width),
round(chunk_height+pos[1]),
abs(round(pos[2]+world_depth2)) mod (chunk_width));
end;
procedure TTerrainGenerator.MutatorBlockAssignValue(block: PBlockType);
begin
block^:=byte(btwater1);
end;
procedure TTerrainGenerator.MutatorZeroBlocks(block: PBlockType);
begin
block^:=byte(btNone);
end;
procedure TTerrainGenerator.Update;
var
x,y:integer;
begin
//atmosphere.update;
//cull blocks in one chunk per frame if queued
x:=lastCulledChunk mod active_chunks_w;
y:=lastCulledChunk div active_chunks_h;
if (cullChunksQueue[x,y]) or (chunksPointer^[X,Y].reBuild) then cullBlocksInChunk(chunksPointer,x,y,true);
inc(lastCulledChunk);
if lastCulledChunk>=active_chunks_w*active_chunks_w then lastCulledChunk:=0;
end;
procedure TTerrainGenerator.saveVboBuffToFile(const filename: string);
var
st:tfilestream;
i,verts:cardinal;
b:rBufferDataBit;
xMin,xMax,zMin,zMax,yMin,yMax,xMid,zMid:single;
begin
try
xMin:=MaxSingle;xMax:=MinSingle;zMin:=MaxSingle;zmax:=MinSingle;zMid:=MinSingle;yMin:=MaxSingle;yMax:=MinSingle;
//first find the 'pivot' at the center of bottom
verts:=(vboDumpCount div sizeof(rBufferDataBit))-1;
for i:=0 to verts do begin
b:=chunkVertexBuffer[i];
b.x+=world_width2;
b.z+=world_depth2;
if b.x<xmin then xMin:=b.x;
if b.x>xMax then xMax:=b.x;
if b.z<zmin then zMin:=b.z;
if b.z>zMax then zMax:=b.z;
if b.y<yMin then yMin:=b.y;
if b.y>yMax then ymax:=b.y;
chunkVertexBuffer[i]:=b;
end;
//then substract it from rest of blocks to 'center' them
xMid:=(xMax-xMin) / 2;
zMid:=(zMax-zMin) / 2;
for i:=0 to verts do begin
b:=chunkVertexBuffer[i];
b.x-=xMin;
b.x-=xMid;
b.z-=zMin;
b.z-=zMid;
b.y-=yMin;
chunkVertexBuffer[i]:=b;
end;
st:=tFilestream.create(filename,fmCreate or fmOpenWrite);
st.Size:=0;
for i:=0 to verts do begin
b:=chunkVertexBuffer[i];
st.WriteBuffer(b,sizeof(b));
end;
finally
st.free;
end;
end;
{ TTerrainGenerator }
procedure TTerrainGenerator.aoPass(chunk: pChunk);
var
pBlok: pBlockType;
x,y,z,i,h,ai: Integer;
begin
log('TTerrainGenerator.aoPass:: wat?');
h:=chunk_width*chunk_width;
for y:=0 to chunk_height-1 do
for z:=0 to chunk_width-1 do
for x:=0 to chunk_width-1 do
begin
pBlok := Chunk^.pblocks[x, y, z];
ai:=x+(z*chunk_width)+y*h;
//if pBlok in mineralsNonBlocking then aoTable[ai];
end;
end;
constructor TTerrainGenerator.create;
begin
lastCulledChunk:=0;
loadBlockColors(appPath+'terrain\blockColorDefs.palette');
//for optimum performance data should be stored in a format that can be directly read
//into chunk buffer ( or rather some bigger cache so vbos can be filled without too much
//waiting. maybe chunks shouldn't have data buffer but rather read from same big
//common cache and just have pointer to location
// swiat powinien być w pliku i streamowany
perlin3DNoise:=TPerlin3DNoise.Create(1234);
if not gameMode then atmosphere:=TfluidThread.create(False);
end;
destructor TTerrainGenerator.destroy;
begin
// fileStream.free;
if atmosphere<>nil then begin
atmosphere.pause;
atmosphere.terminate;
atmosphere.waitfor;
atmosphere.free;
end;
perlin3DNoise.destroy;
if bmpBuffer<>nil then bmpBuffer.free;
inherited;
end;
procedure TTerrainGenerator.setMapSize;
var i,j:integer;
begin
lastCulledChunk:=0;
setlength(cullChunksQueue,active_chunks_w,active_chunks_h);
for i:=0 to length(cullChunksQueue)-1 do for j:=0 to length(cullChunksQueue)-1 do
cullChunksQueue[i,j]:=false;
setlength(topFaces,chunk_width);
setlength(frontFaces,chunk_width);
setlength(backFaces,chunk_width);
//set ao table sie
//if options.renderer.ambientOcclusion then setlength(aoTable,chunk_width+2+chunk_height+2+chunk_width+2);
end;
procedure TTerrainGenerator.perlin(w,h:integer);
var x,y,z : integer;
begin
if bmpBuffer=nil then bmpBuffer:=tbitmap.create;
with bmpBuffer do
begin
width :=w;
height:=h;
end;
with bmpBuffer.canvas do
for y:=0 to w-1 do
for x:=0 to h-1 do
begin
z:=trunc(abs(PerlinNoise_2D(x /32,y /32))*255);
pixels[x,y]:=RGBToColor(z,z,z);
end;
bmpBuffer.SaveToFile(appPath+'terrain\test.bmp');
end;
procedure TTerrainGenerator.loadFromImage(FileName: string);
begin
if bmpBuffer=nil then bmpBuffer:=tbitmap.create;
bmpBuffer.LoadFromFile(appPath+'terrain\'+FileName);
end;
procedure TTerrainGenerator.freeBufferBmp;
begin
if bmpBuffer<>nil then begin
bmpBuffer.free;
bmpBuffer:=nil;
end;
end;
procedure TTerrainGenerator.saveSector;
begin
log('TTerrainGenerator.saveSector:: not implemented');
end;
procedure TTerrainGenerator.loadBlockColors(fiile: string);
var
s: string;
i:TBlockType;
ini:tinifile;
begin
if not fileexists(fiile) then begin
//when file doesn't exist then load default palette
fiile:=format('%sblockColorDefs.palette',[ExtractFilePath(fiile)]);
end;
ini:=tinifile.Create(fiile);
for i:=TBlockType(btNone)+2 to TBlockType(btMax)-1 do begin
s := GetEnumName(TypeInfo(eBlockTypes),TBlockType(i));
s:=ini.ReadString('colors',s,'0;0;0;1;');
blockColors[eBlockTypes(i)][0]:=strtofloat(eatstring(s));
blockColors[eBlockTypes(i)][1]:=strtofloat(eatstring(s));
blockColors[eBlockTypes(i)][2]:=strtofloat(eatstring(s));
blockColors[eBlockTypes(i)][3]:=strtofloat(eatstring(s));
end;
ini.free;
end;
procedure TTerrainGenerator.saveBlockColors(fiile: string);
var
s,c: string;
i:TBlockType;
ini:tinifile;
begin
ini:=tinifile.Create(fiile);
for i:=TBlockType(btNone)+2 to TBlockType(btMax)-1 do begin
s := GetEnumName(TypeInfo(eBlockTypes),TBlockType(i));
//check it sprawdz to
c:= format('%.3f;%.3f;%.3f;%.3f;',[
blockColors[eBlockTypes(i)][0],
blockColors[eBlockTypes(i)][1],
blockColors[eBlockTypes(i)][2],
blockColors[eBlockTypes(i)][3]
]);
ini.writeString('colors',s,c);
end;
ini.free;
end;
procedure TTerrainGenerator.CpyFromBmpBufferToChunkBuffer(blocks: PBlocksBuffer;chunkX,chunkZ:integer);
var
i,x,y,z:integer;
begin
//actually y is z in opengl point of view but whatever
for z:=0 to chunk_width-1 do
for x:=0 to chunk_width-1 do begin
//first zero
for i:=0 to chunk_height-1 do blocks^[x,i,z]:=byte(eBlockTypes.btNone);
y:=red(bmpBuffer.canvas.pixels[x+(chunkX*chunk_width),z+(chunkZ*chunk_width)]);
y:=y div 8;
blocks^[x,y,z]:=byte(eBlockTypes.btStone);
end;
// log('terrain map copied from bmp to chunk');
end;
function packNormal(x,y,z:smallint):single;
begin
result:= (x+2)*100+(y+2)*10+(z+2);
end;
procedure unpackNormal(a:single;var x,y,z:smallint);
var i:integer;
begin
i:=round(a);
x:= (i div 100)-2;
y:= ((i div 10) mod 10)-2;
z:= (i mod 10)-2;
end;
//sets vert properties and inc buffer position
procedure addChunkVert(ix,iy,iz,r,g,b,a:single);
begin
//calculate baked light from surrounding corners
{
if options.renderer.ambientOcclusion then begin
end;
}
chunkVertexBuffer[bufPosition].a:=a;
chunkVertexBuffer[bufPosition].x:=ix;
chunkVertexBuffer[bufPosition].y:=iy;
chunkVertexBuffer[bufPosition].z:=iz;
chunkVertexBuffer[bufPosition].w:=1;
//colour from blocks definition get's a bit tinted by altitude:
chunkVertexBuffer[bufPosition].r:=r;//+(iy/50);
chunkVertexBuffer[bufPosition].g:=g;//+(iy/50);
chunkVertexBuffer[bufPosition].b:=b;//(random(2)+90)/100;//blockColors[block][2]+(iy/50);
inc(bufPosition);
end;
procedure addRightFace(x,y,z:integer;r,g,b,a:single;sasiady:pSasiedzi;lum:single);
var
ao,r2,g2,b2,r1,g1,b1,r3,b3,g3,r4,g4,b4:single;
begin
r*=lum;
g*=lum;
b*=lum;
ao:=0.0;
with options.renderer do begin
if sE in sasiady^ then ao:=ao+aoStep;
if sSE in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r1:=r-ao; g1:=g-ao; b1:=b-ao;
addChunkVert(x+0.5,y-0.5,z-0.5,r1,g1,b1,a);
ao:=0;
if sN in sasiady^ then ao:=ao+aoStep;
if sNE in sasiady^ then ao:=ao+aoStep;
if sE in sasiady^ then ao:=ao+aoStep;
r2:=r-ao;g2:=g-ao;b2:=b-ao;
addChunkVert(x+0.5,y+0.5,z-0.5,r2,g2,b2,a);
ao:=0;
if sW in sasiady^ then ao:=ao+aoStep;
if sSW in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r3:=r-ao;g3:=g-ao;b3:=b-ao;
addChunkVert(x+0.5,y-0.5,z+0.5,r3,g3,b3,a);
addChunkVert(x+0.5,y-0.5,z+0.5,r3,g3,b3,a);
addChunkVert(x+0.5,y+0.5,z-0.5,r2,g2,b2,a);
ao:=0;
if sNW in sasiady^ then ao:=ao+aoStep;
if sN in sasiady^ then ao:=ao+aoStep;
if sW in sasiady^ then ao:=ao+aoStep;
r4:=r-ao;g4:=g-ao;b4:=b-ao;
//if snw in sasiady^ then g4:=1;
addChunkVert(x+0.5,y+0.5,z+0.5,r4,g4,b4,a);
end;
end;
procedure addLeftFace(x,y,z:integer;r,g,b,a:single;sasiady:pSasiedzi;lum:single);
var
ao,r2,g2,b2,r1,g1,b1,r3,b3,g3,r4,g4,b4:single;
begin
r*=lum;
g*=lum;
b*=lum;
ao:=0.0;
with options.renderer do begin
if sW in sasiady^ then ao:=ao+aoStep;
if sNW in sasiady^ then ao:=ao+aoStep;
if sN in sasiady^ then ao:=ao+aoStep;
r1:=r-ao; g1:=g-ao; b1:=b-ao;
addChunkVert(x-0.5,y+0.5,z-0.5,r1,g1,b1,a);
ao:=0;
if sW in sasiady^ then ao:=ao+aoStep;
if sSW in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r2:=r-ao;g2:=g-ao;b2:=b-ao;
addChunkVert(x-0.5,y-0.5,z-0.5,r2,g2,b2,a);
ao:=0;
if sE in sasiady^ then ao:=ao+aoStep;
if sSE in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r3:=r-ao;g3:=g-ao;b3:=b-ao;
addChunkVert(x-0.5,y-0.5,z+0.5,r3,g3,b3,a);
addChunkVert(x-0.5,y-0.5,z+0.5,r3,g3,b3,a);
ao:=0;
if sNE in sasiady^ then ao:=ao+aoStep;
if sN in sasiady^ then ao:=ao+aoStep;
if sE in sasiady^ then ao:=ao+aoStep;
r4:=r-ao;g4:=g-ao;b4:=b-ao;
//if sN in sasiady^ then g4:=1;
addChunkVert(x-0.5,y+0.5,z+0.5,r4,g4,b4,a);
addChunkVert(x-0.5,y+0.5,z-0.5,r1,g1,b1,a);
end;
end;
procedure addBottomFace(x,y,z:integer;r,g,b,a:single;sasiady:pSasiedzi;lum:single);
var
r1,g1,b1,r2,g2,b2,ao,r3,g3,b3,r4,g4,b4:single;
begin
r*=lum;
g*=lum;
b*=lum;
ao:=0.0;
//obecnosc elementu oznacza obecnosc bloku. a to oznacza ze trzeba sciemnic rog
//left back vert
with options.renderer do begin
if sW in sasiady^ then ao:=ao+aoStep;
if sNW in sasiady^ then ao:=ao+aoStep;
if sN in sasiady^ then ao:=ao+aoStep;
r1:=r-ao; g1:=g-ao; b1:=b-ao;
addChunkVert(x-0.5,y-0.5,z-0.5,r1,g1,b1,a);
ao:=0.0;
if sE in sasiady^ then ao:=ao+aoStep;
if sNE in sasiady^ then ao:=ao+aoStep;
if sN in sasiady^ then ao:=ao+aoStep;
r3:=r-ao; g3:=g-ao; b3:=b-ao;
addChunkVert(x+0.5,y-0.5,z-0.5,r3,g3,b3,a);
ao:=0.0;
if sE in sasiady^ then ao:=ao+aoStep;
if sSE in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r2:=r-ao; g2:=g-ao; b2:=b-ao;
addChunkVert(x+0.5,y-0.5,z+0.5,r2,g2,b2,a);
addChunkVert(x-0.5,y-0.5,z-0.5,r1,g1,b1,a);
addChunkVert(x+0.5,y-0.5,z+0.5,r2,g2,b2,a);
ao:=0.0;
if sSW in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
if sW in sasiady^ then ao:=ao+aoStep;
r4:=r-ao; g4:=g-ao; b4:=b-ao;
//if sne in sasiady^ then g3:=1;
addChunkVert(x-0.5,y-0.5,z+0.5,r4,g4,b4,a);
end;
end;
procedure addFrontFace(x,y,z:integer;r,g,b,a:single;sasiady:pSasiedzi;lum:single);
var
r1,g1,b1,r2,g2,b2,ao,r3,g3,b3,r4,g4,b4:single;
begin
r*=lum;
g*=lum;
b*=lum;
ao:=0.0;
//obecnosc elementu oznacza obecnosc bloku. a to oznacza ze trzeba sciemnic rog
with options.renderer do begin
if sW in sasiady^ then ao:=ao+aoStep;
if sSW in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r1:=r-ao; g1:=g-ao; b1:=b-ao;
addChunkVert(x-0.5,y-0.5,z-0.5,r1,g1,b1,a);
ao:=0.0;
if sE in sasiady^ then ao:=ao+aoStep;
if sNE in sasiady^ then ao:=ao+aoStep;
if sN in sasiady^ then ao:=ao+aoStep;
r3:=r-ao; g3:=g-ao; b3:=b-ao;
addChunkVert(x+0.5,y+0.5,z-0.5,r3,g3,b3,a);
ao:=0.0;
if sE in sasiady^ then ao:=ao+aoStep;
if sSE in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r2:=r-ao; g2:=g-ao; b2:=b-ao;
addChunkVert(x+0.5,y-0.5,z-0.5,r2,g2,b2,a);
addChunkVert(x-0.5,y-0.5,z-0.5,r1,g1,b1,a);
ao:=0.0;
if sN in sasiady^ then ao:=ao+aoStep;
if sNW in sasiady^ then ao:=ao+aoStep;
if sW in sasiady^ then ao:=ao+aoStep;
r4:=r-ao; g4:=g-ao; b4:=b-ao;
//if snw in sasiady^ then g4:=1;
addChunkVert(x-0.5,y+0.5,z-0.5,r4,g4,b4,a);
addChunkVert(x+0.5,y+0.5,z-0.5,r3,g3,b3,a);
end;
end;
procedure addBackFace(x,y,z:integer;r,g,b,a:single;sasiady:pSasiedzi;lum:single);
var
r1,g1,b1,r2,g2,b2,ao,r3,g3,b3,r4,g4,b4:single;
begin
r*=lum;
g*=lum;
b*=lum;
ao:=0.0;
//obecnosc elementu oznacza obecnosc bloku. a to oznacza ze trzeba sciemnic rog
with options.renderer do begin
if sW in sasiady^ then ao:=ao+aoStep;
if sSW in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r1:=r-ao; g1:=g-ao; b1:=b-ao;
addChunkVert(x-0.5,y-0.5,z+0.5,r1,g1,b1,a);
ao:=0.0;
if sE in sasiady^ then ao:=ao+aoStep;
if sSE in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r2:=r-ao; g2:=g-ao; b2:=b-ao;
addChunkVert(x+0.5,y-0.5,z+0.5,r2,g2,b2,a);
ao:=0.0;
if sE in sasiady^ then ao:=ao+aoStep;
if sNE in sasiady^ then ao:=ao+aoStep;
if sN in sasiady^ then ao:=ao+aoStep;
r3:=r-ao; g3:=g-ao; b3:=b-ao;
addChunkVert(x+0.5,y+0.5,z+0.5,r3,g3,b3,a);
ao:=0.0;
if sN in sasiady^ then ao:=ao+aoStep;
if sNW in sasiady^ then ao:=ao+aoStep;
if sW in sasiady^ then ao:=ao+aoStep;
r4:=r-ao; g4:=g-ao; b4:=b-ao;
//if sw in sasiady^ then g4:=1;
addChunkVert(x-0.5,y-0.5,z+0.5,r1,g1,b1,a);
addChunkVert(x+0.5,y+0.5,z+0.5,r3,g3,b3,a);
addChunkVert(x-0.5,y+0.5,z+0.5,r4,g4,b4,a);
end;
end;
procedure addTopFace(x,y,z:integer;r,g,b,a:single;sasiady:pSasiedzi;lum:single);
var
r1,g1,b1,r2,g2,b2,ao,r3,g3,b3,r4,g4,b4:single;
begin
r*=lum;
g*=lum;
b*=lum;
ao:=0.0;
//obecnosc elementu oznacza obecnosc bloku. a to oznacza ze trzeba sciemnic rog
//left back vert
with options.renderer do begin
if sW in sasiady^ then ao:=ao+aoStep;
if sNW in sasiady^ then ao:=ao+aoStep;
if sN in sasiady^ then ao:=ao+aoStep;
r1:=r-ao; g1:=g-ao; b1:=b-ao;
addChunkVert(x-0.5,y+0.5,z-0.5,r1,g1,b1,a);
ao:=0.0;
if sE in sasiady^ then ao:=ao+aoStep;
if sSE in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
r2:=r-ao; g2:=g-ao; b2:=b-ao;
addChunkVert(x+0.5,y+0.5,z+0.5,r2,g2,b2,a);
ao:=0.0;
if sE in sasiady^ then ao:=ao+aoStep;
if sNE in sasiady^ then ao:=ao+aoStep;
if sN in sasiady^ then ao:=ao+aoStep;
r3:=r-ao; g3:=g-ao; b3:=b-ao;
addChunkVert(x+0.5,y+0.5,z-0.5,r3,g3,b3,a);
addChunkVert(x-0.5,y+0.5,z-0.5,r1,g1,b1,a);
ao:=0.0;
if sSW in sasiady^ then ao:=ao+aoStep;
if sS in sasiady^ then ao:=ao+aoStep;
if sW in sasiady^ then ao:=ao+aoStep;
r4:=r-ao; g4:=g-ao; b4:=b-ao;
//if sne in sasiady^ then g3:=1;
addChunkVert(x-0.5,y+0.5,z+0.5,r4,g4,b4,a);
addChunkVert(x+0.5,y+0.5,z+0.5,r2,g2,b2,a);
end;
end;
//wrzucic ze strszej wersji szybszy cullling na wszellki wypadek
procedure TTerrainGenerator.cullBlocksInChunk(chunks: PChunksArray; chunkX,
chunkY: integer;executeNow:boolean=false);
var
offsetxz,xx,yy,zz,x,y,z:integer;
left,right,front,back,top,btm,chxL,chxR,chzB,chzF:integer;
block :eBlockTypes;
rr,gg,bb:single;
sasiady:TSasiedzi;
begin
if not executeNow then begin
cullChunksQueue[chunkX,chunkY]:=true;
exit;
end else cullChunksQueue[chunkX,chunkY]:=false;
chunks^[chunkX,chunkY].reBuild:=false;
currentChunkOff[0]:=chunkX*chunk_width;
currentChunkOff[1]:=chunkY*chunk_width;
{$IFNDEF SERVER}
//offset for chunk bufPosition alignemt
offsetxz:=-(chunk_width2 *block_size);
bufPosition:=0;
takeCareOfDataBufferSize(256000);
//first iterate the inner part. just to spare all the ifs for suroounding chunks
for y:=0 to chunk_height-1 do
for z:=0 to chunk_width-1 do begin
for x:=0 to chunk_width-1 do begin
frontFaces[x]:=btNone;
backFaces[x]:=btNone;
//block:=eBlockTypes(core.chunks[chunkX,chunkY].blocks[x,y,z]);
block:=eBlockTypes(chunksPointer^[chunkX,chunkY].pblocks[x,y,z]^);
//if block in mineralsWater then
//atmosphere.waterMap.setWet(chunkX*chunk_width+x,y,chunkY*chunk_width+z);
//if block in mineralsOxygen then
//atmosphere.oxygenMap.setWet(chunkX*chunk_width+x,y,chunkY*chunk_width+z);
if not (block in mineralsDontRender) then
begin
//x axis
left:=-1;
chXL:=0;
if (chunkX=0) and (x=0) then left:=0;
if (chunkX>0) and (x=0) then begin
left:=chunk_width-1;//styczny z poprzedniego bloku
chXL:=-1;
end;
right:=1;
chxR:=0;
if (chunkX<active_chunks_w-1) and (x=chunk_width-1) then begin
right:=-chunk_width+1;//sasiad z nastepnego bloku
chxR:=1;
end;
if (chunkX=active_chunks_w-1) and (x=chunk_width-1) then begin
right:=0;
end;
//z axis
front:=-1;
chZF:=0;
if (chunkY=0) and (z=0) then front:=0;
if (chunkY>0) and (z=0) then begin
front:=chunk_width-1;//styczny z poprzedniego bloku
chZF:=-1;
end;
back:=1;
chzB:=0;
if (chunkY<active_chunks_h-1) and (z=chunk_width-1) then begin
back:=-chunk_width+1;//sasiad z nastepnego bloku
chzB:=1;
end;
if (chunkY=active_chunks_h-1) and (z=chunk_width-1) then begin
back:=0;
end;
top:=1;
if (y=chunk_height-1) or (y=0) then begin
top:=0;
// a:=a+16;
end;
btm:=1;
if y=0 then btm:=0;
xx:=offsetxz+x;
yy:=y;
zz:=offsetxz+z;
//colour from blocks definition get's a bit tinted by altitude:
rr:=blockColors[block][0];//+(y/50);
gg:=blockColors[block][1];//+(y/50);
bb:=blockColors[block][2];//(random(2)+90)/100;//blockColors[block][2]+(y/50);
sasiady:=[];
//cull here first, maybe block won't be shown at all
if eBlockTypes(chunks^[chunkX+chXL,chunkY].blocks[x+left,y,z]) in mineralsDontRender then //left face
begin
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZf].blocks[x+left,y,z+front]) in mineralsDontRender)
then include(sasiady,sW) else exclude(sasiady,sW);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZB].blocks[x+left,y,z+back])in mineralsDontRender)
then include(sasiady,sE) else exclude(sasiady,sE);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY].blocks[x+left,y+top,z])in mineralsDontRender)
then include(sasiady,sN) else exclude(sasiady,sN);
if not (eBlockTypes(chunks^[chunkX+chxL,chunkY].blocks[x+left,y-top,z]) in mineralsDontRender)
then include(sasiady,sS) else exclude(sasiady,sS);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZf].blocks[x+left,y+top,z+front]) in mineralsDontRender)
then include(sasiady,sNW) else exclude(sasiady,sNW);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZf].blocks[x+left,y-top,z+front]) in mineralsDontRender)
then include(sasiady,sSW) else exclude(sasiady,sSW);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZb].blocks[x+left,y+top,z+back]) in mineralsDontRender)
then include(sasiady,sNE) else exclude(sasiady,sNE);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZb].blocks[x+left,y-top,z+back]) in mineralsDontRender)
then include(sasiady,sSE) else exclude(sasiady,sSE);
addLeftFace(xx,yy,zz,rr,gg,bb,packNormal(-1,0,0),@sasiady,
//1
calculateAO((chunkX+chxL)*chunk_width+x+left,y,chunkY*chunk_width+z,fLeft)
);
end;
if eBlockTypes(chunks^[chunkX+chXR,chunkY].blocks[x+right,y,z]) in mineralsDontRender then //right face
begin
if not (eBlockTypes(chunks^[chunkX+chXr,chunkY+chZb].blocks[x+right,y,z+back]) in mineralsDontRender)
then include(sasiady,sW) else exclude(sasiady,sW);
if not (eBlockTypes(chunks^[chunkX+chXr,chunkY+chZf].blocks[x+right,y,z+front])in mineralsDontRender)
then include(sasiady,sE) else exclude(sasiady,sE);
if not (eBlockTypes(chunks^[chunkX+chXr,chunkY].blocks[x+right,y+top,z])in mineralsDontRender)
then include(sasiady,sN) else exclude(sasiady,sN);
if not (eBlockTypes(chunks^[chunkX+chxr,chunkY].blocks[x+right,y-top,z]) in mineralsDontRender)
then include(sasiady,sS) else exclude(sasiady,sS);
if not (eBlockTypes(chunks^[chunkX+chXr,chunkY+chZb].blocks[x+right,y+top,z+back]) in mineralsDontRender)
then include(sasiady,sNW) else exclude(sasiady,sNW);
if not (eBlockTypes(chunks^[chunkX+chXr,chunkY+chZb].blocks[x+right,y-top,z+back]) in mineralsDontRender)
then include(sasiady,sSW) else exclude(sasiady,sSW);
if not (eBlockTypes(chunks^[chunkX+chXr,chunkY+chZf].blocks[x+right,y+top,z+front]) in mineralsDontRender)
then include(sasiady,sNE) else exclude(sasiady,sNE);
if not (eBlockTypes(chunks^[chunkX+chXr,chunkY+chZf].blocks[x+right,y-top,z+front]) in mineralsDontRender)
then include(sasiady,sSE) else exclude(sasiady,sSE);
addRightFace(xx,yy,zz,rr,gg,bb,packNormal(1,0,0),@sasiady,
calculateAO((chunkX+chxr)*chunk_width+x+right,y,chunkY*chunk_width+z,fright));
end;
if eBlockTypes(chunks^[chunkX,chunkY+chZF].blocks[x,y,z+front]) in mineralsDontRender then begin//front face
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chzf].blocks[x+left,y,z+front]) in mineralsDontRender)
then include(sasiady,sW) else exclude(sasiady,sW);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chzf].blocks[x+right,y,z+front])in mineralsDontRender)
then include(sasiady,sE) else exclude(sasiady,sE);
if not (eBlockTypes(chunks^[chunkX,chunkY+chZf].blocks[x,y+top,z+front])in mineralsDontRender)
then include(sasiady,sN) else exclude(sasiady,sN);
if not (eBlockTypes(chunks^[chunkX,chunkY+chZf].blocks[x,y-top,z+front]) in mineralsDontRender)
then include(sasiady,sS) else exclude(sasiady,sS);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZf].blocks[x+left,y+top,z+front]) in mineralsDontRender)
then include(sasiady,sNW) else exclude(sasiady,sNW);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZf].blocks[x+left,y-top,z+front]) in mineralsDontRender)
then include(sasiady,sSW) else exclude(sasiady,sSW);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chZf].blocks[x+right,y+top,z+front]) in mineralsDontRender)
then include(sasiady,sNE) else exclude(sasiady,sNE);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chZf].blocks[x+right,y-top,z+front]) in mineralsDontRender)
then include(sasiady,sSE) else exclude(sasiady,sSE);
addFrontFace(xx,yy,zz,rr,gg,bb,packNormal(0,0,1),@sasiady,
calculateAO((chunkX)*chunk_width+x,y,(chunkY+chzf)*chunk_width+z+front,fFRont));
end;
if eBlockTypes(chunks^[chunkX,chunkY+chZB].blocks[x,y,z+back]) in mineralsDontRender then begin//beck? face
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chzb].blocks[x+left,y,z+back]) in mineralsDontRender)
then include(sasiady,sW) else exclude(sasiady,sW);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chzb].blocks[x+right,y,z+back])in mineralsDontRender)
then include(sasiady,sE) else exclude(sasiady,sE);
if not (eBlockTypes(chunks^[chunkX,chunkY+chZb].blocks[x,y+top,z+back])in mineralsDontRender)
then include(sasiady,sN) else exclude(sasiady,sN);
if not (eBlockTypes(chunks^[chunkX,chunkY+chZb].blocks[x,y-top,z+back]) in mineralsDontRender)
then include(sasiady,sS) else exclude(sasiady,sS);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZb].blocks[x+left,y+top,z+back]) in mineralsDontRender)
then include(sasiady,sNW) else exclude(sasiady,sNW);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZb].blocks[x+left,y-top,z+back]) in mineralsDontRender)
then include(sasiady,sSW) else exclude(sasiady,sSW);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chZb].blocks[x+right,y+top,z+back]) in mineralsDontRender)
then include(sasiady,sNE) else exclude(sasiady,sNE);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chZb].blocks[x+right,y-top,z+back]) in mineralsDontRender)
then include(sasiady,sSE) else exclude(sasiady,sSE);
addBackFace(xx,yy,zz,rr,gg,bb,packNormal(0,0,-1),@sasiady,
calculateAO((chunkX)*chunk_width+x,y,(chunkY+chzb)*chunk_width+z+back,fback));
end;
if eBlockTypes(chunks^[chunkX,chunkY].blocks[x,y+top,z]) in mineralsDontRender then begin//top face
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY].blocks[x+left,y+top,z]) in mineralsDontRender)
then include(sasiady,sW) else exclude(sasiady,sW);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY].blocks[x+right,y+top,z])in mineralsDontRender)
then include(sasiady,sE) else exclude(sasiady,sE);
if not (eBlockTypes(chunks^[chunkX,chunkY+chZf].blocks[x,y+top,z+front])in mineralsDontRender)
then include(sasiady,sN) else exclude(sasiady,sN);
if not (eBlockTypes(chunks^[chunkX,chunkY+chZb].blocks[x,y+top,z+back]) in mineralsDontRender)
then include(sasiady,sS) else exclude(sasiady,sS);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZf].blocks[x+left,y+top,z+front]) in mineralsDontRender)
then include(sasiady,sNW) else exclude(sasiady,sNW);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZb].blocks[x+left,y+top,z+back]) in mineralsDontRender)
then include(sasiady,sSW) else exclude(sasiady,sSW);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chZf].blocks[x+right,y+top,z+front]) in mineralsDontRender)
then include(sasiady,sNE) else exclude(sasiady,sNE);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chZb].blocks[x+right,y+top,z+back]) in mineralsDontRender)
then include(sasiady,sSE) else exclude(sasiady,sSE);
addTopFace(xx,yy,zz,rr,gg,bb,packNormal(0,1,0),@sasiady,
calculateAO(chunkX*chunk_width+x,y+top,chunkY*chunk_width+z,fTop));
end;
//addTopFace(xx,yy,zz,1,rr,gg,bb,5.0);
if eBlockTypes(chunks^[chunkX,chunkY].blocks[x,y-btm,z]) in mineralsDontRender then //btm face
begin
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY].blocks[x+left,y-btm,z]) in mineralsDontRender)
then include(sasiady,sW) else exclude(sasiady,sW);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY].blocks[x+right,y-btm,z])in mineralsDontRender)
then include(sasiady,sE) else exclude(sasiady,sE);
if not (eBlockTypes(chunks^[chunkX,chunkY+chZf].blocks[x,y-btm,z+front])in mineralsDontRender)
then include(sasiady,sN) else exclude(sasiady,sN);
if not (eBlockTypes(chunks^[chunkX,chunkY+chZb].blocks[x,y-btm,z+back]) in mineralsDontRender)
then include(sasiady,sS) else exclude(sasiady,sS);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZf].blocks[x+left,y-btm,z+front]) in mineralsDontRender)
then include(sasiady,sNW) else exclude(sasiady,sNW);
if not (eBlockTypes(chunks^[chunkX+chXL,chunkY+chZb].blocks[x+left,y-btm,z+back]) in mineralsDontRender)
then include(sasiady,sSW) else exclude(sasiady,sSW);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chZf].blocks[x+right,y-btm,z+front]) in mineralsDontRender)
then include(sasiady,sNE) else exclude(sasiady,sNE);
if not (eBlockTypes(chunks^[chunkX+chXR,chunkY+chZb].blocks[x+right,y-btm,z+back]) in mineralsDontRender)
then include(sasiady,sSE) else exclude(sasiady,sSE);
addBottomFace(xx,yy,zz,rr,gg,bb,packNormal(0,-1,0),@sasiady,
//1);
calculateAO(chunkX*chunk_width+x,y-btm,chunkY*chunk_width+z,fBottom));
end;
end;
end;
//addFrontFaces(offsetxz,offsety+y,offsetxz+z);
//addTopFaces(offsetxz,offsety+y,offsetxz+z);
//addBackFaces(offsetxz,offsety+y,offsetxz+z);
end;
vboDumpCount:=(bufPosition*sizeof(rBufferDataBit));
chunksPointer^[chunkX,chunkY].renderable.updateVBO(@chunkVertexBuffer,vboDumpCount);
//core.chunks[chunkX,chunkY].renderable.updateVBO(@chunkVertexBuffer,vboDumpCount);
{$ENDIF}
end;
procedure TTerrainGenerator.cullAllChunks;
var x,z:integer;
begin
for z:=0 to active_chunks_h-1 do
for x:=0 to active_chunks_w-1 do
cullBlocksInChunk(chunksPointer,x,z);
end;
function TTerrainGenerator.calculateAO(xx, yy, zz:integer; dir: eFaces): single;
var i:integer;
total:integer;
begin
total:=0;
with options.renderer do begin//shortcut for options.renderer.aoRayLength
case dir of
fTop:begin
for i:=0 to aoRayLength-1 do //shoot ray up
if getWorldArray(xx,yy+i,zz) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy+i,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy+i,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy+i,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy+i,zz-i) in mineralsDontRender then inc(total) else break;
end;
fLeft:begin
for i:=0 to aoRayLength-1 do //shoot ray left
if getWorldArray(xx-i,yy,zz) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy-i,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy-i,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy+i,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy+i,zz+i) in mineralsDontRender then inc(total) else break;
end;
fRight:begin
for i:=0 to aoRayLength-1 do //shoot ray left
if getWorldArray(xx+i,yy,zz) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy-i,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy-i,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy+i,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy+i,zz+i) in mineralsDontRender then inc(total) else break;
end;
fBack:begin
for i:=0 to aoRayLength-1 do //shoot ray left
if getWorldArray(xx,yy,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy-i,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy-i,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy+i,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy+i,zz+i) in mineralsDontRender then inc(total) else break;
end;
ffront:begin
for i:=0 to aoRayLength-1 do //shoot ray left
if getWorldArray(xx,yy,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy-i,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy-i,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy+i,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy+i,zz-i) in mineralsDontRender then inc(total) else break;
end;
fBottom:begin
for i:=0 to aoRayLength-1 do //shoot ray up
if getWorldArray(xx,yy-i,zz) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy-i,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy-i,zz+i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx+i,yy-i,zz-i) in mineralsDontRender then inc(total) else break;
for i:=0 to aoSkosRayLength-1 do
if getWorldArray(xx-i,yy-i,zz-i) in mineralsDontRender then inc(total) else break;
end;
end;
//more light means less to substract
result:= total / (aoRayLength + 4*aoSkosRayLength);
end;
if result = 0 then result:=0.2
//log(floattostr(result));
end;
procedure addTopFaceF(x,y,z,r,g,b,a:single);
begin
terrain.colorOscilator(r,g,b);
addChunkVert(x-0.5,y+0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z+0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z-0.5,r,g,b,a);
addChunkVert(x-0.5,y+0.5,z-0.5,r,g,b,a);
addChunkVert(x-0.5,y+0.5,z+0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z+0.5,r,g,b,a);
end;
procedure addBackFaceF(x,y,z,r,g,b,a:single);
begin
terrain.colorOscilator(r,g,b);
addChunkVert(x-0.5,y-0.5,z+0.5,r,g,b,a);
addChunkVert(x+0.5,y-0.5,z+0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z+0.5,r,g,b,a);
addChunkVert(x-0.5,y-0.5,z+0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z+0.5,r,g,b,a);
addChunkVert(x-0.5,y+0.5,z+0.5,r,g,b,a);
end;
procedure addFrontFaceF(x,y,z,r,g,b,a:single);
begin
terrain.colorOscilator(r,g,b);
addChunkVert(x-0.5,y-0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y-0.5,z-0.5,r,g,b,a);
addChunkVert(x-0.5,y-0.5,z-0.5,r,g,b,a);
addChunkVert(x-0.5,y+0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z-0.5,r,g,b,a);
end;
procedure addRightFaceF(x,y,z,r,g,b,a:single);
begin
terrain.colorOscilator(r,g,b);
addChunkVert(x+0.5,y-0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y-0.5,z+0.5,r,g,b,a);
addChunkVert(x+0.5,y-0.5,z+0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y+0.5,z+0.5,r,g,b,a);
end;
procedure addLeftFaceF(x,y,z,r,g,b,a:single);
begin
terrain.colorOscilator(r,g,b);
addChunkVert(x-0.5,y-0.5,z-0.5,r,g,b,a);
addChunkVert(x-0.5,y-0.5,z+0.5,r,g,b,a);
addChunkVert(x-0.5,y+0.5,z-0.5,r,g,b,a);
addChunkVert(x-0.5,y-0.5,z+0.5,r,g,b,a);
addChunkVert(x-0.5,y+0.5,z+0.5,r,g,b,a);
addChunkVert(x-0.5,y+0.5,z-0.5,r,g,b,a);
end;
procedure addBottomFaceF(x,y,z,r,g,b,a:single);
begin
terrain.colorOscilator(r,g,b);
addChunkVert(x-0.5,y-0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y-0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y-0.5,z+0.5,r,g,b,a);
addChunkVert(x-0.5,y-0.5,z-0.5,r,g,b,a);
addChunkVert(x+0.5,y-0.5,z+0.5,r,g,b,a);
addChunkVert(x-0.5,y-0.5,z+0.5,r,g,b,a);
end;
procedure TTerrainGenerator.setBlockAndCull(pos: TAffineVector;
blokType: eBlockTypes);
var chX,chY:integer;
blokPos:TVector3b;
begin
chX:=round(pos[0]+world_width2) div( chunk_width);
chY:=round(pos[2]+world_depth2) div ( chunk_width);
if chX>=active_chunks_w then chX:=active_chunks_w-1;
if chY>=active_chunks_h then chY:=active_chunks_h-1;
blokPos:=vector3bmake(abs(round(pos[0]+world_width2)) mod (chunk_width),
round(pos[1]),
abs(round(pos[2]+world_depth2)) mod (chunk_width));
chunksPointer^[chx,chy].setBlock(blokPos,blokType);
cullChunksQueue[chX,chY]:=true;
//cull edge chunks if necessary
if (blokPos[0]=0) and (chx>0) then cullChunksQueue[chx-1,chy]:=true;
if (blokPos[0]=chunk_width-1) and (chx<active_chunks_w-1) then cullChunksQueue[chx+1,chy]:=true;
if (blokPos[1]=0) and (chy>0) then cullChunksQueue[chx,chy-1]:=true;
if (blokPos[1]=chunk_width-1) and (chy<active_chunks_h-1) then cullChunksQueue[chx,chy+1]:=true;
end;
procedure TTerrainGenerator.setBlockInWorld(x, y, z: integer;
blok: eBlockTypes; centered,cull: boolean);
var chX,chY:integer;
blokPos:TVector3b;
begin
if centered then begin
chX:=round(x+world_width2) div( chunk_width);
chY:=round(z+world_depth2) div ( chunk_width);
if chX>=active_chunks_w then chX:=active_chunks_w-1;
if chY>=active_chunks_h then chY:=active_chunks_h-1;
blokPos:=vector3bmake(abs(round(x+world_width2)) mod (chunk_width),
round(chunk_height+y),
abs(round(z+world_depth2)) mod (chunk_width));
blok:=eBlockTypes(chunksPointer^[chx,chy].blocks[blokPos[0],blokPos[1],blokPos[2]]);
chunksPointer^[chx,chy].setBlock(blokPos,blok);
if cull then cullBlocksInChunk(chunksPointer,chX,chY,false);
//blok:=btNone;
end else begin
chunksPointer^[x div chunk_width,z div chunk_width].blocks[x mod chunk_width,y,z mod chunk_width]:=byte(blok);
end;
end;
function TTerrainGenerator.getBlockInWorld(x, y, z: integer; centered: boolean
): pBlockType;
var chX,chY:integer;
blokPos:TVector3b;
begin
if centered then begin
chX:=round(x+world_width2) div( chunk_width);
chY:=round(z+world_depth2) div ( chunk_width);
blokPos:=vector3bmake(abs(round(x+world_width2)) mod (chunk_width),
round(y),
abs(round(z+world_depth2)) mod (chunk_width));
result:=chunksPointer^[chx,chy].pblocks[blokPos[0],blokPos[1],blokPos[2]];
end
else begin
result:=chunksPointer^[x div chunk_width,z div chunk_width].pblocks[x mod chunk_width,y,z mod chunk_width];
end;
end;
end.
|
unit IdTestReplyRFC;
interface
uses
IdTest,
IdReplyRFC,
IdGlobal,
IdObjs,
IdSys;
type
TIdTestReplyRFC = class(TIdTest)
published
procedure TestFormattedReply;
end;
implementation
procedure TIdTestReplyRFC.TestFormattedReply;
var
aStr:string;
R1: TIdReplyRFC;
R2: TIdReplyRFC;
const
CText = 'Hello, World!';
CCode = '201';
begin
R1 := TIdReplyRFC.Create(nil);
R2 := TIdReplyRFC.Create(nil);
try
R1.Code := CCode;
R1.Text.Text := CText;
aStr:=r1.FormattedReply.Text;
Assert(aStr=CCode+' '+CText+EOL, '1:' + AStr);
//check that assign works. eg used in TIdCmdTCPServer.DoConnect
R2.Assign(R1);
Assert(R2.Code = CCode, '2:' + R2.Code);
aStr := R2.Text.Text;
Assert(aStr = CText + EOL, '3:' + aStr);
finally
Sys.FreeAndNil(R1);
Sys.FreeAndNil(R2);
end;
end;
initialization
TIdTest.RegisterTest(TIdTestReplyRFC);
end. |
unit View.ClienteList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
View.TemplateList, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Vcl.Menus,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, System.ImageList, Vcl.ImgList,
Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, View.Cliente,
Controller.Cliente, Util.Enum, View.Template, Vcl.Mask, Model;
type
TClienteListView = class(TTemplateListView)
LBLID: TLabel;
LBLNomeFantasia: TLabel;
LBLCNPJ: TLabel;
EDTID: TEdit;
EDTNomeFantasia: TEdit;
MSKCNPJ: TMaskEdit;
EDTRazaoSocial: TEdit;
LBLRazaoSocial: TLabel;
procedure BTNPesquisarClick(Sender: TObject);
procedure FDQueryAfterOpen(DataSet: TDataSet);
private
public
function CreateViewTemplate(AOperacao: TOperacao): TTemplateView; override;
procedure CreateController; override;
function Search(const ACondition: string): TModel; override;
end;
var
ClienteListView: TClienteListView;
implementation
{$R *.dfm}
{ TTemplateListView1 }
procedure TClienteListView.BTNPesquisarClick(Sender: TObject);
var
SB: TStringBuilder;
begin
inherited;
SB := TStringBuilder.Create;
try
SB.Append('SELECT * ').
Append('FROM ').Append(Controller.Model.DataBaseObject.View).
Append(' WHERE 1 = 1 ');
if StrToIntDef(EDTID.Text, 0) > 0 then
begin
SB.Append(' AND ID = ').Append(EDTID.Text);
end;
if not Trim(EDTRazaoSocial.Text).IsEmpty then
begin
SB.Append(' AND RazaoSocial LIKE ').Append(QuotedStr(Trim('%' + EDTRazaoSocial.Text + '%')));
end;
if not Trim(EDTNomeFantasia.Text).IsEmpty then
begin
SB.Append(' AND NomeFantasia LIKE ').Append(QuotedStr(Trim('%' + EDTNomeFantasia.Text + '%')));
end;
if not Trim(MSKCNPJ.Text).IsEmpty then
begin
SB.Append(' AND CNPJ LIKE ').Append(QuotedStr('%' + Trim(MSKCNPJ.Text) + '%'));
end;
SB.Append(' ORDER BY ID ');
FDQuery.Open(SB.ToString);
finally
FreeAndNil(SB);
end;
end;
procedure TClienteListView.CreateController;
begin
inherited;
if not Assigned(Controller) then
Controller := TClienteController.Create;
end;
function TClienteListView.CreateViewTemplate(AOperacao: TOperacao): TTemplateView;
begin
Result := TClienteView.Create(Self);
end;
procedure TClienteListView.FDQueryAfterOpen(DataSet: TDataSet);
begin
TStringField(DataSource.DataSet.FieldByName('CNPJ')).EditMask := '00\.000\.000\/0000\-00;0;_';
end;
function TClienteListView.Search(const ACondition: string): TModel;
var
LValue: Integer;
begin
Result := nil;
if not ACondition.Trim.IsEmpty then
begin
if TryStrToInt(ACondition, LValue) then
begin
ClienteListView.EDTID.Text := LValue.ToString;
end
else
begin
ClienteListView.EDTRazaoSocial.Text := ACondition;
end;
end;
ClienteListView.BTNPesquisar.OnClick(nil);
if (DataSource.DataSet.Active) and (DataSource.DataSet.RecordCount = 1) then
begin
IDReturnSearch := DataSource.DataSet.FieldByName('ID').AsInteger;
end
else
begin
ClienteListView.ModoViewList := mvlSearch;
ClienteListView.ShowModal;
end;
if IDReturnSearch > 0 then
begin
Result := Controller.DAO.Find(IDReturnSearch);
end;
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.Attributes;
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.Rtti,
System.SysUtils,
{$ELSE}
Rtti,
SysUtils,
{$ENDIF}
DUnitX.Types,
DUnitX.InternalDataProvider;
type
/// <summary>
/// A class decorated with this attribute will be tested. The parameters
/// allow you to control which methods are treated as tests. By default
/// only methods decorated with the Test attribute are run as tests.
/// </summary>
TestFixtureAttribute = class(TCustomAttribute)
private
FName : string;
FDescription : string;
public
constructor Create;overload;
constructor Create(const AName : string);overload;
constructor Create(const AName : string; const ADescription : string);overload;
property Name : string read FName;
property Description : string read FDescription;
end;
/// <summary>
/// A TestFixture decorated with this attribute will be tested using it's
/// own thread. This can speed up unit testing when fixtures do not
/// compete for resources and the test machine has enough cores to service
/// the tests.
/// </summary>
/// <remarks>
/// NOTE - CURRENTLY PLANNED BUT NOT IMPLEMENTED!!!
/// </remarks>
TestInOwnThreadAttribute = class(TCustomAttribute)
end;
/// <summary>
/// A method marked with this attribute will run before any tests in. Note
/// that if more than one method is decorated with this attribute the first
/// method found will be executed (not recommended!).
/// </summary>
SetupFixtureAttribute = class(TCustomAttribute)
end;
/// <summary>
/// A method on a test fixture decorated with this attribute will run
/// before each test method is run. Note that if more than one method is
/// decorated with this attribute the first method found will be executed
/// (not recommended!).
/// </summary>
SetupAttribute = class(TCustomAttribute)
end;
/// <summary>
/// A method on a test fixture class decorated with this attribute will be
/// run after each test method is run. Note that if more than one method is
/// decorated with this attribute the first method found will be executed
/// (not recommended!).
/// </summary>
TearDownAttribute = class(TCustomAttribute)
end;
/// <summary>
/// A method marked with this attribute can contain a teardown method that
/// will be run after each all tests in the fixture have executed. Note
/// that if more than one method is decorated with this attribute the first
/// method found will be executed (not recommended!).
/// </summary>
TearDownFixtureAttribute = class(TCustomAttribute)
end;
/// <summary>
/// This attribue is applied to test methods. If a test is successful and
/// produces a memory leak it will be reported. If you do not want the
/// leak reported, then you can add this attribute to the test method.
/// </summary>
IgnoreMemoryLeaks = class(TCustomAttribute)
private
FIgnoreMemoryLeaks : Boolean;
public
constructor Create(const AIgnoreMemoryLeaks : Boolean = True);
property IgnoreLeaks : Boolean read FIgnoreMemoryLeaks;
end;
/// <summary>
/// Marks a test method to fail after the time specified.
/// Currently only support on Win32 & Win64
/// </summary>
/// <remarks>
/// If [MaxTime(1000)] used then the test will fail if the
/// test takes longer than 1000ms
/// </remarks>
MaxTimeAttribute = class(TCustomAttribute)
private
FMaxTime : Cardinal;
public
constructor Create(const AMaxTime : Cardinal);
property MaxTime : Cardinal read FMaxTime;
end;
/// <summary>
/// This attribute marks a method as a test method
/// </summary>
TestAttribute = class(TCustomAttribute)
private
FEnabled : boolean;
public
constructor Create;overload;
constructor Create(const AEnabled : boolean);overload;
property Enabled : boolean read FEnabled;
end;
/// <summary>
/// This attribute allows you to specify a test Category which can be used
/// when filtering the tests to run.
/// </summary>
CategoryAttribute = class(TCustomAttribute)
private
FCategory : string;
public
constructor Create(const ACategory : string);
property Category : string read FCategory;
end;
/// <summary>
/// This attribute will prevent a test from being run. It will still show
/// up in the lists of tests, and reported as an Ignored test
/// </summary>
/// <remarks>
/// This is useful when you need to temporarily stop a test from running.
/// </remarks>
IgnoreAttribute = class(TCustomAttribute)
private
FReason : string;
public
constructor Create(const AReason : string = '');
property Reason : string read FReason;
end;
/// <summary>
/// Marks a test method to be repeated count times.
/// </summary>
/// <remarks>
/// If [RepeatTest(0)] used then the test will be skipped and behaves like
/// IgnoreAttribute
/// </remarks>
RepeatTestAttribute = class(TCustomAttribute)
private
FCount : Cardinal;
public
constructor Create(const ACount : Cardinal);
property Count : Cardinal read FCount;
end;
/// <summary>
/// This attribute marks a method as a test method which will raise an exception.
/// </summary>
/// <remarks>
/// If [WillRaise(ERangeError)] is used then the test will fail if it
/// does not raise an ERangeError.
/// </remarks>
WillRaiseAttribute = class(TCustomAttribute)
private
FExpectedException : ExceptClass;
FExceptionInheritance: TExceptionInheritance;
public
constructor Create(AExpectedException : ExceptClass; const AInheritance : TExceptionInheritance = exExact);
property ExpectedException : ExceptClass read FExpectedException;
property ExceptionInheritance : TExceptionInheritance read FExceptionInheritance;
end;
/// <summary>
/// Internal Structure used for those implementing CustomTestCase or
/// CustomTestCaseSource descendants.
/// </summary>
TestCaseInfo = record
/// <summary>
/// Name of the Test Case
/// </summary>
Name : string;
/// <summary>
/// Values that will be passed to the method being tested.
/// </summary>
Values : TValueArray;
end;
TestCaseInfoArray = TArray<TestCaseInfo>;
/// <summary>
/// Base class for all Test Case Attributes.
/// </summary>
/// <remarks>
/// Class is abstract and should never be, used to annotate a class as a
/// attribute. Instead use a descendant, that implements the GetCaseInfo
/// method.
/// </remarks>
CustomTestCaseAttribute = class abstract(TCustomAttribute)
protected
function GetCaseInfo : TestCaseInfo; virtual; abstract;
public
property CaseInfo : TestCaseInfo read GetCaseInfo;
end;
/// <summary>
/// Base class for all Test Case Source Attributes.
/// </summary>
/// <remarks>
/// <para>
/// Class is abstract and should never be, used to annotate a class as
/// a attribute. Instead use a descendant, that implements the
/// GetCaseInfoArray method.
/// </para>
/// <para>
/// Note: If a method is annotated with a decendant of
/// TestCaseSourceAttribute and returns an empty TestCaseInfoArray,
/// then no test will be shown for the method.
/// </para>
/// </remarks>
CustomTestCaseSourceAttribute = class abstract(TCustomAttribute)
protected
function GetCaseInfoArray : TestCaseInfoArray; virtual; abstract;
public
property CaseInfoArray : TestCaseInfoArray read GetCaseInfoArray;
end;
/// <summary>
/// The TestCaseAttribute allows you to pass values to a test function.
/// Each value is delimited in the string, by default the delimiter is ','
/// </summary>
TestCaseAttribute = class(CustomTestCaseAttribute)
protected
FCaseInfo : TestCaseInfo;
function GetCaseInfo : TestCaseInfo; override;
function GetName: string;
function GetValues: TValueArray;
public
constructor Create(const ACaseName : string; const AValues : string; const ASeparator : string = ','; const ATrimValues : boolean = false);
property Name : String read GetName;
property Values : TValueArray read GetValues;
end;
/// <summary>
/// TestCaseProvider Attribute allows you, to pass a registered
/// Class to the Test, that provides the test function width the
/// needed data.
/// </summary>
TestCaseProviderAttribute = Class(TCustomAttribute)
protected
FName : string;
FClass : TTestDataProviderClass;
public
constructor Create(const providerName : string);overload;
constructor Create(const AClass : TTestDataProviderClass);overload;
property ProviderName : string read Fname;
property ProviderClass: TTestDataProviderClass read FClass;
end;
implementation
uses
{$IFDEF USE_NS}
System.Types,
System.StrUtils,
{$ELSE}
Types,
StrUtils,
{$ENDIF}
DUnitX.Utils;
{ TestFixture }
constructor TestFixtureAttribute.Create;
begin
inherited;
end;
constructor TestFixtureAttribute.Create(const AName: string);
begin
inherited Create;
FName := AName;
end;
constructor TestFixtureAttribute.Create(const AName: string; const ADescription : string);
begin
inherited Create;
FName := AName;
FDescription := ADescription;
end;
{ IgnoreMemoryLeaks }
constructor IgnoreMemoryLeaks.Create(const AIgnoreMemoryLeaks: Boolean);
begin
inherited Create;
FIgnoreMemoryLeaks := AIgnoreMemoryLeaks;
end;
{ TestAttribute }
constructor TestAttribute.Create;
begin
inherited;
FEnabled := True;
end;
constructor TestAttribute.Create(const AEnabled: boolean);
begin
inherited Create;
FEnabled := AEnabled;
end;
{ CategoryAttribute }
constructor CategoryAttribute.Create(const ACategory: string);
begin
inherited Create;
FCategory := ACategory;
end;
{ IgnoreAttribute }
constructor IgnoreAttribute.Create(const AReason: string);
begin
inherited Create;
FReason := AReason;
end;
{ RepeatTestAttribute }
constructor RepeatTestAttribute.Create(const ACount: Cardinal);
begin
inherited Create;
FCount := ACount;
end;
{ TestCaseAttribute }
constructor TestCaseAttribute.Create(const ACaseName: string; const AValues: string;const ASeparator : string; const ATrimValues : boolean);
var
i: Integer;
l : integer;
lValues : TStringDynArray;
begin
inherited Create;
FCaseInfo.Name := ACaseName;
lValues := SplitString(AValues,ASeparator);
l := Length(lValues);
SetLength(FCaseInfo.Values,l);
for i := 0 to l -1 do
begin
if ATrimValues then
FCaseInfo.Values[i] := TValue.From<string>(Trim(lValues[i]))
else
FCaseInfo.Values[i] := TValue.From<string>(lValues[i]);
end;
end;
function TestCaseAttribute.GetCaseInfo: TestCaseInfo;
begin
Result := FCaseInfo;
end;
function TestCaseAttribute.GetName: String;
begin
Result := FCaseInfo.Name;
end;
function TestCaseAttribute.GetValues: TValueArray;
begin
Result := FCaseInfo.Values;
end;
{ MaxTimeAttribute }
constructor MaxTimeAttribute.Create(const AMaxTime : Cardinal);
begin
inherited Create;
FMaxTime := AMaxTime;
end;
{ WillRaiseAttribute }
constructor WillRaiseAttribute.Create(AExpectedException: ExceptClass; const AInheritance: TExceptionInheritance);
begin
inherited Create;
FExpectedException := AExpectedException;
FExceptionInheritance := AInheritance;
end;
{ TestCaseProviderAttribute }
constructor TestCaseProviderAttribute.Create(const providerName : string);
begin
inherited Create;
FName := ProviderName;
FClass := NIL;
end;
constructor TestCaseProviderAttribute.Create(const AClass: TTestDataProviderClass);
begin
inherited Create;
FName := '';
FClass := AClass;
end;
end.
|
{TSP.inp
4
0 20 35 10
20 0 90 50 >> 1 > 2 > 4 > 3 > 1
35 90 0 12
10 50 12 0 }
Program TravellingSellsmanProblem;
Uses Crt;
Const
MAXN = 20;
MAXVALUE = 1000000;
FI = 'TSP.inp';
FO = 'TSP.out';
Var
graph: Array[1..MAXN, 1..MAXN] Of Longint;
n: Integer; // number of citys
x, bestSolution: Array[1..MAXN] Of Integer; // results
avail: Array[1..MAXN] Of Boolean; // check free city (true)
sum, best: Longint; // total costs
Procedure Init;
Begin
FillChar(graph, n*Sizeof(graph[1]), 0);
FillChar(avail, n*Sizeof(avail[1]), True);
// begin at city 1
x[1] := 1;
avail[1] := False;
best := MAXVALUE;
End;
Procedure ReadFile;
Var
f: Text;
i, j: Integer;
Begin
Assign(f, FI);
Reset(f);
Readln(f, n);
Init;
For i := 1 To n Do
For j := 1 To n Do
read(f, graph[i, j]);
Close(f);
End;
Procedure PrintResult;
Var
i: Integer;
f: Text;
Begin
// To screen
For i := 1 To n Do
Write(bestSolution[i], ' > ');
Writeln(bestSolution[1]);
// To file
Assign(f, FO);
ReWrite(f);
For i := 1 To n Do
Write(f, bestSolution[i], ' > ');
Writeln(f, bestSolution[1]);
Close(f);
End;
Procedure Update;
Begin
If sum + graph[x[n], x[1]] < best Then
Begin
best := sum;
bestSolution := x;
End;
End;
Procedure BranchBound(i: Integer);
Var
j: Integer;
Begin
If sum >= best Then Exit;
For j := 1 To n Do
If avail[j] Then
Begin
// Try j
x[i] := j;
avail[j] := False;
sum := sum + graph[x[i-1], j];
// Check result
If i = n Then
Update
Else
BranchBound(i+1);
// Go back
avail[j] := True;
sum := sum - graph[x[i-1], j];
End;
End;
Begin
Clrscr;
ReadFile;
BranchBound(2);
PrintResult;
Readln;
End. |
unit ItemEditor.Audio;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ItemEditor.Base, StdCtrls, ComCtrls, ExtCtrls, pngimage, Buttons, PngBitBtn;
type
TItemEditorFrame_AUD = class(TItemEditorBaseFrame)
CustomTabSheet: TTabSheet;
CaptionLabel_C1: TLabel;
FormatCombo: TComboBox;
CaptionLabel_C2: TLabel;
InterfaceCombo: TComboBox;
CaptionLabel_C3: TLabel;
ConfigCombo: TComboBox;
MicInCheck: TCheckBox;
LineInCheck: TCheckBox;
CoaxicalCheck: TCheckBox;
MIDICheck: TCheckBox;
HDMICheck: TCheckBox;
InstrumentalCheck: TCheckBox;
PhonesCheck: TCheckBox;
DACFreqCombo: TComboBox;
CaptionLabel_C4: TLabel;
CaptionLabel_C5: TLabel;
DACWordCombo: TComboBox;
ADCFreqCombo: TComboBox;
CaptionLabel_C6: TLabel;
CaptionLabel_C7: TLabel;
ADCWordCombo: TComboBox;
protected
procedure Initialize; override;
procedure Finalize; override;
public
procedure GetDataEx(const Data: Pointer); override;
procedure SetDataEx(const Data: Pointer); override;
function GetShortDescription(const ExData: Pointer): String; override;
function GetDescription(const ExData: Pointer): String; override;
end;
implementation
{$R *.dfm}
uses
CCDBv2;
{ TItemEditorFrame_AUD }
procedure TItemEditorFrame_AUD.Finalize;
begin
inherited;
Dispose(PDataStructAudio(FDefaultDataEx));
end;
procedure TItemEditorFrame_AUD.GetDataEx(const Data: Pointer);
begin
with PDataStructAudio(Data)^ do
begin
Format := FormatCombo.ItemIndex;
ConnInterface := InterfaceCombo.ItemIndex;
Channels := ConfigCombo.ItemIndex;
DAC_Freq := DACFreqCombo.ItemIndex;
DAC_Word := DACWordCombo.ItemIndex;
ADC_Freq := ADCFreqCombo.ItemIndex;
ADC_Word := ADCWordCombo.ItemIndex;
PhonesOut := PhonesCheck.Checked;
MicIn := MicInCheck.Checked;
LineIn := LineInCheck.Checked;
Coaxical := CoaxicalCheck.Checked;
HDMI := HDMICheck.Checked;
MIDI := MIDICheck.Checked;
Instrumental := InstrumentalCheck.Checked;
end;
end;
function TItemEditorFrame_AUD.GetDescription(const ExData: Pointer): String;
var
R: PDataStructAudio absolute ExData;
begin
Result := Format('Тип: %s', [AnsiLowerCase(FormatCombo.Items[R^.Format])]) + CRLF;
Result := Result + Format('Интерфейс: %s', [InterfaceCombo.Items[R^.ConnInterface]]) + CRLF;
Result := Result + Format('Конфигурация: %s', [ConfigCombo.Items[R^.Channels]]) + CRLF;
Result := Result + Format('Частота ЦАП: %s', [DACFreqCombo.Items[R^.DAC_Freq]]) + CRLF;
Result := Result + Format('Разрядность ЦАП: %s', [DACWordCombo.Items[R^.DAC_Word]]) + CRLF;
Result := Result + Format('Частота АЦП: %s', [ADCFreqCombo.Items[R^.ADC_Freq]]) + CRLF;
Result := Result + Format('Разрядность АЦП: %s', [ADCWordCombo.Items[R^.ADC_Word]]);
{ ... }
end;
function TItemEditorFrame_AUD.GetShortDescription(const ExData: Pointer): String;
var
R: PDataStructAudio absolute ExData;
begin
Result := FormatCombo.Items[R^.Format] + #44#32;
Result := Result + ConfigCombo.Items[R^.Channels] + #44#32;
Result := Result + DACFreqCombo.Items[R^.DAC_Freq] + #44#32;
Result := Result + DACWordCombo.Items[R^.DAC_Word] + #44#32;
Result := Result + InterfaceCombo.Items[R^.ConnInterface];
end;
procedure TItemEditorFrame_AUD.Initialize;
begin
inherited;
New(PDataStructAudio(FDefaultDataEx));
GetDataEx(PDataStructAudio(FDefaultDataEx));
with VendorCombo.Items do
begin
Add('ASUS');
Add('Audiotrak');
Add('Creative');
Add('E-MU');
Add('Genius');
Add('Terratec');
Add('VIA');
end;
end;
procedure TItemEditorFrame_AUD.SetDataEx(const Data: Pointer);
begin
if not Assigned(Data) then Exit;
with PDataStructAudio(Data)^ do
begin
FormatCombo.ItemIndex := Format;
InterfaceCombo.ItemIndex := ConnInterface;
ConfigCombo.ItemIndex := Channels;
DACFreqCombo.ItemIndex := DAC_Freq;
DACWordCombo.ItemIndex := DAC_Word;
ADCFreqCombo.ItemIndex := ADC_Freq;
ADCWordCombo.ItemIndex := ADC_Word;
PhonesCheck.Checked := PhonesOut;
MicInCheck.Checked := MicIn;
LineInCheck.Checked := LineIn;
CoaxicalCheck.Checked := Coaxical;
HDMICheck.Checked := HDMI;
MIDICheck.Checked := MIDI;
InstrumentalCheck.Checked := Instrumental;
end;
end;
end.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
CIRFileNameTEdit: TEdit;
Label1: TLabel;
CIRFileNameTButton: TButton;
WriteComponentNameFileTButton: TButton;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
Memo1: TMemo;
Label2: TLabel;
ReadCIRFileTButton: TButton;
procedure CIRFileNameTButtonClick(Sender: TObject);
procedure WriteComponentNameFileTButtonClick(Sender: TObject);
procedure ReadCIRFileTButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses ComponentNameExtract;
procedure TForm1.CIRFileNameTButtonClick(Sender: TObject);
begin
OpenDialog1.InitialDir := ExtractFilePath( ParamStr(0) );
OpenDialog1.Filter := 'Croc Physics files (*.cir)|*.CIR|All files (*.*)|*.*';
if OpenDialog1.Execute then begin
CIRFileNameTEdit.Text := OpenDialog1.FileName;
end;
end;
procedure TForm1.ReadCIRFileTButtonClick(Sender: TObject);
var
Input : TStringlist;
begin
Input := TStringlist.Create;
try
Input.LoadFromFile( CIRFileNameTEdit.Text );
ExtractCrocPhysicsComponentNames( Input, Memo1.Lines );
finally
Input.Free;
end;
end;
procedure TForm1.WriteComponentNameFileTButtonClick(Sender: TObject);
begin
SaveDialog1.InitialDir := ExtractFilePath( CIRFileNameTEdit.Text );
SaveDialog1.Filter := 'Text Files (*.txt)|*.TXT|All Files (*.*)|*.*';
if SaveDialog1.Execute then begin
Memo1.Lines.SaveToFile( SaveDialog1.FileName );
end;
end;
end.
|
unit Report_Badm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorReport, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, dsdAddOn,
ChoicePeriod, Vcl.Menus, dxBarExtItems, dxBar, cxClasses, dsdDB,
Datasnap.DBClient, dsdAction, Vcl.ActnList, cxPropertiesStore, cxLabel,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, Vcl.ExtCtrls, cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, cxPC, dsdGuides, cxButtonEdit, cxCurrencyEdit, dxSkinsCore,
dxSkinsDefaultPainters, dxSkinscxPCPainter, cxPCdxBarPopupMenu,
dxSkinsdxBarPainter, cxCheckBox;
type
TReport_BadmForm = class(TAncestorReportForm)
dxBarButton1: TdxBarButton;
actRefreshStart: TdsdDataSetRefresh;
GoodsName: TcxGridDBColumn;
ExecuteDialog: TExecuteDialog;
bbExecuteDialog: TdxBarButton;
actPrint: TdsdPrintAction;
bbPrint: TdxBarButton;
actOpenFormUnit: TdsdOpenForm;
bbOpenFormUnit: TdxBarButton;
actOpenFormGoodsPartner: TdsdOpenForm;
bbOpenFormUnitBadm: TdxBarButton;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Report_BadmForm: TReport_BadmForm;
implementation
{$R *.dfm}
initialization
RegisterClass(TReport_BadmForm)
end.
|
unit TaxCorrectiveMovementItemTest;
interface
uses dbMovementItemTest, dbTest, ObjectTest;
type
TTaxCorrectiveMovementItemTest = class(TdbTest)
protected
procedure SetUp; override;
// возвращаем данные для тестирования
published
// загрузка процедура из определенной директории
procedure ProcedureLoad; virtual;
procedure Test; virtual;
end;
TTaxCorrectiveMovementItem = class(TMovementItemTest)
private
function InsertDefault: integer; override;
public
function InsertUpdateTaxCorrectiveMovementItem
(Id, MovementId, GoodsId: Integer; Amount, Price, CountForPrice: double; GoodsKindId: Integer): integer;
constructor Create; override;
end;
implementation
uses UtilConst, Db, SysUtils, PersonalTest, dbMovementTest, UnitsTest,
Storage, Authentication, TestFramework, CommonData, dbObjectTest,
Variants, dbObjectMeatTest, TaxCorrectiveTest, GoodsTest;
{ TTaxCorrectiveMovementItemTest }
procedure TTaxCorrectiveMovementItemTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'MovementItem\TaxCorrective\';
inherited;
ScriptDirectory := ProcedurePath + 'Movement\TaxCorrective\';
inherited;
end;
procedure TTaxCorrectiveMovementItemTest.SetUp;
begin
inherited;
TAuthentication.CheckLogin(TStorageFactory.GetStorage, 'Админ', 'Админ', gc_User);
end;
function TTaxCorrectiveMovementItem.InsertDefault: integer;
var Id, MovementId, GoodsId: Integer;
Amount, AmountPartner, Price, CountForPrice,
HeadCount: double;
PartionGoods:String;
GoodsKindId, AssetId: Integer;
begin
Id:=0;
MovementId:= TTaxCorrective.Create.GetDefault;
GoodsId:=TGoods.Create.GetDefault;
Amount:=10;
AmountPartner:=11;
Price:=2.34;
CountForPrice:=1;
HeadCount:=5;
PartionGoods:='';
GoodsKindId:=0;
AssetId:=0;
//
result := InsertUpdateTaxCorrectiveMovementItem(Id, MovementId, GoodsId, Amount, Price, CountForPrice, GoodsKindId);
end;
procedure TTaxCorrectiveMovementItemTest.Test;
var TaxCorrectiveMovementItem: TTaxCorrectiveMovementItem;
Id: Integer;
begin
inherited;
// Создаем документ
TaxCorrectiveMovementItem := TTaxCorrectiveMovementItem.Create;
Id := TaxCorrectiveMovementItem.InsertDefault;
// создание документа
try
// редактирование
finally
TaxCorrectiveMovementItem.Delete(Id);
end;
end;
{ TTaxCorrectiveMovementItem }
constructor TTaxCorrectiveMovementItem.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_MovementItem_TaxCorrective';
end;
function TTaxCorrectiveMovementItem.InsertUpdateTaxCorrectiveMovementItem
(Id, MovementId, GoodsId: Integer; Amount, Price, CountForPrice: double; GoodsKindId: Integer): integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inMovementId', ftInteger, ptInput, MovementId);
FParams.AddParam('inGoodsId', ftInteger, ptInput, GoodsId);
FParams.AddParam('inAmount', ftFloat, ptInput, Amount);
FParams.AddParam('inPrice', ftFloat, ptInput, Price);
FParams.AddParam('ioCountForPrice', ftFloat, ptInput, CountForPrice);
FParams.AddParam('inGoodsKindId', ftInteger, ptInput, GoodsKindId);
result := InsertUpdate(FParams);
end;
initialization
// TestFramework.RegisterTest('Строки Документов', TTaxCorrectiveMovementItemTest.Suite);
end.
|
unit uLog;
interface
procedure sLog (aLogFileName: String; aMessage : String;
aLevel : integer = 1 ;
aRewrite : boolean = false ;
aIncludeDateTime : boolean=true ) ;
var
LogLevel : integer = 3 ;
EnableMessages : boolean = true ;
LogFileName : String ;
// 1 - мегаважный
// 2 - информационный (запустился, ...)
// 3 - отладочный
implementation
uses SysUtils, Vcl.Dialogs, DateUtils;
procedure sLog (aLogFileName: String; aMessage : String;
aLevel : integer = 1 ;
aRewrite : boolean = false ;
aIncludeDateTime : boolean=true ) ;
var
Y,M,D,H,Min,Sec,MSec : word ;
LF : Text ;
S : String ;
//S1 : String ;
N : TDateTime ;
begin
{$I-}
if aLogFileName='' then aLogFileName:=LogFileName ;
if aLevel<= LogLevel then
begin
S:='' ;
AssignFile(LF,aLogFileName) ;
if FileExists(aLogFileName) then
begin
if aRewrite then Rewrite(LF) else append(LF) ;
if IOResult<>0 then
if EnableMessages then
ShowMessage('error appending message ' + aMessage) ;
end
else
begin
rewrite(LF) ;
if IOResult<>0 then
if EnableMessages then
ShowMessage('error rewriting message ' + aMessage) ;
end ;
if aIncludeDateTime then
begin
N:=Now ;
DecodeDateTime(N,Y,M,D,H,Min,Sec,MSec);
//S1:=' [' + IntToStr(MSec)+ '] ' ;
//while Length(S1) <7 do S1:=S1+' ' ;
//S:=DateTimeToStr(N) + S1 ;
S:=DateTimeToStr(N) + ' ';
end;
S:=S + aMessage ;
writeln(LF,S) ;
if IOResult<>0 then
if EnableMessages then
ShowMessage('error writing message ' + aMessage) ;
closeFile(LF) ;
if IOResult<>0 then
if EnableMessages then ShowMessage('error closing message ' + aMessage) ;
end ;
{$I+}
end ;
end. |
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.ORM.App.Config
Description : Load/Save config from/to JSON file
Author : Kike Pérez
Version : 1.2
Created : 26/01/2017
Modified : 08/05/2019
This file is part of QuickORM: https://github.com/exilon/QuickORM
Uses Synopse mORMot framework. Copyright (C) 2017 Arnaud Bouchez
Synopse Informatique - https://synopse.info
***************************************************************************
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.ORM.App.Config;
{$i QuickORM.inc}
interface
uses
Classes,
SysUtils,
mORMot,
SynCommons,
SynCrypto;
type
TORMAppConfig = class(TSQLRecord)
private
fConfigFile : RawUTF8;
fConfigEncrypted : Boolean;
fConfigPassword : RawUTF8;
public
property ConfigFile : RawUTF8 read fConfigFile write fConfigFile;
property ConfigEncrypted : Boolean read fConfigEncrypted write fConfigEncrypted;
property ConfigPassword : RawUTF8 read fConfigPassword write fConfigPassword;
function Load(CreateIfNotExists : Boolean = False) : Boolean;
function Save : Boolean;
end;
{Usage: create a descend class from TORMAppConfig and add published properties to be loaded/saved
TMyConfig = class(TORMAppConfig)
private
fName : RawUTF8;
fSurname : RawUTF8;
fStatus : Integer;
published
property Name : RawUTF8 read fName write fName;
property SurName : RawUTF8 read fSurname write fSurname;
property Status : Integer read fStatus write fStatus;
end;
}
implementation
{ TORMAppConfig }
function TORMAppConfig.Load(CreateIfNotExists : Boolean = False) : Boolean;
var
tmp : RawUTF8;
begin
if (CreateIfNotExists) and (not FileExists(fConfigFile)) then
begin
Self.Save;
Result := False;
end;
try
if fConfigEncrypted then
begin
tmp := AnyTextFileToRawUTF8(fConfigFile,true);
if tmp <> '' then
begin
tmp := AESSHA256(tmp,fConfigPassword,False);
RemoveCommentsFromJSON(pointer(tmp));
JSONToObject(Self,pointer(tmp),result,nil,[]);
end;
end
else
begin
Result := JSONFileToObject(fConfigFile,Self);
end;
except
on e : Exception do raise e;
end;
end;
function TORMAppConfig.Save : Boolean;
var
json : RawUTF8;
begin
try
if fConfigEncrypted then
begin
json := ObjectToJSON(Self);
json := AESSHA256(json,fConfigPassword,True);
Result := FileFromString(json,fConfigFile);
end
else
begin
Result := ObjectToJSONFile(Self,fConfigFile);
end;
except
on e : Exception do raise e;
end;
end;
end.
|
object FormLinkComments: TFormLinkComments
Left = 539
Top = 178
ActiveControl = btnOK
BorderIcons = [biSystemMenu]
BorderStyle = bsSingle
Caption = 'Carry Over Comments'
ClientHeight = 130
ClientWidth = 270
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
PixelsPerInch = 96
TextHeight = 13
object pnlHeading: TPanel
Left = 0
Top = 0
Width = 270
Height = 130
BevelOuter = bvNone
TabOrder = 0
object lblHeading: TLabel
Left = 10
Top = 15
Width = 250
Height = 15
AutoSize = False
Caption = '&Enter a section heading for your comments:'
FocusControl = fldHeading
end
object btnOK: TButton
Left = 102
Top = 100
Width = 75
Height = 25
Action = actOK
Default = True
ModalResult = 1
TabOrder = 2
OnClick = btnOKClick
OnKeyDown = btnOKKeyDown
end
object btnCancel: TButton
Left = 185
Top = 100
Width = 75
Height = 25
Action = actCancel
Cancel = True
ModalResult = 2
TabOrder = 3
end
object fldHeading: TEdit
Left = 10
Top = 37
Width = 250
Height = 21
TabOrder = 0
end
object fldAsk: TCheckBox
Left = 20
Top = 67
Width = 240
Height = 19
Caption = '&Always use this heading for this cell.'
TabOrder = 1
end
end
object slHeading: TActionList
Left = 9
Top = 96
object actCancel: TAction
Caption = '&Cancel'
OnExecute = actCancelExecute
end
object actOK: TAction
Caption = '&OK'
OnUpdate = actOKUpdate
end
end
end
|
{
Модуль отвечает за непоследственный обмен данных между устройствами
Каждый объект создает поток событий, который отслеживает изменения как на
коммуникационном устройстве, так и действия пользователя: отправить данные,
прервать коммуникационного устройства.
Имеется потокобезопасный буфер обмена и количество записанных в него байт
данных.
Как только в буфере появились данные, с помощью метода SetSend сигнализируется
о необходимости отправки данных.
Если данные успешно отправлены, то возникает взводится событие WaitSentEvent.
Как только в устройстве появились данные для чтения, они записываются в буфер
обмена.
Если есть данные в буфере чтения, сигнализиет ожидающему объекту об этом с
помощью WaitReadyReadEvent.
Объекты также создают, закрывают поток событий и соединение с устройством.
Об активности объекта можно узнать с помощью флага IsConnected
}
unit uCommunication;
{$mode objfpc}{$H+}
//{$DEFINE DEBUG}// Альтернатива -dDEBUG
{$C+}// Альтернатива Включить Assert
interface
uses
Classes, SysUtils,
Windows,
Winsock2,
uBase,
uModbus;
type
{$REGION TCommunication}
{ TCommunication }
{
Реализует взаимодействие с устройством
}
TCommunication = class(TClipboard, ICommunication)
private
// Событие ожидания отправки данных на устройство
fSentEvent: THandle;
// Событие ожидания записи во внутренний буфер обмена
fReadyReadEvent: THandle;
protected
// Флаг активности потока: 1 - активен, 0 - нет
fActive: Integer;
protected
procedure DoSend; virtual; abstract;
procedure DoRecv; virtual; abstract;
function GetSentEvent: THandle;
function GetReadyReadEvent: THandle;
public
constructor Create;
destructor Destroy; override;
public
// Выполняется на стороне класса-клиента.
// Сигнализирует о необходимости отправить данные.
procedure NotifyToSend; virtual; abstract;
procedure Connect; virtual; abstract;
procedure Disconnect; virtual; abstract;
function IsConnected: Boolean; virtual;
// Событие ожидания отправки данных на устройство
property SentEvent: THandle read GetSentEvent;
// Событие ожидания записи во внутренний буфер обмена
property ReadyReadEvent: THandle read GetReadyReadEvent;
end;
{$ENDREGION TCommunication}
{$REGION TStubCommunication - класс-заглушка для тестирования контроллера}
{ TStubCommunication }
TStubCommunication = class(TCommunication)
protected
procedure DoSend; override;
procedure DoRecv; override;
public
// Выполняется на стороне класса-клиента.
// Сигнализируем о необходимости отправить данные.
procedure NotifyToSend; override;
procedure Connect; override;
procedure Disconnect; override;
end;
{$ENDREGION TStubCommunication - класс-заглушка для тестирования контроллера}
{$REGION TTcpCommunication}
{ TTcpCommunication }
TTcpCommunication = class(TCommunication, ITcpCommunication)
private
fTcpConnection: ITcpConnection;
fEventLoop: TThreadId;
// События нити
// fEvents[0] используется для остановки нити
// fEvents[1] используется для отправки сообщения
// fEvents[2] связывается с событиями FD_READ, FD_WRITE и FD_CLOSE
fEvents: array[0..2] of WSAEvent;
private
procedure CreateEvents;
procedure CloseEvents;
procedure ResetEvents;
protected
function GetTcpConnection: ITcpConnection;
procedure SetTcpConnection(const aTcpConnection: ITcpConnection);
procedure DoSend; override;
procedure DoRecv; override;
public
procedure AfterConstruction; override;
destructor Destroy; override;
public
// Выполняется на стороне класса-клиента.
// Сигнализирует о необходимости отправить данные.
procedure NotifyToSend; override;
procedure Connect; override;
procedure Disconnect; override;
property TcpConnection: ITcpConnection read GetTcpConnection write SetTcpConnection;
end;
{$ENDREGION TTcpCommunication}
{$REGION TRtuCommunication}
{ TRtuCommunication }
TRtuCommunication = class(TCommunication, IRtuCommunication)
private
Mask: dword;
fRtuConnection: IRtuConnection;
fEventLoop: TThreadId;
// События нити
fBreakEvent: THandle;
fOverlappedStatus: TOverlapped;
fOverlappedRead: TOverlapped;
fOverlappedWrite: TOverlapped;
private
procedure CreateEvents;
procedure CloseEvents;
procedure ResetEvents;
function WaitForAsync(aOverlapped: POverlapped): dword;
protected
function GetRtuConnection: IRtuConnection;
procedure SetRtuConnection(const aRtuConnection: IRtuConnection);
procedure DoSend; override;
procedure DoRecv; override;
procedure DoStatus;
public
procedure AfterConstruction; override;
destructor Destroy; override;
public
procedure Connect; override;
procedure Disconnect; override;
procedure NotifyToSend; override;
property RtuConnection: IRtuConnection read GetRtuConnection write SetRtuConnection;
end;
{$ENDREGION TTcpCommunication}
implementation
const
ERROR_WSA_CREATE_EVENT = 1;
ERROR_THREAD_ARGUMENT = 2;
ERROR_CREATE_EVENT_LOOP = 3;
ERROR_WSA_EVENT_SELECT = 4;
ERROR_ENUM_NETWORK_EVENT = 5;
ERROR_FD_READ = 6;
ERROR_FD_WRITE = 7;
ERROR_WSA_WAIT_FUNCTION = 8;
ERROR_CONNECTION = 9;
ERROR_WAIT_COMM_EVENT = 10;
ERROR_CREATE_EVENT = 11;
ERROR_WAIT_FUNCTION = 12;
ERROR_OVERPLAPPED = 13;
resourcestring
sERROR_WSA_CREATE_EVENT = 'Ошибка создания сокетного события';
sERROR_THREAD_ARGUMENT = 'Аргумент потока равен nil';
sERROR_CREATE_EVENT_LOOP = 'Ошибка создания потока событий';
sERROR_WSA_EVENT_SELECT = 'Ошибка привязки сокета к событию';
sERROR_ENUM_NETWORK_EVENT = 'Ошибка сброса события';
sERROR_FD_READ = 'Ошибка в событии FD_READ';
sERROR_FD_WRITE = 'Ошибка в событии FD_WRITE';
sERROR_WSA_WAIT_FUNCTION = 'Ошибка функции ожидания событий';
sERROR_CONNECTION = 'Нет соединения';
sERROR_WAIT_COMM_EVENT = 'Ошибка создания ожидаемого события';
sERROR_CREATE_EVENT = 'Ошибка создания события';
sERROR_WAIT_FUNCTION = 'Ошибка ожидания события';
sERROR_OVERPLAPPED = 'Ошибка перекрываемой операции';
{$REGION TCommunication}
{ TCommunication }
function TCommunication.GetReadyReadEvent: THandle;
begin
Result := fReadyReadEvent;
end;
function TCommunication.GetSentEvent: THandle;
begin
Result := fSentEvent;
end;
constructor TCommunication.Create;
begin
inherited Create;
Count := 0;
fSentEvent := CreateEvent(nil, False, False, '');
fReadyReadEvent := CreateEvent(nil, False, False, '');
end;
destructor TCommunication.Destroy;
begin
CloseHandle(fSentEvent);
CloseHandle(fReadyReadEvent);
inherited Destroy;
end;
function TCommunication.IsConnected: Boolean;
begin
Result := Windows.InterlockedCompareExchange(fActive, 0, 0) = 1;
end;
{$ENDREGION TCommunication}
{$REGION TStubCommunication}
{ TStubCommunication }
procedure TStubCommunication.Connect;
begin
Windows.InterLockedExchange(fActive, 1);
end;
procedure TStubCommunication.Disconnect;
begin
Windows.InterLockedExchange(fActive, 0);
end;
procedure TStubCommunication.DoSend;
begin
SetEvent(fSentEvent);
Sleep(10);
DoRecv;
end;
procedure TStubCommunication.DoRecv;
begin
Sleep(10);
SetEvent(fReadyReadEvent);
end;
procedure TStubCommunication.NotifyToSend;
begin
DoSend;
end;
{$ENDREGION TStubCommunication}
{$REGION TTcpCommunication}
{ TTcpCommunication }
function TcpEventLoop(Parameter: Pointer): Integer;
var
TcpCommunication: TTcpCommunication;
NetEvents: TWSANetworkEvents;
begin
Result := 0;
if Parameter = nil then
begin
SetLastError(ERROR_THREAD_ARGUMENT);
Exit;
end;
if not (TObject(Parameter) is TTcpCommunication) then
begin
SetLastError(ERROR_THREAD_ARGUMENT);
Exit;
end;
TcpCommunication := TTcpCommunication(Parameter);
// Флаг активности
Windows.InterLockedExchange(TcpCommunication.fActive, 1);
try
repeat
case WSAWaitForMultipleEvents(3, @TcpCommunication.fEvents,
False, WSA_INFINITE, False) of
// Останавливаем нить
WSA_WAIT_EVENT_0: Break;
// Сбрасываем событие и отправляем данные
WSA_WAIT_EVENT_0 + 1:
begin
WSAResetEvent(TcpCommunication.fEvents[1]);
TcpCommunication.DoSend;
end;
// Произошло событие, связанное с сокетом
WSA_WAIT_EVENT_0 + 2:
begin
// Cбрасываем его
if WSAEnumNetworkEvents(TcpCommunication.TcpConnection.Sock,
TcpCommunication.fEvents[2], @NetEvents) = SOCKET_ERROR then
begin
TcpCommunication.SetLastError(ERROR_ENUM_NETWORK_EVENT);
Break;
end;
// Произошло событие - чтение из буфера сокета
if NetEvents.lNetworkEvents and FD_READ <> 0 then
begin
// Есть ли ошибка
if NetEvents.iErrorCode[FD_READ_BIT] <> 0 then
begin
TcpCommunication.SetLastError(ERROR_FD_READ);
Break;
end;
// Читаем данные из буфера сокет в свой буфер
TcpCommunication.DoRecv;
Continue;
end;
// Сокет готов к передаче данных
if NetEvents.lNetworkEvents and FD_WRITE <> 0 then
begin
if NetEvents.iErrorCode[FD_WRITE_BIT] <> 0 then
begin
TcpCommunication.SetLastError(ERROR_FD_WRITE);
Break;
end;
// Отправляем то, что лежит в буфере
TcpCommunication.DoSend;
Continue;
end;
// Клиент закрыл соединение
if NetEvents.lNetworkEvents and FD_CLOSE <> 0 then
Break;
end;
else
begin
TcpCommunication.SetLastError(ERROR_WSA_WAIT_FUNCTION);
Break;
end;
end;
Sleep(10);
until False;
finally
Windows.InterLockedExchange(TcpCommunication.fActive, 0);
end;
end;
procedure TTcpCommunication.AfterConstruction;
begin
inherited AfterConstruction;
// Карта ошибок
fErrors.Add(ERROR_WSA_CREATE_EVENT, sERROR_WSA_CREATE_EVENT);
fErrors.Add(ERROR_THREAD_ARGUMENT, sERROR_THREAD_ARGUMENT);
fErrors.Add(ERROR_CREATE_EVENT_LOOP, sERROR_CREATE_EVENT_LOOP);
fErrors.Add(ERROR_WSA_EVENT_SELECT, sERROR_WSA_EVENT_SELECT);
fErrors.Add(ERROR_ENUM_NETWORK_EVENT, sERROR_ENUM_NETWORK_EVENT);
fErrors.Add(ERROR_FD_READ, sERROR_FD_READ);
fErrors.Add(ERROR_FD_WRITE, sERROR_FD_WRITE);
fErrors.Add(ERROR_WSA_WAIT_FUNCTION, sERROR_WSA_WAIT_FUNCTION);
fErrors.Add(ERROR_CONNECTION, sERROR_CONNECTION);
// Создание событий
CreateEvents;
end;
destructor TTcpCommunication.Destroy;
begin
Disconnect;
CloseEvents;
inherited Destroy;
end;
procedure TTcpCommunication.Connect;
begin
{$IFDEF DEBUG}
Assert(TcpConnection <> nil);
{$ENDIF}
// Нельзя, если серверное соединение
//Disconnect;
// Открытие соединения
TcpConnection.Open;
if TcpConnection.Sock = INVALID_SOCKET then
begin
fLastError := ERROR_CONNECTION;
Exit;
end;
// Сброс событий
ResetEvents;
// Привязка сокета к событию
if WSAEventSelect(TcpConnection.Sock, fEvents[2], FD_READ or FD_WRITE or FD_CLOSE) =
SOCKET_ERROR then
begin
fLastError := ERROR_WSA_EVENT_SELECT;
Exit;
end;
// Создание потока
fEventLoop := BeginThread(@TcpEventLoop, Self);
if fEventLoop = 0 then
begin
fLastError := ERROR_CREATE_EVENT_LOOP;
Exit;
end;
// Для запуска потока
Sleep(100);
end;
procedure TTcpCommunication.Disconnect;
const
TIMEOUT_CLOSE = 100;
begin
// Закрытие потока
if fEventLoop <> 0 then
begin
WSASetEvent(FEvents[0]);
WaitForThreadTerminate(fEventLoop, TIMEOUT_CLOSE);
CloseThread(fEventLoop);
fEventLoop := 0;
end;
// Закрытие сокета
TcpConnection.Close;
end;
procedure TTcpCommunication.CreateEvents;
begin
// Создаём события
fEvents[0] := WSACreateEvent;
if fEvents[0] = WSA_INVALID_HANDLE then
begin
fLastError := ERROR_WSA_CREATE_EVENT;
Exit;
end;
fEvents[1] := WSACreateEvent;
if fEvents[1] = WSA_INVALID_HANDLE then
begin
fLastError := ERROR_WSA_CREATE_EVENT;
Exit;
end;
fEvents[2] := WSACreateEvent;
if fEvents[2] = WSA_INVALID_HANDLE then
begin
fLastError := ERROR_WSA_CREATE_EVENT;
Exit;
end;
end;
procedure TTcpCommunication.CloseEvents;
begin
WSACloseEvent(fEvents[0]);
WSACloseEvent(fEvents[1]);
WSACloseEvent(fEvents[2]);
end;
procedure TTcpCommunication.ResetEvents;
begin
WSAResetEvent(fEvents[0]);
WSAResetEvent(fEvents[1]);
WSAResetEvent(fEvents[2]);
end;
function TTcpCommunication.GetTcpConnection: ITcpConnection;
begin
Result := fTcpConnection;
end;
procedure TTcpCommunication.SetTcpConnection(const aTcpConnection: ITcpConnection);
begin
fTcpConnection := aTcpConnection;
end;
procedure TTcpCommunication.NotifyToSend;
begin
// Сообщить потоку о необходимости отправки данных
WSASetEvent(fEvents[1]);
end;
procedure TTcpCommunication.DoSend;
var
SentRes: Longint;
begin
Lock;
try
SentRes := WinSock2.Send(TcpConnection.Sock, Buffer[0], Count, 0);
if WSAGetLastError = WSAEWOULDBLOCK then
SentRes := 0;
// Информируем о отправки данных
if (SentRes > 0) then
SetEvent(fSentEvent);
finally
Unlock;
end;
end;
procedure TTcpCommunication.DoRecv;
begin
Lock;
try
// Копируем данные из буфера сокета в свой буфер
Count := WinSock2.Recv(TcpConnection.Sock, Buffer, BUFFER_SIZE, 0);
if WSAGetLastError = WSAEWOULDBLOCK then
Count := 0;
// Информируем о наличии данных в буфере
if (Count > 0) then
SetEvent(fReadyReadEvent);
finally
Unlock;
end;
end;
{$ENDREGION TTcpCommunication}
{$REGION TRtuCommunication}
{ TRtuCommunication }
function RtuEventLoop(aParameter: Pointer): Integer;
var
RtuCommunication: TRtuCommunication;
Events: array [0 .. 1] of THandle;
Mask: dword;
begin
Result := 0;
Mask := EV_RXCHAR or EV_ERR or EV_BREAK or EV_TXEMPTY;
if aParameter = nil then
begin
SetLastError(ERROR_THREAD_ARGUMENT);
Exit;
end;
if not (TObject(aParameter) is TRtuCommunication) then
begin
SetLastError(ERROR_THREAD_ARGUMENT);
Exit;
end;
RtuCommunication := TRtuCommunication(aParameter);
Events[0] := RtuCommunication.fBreakEvent;
Events[1] := RtuCommunication.fOverlappedStatus.hEvent;
// Флаг активности
Windows.InterLockedExchange(RtuCommunication.fActive, 1);
try
repeat
// Маска события
if not SetCommMask(RtuCommunication.RtuConnection.Handle, Mask) then
Break;
// Ожидаем события и пимещаем их в маску
if not WaitCommEvent(RtuCommunication.RtuConnection.Handle,
RtuCommunication.Mask, @RtuCommunication.fOverlappedStatus) then
if GetLastError <> ERROR_IO_PENDING then
Break;
// Ожидаем окончание перекрываемой операции или наступления иных событий
case WaitForMultipleObjects(2, @Events, False, INFINITE) of
// Событие: закрытие потока
WAIT_OBJECT_0:
Break;
// Событие: перекрываемая операция
WAIT_OBJECT_0 + 1:
begin
RtuCommunication.DoStatus;
end
else
begin
RtuCommunication.SetLastError(ERROR_WAIT_FUNCTION);
Break;
end;
end;
until False;
finally
// Флаг активности
Windows.InterLockedExchange(RtuCommunication.fActive, 0);
end;
end;
procedure TRtuCommunication.AfterConstruction;
begin
inherited AfterConstruction;
fErrors.Add(ERROR_WAIT_COMM_EVENT, sERROR_WAIT_COMM_EVENT);
fErrors.Add(ERROR_CREATE_EVENT, sERROR_CREATE_EVENT);
fErrors.Add(ERROR_THREAD_ARGUMENT, sERROR_THREAD_ARGUMENT);
fErrors.Add(ERROR_WAIT_FUNCTION, sERROR_WAIT_FUNCTION);
fErrors.Add(ERROR_OVERPLAPPED, sERROR_OVERPLAPPED);
fErrors.Add(ERROR_CONNECTION, sERROR_CONNECTION);
fErrors.Add(ERROR_CREATE_EVENT_LOOP, sERROR_CREATE_EVENT_LOOP);
CreateEvents;
end;
destructor TRtuCommunication.Destroy;
begin
SetEvent(fBreakEvent);
Disconnect;
CloseEvents;
inherited Destroy;
end;
procedure TRtuCommunication.CreateEvents;
begin
fBreakEvent := CreateEvent(nil, False, False, ''); // Break;
if fBreakEvent = INVALID_HANDLE_VALUE then
begin
fLastError := ERROR_CREATE_EVENT;
Exit;
end;
// Перекрываемая структура
FillChar(fOverlappedStatus, SizeOf(fOverlappedStatus), 0);
fOverlappedStatus.hEvent := CreateEvent(nil, True, False, nil);
if fOverlappedStatus.hEvent = INVALID_HANDLE_VALUE then
begin
fLastError := ERROR_CREATE_EVENT;
Exit;
end;
FillChar(fOverlappedRead, SizeOf(fOverlappedRead), 0);
fOverlappedRead.hEvent := CreateEvent(nil, True, False, nil);
if fOverlappedRead.hEvent = INVALID_HANDLE_VALUE then
begin
fLastError := ERROR_CREATE_EVENT;
Exit;
end;
FillChar(fOverlappedWrite, SizeOf(fOverlappedWrite), 0);
fOverlappedWrite.hEvent := CreateEvent(nil, True, False, nil);
if fOverlappedWrite.hEvent = INVALID_HANDLE_VALUE then
begin
fLastError := ERROR_CREATE_EVENT;
Exit;
end;
end;
procedure TRtuCommunication.CloseEvents;
begin
CloseHandle(fBreakEvent);
CloseHandle(fOverlappedStatus.hEvent);
CloseHandle(fOverlappedRead.hEvent);
CloseHandle(fOverlappedWrite.hEvent);
end;
procedure TRtuCommunication.ResetEvents;
begin
ResetEvent(fBreakEvent);
ResetEvent(fOverlappedStatus.hEvent);
ResetEvent(fOverlappedRead.hEvent);
ResetEvent(fOverlappedWrite.hEvent);
end;
function TRtuCommunication.WaitForAsync(aOverlapped: POverlapped): dword;
var
Events: array [0 .. 1] of THandle;
begin
Result := 0;
Events[0] := fBreakEvent;
Events[1] := aOverlapped^.hEvent;
try
case WaitForMultipleObjects(2, @Events, False, INFINITE) of
WAIT_OBJECT_0:
begin
SetEvent(fBreakEvent);
end;
WAIT_OBJECT_0 + 1:
if not GetOverlappedResult(RtuConnection.Handle, aOverlapped^,
Result, False) then
begin
fLastError := ERROR_OVERPLAPPED;
SetEvent(fBreakEvent);
Result := 0;
end;
else
begin
SetEvent(fBreakEvent);
fLastError := ERROR_WAIT_FUNCTION;
end;
end;
finally
ResetEvent(aOverlapped^.hEvent);
end;
end;
function TRtuCommunication.GetRtuConnection: IRtuConnection;
begin
Result := fRtuConnection;
end;
procedure TRtuCommunication.SetRtuConnection(const aRtuConnection: IRtuConnection);
begin
fRtuConnection := aRtuConnection;
end;
procedure TRtuCommunication.DoStatus;
var
NumberOfBytesTransaffered: dword;
begin
NumberOfBytesTransaffered := WaitForAsync(@fOverlappedStatus);
if NumberOfBytesTransaffered = 0 then
begin
fLastError := ERROR_OVERPLAPPED;
Exit;
end;
// Маска событий прерывания связи
if ((EV_BREAK and Mask) <> 0) or ((EV_ERR and Mask) <> 0) then
begin
fLastError := ERROR_CONNECTION;
SetEvent(fBreakEvent);
Exit;
end;
// Информируем о отправке данных на устройство
if (EV_TXEMPTY and Mask) <> 0 then
begin
SetEvent(fSentEvent);
end;
// Маска события: есть данные в приемном буфере
if (EV_RXCHAR and Mask) <> 0 then
begin
DoRecv;
end;
end;
procedure TRtuCommunication.DoSend;
var
NumberOfBytesWritten: dword;
begin
NumberOfBytesWritten := 0;
Sleep(RtuConnection.ThreeAndHalf);
try
if not WriteFile(RtuConnection.Handle, Buffer^[0], Count,
NumberOfBytesWritten, @fOverlappedWrite) then
if (Windows.GetLastError() <> ERROR_IO_PENDING) then
begin
fLastError := ERROR_OVERPLAPPED;
Exit;
end;
// Ждем окончания перекрываемой операции
NumberOfBytesWritten := WaitForAsync(@fOverlappedWrite);
// Информируем о отправке данных на устройство
//if (Longint(NumberOfBytesWritten) = Count) then
// SetEvent(fSentEvent);
finally
if not PurgeComm(RtuConnection.Handle, PURGE_TXCLEAR) then
SetEvent(fBreakEvent);
end;
end;
procedure TRtuCommunication.DoRecv;
var
NumberOfBytesRead: dword;
begin
NumberOfBytesRead := 0;
try
if not ReadFile(RtuConnection.Handle, Buffer^[0], BUFFER_SIZE,
NumberOfBytesRead, @fOverlappedRead) then
if (Windows.GetLastError() <> ERROR_IO_PENDING) then
begin
SetEvent(fBreakEvent);
fLastError := ERROR_OVERPLAPPED;
Exit;
end;
NumberOfBytesRead := WaitForAsync(@fOverlappedRead);
// Информируем о наличии данных в буфере
if (NumberOfBytesRead > 0) then
begin
Count := NumberOfBytesRead;
SetEvent(fReadyReadEvent);
Exit;
end;
finally
if not PurgeComm(RtuConnection.Handle, PURGE_RXCLEAR) then
SetEvent(fBreakEvent);
end;
end;
procedure TRtuCommunication.Connect;
begin
{$IFDEF DEBUG}
Assert(RtuConnection <> nil);
{$ENDIF}
Disconnect;
// Сброс событий
ResetEvents;
// Открытие соединения
RtuConnection.Open;
if RtuConnection.Handle = INVALID_HANDLE_VALUE then
begin
fLastError := ERROR_CONNECTION;
Exit;
end;
// Создание потока
fEventLoop := BeginThread(@RtuEventLoop, Self);
if fEventLoop = 0 then
begin
fLastError := ERROR_CREATE_EVENT_LOOP;
Exit;
end;
// Для запуска потока
Sleep(100);
end;
procedure TRtuCommunication.Disconnect;
const
TIMEOUT_CLOSE = 100;
begin
// Закрытие потока
if fEventLoop <> 0 then
begin
WaitForThreadTerminate(fEventLoop, TIMEOUT_CLOSE);
CloseThread(fEventLoop);
fEventLoop := 0;
end;
// Закрытие сокета
RtuConnection.Close;
end;
procedure TRtuCommunication.NotifyToSend;
begin
DoSend;
end;
{$ENDREGION TRtuCommunication}
end.
|
unit Entidades.Pedidos;
interface
uses
System.sysutils;
type
TPEDIDO = class
private
FID_PEDIDO: Integer;
FDATA: TDate;
FTOTAL: Real;
FCLIENTE: Integer;
public
constructor Create;
destructor Destroy; override;
published
property ID_PEDIDO: Integer read FID_PEDIDO write FID_PEDIDO;
property DATA: TDate read FDATA write FDATA;
property TOTAL: Real read FTOTAL write FTOTAL;
property CLIENTE: Integer read FCLIENTE write FCLIENTE;
function Validar : Boolean;
end;
implementation
{ TPEDIDO }
constructor TPEDIDO.Create;
begin
end;
destructor TPEDIDO.Destroy;
begin
inherited;
end;
function TPEDIDO.Validar: Boolean;
begin
Result := False;
if FCLIENTE <= 0 then
raise Exception.Create('Informe o cliente.');
Result := True;
end;
end.
|
unit ListUtilsUnit;
interface
uses
System.Classes, Winapi.Windows;
type
{: Базовый класс элемента списка }
TCustomItem = class(TPersistent)
private
FId: Integer;
FName: string;
public
constructor Create(AId: Integer; AName: string); overload;
property Id: Integer read FId write FId;
property Name: string read FName write FName;
end;
{: Базовый класс списка элементов }
TCustomList = class(TPersistent)
private
FList: TList;
FLock: TRTLCriticalSection;
function GetCount: Integer;
function GetItems(Index: Integer): TCustomItem;
function GetLastId: Integer;
function GetLastItem: TCustomItem;
public
constructor Create; overload;
destructor Destroy; override;
function Add(AItem: TCustomItem): TCustomItem;
procedure Clear(AIsFreeItems: Boolean = True); virtual;
procedure DestroyNotClear;
function GetItemById(AId: Integer): TCustomItem;
function GetItemByName(AName: string): TCustomItem;
function LockList: TList;
procedure Remove(AItem: TCustomItem; IsFreeItem: Boolean = False);
procedure Sort(ACompare: TListSortCompare);
procedure UnlockList;
property Count: Integer read GetCount;
property Items[Index: integer]: TCustomItem read GetItems; default;
property LastId: Integer read GetLastId;
property LastItem: TCustomItem read GetLastItem;
end;
implementation
{ TCustomItem }
constructor TCustomItem.Create(AId: Integer; AName: string);
begin
inherited Create;
FId := AId;
FName := AName;
end;
{ TCustomItems }
function TCustomList.Add(AItem: TCustomItem): TCustomItem;
begin
LockList;
try
FList.Add(AItem);
Result := AItem;
finally
UnlockList;
end;
end;
procedure TCustomList.Clear(AIsFreeItems: Boolean);
var
I: Integer;
begin
if Assigned(FList) then
begin
if AIsFreeItems then
for I := FList.Count - 1 downto 0 do
if Assigned(FList[I]) then
begin
TCustomItem(FList[I]).Free;
FList[I] := nil;
end;
FList.Clear;
end;
end;
constructor TCustomList.Create;
begin
inherited Create;
InitializeCriticalSection(FLock);
FList := TList.Create;
end;
destructor TCustomList.Destroy;
begin
Clear;
LockList;
try
FList.Free;
inherited;
finally
UnlockList;
DeleteCriticalSection(FLock);
end;
end;
procedure TCustomList.DestroyNotClear;
begin
LockList;
try
FList.Free;
inherited;
finally
UnlockList;
DeleteCriticalSection(FLock);
end;
end;
function TCustomList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TCustomList.GetItemById(AId: Integer): TCustomItem;
var
I: Integer;
Item: TCustomItem;
begin
Result := nil;
LockList;
try
for I := 0 to Count - 1 do
begin
Item := FList[I];
if Assigned(Item) then
if Item.Id = AId then
begin
Result := Item;
Break;
end;
end;
finally
UnlockList;
end;
end;
function TCustomList.GetItemByName(AName: string): TCustomItem;
var
I: Integer;
Item: TCustomItem;
begin
Result := nil;
LockList;
try
for I := 0 to Count - 1 do
begin
Item := FList[I];
if Assigned(Item) then
if Item.Name = AName then
begin
Result := Item;
Break;
end;
end;
finally
UnlockList;
end;
end;
function TCustomList.GetItems(Index: Integer): TCustomItem;
begin
if Index < FList.Count then
Result := FList[Index] else
Result := nil;
end;
function TCustomList.GetLastId: Integer;
var
I: Integer;
Item: TCustomItem;
begin
Result := 0;
if Assigned(FList) then
begin
LockList;
try
for I := 0 to FList.Count - 1 do
begin
Item := FList[I];
if Result < Item.Id then
Result := Item.Id;
end;
finally
UnlockList;
end;
end;
end;
function TCustomList.GetLastItem: TCustomItem;
begin
Result := GetItemById(LastId);
end;
function TCustomList.LockList: TList;
begin
EnterCriticalSection(FLock);
Result := FList;
end;
procedure TCustomList.Remove(AItem: TCustomItem; IsFreeItem: Boolean);
var
I: Integer;
begin
LockList;
try
for I := 0 to Count - 1 do
if FList[I] = AItem then
begin
if IsFreeItem then
AItem.Free;
FList.Delete(I);
Break;
end;
finally
UnlockList;
end;
end;
procedure TCustomList.Sort(ACompare: TListSortCompare);
begin
FList.Sort(ACompare);
end;
procedure TCustomList.UnlockList;
begin
LeaveCriticalSection(FLock);
end;
end.
|
unit Solvation;
interface
type
TSolveLogProc = procedure (Equation: String) of object;
var
SolveLog: TSolveLogProc;
function Solve(Equation: String): Double;
type
TPresolvedVarData = record
Nom: String;
Value: Double;
end;
var
VarList: array of TPresolvedVarData;
implementation
uses
Math, Randomity, SysUtils, Classes;
function Roll(Dice: LongWord = 1; DieSize: Integer = 6): LongWord;
var
I: Integer;
begin
Result := Dice;
for I := Dice-1 downto 0 do
Inc(Result, RandN(DieSize))
;
end;
procedure TVarRec; begin end;
const
NOpLevel = 5;
type
TToken = record
case IsOp: Boolean of
True: (
Op: Char;
);
False: (
Value: Double;
);
end;
TAT = array of TToken;
function Op2OpLevel(Op: Char): Integer;
begin
case Op of
'+', '-': Result := 0;
'*', '/': Result := 1;
'^': Result := 2;
'''': Result := 3;
'#': Result := 4;
else Result := NOpLevel;
end;
end;
function NewAT(Value: Double): TToken;
begin
Result.IsOp := False;
Result.Value := Value;
end;
{
function GetValue(X: TToken): Double;
begin
if X.IsOp then
raise EParserError.Create('Attempt to take value of operator "' + X.Op + '"')
;
Result := X.Value;
end;
}
function PosNChar(SearchFor: array of Char; SearchIn: String): Integer;
var
I: Integer;
begin
for Result := 1 to Length(SearchIn) do
for I := 0 to High(SearchFor) do
if SearchIn[Result] = SearchFor[I] then
Exit
;
Result := 0;
end;
function RPosNChar(SearchFor: array of Char; SearchIn: String): Integer;
var
I: Integer;
begin
for Result := Length(SearchIn) downto 1 do
for I := 0 to High(SearchFor) do
if SearchIn[Result] = SearchFor[I] then
Exit
;
Result := 0;
end;
function ATCopy(A: TAT; Index, Len: Integer): TAT;
var
I: Integer;
begin
if LongWord(Index) + LongWord(Len) > LongWord(Length(A)) then
Len := Length(A) - Index
;
SetLength(Result, Len);
for I := 0 to Len - 1 do
Result[I] := A[Index + I]
;
end;
function StripChar(S: String; C: Char): String;
var
I, J: Integer;
begin
SetLength(Result, Length(S));
J := 1;
for I := 1 to Length(S) do
if S[I] <> C then begin
Result[J] := S[I];
Inc(J);
end
;
SetLength(Result, J - 1);
end;
function BuildArray(LA: TAT; X: Double; RA: TAT): TAT;
var
I: Integer;
begin
SetLength(Result, Length(LA) + 1 + Length(RA));
for I := 0 to High(LA) do
Result[I] := LA[I]
;
Result[Length(LA)] := NewAT(X);
for I := 0 to High(RA) do
Result[I + Length(LA) + 1] := RA[I]
;
end;
function EquationToStr(X: TAT): String;
function TermToStr(XI: TToken): String;
begin
if XI.IsOp then
Result := XI.Op
else try
Result := FloatToStr(XI.Value);
except
Result := '#?#';
end;
end;
var
I: Integer;
begin
if High(X) < 0 then begin
Result := '';
Exit;
end;
Result := TermToStr(X[0]);
for I := 1 to High(X) do
Result := Result + ' ' + TermToStr(X[I])
;
end;
procedure HandleUnarySign(var Equation: TAT);
var
I, J: Integer;
begin
for I := High(Equation) - 1 downto 0 do
if (Equation[I].IsOp)
and (Equation[I].Op in ['+', '-'])
and (
(I = 0)
or ((Equation[I - 1].IsOp) and (Equation[I - 1].Op <> ')'))
) then begin
if Equation[I].Op = '-' then
Equation[I] := NewAT(-Equation[I + 1].Value)
else
Equation[I] := Equation[I + 1]
;
for J := I + 1 to High(Equation) - 1 do
Equation[J] := Equation[J + 1]
;
Equation := ATCopy(Equation, 0, High(Equation));
end
;
end;
function SolveAT(Equation: TAT): Double;
var
I, J, ThisOpLevel, OpLevel: Integer;
A, B: Double;
begin
if Assigned(SolveLog) then SolveLog(':' + EquationToStr(Equation));
if High(Equation) = -1 then raise EParserError.Create('"" is not a valid floating point value');
if High(Equation) = 0 then begin
if Equation[0].IsOp then raise EParserError.Create('Equation "' + EquationToStr(Equation) + '" contained subequation with no terms');
Result := Equation[0].Value;
Exit;
end;
J := -1;
for I := 0 to High(Equation) do
if Equation[I].IsOp then begin
if Equation[I].Op = '(' then
J := I
else if Equation[I].Op = ')' then begin
if J = -1 then raise EParserError.Create('Unmatched close-parenthesis in "' + EquationToStr(Equation) + '"');
Result := SolveAT(BuildArray(
ATCopy(Equation, 0, J),
SolveAT(ATCopy(Equation, J + 1, I - J - 1)),
ATCopy(Equation, I + 1, MAXINT)
));
Exit;
end;
end
;
if J <> -1 then raise EParserError.Create('Unmatched open-parenthesis in "' + EquationToStr(Equation) + '"');
HandleUnarySign(Equation); //This little inanity prevents an internal compiler error
OpLevel := NOpLevel;
for I := High(Equation) downto 0 do
if Equation[I].IsOp then begin
ThisOpLevel := Op2OpLevel(Equation[I].Op);
if ThisOpLevel < OpLevel then begin
J := I;
OpLevel := ThisOpLevel;
if OpLevel = 0 then Break;
end;
end
;
if OpLevel = NOpLevel then begin
//raise EParserError.Create('"' + EquationToStr(Equation) + '"contained multiple terms and no operators');
if Equation[0].IsOp then raise EParserError.Create('Attempt to take value of operator "' + Equation[0].Op + '"');
Result := Equation[0].Value;
for I := 1 to High(Equation) do
if Equation[I].IsOp then
raise EParserError.Create('Attempt to take value of operator "' + Equation[0].Op + '"')
else
Result := Result * Equation[I].Value
;
Exit;
end;
A := SolveAT(ATCopy(Equation, 0, J));
B := SolveAT(ATCopy(Equation, J + 1, MAXINT));
case Equation[J].Op of
'+': Result := A + B;
'-': Result := A - B;
'*': Result := A * B;
'/': Result := A / B;
'^': Result := Power(A, B);
'''': Result := Roll(Round(A), Round(B));
'#': Result := A * Power(10, B);
else raise EParserError.Create('operator "' + Equation[J].Op + '" encountered');
end;
end;
//TokToFloat is similar to StrToFloat, but it (sort of) handles extra radix formats, and it resolves var names.
function TokToFloat(Tok: String): Real;
var
L, Radix, I, J: Integer;
AntiRadix, Fractional: Real;
begin
L := Length(Tok);
case Tok[1] of
'A'..'Z', 'a'..'z': begin
Tok := UpperCase(Tok);
for I := 0 to High(VarList) do
if VarList[I].Nom = Tok then begin
Result := VarList[I].Value;
Exit;
end;
raise EParserError.Create('Var ' + Tok + ' not found.');
end;
'$': begin
Radix := 16;
AntiRadix := 1/16;
I := 2;
end;
else case Tok[L] of
'h', 'H': begin //Not particularly usable
Radix := 16;
AntiRadix := 1/16;
I := 1;
Dec(L);
SetLength(Tok, L);
end;
'b', 'B': begin //Not particularly usable
Radix := 2;
AntiRadix := 1/2;
I := 1;
Dec(L);
SetLength(Tok, L);
end;
else begin
Radix := 10;
AntiRadix := 1/10;
I := 1;
end;
end;
end;
Result := 0;
repeat
case Tok[I] of
'0'..'9': Result := Result * Radix + (Byte(Tok[I]) and $F);
'A'..'F',
'a'..'f': Result := Result * Radix + (Byte(Tok[I]) and $7 + 9);
//A = 41h, 41h and 7h = 1h, 1h + 9 = 10
'.': Break;
else raise EConvertError.Create('"' + Tok + '" contains invalid character "' + Tok[I] + '".');
end;
Inc(I);
if I > L then Exit;
until False;
//Scan right-to-left for the fractional portion
Fractional := 0;
J := L;
repeat
case Tok[J] of
'0'..'9': Fractional := (Fractional + (Byte(Tok[J]) and $F)) * AntiRadix;
'A'..'F',
'a'..'f': Fractional := (Fractional + (Byte(Tok[J]) and $7 + 9)) * AntiRadix;
//A = 41h, 41h and 7h = 1h, 1h + 9 = 10
'.': Break;
else raise EConvertError.Create('"' + Tok + '" contains invalid character "' + Tok[I] + '".');
end;
Dec(J);
until J < I;
Result := Result + Fractional;
end;
function Tokenize(S: String): TAT;
var
I, L: Integer;
Buf: String;
begin
SetLength(Result, 0);
L := 0;
if S = '' then Exit;
while Length(S) <> 0 do begin
I := PosNChar(['+', '-', '*', '/', '^', '''', '#', '(', ')'], S);
if I = 0 then begin
SetLength(Result, L + 1);
Result[L] := NewAT(TokToFloat(S));
//Inc(L);
Break;
end
else begin
Buf := Copy(S, 1, I - 1);
if Buf <> '' then begin
SetLength(Result, L + 2);
Result[L] := NewAT(TokToFloat(Buf));
Inc(L);
end
else
SetLength(Result, L + 1)
;
Result[L].IsOp := True;
Result[L].Op := S[I];
Inc(L);
S := Copy(S, I + 1, MAXINT);
end;
end;
end;
function Solve(Equation: String): Double;
begin
Result := SolveAT(Tokenize(StripChar(Equation, ' ')));
end;
end.
|
unit UBank;
interface
uses USimulation;
type
// Класс TClient - процесс, моделирующий клиента банка
TClient = class(TProcess)
protected
procedure RunProcess; override;
end;
// Класс TClientGenerator - процесс, порождающий клиентов банка
TClientGenerator = class(TProcess)
protected
procedure RunProcess; override;
end;
// Класс TBankSimulation - моделирование работы банка
TBankSimulation = class(TSimulation)
public
// Ресурс кассира
Cashman : TResource;
// Генератор клиентов
Generator : TClientGenerator;
// Статистика и гистограмма по времени пребывания
// клиентов в банке
InBankTime : TStatistics;
InBankHist : THistogram;
// Счетчик клиентов, обслуженных без ожидания
NotWaited : Integer;
destructor Destroy; override;
procedure StopStat; override;
protected
procedure RunSimulation; override;
procedure Init; override;
end;
var
// Датчики случайных чисел
rndClient : TRandom;
rndCashman : TRandom;
// Количество обслуживаемых клиентов
MaxClientCount : Integer = 100;
// Средний интервал между прибытием клиентов
MeanClientInterval : Double = 5;
// Границы времени обслуживания
MinCashTime : Double = 2;
MaxCashTime : Double = 6;
// Параметры гистограммы
HistMin : Double = 2;
HistStep : Double = 2;
HistStepCount : Integer = 20;
implementation
{ TClient }
procedure TClient.RunProcess;
var
par : TBankSimulation;
InTime : Double;
begin
par := Parent as TBankSimulation;
// Дождаться освобождения кассира
GetResource(par.Cashman);
// Приступить к выполнению действия
// Если клиент не ждал, учесть его
if StartingTime = SimTime then
Inc(par.NotWaited);
// Выполнить обслуживание
Hold(rndCashman.Uniform(MinCashTime, MaxCashTime));
// Учесть полное время пребывания в банке
InTime := SimTime - StartingTime;
par.InBankTime.AddData(InTime);
par.InBankHist.AddData(InTime);
// Если все клиенты обслужены, завершить работу
if par.InBankTime.Count = MaxClientCount then
par.ActivateDelay(0);
ReleaseResource(par.Cashman);
// Встать в очередь завершенных процессов
Finish;
end;
{ TClientGenerator }
procedure TClientGenerator.RunProcess;
var
i : Integer;
begin
for i := 1 to MaxClientCount do
begin
ClearFinished;
TClient.Create.ActivateDelay(0);
Hold(rndClient.Exponential(MeanClientInterval));
end;
end;
{ TBankSimulation }
destructor TBankSimulation.Destroy;
begin
Generator.Free;
InBankTime.Free;
InBankHist.Free;
Cashman.Free;
inherited;
end;
procedure TBankSimulation.Init;
begin
inherited;
Cashman := TResource.Create;
Generator := TClientGenerator.Create;
InBankTime := TStatistics.Create;
InBankHist := TUniformHistogram.Create(HistMin, HistStep, HistStepCount);
NotWaited := 0;
end;
procedure TBankSimulation.RunSimulation;
begin
// Запустить процесс создания клиентов
Generator.ActivateDelay(0);
// Ждать конца имитации
Passivate;
StopStat;
end;
procedure TBankSimulation.StopStat;
begin
inherited;
Cashman.StopStat(SimTime);
end;
end.
|
unit PEHeaders;
interface
uses Windows;
const
IMAGE_DOS_SIGNATURE = $5A4D; // MZ
{$EXTERNALSYM IMAGE_DOS_SIGNATURE}
IMAGE_OS2_SIGNATURE = $454E; // NE
{$EXTERNALSYM IMAGE_OS2_SIGNATURE}
IMAGE_OS2_SIGNATURE_LE = $454C; // LE
{$EXTERNALSYM IMAGE_OS2_SIGNATURE_LE}
IMAGE_VXD_SIGNATURE = $454C; // LE
{$EXTERNALSYM IMAGE_VXD_SIGNATURE}
IMAGE_NT_SIGNATURE = $00004550; // PE00
{$EXTERNALSYM IMAGE_NT_SIGNATURE}
// #include "pshpack2.h" // 16 bit headers are 2 byte packed
type
// DOS .EXE header
PIMAGE_DOS_HEADER = ^IMAGE_DOS_HEADER;
{$EXTERNALSYM PIMAGE_DOS_HEADER}
_IMAGE_DOS_HEADER = record
e_magic: Word; // Magic number
e_cblp: Word; // Bytes on last page of file
e_cp: Word; // Pages in file
e_crlc: Word; // Relocations
e_cparhdr: Word; // Size of header in paragraphs
e_minalloc: Word; // Minimum extra paragraphs needed
e_maxalloc: Word; // Maximum extra paragraphs needed
e_ss: Word; // Initial (relative) SS value
e_sp: Word; // Initial SP value
e_csum: Word; // Checksum
e_ip: Word; // Initial IP value
e_cs: Word; // Initial (relative) CS value
e_lfarlc: Word; // File address of relocation table
e_ovno: Word; // Overlay number
e_res: array [0..3] of Word; // Reserved words
e_oemid: Word; // OEM identifier (for e_oeminfo)
e_oeminfo: Word; // OEM information; e_oemid specific
e_res2: array [0..9] of Word; // Reserved words
e_lfanew: Longint; // File address of new exe header
end;
{$EXTERNALSYM _IMAGE_DOS_HEADER}
IMAGE_DOS_HEADER = _IMAGE_DOS_HEADER;
{$EXTERNALSYM IMAGE_DOS_HEADER}
TImageDosHeader = IMAGE_DOS_HEADER;
PImageDosHeader = PIMAGE_DOS_HEADER;
// OS/2 .EXE header
PIMAGE_OS2_HEADER = ^IMAGE_OS2_HEADER;
{$EXTERNALSYM PIMAGE_OS2_HEADER}
_IMAGE_OS2_HEADER = record
ne_magic: Word; // Magic number
ne_ver: CHAR; // Version number
ne_rev: CHAR; // Revision number
ne_enttab: Word; // Offset of Entry Table
ne_cbenttab: Word; // Number of bytes in Entry Table
ne_crc: Longint; // Checksum of whole file
ne_flags: Word; // Flag word
ne_autodata: Word; // Automatic data segment number
ne_heap: Word; // Initial heap allocation
ne_stack: Word; // Initial stack allocation
ne_csip: Longint; // Initial CS:IP setting
ne_sssp: Longint; // Initial SS:SP setting
ne_cseg: Word; // Count of file segments
ne_cmod: Word; // Entries in Module Reference Table
ne_cbnrestab: Word; // Size of non-resident name table
ne_segtab: Word; // Offset of Segment Table
ne_rsrctab: Word; // Offset of Resource Table
ne_restab: Word; // Offset of resident name table
ne_modtab: Word; // Offset of Module Reference Table
ne_imptab: Word; // Offset of Imported Names Table
ne_nrestab: Longint; // Offset of Non-resident Names Table
ne_cmovent: Word; // Count of movable entries
ne_align: Word; // Segment alignment shift count
ne_cres: Word; // Count of resource segments
ne_exetyp: Byte; // Target Operating system
ne_flagsothers: Byte; // Other .EXE flags
ne_pretthunks: Word; // offset to return thunks
ne_psegrefbytes: Word; // offset to segment ref. bytes
ne_swaparea: Word; // Minimum code swap area size
ne_expver: Word; // Expected Windows version number
end;
{$EXTERNALSYM _IMAGE_OS2_HEADER}
IMAGE_OS2_HEADER = _IMAGE_OS2_HEADER;
{$EXTERNALSYM IMAGE_OS2_HEADER}
TImageOs2Header = IMAGE_OS2_HEADER;
PImageOs2Header = PIMAGE_OS2_HEADER;
// Windows VXD header
PIMAGE_VXD_HEADER = ^IMAGE_VXD_HEADER;
{$EXTERNALSYM PIMAGE_VXD_HEADER}
_IMAGE_VXD_HEADER = record
e32_magic: Word; // Magic number
e32_border: Byte; // The byte ordering for the VXD
e32_worder: Byte; // The word ordering for the VXD
e32_level: DWORD; // The EXE format level for now = 0
e32_cpu: Word; // The CPU type
e32_os: Word; // The OS type
e32_ver: DWORD; // Module version
e32_mflags: DWORD; // Module flags
e32_mpages: DWORD; // Module # pages
e32_startobj: DWORD; // Object # for instruction pointer
e32_eip: DWORD; // Extended instruction pointer
e32_stackobj: DWORD; // Object # for stack pointer
e32_esp: DWORD; // Extended stack pointer
e32_pagesize: DWORD; // VXD page size
e32_lastpagesize: DWORD; // Last page size in VXD
e32_fixupsize: DWORD; // Fixup section size
e32_fixupsum: DWORD; // Fixup section checksum
e32_ldrsize: DWORD; // Loader section size
e32_ldrsum: DWORD; // Loader section checksum
e32_objtab: DWORD; // Object table offset
e32_objcnt: DWORD; // Number of objects in module
e32_objmap: DWORD; // Object page map offset
e32_itermap: DWORD; // Object iterated data map offset
e32_rsrctab: DWORD; // Offset of Resource Table
e32_rsrccnt: DWORD; // Number of resource entries
e32_restab: DWORD; // Offset of resident name table
e32_enttab: DWORD; // Offset of Entry Table
e32_dirtab: DWORD; // Offset of Module Directive Table
e32_dircnt: DWORD; // Number of module directives
e32_fpagetab: DWORD; // Offset of Fixup Page Table
e32_frectab: DWORD; // Offset of Fixup Record Table
e32_impmod: DWORD; // Offset of Import Module Name Table
e32_impmodcnt: DWORD; // Number of entries in Import Module Name Table
e32_impproc: DWORD; // Offset of Import Procedure Name Table
e32_pagesum: DWORD; // Offset of Per-Page Checksum Table
e32_datapage: DWORD; // Offset of Enumerated Data Pages
e32_preload: DWORD; // Number of preload pages
e32_nrestab: DWORD; // Offset of Non-resident Names Table
e32_cbnrestab: DWORD; // Size of Non-resident Name Table
e32_nressum: DWORD; // Non-resident Name Table Checksum
e32_autodata: DWORD; // Object # for automatic data object
e32_debuginfo: DWORD; // Offset of the debugging information
e32_debuglen: DWORD; // The length of the debugging info. in bytes
e32_instpreload: DWORD; // Number of instance pages in preload section of VXD file
e32_instdemand: DWORD; // Number of instance pages in demand load section of VXD file
e32_heapsize: DWORD; // Size of heap - for 16-bit apps
e32_res3: array [0..11] of Byte; // Reserved words
e32_winresoff: DWORD;
e32_winreslen: DWORD;
e32_devid: Word; // Device ID for VxD
e32_ddkver: Word; // DDK version for VxD
end;
{$EXTERNALSYM _IMAGE_VXD_HEADER}
IMAGE_VXD_HEADER = _IMAGE_VXD_HEADER;
{$EXTERNALSYM IMAGE_VXD_HEADER}
TImageVxdHeader = IMAGE_VXD_HEADER;
PImageVxdHeader = PIMAGE_VXD_HEADER;
// #include "poppack.h" // Back to 4 byte packing
//
// File header format.
//
PIMAGE_FILE_HEADER = ^IMAGE_FILE_HEADER;
{$EXTERNALSYM PIMAGE_FILE_HEADER}
_IMAGE_FILE_HEADER = record
Machine: WORD;
NumberOfSections: WORD;
TimeDateStamp: DWORD;
PointerToSymbolTable: DWORD;
NumberOfSymbols: DWORD;
SizeOfOptionalHeader: WORD;
Characteristics: WORD;
end;
{$EXTERNALSYM _IMAGE_FILE_HEADER}
IMAGE_FILE_HEADER = _IMAGE_FILE_HEADER;
{$EXTERNALSYM IMAGE_FILE_HEADER}
TImageFileHeader = IMAGE_FILE_HEADER;
PImageFileHeader = PIMAGE_FILE_HEADER;
const
IMAGE_SIZEOF_FILE_HEADER = 20;
{$EXTERNALSYM IMAGE_SIZEOF_FILE_HEADER}
IMAGE_FILE_RELOCS_STRIPPED = $0001; // Relocation info stripped from file.
{$EXTERNALSYM IMAGE_FILE_RELOCS_STRIPPED}
IMAGE_FILE_EXECUTABLE_IMAGE = $0002; // File is executable (i.e. no unresolved externel references).
{$EXTERNALSYM IMAGE_FILE_EXECUTABLE_IMAGE}
IMAGE_FILE_LINE_NUMS_STRIPPED = $0004; // Line nunbers stripped from file.
{$EXTERNALSYM IMAGE_FILE_LINE_NUMS_STRIPPED}
IMAGE_FILE_LOCAL_SYMS_STRIPPED = $0008; // Local symbols stripped from file.
{$EXTERNALSYM IMAGE_FILE_LOCAL_SYMS_STRIPPED}
IMAGE_FILE_AGGRESIVE_WS_TRIM = $0010; // Agressively trim working set
{$EXTERNALSYM IMAGE_FILE_AGGRESIVE_WS_TRIM}
IMAGE_FILE_LARGE_ADDRESS_AWARE = $0020; // App can handle >2gb addresses
{$EXTERNALSYM IMAGE_FILE_LARGE_ADDRESS_AWARE}
IMAGE_FILE_BYTES_REVERSED_LO = $0080; // Bytes of machine word are reversed.
{$EXTERNALSYM IMAGE_FILE_BYTES_REVERSED_LO}
IMAGE_FILE_32BIT_MACHINE = $0100; // 32 bit word machine.
{$EXTERNALSYM IMAGE_FILE_32BIT_MACHINE}
IMAGE_FILE_DEBUG_STRIPPED = $0200; // Debugging info stripped from file in .DBG file
{$EXTERNALSYM IMAGE_FILE_DEBUG_STRIPPED}
IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = $0400; // If Image is on removable media, copy and run from the swap file.
{$EXTERNALSYM IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP}
IMAGE_FILE_NET_RUN_FROM_SWAP = $0800; // If Image is on Net, copy and run from the swap file.
{$EXTERNALSYM IMAGE_FILE_NET_RUN_FROM_SWAP}
IMAGE_FILE_SYSTEM = $1000; // System File.
{$EXTERNALSYM IMAGE_FILE_SYSTEM}
IMAGE_FILE_DLL = $2000; // File is a DLL.
{$EXTERNALSYM IMAGE_FILE_DLL}
IMAGE_FILE_UP_SYSTEM_ONLY = $4000; // File should only be run on a UP machine
{$EXTERNALSYM IMAGE_FILE_UP_SYSTEM_ONLY}
IMAGE_FILE_BYTES_REVERSED_HI = $8000; // Bytes of machine word are reversed.
{$EXTERNALSYM IMAGE_FILE_BYTES_REVERSED_HI}
IMAGE_FILE_MACHINE_UNKNOWN = 0;
{$EXTERNALSYM IMAGE_FILE_MACHINE_UNKNOWN}
IMAGE_FILE_MACHINE_I386 = $014c; // Intel 386.
{$EXTERNALSYM IMAGE_FILE_MACHINE_I386}
IMAGE_FILE_MACHINE_R3000 = $0162; // MIPS little-endian, 0x160 big-endian
{$EXTERNALSYM IMAGE_FILE_MACHINE_R3000}
IMAGE_FILE_MACHINE_R4000 = $0166; // MIPS little-endian
{$EXTERNALSYM IMAGE_FILE_MACHINE_R4000}
IMAGE_FILE_MACHINE_R10000 = $0168; // MIPS little-endian
{$EXTERNALSYM IMAGE_FILE_MACHINE_R10000}
IMAGE_FILE_MACHINE_WCEMIPSV2 = $0169; // MIPS little-endian WCE v2
{$EXTERNALSYM IMAGE_FILE_MACHINE_WCEMIPSV2}
IMAGE_FILE_MACHINE_ALPHA = $0184; // Alpha_AXP
{$EXTERNALSYM IMAGE_FILE_MACHINE_ALPHA}
IMAGE_FILE_MACHINE_SH3 = $01a2; // SH3 little-endian
{$EXTERNALSYM IMAGE_FILE_MACHINE_SH3}
IMAGE_FILE_MACHINE_SH3DSP = $01a3;
{$EXTERNALSYM IMAGE_FILE_MACHINE_SH3DSP}
IMAGE_FILE_MACHINE_SH3E = $01a4; // SH3E little-endian
{$EXTERNALSYM IMAGE_FILE_MACHINE_SH3E}
IMAGE_FILE_MACHINE_SH4 = $01a6; // SH4 little-endian
{$EXTERNALSYM IMAGE_FILE_MACHINE_SH4}
IMAGE_FILE_MACHINE_SH5 = $01a8; // SH5
{$EXTERNALSYM IMAGE_FILE_MACHINE_SH5}
IMAGE_FILE_MACHINE_ARM = $01c0; // ARM Little-Endian
{$EXTERNALSYM IMAGE_FILE_MACHINE_ARM}
IMAGE_FILE_MACHINE_THUMB = $01c2;
{$EXTERNALSYM IMAGE_FILE_MACHINE_THUMB}
IMAGE_FILE_MACHINE_AM33 = $01d3;
{$EXTERNALSYM IMAGE_FILE_MACHINE_AM33}
IMAGE_FILE_MACHINE_POWERPC = $01F0; // IBM PowerPC Little-Endian
{$EXTERNALSYM IMAGE_FILE_MACHINE_POWERPC}
IMAGE_FILE_MACHINE_POWERPCFP = $01f1;
{$EXTERNALSYM IMAGE_FILE_MACHINE_POWERPCFP}
IMAGE_FILE_MACHINE_IA64 = $0200; // Intel 64
{$EXTERNALSYM IMAGE_FILE_MACHINE_IA64}
IMAGE_FILE_MACHINE_MIPS16 = $0266; // MIPS
{$EXTERNALSYM IMAGE_FILE_MACHINE_MIPS16}
IMAGE_FILE_MACHINE_ALPHA64 = $0284; // ALPHA64
{$EXTERNALSYM IMAGE_FILE_MACHINE_ALPHA64}
IMAGE_FILE_MACHINE_MIPSFPU = $0366; // MIPS
{$EXTERNALSYM IMAGE_FILE_MACHINE_MIPSFPU}
IMAGE_FILE_MACHINE_MIPSFPU16 = $0466; // MIPS
{$EXTERNALSYM IMAGE_FILE_MACHINE_MIPSFPU16}
IMAGE_FILE_MACHINE_AXP64 = IMAGE_FILE_MACHINE_ALPHA64;
{$EXTERNALSYM IMAGE_FILE_MACHINE_AXP64}
IMAGE_FILE_MACHINE_TRICORE = $0520; // Infineon
{$EXTERNALSYM IMAGE_FILE_MACHINE_TRICORE}
IMAGE_FILE_MACHINE_CEF = $0CEF;
{$EXTERNALSYM IMAGE_FILE_MACHINE_CEF}
IMAGE_FILE_MACHINE_EBC = $0EBC; // EFI Byte Code
{$EXTERNALSYM IMAGE_FILE_MACHINE_EBC}
IMAGE_FILE_MACHINE_AMD64 = $8664; // AMD64 (K8)
{$EXTERNALSYM IMAGE_FILE_MACHINE_AMD64}
IMAGE_FILE_MACHINE_M32R = $9041; // M32R little-endian
{$EXTERNALSYM IMAGE_FILE_MACHINE_M32R}
IMAGE_FILE_MACHINE_CEE = $C0EE;
{$EXTERNALSYM IMAGE_FILE_MACHINE_CEE}
//
// Directory format.
//
type
PIMAGE_DATA_DIRECTORY = ^IMAGE_DATA_DIRECTORY;
{$EXTERNALSYM PIMAGE_DATA_DIRECTORY}
_IMAGE_DATA_DIRECTORY = record
VirtualAddress: DWORD;
Size: DWORD;
end;
{$EXTERNALSYM _IMAGE_DATA_DIRECTORY}
IMAGE_DATA_DIRECTORY = _IMAGE_DATA_DIRECTORY;
{$EXTERNALSYM IMAGE_DATA_DIRECTORY}
TImageDataDirectory = IMAGE_DATA_DIRECTORY;
PImageDataDirectory = PIMAGE_DATA_DIRECTORY;
const
IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
{$EXTERNALSYM IMAGE_NUMBEROF_DIRECTORY_ENTRIES}
//
// Optional header format.
//
type
PIMAGE_OPTIONAL_HEADER32 = ^IMAGE_OPTIONAL_HEADER32;
{$EXTERNALSYM PIMAGE_OPTIONAL_HEADER32}
_IMAGE_OPTIONAL_HEADER = record
//
// Standard fields.
//
Magic: Word;
MajorLinkerVersion: Byte;
MinorLinkerVersion: Byte;
SizeOfCode: DWORD;
SizeOfInitializedData: DWORD;
SizeOfUninitializedData: DWORD;
AddressOfEntryPoint: DWORD;
BaseOfCode: DWORD;
BaseOfData: DWORD;
//
// NT additional fields.
//
ImageBase: DWORD;
SectionAlignment: DWORD;
FileAlignment: DWORD;
MajorOperatingSystemVersion: Word;
MinorOperatingSystemVersion: Word;
MajorImageVersion: Word;
MinorImageVersion: Word;
MajorSubsystemVersion: Word;
MinorSubsystemVersion: Word;
Win32VersionValue: DWORD;
SizeOfImage: DWORD;
SizeOfHeaders: DWORD;
CheckSum: DWORD;
Subsystem: Word;
DllCharacteristics: Word;
SizeOfStackReserve: DWORD;
SizeOfStackCommit: DWORD;
SizeOfHeapReserve: DWORD;
SizeOfHeapCommit: DWORD;
LoaderFlags: DWORD;
NumberOfRvaAndSizes: DWORD;
DataDirectory: array [0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES - 1] of IMAGE_DATA_DIRECTORY;
end;
{$EXTERNALSYM _IMAGE_OPTIONAL_HEADER}
IMAGE_OPTIONAL_HEADER32 = _IMAGE_OPTIONAL_HEADER;
{$EXTERNALSYM IMAGE_OPTIONAL_HEADER32}
TImageOptionalHeader32 = IMAGE_OPTIONAL_HEADER32;
PImageOptionalHeader32 = PIMAGE_OPTIONAL_HEADER32;
PIMAGE_ROM_OPTIONAL_HEADER = ^IMAGE_ROM_OPTIONAL_HEADER;
{$EXTERNALSYM PIMAGE_ROM_OPTIONAL_HEADER}
_IMAGE_ROM_OPTIONAL_HEADER = record
Magic: Word;
MajorLinkerVersion: Byte;
MinorLinkerVersion: Byte;
SizeOfCode: DWORD;
SizeOfInitializedData: DWORD;
SizeOfUninitializedData: DWORD;
AddressOfEntryPoint: DWORD;
BaseOfCode: DWORD;
BaseOfData: DWORD;
BaseOfBss: DWORD;
GprMask: DWORD;
CprMask: array [0..3] of DWORD;
GpValue: DWORD;
end;
{$EXTERNALSYM _IMAGE_ROM_OPTIONAL_HEADER}
IMAGE_ROM_OPTIONAL_HEADER = _IMAGE_ROM_OPTIONAL_HEADER;
{$EXTERNALSYM IMAGE_ROM_OPTIONAL_HEADER}
TImageRomOptionalHeader = IMAGE_ROM_OPTIONAL_HEADER;
PImageRomOptionalHeader = PIMAGE_ROM_OPTIONAL_HEADER;
PIMAGE_OPTIONAL_HEADER64 = ^IMAGE_OPTIONAL_HEADER64;
{$EXTERNALSYM PIMAGE_OPTIONAL_HEADER64}
_IMAGE_OPTIONAL_HEADER64 = record
Magic: Word;
MajorLinkerVersion: Byte;
MinorLinkerVersion: Byte;
SizeOfCode: DWORD;
SizeOfInitializedData: DWORD;
SizeOfUninitializedData: DWORD;
AddressOfEntryPoint: DWORD;
BaseOfCode: DWORD;
ImageBase: Int64;
SectionAlignment: DWORD;
FileAlignment: DWORD;
MajorOperatingSystemVersion: Word;
MinorOperatingSystemVersion: Word;
MajorImageVersion: Word;
MinorImageVersion: Word;
MajorSubsystemVersion: Word;
MinorSubsystemVersion: Word;
Win32VersionValue: DWORD;
SizeOfImage: DWORD;
SizeOfHeaders: DWORD;
CheckSum: DWORD;
Subsystem: Word;
DllCharacteristics: Word;
SizeOfStackReserve: Int64;
SizeOfStackCommit: Int64;
SizeOfHeapReserve: Int64;
SizeOfHeapCommit: Int64;
LoaderFlags: DWORD;
NumberOfRvaAndSizes: DWORD;
DataDirectory: array [0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES - 1] of IMAGE_DATA_DIRECTORY;
end;
{$EXTERNALSYM _IMAGE_OPTIONAL_HEADER64}
IMAGE_OPTIONAL_HEADER64 = _IMAGE_OPTIONAL_HEADER64;
{$EXTERNALSYM IMAGE_OPTIONAL_HEADER64}
TImageOptionalHeader64 = IMAGE_OPTIONAL_HEADER64;
PImageOptionalHeader64 = PIMAGE_OPTIONAL_HEADER64;
const
IMAGE_SIZEOF_ROM_OPTIONAL_HEADER = 56;
{$EXTERNALSYM IMAGE_SIZEOF_ROM_OPTIONAL_HEADER}
IMAGE_SIZEOF_STD_OPTIONAL_HEADER = 28;
{$EXTERNALSYM IMAGE_SIZEOF_STD_OPTIONAL_HEADER}
IMAGE_SIZEOF_NT_OPTIONAL32_HEADER = 224;
{$EXTERNALSYM IMAGE_SIZEOF_NT_OPTIONAL32_HEADER}
IMAGE_SIZEOF_NT_OPTIONAL64_HEADER = 240;
{$EXTERNALSYM IMAGE_SIZEOF_NT_OPTIONAL64_HEADER}
IMAGE_NT_OPTIONAL_HDR32_MAGIC = $10b;
{$EXTERNALSYM IMAGE_NT_OPTIONAL_HDR32_MAGIC}
IMAGE_NT_OPTIONAL_HDR64_MAGIC = $20b;
{$EXTERNALSYM IMAGE_NT_OPTIONAL_HDR64_MAGIC}
IMAGE_ROM_OPTIONAL_HDR_MAGIC = $107;
{$EXTERNALSYM IMAGE_ROM_OPTIONAL_HDR_MAGIC}
type
IMAGE_OPTIONAL_HEADER = IMAGE_OPTIONAL_HEADER32;
{$EXTERNALSYM IMAGE_OPTIONAL_HEADER}
PIMAGE_OPTIONAL_HEADER = PIMAGE_OPTIONAL_HEADER32;
{$EXTERNALSYM PIMAGE_OPTIONAL_HEADER}
const
IMAGE_SIZEOF_NT_OPTIONAL_HEADER = IMAGE_SIZEOF_NT_OPTIONAL32_HEADER;
{$EXTERNALSYM IMAGE_SIZEOF_NT_OPTIONAL_HEADER}
IMAGE_NT_OPTIONAL_HDR_MAGIC = IMAGE_NT_OPTIONAL_HDR32_MAGIC;
{$EXTERNALSYM IMAGE_NT_OPTIONAL_HDR_MAGIC}
type
PIMAGE_NT_HEADERS64 = ^IMAGE_NT_HEADERS64;
{$EXTERNALSYM PIMAGE_NT_HEADERS64}
_IMAGE_NT_HEADERS64 = record
Signature: DWORD;
FileHeader: IMAGE_FILE_HEADER;
OptionalHeader: IMAGE_OPTIONAL_HEADER64;
end;
{$EXTERNALSYM _IMAGE_NT_HEADERS64}
IMAGE_NT_HEADERS64 = _IMAGE_NT_HEADERS64;
{$EXTERNALSYM IMAGE_NT_HEADERS64}
TImageNtHeaders64 = IMAGE_NT_HEADERS64;
PImageNtHeaders64 = PIMAGE_NT_HEADERS64;
PIMAGE_NT_HEADERS32 = ^IMAGE_NT_HEADERS32;
{$EXTERNALSYM PIMAGE_NT_HEADERS32}
_IMAGE_NT_HEADERS = record
Signature: DWORD;
FileHeader: IMAGE_FILE_HEADER;
OptionalHeader: IMAGE_OPTIONAL_HEADER32;
end;
{$EXTERNALSYM _IMAGE_NT_HEADERS}
IMAGE_NT_HEADERS32 = _IMAGE_NT_HEADERS;
{$EXTERNALSYM IMAGE_NT_HEADERS32}
TImageNtHeaders32 = IMAGE_NT_HEADERS32;
PImageNtHeaders32 = PIMAGE_NT_HEADERS32;
PIMAGE_ROM_HEADERS = ^IMAGE_ROM_HEADERS;
{$EXTERNALSYM PIMAGE_ROM_HEADERS}
_IMAGE_ROM_HEADERS = record
FileHeader: IMAGE_FILE_HEADER;
OptionalHeader: IMAGE_ROM_OPTIONAL_HEADER;
end;
{$EXTERNALSYM _IMAGE_ROM_HEADERS}
IMAGE_ROM_HEADERS = _IMAGE_ROM_HEADERS;
{$EXTERNALSYM IMAGE_ROM_HEADERS}
TImageRomHeaders = IMAGE_ROM_HEADERS;
PImageRomHeaders = PIMAGE_ROM_HEADERS;
IMAGE_NT_HEADERS = IMAGE_NT_HEADERS32;
{$EXTERNALSYM IMAGE_NT_HEADERS}
PIMAGE_NT_HEADERS = PIMAGE_NT_HEADERS32;
{$EXTERNALSYM PIMAGE_NT_HEADERS}
// Subsystem Values
const
IMAGE_SUBSYSTEM_UNKNOWN = 0; // Unknown subsystem.
{$EXTERNALSYM IMAGE_SUBSYSTEM_UNKNOWN}
IMAGE_SUBSYSTEM_NATIVE = 1; // Image doesn't require a subsystem.
{$EXTERNALSYM IMAGE_SUBSYSTEM_NATIVE}
IMAGE_SUBSYSTEM_WINDOWS_GUI = 2; // Image runs in the Windows GUI subsystem.
{$EXTERNALSYM IMAGE_SUBSYSTEM_WINDOWS_GUI}
IMAGE_SUBSYSTEM_WINDOWS_CUI = 3; // Image runs in the Windows character subsystem.
{$EXTERNALSYM IMAGE_SUBSYSTEM_WINDOWS_CUI}
IMAGE_SUBSYSTEM_OS2_CUI = 5; // image runs in the OS/2 character subsystem.
{$EXTERNALSYM IMAGE_SUBSYSTEM_OS2_CUI}
IMAGE_SUBSYSTEM_POSIX_CUI = 7; // image runs in the Posix character subsystem.
{$EXTERNALSYM IMAGE_SUBSYSTEM_POSIX_CUI}
IMAGE_SUBSYSTEM_NATIVE_WINDOWS = 8; // image is a native Win9x driver.
{$EXTERNALSYM IMAGE_SUBSYSTEM_NATIVE_WINDOWS}
IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9; // Image runs in the Windows CE subsystem.
{$EXTERNALSYM IMAGE_SUBSYSTEM_WINDOWS_CE_GUI}
IMAGE_SUBSYSTEM_EFI_APPLICATION = 10;
{$EXTERNALSYM IMAGE_SUBSYSTEM_EFI_APPLICATION}
IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11;
{$EXTERNALSYM IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER}
IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12;
{$EXTERNALSYM IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER}
IMAGE_SUBSYSTEM_EFI_ROM = 13;
{$EXTERNALSYM IMAGE_SUBSYSTEM_EFI_ROM}
IMAGE_SUBSYSTEM_XBOX = 14;
{$EXTERNALSYM IMAGE_SUBSYSTEM_XBOX}
// DllCharacteristics Entries
// IMAGE_LIBRARY_PROCESS_INIT 0x0001 // Reserved.
// IMAGE_LIBRARY_PROCESS_TERM 0x0002 // Reserved.
// IMAGE_LIBRARY_THREAD_INIT 0x0004 // Reserved.
// IMAGE_LIBRARY_THREAD_TERM 0x0008 // Reserved.
IMAGE_DLLCHARACTERISTICS_NO_BIND = $0800; // Do not bind this image.
{$EXTERNALSYM IMAGE_DLLCHARACTERISTICS_NO_BIND}
// 0x1000 // Reserved.
IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = $2000; // Driver uses WDM model
{$EXTERNALSYM IMAGE_DLLCHARACTERISTICS_WDM_DRIVER}
// 0x4000 // Reserved.
IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = $8000;
{$EXTERNALSYM IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE}
// Directory Entries
IMAGE_DIRECTORY_ENTRY_EXPORT = 0; // Export Directory
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_EXPORT}
IMAGE_DIRECTORY_ENTRY_IMPORT = 1; // Import Directory
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_IMPORT}
IMAGE_DIRECTORY_ENTRY_RESOURCE = 2; // Resource Directory
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_RESOURCE}
IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3; // Exception Directory
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_EXCEPTION}
IMAGE_DIRECTORY_ENTRY_SECURITY = 4; // Security Directory
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_SECURITY}
IMAGE_DIRECTORY_ENTRY_BASERELOC = 5; // Base Relocation Table
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_BASERELOC}
IMAGE_DIRECTORY_ENTRY_DEBUG = 6; // Debug Directory
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_DEBUG}
// IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 // (X86 usage)
IMAGE_DIRECTORY_ENTRY_ARCHITECTURE = 7; // Architecture Specific Data
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_ARCHITECTURE}
IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8; // RVA of GP
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_GLOBALPTR}
IMAGE_DIRECTORY_ENTRY_TLS = 9; // TLS Directory
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_TLS}
IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10; // Load Configuration Directory
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG}
IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11; // Bound Import Directory in headers
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT}
IMAGE_DIRECTORY_ENTRY_IAT = 12; // Import Address Table
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_IAT}
IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT = 13; // Delay Load Import Descriptors
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT}
IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14; // COM Runtime descriptor
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR}
//
// Non-COFF Object file header
//
type
PAnonObjectHeader = ^ANON_OBJECT_HEADER;
ANON_OBJECT_HEADER = record
Sig1: Word; // Must be IMAGE_FILE_MACHINE_UNKNOWN
Sig2: Word; // Must be 0xffff
Version: Word; // >= 1 (implies the CLSID field is present)
Machine: Word;
TimeDateStamp: DWORD;
ClassID: TGUID; // Used to invoke CoCreateInstance
SizeOfData: DWORD; // Size of data that follows the header
end;
{$EXTERNALSYM ANON_OBJECT_HEADER}
TAnonObjectHeader = ANON_OBJECT_HEADER;
//
// Section header format.
//
const
IMAGE_SIZEOF_SHORT_NAME = 8;
{$EXTERNALSYM IMAGE_SIZEOF_SHORT_NAME}
type
TImgSecHdrMisc = record
case Integer of
0: (PhysicalAddress: DWORD);
1: (VirtualSize: DWORD);
end;
PIMAGE_SECTION_HEADER = ^IMAGE_SECTION_HEADER;
{$EXTERNALSYM PIMAGE_SECTION_HEADER}
_IMAGE_SECTION_HEADER = record
Name: array [0..IMAGE_SIZEOF_SHORT_NAME - 1] of BYTE;
Misc: TImgSecHdrMisc;
VirtualAddress: DWORD;
SizeOfRawData: DWORD;
PointerToRawData: DWORD;
PointerToRelocations: DWORD;
PointerToLinenumbers: DWORD;
NumberOfRelocations: WORD;
NumberOfLinenumbers: WORD;
Characteristics: DWORD;
end;
{$EXTERNALSYM _IMAGE_SECTION_HEADER}
IMAGE_SECTION_HEADER = _IMAGE_SECTION_HEADER;
{$EXTERNALSYM IMAGE_SECTION_HEADER}
TImageSectionHeader = IMAGE_SECTION_HEADER;
PImageSectionHeader = PIMAGE_SECTION_HEADER;
const
IMAGE_SIZEOF_SECTION_HEADER = 40;
{$EXTERNALSYM IMAGE_SIZEOF_SECTION_HEADER}
//
// Section characteristics.
//
// IMAGE_SCN_TYPE_REG 0x00000000 // Reserved.
// IMAGE_SCN_TYPE_DSECT 0x00000001 // Reserved.
// IMAGE_SCN_TYPE_NOLOAD 0x00000002 // Reserved.
// IMAGE_SCN_TYPE_GROUP 0x00000004 // Reserved.
IMAGE_SCN_TYPE_NO_PAD = $00000008; // Reserved.
{$EXTERNALSYM IMAGE_SCN_TYPE_NO_PAD}
// IMAGE_SCN_TYPE_COPY 0x00000010 // Reserved.
IMAGE_SCN_CNT_CODE = $00000020; // Section contains code.
{$EXTERNALSYM IMAGE_SCN_CNT_CODE}
IMAGE_SCN_CNT_INITIALIZED_DATA = $00000040; // Section contains initialized data.
{$EXTERNALSYM IMAGE_SCN_CNT_INITIALIZED_DATA}
IMAGE_SCN_CNT_UNINITIALIZED_DATA = $00000080; // Section contains uninitialized data.
{$EXTERNALSYM IMAGE_SCN_CNT_UNINITIALIZED_DATA}
IMAGE_SCN_LNK_OTHER = $00000100; // Reserved.
{$EXTERNALSYM IMAGE_SCN_LNK_OTHER}
IMAGE_SCN_LNK_INFO = $00000200; // Section contains comments or some other type of information.
{$EXTERNALSYM IMAGE_SCN_LNK_INFO}
// IMAGE_SCN_TYPE_OVER 0x00000400 // Reserved.
IMAGE_SCN_LNK_REMOVE = $00000800; // Section contents will not become part of image.
{$EXTERNALSYM IMAGE_SCN_LNK_REMOVE}
IMAGE_SCN_LNK_COMDAT = $00001000; // Section contents comdat.
{$EXTERNALSYM IMAGE_SCN_LNK_COMDAT}
// 0x00002000 // Reserved.
// IMAGE_SCN_MEM_PROTECTED - Obsolete 0x00004000
IMAGE_SCN_NO_DEFER_SPEC_EXC = $00004000; // Reset speculative exceptions handling bits in the TLB entries for this section.
{$EXTERNALSYM IMAGE_SCN_NO_DEFER_SPEC_EXC}
IMAGE_SCN_GPREL = $00008000; // Section content can be accessed relative to GP
{$EXTERNALSYM IMAGE_SCN_GPREL}
IMAGE_SCN_MEM_FARDATA = $00008000;
{$EXTERNALSYM IMAGE_SCN_MEM_FARDATA}
// IMAGE_SCN_MEM_SYSHEAP - Obsolete 0x00010000
IMAGE_SCN_MEM_PURGEABLE = $00020000;
{$EXTERNALSYM IMAGE_SCN_MEM_PURGEABLE}
IMAGE_SCN_MEM_16BIT = $00020000;
{$EXTERNALSYM IMAGE_SCN_MEM_16BIT}
IMAGE_SCN_MEM_LOCKED = $00040000;
{$EXTERNALSYM IMAGE_SCN_MEM_LOCKED}
IMAGE_SCN_MEM_PRELOAD = $00080000;
{$EXTERNALSYM IMAGE_SCN_MEM_PRELOAD}
IMAGE_SCN_ALIGN_1BYTES = $00100000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_1BYTES}
IMAGE_SCN_ALIGN_2BYTES = $00200000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_2BYTES}
IMAGE_SCN_ALIGN_4BYTES = $00300000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_4BYTES}
IMAGE_SCN_ALIGN_8BYTES = $00400000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_8BYTES}
IMAGE_SCN_ALIGN_16BYTES = $00500000; // Default alignment if no others are specified.
{$EXTERNALSYM IMAGE_SCN_ALIGN_16BYTES}
IMAGE_SCN_ALIGN_32BYTES = $00600000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_32BYTES}
IMAGE_SCN_ALIGN_64BYTES = $00700000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_64BYTES}
IMAGE_SCN_ALIGN_128BYTES = $00800000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_128BYTES}
IMAGE_SCN_ALIGN_256BYTES = $00900000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_256BYTES}
IMAGE_SCN_ALIGN_512BYTES = $00A00000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_512BYTES}
IMAGE_SCN_ALIGN_1024BYTES = $00B00000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_1024BYTES}
IMAGE_SCN_ALIGN_2048BYTES = $00C00000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_2048BYTES}
IMAGE_SCN_ALIGN_4096BYTES = $00D00000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_4096BYTES}
IMAGE_SCN_ALIGN_8192BYTES = $00E00000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_8192BYTES}
// Unused 0x00F00000
IMAGE_SCN_ALIGN_MASK = $00F00000;
{$EXTERNALSYM IMAGE_SCN_ALIGN_MASK}
IMAGE_SCN_LNK_NRELOC_OVFL = $01000000; // Section contains extended relocations.
{$EXTERNALSYM IMAGE_SCN_LNK_NRELOC_OVFL}
IMAGE_SCN_MEM_DISCARDABLE = $02000000; // Section can be discarded.
{$EXTERNALSYM IMAGE_SCN_MEM_DISCARDABLE}
IMAGE_SCN_MEM_NOT_CACHED = $04000000; // Section is not cachable.
{$EXTERNALSYM IMAGE_SCN_MEM_NOT_CACHED}
IMAGE_SCN_MEM_NOT_PAGED = $08000000; // Section is not pageable.
{$EXTERNALSYM IMAGE_SCN_MEM_NOT_PAGED}
IMAGE_SCN_MEM_SHARED = $10000000; // Section is shareable.
{$EXTERNALSYM IMAGE_SCN_MEM_SHARED}
IMAGE_SCN_MEM_EXECUTE = $20000000; // Section is executable.
{$EXTERNALSYM IMAGE_SCN_MEM_EXECUTE}
IMAGE_SCN_MEM_READ = $40000000; // Section is readable.
{$EXTERNALSYM IMAGE_SCN_MEM_READ}
IMAGE_SCN_MEM_WRITE = DWORD($80000000); // Section is writeable.
{$EXTERNALSYM IMAGE_SCN_MEM_WRITE}
//
// TLS Chaacteristic Flags
//
IMAGE_SCN_SCALE_INDEX = $00000001; // Tls index is scaled
{$EXTERNALSYM IMAGE_SCN_SCALE_INDEX}
// #include "pshpack2.h" // Symbols, relocs, and linenumbers are 2 byte packed
//
// Symbol format.
//
type
TImageSymbolN = record
case Integer of
0: (
ShortName: array [0..7] of BYTE);
1: (
Short: DWORD; // if 0, use LongName
Long: DWORD); // offset into string table
2: (
LongName: array [0..1] of DWORD);
end;
PIMAGE_SYMBOL = ^IMAGE_SYMBOL;
{$EXTERNALSYM PIMAGE_SYMBOL}
_IMAGE_SYMBOL = record
N: TImageSymbolN;
Value: DWORD;
SectionNumber: SHORT;
Type_: WORD;
StorageClass: BYTE;
NumberOfAuxSymbols: BYTE;
end;
{$EXTERNALSYM _IMAGE_SYMBOL}
IMAGE_SYMBOL = _IMAGE_SYMBOL;
{$EXTERNALSYM IMAGE_SYMBOL}
TImageSymbol = IMAGE_SYMBOL;
PImageSymbol = PIMAGE_SYMBOL;
const
IMAGE_SIZEOF_SYMBOL = 18;
{$EXTERNALSYM IMAGE_SIZEOF_SYMBOL}
//
// Section values.
//
// Symbols have a section number of the section in which they are
// defined. Otherwise, section numbers have the following meanings:
//
IMAGE_SYM_UNDEFINED = SHORT(0); // Symbol is undefined or is common.
{$EXTERNALSYM IMAGE_SYM_UNDEFINED}
IMAGE_SYM_ABSOLUTE = SHORT(-1); // Symbol is an absolute value.
{$EXTERNALSYM IMAGE_SYM_ABSOLUTE}
IMAGE_SYM_DEBUG = SHORT(-2); // Symbol is a special debug item.
{$EXTERNALSYM IMAGE_SYM_DEBUG}
IMAGE_SYM_SECTION_MAX = SHORT($FEFF ); // Values 0xFF00-0xFFFF are special
{$EXTERNALSYM IMAGE_SYM_SECTION_MAX}
//
// Type (fundamental) values.
//
IMAGE_SYM_TYPE_NULL = $0000; // no type.
{$EXTERNALSYM IMAGE_SYM_TYPE_NULL}
IMAGE_SYM_TYPE_VOID = $0001;
{$EXTERNALSYM IMAGE_SYM_TYPE_VOID}
IMAGE_SYM_TYPE_CHAR = $0002; // type character.
{$EXTERNALSYM IMAGE_SYM_TYPE_CHAR}
IMAGE_SYM_TYPE_SHORT = $0003; // type short integer.
{$EXTERNALSYM IMAGE_SYM_TYPE_SHORT}
IMAGE_SYM_TYPE_INT = $0004;
{$EXTERNALSYM IMAGE_SYM_TYPE_INT}
IMAGE_SYM_TYPE_LONG = $0005;
{$EXTERNALSYM IMAGE_SYM_TYPE_LONG}
IMAGE_SYM_TYPE_FLOAT = $0006;
{$EXTERNALSYM IMAGE_SYM_TYPE_FLOAT}
IMAGE_SYM_TYPE_DOUBLE = $0007;
{$EXTERNALSYM IMAGE_SYM_TYPE_DOUBLE}
IMAGE_SYM_TYPE_STRUCT = $0008;
{$EXTERNALSYM IMAGE_SYM_TYPE_STRUCT}
IMAGE_SYM_TYPE_UNION = $0009;
{$EXTERNALSYM IMAGE_SYM_TYPE_UNION}
IMAGE_SYM_TYPE_ENUM = $000A; // enumeration.
{$EXTERNALSYM IMAGE_SYM_TYPE_ENUM}
IMAGE_SYM_TYPE_MOE = $000B; // member of enumeration.
{$EXTERNALSYM IMAGE_SYM_TYPE_MOE}
IMAGE_SYM_TYPE_BYTE = $000C;
{$EXTERNALSYM IMAGE_SYM_TYPE_BYTE}
IMAGE_SYM_TYPE_WORD = $000D;
{$EXTERNALSYM IMAGE_SYM_TYPE_WORD}
IMAGE_SYM_TYPE_UINT = $000E;
{$EXTERNALSYM IMAGE_SYM_TYPE_UINT}
IMAGE_SYM_TYPE_DWORD = $000F;
{$EXTERNALSYM IMAGE_SYM_TYPE_DWORD}
IMAGE_SYM_TYPE_PCODE = $8000;
{$EXTERNALSYM IMAGE_SYM_TYPE_PCODE}
//
// Type (derived) values.
//
IMAGE_SYM_DTYPE_NULL = 0; // no derived type.
{$EXTERNALSYM IMAGE_SYM_DTYPE_NULL}
IMAGE_SYM_DTYPE_POINTER = 1; // pointer.
{$EXTERNALSYM IMAGE_SYM_DTYPE_POINTER}
IMAGE_SYM_DTYPE_FUNCTION = 2; // function.
{$EXTERNALSYM IMAGE_SYM_DTYPE_FUNCTION}
IMAGE_SYM_DTYPE_ARRAY = 3; // array.
{$EXTERNALSYM IMAGE_SYM_DTYPE_ARRAY}
//
// Storage classes.
//
IMAGE_SYM_CLASS_END_OF_FUNCTION = BYTE(-1);
{$EXTERNALSYM IMAGE_SYM_CLASS_END_OF_FUNCTION}
IMAGE_SYM_CLASS_NULL = $0000;
{$EXTERNALSYM IMAGE_SYM_CLASS_NULL}
IMAGE_SYM_CLASS_AUTOMATIC = $0001;
{$EXTERNALSYM IMAGE_SYM_CLASS_AUTOMATIC}
IMAGE_SYM_CLASS_EXTERNAL = $0002;
{$EXTERNALSYM IMAGE_SYM_CLASS_EXTERNAL}
IMAGE_SYM_CLASS_STATIC = $0003;
{$EXTERNALSYM IMAGE_SYM_CLASS_STATIC}
IMAGE_SYM_CLASS_REGISTER = $0004;
{$EXTERNALSYM IMAGE_SYM_CLASS_REGISTER}
IMAGE_SYM_CLASS_EXTERNAL_DEF = $0005;
{$EXTERNALSYM IMAGE_SYM_CLASS_EXTERNAL_DEF}
IMAGE_SYM_CLASS_LABEL = $0006;
{$EXTERNALSYM IMAGE_SYM_CLASS_LABEL}
IMAGE_SYM_CLASS_UNDEFINED_LABEL = $0007;
{$EXTERNALSYM IMAGE_SYM_CLASS_UNDEFINED_LABEL}
IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = $0008;
{$EXTERNALSYM IMAGE_SYM_CLASS_MEMBER_OF_STRUCT}
IMAGE_SYM_CLASS_ARGUMENT = $0009;
{$EXTERNALSYM IMAGE_SYM_CLASS_ARGUMENT}
IMAGE_SYM_CLASS_STRUCT_TAG = $000A;
{$EXTERNALSYM IMAGE_SYM_CLASS_STRUCT_TAG}
IMAGE_SYM_CLASS_MEMBER_OF_UNION = $000B;
{$EXTERNALSYM IMAGE_SYM_CLASS_MEMBER_OF_UNION}
IMAGE_SYM_CLASS_UNION_TAG = $000C;
{$EXTERNALSYM IMAGE_SYM_CLASS_UNION_TAG}
IMAGE_SYM_CLASS_TYPE_DEFINITION = $000D;
{$EXTERNALSYM IMAGE_SYM_CLASS_TYPE_DEFINITION}
IMAGE_SYM_CLASS_UNDEFINED_STATIC = $000E;
{$EXTERNALSYM IMAGE_SYM_CLASS_UNDEFINED_STATIC}
IMAGE_SYM_CLASS_ENUM_TAG = $000F;
{$EXTERNALSYM IMAGE_SYM_CLASS_ENUM_TAG}
IMAGE_SYM_CLASS_MEMBER_OF_ENUM = $0010;
{$EXTERNALSYM IMAGE_SYM_CLASS_MEMBER_OF_ENUM}
IMAGE_SYM_CLASS_REGISTER_PARAM = $0011;
{$EXTERNALSYM IMAGE_SYM_CLASS_REGISTER_PARAM}
IMAGE_SYM_CLASS_BIT_FIELD = $0012;
{$EXTERNALSYM IMAGE_SYM_CLASS_BIT_FIELD}
IMAGE_SYM_CLASS_FAR_EXTERNAL = $0044;
{$EXTERNALSYM IMAGE_SYM_CLASS_FAR_EXTERNAL}
IMAGE_SYM_CLASS_BLOCK = $0064;
{$EXTERNALSYM IMAGE_SYM_CLASS_BLOCK}
IMAGE_SYM_CLASS_FUNCTION = $0065;
{$EXTERNALSYM IMAGE_SYM_CLASS_FUNCTION}
IMAGE_SYM_CLASS_END_OF_STRUCT = $0066;
{$EXTERNALSYM IMAGE_SYM_CLASS_END_OF_STRUCT}
IMAGE_SYM_CLASS_FILE = $0067;
{$EXTERNALSYM IMAGE_SYM_CLASS_FILE}
// new
IMAGE_SYM_CLASS_SECTION = $0068;
{$EXTERNALSYM IMAGE_SYM_CLASS_SECTION}
IMAGE_SYM_CLASS_WEAK_EXTERNAL = $0069;
{$EXTERNALSYM IMAGE_SYM_CLASS_WEAK_EXTERNAL}
IMAGE_SYM_CLASS_CLR_TOKEN = $006B;
{$EXTERNALSYM IMAGE_SYM_CLASS_CLR_TOKEN}
// type packing constants
N_BTMASK = $000F;
{$EXTERNALSYM N_BTMASK}
N_TMASK = $0030;
{$EXTERNALSYM N_TMASK}
N_TMASK1 = $00C0;
{$EXTERNALSYM N_TMASK1}
N_TMASK2 = $00F0;
{$EXTERNALSYM N_TMASK2}
N_BTSHFT = 4;
{$EXTERNALSYM N_BTSHFT}
N_TSHIFT = 2;
{$EXTERNALSYM N_TSHIFT}
//
// Auxiliary entry format.
//
type
TImgAuzSymSymMisc = record
case Integer of
0: (
Linenumber: WORD; // declaration line number
Size: WORD); // size of struct, union, or enum
1: (
TotalSize: DWORD);
end;
TImgAuzSymSymFcnAry = record
case Integer of
0: ( // if ISFCN, tag, or .bb
PointerToLinenumber: DWORD;
PointerToNextFunction: DWORD);
1: ( // if ISARY, up to 4 dimen.
Dimension: array [0..3] of WORD);
end;
TImgAuxSymSym = record
TagIndex: DWORD; // struct, union, or enum tag index
Misc: TImgAuzSymSymMisc;
FcnAry: TImgAuzSymSymFcnAry;
TvIndex: WORD; // tv index
end;
TImgAuxSymFile = record
Name: array [0..IMAGE_SIZEOF_SYMBOL - 1] of BYTE;
end;
TImgAuxSymSection = record
Length: DWORD; // section length
NumberOfRelocations: WORD; // number of relocation entries
NumberOfLinenumbers: WORD; // number of line numbers
CheckSum: DWORD; // checksum for communal
Number: SHORT; // section number to associate with
Selection: BYTE; // communal selection type
end;
PIMAGE_AUX_SYMBOL = ^IMAGE_AUX_SYMBOL;
{$EXTERNALSYM PIMAGE_AUX_SYMBOL}
_IMAGE_AUX_SYMBOL = record
case Integer of
0: (Sym: TImgAuxSymSym);
1: (File_: TImgAuxSymFile);
2: (Section: TImgAuxSymSection);
end;
{$EXTERNALSYM _IMAGE_AUX_SYMBOL}
IMAGE_AUX_SYMBOL = _IMAGE_AUX_SYMBOL;
{$EXTERNALSYM IMAGE_AUX_SYMBOL}
TImageAuxSymbol = IMAGE_AUX_SYMBOL;
PImageAuxSymbol = PIMAGE_AUX_SYMBOL;
const
IMAGE_SIZEOF_AUX_SYMBOL = 18;
{$EXTERNALSYM IMAGE_SIZEOF_AUX_SYMBOL}
IMAGE_AUX_SYMBOL_TYPE_TOKEN_DEF = 1;
{$EXTERNALSYM IMAGE_AUX_SYMBOL_TYPE_TOKEN_DEF}
type
IMAGE_AUX_SYMBOL_TYPE = DWORD;
{$EXTERNALSYM IMAGE_AUX_SYMBOL_TYPE}
TImageAuxSymbolType = IMAGE_AUX_SYMBOL_TYPE;
IMAGE_AUX_SYMBOL_TOKEN_DEF = packed record
bAuxType: BYTE; // IMAGE_AUX_SYMBOL_TYPE
bReserved: BYTE; // Must be 0
SymbolTableIndex: DWORD;
rgbReserved: array [0..11] of BYTE; // Must be 0
end;
{$EXTERNALSYM IMAGE_AUX_SYMBOL_TOKEN_DEF}
PIMAGE_AUX_SYMBOL_TOKEN_DEF = ^IMAGE_AUX_SYMBOL_TOKEN_DEF;
{$EXTERNALSYM PIMAGE_AUX_SYMBOL_TOKEN_DEF}
TImageAuxSymbolTokenDef = IMAGE_AUX_SYMBOL_TOKEN_DEF;
PImageAuxSymbolTokenDef = PIMAGE_AUX_SYMBOL_TOKEN_DEF;
//
// Communal selection types.
//
const
IMAGE_COMDAT_SELECT_NODUPLICATES = 1;
{$EXTERNALSYM IMAGE_COMDAT_SELECT_NODUPLICATES}
IMAGE_COMDAT_SELECT_ANY = 2;
{$EXTERNALSYM IMAGE_COMDAT_SELECT_ANY}
IMAGE_COMDAT_SELECT_SAME_SIZE = 3;
{$EXTERNALSYM IMAGE_COMDAT_SELECT_SAME_SIZE}
IMAGE_COMDAT_SELECT_EXACT_MATCH = 4;
{$EXTERNALSYM IMAGE_COMDAT_SELECT_EXACT_MATCH}
IMAGE_COMDAT_SELECT_ASSOCIATIVE = 5;
{$EXTERNALSYM IMAGE_COMDAT_SELECT_ASSOCIATIVE}
IMAGE_COMDAT_SELECT_LARGEST = 6;
{$EXTERNALSYM IMAGE_COMDAT_SELECT_LARGEST}
IMAGE_COMDAT_SELECT_NEWEST = 7;
{$EXTERNALSYM IMAGE_COMDAT_SELECT_NEWEST}
IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = 1;
{$EXTERNALSYM IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY}
IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = 2;
{$EXTERNALSYM IMAGE_WEAK_EXTERN_SEARCH_LIBRARY}
IMAGE_WEAK_EXTERN_SEARCH_ALIAS = 3;
{$EXTERNALSYM IMAGE_WEAK_EXTERN_SEARCH_ALIAS}
//
// Relocation format.
//
type
TImgRelocUnion = record
case Integer of
0: (VirtualAddress: DWORD);
1: (RelocCount: DWORD); // Set to the real count when IMAGE_SCN_LNK_NRELOC_OVFL is set
end;
PIMAGE_RELOCATION = ^IMAGE_RELOCATION;
{$EXTERNALSYM PIMAGE_RELOCATION}
_IMAGE_RELOCATION = record
Union: TImgRelocUnion;
SymbolTableIndex: DWORD;
Type_: WORD;
end;
{$EXTERNALSYM _IMAGE_RELOCATION}
IMAGE_RELOCATION = _IMAGE_RELOCATION;
{$EXTERNALSYM IMAGE_RELOCATION}
TImageRelocation = IMAGE_RELOCATION;
PImageRelocation = PIMAGE_RELOCATION;
const
IMAGE_SIZEOF_RELOCATION = 10;
{$EXTERNALSYM IMAGE_SIZEOF_RELOCATION}
//
// I386 relocation types.
//
IMAGE_REL_I386_ABSOLUTE = $0000; // Reference is absolute, no relocation is necessary
{$EXTERNALSYM IMAGE_REL_I386_ABSOLUTE}
IMAGE_REL_I386_DIR16 = $0001; // Direct 16-bit reference to the symbols virtual address
{$EXTERNALSYM IMAGE_REL_I386_DIR16}
IMAGE_REL_I386_REL16 = $0002; // PC-relative 16-bit reference to the symbols virtual address
{$EXTERNALSYM IMAGE_REL_I386_REL16}
IMAGE_REL_I386_DIR32 = $0006; // Direct 32-bit reference to the symbols virtual address
{$EXTERNALSYM IMAGE_REL_I386_DIR32}
IMAGE_REL_I386_DIR32NB = $0007; // Direct 32-bit reference to the symbols virtual address, base not included
{$EXTERNALSYM IMAGE_REL_I386_DIR32NB}
IMAGE_REL_I386_SEG12 = $0009; // Direct 16-bit reference to the segment-selector bits of a 32-bit virtual address
{$EXTERNALSYM IMAGE_REL_I386_SEG12}
IMAGE_REL_I386_SECTION = $000A;
{$EXTERNALSYM IMAGE_REL_I386_SECTION}
IMAGE_REL_I386_SECREL = $000B;
{$EXTERNALSYM IMAGE_REL_I386_SECREL}
IMAGE_REL_MIPS_SECRELLO = $000C; // Low 16-bit section relative referemce (used for >32k TLS)
{$EXTERNALSYM IMAGE_REL_MIPS_SECRELLO}
IMAGE_REL_MIPS_SECRELHI = $000D; // High 16-bit section relative reference (used for >32k TLS)
{$EXTERNALSYM IMAGE_REL_MIPS_SECRELHI}
IMAGE_REL_I386_REL32 = $0014; // PC-relative 32-bit reference to the symbols virtual address
{$EXTERNALSYM IMAGE_REL_I386_REL32}
//
// MIPS relocation types.
//
IMAGE_REL_MIPS_ABSOLUTE = $0000; // Reference is absolute, no relocation is necessary
{$EXTERNALSYM IMAGE_REL_MIPS_ABSOLUTE}
IMAGE_REL_MIPS_REFHALF = $0001;
{$EXTERNALSYM IMAGE_REL_MIPS_REFHALF}
IMAGE_REL_MIPS_REFWORD = $0002;
{$EXTERNALSYM IMAGE_REL_MIPS_REFWORD}
IMAGE_REL_MIPS_JMPADDR = $0003;
{$EXTERNALSYM IMAGE_REL_MIPS_JMPADDR}
IMAGE_REL_MIPS_REFHI = $0004;
{$EXTERNALSYM IMAGE_REL_MIPS_REFHI}
IMAGE_REL_MIPS_REFLO = $0005;
{$EXTERNALSYM IMAGE_REL_MIPS_REFLO}
IMAGE_REL_MIPS_GPREL = $0006;
{$EXTERNALSYM IMAGE_REL_MIPS_GPREL}
IMAGE_REL_MIPS_LITERAL = $0007;
{$EXTERNALSYM IMAGE_REL_MIPS_LITERAL}
IMAGE_REL_MIPS_SECTION = $000A;
{$EXTERNALSYM IMAGE_REL_MIPS_SECTION}
IMAGE_REL_MIPS_SECREL = $000B;
{$EXTERNALSYM IMAGE_REL_MIPS_SECREL}
//IMAGE_REL_MIPS_SECRELLO = $000C; // Low 16-bit section relative referemce (used for >32k TLS)
//{$EXTERNALSYM IMAGE_REL_MIPS_SECRELLO}
//IMAGE_REL_MIPS_SECRELHI = $000D; // High 16-bit section relative reference (used for >32k TLS)
//{$EXTERNALSYM IMAGE_REL_MIPS_SECRELHI}
IMAGE_REL_MIPS_TOKEN = $000E; // clr token
{$EXTERNALSYM IMAGE_REL_MIPS_TOKEN}
IMAGE_REL_MIPS_JMPADDR16 = $0010;
{$EXTERNALSYM IMAGE_REL_MIPS_JMPADDR16}
IMAGE_REL_MIPS_REFWORDNB = $0022;
{$EXTERNALSYM IMAGE_REL_MIPS_REFWORDNB}
IMAGE_REL_MIPS_PAIR = $0025;
{$EXTERNALSYM IMAGE_REL_MIPS_PAIR}
//
// Alpha Relocation types.
//
IMAGE_REL_ALPHA_ABSOLUTE = $0000;
{$EXTERNALSYM IMAGE_REL_ALPHA_ABSOLUTE}
IMAGE_REL_ALPHA_REFLONG = $0001;
{$EXTERNALSYM IMAGE_REL_ALPHA_REFLONG}
IMAGE_REL_ALPHA_REFQUAD = $0002;
{$EXTERNALSYM IMAGE_REL_ALPHA_REFQUAD}
IMAGE_REL_ALPHA_GPREL32 = $0003;
{$EXTERNALSYM IMAGE_REL_ALPHA_GPREL32}
IMAGE_REL_ALPHA_LITERAL = $0004;
{$EXTERNALSYM IMAGE_REL_ALPHA_LITERAL}
IMAGE_REL_ALPHA_LITUSE = $0005;
{$EXTERNALSYM IMAGE_REL_ALPHA_LITUSE}
IMAGE_REL_ALPHA_GPDISP = $0006;
{$EXTERNALSYM IMAGE_REL_ALPHA_GPDISP}
IMAGE_REL_ALPHA_BRADDR = $0007;
{$EXTERNALSYM IMAGE_REL_ALPHA_BRADDR}
IMAGE_REL_ALPHA_HINT = $0008;
{$EXTERNALSYM IMAGE_REL_ALPHA_HINT}
IMAGE_REL_ALPHA_INLINE_REFLONG = $0009;
{$EXTERNALSYM IMAGE_REL_ALPHA_INLINE_REFLONG}
IMAGE_REL_ALPHA_REFHI = $000A;
{$EXTERNALSYM IMAGE_REL_ALPHA_REFHI}
IMAGE_REL_ALPHA_REFLO = $000B;
{$EXTERNALSYM IMAGE_REL_ALPHA_REFLO}
IMAGE_REL_ALPHA_PAIR = $000C;
{$EXTERNALSYM IMAGE_REL_ALPHA_PAIR}
IMAGE_REL_ALPHA_MATCH = $000D;
{$EXTERNALSYM IMAGE_REL_ALPHA_MATCH}
IMAGE_REL_ALPHA_SECTION = $000E;
{$EXTERNALSYM IMAGE_REL_ALPHA_SECTION}
IMAGE_REL_ALPHA_SECREL = $000F;
{$EXTERNALSYM IMAGE_REL_ALPHA_SECREL}
IMAGE_REL_ALPHA_REFLONGNB = $0010;
{$EXTERNALSYM IMAGE_REL_ALPHA_REFLONGNB}
IMAGE_REL_ALPHA_SECRELLO = $0011; // Low 16-bit section relative reference
{$EXTERNALSYM IMAGE_REL_ALPHA_SECRELLO}
IMAGE_REL_ALPHA_SECRELHI = $0012; // High 16-bit section relative reference
{$EXTERNALSYM IMAGE_REL_ALPHA_SECRELHI}
IMAGE_REL_ALPHA_REFQ3 = $0013; // High 16 bits of 48 bit reference
{$EXTERNALSYM IMAGE_REL_ALPHA_REFQ3}
IMAGE_REL_ALPHA_REFQ2 = $0014; // Middle 16 bits of 48 bit reference
{$EXTERNALSYM IMAGE_REL_ALPHA_REFQ2}
IMAGE_REL_ALPHA_REFQ1 = $0015; // Low 16 bits of 48 bit reference
{$EXTERNALSYM IMAGE_REL_ALPHA_REFQ1}
IMAGE_REL_ALPHA_GPRELLO = $0016; // Low 16-bit GP relative reference
{$EXTERNALSYM IMAGE_REL_ALPHA_GPRELLO}
IMAGE_REL_ALPHA_GPRELHI = $0017; // High 16-bit GP relative reference
{$EXTERNALSYM IMAGE_REL_ALPHA_GPRELHI}
//
// IBM PowerPC relocation types.
//
IMAGE_REL_PPC_ABSOLUTE = $0000; // NOP
{$EXTERNALSYM IMAGE_REL_PPC_ABSOLUTE}
IMAGE_REL_PPC_ADDR64 = $0001; // 64-bit address
{$EXTERNALSYM IMAGE_REL_PPC_ADDR64}
IMAGE_REL_PPC_ADDR32 = $0002; // 32-bit address
{$EXTERNALSYM IMAGE_REL_PPC_ADDR32}
IMAGE_REL_PPC_ADDR24 = $0003; // 26-bit address, shifted left 2 (branch absolute)
{$EXTERNALSYM IMAGE_REL_PPC_ADDR24}
IMAGE_REL_PPC_ADDR16 = $0004; // 16-bit address
{$EXTERNALSYM IMAGE_REL_PPC_ADDR16}
IMAGE_REL_PPC_ADDR14 = $0005; // 16-bit address, shifted left 2 (load doubleword)
{$EXTERNALSYM IMAGE_REL_PPC_ADDR14}
IMAGE_REL_PPC_REL24 = $0006; // 26-bit PC-relative offset, shifted left 2 (branch relative)
{$EXTERNALSYM IMAGE_REL_PPC_REL24}
IMAGE_REL_PPC_REL14 = $0007; // 16-bit PC-relative offset, shifted left 2 (br cond relative)
{$EXTERNALSYM IMAGE_REL_PPC_REL14}
IMAGE_REL_PPC_TOCREL16 = $0008; // 16-bit offset from TOC base
{$EXTERNALSYM IMAGE_REL_PPC_TOCREL16}
IMAGE_REL_PPC_TOCREL14 = $0009; // 16-bit offset from TOC base, shifted left 2 (load doubleword)
{$EXTERNALSYM IMAGE_REL_PPC_TOCREL14}
IMAGE_REL_PPC_ADDR32NB = $000A; // 32-bit addr w/o image base
{$EXTERNALSYM IMAGE_REL_PPC_ADDR32NB}
IMAGE_REL_PPC_SECREL = $000B; // va of containing section (as in an image sectionhdr)
{$EXTERNALSYM IMAGE_REL_PPC_SECREL}
IMAGE_REL_PPC_SECTION = $000C; // sectionheader number
{$EXTERNALSYM IMAGE_REL_PPC_SECTION}
IMAGE_REL_PPC_IFGLUE = $000D; // substitute TOC restore instruction iff symbol is glue code
{$EXTERNALSYM IMAGE_REL_PPC_IFGLUE}
IMAGE_REL_PPC_IMGLUE = $000E; // symbol is glue code; virtual address is TOC restore instruction
{$EXTERNALSYM IMAGE_REL_PPC_IMGLUE}
IMAGE_REL_PPC_SECREL16 = $000F; // va of containing section (limited to 16 bits)
{$EXTERNALSYM IMAGE_REL_PPC_SECREL16}
IMAGE_REL_PPC_REFHI = $0010;
{$EXTERNALSYM IMAGE_REL_PPC_REFHI}
IMAGE_REL_PPC_REFLO = $0011;
{$EXTERNALSYM IMAGE_REL_PPC_REFLO}
IMAGE_REL_PPC_PAIR = $0012;
{$EXTERNALSYM IMAGE_REL_PPC_PAIR}
IMAGE_REL_PPC_SECRELLO = $0013; // Low 16-bit section relative reference (used for >32k TLS)
{$EXTERNALSYM IMAGE_REL_PPC_SECRELLO}
IMAGE_REL_PPC_SECRELHI = $0014; // High 16-bit section relative reference (used for >32k TLS)
{$EXTERNALSYM IMAGE_REL_PPC_SECRELHI}
IMAGE_REL_PPC_GPREL = $0015;
{$EXTERNALSYM IMAGE_REL_PPC_GPREL}
IMAGE_REL_PPC_TOKEN = $0016; // clr token
{$EXTERNALSYM IMAGE_REL_PPC_TOKEN}
IMAGE_REL_PPC_TYPEMASK = $00FF; // mask to isolate above values in IMAGE_RELOCATION.Type
{$EXTERNALSYM IMAGE_REL_PPC_TYPEMASK}
// Flag bits in IMAGE_RELOCATION.TYPE
IMAGE_REL_PPC_NEG = $0100; // subtract reloc value rather than adding it
{$EXTERNALSYM IMAGE_REL_PPC_NEG}
IMAGE_REL_PPC_BRTAKEN = $0200; // fix branch prediction bit to predict branch taken
{$EXTERNALSYM IMAGE_REL_PPC_BRTAKEN}
IMAGE_REL_PPC_BRNTAKEN = $0400; // fix branch prediction bit to predict branch not taken
{$EXTERNALSYM IMAGE_REL_PPC_BRNTAKEN}
IMAGE_REL_PPC_TOCDEFN = $0800; // toc slot defined in file (or, data in toc)
{$EXTERNALSYM IMAGE_REL_PPC_TOCDEFN}
//
// Hitachi SH3 relocation types.
//
IMAGE_REL_SH3_ABSOLUTE = $0000; // No relocation
{$EXTERNALSYM IMAGE_REL_SH3_ABSOLUTE}
IMAGE_REL_SH3_DIRECT16 = $0001; // 16 bit direct
{$EXTERNALSYM IMAGE_REL_SH3_DIRECT16}
IMAGE_REL_SH3_DIRECT32 = $0002; // 32 bit direct
{$EXTERNALSYM IMAGE_REL_SH3_DIRECT32}
IMAGE_REL_SH3_DIRECT8 = $0003; // 8 bit direct, -128..255
{$EXTERNALSYM IMAGE_REL_SH3_DIRECT8}
IMAGE_REL_SH3_DIRECT8_WORD = $0004; // 8 bit direct .W (0 ext.)
{$EXTERNALSYM IMAGE_REL_SH3_DIRECT8_WORD}
IMAGE_REL_SH3_DIRECT8_LONG = $0005; // 8 bit direct .L (0 ext.)
{$EXTERNALSYM IMAGE_REL_SH3_DIRECT8_LONG}
IMAGE_REL_SH3_DIRECT4 = $0006; // 4 bit direct (0 ext.)
{$EXTERNALSYM IMAGE_REL_SH3_DIRECT4}
IMAGE_REL_SH3_DIRECT4_WORD = $0007; // 4 bit direct .W (0 ext.)
{$EXTERNALSYM IMAGE_REL_SH3_DIRECT4_WORD}
IMAGE_REL_SH3_DIRECT4_LONG = $0008; // 4 bit direct .L (0 ext.)
{$EXTERNALSYM IMAGE_REL_SH3_DIRECT4_LONG}
IMAGE_REL_SH3_PCREL8_WORD = $0009; // 8 bit PC relative .W
{$EXTERNALSYM IMAGE_REL_SH3_PCREL8_WORD}
IMAGE_REL_SH3_PCREL8_LONG = $000A; // 8 bit PC relative .L
{$EXTERNALSYM IMAGE_REL_SH3_PCREL8_LONG}
IMAGE_REL_SH3_PCREL12_WORD = $000B; // 12 LSB PC relative .W
{$EXTERNALSYM IMAGE_REL_SH3_PCREL12_WORD}
IMAGE_REL_SH3_STARTOF_SECTION = $000C; // Start of EXE section
{$EXTERNALSYM IMAGE_REL_SH3_STARTOF_SECTION}
IMAGE_REL_SH3_SIZEOF_SECTION = $000D; // Size of EXE section
{$EXTERNALSYM IMAGE_REL_SH3_SIZEOF_SECTION}
IMAGE_REL_SH3_SECTION = $000E; // Section table index
{$EXTERNALSYM IMAGE_REL_SH3_SECTION}
IMAGE_REL_SH3_SECREL = $000F; // Offset within section
{$EXTERNALSYM IMAGE_REL_SH3_SECREL}
IMAGE_REL_SH3_DIRECT32_NB = $0010; // 32 bit direct not based
{$EXTERNALSYM IMAGE_REL_SH3_DIRECT32_NB}
IMAGE_REL_SH3_GPREL4_LONG = $0011; // GP-relative addressing
{$EXTERNALSYM IMAGE_REL_SH3_GPREL4_LONG}
IMAGE_REL_SH3_TOKEN = $0012; // clr token
{$EXTERNALSYM IMAGE_REL_SH3_TOKEN}
IMAGE_REL_ARM_ABSOLUTE = $0000; // No relocation required
{$EXTERNALSYM IMAGE_REL_ARM_ABSOLUTE}
IMAGE_REL_ARM_ADDR32 = $0001; // 32 bit address
{$EXTERNALSYM IMAGE_REL_ARM_ADDR32}
IMAGE_REL_ARM_ADDR32NB = $0002; // 32 bit address w/o image base
{$EXTERNALSYM IMAGE_REL_ARM_ADDR32NB}
IMAGE_REL_ARM_BRANCH24 = $0003; // 24 bit offset << 2 & sign ext.
{$EXTERNALSYM IMAGE_REL_ARM_BRANCH24}
IMAGE_REL_ARM_BRANCH11 = $0004; // Thumb: 2 11 bit offsets
{$EXTERNALSYM IMAGE_REL_ARM_BRANCH11}
IMAGE_REL_ARM_TOKEN = $0005; // clr token
{$EXTERNALSYM IMAGE_REL_ARM_TOKEN}
IMAGE_REL_ARM_GPREL12 = $0006; // GP-relative addressing (ARM)
{$EXTERNALSYM IMAGE_REL_ARM_GPREL12}
IMAGE_REL_ARM_GPREL7 = $0007; // GP-relative addressing (Thumb)
{$EXTERNALSYM IMAGE_REL_ARM_GPREL7}
IMAGE_REL_ARM_BLX24 = $0008;
{$EXTERNALSYM IMAGE_REL_ARM_BLX24}
IMAGE_REL_ARM_BLX11 = $0009;
{$EXTERNALSYM IMAGE_REL_ARM_BLX11}
IMAGE_REL_ARM_SECTION = $000E; // Section table index
{$EXTERNALSYM IMAGE_REL_ARM_SECTION}
IMAGE_REL_ARM_SECREL = $000F; // Offset within section
{$EXTERNALSYM IMAGE_REL_ARM_SECREL}
IMAGE_REL_AM_ABSOLUTE = $0000;
{$EXTERNALSYM IMAGE_REL_AM_ABSOLUTE}
IMAGE_REL_AM_ADDR32 = $0001;
{$EXTERNALSYM IMAGE_REL_AM_ADDR32}
IMAGE_REL_AM_ADDR32NB = $0002;
{$EXTERNALSYM IMAGE_REL_AM_ADDR32NB}
IMAGE_REL_AM_CALL32 = $0003;
{$EXTERNALSYM IMAGE_REL_AM_CALL32}
IMAGE_REL_AM_FUNCINFO = $0004;
{$EXTERNALSYM IMAGE_REL_AM_FUNCINFO}
IMAGE_REL_AM_REL32_1 = $0005;
{$EXTERNALSYM IMAGE_REL_AM_REL32_1}
IMAGE_REL_AM_REL32_2 = $0006;
{$EXTERNALSYM IMAGE_REL_AM_REL32_2}
IMAGE_REL_AM_SECREL = $0007;
{$EXTERNALSYM IMAGE_REL_AM_SECREL}
IMAGE_REL_AM_SECTION = $0008;
{$EXTERNALSYM IMAGE_REL_AM_SECTION}
IMAGE_REL_AM_TOKEN = $0009;
{$EXTERNALSYM IMAGE_REL_AM_TOKEN}
//
// X86-64 relocations
//
IMAGE_REL_AMD64_ABSOLUTE = $0000; // Reference is absolute, no relocation is necessary
{$EXTERNALSYM IMAGE_REL_AMD64_ABSOLUTE}
IMAGE_REL_AMD64_ADDR64 = $0001; // 64-bit address (VA).
{$EXTERNALSYM IMAGE_REL_AMD64_ADDR64}
IMAGE_REL_AMD64_ADDR32 = $0002; // 32-bit address (VA).
{$EXTERNALSYM IMAGE_REL_AMD64_ADDR32}
IMAGE_REL_AMD64_ADDR32NB = $0003; // 32-bit address w/o image base (RVA).
{$EXTERNALSYM IMAGE_REL_AMD64_ADDR32NB}
IMAGE_REL_AMD64_REL32 = $0004; // 32-bit relative address from byte following reloc
{$EXTERNALSYM IMAGE_REL_AMD64_REL32}
IMAGE_REL_AMD64_REL32_1 = $0005; // 32-bit relative address from byte distance 1 from reloc
{$EXTERNALSYM IMAGE_REL_AMD64_REL32_1}
IMAGE_REL_AMD64_REL32_2 = $0006; // 32-bit relative address from byte distance 2 from reloc
{$EXTERNALSYM IMAGE_REL_AMD64_REL32_2}
IMAGE_REL_AMD64_REL32_3 = $0007; // 32-bit relative address from byte distance 3 from reloc
{$EXTERNALSYM IMAGE_REL_AMD64_REL32_3}
IMAGE_REL_AMD64_REL32_4 = $0008; // 32-bit relative address from byte distance 4 from reloc
{$EXTERNALSYM IMAGE_REL_AMD64_REL32_4}
IMAGE_REL_AMD64_REL32_5 = $0009; // 32-bit relative address from byte distance 5 from reloc
{$EXTERNALSYM IMAGE_REL_AMD64_REL32_5}
IMAGE_REL_AMD64_SECTION = $000A; // Section index
{$EXTERNALSYM IMAGE_REL_AMD64_SECTION}
IMAGE_REL_AMD64_SECREL = $000B; // 32 bit offset from base of section containing target
{$EXTERNALSYM IMAGE_REL_AMD64_SECREL}
IMAGE_REL_AMD64_SECREL7 = $000C; // 7 bit unsigned offset from base of section containing target
{$EXTERNALSYM IMAGE_REL_AMD64_SECREL7}
IMAGE_REL_AMD64_TOKEN = $000D; // 32 bit metadata token
{$EXTERNALSYM IMAGE_REL_AMD64_TOKEN}
//
// IA64 relocation types.
//
IMAGE_REL_IA64_ABSOLUTE = $0000;
{$EXTERNALSYM IMAGE_REL_IA64_ABSOLUTE}
IMAGE_REL_IA64_IMM14 = $0001;
{$EXTERNALSYM IMAGE_REL_IA64_IMM14}
IMAGE_REL_IA64_IMM22 = $0002;
{$EXTERNALSYM IMAGE_REL_IA64_IMM22}
IMAGE_REL_IA64_IMM64 = $0003;
{$EXTERNALSYM IMAGE_REL_IA64_IMM64}
IMAGE_REL_IA64_DIR32 = $0004;
{$EXTERNALSYM IMAGE_REL_IA64_DIR32}
IMAGE_REL_IA64_DIR64 = $0005;
{$EXTERNALSYM IMAGE_REL_IA64_DIR64}
IMAGE_REL_IA64_PCREL21B = $0006;
{$EXTERNALSYM IMAGE_REL_IA64_PCREL21B}
IMAGE_REL_IA64_PCREL21M = $0007;
{$EXTERNALSYM IMAGE_REL_IA64_PCREL21M}
IMAGE_REL_IA64_PCREL21F = $0008;
{$EXTERNALSYM IMAGE_REL_IA64_PCREL21F}
IMAGE_REL_IA64_GPREL22 = $0009;
{$EXTERNALSYM IMAGE_REL_IA64_GPREL22}
IMAGE_REL_IA64_LTOFF22 = $000A;
{$EXTERNALSYM IMAGE_REL_IA64_LTOFF22}
IMAGE_REL_IA64_SECTION = $000B;
{$EXTERNALSYM IMAGE_REL_IA64_SECTION}
IMAGE_REL_IA64_SECREL22 = $000C;
{$EXTERNALSYM IMAGE_REL_IA64_SECREL22}
IMAGE_REL_IA64_SECREL64I = $000D;
{$EXTERNALSYM IMAGE_REL_IA64_SECREL64I}
IMAGE_REL_IA64_SECREL32 = $000E;
{$EXTERNALSYM IMAGE_REL_IA64_SECREL32}
//
IMAGE_REL_IA64_DIR32NB = $0010;
{$EXTERNALSYM IMAGE_REL_IA64_DIR32NB}
IMAGE_REL_IA64_SREL14 = $0011;
{$EXTERNALSYM IMAGE_REL_IA64_SREL14}
IMAGE_REL_IA64_SREL22 = $0012;
{$EXTERNALSYM IMAGE_REL_IA64_SREL22}
IMAGE_REL_IA64_SREL32 = $0013;
{$EXTERNALSYM IMAGE_REL_IA64_SREL32}
IMAGE_REL_IA64_UREL32 = $0014;
{$EXTERNALSYM IMAGE_REL_IA64_UREL32}
IMAGE_REL_IA64_PCREL60X = $0015; // This is always a BRL and never converted
{$EXTERNALSYM IMAGE_REL_IA64_PCREL60X}
IMAGE_REL_IA64_PCREL60B = $0016; // If possible, convert to MBB bundle with NOP.B in slot 1
{$EXTERNALSYM IMAGE_REL_IA64_PCREL60B}
IMAGE_REL_IA64_PCREL60F = $0017; // If possible, convert to MFB bundle with NOP.F in slot 1
{$EXTERNALSYM IMAGE_REL_IA64_PCREL60F}
IMAGE_REL_IA64_PCREL60I = $0018; // If possible, convert to MIB bundle with NOP.I in slot 1
{$EXTERNALSYM IMAGE_REL_IA64_PCREL60I}
IMAGE_REL_IA64_PCREL60M = $0019; // If possible, convert to MMB bundle with NOP.M in slot 1
{$EXTERNALSYM IMAGE_REL_IA64_PCREL60M}
IMAGE_REL_IA64_IMMGPREL64 = $001A;
{$EXTERNALSYM IMAGE_REL_IA64_IMMGPREL64}
IMAGE_REL_IA64_TOKEN = $001B; // clr token
{$EXTERNALSYM IMAGE_REL_IA64_TOKEN}
IMAGE_REL_IA64_GPREL32 = $001C;
{$EXTERNALSYM IMAGE_REL_IA64_GPREL32}
IMAGE_REL_IA64_ADDEND = $001F;
{$EXTERNALSYM IMAGE_REL_IA64_ADDEND}
//
// CEF relocation types.
//
IMAGE_REL_CEF_ABSOLUTE = $0000; // Reference is absolute, no relocation is necessary
{$EXTERNALSYM IMAGE_REL_CEF_ABSOLUTE}
IMAGE_REL_CEF_ADDR32 = $0001; // 32-bit address (VA).
{$EXTERNALSYM IMAGE_REL_CEF_ADDR32}
IMAGE_REL_CEF_ADDR64 = $0002; // 64-bit address (VA).
{$EXTERNALSYM IMAGE_REL_CEF_ADDR64}
IMAGE_REL_CEF_ADDR32NB = $0003; // 32-bit address w/o image base (RVA).
{$EXTERNALSYM IMAGE_REL_CEF_ADDR32NB}
IMAGE_REL_CEF_SECTION = $0004; // Section index
{$EXTERNALSYM IMAGE_REL_CEF_SECTION}
IMAGE_REL_CEF_SECREL = $0005; // 32 bit offset from base of section containing target
{$EXTERNALSYM IMAGE_REL_CEF_SECREL}
IMAGE_REL_CEF_TOKEN = $0006; // 32 bit metadata token
{$EXTERNALSYM IMAGE_REL_CEF_TOKEN}
//
// clr relocation types.
//
IMAGE_REL_CEE_ABSOLUTE = $0000; // Reference is absolute, no relocation is necessary
{$EXTERNALSYM IMAGE_REL_CEE_ABSOLUTE}
IMAGE_REL_CEE_ADDR32 = $0001; // 32-bit address (VA).
{$EXTERNALSYM IMAGE_REL_CEE_ADDR32}
IMAGE_REL_CEE_ADDR64 = $0002; // 64-bit address (VA).
{$EXTERNALSYM IMAGE_REL_CEE_ADDR64}
IMAGE_REL_CEE_ADDR32NB = $0003; // 32-bit address w/o image base (RVA).
{$EXTERNALSYM IMAGE_REL_CEE_ADDR32NB}
IMAGE_REL_CEE_SECTION = $0004; // Section index
{$EXTERNALSYM IMAGE_REL_CEE_SECTION}
IMAGE_REL_CEE_SECREL = $0005; // 32 bit offset from base of section containing target
{$EXTERNALSYM IMAGE_REL_CEE_SECREL}
IMAGE_REL_CEE_TOKEN = $0006; // 32 bit metadata token
{$EXTERNALSYM IMAGE_REL_CEE_TOKEN}
IMAGE_REL_M32R_ABSOLUTE = $0000; // No relocation required
{$EXTERNALSYM IMAGE_REL_M32R_ABSOLUTE}
IMAGE_REL_M32R_ADDR32 = $0001; // 32 bit address
{$EXTERNALSYM IMAGE_REL_M32R_ADDR32}
IMAGE_REL_M32R_ADDR32NB = $0002; // 32 bit address w/o image base
{$EXTERNALSYM IMAGE_REL_M32R_ADDR32NB}
IMAGE_REL_M32R_ADDR24 = $0003; // 24 bit address
{$EXTERNALSYM IMAGE_REL_M32R_ADDR24}
IMAGE_REL_M32R_GPREL16 = $0004; // GP relative addressing
{$EXTERNALSYM IMAGE_REL_M32R_GPREL16}
IMAGE_REL_M32R_PCREL24 = $0005; // 24 bit offset << 2 & sign ext.
{$EXTERNALSYM IMAGE_REL_M32R_PCREL24}
IMAGE_REL_M32R_PCREL16 = $0006; // 16 bit offset << 2 & sign ext.
{$EXTERNALSYM IMAGE_REL_M32R_PCREL16}
IMAGE_REL_M32R_PCREL8 = $0007; // 8 bit offset << 2 & sign ext.
{$EXTERNALSYM IMAGE_REL_M32R_PCREL8}
IMAGE_REL_M32R_REFHALF = $0008; // 16 MSBs
{$EXTERNALSYM IMAGE_REL_M32R_REFHALF}
IMAGE_REL_M32R_REFHI = $0009; // 16 MSBs; adj for LSB sign ext.
{$EXTERNALSYM IMAGE_REL_M32R_REFHI}
IMAGE_REL_M32R_REFLO = $000A; // 16 LSBs
{$EXTERNALSYM IMAGE_REL_M32R_REFLO}
IMAGE_REL_M32R_PAIR = $000B; // Link HI and LO
{$EXTERNALSYM IMAGE_REL_M32R_PAIR}
IMAGE_REL_M32R_SECTION = $000C; // Section table index
{$EXTERNALSYM IMAGE_REL_M32R_SECTION}
IMAGE_REL_M32R_SECREL32 = $000D; // 32 bit section relative reference
{$EXTERNALSYM IMAGE_REL_M32R_SECREL32}
IMAGE_REL_M32R_TOKEN = $000E; // clr token
{$EXTERNALSYM IMAGE_REL_M32R_TOKEN}
// Please contact INTEL to get IA64-specific information
(* TODO
#define EXT_IMM64(Value, Address, Size, InstPos, ValPos)
Value |= (((ULONGLONG)((*(Address) >> InstPos) & (((ULONGLONG)1 << Size) - 1))) << ValPos) // Intel-IA64-Filler
#define INS_IMM64(Value, Address, Size, InstPos, ValPos) /* Intel-IA64-Filler */\
*(PDWORD)Address = (*(PDWORD)Address & ~(((1 << Size) - 1) << InstPos)) | /* Intel-IA64-Filler */\
((DWORD)((((ULONGLONG)Value >> ValPos) & (((ULONGLONG)1 << Size) - 1))) << InstPos) // Intel-IA64-Filler
*)
const
EMARCH_ENC_I17_IMM7B_INST_WORD_X = 3; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM7B_INST_WORD_X}
EMARCH_ENC_I17_IMM7B_SIZE_X = 7; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM7B_SIZE_X}
EMARCH_ENC_I17_IMM7B_INST_WORD_POS_X = 4; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM7B_INST_WORD_POS_X}
EMARCH_ENC_I17_IMM7B_VAL_POS_X = 0; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM7B_VAL_POS_X}
EMARCH_ENC_I17_IMM9D_INST_WORD_X = 3; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM9D_INST_WORD_X}
EMARCH_ENC_I17_IMM9D_SIZE_X = 9; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM9D_SIZE_X}
EMARCH_ENC_I17_IMM9D_INST_WORD_POS_X = 18; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM9D_INST_WORD_POS_X}
EMARCH_ENC_I17_IMM9D_VAL_POS_X = 7; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM9D_VAL_POS_X}
EMARCH_ENC_I17_IMM5C_INST_WORD_X = 3; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM5C_INST_WORD_X}
EMARCH_ENC_I17_IMM5C_SIZE_X = 5; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM5C_SIZE_X}
EMARCH_ENC_I17_IMM5C_INST_WORD_POS_X = 13; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM5C_INST_WORD_POS_X}
EMARCH_ENC_I17_IMM5C_VAL_POS_X = 16; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM5C_VAL_POS_X}
EMARCH_ENC_I17_IC_INST_WORD_X = 3; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IC_INST_WORD_X}
EMARCH_ENC_I17_IC_SIZE_X = 1; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IC_SIZE_X}
EMARCH_ENC_I17_IC_INST_WORD_POS_X = 12; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IC_INST_WORD_POS_X}
EMARCH_ENC_I17_IC_VAL_POS_X = 21; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IC_VAL_POS_X}
EMARCH_ENC_I17_IMM41a_INST_WORD_X = 1; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41a_INST_WORD_X}
EMARCH_ENC_I17_IMM41a_SIZE_X = 10; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41a_SIZE_X}
EMARCH_ENC_I17_IMM41a_INST_WORD_POS_X = 14; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41a_INST_WORD_POS_X}
EMARCH_ENC_I17_IMM41a_VAL_POS_X = 22; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41a_VAL_POS_X}
EMARCH_ENC_I17_IMM41b_INST_WORD_X = 1; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41b_INST_WORD_X}
EMARCH_ENC_I17_IMM41b_SIZE_X = 8; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41b_SIZE_X}
EMARCH_ENC_I17_IMM41b_INST_WORD_POS_X = 24; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41b_INST_WORD_POS_X}
EMARCH_ENC_I17_IMM41b_VAL_POS_X = 32; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41b_VAL_POS_X}
EMARCH_ENC_I17_IMM41c_INST_WORD_X = 2; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41c_INST_WORD_X}
EMARCH_ENC_I17_IMM41c_SIZE_X = 23; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41c_SIZE_X}
EMARCH_ENC_I17_IMM41c_INST_WORD_POS_X = 0; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41c_INST_WORD_POS_X}
EMARCH_ENC_I17_IMM41c_VAL_POS_X = 40; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_IMM41c_VAL_POS_X}
EMARCH_ENC_I17_SIGN_INST_WORD_X = 3; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_SIGN_INST_WORD_X}
EMARCH_ENC_I17_SIGN_SIZE_X = 1; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_SIGN_SIZE_X}
EMARCH_ENC_I17_SIGN_INST_WORD_POS_X = 27; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_SIGN_INST_WORD_POS_X}
EMARCH_ENC_I17_SIGN_VAL_POS_X = 63; // Intel-IA64-Filler
{$EXTERNALSYM EMARCH_ENC_I17_SIGN_VAL_POS_X}
//
// Line number format.
//
type
TImgLineNoType = record
case Integer of
0: (SymbolTableIndex: DWORD); // Symbol table index of function name if Linenumber is 0.
1: (VirtualAddress: DWORD); // Virtual address of line number.
end;
PIMAGE_LINENUMBER = ^IMAGE_LINENUMBER;
{$EXTERNALSYM PIMAGE_LINENUMBER}
_IMAGE_LINENUMBER = record
Type_: TImgLineNoType;
Linenumber: WORD; // Line number.
end;
{$EXTERNALSYM _IMAGE_LINENUMBER}
IMAGE_LINENUMBER = _IMAGE_LINENUMBER;
{$EXTERNALSYM IMAGE_LINENUMBER}
TImageLineNumber = IMAGE_LINENUMBER;
PImageLineNumber = PIMAGE_LINENUMBER;
const
IMAGE_SIZEOF_LINENUMBER = 6;
{$EXTERNALSYM IMAGE_SIZEOF_LINENUMBER}
// #include "poppack.h" // Back to 4 byte packing
//
// Based relocation format.
//
type
PIMAGE_BASE_RELOCATION = ^IMAGE_BASE_RELOCATION;
{$EXTERNALSYM PIMAGE_BASE_RELOCATION}
_IMAGE_BASE_RELOCATION = record
VirtualAddress: DWORD;
SizeOfBlock: DWORD;
// WORD TypeOffset[1];
end;
{$EXTERNALSYM _IMAGE_BASE_RELOCATION}
IMAGE_BASE_RELOCATION = _IMAGE_BASE_RELOCATION;
{$EXTERNALSYM IMAGE_BASE_RELOCATION}
TImageBaseRelocation = IMAGE_BASE_RELOCATION;
PImageBaseRelocation = PIMAGE_BASE_RELOCATION;
const
IMAGE_SIZEOF_BASE_RELOCATION = 8;
{$EXTERNALSYM IMAGE_SIZEOF_BASE_RELOCATION}
//
// Based relocation types.
//
IMAGE_REL_BASED_ABSOLUTE = 0;
{$EXTERNALSYM IMAGE_REL_BASED_ABSOLUTE}
IMAGE_REL_BASED_HIGH = 1;
{$EXTERNALSYM IMAGE_REL_BASED_HIGH}
IMAGE_REL_BASED_LOW = 2;
{$EXTERNALSYM IMAGE_REL_BASED_LOW}
IMAGE_REL_BASED_HIGHLOW = 3;
{$EXTERNALSYM IMAGE_REL_BASED_HIGHLOW}
IMAGE_REL_BASED_HIGHADJ = 4;
{$EXTERNALSYM IMAGE_REL_BASED_HIGHADJ}
IMAGE_REL_BASED_MIPS_JMPADDR = 5;
{$EXTERNALSYM IMAGE_REL_BASED_MIPS_JMPADDR}
IMAGE_REL_BASED_MIPS_JMPADDR16 = 9;
{$EXTERNALSYM IMAGE_REL_BASED_MIPS_JMPADDR16}
IMAGE_REL_BASED_IA64_IMM64 = 9;
{$EXTERNALSYM IMAGE_REL_BASED_IA64_IMM64}
IMAGE_REL_BASED_DIR64 = 10;
{$EXTERNALSYM IMAGE_REL_BASED_DIR64}
//
// Archive format.
//
IMAGE_ARCHIVE_START_SIZE = 8;
{$EXTERNALSYM IMAGE_ARCHIVE_START_SIZE}
IMAGE_ARCHIVE_START = '!<arch>\n';
{$EXTERNALSYM IMAGE_ARCHIVE_START}
IMAGE_ARCHIVE_END = '`\n';
{$EXTERNALSYM IMAGE_ARCHIVE_END}
IMAGE_ARCHIVE_PAD = '\n';
{$EXTERNALSYM IMAGE_ARCHIVE_PAD}
IMAGE_ARCHIVE_LINKER_MEMBER = '/ ';
{$EXTERNALSYM IMAGE_ARCHIVE_LINKER_MEMBER}
IMAGE_ARCHIVE_LONGNAMES_MEMBER = '// ';
{$EXTERNALSYM IMAGE_ARCHIVE_LONGNAMES_MEMBER}
type
PIMAGE_ARCHIVE_MEMBER_HEADER = ^IMAGE_ARCHIVE_MEMBER_HEADER;
{$EXTERNALSYM PIMAGE_ARCHIVE_MEMBER_HEADER}
_IMAGE_ARCHIVE_MEMBER_HEADER = record
Name: array [0..15] of Byte; // File member name - `/' terminated.
Date: array [0..11] of Byte; // File member date - decimal.
UserID: array [0..5] of Byte; // File member user id - decimal.
GroupID: array [0..5] of Byte; // File member group id - decimal.
Mode: array [0..7] of Byte; // File member mode - octal.
Size: array [0..9] of Byte; // File member size - decimal.
EndHeader: array [0..1] of Byte; // String to end header.
end;
{$EXTERNALSYM _IMAGE_ARCHIVE_MEMBER_HEADER}
IMAGE_ARCHIVE_MEMBER_HEADER = _IMAGE_ARCHIVE_MEMBER_HEADER;
{$EXTERNALSYM IMAGE_ARCHIVE_MEMBER_HEADER}
TImageArchiveMemberHeader = IMAGE_ARCHIVE_MEMBER_HEADER;
PImageArchiveMemberHeader = PIMAGE_ARCHIVE_MEMBER_HEADER;
const
IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR = 60;
{$EXTERNALSYM IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR}
//
// DLL support.
//
//
// Export Format
//
type
PIMAGE_EXPORT_DIRECTORY = ^IMAGE_EXPORT_DIRECTORY;
{$EXTERNALSYM PIMAGE_EXPORT_DIRECTORY}
_IMAGE_EXPORT_DIRECTORY = record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: Word;
MinorVersion: Word;
Name: DWORD;
Base: DWORD;
NumberOfFunctions: DWORD;
NumberOfNames: DWORD;
AddressOfFunctions: DWORD; // RVA from base of image
AddressOfNames: DWORD; // RVA from base of image
AddressOfNameOrdinals: DWORD; // RVA from base of image
end;
{$EXTERNALSYM _IMAGE_EXPORT_DIRECTORY}
IMAGE_EXPORT_DIRECTORY = _IMAGE_EXPORT_DIRECTORY;
{$EXTERNALSYM IMAGE_EXPORT_DIRECTORY}
TImageExportDirectory = IMAGE_EXPORT_DIRECTORY;
PImageExportDirectory = PIMAGE_EXPORT_DIRECTORY;
//
// Import Format
//
PIMAGE_IMPORT_BY_NAME = ^IMAGE_IMPORT_BY_NAME;
{$EXTERNALSYM PIMAGE_IMPORT_BY_NAME}
_IMAGE_IMPORT_BY_NAME = record
Hint: Word;
Name: array [0..0] of Byte;
end;
{$EXTERNALSYM _IMAGE_IMPORT_BY_NAME}
IMAGE_IMPORT_BY_NAME = _IMAGE_IMPORT_BY_NAME;
{$EXTERNALSYM IMAGE_IMPORT_BY_NAME}
TImageImportByName = IMAGE_IMPORT_BY_NAME;
PImageImportByName = PIMAGE_IMPORT_BY_NAME;
// #include "pshpack8.h" // Use align 8 for the 64-bit IAT.
PIMAGE_THUNK_DATA64 = ^IMAGE_THUNK_DATA64;
{$EXTERNALSYM PIMAGE_THUNK_DATA64}
_IMAGE_THUNK_DATA64 = record
case Integer of
0: (ForwarderString: ULONGLONG); // PBYTE
1: (Function_: ULONGLONG); // PDWORD
2: (Ordinal: ULONGLONG);
3: (AddressOfData: ULONGLONG); // PIMAGE_IMPORT_BY_NAME
end;
{$EXTERNALSYM _IMAGE_THUNK_DATA64}
IMAGE_THUNK_DATA64 = _IMAGE_THUNK_DATA64;
{$EXTERNALSYM IMAGE_THUNK_DATA64}
TImageThunkData64 = IMAGE_THUNK_DATA64;
PImageThunkData64 = PIMAGE_THUNK_DATA64;
// #include "poppack.h" // Back to 4 byte packing
PIMAGE_THUNK_DATA32 = ^IMAGE_THUNK_DATA32;
{$EXTERNALSYM PIMAGE_THUNK_DATA32}
_IMAGE_THUNK_DATA32 = record
case Integer of
0: (ForwarderString: DWORD); // PBYTE
1: (Function_: DWORD); // PDWORD
2: (Ordinal: DWORD);
3: (AddressOfData: DWORD); // PIMAGE_IMPORT_BY_NAME
end;
{$EXTERNALSYM _IMAGE_THUNK_DATA32}
IMAGE_THUNK_DATA32 = _IMAGE_THUNK_DATA32;
{$EXTERNALSYM IMAGE_THUNK_DATA32}
TImageThunkData32 = IMAGE_THUNK_DATA32;
PImageThunkData32 = PIMAGE_THUNK_DATA32;
const
IMAGE_ORDINAL_FLAG64 = ULONGLONG($8000000000000000);
{$EXTERNALSYM IMAGE_ORDINAL_FLAG64}
IMAGE_ORDINAL_FLAG32 = DWORD($80000000);
{$EXTERNALSYM IMAGE_ORDINAL_FLAG32}
//
// Thread Local Storage
//
type
PIMAGE_TLS_CALLBACK = procedure (DllHandle: Pointer; Reason: DWORD; Reserved: Pointer); stdcall;
{$EXTERNALSYM PIMAGE_TLS_CALLBACK}
TImageTlsCallback = PIMAGE_TLS_CALLBACK;
PIMAGE_TLS_DIRECTORY64 = ^IMAGE_TLS_DIRECTORY64;
{$EXTERNALSYM PIMAGE_TLS_DIRECTORY64}
_IMAGE_TLS_DIRECTORY64 = record
StartAddressOfRawData: ULONGLONG;
EndAddressOfRawData: ULONGLONG;
AddressOfIndex: ULONGLONG; // PDWORD
AddressOfCallBacks: ULONGLONG; // PIMAGE_TLS_CALLBACK *;
SizeOfZeroFill: DWORD;
Characteristics: DWORD;
end;
{$EXTERNALSYM _IMAGE_TLS_DIRECTORY64}
IMAGE_TLS_DIRECTORY64 = _IMAGE_TLS_DIRECTORY64;
{$EXTERNALSYM IMAGE_TLS_DIRECTORY64}
TImageTlsDirectory64 = IMAGE_TLS_DIRECTORY64;
PImageTlsDirectory64 = PIMAGE_TLS_DIRECTORY64;
PIMAGE_TLS_DIRECTORY32 = ^IMAGE_TLS_DIRECTORY32;
{$EXTERNALSYM PIMAGE_TLS_DIRECTORY32}
_IMAGE_TLS_DIRECTORY32 = record
StartAddressOfRawData: DWORD;
EndAddressOfRawData: DWORD;
AddressOfIndex: DWORD; // PDWORD
AddressOfCallBacks: DWORD; // PIMAGE_TLS_CALLBACK *
SizeOfZeroFill: DWORD;
Characteristics: DWORD;
end;
{$EXTERNALSYM _IMAGE_TLS_DIRECTORY32}
IMAGE_TLS_DIRECTORY32 = _IMAGE_TLS_DIRECTORY32;
{$EXTERNALSYM IMAGE_TLS_DIRECTORY32}
TImageTlsDirectory32 = IMAGE_TLS_DIRECTORY32;
PImageTlsDirectory32 = PIMAGE_TLS_DIRECTORY32;
const
IMAGE_ORDINAL_FLAG = IMAGE_ORDINAL_FLAG32;
{$EXTERNALSYM IMAGE_ORDINAL_FLAG}
type
IMAGE_THUNK_DATA = IMAGE_THUNK_DATA32;
{$EXTERNALSYM IMAGE_THUNK_DATA}
PIMAGE_THUNK_DATA = PIMAGE_THUNK_DATA32;
{$EXTERNALSYM PIMAGE_THUNK_DATA}
TImageThunkData = TImageThunkData32;
PImageThunkData = PImageThunkData32;
type
IMAGE_TLS_DIRECTORY = IMAGE_TLS_DIRECTORY32;
{$EXTERNALSYM IMAGE_TLS_DIRECTORY}
PIMAGE_TLS_DIRECTORY = PIMAGE_TLS_DIRECTORY32;
{$EXTERNALSYM PIMAGE_TLS_DIRECTORY}
TImageTlsDirectory = TImageTlsDirectory32;
PImageTlsDirectory = PImageTlsDirectory32;
TIIDUnion = record
case Integer of
0: (Characteristics: DWORD); // 0 for terminating null import descriptor
1: (OriginalFirstThunk: DWORD); // RVA to original unbound IAT (PIMAGE_THUNK_DATA)
end;
PIMAGE_IMPORT_DESCRIPTOR = ^IMAGE_IMPORT_DESCRIPTOR;
{$EXTERNALSYM PIMAGE_IMPORT_DESCRIPTOR}
_IMAGE_IMPORT_DESCRIPTOR = record
Union: TIIDUnion;
TimeDateStamp: DWORD; // 0 if not bound,
// -1 if bound, and real date\time stamp
// in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT (new BIND)
// O.W. date/time stamp of DLL bound to (Old BIND)
ForwarderChain: DWORD; // -1 if no forwarders
Name: DWORD;
FirstThunk: DWORD; // RVA to IAT (if bound this IAT has actual addresses)
end;
{$EXTERNALSYM _IMAGE_IMPORT_DESCRIPTOR}
IMAGE_IMPORT_DESCRIPTOR = _IMAGE_IMPORT_DESCRIPTOR;
{$EXTERNALSYM IMAGE_IMPORT_DESCRIPTOR}
TImageImportDecriptor = IMAGE_IMPORT_DESCRIPTOR;
PImageImportDecriptor = PIMAGE_IMPORT_DESCRIPTOR;
//
// New format import descriptors pointed to by DataDirectory[ IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT ]
//
type
PIMAGE_BOUND_IMPORT_DESCRIPTOR = ^IMAGE_BOUND_IMPORT_DESCRIPTOR;
{$EXTERNALSYM PIMAGE_BOUND_IMPORT_DESCRIPTOR}
_IMAGE_BOUND_IMPORT_DESCRIPTOR = record
TimeDateStamp: DWORD;
OffsetModuleName: Word;
NumberOfModuleForwarderRefs: Word;
// Array of zero or more IMAGE_BOUND_FORWARDER_REF follows
end;
{$EXTERNALSYM _IMAGE_BOUND_IMPORT_DESCRIPTOR}
IMAGE_BOUND_IMPORT_DESCRIPTOR = _IMAGE_BOUND_IMPORT_DESCRIPTOR;
{$EXTERNALSYM IMAGE_BOUND_IMPORT_DESCRIPTOR}
TImageBoundImportDescriptor = IMAGE_BOUND_IMPORT_DESCRIPTOR;
PImageBoundImportDescriptor = PIMAGE_BOUND_IMPORT_DESCRIPTOR;
PIMAGE_BOUND_FORWARDER_REF = ^IMAGE_BOUND_FORWARDER_REF;
{$EXTERNALSYM PIMAGE_BOUND_FORWARDER_REF}
_IMAGE_BOUND_FORWARDER_REF = record
TimeDateStamp: DWORD;
OffsetModuleName: Word;
Reserved: Word;
end;
{$EXTERNALSYM _IMAGE_BOUND_FORWARDER_REF}
IMAGE_BOUND_FORWARDER_REF = _IMAGE_BOUND_FORWARDER_REF;
{$EXTERNALSYM IMAGE_BOUND_FORWARDER_REF}
TImageBoundForwarderRef = IMAGE_BOUND_FORWARDER_REF;
PImageBoundForwarderRef = PIMAGE_BOUND_FORWARDER_REF;
//
// Resource Format.
//
//
// Resource directory consists of two counts, following by a variable length
// array of directory entries. The first count is the number of entries at
// beginning of the array that have actual names associated with each entry.
// The entries are in ascending order, case insensitive strings. The second
// count is the number of entries that immediately follow the named entries.
// This second count identifies the number of entries that have 16-bit integer
// Ids as their name. These entries are also sorted in ascending order.
//
// This structure allows fast lookup by either name or number, but for any
// given resource entry only one form of lookup is supported, not both.
// This is consistant with the syntax of the .RC file and the .RES file.
//
PIMAGE_RESOURCE_DIRECTORY = ^IMAGE_RESOURCE_DIRECTORY;
{$EXTERNALSYM PIMAGE_RESOURCE_DIRECTORY}
_IMAGE_RESOURCE_DIRECTORY = record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: Word;
MinorVersion: Word;
NumberOfNamedEntries: Word;
NumberOfIdEntries: Word;
// IMAGE_RESOURCE_DIRECTORY_ENTRY DirectoryEntries[];
end;
{$EXTERNALSYM _IMAGE_RESOURCE_DIRECTORY}
IMAGE_RESOURCE_DIRECTORY = _IMAGE_RESOURCE_DIRECTORY;
{$EXTERNALSYM IMAGE_RESOURCE_DIRECTORY}
TImageResourceDirectory = IMAGE_RESOURCE_DIRECTORY;
PImageResourceDirectory = PIMAGE_RESOURCE_DIRECTORY;
const
IMAGE_RESOURCE_NAME_IS_STRING = DWORD($80000000);
{$EXTERNALSYM IMAGE_RESOURCE_NAME_IS_STRING}
IMAGE_RESOURCE_DATA_IS_DIRECTORY = DWORD($80000000);
{$EXTERNALSYM IMAGE_RESOURCE_DATA_IS_DIRECTORY}
//
// Each directory contains the 32-bit Name of the entry and an offset,
// relative to the beginning of the resource directory of the data associated
// with this directory entry. If the name of the entry is an actual text
// string instead of an integer Id, then the high order bit of the name field
// is set to one and the low order 31-bits are an offset, relative to the
// beginning of the resource directory of the string, which is of type
// IMAGE_RESOURCE_DIRECTORY_STRING. Otherwise the high bit is clear and the
// low-order 16-bits are the integer Id that identify this resource directory
// entry. If the directory entry is yet another resource directory (i.e. a
// subdirectory), then the high order bit of the offset field will be
// set to indicate this. Otherwise the high bit is clear and the offset
// field points to a resource data entry.
//
type
TIRDEName = record
case Integer of
0: (
NameOffset: DWORD); // 0..30: NameOffset; 31: NameIsString
1: (
Name: DWORD);
2: (
Id: WORD);
end;
TIRDEDirectory = record
case Integer of
0: (
OffsetToData: DWORD);
1: (
OffsetToDirectory: DWORD); // 0..30: OffsetToDirectory; 31: DataIsDirectory
end;
PIMAGE_RESOURCE_DIRECTORY_ENTRY = ^IMAGE_RESOURCE_DIRECTORY_ENTRY;
{$EXTERNALSYM PIMAGE_RESOURCE_DIRECTORY_ENTRY}
_IMAGE_RESOURCE_DIRECTORY_ENTRY = record
Name: TIRDEName;
Directory: TIRDEDirectory;
end;
{$EXTERNALSYM _IMAGE_RESOURCE_DIRECTORY_ENTRY}
IMAGE_RESOURCE_DIRECTORY_ENTRY = _IMAGE_RESOURCE_DIRECTORY_ENTRY;
{$EXTERNALSYM IMAGE_RESOURCE_DIRECTORY_ENTRY}
TImageResourceDirectoryEntry = IMAGE_RESOURCE_DIRECTORY_ENTRY;
PImageResourceDirectoryEntry = PIMAGE_RESOURCE_DIRECTORY_ENTRY;
//
// For resource directory entries that have actual string names, the Name
// field of the directory entry points to an object of the following type.
// All of these string objects are stored together after the last resource
// directory entry and before the first resource data object. This minimizes
// the impact of these variable length objects on the alignment of the fixed
// size directory entry objects.
//
type
PIMAGE_RESOURCE_DIRECTORY_STRING = ^IMAGE_RESOURCE_DIRECTORY_STRING;
{$EXTERNALSYM PIMAGE_RESOURCE_DIRECTORY_STRING}
_IMAGE_RESOURCE_DIRECTORY_STRING = record
Length: Word;
NameString: array [0..0] of CHAR;
end;
{$EXTERNALSYM _IMAGE_RESOURCE_DIRECTORY_STRING}
IMAGE_RESOURCE_DIRECTORY_STRING = _IMAGE_RESOURCE_DIRECTORY_STRING;
{$EXTERNALSYM IMAGE_RESOURCE_DIRECTORY_STRING}
TImageResourceDirectoryString = IMAGE_RESOURCE_DIRECTORY_STRING;
PImageResourceDirectoryString = PIMAGE_RESOURCE_DIRECTORY_STRING;
PIMAGE_RESOURCE_DIR_STRING_U = ^IMAGE_RESOURCE_DIR_STRING_U;
{$EXTERNALSYM PIMAGE_RESOURCE_DIR_STRING_U}
_IMAGE_RESOURCE_DIR_STRING_U = record
Length: Word;
NameString: array [0..0] of WCHAR;
end;
{$EXTERNALSYM _IMAGE_RESOURCE_DIR_STRING_U}
IMAGE_RESOURCE_DIR_STRING_U = _IMAGE_RESOURCE_DIR_STRING_U;
{$EXTERNALSYM IMAGE_RESOURCE_DIR_STRING_U}
TImageResourceDirStringU = IMAGE_RESOURCE_DIR_STRING_U;
PImageResourceDirStringU = PIMAGE_RESOURCE_DIR_STRING_U;
//
// Each resource data entry describes a leaf node in the resource directory
// tree. It contains an offset, relative to the beginning of the resource
// directory of the data for the resource, a size field that gives the number
// of bytes of data at that offset, a CodePage that should be used when
// decoding code point values within the resource data. Typically for new
// applications the code page would be the unicode code page.
//
PIMAGE_RESOURCE_DATA_ENTRY = ^IMAGE_RESOURCE_DATA_ENTRY;
{$EXTERNALSYM PIMAGE_RESOURCE_DATA_ENTRY}
_IMAGE_RESOURCE_DATA_ENTRY = record
OffsetToData: DWORD;
Size: DWORD;
CodePage: DWORD;
Reserved: DWORD;
end;
{$EXTERNALSYM _IMAGE_RESOURCE_DATA_ENTRY}
IMAGE_RESOURCE_DATA_ENTRY = _IMAGE_RESOURCE_DATA_ENTRY;
{$EXTERNALSYM IMAGE_RESOURCE_DATA_ENTRY}
TImageResourceDataEntry = IMAGE_RESOURCE_DATA_ENTRY;
PImageResourceDataEntry = PIMAGE_RESOURCE_DATA_ENTRY;
//
// Load Configuration Directory Entry
//
type
PIMAGE_LOAD_CONFIG_DIRECTORY32 = ^IMAGE_LOAD_CONFIG_DIRECTORY32;
{$EXTERNALSYM PIMAGE_LOAD_CONFIG_DIRECTORY32}
IMAGE_LOAD_CONFIG_DIRECTORY32 = record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: WORD;
MinorVersion: WORD;
GlobalFlagsClear: DWORD;
GlobalFlagsSet: DWORD;
CriticalSectionDefaultTimeout: DWORD;
DeCommitFreeBlockThreshold: DWORD;
DeCommitTotalFreeThreshold: DWORD;
LockPrefixTable: DWORD; // VA
MaximumAllocationSize: DWORD;
VirtualMemoryThreshold: DWORD;
ProcessHeapFlags: DWORD;
ProcessAffinityMask: DWORD;
CSDVersion: WORD;
Reserved1: WORD;
EditList: DWORD; // VA
Reserved: array [0..0] of DWORD;
end;
{$EXTERNALSYM IMAGE_LOAD_CONFIG_DIRECTORY32}
TImageLoadConfigDirectory32 = IMAGE_LOAD_CONFIG_DIRECTORY32;
PImageLoadConfigDirectory32 = PIMAGE_LOAD_CONFIG_DIRECTORY32;
PIMAGE_LOAD_CONFIG_DIRECTORY64 = ^IMAGE_LOAD_CONFIG_DIRECTORY64;
{$EXTERNALSYM PIMAGE_LOAD_CONFIG_DIRECTORY64}
IMAGE_LOAD_CONFIG_DIRECTORY64 = record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: WORD;
MinorVersion: WORD;
GlobalFlagsClear: DWORD;
GlobalFlagsSet: DWORD;
CriticalSectionDefaultTimeout: DWORD;
DeCommitFreeBlockThreshold: ULONGLONG;
DeCommitTotalFreeThreshold: ULONGLONG;
LockPrefixTable: ULONGLONG; // VA
MaximumAllocationSize: ULONGLONG;
VirtualMemoryThreshold: ULONGLONG;
ProcessAffinityMask: ULONGLONG;
ProcessHeapFlags: DWORD;
CSDVersion: WORD;
Reserved1: WORD;
EditList: ULONGLONG; // VA
Reserved: array [0..1] of DWORD;
end;
{$EXTERNALSYM IMAGE_LOAD_CONFIG_DIRECTORY64}
TImageLoadConfigDirectory64 = IMAGE_LOAD_CONFIG_DIRECTORY64;
PImageLoadConfigDirectory64 = PIMAGE_LOAD_CONFIG_DIRECTORY64;
IMAGE_LOAD_CONFIG_DIRECTORY = IMAGE_LOAD_CONFIG_DIRECTORY32;
{$EXTERNALSYM IMAGE_LOAD_CONFIG_DIRECTORY}
PIMAGE_LOAD_CONFIG_DIRECTORY = PIMAGE_LOAD_CONFIG_DIRECTORY32;
{$EXTERNALSYM PIMAGE_LOAD_CONFIG_DIRECTORY}
TImageLoadConfigDirectory = TImageLoadConfigDirectory32;
PImageLoadConfigDirectory = PImageLoadConfigDirectory32;
//
// WIN CE Exception table format
//
//
// Function table entry format. Function table is pointed to by the
// IMAGE_DIRECTORY_ENTRY_EXCEPTION directory entry.
//
type
PIMAGE_CE_RUNTIME_FUNCTION_ENTRY = ^IMAGE_CE_RUNTIME_FUNCTION_ENTRY;
{$EXTERNALSYM PIMAGE_CE_RUNTIME_FUNCTION_ENTRY}
_IMAGE_CE_RUNTIME_FUNCTION_ENTRY = record
FuncStart: DWORD;
Flags: DWORD;
//DWORD PrologLen : 8;
//DWORD FuncLen : 22;
//DWORD ThirtyTwoBit : 1;
//DWORD ExceptionFlag : 1;
end;
{$EXTERNALSYM _IMAGE_CE_RUNTIME_FUNCTION_ENTRY}
IMAGE_CE_RUNTIME_FUNCTION_ENTRY = _IMAGE_CE_RUNTIME_FUNCTION_ENTRY;
{$EXTERNALSYM IMAGE_CE_RUNTIME_FUNCTION_ENTRY}
TImageCERuntimeFunctionEntry = IMAGE_CE_RUNTIME_FUNCTION_ENTRY;
PImageCERuntimeFunctionEntry = PIMAGE_CE_RUNTIME_FUNCTION_ENTRY;
//
// Debug Format
//
type
PIMAGE_DEBUG_DIRECTORY = ^IMAGE_DEBUG_DIRECTORY;
{$EXTERNALSYM PIMAGE_DEBUG_DIRECTORY}
_IMAGE_DEBUG_DIRECTORY = record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: Word;
MinorVersion: Word;
Type_: DWORD;
SizeOfData: DWORD;
AddressOfRawData: DWORD;
PointerToRawData: DWORD;
end;
{$EXTERNALSYM _IMAGE_DEBUG_DIRECTORY}
IMAGE_DEBUG_DIRECTORY = _IMAGE_DEBUG_DIRECTORY;
{$EXTERNALSYM IMAGE_DEBUG_DIRECTORY}
TImageDebugDirectory = IMAGE_DEBUG_DIRECTORY;
PImageDebugDirectory = PIMAGE_DEBUG_DIRECTORY;
const
IMAGE_DEBUG_TYPE_UNKNOWN = 0;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_UNKNOWN}
IMAGE_DEBUG_TYPE_COFF = 1;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_COFF}
IMAGE_DEBUG_TYPE_CODEVIEW = 2;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_CODEVIEW}
IMAGE_DEBUG_TYPE_FPO = 3;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_FPO}
IMAGE_DEBUG_TYPE_MISC = 4;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_MISC}
IMAGE_DEBUG_TYPE_EXCEPTION = 5;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_EXCEPTION}
IMAGE_DEBUG_TYPE_FIXUP = 6;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_FIXUP}
IMAGE_DEBUG_TYPE_OMAP_TO_SRC = 7;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_OMAP_TO_SRC}
IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = 8;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_OMAP_FROM_SRC}
IMAGE_DEBUG_TYPE_BORLAND = 9;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_BORLAND}
IMAGE_DEBUG_TYPE_RESERVED10 = 10;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_RESERVED10}
IMAGE_DEBUG_TYPE_CLSID = 11;
{$EXTERNALSYM IMAGE_DEBUG_TYPE_CLSID}
type
PIMAGE_COFF_SYMBOLS_HEADER = ^IMAGE_COFF_SYMBOLS_HEADER;
{$EXTERNALSYM PIMAGE_COFF_SYMBOLS_HEADER}
_IMAGE_COFF_SYMBOLS_HEADER = record
NumberOfSymbols: DWORD;
LvaToFirstSymbol: DWORD;
NumberOfLinenumbers: DWORD;
LvaToFirstLinenumber: DWORD;
RvaToFirstByteOfCode: DWORD;
RvaToLastByteOfCode: DWORD;
RvaToFirstByteOfData: DWORD;
RvaToLastByteOfData: DWORD;
end;
{$EXTERNALSYM _IMAGE_COFF_SYMBOLS_HEADER}
IMAGE_COFF_SYMBOLS_HEADER = _IMAGE_COFF_SYMBOLS_HEADER;
{$EXTERNALSYM IMAGE_COFF_SYMBOLS_HEADER}
TImageCoffSymbolsHeader = IMAGE_COFF_SYMBOLS_HEADER;
PImageCoffSymbolsHeader = PIMAGE_COFF_SYMBOLS_HEADER;
const
FRAME_FPO = 0;
{$EXTERNALSYM FRAME_FPO}
FRAME_TRAP = 1;
{$EXTERNALSYM FRAME_TRAP}
FRAME_TSS = 2;
{$EXTERNALSYM FRAME_TSS}
FRAME_NONFPO = 3;
{$EXTERNALSYM FRAME_NONFPO}
FPOFLAGS_PROLOG = $00FF; // # bytes in prolog
FPOFLAGS_REGS = $0700; // # regs saved
FPOFLAGS_HAS_SEH = $0800; // TRUE if SEH in func
FPOFLAGS_USE_BP = $1000; // TRUE if EBP has been allocated
FPOFLAGS_RESERVED = $2000; // reserved for future use
FPOFLAGS_FRAME = $C000; // frame type
type
PFPO_DATA = ^FPO_DATA;
{$EXTERNALSYM PFPO_DATA}
_FPO_DATA = record
ulOffStart: DWORD; // offset 1st byte of function code
cbProcSize: DWORD; // # bytes in function
cdwLocals: DWORD; // # bytes in locals/4
cdwParams: WORD; // # bytes in params/4
Flags: WORD;
end;
{$EXTERNALSYM _FPO_DATA}
FPO_DATA = _FPO_DATA;
{$EXTERNALSYM FPO_DATA}
TFpoData = FPO_DATA;
PFpoData = PFPO_DATA;
const
SIZEOF_RFPO_DATA = 16;
{$EXTERNALSYM SIZEOF_RFPO_DATA}
IMAGE_DEBUG_MISC_EXENAME = 1;
{$EXTERNALSYM IMAGE_DEBUG_MISC_EXENAME}
type
PIMAGE_DEBUG_MISC = ^IMAGE_DEBUG_MISC;
{$EXTERNALSYM PIMAGE_DEBUG_MISC}
_IMAGE_DEBUG_MISC = record
DataType: DWORD; // type of misc data, see defines
Length: DWORD; // total length of record, rounded to four byte multiple.
Unicode: ByteBool; // TRUE if data is unicode string
Reserved: array [0..2] of Byte;
Data: array [0..0] of Byte; // Actual data
end;
{$EXTERNALSYM _IMAGE_DEBUG_MISC}
IMAGE_DEBUG_MISC = _IMAGE_DEBUG_MISC;
{$EXTERNALSYM IMAGE_DEBUG_MISC}
TImageDebugMisc = IMAGE_DEBUG_MISC;
PImageDebugMisc = PIMAGE_DEBUG_MISC;
//
// Function table extracted from MIPS/ALPHA/IA64 images. Does not contain
// information needed only for runtime support. Just those fields for
// each entry needed by a debugger.
//
PIMAGE_FUNCTION_ENTRY = ^IMAGE_FUNCTION_ENTRY;
{$EXTERNALSYM PIMAGE_FUNCTION_ENTRY}
_IMAGE_FUNCTION_ENTRY = record
StartingAddress: DWORD;
EndingAddress: DWORD;
EndOfPrologue: DWORD;
end;
{$EXTERNALSYM _IMAGE_FUNCTION_ENTRY}
IMAGE_FUNCTION_ENTRY = _IMAGE_FUNCTION_ENTRY;
{$EXTERNALSYM IMAGE_FUNCTION_ENTRY}
TImageFunctionEntry = IMAGE_FUNCTION_ENTRY;
PImageFunctionEntry = PIMAGE_FUNCTION_ENTRY;
PIMAGE_FUNCTION_ENTRY64 = ^IMAGE_FUNCTION_ENTRY64;
{$EXTERNALSYM PIMAGE_FUNCTION_ENTRY64}
_IMAGE_FUNCTION_ENTRY64 = record
StartingAddress: ULONGLONG;
EndingAddress: ULONGLONG;
case Integer of
0: (EndOfPrologue: ULONGLONG);
1: (UnwindInfoAddress: ULONGLONG);
end;
{$EXTERNALSYM _IMAGE_FUNCTION_ENTRY64}
IMAGE_FUNCTION_ENTRY64 = _IMAGE_FUNCTION_ENTRY64;
{$EXTERNALSYM IMAGE_FUNCTION_ENTRY64}
TImageFunctionEntry64 = IMAGE_FUNCTION_ENTRY64;
PImageFunctionEntry64 = PIMAGE_FUNCTION_ENTRY64;
//
// Debugging information can be stripped from an image file and placed
// in a separate .DBG file, whose file name part is the same as the
// image file name part (e.g. symbols for CMD.EXE could be stripped
// and placed in CMD.DBG). This is indicated by the IMAGE_FILE_DEBUG_STRIPPED
// flag in the Characteristics field of the file header. The beginning of
// the .DBG file contains the following structure which captures certain
// information from the image file. This allows a debug to proceed even if
// the original image file is not accessable. This header is followed by
// zero of more IMAGE_SECTION_HEADER structures, followed by zero or more
// IMAGE_DEBUG_DIRECTORY structures. The latter structures and those in
// the image file contain file offsets relative to the beginning of the
// .DBG file.
//
// If symbols have been stripped from an image, the IMAGE_DEBUG_MISC structure
// is left in the image file, but not mapped. This allows a debugger to
// compute the name of the .DBG file, from the name of the image in the
// IMAGE_DEBUG_MISC structure.
//
PIMAGE_SEPARATE_DEBUG_HEADER = ^IMAGE_SEPARATE_DEBUG_HEADER;
{$EXTERNALSYM PIMAGE_SEPARATE_DEBUG_HEADER}
_IMAGE_SEPARATE_DEBUG_HEADER = record
Signature: Word;
Flags: Word;
Machine: Word;
Characteristics: Word;
TimeDateStamp: DWORD;
CheckSum: DWORD;
ImageBase: DWORD;
SizeOfImage: DWORD;
NumberOfSections: DWORD;
ExportedNamesSize: DWORD;
DebugDirectorySize: DWORD;
SectionAlignment: DWORD;
Reserved: array [0..1] of DWORD;
end;
{$EXTERNALSYM _IMAGE_SEPARATE_DEBUG_HEADER}
IMAGE_SEPARATE_DEBUG_HEADER = _IMAGE_SEPARATE_DEBUG_HEADER;
{$EXTERNALSYM IMAGE_SEPARATE_DEBUG_HEADER}
TImageSeparateDebugHeader = IMAGE_SEPARATE_DEBUG_HEADER;
PImageSeparateDebugHeader = PIMAGE_SEPARATE_DEBUG_HEADER;
_NON_PAGED_DEBUG_INFO = record
Signature: WORD;
Flags: WORD;
Size: DWORD;
Machine: WORD;
Characteristics: WORD;
TimeDateStamp: DWORD;
CheckSum: DWORD;
SizeOfImage: DWORD;
ImageBase: ULONGLONG;
//DebugDirectorySize
//IMAGE_DEBUG_DIRECTORY
end;
{$EXTERNALSYM _NON_PAGED_DEBUG_INFO}
NON_PAGED_DEBUG_INFO = _NON_PAGED_DEBUG_INFO;
{$EXTERNALSYM NON_PAGED_DEBUG_INFO}
PNON_PAGED_DEBUG_INFO = ^NON_PAGED_DEBUG_INFO;
{$EXTERNALSYM PNON_PAGED_DEBUG_INFO}
const
IMAGE_SEPARATE_DEBUG_SIGNATURE = $4944;
{$EXTERNALSYM IMAGE_SEPARATE_DEBUG_SIGNATURE}
NON_PAGED_DEBUG_SIGNATURE = $494E;
{$EXTERNALSYM NON_PAGED_DEBUG_SIGNATURE}
IMAGE_SEPARATE_DEBUG_FLAGS_MASK = $8000;
{$EXTERNALSYM IMAGE_SEPARATE_DEBUG_FLAGS_MASK}
IMAGE_SEPARATE_DEBUG_MISMATCH = $8000; // when DBG was updated, the old checksum didn't match.
{$EXTERNALSYM IMAGE_SEPARATE_DEBUG_MISMATCH}
//
// The .arch section is made up of headers, each describing an amask position/value
// pointing to an array of IMAGE_ARCHITECTURE_ENTRY's. Each "array" (both the header
// and entry arrays) are terminiated by a quadword of 0xffffffffL.
//
// NOTE: There may be quadwords of 0 sprinkled around and must be skipped.
//
const
IAHMASK_VALUE = $00000001; // 1 -> code section depends on mask bit
// 0 -> new instruction depends on mask bit
IAHMASK_MBZ7 = $000000FE; // MBZ
IAHMASK_SHIFT = $0000FF00; // Amask bit in question for this fixup
IAHMASK_MBZ16 = DWORD($FFFF0000); // MBZ
type
PIMAGE_ARCHITECTURE_HEADER = ^IMAGE_ARCHITECTURE_HEADER;
{$EXTERNALSYM PIMAGE_ARCHITECTURE_HEADER}
_ImageArchitectureHeader = record
Mask: DWORD;
FirstEntryRVA: DWORD; // RVA into .arch section to array of ARCHITECTURE_ENTRY's
end;
{$EXTERNALSYM _ImageArchitectureHeader}
IMAGE_ARCHITECTURE_HEADER = _ImageArchitectureHeader;
{$EXTERNALSYM IMAGE_ARCHITECTURE_HEADER}
TImageArchitectureHeader = IMAGE_ARCHITECTURE_HEADER;
PImageArchitectureHeader = PIMAGE_ARCHITECTURE_HEADER;
PIMAGE_ARCHITECTURE_ENTRY = ^IMAGE_ARCHITECTURE_ENTRY;
{$EXTERNALSYM PIMAGE_ARCHITECTURE_ENTRY}
_ImageArchitectureEntry = record
FixupInstRVA: DWORD; // RVA of instruction to fixup
NewInst: DWORD; // fixup instruction (see alphaops.h)
end;
{$EXTERNALSYM _ImageArchitectureEntry}
IMAGE_ARCHITECTURE_ENTRY = _ImageArchitectureEntry;
{$EXTERNALSYM IMAGE_ARCHITECTURE_ENTRY}
TImageArchitectureEntry = IMAGE_ARCHITECTURE_ENTRY;
PImageArchitectureEntry = PIMAGE_ARCHITECTURE_ENTRY;
// #include "poppack.h" // Back to the initial value
// The following structure defines the new import object. Note the values of the first two fields,
// which must be set as stated in order to differentiate old and new import members.
// Following this structure, the linker emits two null-terminated strings used to recreate the
// import at the time of use. The first string is the import's name, the second is the dll's name.
const
IMPORT_OBJECT_HDR_SIG2 = $ffff;
{$EXTERNALSYM IMPORT_OBJECT_HDR_SIG2}
const
IOHFLAGS_TYPE = $0003; // IMPORT_TYPE
IAHFLAGS_NAMETYPE = $001C; // IMPORT_NAME_TYPE
IAHFLAGS_RESERVED = $FFE0; // Reserved. Must be zero.
type
PImportObjectHeader = ^IMPORT_OBJECT_HEADER;
IMPORT_OBJECT_HEADER = record
Sig1: WORD; // Must be IMAGE_FILE_MACHINE_UNKNOWN
Sig2: WORD; // Must be IMPORT_OBJECT_HDR_SIG2.
Version: WORD;
Machine: WORD;
TimeDateStamp: DWORD; // Time/date stamp
SizeOfData: DWORD; // particularly useful for incremental links
OrdinalOrHint: record
case Integer of
0: (Ordinal: WORD); // if grf & IMPORT_OBJECT_ORDINAL
1: (Flags: DWORD);
end;
Flags: WORD;
//WORD Type : 2; // IMPORT_TYPE
//WORD NameType : 3; // IMPORT_NAME_TYPE
//WORD Reserved : 11; // Reserved. Must be zero.
end;
{$EXTERNALSYM IMPORT_OBJECT_HEADER}
TImportObjectHeader = IMPORT_OBJECT_HEADER;
IMPORT_OBJECT_TYPE = (IMPORT_OBJECT_CODE, IMPORT_OBJECT_DATA, IMPORT_OBJECT_CONST);
{$EXTERNALSYM IMPORT_OBJECT_TYPE}
TImportObjectType = IMPORT_OBJECT_TYPE;
IMPORT_OBJECT_NAME_TYPE = (
IMPORT_OBJECT_ORDINAL, // Import by ordinal
IMPORT_OBJECT_NAME, // Import name == public symbol name.
IMPORT_OBJECT_NAME_NO_PREFIX, // Import name == public symbol name skipping leading ?, @, or optionally _.
IMPORT_OBJECT_NAME_UNDECORATE); // Import name == public symbol name skipping leading ?, @, or optionally _
// and truncating at first @
{$EXTERNALSYM IMPORT_OBJECT_NAME_TYPE}
TImportObjectNameType = IMPORT_OBJECT_NAME_TYPE;
ReplacesCorHdrNumericDefines = DWORD;
{$EXTERNALSYM ReplacesCorHdrNumericDefines}
const
// COM+ Header entry point flags.
COMIMAGE_FLAGS_ILONLY = $00000001;
{$EXTERNALSYM COMIMAGE_FLAGS_ILONLY}
COMIMAGE_FLAGS_32BITREQUIRED = $00000002;
{$EXTERNALSYM COMIMAGE_FLAGS_32BITREQUIRED}
COMIMAGE_FLAGS_IL_LIBRARY = $00000004;
{$EXTERNALSYM COMIMAGE_FLAGS_IL_LIBRARY}
COMIMAGE_FLAGS_STRONGNAMESIGNED = $00000008;
{$EXTERNALSYM COMIMAGE_FLAGS_STRONGNAMESIGNED}
COMIMAGE_FLAGS_TRACKDEBUGDATA = $00010000;
{$EXTERNALSYM COMIMAGE_FLAGS_TRACKDEBUGDATA}
// Version flags for image.
COR_VERSION_MAJOR_V2 = 2;
{$EXTERNALSYM COR_VERSION_MAJOR_V2}
COR_VERSION_MAJOR = COR_VERSION_MAJOR_V2;
{$EXTERNALSYM COR_VERSION_MAJOR}
COR_VERSION_MINOR = 0;
{$EXTERNALSYM COR_VERSION_MINOR}
COR_DELETED_NAME_LENGTH = 8;
{$EXTERNALSYM COR_DELETED_NAME_LENGTH}
COR_VTABLEGAP_NAME_LENGTH = 8;
{$EXTERNALSYM COR_VTABLEGAP_NAME_LENGTH}
// Maximum size of a NativeType descriptor.
NATIVE_TYPE_MAX_CB = 1;
{$EXTERNALSYM NATIVE_TYPE_MAX_CB}
COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE= $FF;
{$EXTERNALSYM COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE}
// #defines for the MIH FLAGS
IMAGE_COR_MIH_METHODRVA = $01;
{$EXTERNALSYM IMAGE_COR_MIH_METHODRVA}
IMAGE_COR_MIH_EHRVA = $02;
{$EXTERNALSYM IMAGE_COR_MIH_EHRVA}
IMAGE_COR_MIH_BASICBLOCK = $08;
{$EXTERNALSYM IMAGE_COR_MIH_BASICBLOCK}
// V-table constants
COR_VTABLE_32BIT = $01; // V-table slots are 32-bits in size.
{$EXTERNALSYM COR_VTABLE_32BIT}
COR_VTABLE_64BIT = $02; // V-table slots are 64-bits in size.
{$EXTERNALSYM COR_VTABLE_64BIT}
COR_VTABLE_FROM_UNMANAGED = $04; // If set, transition from unmanaged.
{$EXTERNALSYM COR_VTABLE_FROM_UNMANAGED}
COR_VTABLE_CALL_MOST_DERIVED = $10; // Call most derived method described by
{$EXTERNALSYM COR_VTABLE_CALL_MOST_DERIVED}
// EATJ constants
IMAGE_COR_EATJ_THUNK_SIZE = 32; // Size of a jump thunk reserved range.
{$EXTERNALSYM IMAGE_COR_EATJ_THUNK_SIZE}
// Max name lengths
// Change to unlimited name lengths.
MAX_CLASS_NAME = 1024;
{$EXTERNALSYM MAX_CLASS_NAME}
MAX_PACKAGE_NAME = 1024;
{$EXTERNALSYM MAX_PACKAGE_NAME}
// COM+ 2.0 header structure.
type
IMAGE_COR20_HEADER = record
// Header versioning
cb: DWORD;
MajorRuntimeVersion: WORD;
MinorRuntimeVersion: WORD;
// Symbol table and startup information
MetaData: IMAGE_DATA_DIRECTORY;
Flags: DWORD;
EntryPointToken: DWORD;
// Binding information
Resources: IMAGE_DATA_DIRECTORY;
StrongNameSignature: IMAGE_DATA_DIRECTORY;
// Regular fixup and binding information
CodeManagerTable: IMAGE_DATA_DIRECTORY;
VTableFixups: IMAGE_DATA_DIRECTORY;
ExportAddressTableJumps: IMAGE_DATA_DIRECTORY;
// Precompiled image info (internal use only - set to zero)
ManagedNativeHeader: IMAGE_DATA_DIRECTORY;
end;
{$EXTERNALSYM IMAGE_COR20_HEADER}
PIMAGE_COR20_HEADER = ^IMAGE_COR20_HEADER;
{$EXTERNALSYM PIMAGE_COR20_HEADER}
TImageCor20Header = IMAGE_COR20_HEADER;
PImageCor20Header = PIMAGE_COR20_HEADER;
//
// End Image Format
//
implementation
end.
|
unit client;
{
Trida TTCPClient zabezpecuje TCP klient soket, ktery resi komunikaci
s technologickym serverem.
Nize je popis komunikacniho protokolu.
}
interface
uses SysUtils, IdTCPClient, listeningThread, IdTCPConnection, IdGlobal,
Classes, StrUtils, Graphics, Windows, Forms, Controls, ExtCtrls,
Generics.Collections, Hash, tUltimateLIConst;
const
_DEFAULT_PORT = 5896;
_PING_TIMER_PERIOD_MS = 20000;
// tady jsou vyjmenovane vsechny verze protokoluk pripojeni k serveru, ktere klient podporuje
protocol_version_accept : array[0..0] of string =
(
'1.0'
);
type
TPanelConnectionStatus = (closed, opening, handshake, opened);
TtoAuth = record
username: string;
password: string;
end;
TSlotToAuth = record
slot: Byte;
ruc: boolean;
end;
TTCPClient = class
private const
_PROTOCOL_VERSION = '1.0'; // verze protokolu od klienta
private
rthread: TReadingThread; // ctecti vlakno (poslouchani probiha v jinem vlakne)
tcpClient: TIdTCPClient; // objekt TCP klienta
fstatus : TPanelConnectionStatus; // aktualni stav klienta, pro pistup pouzivat \status
parsed: TStrings; // aktualni naparsovana data, pouze pro vnitrni potrebu objektu pri prijmu dat
data:string; // aktualni prijata data v RAW formatu (jeden radek dat)
control_disconnect:boolean; // true, pokud se odpojuji od serveru na zaklade pozadavku uzivatele, pri nucenem odpojeni false
fauthorised:boolean; // true, pokud strojvedouci autorizovan, pouzivat \authorised
first_connection:boolean; // true, pokud aktualni pripojovani je prvni pripojovani (po startu)
username:string;
pingTimer:TTimer;
procedure OnTcpClientConnected(Sender: TObject); // event TCP klienta pripojeni k serveru
procedure OnTcpClientDisconnected(Sender: TObject); // event TCP klienta odpojeni od serveru
procedure DataReceived(const data: string); // event prijatych dat od cteciho vlakna
procedure Timeout(); // timeout from socket = broken pipe // event timeoutu cteciho vlakna (spojeni se serverem rozvbto)
// data se predavaji v Self.Parsed
procedure ParseLokGlobal(); // parsing dat s prefixem "-;LOK;G"
procedure ParseGlobal(); // parsing dat s prefixem "-;"
procedure ParseLok(); // parsing dat s prefixem "-;LOK;addr"
procedure SendPing(Sedner:TObject);
public
toAuth: TtoAuth;
lokToSlotMap: TDictionary<Word, TSlotToAuth>;
constructor Create();
destructor Destroy(); override;
function Connect(host:string; port:Word):Integer; // pripojit k serveru
function Disconnect():Integer; // odpojit od serveru
procedure SendLn(str:string); // poslat zpravu (jeden radek)
procedure LokoPlease(addr:Word; token:string); // zadost o lokomotivu tokenem
procedure Auth();
class function SlotToAuth(slot:Byte; ruc:boolean):TSlotToAuth;
property status:TPanelConnectionStatus read fstatus; // aktualni stav pripojeni
property authorised:boolean read fauthorised; // true pokud strojvedouci autorizovan
property user:string read username;
end;//TPanelTCPClient
var
TCPClient : TTCPClient;
implementation
{
Specifikace komunikacniho protokolu:
Jedna se o retezec, ve kterem jsou jednotliva data oddelena strednikem
prvni parametr je v pripade regulatoru vzdy '-'.
Komunikace probiha znakovou sadou UTF-8.
Komunikace JE case-sensitive.
vynatek z protokolu:
PRIKAZY PRO REGULATOR:
////////////////////////////////////////////////////////////////////////////////
/////////////////////////// KLIENT -> SERVER ///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-;OR-LIST; - pozadavek na ziskani seznamu oblasti rizeni (stanic)
-;LOK;G;AUTH;username;passwd - pozadavek na autorizaci uzivatele
-;LOK;G:PLEASE;or_id;comment - pozadavek na rizeni loko z dane oblasti rizeni
-;LOK;G:CANCEL; - zruseni pozadavku o loko
-:LOK;addr;PLEASE;token - zadost o rizeni konkretni lokomotivy; token neni potreba pripojovat v pripade, kdy loko uz mame autorizovane a bylo nam ukradeno napriklad mysi
-;LOK;addr;RELEASE - zadost o uvolneni lokomotivy z regulatoru
-;LOK;addr;SP;sp_km/h - nastaveni rychlosti lokomotivy
-;LOK;addr;SPD;sp_km/h;dir[0,1] - nastaveni rychlosti a smeru lokomotivy
-;LOK;addr;D;dir[0,1] - nastaveni smeru lokomotivy
-;LOK;addr;SP-S;sp_stupen[0-28] - nastaveni rychlosti lokomotivy ve stupnich
-;LOK;addr;SPD-S;sp_stupen;dir[0,1] - nastaveni rychlosti a smeru lokomotivy ve stupnich
-;LOK;addr;F;F_left-F_right;states - nastaveni funkci lokomotivy
napr.; or;LOK;F;0-4;00010 nastavi F3 a ostatni F vypne
-;LOK;addr;STOP; - nouzove zastaveni
-;LOK;addr;TOTAL;[0,1] - nastaveni totalniho rucniho rizeni hnaciho vozidla
////////////////////////////////////////////////////////////////////////////////
/////////////////////////// SERVER -> KLIENT ///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-;OR-LIST;[or1id,or1name][or2id, ... - zaslani seznamu vsech oblasti rizeni; id je unikatni ID, nazev je nazev pro uzivatele
dale v protokolu je pouzivano pouze ID
-;LOK;G:PLEASE-RESP;[ok, err];info - odpoved na zadost o lokomotivu z reliefu; v info je pripadna chybova zprava
-;LOK;G;AUTH;[ok,not];info - navratove hlaseni o autorizaci uzivatele
-;LOK;addr;AUTH;[ok,not,stolen,release,total];info;hv_data
- odpoved na pozadavek o autorizaci rizeni hnaciho vozidla (odesilano take jako informace o zruseni ovladani hnacicho vozidla)
info je string
hv_data jsou pripojovana k prikazu v pripade, ze doslo uspesne k autorizaci; jedna se o PanelString hnaciho vozdila obsahujici vsechny informace o nem
-;LOK;addr;F;F_left-F_right;states - informace o stavu funkci lokomotivy
napr.; or;LOK;0-4;00010 informuje, ze je zaple F3 a F0, F1, F2 a F4 jsou vyple
-;LOK;addr;SPD;sp_km/h;sp_stupne;dir - informace o zmene rychlosti (ci smeru) lokomotivy
-;LOK;addr;RESP;[ok, err];info;speed_kmph
- odpoved na prikaz; speed_kmph je nepovinny argument; info zpravidla obsahuje rozepsani chyby, pokud je odpoved "ok", info je prazdne
-;LOK;addr;TOTAL;[0,1] - zmena rucniho rizeni lokomotivy
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
navazani komunikace:
1) klient se pripoji
2) klient posle hanshake ("-;HELLO;verze_protokolu")
3) klient vycka na odpoved na handshake
4) klient posle na server pozadavek o autorizaci obecneho rizeni -- login strojvedouciho a vycka na odpoved
5) klient nacte seznam oblasti rizeni a nabidne uzivateli vybrat oblast rizeni, do ktere provest zadost o LOKO
jak funguje rizeni z regulatoru:
a) cesta zadosti z regulatoru
1) klient se pripoji, autorizuje se vuci serveru prikazem LOK;G;AUTH;
2) klient si nacte seznam oblasti rizeni
3) klient si vybere oblasti rizeni a do ni posle pozadavek
4) oblasti rizeni priradi regulatoru hnaci vozidlo (vozidla)
b) cesta primeho prevzeti
1) klient se pripoji, autorizuje se vuci serveru prikazem LOK;G;AUTH;
2) klient si obstara autorizacni token pro dane hnaci vozidlo (napriklad od dispecera -- resp. z panelu)
3) klient pozada o LOKO a prilozi token, loko je mu prirazeno (pozor: token ma omezenou casovou platnost)
}
uses fDebug, fMain, ORList, tUltimateLI, tHnaciVozidlo, server;
////////////////////////////////////////////////////////////////////////////////
constructor TTCPClient.Create();
begin
inherited;
// inicializace vlastnosti a objetku
Self.fauthorised := false;
Self.parsed := TStringList.Create;
Self.first_connection := true;
Self.pingTimer := TTimer.Create(nil);
Self.pingTimer.Enabled := false;
Self.pingTimer.Interval := _PING_TIMER_PERIOD_MS;
Self.pingTimer.OnTimer := Self.SendPing;
// vytvoreni TCP klienta
Self.tcpClient := TIdTCPClient.Create(nil);
Self.tcpClient.OnConnected := Self.OnTcpClientConnected;
Self.tcpClient.OnDisconnected := Self.OnTcpClientDisconnected;
Self.tcpClient.ConnectTimeout := 1500;
Self.lokToSlotMap := TDictionary<Word, TSlotToAuth>.Create();
// aktualni status = zavrene spojeni
Self.fstatus := TPanelConnectionStatus.closed;
Self.username := '';
end;//ctor
destructor TTCPClient.Destroy();
begin
try
if (Assigned(Self.tcpClient)) then
FreeAndNil(Self.tcpClient);
if (Assigned(Self.parsed)) then
FreeAndNil(Self.parsed);
Self.lokToSlotMap.Free();
Self.pingTimer.Free();
finally
inherited;
end;
end;//dtor
////////////////////////////////////////////////////////////////////////////////
function TTCPClient.Connect(host:string; port:Word):Integer;
begin
try
if (Self.tcpClient.Connected) then Exit(1);
except
try
Self.tcpClient.Disconnect(False);
except
end;
if (Self.tcpClient.IOHandler <> nil) then Self.tcpClient.IOHandler.InputBuffer.Clear;
end;
F_Main.ClearMessage();
Self.tcpClient.Host := host;
Self.tcpClient.Port := port;
Self.fstatus := TPanelConnectionStatus.opening;
try
Self.tcpClient.Connect();
except
Self.fstatus := TPanelConnectionStatus.closed;
raise;
end;
Self.tcpClient.IOHandler.DefStringEncoding := TIdEncoding.enUTF8;
Self.control_disconnect := false;
Result := 0;
end;//function
////////////////////////////////////////////////////////////////////////////////
function TTCPClient.Disconnect():Integer;
begin
try
if (not Self.tcpClient.Connected) then Exit(1);
except
end;
Self.control_disconnect := true;
if Assigned(Self.rthread) then Self.rthread.Terminate;
try
Self.tcpClient.Disconnect();
finally
if Assigned(Self.rthread) then
begin
Self.rthread.WaitFor;
FreeAndNil(Self.rthread);
end;
end;
Result := 0;
end;//function
////////////////////////////////////////////////////////////////////////////////
// eventy z IdTCPClient
procedure TTCPClient.OnTcpClientConnected(Sender: TObject);
begin
// klient pripojen -> vytvorime cteci vlakno
try
Self.rthread := TReadingThread.Create(TIdTCPClient(Sender));
Self.rthread.OnData := DataReceived;
Self.rthread.OnTimeout := Timeout;
Self.rthread.Resume;
except
(Sender as TIdTCPClient).Disconnect;
raise;
end;
// update okynka
F_Main.P_Client.Color := clYellow;
F_Main.P_Client.Hint := 'Probíhá handshake...';
Self.fstatus := TPanelConnectionStatus.handshake;
Self.pingTimer.Enabled := true;
// odeslat handshake
Self.SendLn('-;HELLO;'+Self._PROTOCOL_VERSION+';');
end;//procedure
procedure TTCPClient.OnTcpClientDisconnected(Sender: TObject);
begin
// klient odpojen -> znicit cteci vlakno
if Assigned(Self.rthread) then Self.rthread.Terminate;
// status klienta na odpojen
Self.fstatus := TPanelConnectionStatus.closed;
Self.pingTimer.Enabled := false;
Self.fauthorised := false;
// aktualizace okynka
F_Main.P_Client.Color := clRed;
F_Main.P_Client.Hint := 'Odpojeno od hJOP serveru';
// vypnout Rocomaus
uLI.HardResetSlots();
TCPServer.BroadcastSlots();
TCPServer.BroadcastAuth(true);
uLI.busEnabled := false;
Self.username := '';
F_Main.UpdateTitle();
if ((F_Main.close_app) and (not uLI.connected)) then F_Main.Close();
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// parsing prijatych dat
procedure TTCPClient.DataReceived(const data: string);
begin
Self.parsed.Clear();
// vlastni parsovaci funkce
ExtractStringsEx([';'], [#13, #10], data, Self.parsed);
Self.data := data;
// logovani dat
F_Debug.Log('GET: '+data);
try
// zakladni rozdeleni podle prefixu
if (Self.parsed[0] = '-') then
begin
if (Self.parsed[1] = 'LOK') then
begin
if (Self.parsed[2] = 'G') then
Self.ParseLokGlobal()
else
Self.ParseLok();
end else
Self.ParseGlobal();
end;
except
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTCPClient.Timeout();
begin
Self.OnTcpClientDisconnected(Self);
F_Main.SB_Main.Panels[1].Text := 'Spojení se serverem přerušeno';
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTCPClient.ParseGlobal();
var i:Integer;
found:boolean;
begin
// parse handhake
if (Self.parsed[1] = 'HELLO') then
begin
// kontrola verze protokolu
found := false;
for i := 0 to Length(protocol_version_accept)-1 do
begin
if (Self.parsed[2] = protocol_version_accept[i]) then
begin
found := true;
break;
end;
end;//for i
if (not found) then
Application.MessageBox(PChar('Verze protokolu, kterou používá server ('+Self.parsed[2]+') není podporována'),
'Upozornění', MB_OK OR MB_ICONWARNING);
Self.fstatus := TPanelConnectionStatus.opened;
F_Main.P_Client.Hint := 'Připojeno k hJOP serveru, probíhá autorizace...';
// autorizace strojvedouciho
Self.Auth();
end
else if (parsed[1] = 'OR-LIST') then
begin
ORDb.Parse(parsed[2]);
//F_NewLoko.FillStanice(); TODO
end
else if (parsed[1] = 'DCC') then
begin
uLI.DCC := (parsed[2] = 'GO');
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTCPClient.ParseLokGlobal();
var oldAuth:boolean;
begin
if (parsed[3] = 'AUTH') then
begin
// autorizace uzivatele
oldAuth := Self.authorised;
Self.fauthorised := (LowerCase(Self.parsed[4]) = 'ok');
if (Self.fauthorised) then
begin
if (oldAuth) then Exit();
F_Main.P_Client.Hint := 'Připojeno k hJOP serveru, autorizováno';
F_Main.P_Client.Color := clGreen;
TCPServer.BroadcastAuth(true);
// spojedni se serverem uspesne navazano -> zapinam Rocomaus
if (uLI.connected) then
begin
try
uLI.busEnabled := true;
except
on E:Exception do
Application.MessageBox(PChar('Nelze zapnout napájení sběrnice pro ovladače:'+#13#10+E.Message), 'uLI-daemon', MB_OK OR MB_ICONWARNING);
end;
end;
end else begin
F_Main.P_Client.Color := clYellow;
F_Main.P_Client.Hint := 'Připojeno k hJOP serveru, NEAUTORIZOVÁNO : '+parsed[5];
if (oldAuth) then
begin
if (uli.busEnabled) then
uLI.busEnabled := false;
Application.MessageBox(PChar('Zrušena autorizace uživatele!'+#13#10+parsed[5]), 'Zrušena autorizace', MB_OK OR MB_ICONWARNING);
end else begin
Self.toAuth.username := '';
Application.MessageBox(PChar('Nepodařilo se autorizovat uživatele!'+#13#10+parsed[5]), 'Autorizace se nezdařila', MB_OK OR MB_ICONWARNING);
end;
TCPServer.BroadcastAuth();
end;
Self.username := Self.toAuth.username;
Self.toAuth.username := '';
Self.toAuth.password := '';
F_Main.UpdateTitle();
end;//if parsed[3] = AUTH
end;//procedure
////////////////////////////////////////////////////////////////////////////////
{
-;LOK;addr;AUTH;[ok,not,stolen,release,total];info;hv_data
- odpoved na pozadavek o autorizaci rizeni hnaciho vozidla (odesilano take jako informace o zruseni ovladani hnacicho vozidla)
info je string
hv_data jsou pripojovana k prikazu v pripade, ze doslo uspesne k autorizaci; jedna se o PanelString hnaciho vozdila obsahujici vsechny informace o nem
-;LOK;addr;F;F_left-F_right;states - informace o stavu funkci lokomotivy
napr.; or;LOK;0-4;00010 informuje, ze je zaple F3 a F0, F1, F2 a F4 jsou vyple
-;LOK;addr;SPD;sp_km/h;sp_stupne;dir - informace o zmene rychlosti (ci smeru) lokomotivy
-;LOK;addr;RESP;[ok, err];info;speed_kmph
}
procedure TTCPClient.ParseLok();
var addr:Word;
slot:Byte;
func:TStrings;
left, right, i, hvIndex:Integer;
HV:THV;
begin
addr := StrToInt(parsed[2]);
if (parsed[3] = 'AUTH') then begin
if (not Self.lokToSlotMap.ContainsKey(addr)) then Exit();
slot := Self.lokToSlotMap[addr].slot;
hvIndex := uLI.sloty[slot].GetHVIndex(addr);
if (hvindex = -1) then
begin
// prirazeni nove loko do slotu
if ((parsed[4] = 'ok') or (parsed[4] = 'total')) then begin
HV := THV.Create(parsed[5]);
HV.total := (parsed[4] = 'total');
uLI.sloty[slot].AddLoko(HV);
uLI.SendLokoStolen(uLI.CalcParity(uLI.sloty[slot].mausId + $60), slot);
if ((not HV.total) and (Self.lokToSlotMap[addr].ruc)) then
begin
// loko se chce prevzit do rucniho rizeni
Self.SendLn('-;LOK;'+IntToStr(HV.Adresa)+';TOTAL;1');
end;
// zamezit budoucim prebiranim na rucni rizeni
Self.lokToSlotMap[addr] := TTCPClient.SlotToAuth(slot, false);
end else if (parsed[4] = 'not') then begin
if (Assigned(uLI.sloty[slot].sender)) then
begin
TCPServer.SendLn(uLI.sloty[slot].sender, 'LOKO;err;10;'+parsed[5]);
uLI.sloty[slot].sender := nil;
end;
uLI.sloty[slot].UpdateGUI();
Application.MessageBox(PChar('Lokomotivu '+parsed[2]+' se nepodařio autorizovat'+#13#10+parsed[5]), 'Loko neautorizováno', MB_OK OR MB_ICONWARNING)
end;
end else begin
// aktualizace dat o existujici loko
if ((parsed[4] = 'ok') or (parsed[4] = 'total')) then begin
uLI.sloty[slot].gui.P_status.Caption := 'OK';
uLI.sloty[slot].HVs[hvIndex].total := (parsed[4] = 'total');
uLI.sloty[slot].HVs[hvIndex].ukradeno := false;
uLI.sloty[slot].UpdateGUI();
uLI.SendLokoStolen(uLI.CalcParity(uLI.sloty[slot].mausId + $60), slot);
end else if (parsed[4] = 'stolen') then begin
uLI.sloty[slot].HVs[hvIndex].ukradeno := true;
uLI.SendLokoStolen(uLI.CalcParity(uLI.sloty[slot].mausId + $60), slot);
uLI.sloty[slot].UpdateGUI();
end else if (parsed[4] = 'release') then begin
uLI.sloty[slot].RemoveLoko(hvIndex);
Self.lokToSlotMap.Remove(addr);
if (uLI.sloty[slot].isMaus) then uLI.SendLokoStolen(uLI.CalcParity(uLI.sloty[slot].mausId + $60), slot);
TCPServer.BroadcastSlots();
end;
end;
end else begin
// vsechny nasledujici prikazy vyzaduji znalost \slot a \hvIndex
if (not Self.lokToSlotMap.ContainsKey(addr)) then Exit();
slot := Self.lokToSlotMap[addr].slot;
if (not uLI.sloty[slot].isLoko) then Exit();
hvIndex := uLI.sloty[slot].GetHVIndex(addr);
if (hvIndex < 0) then Exit();
if (parsed[3] = 'F') then begin
func := TStringList.Create();
ExtractStringsEx(['-'], [], parsed[4], func);
left := StrToInt(func[0]);
if (func.Count > 1) then
right := StrToInt(func[1])
else
right := left;
func.Free();
for i := left to right do
if (i < _MAX_FUNC) then
uLI.sloty[slot].HVs[hvIndex].funkce[i] := (parsed[5][i-left+1] = '1');
uLI.SendLokoStolen(uLI.CalcParity(uLI.sloty[slot].mausId + $60), slot);
end else if (parsed[3] = 'SPD') then begin
uLI.sloty[slot].HVs[hvIndex].rychlost_kmph := StrToInt(parsed[4]);
uLI.sloty[slot].HVs[hvIndex].rychlost_stupne := StrToInt(parsed[5]);
uLI.sloty[slot].HVs[hvIndex].smer := StrToInt(parsed[6]);
uLI.SendLokoStolen(uLI.CalcParity(uLI.sloty[slot].mausId + $60), slot);
uLI.sloty[slot].gui.L_Speed.Caption := IntToStr(uLI.sloty[slot].HVs[hvIndex].rychlost_kmph) + ' km/h';
end else if (parsed[3] = 'RESP') then begin
if (parsed[4] = 'ok') then
begin
if (parsed.Count > 4) then uLI.sloty[slot].gui.L_Speed.Caption := parsed[5] + ' km/h';
uLI.sloty[slot].gui.P_status.Color := clLime;
uLI.sloty[slot].gui.P_status.Caption := 'OK';
end else begin
uLI.sloty[slot].gui.P_status.Color := clRed;
uLI.sloty[slot].gui.P_status.Caption := 'ERROR';
uLI.sloty[slot].gui.P_status.Hint := parsed[5];
end;
end else if (parsed[3] = 'TOTAL') then begin
uLI.sloty[slot].updating := true;
uLI.sloty[slot].HVs[hvIndex].total := boolean(StrToInt(parsed[4]));
uLI.sloty[slot].gui.CHB_Total.Checked := uLI.sloty[slot].total;
uLI.sloty[slot].updating := false;
uLI.sloty[slot].gui.P_status.Color := clLime;
uLI.sloty[slot].gui.P_status.Caption := 'OK';
uLI.sloty[slot].gui.P_status.Hint := '';
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTCPClient.SendLn(str:string);
begin
try
if (not Self.tcpClient.Connected) then Exit;
except
end;
try
Self.tcpClient.Socket.WriteLn(str);
except
if (Self.fstatus = opened) then
Self.OnTcpClientDisconnected(Self);
end;
F_Debug.Log('SEND: '+str);
end;//procedure
procedure TTCPClient.LokoPlease(addr:Word; token:string);
begin
Self.SendLn('-;LOK;'+IntToStr(addr)+';PLEASE;'+token);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTCPClient.SendPing(Sedner:TObject);
begin
try
if (Self.tcpClient.Connected) then
Self.SendLn('-;PING');
except
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTCPClient.Auth();
begin
Self.SendLn('-;LOK;G;AUTH;' + Self.toAuth.username + ';' + Self.toAuth.password);
end;
////////////////////////////////////////////////////////////////////////////////
class function TTCPClient.SlotToAuth(slot:Byte; ruc:boolean):TSlotToAuth;
begin
Result.slot := slot;
Result.ruc := ruc;
end;
////////////////////////////////////////////////////////////////////////////////
initialization
TCPClient := TTCPClient.Create;
finalization
FreeAndNil(TCPCLient);
end.//unit
|
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, TextOutScripts, RPDB, Db, DBTables, ComCtrls, Grids, DBGrids;
type
TForm1 = class(TForm)
OpenDialog: TOpenDialog;
Environment: TRPDataEnvironment;
SaveDialog: TSaveDialog;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
mmResults: TMemo;
mmSource: TMemo;
btnOpen: TButton;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
mmOutput: TMemo;
btnRun: TButton;
Table1: TTable;
DataSource1: TDataSource;
DataSource2: TDataSource;
Query1: TQuery;
DBGrid1: TDBGrid;
DBGrid2: TDBGrid;
procedure btnOpenClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnRunClick(Sender: TObject);
private
{ Private declarations }
FContext : TScriptContext;
procedure ViewResults;
procedure AddInfo(const s:string);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
FContext := TScriptContext.Create(Self);
FContext.Environment := Environment;
Query1.Open;
Table1.Open;
end;
procedure TForm1.AddInfo(const s: string);
begin
mmResults.Lines.Add(s);
end;
procedure TForm1.btnOpenClick(Sender: TObject);
begin
if OpenDialog.Execute then
begin
mmSource.Lines.LoadFromFile(OpenDialog.FileName);
mmResults.Lines.Clear;
FContext.LoadScripts(OpenDialog.FileName);
ViewResults;
end;
end;
procedure TForm1.ViewResults;
var
i : integer;
Node : TTOScriptNode;
begin
//
AddInfo('Default File Name '+FContext.DefaultFileName);
// data entries
AddInfo('Data Entries');
for i:=0 to FContext.DataEntries.Count-1 do
with FContext.DataEntries[i] do
AddInfo(Format('%d: Dataset=%s,Controller=%s,GroupFields=%s',[i,DatasetName,ControllerName,Groups.Text]));
// nodes
AddInfo('');
AddInfo('Nodes');
for i:=0 to FContext.Nodes.Count-1 do
begin
Node := TTOScriptNode(FContext.Nodes[i]);
if Node is TTOText then
AddInfo(Format('%d - Text',[I]))
else if Node is TTOFieldValue then
with TTOFieldValue(Node) do
AddInfo(Format('%d - Field : Name=%s,Width=%d,Align=%d',[I,FieldName,Width,Ord(Align)]))
else if Node is TTOForLoop then
with TTOForLoop(Node) do
AddInfo(Format('%d - For : Controller=%s,GroupIndex=%d,Exit=%d',[I,ControllerName,GroupIndex,ExitNodeIndex]))
else if Node is TTOEndLoop then
with TTOEndLoop(Node) do
AddInfo(Format('%d - End : For=%d',[I,ForNodeIndex]))
end;
end;
procedure TForm1.btnRunClick(Sender: TObject);
begin
if FContext.DefaultFileName<>'' then
SaveDialog.FileName := FContext.DefaultFileName;
if SaveDialog.Execute then
begin
if FContext.DataEntries.IndexOfDataset('Animals')>=0 then
FContext.DataEntries.AddDatasource('Animals',DataSource1);
if FContext.DataEntries.IndexOfDataset('Orders')>=0 then
FContext.DataEntries.AddDatasource('Orders',DataSource2);
FContext.Output(SaveDialog.FileName);
mmOutput.Lines.LoadFromFile(SaveDialog.FileName);
end;
end;
end.
|
unit uClasseCriterio;
interface
uses
Classes, uDMPrincipal, sysutils, consttipos, uFuncoesGeral;
type
TCriterio = class;
TCalculoRecuperacao = (crMedia, crBimestres, crMaiorNota, crPesosBim, crRecuperacao,crSomaTotal,crMediaAngola);
TCampoNotaBoletim = (cnbNotaPeriodo, cnbRecSem1, cnbRecSem2, cnbMediaSem1,
cnbMediaSem2, cnbMediaBim, cnbNotaRec, cnbMediaFinal,cnbMediaPeriodo);
TItemCriterio = class
Criterio : TCriterio;
Campo : Integer;
Periodo : Integer;
Inicial,
Final : Double;
Situacao : char;
DescricaoSituacao : String;
end;
TItemArredondamento = record
NotaInicial,
NotaFinal,
Nota : Double;
end;
TTabelaArredondamento = class
private
function getCount: Integer;
procedure setCount(const Value: Integer);
public
Codigo : Integer;
Items : array of TItemArredondamento;
property Count : Integer read getCount write setCount;
procedure Carregar(pCodigo: Integer; Letivo : String);
function Arredonda(Valor : Double) : Double;
end;
TConceito = record
NotaInicial : Double;
NotaFinal : Double;
Conceito : String;
end;
TCriterio = class
private
FItens : TList;
fPesos : array of integer;
fNotaMaxima: array of Double; //era single mudei para double
fNotaCorte: array of Double; //era single mudei para double
fNumPeriodos : Integer;
fconceitos : array of TConceito;
function GetItem(indice: Integer): TItemCriterio;
procedure SetItem(indice: Integer; const Value: TItemCriterio);
function GetCriterioPadrao(Letivo: String): Integer;
procedure SetCriterioPadrao(Letivo: String; const Value: Integer);
function GetPeso(Bimestre: Integer): Integer;
procedure SetPeso(Bimestre: Integer; const Value: Integer);
procedure SetNumPeriodos(const Value: Integer);
procedure ValidaBimestre(Bimestre: Integer);
function GetConceito(index: Integer): TConceito;
procedure SetConceito(index: Integer; const Value: TConceito);
function GetNumConceitos: Integer;
procedure SetNumConceitos(const Value: Integer);
public
CalculoNotaFinal: char;
CalculoRecuperacao : TCalculoRecuperacao;
LimiteRecuperacao : Integer;
LimiteDependencia : Integer;
ArredondMediaBim : TTabelaArredondamento;
ArredondMediaFinal : TTabelaArredondamento;
TipoBoletim : Integer;
Decimais : Integer;
DecimaisMedia: Integer;
UsarExtensoMax, UsarExtensoMin : Boolean;
FreqGlobalMinima : Double;
ConsiderarRecuperacaoMenor: Boolean;
CalcRecBim: Integer;
CalcRecSem: Integer;
constructor Create;
destructor Destroy; override;
function NotaCorte(Campo: TCampoNotaBoletim; Bimestre: Integer = 0) : Double;
function NotaCorteRec( Campo: TcampoNotaBoletim; Bimestre: Integer = 0) : Double;
function NotaCorteAposRec : Double;
function NotaMaxima(Campo: TCampoNotaBoletim; Bimestre: Integer = 0) : Double;
procedure Carregar(Codigo : Integer; AnoLetivo: String = '');
procedure CarregarCriterioPadrao(Letivo : String = '');
procedure CarregarCriterioSerie(Curso : String; Serie : String; Letivo: string = '');
procedure CarregarCriterioClasse(CodClasse : String; AnoLetivo : String = '');
procedure LimpaItens;
procedure RemoveItem(Indice : Integer);
function NovoItem : TItemCriterio;
function NumeroItens : Integer;
function MascaraNota(MediaFinal: Boolean = false): String;
property Itens[indice : Integer] : TItemCriterio read GetItem write SetItem;
property CriterioPadrao[Letivo : String] : Integer read GetCriterioPadrao write SetCriterioPadrao;
property Peso[Bimestre : Integer] : Integer read GetPeso write SetPeso;
property NumPeriodos : Integer read FNumPeriodos write SetNumPeriodos;
property NumConceitos : Integer read GetNumConceitos write SetNumConceitos;
property Conceito[index : Integer] : TConceito read GetConceito write SetConceito;
function ConceitoNota(Nota: Double; var Erro : Boolean) : String;
end;
implementation
uses DB;
{ TCriterio }
procedure TCriterio.Carregar(Codigo : Integer; AnoLetivo: String = '');
var
it : TItemCriterio;
Let : String;
i : Integer;
begin
with DMPrincipal do
begin
if AnoLetivo = '' then
Let := vUser.AnoLetivo
else
Let := AnoLetivo;
OpenSQL(sqlAnosLetivos, 'SELECT * '+
' FROM AnosLetivos '+
' WHERE AnoLetivo = ' + QuotedStr(Let) );
TipoBoletim := Letivo.TipoBoletim;
NumPeriodos := Letivo.NumPeriodos;
OpenSQL(sqlCriterios, 'SELECT * '+
' FROM Criterios '+
' WHERE Codigo = ' + IntToStr(Codigo) +
' AND AnoLetivo = ' + QuotedStr(Let) );
CalculoNotaFinal := StrToChar(sqlCriteriosCalculoNotaFinal.Value);
if CalculoNotaFinal = calc_Media then
begin
SetLength(fNotaMaxima, 1);
SetLength(fNotaCorte, 2);
fNotaCorte[0] := sqlCriteriosNotaCorte.Value;
fNotaCorte[1] := sqlCriteriosNotaCorteRec.Value;
fNotaMaxima[0] := sqlCriteriosNotaMaxima.Value;
end else
begin
SetLength(fNotaMaxima, NumPeriodos + 1);
SetLength(fNotaCorte, NumPeriodos + 1);
end;
case StrToChar(sqlCriteriosCalculoRecuperacao.Value) of
'M' : CalculoRecuperacao := crMedia;
'B' : CalculoRecuperacao := crBimestres;
'>' : CalculoRecuperacao := crMaiorNota;
'<' : CalculoRecuperacao := crPesosBim;
'R' : CalculoRecuperacao := crRecuperacao;
'S' : CalculoRecuperacao := crSomaTotal;
'A' : CalculoRecuperacao := crMediaAngola;
end;
LimiteRecuperacao := sqlCriteriosLimiteRecuperacao.Value;
LimiteDependencia := sqlCriteriosLimiteDependencia.Value; // 21/02/2011 -> Bruno, novo calculo para limite de dependencia.
Decimais := sqlCriteriosDecimais.Value;
DecimaisMedia := sqlCriteriosDecimaisMedia.Value;
CalcRecBim := sqlCriteriosCalculoRecBim.AsInteger;
CalcRecSem := sqlCriteriosCalculoRecSem.AsInteger;
if sqlCriteriosUsarExtensoMax.AsInteger = 0 then
UsarExtensoMax := False
else
UsarExtensoMax := True;
if sqlCriteriosUsarExtensoMin.AsInteger = 0 then
UsarExtensoMin := False
else
UsarExtensoMin := True;
FreqGlobalMinima := sqlCriteriosFrequenciaGlobalMinima.Value;
if sqlCriteriosConsiderarRecuperacaoMenor.AsInteger = 0 then
ConsiderarRecuperacaoMenor := False
else
ConsiderarRecuperacaoMenor := True;
ArredondMediaBim.Carregar(sqlCriteriosArredMediaBim.Value, Let);
ArredondMediaFinal.Carregar(sqlCriteriosArredMediaFinal.Value, Let);
// Carrega o peso e outras configurações por bimestre
OpenSQL(sqlPesosCriterio, 'SELECT * '+
' FROM PesosCriterio '+
' WHERE AnoLetivo = ' + QuotedStr(Let) +
' AND Codigo = ' + IntToStr(Codigo) );
// Carrega o peso de cada bimestre, além da nota de corte e nota
// máxima, caso o cálculo da nota for pela soma.
for i := 1 to NumPeriodos do
begin
if sqlPesosCriterio.Locate('Periodo', i, []) then
begin
if CalculoNotaFinal = calc_Soma then
begin
Peso[i] := 1;
fNotaMaxima[i] := sqlPesosCriterioNotaMaxima.Value;
fNotaCorte[i] := sqlPesosCriterioNotaCorte.Value;
end else
Peso[i] := sqlPesosCriterioPeso.Value;
end
else
begin
Peso[i] := 1;
if CalculoNotaFinal = calc_Soma then
begin
fNotaMaxima[i] := 0;
fNotaCorte[i] := 0;
end;
end;
end;
sqlPesosCriterio.Close;
Peso[NumPeriodos + 1] := sqlCriteriosPesoRecuperacao.Value;
sqlCriterios.Close;
// Carrega itens de critério
sqlItensCriterio.close;
OpenSQL(sqlItensCriterio, 'SELECT * '+
' FROM ItensCriterio '+
' WHERE Criterio = ' + IntToStr(Codigo) +
' AND AnoLetivo = ' + QuotedStr(Let) +
' ORDER BY Item ');
LimpaItens;
sqlItensCriterio.First;
while not sqlItensCriterio.Eof do
begin
it := NovoItem;
it.Campo := sqlItensCriterioCampo.Value;
it.Periodo := sqlItensCriterioperiodo.Value;
it.Inicial := sqlItensCriterioFaixaInicial.Value;
it.Final := sqlItensCriterioFaixaFinal.Value;
it.Situacao := StrToChar(sqlItensCriterioSituacao.Value);
it.DescricaoSituacao := sqlItensCriterioDescricaoSituacao.Value;
sqlItensCriterio.Next;
end;
sqlItensCriterio.Close;
// Carrega os conceitos do critério
OpenSQL(sqlConceitos, 'SELECT * '+
' FROM Conceitos '+
' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
' AND CodCriterio = ' + IntToStr(Codigo) +
' ORDER BY NotaInicial, NotaFinal ');
try
NumConceitos := sqlConceitos.RecordCount;
i := 0;
while not sqlConceitos.Eof do
begin
fconceitos[i].NotaInicial := sqlConceitosNotaInicial.Value;
fConceitos[i].NotaFinal := sqlConceitosNotaFinal.Value;
fConceitos[i].Conceito := sqlConceitosConceito.Value;
Inc(i);
sqlConceitos.Next;
end;
finally
sqlConceitos.Close;
end;
end;
end;
procedure TCriterio.CarregarCriterioClasse(CodClasse: String; AnoLetivo : String = '');
var
Let : String;
begin
with DMPrincipal do
begin
if AnoLetivo = '' then
Let := vUser.AnoLetivo
else
Let := AnoLetivo;
OpenSQL(sqlClasses , 'SELECT * '+
' FROM Classe1 '+
' WHERE idClasse1 = ' + QuotedStr(CodClasse) +
' AND AnoLetivo = ' + QuotedStr(Let) );
CarregarCriterioSerie(sqlClassesidCursos.Value, sqlClassesSerie.Value, Let);
sqlClasses.Close;
end;
end;
procedure TCriterio.CarregarCriterioPadrao(Letivo : string = '');
var
Let : String;
begin
if Letivo = '' then
Let := vUser.AnoLetivo
else
Let := Letivo;
Carregar(CriterioPadrao[Let], Let);
end;
procedure TCriterio.CarregarCriterioSerie(Curso, Serie: String; Letivo : String = '');
var
sSQL : String;
Criterio : Integer;
Let : String;
begin
if Letivo = '' then
Let := vUser.AnoLetivo
else
Let := Letivo;
sSQL := 'SELECT Criterio '+
' FROM CriterioSeries '+
' WHERE AnoLetivo = ' + QuotedStr(Let) +
' AND Curso = ' + QuotedStr(Curso) +
' AND Serie = ' + QuotedStr(Serie) ;
Criterio := DMPrincipal.ExSQLi(sSQL);
if Criterio = 0 then
CarregarCriterioPadrao(Letivo)
else
Carregar(Criterio, Letivo);
end;
constructor TCriterio.Create;
begin
FItens := TList.Create;
ArredondMediaBim := TTabelaArredondamento.Create;
ArredondMediaFinal := TTabelaArredondamento.Create;
end;
destructor TCriterio.Destroy;
begin
FItens.Free;
ArredondMediaBim.Free;
ArredondMediaFinal.Free;
inherited;
end;
function TCriterio.GetCriterioPadrao(Letivo: String): Integer;
begin
Result := DMPrincipal.ExSQLi( 'SELECT Criterio '+
' FROM CriterioPadrao '+
' WHERE AnoLetivo = ' + QuotedStr(Letivo) );
end;
function TCriterio.GetItem(indice: Integer): TItemCriterio;
begin
Result := TItemCriterio(FItens[indice]);
end;
procedure TCriterio.ValidaBimestre(Bimestre : Integer);
begin
if (bimestre < 1) or (Bimestre > (NumPeriodos + 1)) then
raise ERangeError.Create('Bimestre inválido : ' + IntToStr(Bimestre));
end;
function TCriterio.GetPeso(Bimestre: Integer): Integer;
begin
ValidaBimestre(Bimestre);
Result := fpesos[Bimestre - 1];
end;
procedure TCriterio.LimpaItens;
var
i : Integer;
begin
for i := FItens.Count - 1 downto 0 do
RemoveItem(i);
end;
function TCriterio.NovoItem: TItemCriterio;
begin
Result := TItemCriterio.Create;
Result.Criterio := Self;
FItens.Add(result);
end;
function TCriterio.NumeroItens: Integer;
begin
Result := FItens.Count;
end;
procedure TCriterio.RemoveItem(Indice: Integer);
begin
Itens[indice].Free;
FItens.Delete(indice);
end;
procedure TCriterio.SetCriterioPadrao(Letivo: String; const Value: Integer);
var
sSQL : String;
begin
sSQL := 'SELECT COUNT(*) '+
' FROM CriterioPadrao '+
' WHERE AnoLetivo = ' + QuotedStr(Letivo) ;
if DMPrincipal.ExSQLi(sSQL) > 0 then
sSQL := 'UPDATE CriterioPadrao '+
' SET Criterio = ' + IntToStr(Value) +
' WHERE AnoLetivo = ' + QuotedStr(Letivo)
else
sSQL := 'INSERT INTO '+
' CriterioPadrao (AnoLetivo, Criterio) '+
' VALUES(' + QuotedStr(Letivo) + ', ' + IntToStr(Value) + ')';
DMPrincipal.Zconn.ExecuteDirect(sSQL);
end;
procedure TCriterio.SetItem(indice: Integer; const Value: TItemCriterio);
begin
FItens[indice] := Value;
end;
procedure TCriterio.SetNumPeriodos(const Value: Integer);
begin
FNumPeriodos := Value;
SetLength(fpesos, Value + 1); // Mais um por causa da recuperação
end;
procedure TCriterio.SetPeso(Bimestre: Integer; const Value: Integer);
begin
ValidaBimestre(Bimestre);
fPesos[Bimestre - 1] := Value;
end;
function TCriterio.MascaraNota(MediaFinal: Boolean): String;
begin
if MediaFinal then
MascaraNota := '0.' + StringOfChar('0', DecimaisMedia)
else
MascaraNota := '0.' + StringOfChar('0', Decimais);
end;
function TCriterio.NotaCorte(Campo: TCampoNotaBoletim; Bimestre: Integer): Double;
begin
if CalculoNotaFinal = calc_Soma then
begin
if Campo = cnbNotaPeriodo then
begin
if Bimestre = DMPrincipal.Letivo.NumPeriodos + 1 then
Campo := cnbNotaRec
else
if Bimestre = DMPrincipal.Letivo.NumPeriodos + 2 then
Campo := cnbRecSem1
else
if Bimestre = DMPrincipal.Letivo.NumPeriodos + 3 then
Campo := cnbRecSem2;
end;
case Campo of
cnbNotaPeriodo : Result := fNotaCorte[Bimestre];
cnbRecSem1, cnbMediaSem1 : Result := fNotaCorte[1] + fNotaCorte[2];
cnbRecSem2, cnbMediaSem2 : Result := fNotaCorte[3] + fNotaCorte[4];
cnbMediaBim, cnbNotaRec, cnbMediaFinal : Result := fNotaCorte[1]
+ fNotaCorte[2] + fNotaCorte[3] + fNotaCorte[4];
else
Result := 0;
end;
end else
Result := fNotaCorte[0];
end;
function TCriterio.NotaMaxima(Campo: TCampoNotaBoletim; Bimestre: Integer): Double;
begin
if CalculoNotaFinal = calc_Soma then
begin
if Campo = cnbNotaPeriodo then
begin
if Bimestre = DMPrincipal.Letivo.NumPeriodos + 1 then
Campo := cnbNotaRec
else
if Bimestre = DMPrincipal.Letivo.NumPeriodos + 2 then
Campo := cnbRecSem1
else
if Bimestre = DMPrincipal.Letivo.NumPeriodos + 3 then
Campo := cnbRecSem2;
end;
case Campo of
cnbNotaPeriodo : Result := fNotaMaxima[Bimestre];
cnbRecSem1, cnbMediaSem1 : Result := fNotaMaxima[1] + fNotaMaxima[2];
cnbRecSem2, cnbMediaSem2 : Result := fNotaMaxima[3] + fNotaMaxima[4];
cnbMediaBim, cnbNotaRec, cnbMediaFinal : Result := fNotaMaxima[1]
+ fNotaMaxima[2] + fNotaMaxima[3] + fNotaMaxima[4];
else
Result := 0;
end;
end else
Result := fNotaMaxima[0];
end;
function TCriterio.GetConceito(index: Integer): TConceito;
begin
Result := FConceitos[index];
end;
procedure TCriterio.SetConceito(index: Integer; const Value: TConceito);
begin
fConceitos[index] := Value;
end;
function TCriterio.GetNumConceitos: Integer;
begin
Result := Length(fConceitos);
end;
procedure TCriterio.SetNumConceitos(const Value: Integer);
begin
SetLength(fconceitos, Value);
end;
function TCriterio.ConceitoNota(Nota: Double; var Erro : Boolean): String;
var
i : Integer;
begin
Erro := false;
if NumConceitos = 0 then
Result := ''
else
begin
for i := 0 to NumConceitos - 1 do
if (Nota >= Conceito[i].NotaInicial) and (Nota <= Conceito[i].NotaFinal) then
begin
Result := Conceito[i].Conceito;
exit;
end;
// Se chegou nesse ponto é por que não encontrou nenhum conceito
// que coincida com a nota.
Erro := true;
Result := '';
end;
end;
function TCriterio.NotaCorteAposRec: Double;
begin
if CalculoNotaFinal = calc_soma then
Result := NotaCorte(cnbMediaFinal)
else
Result := fNotaCorte[1];
end;
{ TTabelaArredondamento }
function TTabelaArredondamento.Arredonda(Valor: Double): Double;
var
i : Integer;
begin
if Count = 0 then
Result := Valor
else
begin
i := 0;
{ while (i < Count) and not ((Valor >= Items[i].NotaInicial)
and (Valor < Items[i].NotaFinal)) do}
while (i < Count) and not ((strtofloat(formatfloat(',0.0000',Valor)) >= strtofloat(formatfloat(',0.0000',Items[i].NotaInicial)))
and (strtofloat(formatfloat(',0.0000',Valor)) < strtofloat(formatfloat(',0.0000',Items[i].NotaFinal )))) do
Inc(i);
if i < Count then
Result := items[i].Nota
else
result := Valor;
end;
end;
function TTabelaArredondamento.getCount: Integer;
begin
Result := Length(items);
end;
procedure TTabelaArredondamento.setCount(const Value: Integer);
begin
SetLength(items, Value);
end;
procedure TTabelaArredondamento.Carregar(pCodigo: Integer; Letivo : String);
var
i : Integer;
begin
with DMPrincipal do
begin
Codigo := pCodigo;
if pCodigo = 0 then
Count := 0
else
begin
OpenSQL(sqlItensArredondamento, 'SELECT * '+
' FROM ItensArredondamento '+
' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
' AND Codigo = '+ IntToStr(Codigo) +
' ORDER BY Item ');
Count := sqlItensArredondamento.RecordCount;
i := 0;
while not sqlItensArredondamento.Eof do
begin
items[i].NotaInicial := sqlItensArredondamentoNotaInicial.Value;
items[i].NotaFinal := sqlItensArredondamentoNotaFinal.Value;
items[i].Nota := sqlItensArredondamentoNota.Value;
sqlItensArredondamento.Next;
Inc(i);
end;
sqlItensArredondamento.Close;
end;
end;
end;
function TCriterio.NotaCorteRec(Campo: TCampoNotaBoletim; Bimestre: Integer): Double;
begin
if CalculoNotaFinal = calc_Soma then
begin
if Campo = cnbNotaPeriodo then
begin
if Bimestre = DMPrincipal.Letivo.NumPeriodos + 1 then
Campo := cnbNotaRec
else
if Bimestre = DMPrincipal.Letivo.NumPeriodos + 2 then
Campo := cnbRecSem1
else
if Bimestre = DMPrincipal.Letivo.NumPeriodos + 3 then
Campo := cnbRecSem2;
end;
case Campo of
cnbNotaPeriodo : Result := fNotaCorte[Bimestre];
cnbRecSem1, cnbMediaSem1 : Result := fNotaCorte[1] + fNotaCorte[2];
cnbRecSem2, cnbMediaSem2 : Result := fNotaCorte[3] + fNotaCorte[4];
cnbMediaBim, cnbNotaRec, cnbMediaFinal : Result := fNotaCorte[1]
+ fNotaCorte[2] + fNotaCorte[3] + fNotaCorte[4];
else
Result := 0;
end;
end else
Result := fNotaCorte[1];
end;
end.
|
unit zExplorerExt;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, RxVerInf,
Registry, zSharedFunctions, zAVKernel, zAVZKernel, zLogSystem;
type
// Информация о расширении проводника
TExplorerExtInfo = record
RegKey : string; // Ключ реестра
CLSID : string; // CLSID
BinFile : string; // Бинарный файл
ExtName : string; // Название
Descr : string; // Описание файла
LegalCopyright : string; // Копирайты файла
CheckResult : integer; // Результат проверки по базе безопасных программ
end;
TExplorerExtInfoArray = array of TExplorerExtInfo;
// Менеджер расширений проводника
TExplorerExtList = class
ExplorerExtInfoArray : TExplorerExtInfoArray;
constructor Create;
destructor Destroy; override;
function RefresList : boolean;
function ScanExplorerExtKeys(APrefix : string) : boolean;
function GetItemEnabledStatus(ItemInfo : TExplorerExtInfo) : integer;
function DeleteItem(ItemInfo : TExplorerExtInfo) : boolean;
function SetItemEnabledStatus(var ItemInfo : TExplorerExtInfo; NewStatus : boolean) : boolean;
function AddExplorerExt(ItemInfo : TExplorerExtInfo) : boolean;
private
function ExpandModuleFilename(AModuleName: string): string;
end;
implementation
uses zutil, zScriptingKernel;
{ TExplorerExtList }
function TExplorerExtList.ExpandModuleFilename(AModuleName : string): string;
begin
Result := NTFileNameToNormalName(Trim(AModuleName));
if not(FileExists(Result)) then
if FileExists(GetSystemDirectoryPath+Result) then
Result := GetSystemDirectoryPath+Result else
if FileExists(GetWindowsDirectoryPath+Result) then
Result := GetWindowsDirectoryPath+Result;
end;
function TExplorerExtList.AddExplorerExt(
ItemInfo: TExplorerExtInfo): boolean;
var
VersionInfo : TVersionInfo;
begin
ItemInfo.BinFile := ExpandModuleFilename(ItemInfo.BinFile);
ItemInfo.CheckResult := FileSignCheck.CheckFile(ItemInfo.BinFile);
try
VersionInfo := TVersionInfo.Create(ItemInfo.BinFile);
ItemInfo.Descr := VersionInfo.FileDescription;
ItemInfo.LegalCopyright := VersionInfo.LegalCopyright;
VersionInfo.Free;
except end;
SetLength(ExplorerExtInfoArray, Length(ExplorerExtInfoArray)+1);
ExplorerExtInfoArray[Length(ExplorerExtInfoArray)-1] := ItemInfo;
end;
constructor TExplorerExtList.Create;
begin
ExplorerExtInfoArray := nil;
end;
function TExplorerExtList.DeleteItem(
ItemInfo: TExplorerExtInfo): boolean;
var
Reg : TRegistry;
begin
Result := false;
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.DeleteKey(ItemInfo.RegKey+'\'+ItemInfo.CLSID);
Reg.Free;
Result := true;
end;
destructor TExplorerExtList.Destroy;
begin
ExplorerExtInfoArray := nil;
inherited;
end;
function TExplorerExtList.GetItemEnabledStatus(
ItemInfo: TExplorerExtInfo): integer;
begin
Result := 1;
if copy(ItemInfo.RegKey, length(ItemInfo.RegKey), 1) = '-' then
Result := 0;
end;
function TExplorerExtList.RefresList: boolean;
begin
ExplorerExtInfoArray := nil;
ScanExplorerExtKeys('');
ScanExplorerExtKeys('-');
end;
function TExplorerExtList.ScanExplorerExtKeys(APrefix: string): boolean;
var
Reg : TRegistry;
List : TStrings;
Tmp : TExplorerExtInfo;
i : integer;
BaseKey, S : string;
begin
Reg := TRegistry.Create;
List := TStringList.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
// Поиск элементов расширения
BaseKey := 'SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved'+APrefix;
if Reg.OpenKey(BaseKey, false) then begin
Reg.GetValueNames(List);
ZProgressClass.AddProgressMax(List.Count);
for i := 0 to List.Count - 1 do begin
ZProgressClass.ProgressStep;
Tmp.RegKey := BaseKey;
Tmp.CLSID := Trim(List[i]);
S := copy(Tmp.CLSID, 2, length(Tmp.CLSID)-2);
Tmp.BinFile := CLSIDFileName(S);
Tmp.ExtName := '';
if Reg.GetDataType(List[i]) in [rdString, rdExpandString] then
Tmp.ExtName := Reg.ReadString(List[i]);
AddExplorerExt(Tmp);
end;
Reg.CloseKey;
end;
List.Free;
Reg.Free;
end;
function TExplorerExtList.SetItemEnabledStatus(
var ItemInfo: TExplorerExtInfo; NewStatus: boolean): boolean;
var
Reg : TRegistry;
S : string;
begin
Result := false;
// Лог. защита - блокирования активации активного и выключения неактивного
if NewStatus and (GetItemEnabledStatus(ItemInfo) <> 0) then exit;
if not(NewStatus) and (GetItemEnabledStatus(ItemInfo) <> 1) then exit;
// Блокировка
if not(NewStatus) then begin
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey(ItemInfo.RegKey, false) then begin
S := Reg.ReadString(ItemInfo.CLSID);
Reg.DeleteValue(ItemInfo.CLSID);
Reg.CloseKey;
// Создание на новом месте
ItemInfo.RegKey := ItemInfo.RegKey + '-';
if Reg.OpenKey(ItemInfo.RegKey, true) then begin
Reg.WriteString(ItemInfo.CLSID, S);
Reg.CloseKey;
Result := true;
end;
end;
end;
// Разблокировка
if NewStatus then begin
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey(ItemInfo.RegKey, false) then begin
S := Reg.ReadString(ItemInfo.CLSID);
Reg.DeleteValue(ItemInfo.CLSID);
Reg.CloseKey;
ItemInfo.RegKey := copy(ItemInfo.RegKey, 1, length(ItemInfo.RegKey)-1);
// Создание на новом месте
if Reg.OpenKey(ItemInfo.RegKey, true) then begin
Reg.WriteString(ItemInfo.CLSID, S);
Reg.CloseKey;
end;
Result := true;
end;
end;
end;
end.
|
unit uDetailedProxyForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, Forms,
uConfiguratorData;
type
{ TDetailedProxyForm }
TDetailedProxyForm = class
private
fParent: TWinControl;
fCurrent: TDetailedForm;
private
function Find(const aFormClass: TDetailedFormClass): TDetailedForm;
function Creator(const aFormClass: TDetailedFormClass): TDetailedForm;
public
constructor Create(const aParent: TWinControl); reintroduce;
destructor Destroy; override;
procedure View(const aContentData: array of TContentData);
procedure Hide;
end;
implementation
constructor TDetailedProxyForm.Create(const aParent: TWinControl);
begin
inherited Create;
fParent := aParent;
fCurrent := nil;
end;
destructor TDetailedProxyForm.Destroy;
begin
Hide;
inherited Destroy;
end;
procedure TDetailedProxyForm.View(const aContentData: array of TContentData);
begin
if Length(aContentData) = 0 then
Exit;
if aContentData[0].FormClass = nil then
Exit;
Hide;
try
// Загрузить форму в соответствии с классовой ссылкой
if fCurrent = nil then
begin
fCurrent := Creator(aContentData[0].FormClass);
// Показать
fCurrent.Show;
Exit;
end;
if not (fCurrent is aContentData[0].FormClass) then
begin
// Скрыть форму
fCurrent.Hide;
// Поиск формы
fCurrent := Find(aContentData[0].FormClass);
// Если не найдена, создается новая
if fCurrent = nil then
fCurrent := Creator(aContentData[0].FormClass);
// Показать
fCurrent.Show;
end;
finally
// Загрузить новые параметры
fCurrent.Load(aContentData);
end;
end;
procedure TDetailedProxyForm.Hide;
begin
if fCurrent <> nil then
fCurrent.Unload;
end;
function TDetailedProxyForm.Find(const aFormClass: TDetailedFormClass
): TDetailedForm;
var
Index: integer;
begin
Result := nil;
// Поиск дочерних элементов управления(форм) в контейнере
for Index := 0 to fParent.ControlCount - 1 do
if fParent.Controls[Index] is aFormClass then
begin
Result := fParent.Controls[Index] as TDetailedForm;
Break;
end;
end;
function TDetailedProxyForm.Creator(const aFormClass: TDetailedFormClass
): TDetailedForm;
begin
Result := aFormClass.Create(Application);
Result.Parent := fParent;
Result.Align := alClient;
end;
end.
|
unit TelegAPI.Base;
{$I config.inc}
interface
uses
System.Classes;
type
TtgAbstractComponent = class(TComponent)
private
FVersion: string;
FAutor: string;
public
constructor Create(AOwner: TComponent); override;
published
property Autor: string read FAutor;
/// <summary>
/// Поддерживаемая версия платформы BotAPI
/// </summary>
property Version: string read FVersion;
end;
implementation
{ TtgAbstractComponent }
constructor TtgAbstractComponent.Create(AOwner: TComponent);
begin
inherited;
FAutor := 'Maxim Sysoev';
FVersion := '3.5.5';
end;
end.
|
unit uPessoa;
interface
type
TPessoa = class
private
FNome:string;
FDataNasc:String;
FSexo:String;
FNacionalidade:String;
function getNome:string;
procedure setNome(valor:String);
function getDataNasc:string;
procedure setDataNasc(valor:string);
function getSexo:String;
procedure setSexo(valor:string);
function getNacionalidade:string;
procedure setNacionalidade(valor:string);
public
property Nome:String read getNome write setNome;
property DataNasc:string read getDataNasc write setDataNasc;
property Sexo:string read getSexo write setSexo;
property Nacionalidade:string read getNacionalidade write setNacionalidade;
Function idade : Integer;
function ReceberValor(i:Integer):string;overload;
function receberValor(i:string):string;overload;
function RetornaNome:String; virtual;{indica que essa função pode ser reescrita em outra classe filha}
function MetodoAbstrato:String; virtual; abstract;{não pode ser implementado na classe mãe}
end;
implementation
uses SysUtils;
{TPessoa}
function TPessoa.idade : Integer;
begin
result:= Trunc((now - StrToDate(DataNasc))/365.25);
end;
function TPessoa.getNome:string;
begin
result:=FNome;
end;
procedure TPessoa.setNome(valor:String);
begin
FNome := valor;
end;
function TPessoa.getDataNasc:string;
begin
Result:=FDataNasc;
end;
procedure TPessoa.setDataNasc(valor:string);
begin
FDataNasc:=valor;
end;
function TPessoa.getSexo:string;
begin
result:= FSexo;
end;
procedure TPessoa.setSexo(valor:string);
begin
fsexo := valor;
end;
function TPessoa.getNacionalidade:string;
begin
result:=FNacionalidade;
end;
procedure TPessoa.setNacionalidade(valor:string);
begin
FNacionalidade:=valor;
end;
function TPessoa.ReceberValor(i: Integer): string;
begin
result:= 'O valor recebido foi um inteiro de: '+IntToStr(i);
end;
function TPessoa.ReceberValor(i: string): string;
begin
result:= 'O valor recebido foi uma string de: '+i;
end;
function TPessoa.RetornaNome: String;
begin
Nome := 'TPessoa';
// Result:= 'Essa é a classe TPessoa';
end;
end.
|
unit uFrameCover;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, IdComponent, JPEG, PNGImage, GIFImg,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, acImage, Vcl.ComCtrls, acProgressBar, sPanel, sFrameAdapter, Vcl.StdCtrls, sLabel,
xSuperObject, IdTCPConnection, IdTCPClient, IdHTTP, IdSSL, IdSSLOpenSSL, IdURI, NetEncoding, KryptoGlowLabel;
type
tREfreshCell0 = procedure(fPos: Integer) of object;
tAddLog = procedure(sFunc, sLog: String) of object;
tSearchEnd = procedure(presult : Integer) of object;
tSearchTerminated = procedure(pFrame : tFrame; iResult : Integer) of object;
tDownloadThread = class(TThread)
private
fMax: Integer;
fPos: Integer;
fCol: Integer;
fRow: Integer;
fUrl: String;
fRefresh: tREfreshCell0;
fImage1: tsImage;
fAddLog: tAddLog;
fSearchEnd : tSearchEnd;
fFrameName : String;
procedure downloadImage(sUrl: string);
protected
procedure Execute; override;
public
procedure onWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
procedure onWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
procedure onWorkEnd(ASender: TObject; AWorkMode: TWorkMode);
constructor create(aUrl: String; aImage: tsImage; CallBack: tREfreshCell0; pAddLog: tAddLog; sFrameName : String; pSearchEnd : tSearchEnd); reintroduce;
end;
tFrameCover = class(TFrame)
sPnCCoverSearch: TsPanel;
sPB1: TsProgressBar;
sImage1: tsImage;
sFrameAdapter1: TsFrameAdapter;
sLabel1: TsLabel;
private
{ Déclarations privées }
iResult : Integer;
public
{ Déclarations publiques }
addLog: tAddLog;
sUrl: String;
SearchTerminated : tSearchTerminated;
procedure StartDownload;
procedure refreshPB(aPos: Integer);
procedure SearchEnd(pResult : Integer);
end;
implementation
{$R *.dfm}
constructor tDownloadThread.create(aUrl: String; aImage: tsImage; CallBack: tREfreshCell0; pAddLog: tAddLog; sFrameName : String; pSearchEnd : tSearchEnd);
begin
inherited create(true);
FreeOnTerminate := true;
fImage1 := aImage;
fUrl := aUrl;
fRefresh := CallBack;
fAddLog := pAddLog;
fFrameName := sFrameName;
fSearchEnd := pSearchEnd;
end;
procedure tDownloadThread.downloadImage(sUrl: string);
var
IdSSL: TIdSSLIOHandlerSocketOpenSSL;
IdHTTP1: TIdHTTP;
MS: tMemoryStream;
jpgImg: TJPEGImage;
Picture: tPicture;
bContinue : boolean;
begin
IdSSL := TIdSSLIOHandlerSocketOpenSSL.create(nil);
IdHTTP1 := TIdHTTP.create;
IdHTTP1.ReadTimeout := 5000;
IdHTTP1.IOHandler := IdSSL;
IdHTTP1.Request.Accept := 'text/html, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*';
IdHTTP1.Request.AcceptEncoding := 'gzip, deflate';
IdHTTP1.Request.UserAgent := 'Mozilla/5.0';
IdHTTP1.onWork := onWork;
IdHTTP1.onWorkBegin := onWorkBegin;
IdHTTP1.onWorkEnd := onWorkEnd;
IdSSL.SSLOptions.Method := sslvTLSv1_2;
IdSSL.SSLOptions.Mode := sslmUnassigned;
fAddLog('uFrameCover.tDownloadThread.DownloadImage : '+sUrl, 'Start');
try
MS := tMemoryStream.create;
jpgImg := TJPEGImage.create;
try
IdHTTP1.Get(sUrl, MS);
Application.ProcessMessages;
MS.Seek(0, soFromBeginning);
jpgImg.LoadFromStream(MS);
Picture := tPicture.create;
Picture.Bitmap.Assign(jpgImg);
// fGrid.AddPicture(fCol, fRow, Picture, false, tStretchMode.Shrink, 2, haCenter, vaCenter);
fImage1.Picture.Assign(Picture);
except
on e: exception do
begin
fAddLog(fFrameName + '.tDownloadThread.DownloadImage', e.Message);
fSearchEnd(-1);
// Memo1.Lines.Add('erreur '+e.Message);
end;
end;
finally
FreeAndNil(MS);
FreeAndNil(jpgImg);
IdHTTP1.Free;
IdSSL.Free;
fRefresh(-1);
fSearchEnd(0);
end;
if not terminated then
terminate;
end;
procedure tDownloadThread.Execute;
begin
inherited;
downloadImage(fUrl);
while not terminated do
begin
Application.ProcessMessages;
end;
end;
procedure tDownloadThread.onWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
var
p: Integer;
begin
p := round(AWorkCount / fMax * 100);
fRefresh(p);
end;
procedure tDownloadThread.onWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
begin
fMax := AWorkCountMax;
fPos := 0;
end;
procedure tDownloadThread.onWorkEnd(ASender: TObject; AWorkMode: TWorkMode);
var
aFrame: tFrameCover;
begin
fPos := 0;
end;
{ tFrameCover }
procedure tFrameCover.refreshPB(aPos: Integer);
begin
if aPos = -1 then
begin
sPB1.Visible := false;
if self.Name = 'aFrameCover1' then
begin
sImage1.OnClick(sImage1);
end;
end
else
sPB1.Position := aPos;
end;
procedure tFrameCover.SearchEnd(pResult: Integer);
begin
SearchTerminated(self,pResult);
end;
procedure tFrameCover.StartDownload;
var
aDownloadTh: tDownloadThread;
begin
sPB1.Visible := true;
iResult := 0;
aDownloadTh := tDownloadThread.create(sUrl, sImage1, refreshPB, addLog, name, SearchEnd);
aDownloadTh.FreeOnTerminate := true;
aDownloadTh.Start;
end;
end.
|
program menulayout;
{$IFNDEF HASAMIGA}
{$FATAL This source is compatible with Amiga, AROS and MorphOS only !}
{$ENDIF}
{
Project : menulayout
Topic : Example showing how to do menu layout in general.
Source : RKRM
}
{*
** This example also illustrates handling menu events, including
** IDCMP_MENUHELP events.
**
** Note that handling arbitrary fonts is fairly complex. Applications that require V37
** should use the simpler menu layout routines found in the GadTools library.
*}
{$MODE OBJFPC}{$H+}{$HINTS ON}
{$UNITPATH ../../../Base/CHelpers}
{$UNITPATH ../../../Base/Trinity}
Uses
Exec, AmigaDOS, AGraphics, Intuition, utility,
{$IFDEF AMIGA}
SystemVarTags,
{$ENDIF}
CHelpers,
Trinity;
type
pUWORD = ^UWORD;
const
//* Settings Item IntuiText */
SettText : array[0..3] of TIntuiText =
(
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Sound...'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: CHECKWIDTH; TopEdge: 1; ITextFont: nil; IText: ' Auto Save'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: CHECKWIDTH; TopEdge: 1; ITextFont: nil; IText: ' Have Your Cake'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: CHECKWIDTH; TopEdge: 1; ITextFont: nil; IText: ' Eat It Too'; NextText: nil )
);
SettItem : array[0..3] of TMenuItem =
(
//* "Sound..." */
(
NextItem : @SettItem[1]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@SettText[0]); SelectFill: nil; Command: #0; SubItem: nil;
NextSelect : MENUNULL
),
//* "Auto Save" (toggle-select, initially selected) */
(
NextItem : @SettItem[2]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or ITEMENABLED or HIGHCOMP or CHECKIT or MENUTOGGLE or CHECKED; MutualExclude: 0;
ItemFill : APTR(@SettText[1]); SelectFill: nil; Command: #0; SubItem: nil;
NextSelect : MENUNULL
),
//* "Have Your Cake" (initially selected, excludes "Eat It Too") */
(
NextItem : @SettItem[3]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or ITEMENABLED or HIGHCOMP or CHECKIT or CHECKED; MutualExclude: 0;
ItemFill : APTR(@SettText[2]); SelectFill: nil; Command: #0; SubItem: nil;
NextSelect : MENUNULL
),
//* "Eat It Too" (excludes "Have Your Cake") */
(
NextItem : nil; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or ITEMENABLED or HIGHCOMP or CHECKIT; MutualExclude: 0;
ItemFill : APTR(@SettText[3]); SelectFill: nil; Command: #0; SubItem: nil;
NextSelect : MENUNULL
)
);
//* Edit Menu Item IntuiText */
EditText : array[0..4] of TIntuiText =
(
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Cut'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Copy'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Paste'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Erase'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Undo'; NextText: nil )
);
//* Edit Menu Items */
EditItem : array[0..4] of TMenuItem =
(
( //* "Cut" (key-equivalent: 'X') */
NextItem : @EditItem[1]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or COMMSEQ or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@EditText[0]); SelectFill: nil; Command: 'X'; SubItem: nil;
NextSelect : MENUNULL
),
( //* "Copy" (key-equivalent: 'C') */
NextItem : @EditItem[2]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or COMMSEQ or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@EditText[1]); SelectFill: nil; Command: 'C'; SubItem: nil;
NextSelect : MENUNULL
),
( //* "Paste" (key-equivalent: 'V') */
NextItem : @EditItem[3]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or COMMSEQ or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@EditText[2]); SelectFill: nil; Command: 'V'; SubItem: nil;
NextSelect : MENUNULL
),
( //* "Erase" (disabled) */
NextItem : @EditItem[4]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@EditText[3]); SelectFill: nil; Command: #0; SubItem: nil;
NextSelect : MENUNULL
),
( //* "Undo" MenuItem (key-equivalent: 'Z') */
NextItem : nil; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or COMMSEQ or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@EditText[4]); SelectFill: nil; Command: 'Z'; SubItem: nil;
NextSelect : MENUNULL
)
);
//* IntuiText for the Print Sub-Items */
PrtText : array[0..1] of TIntuiText =
(
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'NLQ'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Draft'; NextText: nil )
);
//* Print Sub-Items */
PrtItem : array[0..1] of TMenuItem =
(
( //* "NLQ" */
NextItem : @PrtItem[1]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@PrtText[0]); SelectFill: nil; Command: #0; SubItem: nil;
NextSelect : MENUNULL
),
( //* "NLQ" */
NextItem : nil; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@PrtText[1]); SelectFill: nil; Command: #0; SubItem: nil;
NextSelect : MENUNULL
)
);
{* Uses the >> character to indicate a sub-menu item.
** This is \273 Octal, 0xBB Hex or Alt-0 from the Keyboard.
**
** NOTE that standard menus place this character at the right margin of the menu box.
** This may be done by using a second IntuiText structure for the single character,
** linking this IntuiText to the first one, and positioning the IntuiText so that the
** character appears at the right margin. GadTools library will provide the correct behavior.
*}
//* Project Menu Item IntuiText */
ProjText : array[0..6] of TIntuiText =
(
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'New'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Open...'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Save'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Save As...'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Print '#187; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'About'; NextText: nil ),
( FrontPen: 0; BackPen: 1; DrawMode: JAM2; LeftEdge: 2; TopEdge: 1; ITextFont: nil; IText: 'Quit'; NextText: nil )
);
//* Project Menu Items */
ProjItem : array[0..6] of TMenuItem =
(
( //* "New" (key-equivalent: 'N' */
NextItem : @ProjItem[1]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or COMMSEQ or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@ProjText[0]); SelectFill: nil; Command: 'N'; SubItem: nil;
NextSelect : MENUNULL
),
( //* "Open..." (key-equivalent: 'O') */
NextItem : @ProjItem[2]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or COMMSEQ or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@ProjText[1]); SelectFill: nil; Command: 'O'; SubItem: nil;
NextSelect : MENUNULL
),
( //* "Save" (key-equivalent: 'S') */
NextItem : @ProjItem[3]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or COMMSEQ or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@ProjText[2]); SelectFill: nil; Command: 'S'; SubItem: nil;
NextSelect : MENUNULL
),
( //* "Save As..." (key-equivalent: 'A') */
NextItem : @ProjItem[4]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@ProjText[3]); SelectFill: nil; Command: 'A'; SubItem: nil;
NextSelect : MENUNULL
),
( //* "Print" (has sub-menu) */
NextItem : @ProjItem[5]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@ProjText[4]); SelectFill: nil; Command: #0; SubItem: @PrtItem[0];
NextSelect : MENUNULL
),
( //* "About..." */
NextItem : @ProjItem[6]; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@ProjText[5]); SelectFill: nil; Command: #0; SubItem: nil;
NextSelect : MENUNULL
),
( //* "Quit" (key-equivalent: 'Q' */
NextItem : nil; LeftEdge: 0; TopEdge: 0; Width: 0; Height: 0;
Flags : ITEMTEXT or COMMSEQ or ITEMENABLED or HIGHCOMP; MutualExclude: 0;
ItemFill : APTR(@ProjText[6]); SelectFill: nil; Command: 'Q'; SubItem: nil;
NextSelect : MENUNULL
)
);
//* Menu Titles */
Menus : array[0..2] of TMenu =
(
( NextMenu: @Menus[1]; LeftEdge: 0; TopEdge: 0; Width: 63; Height: 0; Flags: MENUENABLED; MenuName: 'Project' ; FirstItem: @ProjItem[0] ),
( NextMenu: @Menus[2]; LeftEdge: 70; TopEdge: 0; Width: 39; Height: 0; Flags: MENUENABLED; MenuName: 'Edit' ; FirstItem: @EditItem[0] ),
( NextMenu: nil; LeftEdge: 120; TopEdge: 0; Width: 88; Height: 0; Flags: MENUENABLED; MenuName: 'Settings'; FirstItem: @SettItem[0] )
);
//* A pointer to the first menu for easy reference */
FirstMenu : PMenu = @Menus[0];
//* Window Text for Explanation of Program */
WinText : array[0..1] of TIntuiText =
(
( FrontPen: 0; BackPen: 0; DrawMode: JAM2; LeftEdge: 0; TopEdge: 0; ITextFont: nil; IText: 'How to do a Menu'; NextText: nil ),
( FrontPen: 0; BackPen: 0; DrawMode: JAM2; LeftEdge: 0; TopEdge: 0; ITextFont: nil; IText: '(with Style)' ; NextText: @WinText[0] )
);
//* Our function prototypes */
function processMenus(selection: Word; done: Boolean): Boolean; forward;
function handleIDCMP(win: PWindow): boolean; forward;
function MaxLength(textRPort: PRastPort; first_item: PMenuItem; char_size: Word): Word; forward;
procedure setITextAttr(first_IText: PIntuiText; textAttr: PTextAttr); forward;
procedure adjustItems(textRPort: PRastPort; first_item: PMenuItem; textAttr: PTextAttr; char_size: Word; Height: Word; level: Word; left_edge: Word); forward;
function adjustMenus(first_menu: PMenu; textAttr: PTextAttr): Boolean; forward;
function doWindow: LONG; forward;
{* open all of the required libraries. Note that we require
** Intuition V37, as the routine uses OpenWindowTags().
*}
function Main(argc: Integer; argv: PPChar): Integer;
var
returnValue : LONG;
begin
//* This gets set to RETURN_OK if everything goes well. */
returnValue := RETURN_FAIL;
//* Open the Intuition Library */
{$IFDEF MORPHOS}
IntuitionBase := OpenLibrary('intuition.library', 37);
if Assigned(IntuitionBase) then
{$ENDIF}
begin
//* Open the Graphics Library */
{$IFNDEF HASAMIGA}
GfxBase := PGfxBase(OpenLibrary('graphics.library', 33));
if assigned(GfxBase) then
{$ENDIF}
begin
returnValue := doWindow();
{$IFNDEF HASAMIGA}
CloseLibrary(GfxBase);
{$ENDIF}
end;
{$IFDEF MORPHOS}
CloseLibrary(PLibrary(IntuitionBase));
{$ENDIF}
end;
Result := (returnValue);
end;
{* Open a window with some properly positioned text. Layout and set
** the menus, then process any events received. Cleanup when done.
*}
function doWindow: LONG;
var
window : PWindow;
screen : PScreen;
drawinfo : PDrawInfo;
signalmask,
signals : ULONG;
win_width,
alt_width,
win_height : ULONG;
returnValue : LONG = RETURN_FAIL;
done : Boolean = FALSE;
begin
if SetAndTest(screen, LockPubScreen(nil)) then
begin
if SetAndTest(drawinfo, GetScreenDrawInfo(screen)) then
begin
///* get the colors for the window text */
WinText[0].FrontPen := PUWORD(drawinfo^.dri_Pens)[TEXTPEN];
WinText[1].FrontPen := PUWORD(drawinfo^.dri_Pens)[TEXTPEN];
WinText[0].BackPen := PUWORD(drawinfo^.dri_Pens)[BACKGROUNDPEN];
WinText[1].BackPen := PUWORD(drawinfo^.dri_Pens)[BACKGROUNDPEN];
//* use the screen's font for the text */
WinText[0].ITextFont := screen^.Font;
WinText[1].ITextFont := screen^.Font;
//* calculate window size */
win_width := 100 + IntuiTextLength(@(WinText[0]));
alt_width := 100 + IntuiTextLength(@(WinText[1]));
if (win_width < alt_width) then win_width := alt_width;
win_height := 1 + screen^.WBorTop + screen^.WBorBottom +
(screen^.Font^.ta_YSize * 5);
//* calculate the correct positions for the text in the window */
WinText[0].LeftEdge := (win_width - IntuiTextLength(@(WinText[0]))) shr 1;
WinText[0].TopEdge := 1 + screen^.WBorTop + (2 * screen^.Font^.ta_YSize);
WinText[1].LeftEdge := (win_width - IntuiTextLength(@(WinText[1]))) shr 1;
WinText[1].TopEdge := WinText[0].TopEdge + screen^.Font^.ta_YSize;
//* Open the window */
window := OpenWindowTags(nil,
[
TAG_(WA_PubScreen) , TAG_(screen),
TAG_(WA_IDCMP) , IDCMP_MENUPICK or IDCMP_CLOSEWINDOW or IDCMP_MENUHELP,
TAG_(WA_Flags) , WFLG_DRAGBAR or WFLG_DEPTHGADGET or WFLG_CLOSEGADGET or WFLG_ACTIVATE or WFLG_NOCAREREFRESH,
TAG_(WA_Left) , 10,
TAG_(WA_Top) , screen^.BarHeight + 1,
TAG_(WA_Width) , win_width,
TAG_(WA_Height) , win_height,
TAG_(WA_Title) , TAG_(PChar('Menu Example')),
TAG_(WA_MenuHelp) , TAG_(TRUE),
TAG_END
]);
if assigned(window) then
begin
returnValue := RETURN_OK; //* program initialized ok */
//* Give a brief explanation of the program */
PrintIText(window^.RPort, @WinText[1],0,0);
//* Adjust the menu to conform to the font (TextAttr) */
adjustMenus(FirstMenu, PScreen(window^.WScreen)^.Font);
//* attach the menu to the window */
SetMenuStrip(window, FirstMenu);
//* Set up the signals that you want to hear about ... */
signalmask := 1 shl window^.UserPort^.mp_SigBit;
//* And wait to hear from your signals */
while not(done) do
begin
signals := Wait(signalmask);
if (signals and signalmask <> 0) then done := handleIDCMP(window);
end;
//* clean up everything used here */
ClearMenuStrip(window);
CloseWindow(window);
end;
FreeScreenDrawInfo(screen, drawinfo);
end;
UnlockPubScreen(nil, screen);
end;
Result := (returnValue);
end;
{* print out what menu was selected. Properly handle the IDCMP_MENUHELP
** events. Set done to TRUE if quit is selected.
*}
function processMenus(selection: Word; done: Boolean): Boolean;
var
flags : Word;
menuNum,
itemNum,
subNum : Word;
begin
menuNum := Intuition.MENUNUM(selection);
itemNum := Intuition.ITEMNUM(selection);
subNum := Intuition.SUBNUM(selection);
{* when processing IDCMP_MENUHELP, you are not guaranteed
** to get a menu item.
*}
if (itemNum <> NOITEM) then
begin
flags := PMenuItem(ItemAddress(FirstMenu,LONG(selection)))^.Flags;
if (flags and CHECKED <> 0)
then Write('(Checked) ');
end;
case (menuNum) of
0: //* Project Menu */
case (itemNum) of
NOITEM: WriteLn('Project Menu');
0: WriteLn('New');
1: WriteLn('Open');
2: WriteLn('Save');
3: WriteLn('Save As');
4: begin
Write('Print ');
case (subNum) of
NOSUB: WriteLn('Item');
0: WriteLn('NLQ');
1: WriteLn('Draft');
end;
end;
5: WriteLn('About');
6: begin
WriteLn('Quit');
done := TRUE;
end;
end;
1: //* Edit Menu */
case (itemNum) of
NOITEM: WriteLn('Edit Menu');
0: WriteLn('Cut');
1: WriteLn('Copy');
2: WriteLn('Paste');
3: WriteLn('Erase');
4: WriteLn('Undo');
end;
2: //* Settings Menu */
case (itemNum) of
NOITEM: WriteLn('Settings Menu');
0: WriteLn('Sound');
1: WriteLn('Auto Save');
2: WriteLn('Have Your Cake');
3: WriteLn('Eat It Too');
end;
NOMENU: //* No menu selected, can happen with IDCMP_MENUHELP */
WriteLn('no menu');
end;
Result := (done);
end;
//* Handle the IDCMP messages. Set done to TRUE if quit or closewindow is selected. */
function handleIDCMP(win: PWindow): boolean;
var
done : boolean;
code,
selection : Word;
imessage : PIntuiMessage = nil;
iclass : ULONG;
begin
done := FALSE;
//* Examine pending messages */
while SetAndTest(imessage, PIntuiMessage(GetMsg(win^.UserPort))) do
begin
iclass := imessage^.iClass;
code := imessage^.Code;
//* When we're through with a message, reply */
ReplyMsg(PMessage(imessage));
//* See what events occurred */
case (iclass) of
IDCMP_CLOSEWINDOW:
begin
done := TRUE;
end;
IDCMP_MENUHELP:
begin
{*
** The routine that handles the menus for IDCMP_MENUHELP must be very careful
** it can receive menu information that is impossible under IDCMP_MENUPICK.
** For instance, the code value on a IDCMP_MENUHELP may have a valid number
** for the menu, then NOITEM and NOSUB. IDCMP_MENUPICK would get MENUNULL
** in this case. IDCMP_MENUHELP never come as multi-select items, and the
** event terminates the menu processing session.
**
** Note that I do not keep the return value from the processMenus() routine here--the
** application should not quit if the user selects "help" over the quit menu item.
*}
Write('IDCMP_MENUHELP: Help on ');
processMenus(code, done);
end;
IDCMP_MENUPICK:
begin
selection := code;
while (selection <> MENUNULL) do
begin
Write('IDCMP_MENUPICK: Selected ');
done := processMenus(selection, done);
selection := ItemAddress(FirstMenu, LONG(selection))^.NextSelect;
end;
end;
end;
end;
Result := done;
end;
//* Steps thru each item to determine the maximum width of the strip */
function MaxLength(textRPort: PRastPort; first_item: PMenuItem; char_size: Word): Word;
var
maxLen : Word;
total_textlen : Word;
cur_item : PMenuItem;
itext : PIntuiText;
extra_width : Word;
maxCommCharWidth : Word;
commCharWidth : Word;
begin
extra_width := char_size; //* used as padding for each item. */
{* Find the maximum length of a command character, if any.
** If found, it will be added to the extra_width field.
*}
maxCommCharWidth := 0;
cur_item := first_item;
while (cur_item <> nil) do
begin
if (cur_item^.Flags and COMMSEQ <> 0) then
begin
commCharWidth := TextLength(textRPort, @(cur_item^.Command), 1);
if (commCharWidth > maxCommCharWidth)
then maxCommCharWidth := commCharWidth;
end;
cur_item := cur_item^.NextItem;
end;
{* if we found a command sequence, add it to the extra required space. Add
** space for the Amiga key glyph plus space for the command character. Note
** this only works for HIRES screens, for LORES, use LOWCOMMWIDTH.
*}
if (maxCommCharWidth > 0)
then extra_width := extra_width + maxCommCharWidth + COMMWIDTH;
//* Find the maximum length of the menu items, given the extra width calculated above. */
maxLen := 0;
cur_item := first_item;
while (cur_item <> nil) do
begin
itext := PIntuiText(cur_item^.ItemFill);
total_textlen := extra_width + itext^.LeftEdge +
TextLength(textRPort, itext^.IText, strlen(itext^.IText));
//* returns the greater of the two */
if (total_textlen > maxLen)
then maxLen := total_textlen;
cur_item := cur_item^.NextItem;
end;
result := (maxLen);
end;
//* Set all IntuiText in a chain (they are linked through the NextText ** field) to the same font. */
procedure setITextAttr(first_IText: PIntuiText; textAttr: PTextAttr);
var
cur_IText : PIntuiText;
begin
cur_IText := first_IText;
while (cur_IText <> nil) do
begin
cur_IText^.ITextFont := textAttr;
cur_IText := cur_IText^.NextText;
end;
end;
procedure adjustItems(textRPort: PRastPort; first_item: PMenuItem; textAttr: PTextAttr; char_size: Word; Height: Word; level: Word; left_edge: Word);
var
item_num : Word;
cur_item : PMenuItem;
strip_width,
subitem_edge : Word;
begin
if (first_item = nil)
then exit;
//* The width of this strip is the maximum length of its members. */
strip_width := MaxLength(textRPort, first_item, char_size);
//* Position the items. */
cur_item := first_item;
item_num := 0;
while (cur_item <> nil) do
begin
cur_item^.TopEdge := (item_num * height) - level;
cur_item^.LeftEdge := left_edge;
cur_item^.Width := strip_width;
cur_item^.Height := height;
//* place the sub_item 3/4 of the way over on the item. */
subitem_edge := strip_width - (strip_width shr 2);
setITextAttr(PIntuiText(cur_item^.ItemFill), textAttr);
adjustItems(textRPort, cur_item^.SubItem, textAttr, char_size, height, 1, subitem_edge);
cur_item := cur_item^.NextItem;
inc(item_num);
end;
end;
{* The following routines adjust an entire menu system to conform to the
** specified fonts' width and height. Allows for Proportional Fonts. This is
** necessary for a clean look regardless of what the users preference in Fonts
** may be. Using these routines, you don't need to specify TopEdge, LeftEdge,
** Width or Height in the MenuItem structures.
**
** NOTE that this routine does not work for menus with images, but assumes
** that all menu items are rendered with IntuiText.
**
** This set of routines does NOT check/correct if the menu runs off
** the screen due to large fonts, too many items, lo-res screen.
*}
function adjustMenus(first_menu: PMenu; textAttr: PTextAttr): Boolean;
var
textrp : TRastPort; //* Temporary RastPort */
cur_menu : PMenu;
font : PTextFont; //* Font to use */
start,
char_size,
height : Word;
returnValue : boolean = false;
begin
textrp := default(TRastPort);
//* open the font */
if SetAndTest(font, OpenFont(textAttr)) then
begin
SetFont(@textrp, font); //* Put font into temporary RastPort */
char_size := TextLength(@textrp, 'n', 1); //* Get the Width of the Font */
{* To prevent crowding of the Amiga key when using COMMSEQ, don't allow the items to be less
** than 8 pixels high. Also, add an extra pixel for inter-line spacing.
*}
if (font^.tf_YSize > 8)
then height := 1 + font^.tf_YSize
else height := 1 + 8;
start := 2; //* Set Starting Pixel */
//* Step thru the menu structure and adjust it */
cur_menu := first_menu;
while (cur_menu <> nil) do
begin
cur_menu^.LeftEdge := start;
cur_menu^.Width := char_size + TextLength(@textrp, cur_menu^.MenuName, strlen(cur_menu^.MenuName));
adjustItems(@textrp, cur_menu^.FirstItem, textAttr, char_size, height, 0, 0);
start := start + cur_menu^.Width + char_size + char_size;
cur_menu := cur_menu^.NextMenu;
end;
CloseFont(font); //* Close the Font */
returnValue := TRUE;
end;
result := (returnValue);
end;
begin
ExitCode := Main(Argc, ArgV);
end.
|
unit modFVersion;
interface
uses ShellApi,SysUtils,Windows;
type
TFileVersionInfo = record
FileType,
CompanyName,
FileDescription,
FileVersion,
InternalName,
LegalCopyRight,
LegalTradeMarks,
OriginalFileName,
ProductName,
ProductVersion,
Comments,
SpecialBuildStr,
PrivateBuildStr,
FileFunction : string;
DebugBuild,
PreRelease,
SpecialBuild,
PrivateBuild,
Patched,
InfoInferred : Boolean;
end;
function FileVersionInfo(const sAppNamePath: TFileName): TFileVersionInfo;
function GetFileVersionString(const sAppNamePath: TFileName): String;
function GetFileVersionString2(const sAppNamePath: TFileName): String;
implementation
function FileVersionInfo(const sAppNamePath: TFileName): TFileVersionInfo;
var
rSHFI: TSHFileInfo;
iRet: Integer;
VerSize: Integer;
VerBuf: PChar;
VerBufValue: Pointer;
VerHandle: Cardinal;
VerBufLen: Cardinal;
VerKey: string;
FixedFileInfo: PVSFixedFileInfo;
// dwFileType, dwFileSubtype
function GetFileSubType(FixedFileInfo: PVSFixedFileInfo) : string;
begin
case FixedFileInfo.dwFileType of
VFT_UNKNOWN: Result := 'Unknown';
VFT_APP: Result := 'Application';
VFT_DLL: Result := 'DLL';
VFT_STATIC_LIB: Result := 'Static-link Library';
VFT_DRV:
case
FixedFileInfo.dwFileSubtype of
VFT2_UNKNOWN: Result := 'Unknown Driver';
VFT2_DRV_COMM: Result := 'Communications Driver';
VFT2_DRV_PRINTER: Result := 'Printer Driver';
VFT2_DRV_KEYBOARD: Result := 'Keyboard Driver';
VFT2_DRV_LANGUAGE: Result := 'Language Driver';
VFT2_DRV_DISPLAY: Result := 'Display Driver';
VFT2_DRV_MOUSE: Result := 'Mouse Driver';
VFT2_DRV_NETWORK: Result := 'Network Driver';
VFT2_DRV_SYSTEM: Result := 'System Driver';
VFT2_DRV_INSTALLABLE: Result := 'InstallableDriver';
VFT2_DRV_SOUND: Result := 'Sound Driver';
end;
VFT_FONT:
case FixedFileInfo.dwFileSubtype of
VFT2_UNKNOWN: Result := 'Unknown Font';
VFT2_FONT_RASTER: Result := 'Raster Font';
VFT2_FONT_VECTOR: Result := 'Vector Font';
VFT2_FONT_TRUETYPE: Result :='Truetype Font';
else;
end;
VFT_VXD: Result :='Virtual Defice Identifier = ' +
IntToHex(FixedFileInfo.dwFileSubtype, 8);
end;
end;
function HasdwFileFlags(FixedFileInfo: PVSFixedFileInfo;
Flag : Word) : Boolean;
begin
Result := (FixedFileInfo.dwFileFlagsMask and
FixedFileInfo.dwFileFlags and
Flag) = Flag;
end;
function GetFixedFileInfo: PVSFixedFileInfo;
begin
if not VerQueryValue(VerBuf, '', Pointer(Result), VerBufLen) then
Result := nil
end;
function GetInfo(const aKey: string): string;
begin
Result := '';
VerKey := Format('\StringFileInfo\%.4x%.4x\%s',
[LoWord(Integer(VerBufValue^)),
HiWord(Integer(VerBufValue^)), aKey]);
if VerQueryValue(VerBuf, PChar(VerKey),VerBufValue,VerBufLen) then
Result := StrPas(VerBufValue);
end;
function QueryValue(const aValue: string): string;
begin
Result := '';
// obtain version information about the specified file
if GetFileVersionInfo(PChar(sAppNamePath), VerHandle,
VerSize, VerBuf) and
// return selected version information
VerQueryValue(VerBuf, '\VarFileInfo\Translation',
VerBufValue, VerBufLen) then
Result := GetInfo(aValue);
end;
begin
// Initialize the Result
with Result do
begin
FileType := '';
CompanyName := '';
FileDescription := '';
FileVersion := '';
InternalName := '';
LegalCopyRight := '';
LegalTradeMarks := '';
OriginalFileName := '';
ProductName := '';
ProductVersion := '';
Comments := '';
SpecialBuildStr:= '';
PrivateBuildStr := '';
FileFunction := '';
DebugBuild := False;
Patched := False;
PreRelease:= False;
SpecialBuild:= False;
PrivateBuild:= False;
InfoInferred := False;
end;
// Get the file type
if SHGetFileInfo(PChar(sAppNamePath), 0, rSHFI, SizeOf(rSHFI),
SHGFI_TYPENAME) <> 0 then
begin
Result.FileType := rSHFI.szTypeName;
end;
iRet := SHGetFileInfo(PChar(sAppNamePath), 0, rSHFI,
SizeOf(rSHFI), SHGFI_EXETYPE);
if iRet <> 0 then
begin
// determine whether the OS can obtain version information
VerSize := GetFileVersionInfoSize(PChar(sAppNamePath), VerHandle);
if VerSize > 0 then
begin
VerBuf := AllocMem(VerSize);
try
with Result do
begin
CompanyName := QueryValue('CompanyName');
FileDescription := QueryValue('FileDescription');
FileVersion := QueryValue('FileVersion');
InternalName := QueryValue('InternalName');
LegalCopyRight := QueryValue('LegalCopyRight');
LegalTradeMarks := QueryValue('LegalTradeMarks');
OriginalFileName := QueryValue('OriginalFileName');
ProductName := QueryValue('ProductName');
ProductVersion := QueryValue('ProductVersion');
Comments := QueryValue('Comments');
SpecialBuildStr := QueryValue('SpecialBuild');
PrivateBuildStr := QueryValue('PrivateBuild');
// Fill the VS_FIXEDFILEINFO structure
FixedFileInfo := GetFixedFileInfo;
DebugBuild := HasdwFileFlags(FixedFileInfo,VS_FF_DEBUG);
PreRelease := HasdwFileFlags(FixedFileInfo,VS_FF_PRERELEASE);
PrivateBuild := HasdwFileFlags(FixedFileInfo,VS_FF_PRIVATEBUILD);
SpecialBuild := HasdwFileFlags(FixedFileInfo,VS_FF_SPECIALBUILD);
Patched := HasdwFileFlags(FixedFileInfo,VS_FF_PATCHED);
InfoInferred := HasdwFileFlags(FixedFileInfo,VS_FF_INFOINFERRED);
FileFunction := GetFileSubType(FixedFileInfo);
end;
finally
FreeMem(VerBuf, VerSize);
end
end;
end
end;
// Test it:
function GetFileVersionString(const sAppNamePath: TFileName): String;
var
FvI: TFileVersionInfo;
const
Tabulator: array[0..0] of Integer = (70);
BoolValues: array[Boolean] of string = ('No', 'Yes');
begin
FvI := FileVersionInfo(sAppNamePath);
Result := '';
with FvI do
begin
Result := Result + 'FileType:'#9 + FileType + #13#10;
Result := Result + 'CompanyName:'#9 + CompanyName + #13#10;
Result := Result + 'CompanyName:'#9 + FileDescription + #13#10;
Result := Result + 'FileVersion:'#9 + FileVersion + #13#10;
Result := Result + 'InternalName:'#9 + InternalName + #13#10;
Result := Result + 'LegalCopyRight:'#9 + LegalCopyRight + #13#10;
Result := Result + 'LegalTradeMarks:'#9 + LegalTradeMarks + #13#10;
Result := Result + 'OriginalFileName:'#9 + OriginalFileName + #13#10;
Result := Result + 'ProductName:'#9 + ProductName + #13#10;
Result := Result + 'ProductVersion:'#9 + ProductVersion + #13#10;
Result := Result + 'SpecialBuildStr:'#9 + SpecialBuildStr + #13#10;
Result := Result + 'PrivateBuildStr:'#9 + PrivateBuildStr + #13#10;
Result := Result + 'FileFunction:'#9 + FileFunction + #13#10;
Result := Result + 'DebugBuild:'#9 + BoolValues[DebugBuild] + #13#10;
Result := Result + 'PreRelease:'#9 + BoolValues[PreRelease] + #13#10;
Result := Result + 'PrivateBuild:'#9 + BoolValues[PrivateBuild] + #13#10;
Result := Result + 'SpecialBuild:'#9 + BoolValues[SpecialBuild] + #13#10;
end;
end;
function GetFileVersionString2(const sAppNamePath: TFileName): String;
var
FvI: TFileVersionInfo;
begin
FvI := FileVersionInfo(sAppNamePath);
Result := FvI.FileVersion;
end;
end.
|
unit UMain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IBConnection, sqldb, DB, FileUtil, Forms, Controls,
Graphics, Dialogs, DBCtrls, DBGrids, StdCtrls, Menus,UShowInformation,
UDBConnection,UMetadata,UBuildQuery,UEditTable;
type
{ TMainForm }
TMainForm = class(TForm)
Tables: TMenuItem;
MainMenu: TMainMenu;
AboutMeItem: TMenuItem;
FileItem: TMenuItem;
ExitItem: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure AboutMeItemClick(Sender: TObject);
procedure ExitItemClick(Sender: TObject);
procedure OnTableItemClick(Sender: TObject);
procedure AddTableItem(ItemName: string; ParentItem: TMenuItem;
ComponentName: string);
private
ItemIndex: integer;
public
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
procedure TMainForm.FormCreate(Sender: TObject);
begin
DataBase.Connect();
ItemIndex := 0;
AddTableItem('Расписание', Tables, 'Timetable');
AddTableItem('Преподаватели', Tables, 'Teachers');
AddTableItem('Предметы', Tables, 'Lessons');
AddTableItem('Студенты', Tables, 'Students');
AddTableItem('Группы', Tables, 'Groups');
AddTableItem('Дни недели', Tables, 'Weekdays');
AddTableItem('Типы Занятий', Tables, 'Lessons_Types');
AddTableItem('Время Занятий', Tables, 'Lessons_Times');
AddTableItem('Аудитории', Tables, 'Classrooms');
end;
procedure TMainForm.AddTableItem(ItemName: string; ParentItem: TMenuItem;
ComponentName: string);
var
TableItem: TMenuItem;
begin
TableItem := TMenuItem.Create(ParentItem);
TableItem.Name := ComponentName;
TableItem.Caption := ItemName;
TableItem.OnClick := @OnTableItemClick;
ParentItem.Insert(ItemIndex, TableItem);
Inc(ItemIndex);
end;
procedure TMainForm.OnTableItemClick(Sender: TObject);
begin
SetLength(InformationForms, Length(InformationForms) + 1);
InformationForms[High(InformationForms)] := TInformationForm.Create(Self, Sender as TMenuItem);
InformationForms[High(InformationForms)].Show;
end;
procedure TMainForm.AboutMeItemClick(Sender: TObject);
begin
ShowMessage('Гурьев Андрей Б8103а1');
end;
procedure TMainForm.ExitItemClick(Sender: TObject);
begin
Close;
end;
end.
|
unit uAutoUpdate;
// ****************** Автоматическое обновление **********************
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Buttons, ComCtrls, zAutoUpdate, FileLoader,
Mask, ToolEdit, INIFiles, zAVZDriverRK, zAVKernel, zAVZVersion, ZLogSystem;
type
TAutoUpdate = class(TForm)
lbStep1: TLabel;
lbStep2: TLabel;
lbStep3: TLabel;
lbStep4: TLabel;
lbCurrentFile: TLabel;
Label1: TLabel;
pbCurrentOp: TProgressBar;
pbFullProgress: TProgressBar;
Timer1: TTimer;
Label2: TLabel;
cbSourceURL: TComboBox;
Panel1: TPanel;
mbStart: TBitBtn;
mbExit: TBitBtn;
Label3: TLabel;
ceSetup: TComboEdit;
lbAnalizResult: TLabel;
procedure mbStartClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ceSetupButtonClick(Sender: TObject);
private
// Настойка текущего шага - отображается визуально на окне
procedure SetCurrentStep(const Value: integer);
procedure OnStep(AStep : integer);
procedure OnFileOperation(AFileName : string; ATek, AMax : integer);
procedure OnAnalizComplete(DownloadSize : integer);
public
FCurrentStep : integer;
Mode : byte; // Код режима (0...4, см. расшифровку в GetSetupDescr)
Proxy, ProxyUser, ProxyPass : string; // Парамеры связи с прокси
// Загрузка настроек
Function LoadSetup : boolean;
// Выполнение диалога
Function Execute : boolean;
// Обновление строки с описанием источника обновления
Function RefreshSetupStr : boolean;
// Выполнение обновления (NoGUI - перекл. невизуального режима)
Function ExecuteUpdate(NoGUI : boolean; ServerPath : string; ConnectMode : byte; ProxyServer, ProxyUser, ProxyPass : string) : boolean;
end;
var
AutoUpdate: TAutoUpdate;
// Вызов в диалоговом режиме
function ExecuteAutoUpdate : boolean;
// Вызов в автоматическом режиме
function ExecuteAutoUpdateNoGUI(ASrcCode : integer; ServerPath : string; ConnectMode : byte; ProxyServer, ProxyUser, ProxyPass : string) : boolean;
// Запрос описания настроек в текстовом виде человекочитаемом (для отображения на окне и логе)
function GetSetupDescr(ConnectMode : byte; ProxyServer, ProxyUser, ProxyPass : string) : string;
implementation
uses zutil, uAutoUpdateSetup, zTranslate;
{$R *.dfm}
function GetSetupDescr(ConnectMode : byte; ProxyServer, ProxyUser, ProxyPass : string) : string;
begin
Result := '$AVZ0512';
case ConnectMode of
0 : Result := '$AVZ0319';
1 : Result := '$AVZ0880';
2 : Result := '$AVZ1140' + ' "' + ProxyServer +'"';
3 : Result := '$AVZ1142' + ' "' + ProxyServer +', '+'$AVZ0781'+'="' + ProxyUser + '"';
4 : Result := '$AVZ1141' + ' "' + ProxyServer +', '+'$AVZ0781'+'="' + ProxyUser + '"';
end;
Result := TranslateStr(Result);
end;
function ExecuteAutoUpdateNoGUI(ASrcCode : integer; ServerPath : string; ConnectMode : byte; ProxyServer, ProxyUser, ProxyPass : string) : boolean;
begin
try
AutoUpdate := nil;
AutoUpdate := TAutoUpdate.Create(nil);
Result := AutoUpdate.ExecuteUpdate(true, ServerPath, ConnectMode, ProxyServer, ProxyUser, ProxyPass);
finally
AutoUpdate.Free;
AutoUpdate := nil;
end;
end;
function ExecuteAutoUpdate : boolean;
begin
try
AutoUpdate := nil;
AutoUpdate := TAutoUpdate.Create(nil);
Result := AutoUpdate.Execute;
finally
AutoUpdate.Free;
AutoUpdate := nil;
end;
end;
procedure TAutoUpdate.SetCurrentStep(const Value: integer);
var
i : integer;
begin
FCurrentStep := Value;
pbFullProgress.Position := Value;
Application.ProcessMessages;
for i := 1 to ComponentCount-1 do
if (Components[i] is TLabel) then
if (Components[i] as TLabel).Tag > 0 then
if (Components[i] as TLabel).Tag = FCurrentStep then
(Components[i] as TLabel).Font.Style := [fsBold]
else (Components[i] as TLabel).Font.Style := [];
Application.ProcessMessages;
Application.ProcessMessages;
Application.ProcessMessages;
Application.ProcessMessages;
end;
function TAutoUpdate.Execute: boolean;
begin
lbAnalizResult.Caption := '';
LoadSetup;
RefreshSetupStr;
ShowModal;
Result := ModalResult = mrOk;
end;
procedure TAutoUpdate.mbStartClick(Sender: TObject);
begin
try
mbStart.Enabled := false;
mbExit.Enabled := false;
if ExecuteUpdate(false, '', Mode, Proxy, ProxyUser, ProxyPass) then ModalResult := mrOk;
finally
mbStart.Enabled := true;
mbExit.Enabled := true;
end;
end;
procedure TAutoUpdate.OnStep(AStep: integer);
begin
SetCurrentStep(AStep);
end;
procedure TAutoUpdate.OnFileOperation(AFileName: string; ATek,
AMax: integer);
begin
lbCurrentFile.Caption := AFileName;
pbCurrentOp.Max := AMax;
pbCurrentOp.Position := ATek;
Application.ProcessMessages;
end;
procedure TAutoUpdate.FormCreate(Sender: TObject);
begin
Randomize;
cbSourceURL.ItemIndex := 0;
if cbSourceURL.Items.Count > 1 then
if random(20) > 17 then
cbSourceURL.ItemIndex := 1;
Mode := 0;
Proxy := '';
ProxyUser := '';
ProxyPass := '';
TranslateForm(Self);
end;
function TAutoUpdate.ExecuteUpdate(NoGUI : boolean; ServerPath : string; ConnectMode : byte; ProxyServer, ProxyUser, ProxyPass : string): boolean;
var
AVAAutoUpdater : TAVZAutoUpdater;
S : string;
begin
lbAnalizResult.Caption := '';
Result := false;
ServerPath := trim(ServerPath);
AVAAutoUpdater := TAVZAutoUpdater.Create;
AVAAutoUpdater.ServerPath := cbSourceURL.Text;
// Путь к серверу (URL)
if ServerPath <> '' then
AVAAutoUpdater.ServerPath := ServerPath;
// Режим работы
case ConnectMode of
0 : AVAAutoUpdater.HTTPDownloadMode := hdmIESettings;
1 : AVAAutoUpdater.HTTPDownloadMode := hdmDirectConnection;
2 : begin
AVAAutoUpdater.HTTPDownloadMode := hdmProxy;
AVAAutoUpdater.ProxyServer := ProxyServer;
end;
3 : begin
AVAAutoUpdater.HTTPDownloadMode := hdmProxyAuth;
AVAAutoUpdater.ProxyServer := ProxyServer;
AVAAutoUpdater.ProxyUser := ProxyUser;
AVAAutoUpdater.ProxyPass := ProxyPass;
end;
4 : begin
AVAAutoUpdater.HTTPDownloadMode := hdmProxyAuthNTLM;
AVAAutoUpdater.ProxyServer := ProxyServer;
AVAAutoUpdater.ProxyUser := ProxyUser;
AVAAutoUpdater.ProxyPass := ProxyPass;
end;
else exit;
end;
AVAAutoUpdater.TempPath := AVZTempDirectoryPath+'AVZ\';
AVAAutoUpdater.DestPath := ExtractFilePath(Application.ExeName);
AVAAutoUpdater.OnStep := OnStep;
AVAAutoUpdater.OnFileOperation := OnFileOperation;
AVAAutoUpdater.OnAnalizComplete := OnAnalizComplete;
AVAAutoUpdater.LocalVer := StrToFloatDef(VER_NUM, 0);
// Выполнение обновления
Result := AVAAutoUpdater.Execute;
// Вывод сообщения
if not(NoGUI) then
if Result then begin
if AVAAutoUpdater.ResStatus = 1 then S := '$AVZ0552'
else S := '$AVZ0553';
if AVAAutoUpdater.CurrentVer > AVAAutoUpdater.LocalVer then
S := S + ' '#$0D#$0A + '$AVZ0168 '+FloatToStr(AVAAutoUpdater.CurrentVer);
zMessageDlg('$AVZ0049. '+S, mtInformation, [mbOk], 0)
end else zMessageDlg('$AVZ0644 '+AVAAutoUpdater.LastError, mtError, [mbOk], 0);
// Обновление драйвера PM (при условии, что он загружен)
if Result and AVZDriverRK.Loaded and (AVAAutoUpdater.ResStatus <> 1) then begin
// Перезагрузка базы
KMBase.LoadBinDatabase;
// Реинсталляция драйвера
AVZDriverRK.InstallDriver;
end;
pbCurrentOp.Position := 0;
pbFullProgress.Position := 0;
lbCurrentFile.Caption := '';
SetCurrentStep(-1);
AVAAutoUpdater.Free;
end;
procedure TAutoUpdate.ceSetupButtonClick(Sender: TObject);
begin
if ExecuteAutoUpdateSetup(Mode, Proxy, ProxyUser, ProxyPass) then
RefreshSetupStr;
end;
function TAutoUpdate.RefreshSetupStr: boolean;
begin
ceSetup.Text := GetSetupDescr(Mode, Proxy, ProxyUser, ProxyPass);
end;
procedure TAutoUpdate.OnAnalizComplete(DownloadSize: integer);
begin
lbAnalizResult.Caption := TranslateStr('$AVZ1069 ') + FormatFloat('0.0',DownloadSize/1024)+TranslateStr(' $AVZ1191)');
lbAnalizResult.Refresh;
lbAnalizResult.Repaint;
Application.ProcessMessages;
end;
function TAutoUpdate.LoadSetup: boolean;
var
INI : TIniFile;
begin
Result := false;
INI := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
Mode := Byte(INI.ReadInteger('Update', 'Mode', 0));
if Mode > 4 then Mode := 0;
Proxy := INI.ReadString('Update', 'Proxy', '');
ProxyUser := INI.ReadString('Update', 'ProxyUser', '');
ProxyPass := DeCryptPwd(INI.ReadString('Update', 'ProxyPass', ''));
INI.Free;
Result := true;
end;
end.
|
unit IdTestHTTP;
interface
uses
IdSys,
IdContext,
IdTCPServer,
IdTest,
IdHTTP;
type
//this test shows a memory leak due to AResponse.KeepAlive being called in a
//finally block, and raising an exception.
//seperate test class as it has private callbacks for the server
//the actual result of this test (a memory leak) will only properly be detected
//on application shutdown, when running an appropriate memory checker
TIdTestHTTP_01 = class(TIdTest)
private
procedure CallbackExecute(AContext:TIdContext);
published
procedure TestMemoryLeak;
end;
implementation
procedure TIdTestHTTP_01.CallbackExecute(AContext: TIdContext);
begin
AContext.Connection.Disconnect;
end;
procedure TIdTestHTTP_01.TestMemoryLeak;
var
aClient:TIdHTTP;
aServer:TIdTCPServer;
begin
aClient:=TIdHTTP.Create(nil);
aServer:=TIdTCPServer.Create(nil);
try
aServer.DefaultPort:=20202;
aServer.OnExecute:=Self.CallbackExecute;
aServer.Active:=True;
//the circumstances for the memory leak also require a ConnectionTimeout
//haven't investigated why
aClient.ConnectTimeout:=2000;
try
aClient.Get('http://127.0.0.1:20202');
except
//we're expecting this exception, ignore it
end;
finally
Sys.FreeAndNil(aClient);
Sys.FreeAndNil(aServer);
end;
end;
initialization
TIdTest.RegisterTest(TIdTestHTTP_01);
end.
|
unit CardFormViewModelMapper;
interface
uses
ReferenceFormRecordViewModel,
CardFormViewModel;
type
ICardFormViewModelMapper = interface
function CreateEmptyCardFormViewModel: TCardFormViewModel;
function MapCardFormViewModelFrom(
ReferenceFormRecordViewModel: TReferenceFormRecordViewModel
): TCardFormViewModel;
procedure FillCardFormViewModelFrom(
CardFormViewModel: TCardFormViewModel;
ReferenceFormRecordViewModel: TReferenceFormRecordViewModel
);
end;
implementation
end.
|
unit UShopVisual;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Grids, ComCtrls, UShop, USimulation;
type
TfrShopVisual = class(TForm)
Label6: TLabel;
lbSimTime: TLabel;
Label7: TLabel;
edSimulationTime: TEdit;
btStart: TButton;
tmShop: TTimer;
pgStat: TPageControl;
tsStat: TTabSheet;
sgCash: TStringGrid;
sgTime: TStringGrid;
sgShopping: TStringGrid;
sgQueue: TStringGrid;
tsGraph: TTabSheet;
imAnimation: TImage;
tsModel: TTabSheet;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
lbShopping: TLabel;
lbQueue: TLabel;
lbCash: TLabel;
lbServiced: TLabel;
lbTimeInSystem: TLabel;
procedure btStartClick(Sender: TObject);
procedure tmShopTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure ShowAnimation;
procedure DrawCustomer(cust : TCustomer);
procedure ClearCustomer(cust : TCustomer);
procedure DrawCash;
public
{ Public declarations }
end;
var
frShopVisual: TfrShopVisual;
implementation
{$R *.dfm}
var
shp : TShop = nil;
que : array [0 .. 1] of TList;
procedure TfrShopVisual.btStartClick(Sender: TObject);
begin
if tmShop.Enabled then
begin
tmShop.Enabled := False;
end
else
begin
shp.Free;
MinX := 0;
MinY := 0;
MaxX := imAnimation.Width - SpriteX;
MaxY := imAnimation.Height;
StartX := MinX;
StartY := rndCust.NextInt(MinY, imAnimation.Height - SpriteY);
CashX := imAnimation.Width - SpriteX;
CashY := rndCust.NextInt(MinY, imAnimation.Height - SpriteY);
SimulationTime := StrToFloat(edSimulationTime.Text);
shp := TShop.Create;
que[0] := shp.Queue;
que[1] := shp.Calendar;
tmShop.Enabled := True;
with imAnimation.Canvas do
begin
Brush.Color := clWhite;
Pen.Style := psClear;
Rectangle(0, 0, Width, Height);
Pen.Style := psSolid;
Brush.Color := Color;
end;
end;
end;
procedure TfrShopVisual.tmShopTimer(Sender: TObject);
begin
shp.StopStat;
lbSimTime.Caption := TimeToStr(shp.SimTime / 1440 + 1 / 3);
lbTimeInSystem.Caption := Format('%.3f', [shp.TimeStat.Mean]);
lbShopping.Caption := Chars(shp.PeopleStat.Running, '*');
lbQueue.Caption := Chars(shp.Queue.Size, '*');
ShowStat(sgQueue, ['Очередь', 'Календарь'], que);
ShowStat(sgShopping, ['Торговый зал'], shp.PeopleStat);
ShowStat(sgTime, ['Время в системе'], shp.TimeStat);
ShowStat(sgCash, ['Касса'], shp.CashStat);
ShowAnimation;
if shp.CashStat.Running > 0 then
lbCash.Caption := '(*)'
else
lbCash.Caption := '';
lbServiced.Caption := IntToStr(shp.TimeStat.Count);
if shp.Terminated then
begin
tmShop.Enabled := False;
end
else
begin
RunSimulation(shp);
end;
end;
procedure TfrShopVisual.FormCreate(Sender: TObject);
begin
rndCust := TRandom.Create;
rndService := TRandom.Create;
sgQueue.ColWidths[0] := 90;
sgQueue.ColWidths[1] := 70;
sgQueue.ColWidths[2] := 100;
sgQueue.ColWidths[3] := 80;
sgQueue.ColWidths[4] := 60;
sgQueue.ColWidths[5] := 80;
sgCash.ColWidths[0] := 90;
sgCash.ColWidths[1] := 95;
sgCash.ColWidths[2] := 70;
sgCash.ColWidths[3] := 100;
sgCash.ColWidths[4] := 60;
sgCash.ColWidths[5] := 145;
sgCash.ColWidths[6] := 115;
sgCash.ColWidths[7] := 105;
sgCash.ColWidths[8] := 90;
sgTime.ColWidths[0] := 130;
sgTime.ColWidths[1] := 70;
sgTime.ColWidths[2] := 100;
sgTime.ColWidths[3] := 75;
sgTime.ColWidths[4] := 80;
sgTime.ColWidths[5] := 95;
sgShopping.ColWidths[0] := 110;
sgShopping.ColWidths[1] := 70;
sgShopping.ColWidths[2] := 100;
sgShopping.ColWidths[3] := 80;
sgShopping.ColWidths[4] := 60;
sgShopping.ColWidths[5] := 90;
MinX := 0;
MinY := 0;
MaxX := imAnimation.Width - SpriteX;
MaxY := imAnimation.Height;
StartX := MinX;
StartY := rndCust.NextInt(MinY, imAnimation.Height - SpriteY);
CashX := imAnimation.Width - SpriteX;
CashY := rndCust.NextInt(MinY, imAnimation.Height - SpriteY);
end;
procedure TfrShopVisual.ClearCustomer(cust: TCustomer);
begin
with imAnimation.Canvas do
begin
Pen.Style := psClear;
Brush.Color := clWhite;
Rectangle(Round(cust.X), Round(cust.Y), Round(cust.X + SpriteX) + 1,
Round(cust.Y + SpriteY) + 1);
Brush.Color := Color;
Pen.Style := psSolid;
end;
end;
procedure TfrShopVisual.DrawCustomer(cust: TCustomer);
begin
with imAnimation.Canvas do
begin
Brush.Color := cust.Color;
Rectangle(Round(cust.X), Round(cust.Y), Round(cust.X + SpriteX),
Round(cust.Y + SpriteY));
Brush.Color := cust.BuysColor;
Pen.Color := not (cust.Color xor cust.BuysColor) and $00FFFFFF;
Pen.Width := 2;
Rectangle(Round(cust.X + BuysLeft), Round(cust.Y + BuysBottom -
cust.CurrentBuys * BuysMaxHeight / MaxBuysCount),
Round(cust.X + BuysRight), Round(cust.Y + BuysBottom));
Pen.Color := clBlack;
Pen.Width := 1;
Brush.Color := Color;
end;
end;
procedure TfrShopVisual.ShowAnimation;
var
cust : TCustomer;
TargetX, TargetY : Integer;
dx, dy : Double;
begin
cust := shp.InShop.First as TCustomer;
while cust <> nil do
begin
ClearCustomer(cust);
cust := cust.Next as TCustomer;
end;
cust := shp.Queue.First as TCustomer;
while cust <> nil do
begin
ClearCustomer(cust);
cust := cust.Next as TCustomer;
end;
if shp.CashCustomer <> nil then
ClearCustomer(shp.CashCustomer);
TargetX := CashX - (shp.Queue.Size + 1) * SpriteStep;
TargetY := CashY;
cust := shp.InShop.First as TCustomer;
while cust <> nil do
begin
dx := (TargetX - cust.X) * VisTimeStep / (cust.EventTime - shp.SimTime);
dy := (TargetY - cust.Y) * VisTimeStep / (cust.EventTime - shp.SimTime);
dx := rndCust.Normal(dx, DeviationX + Abs(dx));
dy := rndCust.Normal(dy, DeviationY + Abs(dy));
dx := Max(cust.dx - MaxDDX, Min(cust.dx + MaxDDX, (cust.dx * 3 + dx) / 4));
dy := Max(cust.dy - MaxDDY, Min(cust.dy + MaxDDY, (cust.dy * 3 + dy) / 4));
cust.X := Max(MinX, Min(MaxX - SpriteX, cust.X + dx));
cust.Y := Max(MinY, Min(MaxY - SpriteY, cust.Y + dy));
cust.dx := dx;
cust.dy := dy;
cust.CurrentBuys := cust.BuysCount * (shp.SimTime - cust.StartingTime) /
(cust.EventTime - cust.StartingTime);
DrawCustomer(cust);
cust := cust.Next as TCustomer;
end;
TargetX := CashX - SpriteStep;
cust := shp.Queue.First as TCustomer;
while cust <> nil do
begin
cust.X := TargetX;
cust.Y := TargetY;
TargetX := TargetX - SpriteStep;
DrawCustomer(cust);
cust := cust.Next as TCustomer;
end;
DrawCash;
if shp.CashCustomer <> nil then
begin
shp.CashCustomer.X := CashX;
shp.CashCustomer.Y := CashY;
shp.CashCustomer.CurrentBuys := shp.CashCustomer.BuysCount *
(shp.Cash.EventTime - shp.SimTime) / (shp.Cash.EventTime - shp.CashStart);
DrawCustomer(shp.CashCustomer);
end;
end;
procedure TfrShopVisual.DrawCash;
begin
with imAnimation.Canvas do
begin
Brush.Color := clFuchsia;
Rectangle(CashX - 2, CashY - 2, CashX + SpriteX + 2, CashY + SpriteY + 2);
Brush.Color := Color;
end;
end;
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit Server.Context;
interface
uses
System.SysUtils, System.Classes, System.Rtti,
WiRL.Rtti.Utils,
WiRL.Core.Context,
WiRL.Core.Injection;
type
// Class to be injected
TMyClass = class
private
FValue: Integer;
FInfo: string;
public
property Value: Integer read FValue write FValue;
property Info: string read FInfo write FInfo;
end;
// Attribute to check inside the factory
ValueAttribute = class(TCustomAttribute)
private
FValue: Integer;
public
property Value: Integer read FValue;
constructor Create(AValue: Integer);
end;
// The class factory is responsable to create the context.
// It will be released by the system unless it's annotated
// with the Singleton attribute
TMyClassFactory = class(TInterfacedObject, IContextFactory)
public
function CreateContext(const AObject: TRttiObject;
AContext: TWiRLContext): TValue;
end;
implementation
{ TMyClassFactory }
function TMyClassFactory.CreateContext(const AObject: TRttiObject;
AContext: TWiRLContext): TValue;
var
LInstance: TMyClass;
begin
LInstance := TMyClass.Create;
LInstance.Value := 0;
LInstance.Info := AContext.Request.PathInfo;
TRttiHelper.HasAttribute<ValueAttribute>(AObject,
procedure (LAttr: ValueAttribute)
begin
LInstance.Value := LAttr.Value;
end
);
Result := LInstance;
end;
{ ValueAttribute }
constructor ValueAttribute.Create(AValue: Integer);
begin
inherited Create;
FValue := AValue;
end;
initialization
TWiRLContextInjectionRegistry.Instance.RegisterFactory<TMyClass>(TMyClassFactory);
end.
|
unit SLTaskList;
interface
uses
Classes;
function LoadSLTaskList(IniFile: string): TList;
procedure SaveSLTaskList(list: TList; inifile: string);
procedure FreeSLTaskList(list: TList);
implementation
uses
SysUtils, SyncObjs, EncdDecd, IniFiles, SLTask, IsmvSettings,
HttpDownload, HttpMessage;
const
SID = 'ID';
SPageUrl = 'PageUrl';
SXmlUrl = 'XmlUrl';
SXmlFile = 'XmlFile';
SVideoIndex = 'VideoIndex';
SAudioIndex = 'AudioIndex';
SMovieFile = 'MovieFile';
STotalSize = 'TotalSize';
SCurrentSize = 'CurrentSize';
SVideoPartCount = 'VideoPartCount';
SAudioPartCount = 'AudioPartCount';
SNextVideoIndex = 'NextVideoIndex';
SNextAudioIndex = 'NextAudioIndex';
SExistVideos = 'ExistVideos';
SExistAudios = 'ExistAudios';
SVideoOffsets = 'VideoOffsets';
SAudioOffsets = 'AudioOffsets';
SHttpRequestMessage = 'HttpRequestMessage';
COffsetsSeq = ',';
function BoolArrToStr(arr: Booleans): string;
var
p: array of Char;
i: Integer;
len: Integer;
begin
len := Length(arr);
SetLength(p, len + 1);
for i := 0 to len - 1 do
begin
if arr[i] then
p[i] := '1'
else
p[i] := '0';
end;
Result := string(p);
SetLength(p, 0);
end;
procedure StrToBoolArr(str: string; out result: Booleans);
var
Len: Integer;
i: Integer;
begin
len := Length(str);
SetLength(Result, Len);
for i := 1 to len do
begin
if str[i] = '1' then
Result[i - 1] := True
else
Result[i - 1] := False;
end;
end;
procedure Split(str: string; sep: Char; out result: TStringList);
var
i: Integer;
begin
with TStringList.Create do
begin
Delimiter := sep;
DelimitedText := str;
for i := 0 to Count - 1 do
begin
result.Add(Strings[i]);
end;
end;
end;
function Joint(strs: TStringList; joint: Char): string;
begin
strs.Delimiter := joint;
result := strs.DelimitedText;
end;
function LoadSLTaskList(IniFile: string): TList;
var
ini: TIniFile;
sections, sectionValues: TStringList;
section: string;
i: Integer;
PTask: PSLTask;
MsgStr: string;
begin
Result := TList.Create;
if not FileExists(IniFile) then Exit;
ini := TIniFile.Create(IniFile);
sections := TStringList.Create;
try
ini.ReadSections(sections);
for i := 0 to sections.Count - 1 do
begin
section := sections[i]; // ID
sectionValues := TStringList.Create;
try
ini.ReadSectionValues(section, sectionValues);
New(PTask);
try
with PTask^ do
begin
TaskState := tsStopped;
ID := section;
PageUrl := sectionValues.Values[SPageUrl];
XmlUrl := sectionValues.Values[SXmlUrl];
XmlFile := sectionValues.Values[SXmlFile];
MovieFile := sectionValues.Values[SMovieFile];
VideoIndex := StrToInt(sectionValues.Values[SVideoIndex]);
AudioIndex := StrToInt(sectionValues.Values[SAudioIndex]);
LoadIsmvSettings(@MovieSettings, XmlFile, VideoIndex, AudioIndex);
TotalSize := StrToInt64(sectionValues.Values[STotalSize]);
CurrentSize := StrToInt64(sectionValues.Values[SCurrentSize]);
Speed := 0;
VideoPartCount := StrToInt(sectionValues.Values[SVideoPartCount]);
AudioPartCount := StrToInt(sectionValues.Values[SAudioPartCount]);
NextVideoIndex := StrToInt(sectionValues.Values[SNextVideoIndex]);
NextAudioIndex := StrToInt(sectionValues.Values[SNextAudioIndex]);
SetLength(ExistVideos, VideoPartCount);
SetLength(ExistAudios, AudioPartCount);
VideoOffsets := TStringList.Create;
AudioOffsets := TStringList.Create;
Split(sectionValues.Values[SVideoOffsets], COffsetsSeq, VideoOffsets);
Split(sectionValues.Values[SAudioOffsets], COffsetsSeq, AudioOffsets);
if sectionValues.IndexOf(SHttpRequestMessage) >= 0 then
begin
MsgStr := DecodeString(sectionValues.Values[SHttpRequestMessage]);
HttpRequestMsg := THttpMessage.Create(MsgStr);
end;
DownloadList := nil;
MovieFileStream := nil;
MergeLock := TCriticalSection.Create;
HttpRequestMsg := nil;
end;
except
Dispose(PTask);
Continue;
end;
Result.Add(PTask);
finally
sectionValues.Free;
end;
end;
finally
sections.Free;
ini.Free;
end;
end;
procedure SaveSLTaskList(list: TList; inifile: string);
var
ini: TIniFile;
i: Integer;
begin
with TStringList.Create do
SaveToFile(inifile);
ini := TIniFile.Create(inifile);
try
for i := 0 to list.Count - 1 do
begin
with PSLTask(list[i])^ do
begin
ini.WriteString(ID, SPageUrl, PageUrl);
ini.WriteString(ID, SXmlUrl, XmlUrl);
ini.WriteString(ID, SXmlFile, XmlFile);
ini.WriteString(ID, SMovieFile, MovieFile);
ini.WriteInteger(ID, SVideoIndex, VideoIndex);
ini.WriteInteger(ID, SAudioIndex, AudioIndex);
ini.WriteInteger(ID, STotalSize, TotalSize);
ini.WriteInteger(ID, SCurrentSize, CurrentSize);
ini.WriteInteger(ID, SVideoPartCount, VideoPartCount);
ini.WriteInteger(ID, SAudioPartCount, AudioPartCount);
ini.WriteInteger(ID, SNextVideoIndex, NextVideoIndex);
ini.WriteInteger(ID, SNextAudioIndex, NextAudioIndex);
ini.WriteString(ID, SVideoOffsets, Joint(VideoOffsets, COffsetsSeq));
ini.WriteString(ID, SAudioOffsets, Joint(AudioOffsets, COffsetsSeq));
if Assigned(HttpRequestMsg) then
begin
ini.WriteString(ID, SHttpRequestMessage, EncodeString(HttpRequestMsg.ToString));
end;
end;
end;
finally
ini.Free;
end;
end;
procedure FreeSLTaskList(list: TList);
var
i: Integer;
begin
for i := 0 to list.Count - 1 do
begin
DisposeSLTask(list[i]);
end;
list.Free;
end;
end.
|
(* Output:
not(a and b) = true
((a or b)or a) and b) = false
(a and b) and b = false
(a and b) and b = false
Condition is true
*)
program test13;
var
a, b, c: boolean;
begin
a := true;
b := false;
c := not(a and b);
writeln('not(a and b) = ', c);
c := ((a or b)or a) and b;
writeln('((a or b)or a) and b) = ' , c);
a := false;
b := true;
c := (a and b) and b;
writeln('(a and b) and b = ' , c);
c := (a and b) and b;
writeln('(a and b) and b = ' , c);
if (a or b) then
writeln('Condition is true' )
else
writeln('Condition is not true');
end.
|
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Abbrevia
*
* The Initial Developer of the Original Code is
* Craig Peterson
*
* Portions created by the Initial Developer are Copyright (C) 1997-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
unit AbBzip2TypTests;
{$I AbDefine.inc}
interface
uses
Classes, AbArcTypTests, AbArcTyp, AbUtils;
type
TAbBzip2ArchiveTests = class(TAbArchiveTests)
protected
class function ArchiveClass: TAbArchiveClass; override;
class function ArchiveExt: string; override;
class function ArchiveType: TAbArchiveType; override;
class function VerifyArchive(aStream: TStream): TAbArchiveType; override;
end;
TAbBzippedTarArchiveTests = class(TAbArchiveMultiFileTests)
protected
class function CreateArchive(const aFileName : string; aMode : Word): TAbArchive;
override;
class function CreateArchive(aStream : TStream; const aArchiveName : string): TAbArchive;
override;
class function ArchiveClass: TAbArchiveClass; override;
class function ArchiveExt: string; override;
class function ArchiveType: TAbArchiveType; override;
class function VerifyArchive(aStream: TStream): TAbArchiveType; override;
end;
implementation
uses
SysUtils, TestFrameWork, AbBzip2Typ;
{----------------------------------------------------------------------------}
{ TAbBzip2ArchiveTests }
{----------------------------------------------------------------------------}
class function TAbBzip2ArchiveTests.ArchiveClass: TAbArchiveClass;
begin
Result := TAbBzip2Archive;
end;
{ -------------------------------------------------------------------------- }
class function TAbBzip2ArchiveTests.ArchiveExt: string;
begin
Result := '.bz2';
end;
{ -------------------------------------------------------------------------- }
class function TAbBzip2ArchiveTests.ArchiveType: TAbArchiveType;
begin
Result := atBzip2;
end;
{ -------------------------------------------------------------------------- }
class function TAbBzip2ArchiveTests.VerifyArchive(aStream: TStream): TAbArchiveType;
begin
Result := VerifyBzip2(aStream);
end;
{----------------------------------------------------------------------------}
{ TAbBzippedTarArchiveTests }
{----------------------------------------------------------------------------}
class function TAbBzippedTarArchiveTests.CreateArchive(const aFileName : string;
aMode : Word): TAbArchive;
begin
Result := inherited CreateArchive(aFileName, aMode);
TAbBzip2Archive(Result).TarAutoHandle := True;
TAbBzip2Archive(Result).IsBzippedTar := True;
end;
{----------------------------------------------------------------------------}
class function TAbBzippedTarArchiveTests.CreateArchive(aStream : TStream;
const aArchiveName : string): TAbArchive;
begin
Result := inherited CreateArchive(aStream, aArchiveName);
TAbBzip2Archive(Result).TarAutoHandle := True;
TAbBzip2Archive(Result).IsBzippedTar := True;
end;
{----------------------------------------------------------------------------}
class function TAbBzippedTarArchiveTests.ArchiveClass: TAbArchiveClass;
begin
Result := TAbBzip2Archive;
end;
{----------------------------------------------------------------------------}
class function TAbBzippedTarArchiveTests.ArchiveExt: string;
begin
Result := '.tbz';
end;
{ -------------------------------------------------------------------------- }
class function TAbBzippedTarArchiveTests.ArchiveType: TAbArchiveType;
begin
Result := atBzippedTar;
end;
{ -------------------------------------------------------------------------- }
class function TAbBzippedTarArchiveTests.VerifyArchive(aStream: TStream): TAbArchiveType;
begin
Result := VerifyBzip2(aStream);
end;
{----------------------------------------------------------------------------}
initialization
TestFramework.RegisterTest('Abbrevia.Low-Level Compression Test Suite',
TAbBzip2ArchiveTests.Suite);
TestFramework.RegisterTest('Abbrevia.Low-Level Compression Test Suite',
TAbBzippedTarArchiveTests.Suite);
end.
|
{ ****************************************************************************** }
{ * AI Training task Support * }
{ * by QQ 600585@qq.com * }
{ ****************************************************************************** }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zRasterization * }
{ ****************************************************************************** }
unit zAI_TrainingTask;
{$INCLUDE zDefine.inc}
interface
uses Types,
CoreClasses,
{$IFDEF FPC}
FPCGenericStructlist,
{$ENDIF FPC}
PascalStrings, MemoryStream64, UnicodeMixedLib, DataFrameEngine, CoreCipher,
ZDBEngine, ZDBLocalManager, ObjectDataManager, ObjectData, ItemStream,
DoStatusIO, ListEngine, Geometry2DUnit, MemoryRaster, LearnTypes, Learn, zAI;
type
TTrainingTask = class(TCoreClassObject)
private
procedure On_Save_DoStatus(AText: SystemString; const ID: Integer);
public
DB_Stream: TMemoryStream64;
DB_Engine: TObjectDataManager;
LastWriteFileList: TPascalStringList;
LastReadMD5, LastWriteMD5: TMD5;
TaskLogStatus: TPascalStringList;
constructor Create;
class function OpenTask(filename: SystemString): TTrainingTask; overload;
class function OpenTask(stream: TCoreClassStream): TTrainingTask; overload;
class function CreateTask: TTrainingTask;
destructor Destroy; override;
procedure SaveToStream(stream: TCoreClassStream);
procedure SaveToFile(filename: SystemString);
procedure Write(name: SystemString; m64: TMemoryStream64); overload;
procedure Write(name: SystemString; data: THashVariantList); overload;
procedure Write(name: SystemString; data: TPascalStringList); overload;
procedure Write(name: SystemString; data: TCoreClassStrings); overload;
procedure Write(name: SystemString; data: TMemoryRaster); overload;
procedure Write(name: SystemString; data: TAI_ImageList); overload;
procedure WriteFile(name: SystemString; fromfile: SystemString); overload;
procedure Read(name: SystemString; m64: TMemoryStream64); overload;
procedure Read(name: SystemString; data: THashVariantList); overload;
procedure Read(name: SystemString; data: TPascalStringList); overload;
procedure Read(name: SystemString; data: TCoreClassStrings); overload;
procedure Read(name: SystemString; data: TMemoryRaster); overload;
procedure Read(name: SystemString; data: TAI_ImageList); overload;
procedure ReadToFile(name: SystemString; destfile: SystemString); overload;
function Exists(name: SystemString): Boolean;
function Delete(name: SystemString): Boolean;
procedure CopyTo(LocalName: SystemString; dest: TTrainingTask; destName: SystemString); overload;
// check file for training before
function CheckTrainingBefore(const paramFile: SystemString; var report: SystemString): Boolean;
// check file for training after
function CheckTrainingAfter(const paramFile: SystemString; var report: SystemString): Boolean;
// prepare again training file list
function RebuildTrainingData(const paramFile: SystemString; var report: SystemString; dest: TTrainingTask): Boolean;
// training on AI
function RunTraining(const AI: TAI; const paramFile: SystemString): Boolean;
// load output data to AI
function LoadTrainingOutput(const paramFile: SystemString; AI: TAI; var report: SystemString): Boolean; overload;
function LoadTrainingOutput(const paramFile: SystemString; AI_P: TAI_Parallel; var report: SystemString): Boolean; overload;
procedure ExportLastWriteToStream(stream: TMemoryStream64);
procedure ExportLastWriteToFile(filename: SystemString);
end;
implementation
procedure TTrainingTask.On_Save_DoStatus(AText: SystemString; const ID: Integer);
begin
if TaskLogStatus <> nil then
TaskLogStatus.Add(umlDateTimeToStr(umlNow()) + #9 + AText);
end;
constructor TTrainingTask.Create;
begin
inherited Create;
DB_Stream := nil;
DB_Engine := nil;
LastWriteFileList := nil;
LastReadMD5 := NullMD5;
LastWriteMD5 := NullMD5;
TaskLogStatus := nil;
AddDoStatusHook(Self, {$IFDEF FPC}@{$ENDIF FPC}On_Save_DoStatus);
end;
class function TTrainingTask.OpenTask(filename: SystemString): TTrainingTask;
begin
Result := TTrainingTask.Create;
Result.DB_Stream := TMemoryStream64.CustomCreate($FFFF);
Result.DB_Stream.LoadFromFile(filename);
Result.DB_Engine := TObjectDataManagerOfCache.CreateAsStream(Result.DB_Stream, '', DBMarshal.ID, False, False, False);
Result.LastWriteFileList := TPascalStringList.Create;
Result.TaskLogStatus := TPascalStringList.Create;
end;
class function TTrainingTask.OpenTask(stream: TCoreClassStream): TTrainingTask;
begin
Result := TTrainingTask.Create;
Result.DB_Stream := TMemoryStream64.CustomCreate($FFFF);
Result.DB_Stream.LoadFromStream(stream);
Result.DB_Stream.Position := 0;
Result.DB_Engine := TObjectDataManagerOfCache.CreateAsStream(Result.DB_Stream, '', DBMarshal.ID, False, False, False);
Result.LastWriteFileList := TPascalStringList.Create;
Result.TaskLogStatus := TPascalStringList.Create;
end;
class function TTrainingTask.CreateTask: TTrainingTask;
begin
Result := TTrainingTask.Create;
Result.DB_Stream := TMemoryStream64.CustomCreate($FFFF);
Result.DB_Engine := TObjectDataManagerOfCache.CreateAsStream(Result.DB_Stream, '', DBMarshal.ID, False, True, False);
Result.LastWriteFileList := TPascalStringList.Create;
Result.TaskLogStatus := TPascalStringList.Create;
end;
destructor TTrainingTask.Destroy;
begin
DeleteDoStatusHook(Self);
DisposeObject(DB_Engine);
DisposeObject(DB_Stream);
DisposeObject(LastWriteFileList);
DisposeObject(TaskLogStatus);
inherited Destroy;
end;
procedure TTrainingTask.SaveToStream(stream: TCoreClassStream);
var
temp_db: TObjectDataManager;
begin
DB_Engine.UpdateIO;
temp_db := TObjectDataManagerOfCache.CreateAsStream(stream, '', DB_Engine.DefaultItemID, False, True, False);
DB_Engine.CopyTo(temp_db);
DisposeObject(temp_db);
end;
procedure TTrainingTask.SaveToFile(filename: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(filename, fmCreate);
SaveToStream(fs);
DisposeObject(fs);
end;
procedure TTrainingTask.Write(name: SystemString; m64: TMemoryStream64);
begin
if not DB_Engine.ItemWriteFromStream('/', Name, m64) then
RaiseInfo('training task write item %s failed.', [name]);
LastWriteMD5 := umlStreamMD5(m64);
if LastWriteFileList.ExistsValue(name) < 0 then
LastWriteFileList.Add(name);
end;
procedure TTrainingTask.Write(name: SystemString; data: THashVariantList);
var
m64: TMemoryStream64;
begin
m64 := TMemoryStream64.Create;
data.SaveToStream(m64);
Write(Name, m64);
DisposeObject(m64);
end;
procedure TTrainingTask.Write(name: SystemString; data: TPascalStringList);
var
m64: TMemoryStream64;
begin
m64 := TMemoryStream64.Create;
data.SaveToStream(m64);
Write(Name, m64);
DisposeObject(m64);
end;
procedure TTrainingTask.Write(name: SystemString; data: TCoreClassStrings);
var
m64: TMemoryStream64;
begin
m64 := TMemoryStream64.Create;
data.SaveToStream(m64);
Write(Name, m64);
DisposeObject(m64);
end;
procedure TTrainingTask.Write(name: SystemString; data: TMemoryRaster);
var
m64: TMemoryStream64;
begin
m64 := TMemoryStream64.Create;
data.SaveToBmp24Stream(m64);
Write(Name, m64);
DisposeObject(m64);
end;
procedure TTrainingTask.Write(name: SystemString; data: TAI_ImageList);
var
m64: TMemoryStream64;
begin
m64 := TMemoryStream64.Create;
data.SaveToStream(m64, True, False);
Write(Name, m64);
DisposeObject(m64);
end;
procedure TTrainingTask.WriteFile(name: SystemString; fromfile: SystemString);
var
m64: TMemoryStream64;
begin
m64 := TMemoryStream64.Create;
if umlFileExists(fromfile) then
begin
try
m64.LoadFromFile(fromfile);
except
end;
end;
write(name, m64);
DisposeObject(m64);
end;
procedure TTrainingTask.Read(name: SystemString; m64: TMemoryStream64);
begin
if not DB_Engine.ItemReadToStream('/', name, m64) then
RaiseInfo('training task read item %s failed.', [name]);
LastReadMD5 := umlStreamMD5(m64);
m64.Position := 0;
end;
procedure TTrainingTask.Read(name: SystemString; data: THashVariantList);
var
m64: TMemoryStream64;
begin
data.Clear;
m64 := TMemoryStream64.Create;
read(name, m64);
data.LoadFromStream(m64);
DisposeObject(m64);
end;
procedure TTrainingTask.Read(name: SystemString; data: TPascalStringList);
var
m64: TMemoryStream64;
begin
data.Clear;
m64 := TMemoryStream64.Create;
read(name, m64);
data.LoadFromStream(m64);
DisposeObject(m64);
end;
procedure TTrainingTask.Read(name: SystemString; data: TCoreClassStrings);
var
m64: TMemoryStream64;
begin
data.Clear;
m64 := TMemoryStream64.Create;
read(name, m64);
data.LoadFromStream(m64);
DisposeObject(m64);
end;
procedure TTrainingTask.Read(name: SystemString; data: TMemoryRaster);
var
m64: TMemoryStream64;
begin
data.Clear;
m64 := TMemoryStream64.Create;
read(name, m64);
data.LoadFromStream(m64);
DisposeObject(m64);
end;
procedure TTrainingTask.Read(name: SystemString; data: TAI_ImageList);
var
m64: TMemoryStream64;
begin
data.Clear;
m64 := TMemoryStream64.Create;
read(name, m64);
data.LoadFromStream(m64);
DisposeObject(m64);
end;
procedure TTrainingTask.ReadToFile(name: SystemString; destfile: SystemString);
var
m64: TMemoryStream64;
begin
m64 := TMemoryStream64.Create;
read(name, m64);
try
m64.SaveToFile(destfile);
except
end;
DisposeObject(m64);
end;
function TTrainingTask.Exists(name: SystemString): Boolean;
begin
Result := DB_Engine.ItemExists('/', name);
end;
function TTrainingTask.Delete(name: SystemString): Boolean;
begin
Result := DB_Engine.ItemDelete('/', name);
LastWriteFileList.DeletePascalString(name);
end;
procedure TTrainingTask.CopyTo(LocalName: SystemString; dest: TTrainingTask; destName: SystemString);
var
m64: TMemoryStream64;
begin
m64 := TMemoryStream64.Create;
read(LocalName, m64);
m64.Position := 0;
dest.Write(destName, m64);
DisposeObject(m64);
end;
function TTrainingTask.CheckTrainingBefore(const paramFile: SystemString; var report: SystemString): Boolean;
var
Param: THashVariantList;
ComputeFunc: TPascalString;
inputfile1, inputfile2: SystemString;
begin
Result := False;
Param := THashVariantList.Create;
Read(paramFile, Param);
if Param.Exists('func') then
ComputeFunc := Param['func']
else if Param.Exists('compute') then
ComputeFunc := Param['compute']
else
ComputeFunc := Param.GetDefaultValue('ComputeFunc', '');
ComputeFunc := ComputeFunc.TrimChar(#32#9);
if umlMultipleMatch(['surf', 'fastsurf'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
inputfile2 := Param.GetDefaultValue('dest', '');
Result := Exists(inputfile1) and Exists(inputfile2);
if not Result then
report := PFormat('error training source: %s', [inputfile1])
end
else if umlMultipleMatch(['TrainOD', 'TrainingOD', 'TrainObjectDetector'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
Result := Exists(inputfile1);
if not Result then
report := PFormat('error training source: %s', [inputfile1])
end
else if umlMultipleMatch(['TrainOD_Marshal', 'TrainingOD_Marshal', 'TrainObjectDetectorMarshal'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
Result := Exists(inputfile1);
if not Result then
report := PFormat('error training source: %s', [inputfile1])
end
else if umlMultipleMatch(['TrainSP', 'TrainingSP', 'TrainShapePredictor'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
Result := Exists(inputfile1);
if not Result then
report := PFormat('error training source: %s', [inputfile1])
end
else if umlMultipleMatch(['TrainMRN', 'TrainingMRN', 'TrainMetricResNet'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
Result := Exists(inputfile1);
if not Result then
report := PFormat('error training source: %s', [inputfile1])
end
else if umlMultipleMatch(['TrainMMOD', 'TrainingMMOD', 'TrainMaxMarginDNNObjectDetector'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
Result := Exists(inputfile1);
if not Result then
report := PFormat('error training source: %s', [inputfile1])
end
else if umlMultipleMatch(['TrainRNIC', 'TrainingRNIC', 'TrainResNetImageClassifier'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
Result := Exists(inputfile1);
if not Result then
report := PFormat('error training source: %s', [inputfile1])
end
else
begin
report := 'illegal ComputeFunc.';
end;
DisposeObject(Param);
if Result then
report := 'solve.';
end;
function TTrainingTask.CheckTrainingAfter(const paramFile: SystemString; var report: SystemString): Boolean;
var
Param: THashVariantList;
ResultValues: THashVariantList;
ComputeFunc: TPascalString;
outputfile: SystemString;
begin
Result := False;
if not Exists(paramFile) then
begin
report := PFormat('error param file: %s', [paramFile]);
DisposeObject(Param);
exit;
end;
Param := THashVariantList.Create;
Read(paramFile, Param);
outputfile := Param.GetDefaultValue('Result', 'Result.txt');
if not Exists(outputfile) then
begin
report := PFormat('error result file: %s', [outputfile]);
DisposeObject(Param);
exit;
end;
ResultValues := THashVariantList.Create;
Read(outputfile, ResultValues);
if Param.Exists('func') then
ComputeFunc := Param['func']
else if Param.Exists('compute') then
ComputeFunc := Param['compute']
else
ComputeFunc := Param.GetDefaultValue('ComputeFunc', '');
ComputeFunc := ComputeFunc.TrimChar(#32#9);
if ResultValues.GetDefaultValue('Result', False) = False then
begin
report := 'Training Result Error.';
end
else if umlMultipleMatch(['surf', 'fastsurf'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output.bmp');
Result := Exists(outputfile);
if not Result then
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainOD', 'TrainingOD', 'TrainObjectDetector'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_OD_Ext);
Result := Exists(outputfile);
if not Result then
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainOD_Marshal', 'TrainingOD_Marshal', 'TrainObjectDetectorMarshal'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_OD_Marshal_Ext);
Result := Exists(outputfile);
if not Result then
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainSP', 'TrainingSP', 'TrainShapePredictor'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_SP_Ext);
Result := Exists(outputfile);
if not Result then
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainMRN', 'TrainingMRN', 'TrainMetricResNet'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output.sync', 'output' + C_Metric_ResNet_Ext + '.sync');
if Exists(outputfile) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_Metric_ResNet_Ext);
Result := Exists(outputfile);
if not Result then
report := PFormat('error training output: %s', [outputfile]);
end
else
report := PFormat('error training sync file: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainMMOD', 'TrainingMMOD', 'TrainMaxMarginDNNObjectDetector'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output.sync', 'output' + C_MMOD_Ext + '.sync');
if Exists(outputfile) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_MMOD_Ext);
Result := Exists(outputfile);
if not Result then
report := PFormat('error training output: %s', [outputfile]);
end
else
report := PFormat('error training sync file: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainRNIC', 'TrainingRNIC', 'TrainResNetImageClassifier'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output.sync', 'output' + C_RNIC_Ext + '.sync');
if Exists(outputfile) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_RNIC_Ext);
Result := Exists(outputfile);
if not Result then
report := PFormat('error training output: %s', [outputfile]);
end
else
report := PFormat('error training sync file: %s', [outputfile]);
end
else
begin
report := 'illegal ComputeFunc.';
end;
DisposeObject([Param, ResultValues]);
if Result then
report := 'solve.';
end;
function TTrainingTask.RebuildTrainingData(const paramFile: SystemString; var report: SystemString; dest: TTrainingTask): Boolean;
var
Param: THashVariantList;
ResultValues: THashVariantList;
ComputeFunc: TPascalString;
inputfile1, inputfile2: SystemString;
outputfile, syncfile: SystemString;
m1, m2: TStream64;
begin
Result := CheckTrainingBefore(paramFile, report);
if not Result then
exit;
Result := CheckTrainingAfter(paramFile, report);
if not Result then
exit;
Result := False;
Param := THashVariantList.Create;
Read(paramFile, Param);
outputfile := Param.GetDefaultValue('Result', 'Result.txt');
ResultValues := THashVariantList.Create;
Read(outputfile, ResultValues);
if Param.Exists('func') then
ComputeFunc := Param['func']
else if Param.Exists('compute') then
ComputeFunc := Param['compute']
else
ComputeFunc := Param.GetDefaultValue('ComputeFunc', '');
ComputeFunc := ComputeFunc.TrimChar(#32#9);
if umlMultipleMatch(['surf', 'fastsurf'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
inputfile2 := Param.GetDefaultValue('dest', '');
outputfile := Param.GetDefaultValue('output', 'output.bmp');
CopyTo(paramFile, dest, paramFile);
CopyTo(inputfile1, dest, inputfile1);
CopyTo(inputfile2, dest, inputfile2);
Result := True;
end
else if umlMultipleMatch(['TrainOD', 'TrainingOD', 'TrainObjectDetector'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
outputfile := Param.GetDefaultValue('output', 'output' + C_OD_Ext);
CopyTo(paramFile, dest, paramFile);
CopyTo(inputfile1, dest, inputfile1);
Result := True;
end
else if umlMultipleMatch(['TrainOD_Marshal', 'TrainingOD_Marshal', 'TrainObjectDetectorMarshal'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
outputfile := Param.GetDefaultValue('output', 'output' + C_OD_Marshal_Ext);
CopyTo(paramFile, dest, paramFile);
CopyTo(inputfile1, dest, inputfile1);
Result := True;
end
else if umlMultipleMatch(['TrainSP', 'TrainingSP', 'TrainShapePredictor'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
outputfile := Param.GetDefaultValue('output', 'output' + C_SP_Ext);
CopyTo(paramFile, dest, paramFile);
CopyTo(inputfile1, dest, inputfile1);
Result := True;
end
else if umlMultipleMatch(['TrainMRN', 'TrainingMRN', 'TrainMetricResNet'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
inputfile2 := Param.GetDefaultValue('syncfile', 'output' + C_Metric_ResNet_Ext + '.sync');
syncfile := Param.GetDefaultValue('output.sync', 'output' + C_Metric_ResNet_Ext + '.sync');
outputfile := Param.GetDefaultValue('output', 'output' + C_Metric_ResNet_Ext);
CopyTo(paramFile, dest, paramFile);
CopyTo(inputfile1, dest, inputfile1);
CopyTo(syncfile, dest, inputfile2);
Result := True;
end
else if umlMultipleMatch(['TrainMMOD', 'TrainingMMOD', 'TrainMaxMarginDNNObjectDetector'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
inputfile2 := Param.GetDefaultValue('syncfile', 'output' + C_MMOD_Ext + '.sync');
syncfile := Param.GetDefaultValue('output.sync', 'output' + C_MMOD_Ext + '.sync');
outputfile := Param.GetDefaultValue('output', 'output' + C_MMOD_Ext);
CopyTo(paramFile, dest, paramFile);
CopyTo(inputfile1, dest, inputfile1);
CopyTo(syncfile, dest, inputfile2);
Result := True;
end
else if umlMultipleMatch(['TrainRNIC', 'TrainingRNIC', 'TrainResNetImageClassifier'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
inputfile2 := Param.GetDefaultValue('syncfile', 'output' + C_RNIC_Ext + '.sync');
syncfile := Param.GetDefaultValue('output.sync', 'output' + C_RNIC_Ext + '.sync');
outputfile := Param.GetDefaultValue('output', 'output' + C_RNIC_Ext);
CopyTo(paramFile, dest, paramFile);
CopyTo(inputfile1, dest, inputfile1);
CopyTo(syncfile, dest, inputfile2);
Result := True;
end
else
begin
report := 'illegal ComputeFunc.';
end;
DisposeObject([Param, ResultValues]);
if Result then
report := 'solve.';
end;
function TTrainingTask.RunTraining(const AI: TAI; const paramFile: SystemString): Boolean;
var
Param: THashVariantList;
ComputeFunc: SystemString;
param_md5: TMD5;
// batch free
inputfile1, inputfile2: SystemString;
inputstream1, inputstream2: TMemoryStream64;
inputraster1, inputraster2: TMemoryRaster;
inputImgList: TAI_ImageList;
ResultValues: THashVariantList;
// manual free
outputstream: TMemoryStream64;
outputPacalStringList: TPascalStringList;
outputraster: TMemoryRaster;
local_sync, sync_file, output_file: SystemString;
scale: TGeoFloat;
metric_resnet_param: PMetric_ResNet_Train_Parameter;
mmod_param: PMMOD_Train_Parameter;
rnic_param: PRNIC_Train_Parameter;
begin
Result := False;
if not AI.Activted then
exit;
LastWriteFileList.Clear;
Param := THashVariantList.Create;
Read(paramFile, Param);
param_md5 := LastReadMD5;
if Param.Exists('func') then
ComputeFunc := Param['func']
else if Param.Exists('compute') then
ComputeFunc := Param['compute']
else
ComputeFunc := Param.GetDefaultValue('ComputeFunc', '');
DoStatus('input training parameter.');
DoStatus(Param.AsText);
inputfile1 := '';
inputfile2 := '';
inputstream1 := TMemoryStream64.Create;
inputstream2 := TMemoryStream64.Create;
inputraster1 := TMemoryRaster.Create;
inputraster2 := TMemoryRaster.Create;
inputImgList := TAI_ImageList.Create;
ResultValues := THashVariantList.Create;
ResultValues['Begin'] := umlNow();
try
if umlMultipleMatch(['surf', 'fastsurf'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
inputfile2 := Param.GetDefaultValue('dest', '');
if Exists(inputfile1) and Exists(inputfile2) then
begin
try
Read(inputfile1, inputraster1);
Read(inputfile2, inputraster2);
inputraster1.scale(Param.GetDefaultValue('scale', 1.0));
inputraster2.scale(Param.GetDefaultValue('scale', 1.0));
outputraster := AI.BuildSurfMatchOutput(inputraster1, inputraster2);
write(Param.GetDefaultValue('output', 'output.bmp'), outputraster);
DisposeObject(outputraster);
Result := True;
except
end;
end;
end
else if umlMultipleMatch(['TrainOD', 'TrainingOD', 'TrainObjectDetector'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
if Exists(inputfile1) then
begin
try
Read(inputfile1, inputImgList);
inputImgList.scale(Param.GetDefaultValue('scale', 1.0));
outputstream := AI.OD_Train_Stream(
inputImgList,
Param.GetDefaultValue('window_width', 80),
Param.GetDefaultValue('window_height', 80),
Param.GetDefaultValue('thread', 2)
);
if outputstream <> nil then
begin
write(Param.GetDefaultValue('output', 'output' + C_OD_Ext), outputstream);
DisposeObject(outputstream);
Result := True;
end;
except
end;
end;
end
else if umlMultipleMatch(['TrainOD_Marshal', 'TrainingOD_Marshal', 'TrainObjectDetectorMarshal'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
if Exists(inputfile1) then
begin
try
Read(inputfile1, inputImgList);
inputImgList.scale(Param.GetDefaultValue('scale', 1.0));
outputstream := AI.OD_Marshal_Train(
inputImgList,
Param.GetDefaultValue('window_width', 80),
Param.GetDefaultValue('window_height', 80),
Param.GetDefaultValue('thread', 2)
);
if outputstream <> nil then
begin
write(Param.GetDefaultValue('output', 'output' + C_OD_Marshal_Ext), outputstream);
DisposeObject(outputstream);
Result := True;
end;
except
end;
end;
end
else if umlMultipleMatch(['TrainSP', 'TrainingSP', 'TrainShapePredictor'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
if Exists(inputfile1) then
begin
try
Read(inputfile1, inputImgList);
inputImgList.scale(Param.GetDefaultValue('scale', 1.0));
outputstream := AI.SP_Train_Stream(
inputImgList,
Param.GetDefaultValue('oversampling_amount', 300),
Param.GetDefaultValue('tree_depth', 2),
Param.GetDefaultValue('thread', 2)
);
if outputstream <> nil then
begin
write(Param.GetDefaultValue('output', 'output' + C_SP_Ext), outputstream);
DisposeObject(outputstream);
Result := True;
end;
except
end;
end;
end
else if umlMultipleMatch(['TrainMRN', 'TrainingMRN', 'TrainMetricResNet'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
if Exists(inputfile1) then
begin
try
Read(inputfile1, inputImgList);
local_sync := Param.GetDefaultValue('syncfile', 'output' + C_Metric_ResNet_Ext + '.sync');
sync_file := umlCombineFileName(AI.RootPath, local_sync + '_' + umlMD5ToStr(umlCombineMD5(param_md5, LastReadMD5)));
if Exists(local_sync) then
if not umlFileExists(sync_file) then
ReadToFile(local_sync, sync_file);
output_file := umlMD5ToStr(umlCombineMD5(param_md5, LastReadMD5)) + C_Metric_ResNet_Ext;
if umlFileExists(output_file) then
begin
outputstream := TMemoryStream64.Create;
outputstream.LoadFromFile(output_file);
outputstream.Position := 0;
end
else
begin
metric_resnet_param := TAI.Init_Metric_ResNet_Parameter(sync_file, output_file);
metric_resnet_param^.timeout := Param.GetDefaultValue('timeout', metric_resnet_param^.timeout);
metric_resnet_param^.weight_decay := Param.GetDefaultValue('weight_decay', metric_resnet_param^.weight_decay);
metric_resnet_param^.momentum := Param.GetDefaultValue('momentum', metric_resnet_param^.momentum);
metric_resnet_param^.iterations_without_progress_threshold := Param.GetDefaultValue('iterations_without_progress_threshold', metric_resnet_param^.iterations_without_progress_threshold);
metric_resnet_param^.learning_rate := Param.GetDefaultValue('learning_rate', metric_resnet_param^.learning_rate);
metric_resnet_param^.completed_learning_rate := Param.GetDefaultValue('completed_learning_rate', metric_resnet_param^.completed_learning_rate);
metric_resnet_param^.step_mini_batch_target_num := Param.GetDefaultValue('step_mini_batch_target_num', metric_resnet_param^.step_mini_batch_target_num);
metric_resnet_param^.step_mini_batch_raster_num := Param.GetDefaultValue('step_mini_batch_raster_num', metric_resnet_param^.step_mini_batch_raster_num);
metric_resnet_param^.fullGPU_Training := Param.GetDefaultValue('fullGPU_Training', metric_resnet_param^.fullGPU_Training);
outputstream := AI.Metric_ResNet_Train_Stream(
inputImgList,
metric_resnet_param);
TAI.Free_Metric_ResNet_Parameter(metric_resnet_param);
end;
if outputstream <> nil then
begin
write(Param.GetDefaultValue('output', 'output' + C_Metric_ResNet_Ext), outputstream);
WriteFile(Param.GetDefaultValue('output.sync', 'output' + C_Metric_ResNet_Ext + '.sync'), sync_file);
DisposeObject(outputstream);
ResultValues['Loss'] := AI.Last_training_average_loss;
ResultValues['Rate'] := AI.Last_training_learning_rate;
Result := True;
end;
umlDeleteFile(sync_file);
except
end;
end;
end
else if umlMultipleMatch(['TrainMMOD', 'TrainingMMOD', 'TrainMaxMarginDNNObjectDetector'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
if Exists(inputfile1) then
begin
try
Read(inputfile1, inputImgList);
inputImgList.scale(Param.GetDefaultValue('scale', 1.0));
local_sync := Param.GetDefaultValue('syncfile', 'output' + C_MMOD_Ext + '.sync');
sync_file := umlCombineFileName(AI.RootPath, local_sync + '_' + umlMD5ToStr(umlCombineMD5(param_md5, LastReadMD5)));
if Exists(local_sync) then
if not umlFileExists(sync_file) then
ReadToFile(local_sync, sync_file);
mmod_param := AI.MMOD_DNN_PrepareTrain(inputImgList, sync_file);
mmod_param^.timeout := Param.GetDefaultValue('timeout', mmod_param^.timeout);
mmod_param^.target_size := Param.GetDefaultValue('target_size', mmod_param^.target_size);
mmod_param^.min_target_size := Param.GetDefaultValue('min_target_size', mmod_param^.min_target_size);
mmod_param^.min_detector_window_overlap_iou := Param.GetDefaultValue('min_detector_window_overlap_iou', mmod_param^.min_detector_window_overlap_iou);
mmod_param^.iterations_without_progress_threshold := Param.GetDefaultValue('iterations_without_progress_threshold', mmod_param^.iterations_without_progress_threshold);
mmod_param^.learning_rate := Param.GetDefaultValue('learning_rate', mmod_param^.learning_rate);
mmod_param^.completed_learning_rate := Param.GetDefaultValue('completed_learning_rate', mmod_param^.completed_learning_rate);
mmod_param^.num_crops := Param.GetDefaultValue('num_crops', mmod_param^.num_crops);
mmod_param^.chip_dims_x := Param.GetDefaultValue('chip_dims_x', mmod_param^.chip_dims_x);
mmod_param^.chip_dims_y := Param.GetDefaultValue('chip_dims_y', mmod_param^.chip_dims_y);
mmod_param^.min_object_size_x := Param.GetDefaultValue('min_object_size_x', mmod_param^.min_object_size_x);
mmod_param^.min_object_size_y := Param.GetDefaultValue('min_object_size_y', mmod_param^.min_object_size_y);
mmod_param^.max_rotation_degrees := Param.GetDefaultValue('max_rotation_degrees', mmod_param^.max_rotation_degrees);
mmod_param^.max_object_size := Param.GetDefaultValue('max_object_size', mmod_param^.max_object_size);
outputstream := AI.MMOD_DNN_Train_Stream(mmod_param);
AI.MMOD_DNN_FreeTrain(mmod_param);
if outputstream <> nil then
begin
write(Param.GetDefaultValue('output', 'output' + C_MMOD_Ext), outputstream);
WriteFile(Param.GetDefaultValue('output.sync', 'output' + C_MMOD_Ext + '.sync'), sync_file);
DisposeObject(outputstream);
ResultValues['Loss'] := AI.Last_training_average_loss;
ResultValues['Rate'] := AI.Last_training_learning_rate;
Result := True;
end;
umlDeleteFile(sync_file);
except
end;
end;
end
else if umlMultipleMatch(['TrainRNIC', 'TrainingRNIC', 'TrainResNetImageClassifier'], ComputeFunc) then
begin
inputfile1 := Param.GetDefaultValue('source', '');
if Exists(inputfile1) then
begin
outputPacalStringList := TPascalStringList.Create;
try
Read(inputfile1, inputImgList);
inputImgList.scale(Param.GetDefaultValue('scale', 1.0));
local_sync := Param.GetDefaultValue('syncfile', 'output' + C_RNIC_Ext + '.sync');
sync_file := umlCombineFileName(AI.RootPath, local_sync + '_' + umlMD5ToStr(umlCombineMD5(param_md5, LastReadMD5)));
if Exists(local_sync) then
if not umlFileExists(sync_file) then
ReadToFile(local_sync, sync_file);
output_file := umlMD5ToStr(umlCombineMD5(param_md5, LastReadMD5)) + C_Metric_ResNet_Ext;
rnic_param := TAI.Init_RNIC_Train_Parameter(sync_file, output_file);
rnic_param^.timeout := Param.GetDefaultValue('timeout', rnic_param^.timeout);
rnic_param^.iterations_without_progress_threshold := Param.GetDefaultValue('iterations_without_progress_threshold', rnic_param^.iterations_without_progress_threshold);
rnic_param^.learning_rate := Param.GetDefaultValue('learning_rate', rnic_param^.learning_rate);
rnic_param^.completed_learning_rate := Param.GetDefaultValue('completed_learning_rate', rnic_param^.completed_learning_rate);
rnic_param^.all_bn_running_stats_window_sizes := Param.GetDefaultValue('all_bn_running_stats_window_sizes', rnic_param^.all_bn_running_stats_window_sizes);
rnic_param^.img_mini_batch := Param.GetDefaultValue('img_mini_batch', rnic_param^.img_mini_batch);
outputstream := AI.RNIC_Train_Stream(
inputImgList,
rnic_param,
outputPacalStringList
);
TAI.Free_RNIC_Train_Parameter(rnic_param);
if outputstream <> nil then
begin
write(Param.GetDefaultValue('output', 'output' + C_RNIC_Ext), outputstream);
WriteFile(Param.GetDefaultValue('output.sync', 'output' + C_RNIC_Ext + '.sync'), sync_file);
write(Param.GetDefaultValue('output.index', 'output' + C_RNIC_Ext + '.index'), outputPacalStringList);
DisposeObject(outputstream);
ResultValues['Loss'] := AI.Last_training_average_loss;
ResultValues['Rate'] := AI.Last_training_learning_rate;
Result := True;
end;
umlDeleteFile(sync_file);
except
end;
DisposeObject(outputPacalStringList);
end;
end
else
begin
DoStatus('AI Training task failed: no define ComputeFunc.');
end;
finally
ResultValues['Result'] := Result;
ResultValues['End'] := umlNow();
Write(Param.GetDefaultValue('Result', 'Result.txt'), ResultValues);
Write(Param.GetDefaultValue('LogFile', 'Log.txt'), TaskLogStatus);
if Result then
begin
if LastWriteFileList.ExistsValue(paramFile) < 0 then
LastWriteFileList.Add(paramFile);
Write(Param.GetDefaultValue('LastOutput', 'LastOutput.txt'), LastWriteFileList);
end;
end;
DisposeObject(Param);
DisposeObject([inputstream1, inputstream2]);
DisposeObject([inputraster1, inputraster2]);
DisposeObject(inputImgList);
DisposeObject(ResultValues);
end;
function TTrainingTask.LoadTrainingOutput(const paramFile: SystemString; AI: TAI; var report: SystemString): Boolean;
var
Param: THashVariantList;
ResultValues: THashVariantList;
ComputeFunc: TPascalString;
outputfile: SystemString;
m64: TMemoryStream64;
begin
Result := False;
if not Exists(paramFile) then
begin
report := PFormat('error param file: %s', [paramFile]);
DisposeObject(Param);
exit;
end;
Param := THashVariantList.Create;
Read(paramFile, Param);
outputfile := Param.GetDefaultValue('Result', 'Result.txt');
if not Exists(outputfile) then
begin
report := PFormat('error result file: %s', [outputfile]);
DisposeObject(Param);
exit;
end;
ResultValues := THashVariantList.Create;
Read(outputfile, ResultValues);
if Param.Exists('func') then
ComputeFunc := Param['func']
else if Param.Exists('compute') then
ComputeFunc := Param['compute']
else
ComputeFunc := Param.GetDefaultValue('ComputeFunc', '');
ComputeFunc := ComputeFunc.TrimChar(#32#9);
if ResultValues.GetDefaultValue('Result', False) = False then
begin
report := 'Training Result Error.';
end
else if umlMultipleMatch(['surf', 'fastsurf'], ComputeFunc) then
begin
Result := False;
report := PFormat('surf not require.', []);
end
else if umlMultipleMatch(['TrainOD', 'TrainingOD', 'TrainObjectDetector'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_OD_Ext);
if Exists(outputfile) then
begin
if AI.Parallel_OD_Hnd <> nil then
AI.OD_Close(AI.Parallel_OD_Hnd);
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI.Parallel_OD_Hnd := AI.OD_Open_Stream(m64);
DisposeObject(m64);
Result := AI.Parallel_OD_Hnd <> nil;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainOD_Marshal', 'TrainingOD_Marshal', 'TrainObjectDetectorMarshal'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_OD_Marshal_Ext);
if Exists(outputfile) then
begin
if AI.Parallel_OD_Marshal_Hnd <> nil then
AI.OD_Marshal_Close(AI.Parallel_OD_Marshal_Hnd);
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI.Parallel_OD_Marshal_Hnd := AI.OD_Marshal_Open_Stream(m64);
DisposeObject(m64);
Result := AI.Parallel_OD_Marshal_Hnd <> nil;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainSP', 'TrainingSP', 'TrainShapePredictor'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_SP_Ext);
if Exists(outputfile) then
begin
if AI.Parallel_SP_Hnd <> nil then
AI.SP_Close(AI.Parallel_SP_Hnd);
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI.Parallel_SP_Hnd := AI.SP_Open_Stream(m64);
DisposeObject(m64);
Result := AI.Parallel_SP_Hnd <> nil;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainMRN', 'TrainingMRN', 'TrainMetricResNet'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_Metric_ResNet_Ext);
if Exists(outputfile) then
begin
if AI.Parallel_MDNN_Hnd <> nil then
AI.Metric_ResNet_Close(AI.Parallel_MDNN_Hnd);
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI.Parallel_MDNN_Hnd := AI.Metric_ResNet_Open_Stream(m64);
DisposeObject(m64);
Result := AI.Parallel_MDNN_Hnd <> nil;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainMMOD', 'TrainingMMOD', 'TrainMaxMarginDNNObjectDetector'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_MMOD_Ext);
if Exists(outputfile) then
begin
if AI.Parallel_MMOD_Hnd <> nil then
AI.MMOD_DNN_Close(AI.Parallel_MMOD_Hnd);
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI.Parallel_MMOD_Hnd := AI.MMOD_DNN_Open_Stream(m64);
DisposeObject(m64);
Result := AI.Parallel_MMOD_Hnd <> nil;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainRNIC', 'TrainingRNIC', 'TrainResNetImageClassifier'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_RNIC_Ext);
if Exists(outputfile) then
begin
if AI.Parallel_RNIC_Hnd <> nil then
AI.RNIC_Close(AI.Parallel_RNIC_Hnd);
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI.Parallel_RNIC_Hnd := AI.RNIC_Open_Stream(m64);
DisposeObject(m64);
Result := AI.Parallel_RNIC_Hnd <> nil;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else
begin
report := 'illegal ComputeFunc.';
end;
DisposeObject([Param, ResultValues]);
if Result then
report := 'solve.';
end;
function TTrainingTask.LoadTrainingOutput(const paramFile: SystemString; AI_P: TAI_Parallel; var report: SystemString): Boolean;
var
Param: THashVariantList;
ResultValues: THashVariantList;
ComputeFunc: TPascalString;
outputfile: SystemString;
m64: TMemoryStream64;
begin
Result := False;
if not Exists(paramFile) then
begin
report := PFormat('error param file: %s', [paramFile]);
DisposeObject(Param);
exit;
end;
Param := THashVariantList.Create;
Read(paramFile, Param);
outputfile := Param.GetDefaultValue('Result', 'Result.txt');
if not Exists(outputfile) then
begin
report := PFormat('error result file: %s', [outputfile]);
DisposeObject(Param);
exit;
end;
ResultValues := THashVariantList.Create;
Read(outputfile, ResultValues);
if Param.Exists('func') then
ComputeFunc := Param['func']
else if Param.Exists('compute') then
ComputeFunc := Param['compute']
else
ComputeFunc := Param.GetDefaultValue('ComputeFunc', '');
ComputeFunc := ComputeFunc.TrimChar(#32#9);
if ResultValues.GetDefaultValue('Result', False) = False then
begin
report := 'Training Result Error.';
end
else if umlMultipleMatch(['surf', 'fastsurf'], ComputeFunc) then
begin
Result := False;
report := PFormat('surf not require.', []);
end
else if umlMultipleMatch(['TrainOD', 'TrainingOD', 'TrainObjectDetector'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_OD_Ext);
if Exists(outputfile) then
begin
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI_P.Prepare_OD(m64);
DisposeObject(m64);
Result := True;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainOD_Marshal', 'TrainingOD_Marshal', 'TrainObjectDetectorMarshal'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_OD_Marshal_Ext);
if Exists(outputfile) then
begin
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI_P.Prepare_OD_Marshal(m64);
DisposeObject(m64);
Result := True;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainSP', 'TrainingSP', 'TrainShapePredictor'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_SP_Ext);
if Exists(outputfile) then
begin
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI_P.Prepare_SP(m64);
DisposeObject(m64);
Result := True;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainMRN', 'TrainingMRN', 'TrainMetricResNet'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_Metric_ResNet_Ext);
if Exists(outputfile) then
begin
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI_P.Prepare_MDNN(m64);
DisposeObject(m64);
Result := True;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainMMOD', 'TrainingMMOD', 'TrainMaxMarginDNNObjectDetector'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_MMOD_Ext);
if Exists(outputfile) then
begin
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI_P.Prepare_MMOD(m64);
DisposeObject(m64);
Result := True;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else if umlMultipleMatch(['TrainRNIC', 'TrainingRNIC', 'TrainResNetImageClassifier'], ComputeFunc) then
begin
outputfile := Param.GetDefaultValue('output', 'output' + C_RNIC_Ext);
if Exists(outputfile) then
begin
m64 := TMemoryStream64.Create;
Read(outputfile, m64);
AI_P.Prepare_RNIC(m64);
DisposeObject(m64);
Result := True;
end
else
report := PFormat('error training output: %s', [outputfile]);
end
else
begin
report := 'illegal ComputeFunc.';
end;
DisposeObject([Param, ResultValues]);
if Result then
report := 'solve.';
end;
procedure TTrainingTask.ExportLastWriteToStream(stream: TMemoryStream64);
var
dest_db: TObjectDataManager;
i: Integer;
m64: TMemoryStream64;
begin
dest_db := TObjectDataManager.CreateAsStream(stream, '', DBMarshal.ID, False, True, False);
for i := 0 to LastWriteFileList.Count - 1 do
begin
m64 := TMemoryStream64.CustomCreate($FFFF);
DB_Engine.ItemReadToStream('/', LastWriteFileList[i], m64);
m64.Position := 0;
dest_db.ItemWriteFromStream('/', LastWriteFileList[i], m64);
DisposeObject(m64);
end;
DisposeObject(dest_db);
end;
procedure TTrainingTask.ExportLastWriteToFile(filename: SystemString);
var
m64: TMemoryStream64;
begin
m64 := TMemoryStream64.CustomCreate($FFFF);
ExportLastWriteToStream(m64);
m64.SaveToFile(filename);
DisposeObject(m64);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Androidapi.JNI.Support;
interface
uses
Androidapi.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Widget,
Androidapi.JNI.App,
Androidapi.JNI.Net,
Androidapi.JNI.GraphicsContentViewText;
type
{Class forward declarations}
JNotificationCompat_Builder = interface;//android.support.v4.app.NotificationCompat$Builder
JNotificationCompat_Style = interface;//android.support.v4.app.NotificationCompat$Style
JNotificationCompat_BuilderClass = interface(JObjectClass)
['{6EC74C2C-EBCC-4A55-98B6-6DD36DE3BA8C}']
{Methods}
function init(context: JContext): JNotificationCompat_Builder; cdecl;
end;
[JavaSignature('android/support/v4/app/NotificationCompat$Builder')]
JNotificationCompat_Builder = interface(JObject)
['{7DE9C385-1C34-413C-9E85-D8FA90028065}']
{Methods}
function addAction(icon: Integer; title: JCharSequence; intent: JPendingIntent): JNotificationCompat_Builder; cdecl;
function build: JNotification; cdecl;
function getNotification: JNotification; cdecl;//Deprecated
function setAutoCancel(autoCancel: Boolean): JNotificationCompat_Builder; cdecl;
function setContent(views: JRemoteViews): JNotificationCompat_Builder; cdecl;
function setContentInfo(info: JCharSequence): JNotificationCompat_Builder; cdecl;
function setContentIntent(intent: JPendingIntent): JNotificationCompat_Builder; cdecl;
function setContentText(text: JCharSequence): JNotificationCompat_Builder; cdecl;
function setContentTitle(title: JCharSequence): JNotificationCompat_Builder; cdecl;
function setDefaults(defaults: Integer): JNotificationCompat_Builder; cdecl;
function setDeleteIntent(intent: JPendingIntent): JNotificationCompat_Builder; cdecl;
function setFullScreenIntent(intent: JPendingIntent; highPriority: Boolean): JNotificationCompat_Builder; cdecl;
function setLargeIcon(icon: JBitmap): JNotificationCompat_Builder; cdecl;
function setLights(argb: Integer; onMs: Integer; offMs: Integer): JNotificationCompat_Builder; cdecl;
function setNumber(number: Integer): JNotificationCompat_Builder; cdecl;
function setOngoing(ongoing: Boolean): JNotificationCompat_Builder; cdecl;
function setOnlyAlertOnce(onlyAlertOnce: Boolean): JNotificationCompat_Builder; cdecl;
function setPriority(pri: Integer): JNotificationCompat_Builder; cdecl;
function setProgress(max: Integer; progress: Integer; indeterminate: Boolean): JNotificationCompat_Builder; cdecl;
function setSmallIcon(icon: Integer): JNotificationCompat_Builder; cdecl; overload;
function setSmallIcon(icon: Integer; level: Integer): JNotificationCompat_Builder; cdecl; overload;
function setSound(sound: Jnet_Uri): JNotificationCompat_Builder; cdecl; overload;
function setSound(sound: Jnet_Uri; streamType: Integer): JNotificationCompat_Builder; cdecl; overload;
function setStyle(style: JNotificationCompat_Style): JNotificationCompat_Builder; cdecl;
function setSubText(text: JCharSequence): JNotificationCompat_Builder; cdecl;
function setTicker(tickerText: JCharSequence): JNotificationCompat_Builder; cdecl; overload;
function setTicker(tickerText: JCharSequence; views: JRemoteViews): JNotificationCompat_Builder; cdecl; overload;
function setUsesChronometer(b: Boolean): JNotificationCompat_Builder; cdecl;
function setVibrate(pattern: TJavaArray<Int64>): JNotificationCompat_Builder; cdecl;
function setWhen(when: Int64): JNotificationCompat_Builder; cdecl;
end;
TJNotificationCompat_Builder = class(TJavaGenericImport<JNotificationCompat_BuilderClass, JNotificationCompat_Builder>) end;
JNotificationCompat_StyleClass = interface(JObjectClass)
['{A76478B0-8BCB-4AFA-AFCD-CB0460219CDA}']
{Methods}
function init: JNotificationCompat_Style; cdecl;
end;
[JavaSignature('android/support/v4/app/NotificationCompat$Style')]
JNotificationCompat_Style = interface(JObject)
['{5C782C73-8C4B-4ADA-994D-4293E0D2D282}']
{Methods}
function build: JNotification; cdecl;
procedure setBuilder(builder: JNotificationCompat_Builder); cdecl;
end;
TJNotificationCompat_Style = class(TJavaGenericImport<JNotificationCompat_StyleClass, JNotificationCompat_Style>) end;
implementation
begin
end.
|
{***************************************************************}
{ Сервис для E-Mail рассылки }
{ Copyright (c) 2013 год . }
{ Тетенев Леонид Петрович, ltetenev@yandex.ru }
{ }
{***************************************************************}
unit frLsrmSend;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs,
Data.DB, IBDatabase, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdMessage,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient,
IdSMTPBase, IdSMTP, IBCustomDataSet, IBQuery, Vcl.ExtCtrls, IBEvents;
type
TSaveInLog = ( slNo, slAll, slError );
TLsrmMailSend = class(TService)
IBDB: TIBDatabase;
IBTr_Read: TIBTransaction;
IBTr_Write: TIBTransaction;
SMTP: TIdSMTP;
Mess: TIdMessage;
OpenSSL: TIdSSLIOHandlerSocketOpenSSL;
TM: TTimer;
Q_Mess: TIBQuery;
Q_Save: TIBQuery;
Q_MessAttach: TIBQuery;
IBEvent: TIBEvents;
Q_LabelList: TIBQuery;
Q_LabelValue: TIBQuery;
procedure ServiceCreate(Sender: TObject);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
procedure ServiceShutdown(Sender: TService);
procedure ServiceExecute(Sender: TService);
procedure TMTimer(Sender: TObject);
procedure IBEventEventAlert(Sender: TObject; EventName: string; EventCount: Integer; var CancelAlerts: Boolean);
procedure Q_LabelValueBeforeOpen(DataSet: TDataSet);
private
{ Private declarations }
IniPath: String;
SaveInLog: TSaveInLog;
function GetLogFileName: String;
procedure ToLogFile(const Str: string);
function ConnectParams: Boolean;
procedure ReadMailList;
procedure SaveResult( IsSend: Boolean; const ResultText: String);
function SendToEMail(var ResultText: String): Boolean;
procedure AddAttachmentFile( var Body: String );
function MailBodyReplaceLabel( BodyValue: String ): String;
property LogFileName: String read GetLogFileName;
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
// Интервал опроса
const
tiSmall = 3000; // 3 секунды
tiBig = 1800000; // 30 минут
var
LsrmMailSend: TLsrmMailSend;
implementation
{$R *.DFM}
uses
IdAttachment, IdAttachmentFile, IdText, IdHashMessageDigest;
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
LsrmMailSend.Controller(CtrlCode);
end;
{MD5}
function StrToMd5( Value: string ): string;
var
Hash: TIdHashMessageDigest5;
begin
Result := '';
Hash := TIdHashMessageDigest5.Create;
try
Result := AnsiUpperCase( Hash.HashStringAsHex( Value ));
finally
Hash.Free;
end;
end;
{ Работа с ini-файлом }
function IniGetString( FileName, Section, Key: String ): String;
var
Res : DWORD;
begin
SetLength( Result, MAX_PATH );
Res := GetPrivateProfileString( PChar( Section ), PChar( Key ), #0, PChar( Result ), Length( Result ), PChar( FileName ));
If Res > 0 then
SetLength( Result, Res )
else
Result := '';
end;
function IniGetInteger( FileName, Section, Key : STRING ): Integer;
begin
Result :=
GetPrivateProfileInt( PChar( Section ), PChar( Key ), -1, PChar( FileName ) );
end;
function IniGetIntegerDef( FileName, Section, Key : STRING; DefValue: Integer ): Integer;
begin
Result :=
GetPrivateProfileInt( PChar( Section ), PChar( Key ), DefValue, PChar( FileName ) );
end;
{TLsrmMailSend}
function TLsrmMailSend.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TLsrmMailSend.IBEventEventAlert(Sender: TObject; EventName: string; EventCount: Integer;
var CancelAlerts: Boolean);
begin
if TM.Enabled then
ReadMailList;
end;
procedure TLsrmMailSend.TMTimer(Sender: TObject);
begin
TM.Enabled := False;
try
If not ConnectParams then
Exit;
ReadMailList;
finally
TM.Enabled := True;
end;
end;
/// Запись данных в лог
procedure TLsrmMailSend.ToLogFile(const Str: string);
var
FFile: TextFile;
begin
if SaveInLog = slNo then
Exit;
try
try
AssignFile( FFile, LogFileName );
If FileExists( LogFileName ) then
Append( FFile )
else
Rewrite( FFile );
Writeln( FFile, Str + #9 + DateTimeToStr( Now ));
except
// Если не удалось записать, то значит не судьба.
end;
finally
CloseFile( FFile );
end;
end;
/// имя лог файла
function TLsrmMailSend.GetLogFileName: String;
function GetLogPathDefault: String;
begin
Result := ExtractFileDir( ParamStr( 0 ));
Result := IncludeTrailingPathDelimiter( IncludeTrailingPathDelimiter( Result ) + 'LOG' );
end;
const
LogName = 'Log.txt';
begin
Result := GetLogPathDefault + LogName;
If not DirectoryExists( ExtractFileDir( Result )) then
ForceDirectories( ExtractFileDir( Result ));
end;
procedure TLsrmMailSend.SaveResult( IsSend: Boolean; const ResultText: String);
begin
If not IBTr_Write.InTransaction then
IBTr_Write.StartTransaction;
try
case IsSend of
True:
Q_Save.ParamByName( 'DATE_SEND' ).AsDateTime := Now;
else
Q_Save.ParamByName( 'DATE_SEND' ).Clear;
end;
Q_Save.ParamByName( 'SUBSCRIBE_LIST_ID' ).AsInteger := Q_Mess.FieldByName( 'SUBSCRIBE_LIST_ID' ).AsInteger;
Q_Save.ParamByName( 'CLIENTS_MAIL_LIST_ID' ).AsInteger := Q_Mess.FieldByName( 'CLIENTS_MAIL_LIST_ID' ).AsInteger;
Q_Save.ParamByName( 'ERROR_TEXT' ).AsString := ResultText;
Q_Save.ParamByName( 'IS_OK' ).AsInteger := Integer( IsSend );
try
Q_Save.ExecSQL;
if SaveInLog = slAll then
ToLogFile( Format( 'Запись результата отправки: "%S"', [ ResultText ]) );
except
on E: Exception do begin
ToLogFile( E.Message );
If IBTr_Write.InTransaction then
IBTr_Write.Rollback;
end;
end;
finally
If IBTr_Write.InTransaction then
IBTr_Write.Commit;
end;
end;
procedure TLsrmMailSend.ServiceCreate(Sender: TObject);
begin
// sleep( 5000 );
IniPath := IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))) + 'Login.ini';
GetFormatSettings;
SysLocale.PriLangID := LANG_RUSSIAN;
SysLocale.SubLangID := SUBLANG_ENGLISH_US;
SaveInLog := TSaveInLog( IniGetIntegerDef( IniPath, 'LOG_FILE', 'SaveInLog', 0 ));
SMTP.Host := IniGetString( IniPath, 'MAIL_SERVER', 'ServerName' );
SMTP.Username := IniGetString( IniPath, 'MAIL_SERVER', 'Login' );
SMTP.Password := IniGetString( IniPath, 'MAIL_SERVER', 'Pass' );
SMTP.Port := IniGetInteger( IniPath, 'MAIL_SERVER', 'Port' );
// Mess.From.Domain := IniGetString( IniPath, 'MAIL_SERVER', 'Domain' );
Mess.From.Address := IniGetString( IniPath, 'MAIL_SERVER', 'FromAddress' );
// Mess.From.User := SMTP.Username;
Mess.Sender.Address := IniGetString( IniPath, 'MAIL_SERVER', 'FromAddress' );
// Mess.Sender.User := SMTP.Username;
OpenSSL.Destination := SMTP.Host + ':' + IntToStr( SMTP.Port );
OpenSSL.Host := SMTP.Host;
OpenSSL.Port := SMTP.Port;
OpenSSL.DefaultPort := 0;
OpenSSL.SSLOptions.Method := sslvTLSv1;
OpenSSL.SSLOptions.Mode := sslmUnassigned;
// SMTP.UseTLS := utUseExplicitTLS;
end;
function TLsrmMailSend.ConnectParams: Boolean;
begin
IBDB.Close;
sleep( 1000 );
IBDB.Params.Clear;
try
IBDB.Params.Values[ 'user_name' ] := IniGetString(IniPath, 'User', 'Login' );
IBDB.Params.Values[ 'password' ] := IniGetString(IniPath, 'User', 'Pass' );
IBDB.Params.Values[ 'sql_role_name' ] := IniGetString(IniPath, 'User', 'Role' );
IBDB.Params.Values[ 'lc_ctype' ] := 'WIN1251';
IBDB.DatabaseName := IniGetString(IniPath, 'Base', 'Path' );
if SaveInLog = slAll then begin
ToLogFile( IBDB.DatabaseName );
ToLogFile( IBDB.Params.Text );
end;
try
IBDB.Connected := True;
if SaveInLog = slAll then
ToLogFile( 'IBDB.Connected := True' );
IBTr_Read.StartTransaction;
IBEvent.AutoRegister := True;
except
on E: Exception do begin
ToLogFile( 'Ошибка коннекта к базе' + #13#10 + E.Message );
end;
end;
finally
Result := IBDB.Connected;
end;
end;
procedure TLsrmMailSend.ServiceExecute(Sender: TService);
begin
ToLogFile( 'Start' );
If ConnectParams then begin
sleep( 1000 );
ReadMailList;
end
else
Self.Status := csStopped;
If not Terminated then
ServiceThread.ProcessRequests(True);
end;
procedure TLsrmMailSend.ReadMailList;
var
ResultText: String;
IsSend: Boolean;
begin
TM.Enabled := False;
SaveInLog := TSaveInLog( IniGetIntegerDef( IniPath, 'LOG_FILE', 'SaveInLog', 0 ));
TM.Interval := tiBig; // Интервал для повторного запуска при отсутствии событий в базе (контрольная проверка)
try
if SaveInLog = slAll then
ToLogFile( 'Чтение списка для отправки' );
try
if not IBTr_Read.InTransaction then
IBTr_Read.StartTransaction;
try
Q_Mess.Open;
except
on E: Exception do
ToLogFile( 'Чтение списка: ' + #13#10 + E.Message );
end;
while not Q_Mess.Eof do begin
IsSend := SendToEMail( ResultText );
SaveResult( IsSend, ResultText );
Q_Mess.Next;
end;
finally
Q_Mess.Close;
end;
finally
TM.Enabled := True;
end;
end;
function TLsrmMailSend.MailBodyReplaceLabel(BodyValue: String): String;
var
FName: String;
begin
Result := StringReplace( BodyValue, 'src="images/', ' src="cid:', [ rfReplaceAll, rfIgnoreCase ]);
Q_LabelList.Close;
Q_LabelList.Open;
Q_LabelList.First;
while not Q_LabelList.Eof do begin
FName := Q_LabelList.FieldByName( 'MAIL_BASE_LABEL_NAME' ).AsString;
if Assigned( Q_LabelValue.FindField( FName )) then begin
Result :=
StringReplace( Result,
'####' + FName + '###',
Q_LabelValue.FieldByName( FName ).AsString,
[ rfReplaceAll, rfIgnoreCase ]);
end;
Q_LabelList.Next;
end;
end;
procedure TLsrmMailSend.Q_LabelValueBeforeOpen(DataSet: TDataSet);
begin
Q_LabelValue.ParamByName( 'SUBSCRIBE_LIST_ID' ).AsInteger := Q_MEss.FieldByName( 'SUBSCRIBE_LIST_ID' ).AsInteger;
Q_LabelValue.ParamByName( 'CLIENTS_MAIL_LIST_ID' ).AsInteger := Q_MEss.FieldByName( 'CLIENTS_MAIL_LIST_ID' ).AsInteger;
end;
function TLsrmMailSend.SendToEMail( var ResultText: String ): Boolean;
const
rsOK = 'Отправлено';
rsErr = 'Ошибка отправки';
var
TestMail, BodySource: String;
begin
Result := false;
ResultText := '';
if SaveInLog = slAll then
ToLogFile( '********************************************' );
try
try
if SaveInLog = slAll then
ToLogFile( 'Соединение с сервером почты' );
SMTP.Connect;
except
on E: Exception do begin
ToLogFile( E.Message );
Exit;
end;
end;
try
if SaveInLog = slAll then
ToLogFile( Format( 'Connected = %D ', [ Integer( SMTP.Connected )]) );
try
Mess.ContentType := 'multipart/mixed'; //'multipart/mixed';
Mess.MessageParts.Clear;
Mess.CharSet := 'utf-8';
Mess.Date := Date + Time;
Mess.Subject := Q_Mess.FieldByName( 'SUBJECT' ).AsString;
Mess.Body.Clear;
with TIdText.Create( Mess.MessageParts ) do begin
ContentType := 'multipart/related; type="multipart/alternative"';
end;
with TIdText.Create( Mess.MessageParts ) do begin
ContentType := 'multipart/alternative';
ParentPart := 0;
end;
Q_LabelValue.Close;
Q_LabelValue.Open;
with TIdText.Create( Mess.MessageParts ) do begin
Body.Text :=
String( AnsiToUtf8( MailBodyReplaceLabel( Q_Mess.FieldByName( 'BODY_TEXT' ).AsString )));
ContentType := 'text/plain';
CharSet := 'utf-8';
ParentPart := 1;
end;
with TIdText.Create( Mess.MessageParts ) do begin
BodySource := MailBodyReplaceLabel( Q_Mess.FieldByName( 'MAIL_BODY' ).AsString );
ContentType := 'text/html';
CharSet := 'utf-8';
ParentPart := 1;
AddAttachmentFile( BodySource );
Body.Text :=
String( AnsiToUtf8( BodySource ));
end;
TestMail := Trim( IniGetString(IniPath, 'TEST_MODE', 'E_Mail' ));
if TestMail <> '' then
Mess.Recipients.EMailAddresses := TestMail
else
Mess.Recipients.EMailAddresses := Q_Mess.FieldByName( 'E_MAIL' ).AsString;
Mess.CCList.EMailAddresses := Q_Mess.FieldByName( 'COPY_ADDRESS' ).AsString;
Mess.ReplyTo.EMailAddresses := Q_Mess.FieldByName( 'REPLY_ADDRESS' ).AsString;
if SaveInLog = slAll then begin
ToLogFile( Format( 'Тема: "%S"', [ Mess.Subject ]));
ToLogFile( Format( 'Отправка для "%S"', [ Mess.Recipients.EMailAddresses ]));
ToLogFile( Format( 'Кодировка "%S"', [ Mess.ContentType ]));
end;
Mess.CharSet := 'utf-8';
except on E: Exception do
ToLogFile( E.Message );
end;
If SMTP.Connected {and SMTP.Authenticate} then
try
SMTP.Send( Mess );
ResultText := rsOK;
if SaveInLog = slAll then
ToLogFile( 'Сообщение отправлено!' );
except
on E: Exception do begin
ResultText := rsErr + #13#10 + E.Message;
ToLogFile( ResultText );
Exit;
end;
end;
finally
if SaveInLog = slAll then
ToLogFile( ResultText );
SMTP.Disconnect;
Q_LabelValue.Close;
end;
finally
Result := ResultText = rsOK;
end;
end;
procedure TLsrmMailSend.AddAttachmentFile( var Body: String );
var
ST: TMemoryStream;
ContentName: String;
begin
if SaveInLog = slAll then
ToLogFile( Format( 'Добавить attach: "%D"', [ Q_Mess.FieldByName( 'SUBSCRIBE_LIST_ID' ).AsInteger ]) );
Q_MessAttach.Close;
Q_MessAttach.ParamByName( 'SUBSCRIBE_LIST_ID' ).AsInteger :=
Q_Mess.FieldByName( 'SUBSCRIBE_LIST_ID' ).AsInteger;
try
Q_MessAttach.Open;
except
on E: Exception do
ToLogFile( 'Добавить attach ' + #13#10 + E.Message );
end;
If Q_MessAttach.Eof and Q_MessAttach.Bof then begin
if SaveInLog = slAll then
ToLogFile( 'attach не найден' );
Exit;
end;
ST := TMemoryStream.Create;
try
while not Q_MessAttach.Eof do begin
ST.Clear;
try
TBlobField( Q_MessAttach.FieldByName( 'FILE_BODY' )).SaveToStream( ST );
ST.Position := 0;
With TIdAttachmentFile.Create( Mess.MessageParts ) do begin
if Q_MessAttach.FieldByName( 'IS_RELATED' ).AsInteger = 1 then begin
ContentName := StrToMd5( Q_MessAttach.FieldByName( 'FILE_NAME' ).AsString );
Body := StringReplace( Body, Q_MessAttach.FieldByName( 'FILE_NAME' ).AsString, ContentName, [ rfReplaceAll, rfIgnoreCase ]);
ContentID := ContentName;
ParentPart := 0;
ContentDisposition := 'inline';
end;
ContentType := 'image/' + StringReplace( ExtractFileExt( Q_MessAttach.FieldByName( 'FILE_NAME' ).AsString ), '.', '', []);
FileName := Q_MessAttach.FieldByName( 'FILE_NAME' ).AsString;
LoadFromStream( ST );
if SaveInLog = slAll then
ToLogFile( Format( 'Add "%S" "%S"', [ FileName, ContentName ]));
end;
except
on E:Exception do
ToLogFile( 'Ошибка при добавлении вложения'+ #13#10 + E.Message );
end;
Q_MessAttach.Next;
Sleep( 1000 );
end;
finally
ST.Free;
end;
end;
procedure TLsrmMailSend.ServiceShutdown(Sender: TService);
begin
Self.Status := csStopped;
end;
procedure TLsrmMailSend.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
ToLogFile( 'Stop' + #13#10#13#10 );
end;
end.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// 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.
//
// Ported to Delphi by Michal Wojcik.
//
// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the GNU General Public License version 2 or later.
{$H+}
//TODO This is very limited port
unit StreamReader;
interface
uses
InputStream;
type
TStreamReader = class(TObject)
private
stream : TInputStream;
public
constructor Create(input : TInputStream);
function read(size : Integer) : string;
function readBytes(size : Integer) : string;
function readLine() : string;
function isEof() : Boolean;
end;
implementation
uses
IdTCPStream,
Classes,
IdIOHandler;
{ TStreamReader }
constructor TStreamReader.Create(input : TInputStream);
begin
inherited Create;
stream := input;
end;
function TStreamReader.isEof : Boolean;
begin
Result := stream.isEof;
end;
function TStreamReader.read(size : Integer) : string;
var
S : string;
l : Integer;
begin
// TODO Ugly quick fix
if (stream.stream is TIdTCPStream) then
begin
Result := (stream.stream as TIdTCPStream).Connection.IOHandler.ReadString(size);
exit;
end;
SetString(S, nil, Size);
l := Stream.stream.Read(Pointer(S)^, Size);
Result := Copy(S, 1, l);
end;
function TStreamReader.readBytes(size : Integer) : string;
begin
Result := read(size); //TODO
end;
function TStreamReader.readLine : string;
var
s : string;
begin
// TODO Ugly quick fix
if (stream.stream is TIdTCPStream) then
begin
Result := (stream.stream as TIdTCPStream).Connection.IOHandler.ReadLn;
exit;
end;
Result := '';
while not stream.isEof do
begin
s := read(1);
if s = #13 then // TODO #13 case, slow
begin
s := read(1);
if s = #10 then // TODO #10 case, slow
break
else
stream.stream.Position := stream.stream.Position - 1;
end
else
Result := Result + s;
end;
end;
end.
|
unit ufrmQueryConfig3;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
System.Types,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TfrmQueryConfig3 = class(TForm)
btnOk: TButton;
edtIdenticalColCount: TEdit;
Label3: TLabel;
edtCompareRowCount: TEdit;
Label4: TLabel;
Label1: TLabel;
Label2: TLabel;
edtIntervalValue: TEdit;
edtIntervalValue2: TEdit;
Label5: TLabel;
procedure btnOkClick(Sender: TObject);
private
fIntervalValues: TWordDynArray;
fIdenticalColCount: Word;
fCompareRowCount: Word;
public
property IntervalValues: TWordDynArray read fIntervalValues;
property IdenticalColCount: Word read fIdenticalColCount;
property CompareRowCount: Word read fCompareRowCount;
end;
var
frmQueryConfig3: TfrmQueryConfig3;
implementation
{$R *.dfm}
procedure TfrmQueryConfig3.btnOkClick(Sender: TObject);
var
v, v2: Integer;
begin
if not (TryStrToInt(edtIntervalValue.Text, v) and (v >= 1) and (v <= 256)) then
begin
edtIntervalValue.SetFocus;
edtIntervalValue.SelectAll;
raise Exception.Create('请输入有效值');
end;
if not (TryStrToInt(edtIntervalValue2.Text, v2) and (v2 >= 0) and (v2 < 256)) then
begin
edtIntervalValue2.SetFocus;
edtIntervalValue2.SelectAll;
raise Exception.Create('请输入有效值');
end;
if v + v2 > 256 then raise Exception.Create('总列数不能超过256');
SetLength(fIntervalValues, 1);
fIntervalValues[0] := v;
if v2 > 0 then
begin
SetLength(fIntervalValues, 2);
fIntervalValues[1] := v2;
end;
if not (TryStrToInt(edtIdenticalColCount.Text, v) and (v >= 0)) then
begin
edtIdenticalColCount.SetFocus;
edtIdenticalColCount.SelectAll;
raise Exception.Create('请输入有效值');
end;
fIdenticalColCount := v;
if not (TryStrToInt(edtCompareRowCount.Text, v) and (v > 0)) then
begin
edtCompareRowCount.SetFocus;
edtCompareRowCount.SelectAll;
raise Exception.Create('请输入有效值');
end;
fCompareRowCount := v;
ModalResult := mrOK;
end;
end.
|
/// <summary>
/// Модуль содержит описание классов для получения сведений о версии
/// приложения
/// </summary>
unit AppInfo;
interface
uses
System.SysUtils, System.Classes, VerInfo;
type
/// <summary>
/// Класс, обеспечивающий получение сведений о версии программы, а также
/// дополнительных сведений о приложении и его разработчике
/// </summary>
TApplicationInfo = record
private
class function ApplicationExeName: string; static;
public
const
AppGUID = '{977D2D66-DBCE-44D7-979C-41EFDD52AD29}';
AppPublisherUrl = 'www.somesite.ru';
AppSupportUrl = 'www.somesite.ru/support';
AppUpdatesUrl = 'www.somesite.ru/support/updates/idb';
AppWikiUrl = 'www.somesite.ru/support/wiki/idb';
AppContact = 'somesite@somesite.ru';
/// <summary>
/// Версия файла приложения
/// </summary>
class function FileVersion: String; static;
/// <summary>
/// Версия программного продукта
/// </summary>
class function ProductVersion: String; static;
/// <summary>
/// Старший номер версии файла приложения
/// </summary>
class function FileVersionMajor: Cardinal; static;
/// <summary>
/// Младший номер версии файла приложения
/// </summary>
class function FileVersionMinor: Cardinal; static;
/// <summary>
/// Номер релиза версии файла приложения
/// </summary>
class function FileVersionRelease: Cardinal; static;
/// <summary>
/// Номер сборки файла приложения
/// </summary>
class function FileVersionBuild: Cardinal; static;
/// <summary>
/// Старший номер версии программного продукта
/// </summary>
class function ProductVersionMajor: Cardinal; static;
/// <summary>
/// Младший номер версии программного продукта
/// </summary>
class function ProductVersionMinor: Cardinal; static;
/// <summary>
/// Номер релиза программного продукта
/// </summary>
class function ProductVersionRelease: Cardinal; static;
/// <summary>
/// Номер сборки программного продукта
/// </summary>
class function ProductVersionBuild: Cardinal; static;
/// <summary>
/// Комментарии к приложению
/// </summary>
class function Comments: string; static;
/// <summary>
/// Дата компиляции приложения
/// </summary>
/// <remarks>
/// В ресурсе должно храниться значение "Last Compile"
/// </remarks>
class function LastCompile: string; static;
end;
implementation
uses Forms;
{ TApplicationInfo }
class function TApplicationInfo.ApplicationExeName: string;
begin
Result := Application.ExeName;
end;
class function TApplicationInfo.Comments: string;
var
vir: TVerInfoRes;
begin
Result := EmptyStr;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.Comments;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.FileVersion: String;
var
vir: TVerInfoRes;
begin
Result := EmptyStr;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.FileVersion;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.FileVersionBuild: Cardinal;
var
vir: TVerInfoRes;
begin
Result := 0;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.FileVersionBuild;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.FileVersionMajor: Cardinal;
var
vir: TVerInfoRes;
begin
Result := 0;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.FileVersionMajor;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.FileVersionMinor: Cardinal;
var
vir: TVerInfoRes;
begin
Result := 0;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.FileVersionMinor;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.FileVersionRelease: Cardinal;
var
vir: TVerInfoRes;
begin
Result := 0;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.FileVersionRelease;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.LastCompile: string;
var
vir: TVerInfoRes;
begin
Result := EmptyStr;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.GetUserDefKeyString('Last Compile');
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.ProductVersion: String;
var
vir: TVerInfoRes;
begin
Result := EmptyStr;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.ProductVersion;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.ProductVersionBuild: Cardinal;
var
vir: TVerInfoRes;
begin
Result := 0;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.ProductVersionBuild;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.ProductVersionMajor: Cardinal;
var
vir: TVerInfoRes;
begin
Result := 0;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.ProductVersionMajor;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.ProductVersionMinor: Cardinal;
var
vir: TVerInfoRes;
begin
Result := 0;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.ProductVersionMinor;
finally
FreeAndNil(vir);
end;
end;
class function TApplicationInfo.ProductVersionRelease: Cardinal;
var
vir: TVerInfoRes;
begin
Result := 0;
if not TVerInfoRes.VersionResourceAvailable(ApplicationExeName) then Exit;
vir := TVerInfoRes.Create(ApplicationExeName);
try
Result := vir.ProductVersionRelease;
finally
FreeAndNil(vir);
end;
end;
end.
|
unit DUTrees;
interface
{$DEFINE USE_TREENT}
uses {$IFDEF USE_TREENT}TreeNT{$ELSE}ComCtrls{$ENDIF}, SysUtils;
{$IFDEF USE_TREENT}
type
TTreeNode=TTreeNTNode;
TTreeView=TTreeNT;
{$ENDIF}
procedure DirToTree(const ADirectory: string; var Tree: TTreeView; Start: TTreeNode);
Function GetTreeNodePath(ANode: TTreenode; ADelimiter: Char='\'): String;
implementation
procedure DirToTree(const ADirectory: string; var Tree: TTreeView; Start: TTreeNode);
function SlashSep(const Path, S: string): string;
begin
if AnsiLastChar(Path)^ <> '\' then
Result := Path + '\' + S else
Result := Path + S;
end;
var SearchRec: TSearchRec;
NewNode: TTreeNode;
begin
if FindFirst(SlashSep(ADirectory, '*.*'), faAnyFile, SearchRec) = 0 then begin
try
repeat
if ((SearchRec.Attr and faDirectory) <> 0) then begin
if ((SearchRec.Name <> '.') and (SearchRec.Name <> '..')) then begin
NewNode:=Tree.Items.AddChild(Start, SearchRec.Name);
DirToTree(SlashSep(ADirectory, SearchRec.Name), Tree, NewNode);
end;
end;
until FindNext(SearchRec) <> 0;
finally
SysUtils.FindClose(SearchRec);
end;
end;
end;
Function GetTreeNodePath(ANode: TTreenode; ADelimiter: Char='\'): String;
Begin
Result := '';
while assigned(ANode) do
begin
Result := ADelimiter + aNode.Text + Result;
ANode := ANode.Parent;
end;
if Result <> '' then
Delete(Result,1,1);
End;
end.
|
{==============================================================================|
| Project : PIC_downloader | 1.0.8.0 |
|==============================================================================|
| PIC downloader Copyright (C)2000-2001 EHL elektronika |
| Freely distributable. |
| NO WARRANTY is given by EHL elektronika. |
|==============================================================================|
| The Developer of the Original Code is Petr Kolomaznik (Czech Republic). |
| http://www.ehl.cz/pic |
| email: kolomaznik@ehl.cz |
|==============================================================================|
| Note: The code is developed and primary tested on Delphi 5.0 under |
| Windows 95. |
|==============================================================================|
| History: |
| 1.0.3.0 23.8.2000 |
| -present version |
| 1.0.4.0 5.10.2000 |
| -RESET and trigger pin control |
| 1.0.5.0 12.10.2000 |
| -correction for CCS compiler hex file |
| -check empty line in hex file, new message 'Empty line number xx !' |
| -correction for ini file in the root directory |
| 1.0.7.0 15.11.2000 |
| -better synchronization between bootloader and downloader |
| -add COM5 and COM6 |
| -add 38400 and 56000 baud rate speed |
| -add CANCEL button |
| 1.0.8.0 25.7.2001 |
| -open hex file automatically as parameter,PIC downloader.exe [file name]|
|==============================================================================}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
unit Main;
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, ExtCtrls, IniFiles, Buttons;
type
TMainForm = class(TForm)
Label2: TLabel;
Button1: TButton;
Edit1: TEdit;
Label3: TLabel;
Label4: TLabel;
ComboBox2: TComboBox;
OpenDialog1: TOpenDialog;
Button2: TButton;
Edit2: TEdit;
Bevel1: TBevel;
ProgressBar1: TProgressBar;
Bevel2: TBevel;
Label1: TLabel;
ComboBox1: TComboBox;
Label5: TLabel;
CheckBox1: TCheckBox;
Timer1: TTimer;
Label6: TLabel;
Label7: TLabel;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Programing (Jmeno_Souboru: string; System: integer; Port: integer);
procedure Button2Click(Sender: TObject);
function OpenCom(SerLinka : PChar) : boolean;
procedure CloseCom();
function Communication(Instr: byte; VysBuff : string) : boolean;
procedure ComboBox2Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure ComboBox1Change(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FileSearch();
private
{ Private declarations }
public
{ Public declarations }
end;
type
TSetup = record
LastFile : string;
Port : string;
Speed : string;
Eeprom : integer;
end;
var
MainForm: TMainForm;
GoProgram, InPrograming: Boolean;
hCom: THandle;
Directory: string;
IniFile: TIniFile;
Setup: TSetup;
CancelStart: Boolean;
const
READ = $E0;
RACK = $E1;
WRITE = $E3;
WOK = $E4;
WBAD = $E5;
DATA_OK = $E7;
DAT_BAD = $E8;
IDENT = $EA;
IDACK = $EB;
DONE = $ED;
ApplicationName = 'PIC downloader 1.08';
implementation
uses synaser {$IFDEF FPC}, LCLType {$ENDIF};
{$IFNDEF FPC}
{$R *.DFM}
{$ENDIF}
procedure TMainForm.Button1Click(Sender: TObject);
begin
FileSearch();
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
if GoProgram then Programing (Setup.LastFile, 1, 1)
else Application.MessageBox('No hex file specified or '+#10+#13+'file does not exist !', ApplicationName, MB_OK);
end;
procedure TMainForm.Programing (Jmeno_Souboru: string; System: integer; Port: integer);
var
Soubor: Textfile;
Data: string;
ComOK, EndOfRecord: boolean;
NumberOfLines, LineNumber : integer;
Received : dword;
Sended : dword;
RecBuff : array [0..1] of byte;
SendBuff : array [0..1] of byte;
AutoStart : boolean;
TimeOuts : COMMTIMEOUTS;
begin
if not InPrograming then
begin
ProgressBar1.Position := 0;
InPrograming := true;
EndOfRecord := false;
AssignFile(Soubor, Jmeno_Souboru);
if (OpenCom (PChar (Setup.Port)) = True) then //Open port
begin
EscapeCommFunction(hCom, SETDTR); // trigger pin = 0
Edit2.Text := 'Reset';
EscapeCommFunction(hCom, SETRTS); // Reset = 0
Timer1.Enabled := true;
while Timer1.Enabled do
begin
Application.ProcessMessages;
end;
Application.ProcessMessages;
EscapeCommFunction(hCom, CLRRTS); // Reset = 1
GetCommTimeouts(hCom,TimeOuts);
TimeOuts.ReadIntervalTimeout := 0;
TimeOuts.ReadTotalTimeoutMultiplier := 1;
TimeOuts.ReadTotalTimeoutConstant := 100;
SetCommTimeouts(hCom,TimeOuts);
Edit2.Text := 'Searching for bootloader.';
AutoStart := false;
CancelStart := false;
ComOK := false;
while (not AutoStart) and (not CancelStart) do
begin
Application.ProcessMessages;
PurgeComm(hCom,PURGE_TXABORT+PURGE_RXABORT+PURGE_TXCLEAR+PURGE_RXCLEAR);
SendBuff [0] := IDENT;
WriteFile(hCom, SendBuff, 1, Sended, nil); //send IDENT
ReadFile(hCom, RecBuff, 1, Received, nil); //receive IDACK
if (Received = 1) and (RecBuff[0] = IDACK) then
AutoStart := true;
end;
TimeOuts.ReadIntervalTimeout := 50;
TimeOuts.ReadTotalTimeoutMultiplier := 100;
TimeOuts.ReadTotalTimeoutConstant := 1000;
SetCommTimeouts(hCom,TimeOuts);
if AutoStart and (not CancelStart) then
begin
ComOK := true;
end;
if ComOK then
begin
Edit2.Text := 'Writing, please wait !';
NumberOfLines := 0;
Reset(Soubor);
while not EOF(Soubor) do
begin
Readln(Soubor, Data); //Number of lines
NumberOfLines := NumberOfLines +1;
end;
LineNumber := 0;
Reset(Soubor);
while not EOF(Soubor) and ComOK and not EndOfRecord do
begin
if CancelStart then
ComOK := false;
Readln(Soubor, Data); //Read one line
LineNumber := LineNumber + 1;
ProgressBar1.Position := (LineNumber*100) div NumberOfLines;
if (Length(Data) <> 0) then
begin
if (Data[1] = ':') then
begin
if ((Data [8] = '0') and (Data [9] = '0')) then
begin // if Data Record then send
if not Communication (WRITE, Data) then ComOK := false;
end
else
begin
if ((Data [8] = '0') and (Data [9] = '1')) then
begin
EndOfRecord := true; // End of File Record
end;
end;
end
else
begin
ComOK := false;
Application.MessageBox(PChar('Hex file error !'+#10+#13+'Line number '+IntToStr(LineNumber)+' does not begin with the colon !'), ApplicationName, MB_OK);
end;
end
else
begin
ComOK := false;
Application.MessageBox(PChar('Hex file error !'+#10+#13+'Empty line number '+IntToStr(LineNumber)+' !'), ApplicationName, MB_OK);
end;
end;
if ComOK then
begin
if Communication (DONE, Data) then
begin
ProgressBar1.Position := 100;
Beep();
Edit2.Text := 'All OK !';
EscapeCommFunction(hCom, CLRDTR); // trigger pin = 1
EscapeCommFunction(hCom, SETRTS); // Reset = 0
Timer1.Enabled := true;
while Timer1.Enabled do
begin
Application.ProcessMessages;
end;
EscapeCommFunction(hCom, CLRRTS); // Reset = 1
end
else
begin
ComOK := false;
end;
end;
if CancelStart then
begin
Edit2.Text := 'Cancel of writing !';
end
else
begin
if not ComOK then
begin
Edit2.Text := 'Wrong writing !';
Application.MessageBox('Writing error !', ApplicationName, MB_OK);
end;
end;
EscapeCommFunction(hCom, CLRDTR); // trigger pin = 1
CloseFile(Soubor);
end
else
begin
if not CancelStart then
begin
Edit2.Text := 'Timeout of communication !';
Application.MessageBox('Timeout of communication, '+#13+#10+'please check port and ready of PIC for download !', ApplicationName, MB_OK);
end
else
Edit2.Text := 'Cancel of searching for bootloader.';
end;
end;
CloseCom ();
InPrograming := false;
end;
end;
function TMainForm.Communication(Instr: byte; VysBuff : string) : boolean;
var
Sended : dword;
Received : dword;
CheckSum : byte;
NumberOfData, N, Pointer : byte;
RecBuff : array [0..40] of byte;
SendBuff : array [0..40] of byte;
SendLength : byte;
RecLength : byte;
Code, I, J : integer;
fSuccess : boolean;
Address : word;
begin
fSuccess := True;
Communication := True;
SendBuff[0] := Instr;
SendLength := 1;
RecLength := 1;
if Instr = WRITE then
begin
Val('$'+VysBuff[4]+VysBuff[5], I, Code);
Val('$'+VysBuff[6]+VysBuff[7], J, Code);
Address := ((I*256) + J) div 2;
if (Address >= $2000) and (Address < $2100) then
begin //don't send address from 0x2000 to 0x20FF
Communication := True;
exit;
end;
if (Address >= $2100) and (not CheckBox1.Checked) then
begin //don't send address for EEPROM
Communication := True;
exit;
end;
SendBuff[1] := Address div 256; //high byte of address
SendBuff[2] := Address - (SendBuff[1]*256); //low byte of address
Val('$'+VysBuff[2]+VysBuff[3], I, Code);
NumberOfData := I;
SendBuff[3] := NumberOfData; //number of data
CheckSum := 0;
for N := 1 to NumberOfData div 2 do
begin
Pointer := (N-1) * 4;
Val('$'+VysBuff [12+Pointer]+VysBuff[13+Pointer], I, Code);
SendBuff [5 + ((N-1)*2)] := I; //high byte of instruction
CheckSum := CheckSum + I;
Val('$'+VysBuff [10+Pointer]+VysBuff[11+Pointer], I, Code);
SendBuff [6 + ((N-1)*2)] := I; //low byte of instruction
CheckSum := CheckSum + I;
end;
SendBuff[4] := CheckSum; //checksum
SendLength := 5 + NumberOfData;
RecLength := 2; //wait for 2 bytes
end;
Application.ProcessMessages;
PurgeComm(hCom,PURGE_TXABORT+PURGE_RXABORT+PURGE_TXCLEAR+PURGE_RXCLEAR);
WriteFile(hCom, SendBuff, SendLength, Sended, nil); //send
ReadFile(hCom, RecBuff, RecLength, Received, nil); //receive
if(Received > 0) then
case Instr of
IDENT: if RecBuff[0] = IDACK then Communication := True
else Communication := False;
WRITE: if ((RecBuff[0] = DATA_OK) and (RecBuff[1] = WOK)) then Communication := True
else Communication := False;
DONE: if RecBuff[0] = WOK then Communication := True
else Communication := False;
end
else fSuccess := False;
PurgeComm(hCom,PURGE_TXABORT+PURGE_RXABORT+PURGE_TXCLEAR+PURGE_RXCLEAR);
if(not fSuccess) then begin
Application.MessageBox('Timeout of communication !', ApplicationName, MB_OK);
Communication := false;
end;
end;
function TMainForm.OpenCom(SerLinka : PChar) : boolean;
var
fSuccess : boolean;
dcb : TDCB;
TimeOuts : COMMTIMEOUTS;
begin
hCom := CreateFile(SerLinka, //open port
GENERIC_READ or GENERIC_WRITE,
0, //exclusive access
NIL, //no security attrs
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0
);
if(hCom = INVALID_HANDLE_VALUE) then begin
Application.MessageBox('Open port error !' , ApplicationName, MB_OK);
OpenCom := False;
exit;
end;
//set of parameters
fSuccess := GetCommState(hCom, dcb);
if(not fSuccess ) then begin
Application.MessageBox('Read port parameters error !', ApplicationName, MB_OK);
OpenCom := False;
exit;
end;
dcb.BaudRate := StrToInt(Setup.Speed); //change of parameters
dcb.ByteSize := 8;
dcb.Parity := NOPARITY;
dcb.StopBits := ONESTOPBIT;
dcb.Flags := $00000001; //only fBinary = 1
fSuccess := SetCommState(hCom, dcb); //write of parameters back
if(not fSuccess) then begin
Application.MessageBox('Write port parameters error !', ApplicationName, MB_OK);
OpenCom := False;
exit;
end;
//set of timeouts
TimeOuts.ReadIntervalTimeout := 50;
TimeOuts.ReadTotalTimeoutMultiplier := 100;
TimeOuts.ReadTotalTimeoutConstant := 1000;
TimeOuts.WriteTotalTimeoutMultiplier := 20;
TimeOuts.WriteTotalTimeoutConstant := 1000;
fSuccess := SetCommTimeouts(hCom,TimeOuts);
if(not fSuccess) then begin
Application.MessageBox('Set communication timeout error !', ApplicationName, MB_OK);
OpenCom := False;
exit;
end;
//clear of buffers
fSuccess := PurgeComm(hCom,PURGE_TXABORT+PURGE_RXABORT+PURGE_TXCLEAR+PURGE_RXCLEAR);
if(not fSuccess) then begin
Application.MessageBox('Clear buffers error !', ApplicationName, MB_OK);
OpenCom := False;
exit;
end;
OpenCom := True;
end;
procedure TMainForm.CloseCom(); //close port
begin
CloseHandle(hCom);
end;
procedure TMainForm.FileSearch();
begin
CancelStart := True;
OpenDialog1.Filter := 'Hex file (*.hex) | *.hex';
OpenDialog1.InitialDir := ExtractFileDir (Setup.LastFile);
OpenDialog1.FileName := ExtractFileName (Setup.LastFile);
if OpenDialog1.Execute then
try
GoProgram := True;
Setup.LastFile := OpenDialog1.FileName;
Edit1.Text := ExtractFileName (Setup.LastFile);
except
Application.MessageBox('File read error !', ApplicationName, MB_OK);
end;
end;
procedure TMainForm.ComboBox2Change(Sender: TObject);
begin
CancelStart := True;
Setup.Port := ComboBox2.Text;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
IniValueList: TStringList;
I,Code: integer;
S: string;
begin
InPrograming := false;
MainForm.Caption := ApplicationName;
Directory := GetCurrentDir;
if (Length(Directory) > 3) then
begin
Directory := Directory + '\';
end;
if FileExists(Directory+'pic.ini') then
begin
IniFile := TIniFile.Create (Directory+'pic.ini');
IniValueList := TStringList.Create;
try
IniFile.ReadSectionValues('Setup', IniValueList);
Setup.LastFile := IniValueList.Values['File'];
Setup.Port := IniValueList.Values['Port'];
Setup.Speed := IniValueList.Values['Speed'];
Val (IniValueList.Values['Eeprom'], I, Code);
Setup.Eeprom := I;
finally
IniValueList.Free;
end;
end
else
begin
IniFile := TIniFile.Create (Directory+'pic.ini'); // ini file doesn't exist
Setup.LastFile := Directory;
Setup.Port := 'COM1';
Setup.Speed := '19200';
Setup.Eeprom := 0;
end;
S := ParamStr(1);
if S <> '' then
Setup.LastFile := S;
Edit1.Text := ExtractFileName(Setup.LastFile);
if Setup.Port = 'COM1' then
ComboBox2.ItemIndex := 0
else
if Setup.Port = 'COM2' then
ComboBox2.ItemIndex := 1
else
if Setup.Port = 'COM3' then
ComboBox2.ItemIndex := 2
else
if Setup.Port = 'COM4' then
ComboBox2.ItemIndex := 3
else
if Setup.Port = 'COM5' then
ComboBox2.ItemIndex := 4
else
if Setup.Port = 'COM6' then
ComboBox2.ItemIndex := 5
else
begin
ComboBox2.ItemIndex := 0;
Setup.Port := 'COM1';
end;
if Setup.Speed = '2400' then
ComboBox1.ItemIndex := 0
else
if Setup.Speed = '4800' then
ComboBox1.ItemIndex := 1
else
if Setup.Speed = '9600' then
ComboBox1.ItemIndex := 2
else
if Setup.Speed = '19200' then
ComboBox1.ItemIndex := 3
else
if Setup.Speed = '38400' then
ComboBox1.ItemIndex := 4
else
if Setup.Speed = '56000' then
ComboBox1.ItemIndex := 5
else
begin
ComboBox1.ItemIndex := 3;
Setup.Speed := '19200';
end;
if (Setup.Eeprom = 1) then
CheckBox1.Checked := true
else
CheckBox1.Checked := false;
if (FileExists(Setup.LastFile)) then
GoProgram := True
else
GoProgram := false;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CancelStart := true;
IniFile.WriteString('Setup','File',Setup.LastFile);
IniFile.WriteString('Setup','Port',Setup.Port);
IniFile.WriteString('Setup','Speed',Setup.Speed);
IniFile.WriteString('Setup','Eeprom',IntToStr(Setup.Eeprom));
IniFile.Free;
CloseCom();
end;
procedure TMainForm.ComboBox1Change(Sender: TObject);
begin
CancelStart := True;
Setup.Speed := ComboBox1.Text;
end;
procedure TMainForm.CheckBox1Click(Sender: TObject);
begin
CancelStart := True;
if CheckBox1.Checked then
Setup.Eeprom := 1
else
Setup.Eeprom := 0;
end;
procedure TMainForm.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := false;
end;
procedure TMainForm.Button3Click(Sender: TObject);
begin
CancelStart := True;
end;
procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_F2: FileSearch();
VK_F4: begin
if GoProgram then Programing (Setup.LastFile, 1, 1)
else Application.MessageBox('No hex file specified or '+#10+#13+'file does not exist !', ApplicationName, MB_OK);
end;
VK_ESCAPE: CancelStart := true;
VK_F10: Close;
end;
end;
end.
|
unit SendOnPriceTest;
interface
uses dbTest, dbMovementTest, ObjectTest;
type
TSendOnPriceTest = class (TdbMovementTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TSendOnPrice = class(TMovementTest)
private
function InsertDefault: integer; override;
public
function InsertUpdateMovementSendOnPrice(Id: Integer; InvNumber: String; OperDate: TDateTime;
OperDatePartner: TDateTime; PriceWithVAT: Boolean;
VATPercent, ChangePercent: double;
FromId, ToId, CarId, PersonalDriverId, RouteId, RouteSortingId: Integer
): integer;
constructor Create; override;
end;
implementation
uses UtilConst, PartnerTest, UnitsTest, CurrencyTest, dbObjectTest, SysUtils,
Db, TestFramework;
{ TSendOnPrice }
constructor TSendOnPrice.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_Movement_SendOnPrice';
spSelect := 'gpSelect_Movement_SendOnPrice';
spGet := 'gpGet_Movement_SendOnPrice';
end;
function TSendOnPrice.InsertDefault: integer;
var Id: Integer;
InvNumber: String;
OperDate: TDateTime;
OperDatePartner: TDateTime;
PriceWithVAT: Boolean;
VATPercent, ChangePercent: double;
FromId, ToId, CarId, PersonalDriverId, RouteId, RouteSortingId: Integer;
begin
Id:=0;
InvNumber:='1';
OperDate:= Date;
OperDatePartner:= Date;
PriceWithVAT:=true;
VATPercent:=20;
ChangePercent:=-10;
FromId := TPartner.Create.GetDefault;
ToId := TUnit.Create.GetDefault;
CarId:=0;
PersonalDriverId:=0;
RouteId:=0;
RouteSortingId:=0;
//
result := InsertUpdateMovementSendOnPrice(Id, InvNumber, OperDate,
OperDatePartner, PriceWithVAT,
VATPercent, ChangePercent,
FromId, ToId, CarId, PersonalDriverId, RouteId, RouteSortingId);
end;
function TSendOnPrice.InsertUpdateMovementSendOnPrice(Id: Integer; InvNumber: String; OperDate: TDateTime;
OperDatePartner: TDateTime; PriceWithVAT: Boolean;
VATPercent, ChangePercent: double;
FromId, ToId, CarId, PersonalDriverId, RouteId, RouteSortingId: Integer):Integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber);
FParams.AddParam('inOperDate', ftDateTime, ptInput, OperDate);
FParams.AddParam('inOperDatePartner', ftDateTime, ptInput, OperDatePartner);
FParams.AddParam('inPriceWithVAT', ftBoolean, ptInput, PriceWithVAT);
FParams.AddParam('inVATPercent', ftFloat, ptInput, VATPercent);
FParams.AddParam('inChangePercent', ftFloat, ptInput, ChangePercent);
FParams.AddParam('inFromId', ftInteger, ptInput, FromId);
FParams.AddParam('inToId', ftInteger, ptInput, ToId);
FParams.AddParam('inCarId', ftInteger, ptInput, CarId);
FParams.AddParam('inPersonalDriverId', ftInteger, ptInput, PersonalDriverId);
FParams.AddParam('inRouteId', ftInteger, ptInput, RouteId);
FParams.AddParam('inRouteSortingId', ftInteger, ptInput, RouteSortingId);
result := InsertUpdate(FParams);
end;
{ TSendOnPriceTest }
procedure TSendOnPriceTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'Movement\SendOnPrice\';
inherited;
end;
procedure TSendOnPriceTest.Test;
var
MovementSendOnPrice: TSendOnPrice;
Id: Integer;
begin
MovementSendOnPrice := TSendOnPrice.Create;
Id := MovementSendOnPrice.InsertDefault;
// создание документа
try
// редактирование
finally
// удаление
DeleteMovement(Id);
end;
end;
initialization
// TestFramework.RegisterTest('Документы', TSendOnPriceTest.Suite);
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit RawSessionIdGeneratorImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
SessionIdGeneratorIntf,
EnvironmentIntf,
RandomIntf;
type
(*!------------------------------------------------
* basic class having capability to
* generate session id
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
TRawSessionIdGenerator = class(TInterfacedObject, ISessionIdGenerator)
protected
fEnv : ICGIEnvironment;
fRandom : IRandom;
public
constructor create(const env : ICGIEnvironment; const randInst : IRandom);
destructor destroy(); override;
(*!------------------------------------
* get session id
*-------------------------------------
* @return session id string
*-------------------------------------*)
function getSessionId() : string;
end;
implementation
uses
Unix,
SysUtils,
BaseUnix;
constructor TRawSessionIdGenerator.create(const env : ICGIEnvironment; const randInst : IRandom);
begin
inherited create();
fEnv := env;
fRandom := randInst;
end;
destructor TRawSessionIdGenerator.destroy();
begin
fEnv := nil;
fRandom := nil;
inherited destroy();
end;
(*!------------------------------------
* get session id
*-------------------------------------
* @return session id string
*-------------------------------------*)
function TRawSessionIdGenerator.getSessionId() : string;
var tv: TTimeVal;
begin
fpGetTimeOfDay (@tv, nil);
result := format(
'%s%d%d%s',
[
fEnv.remoteAddr(),
tv.tv_sec,
tv.tv_usec,
stringOf(fRandom.randomBytes(32))
]
);
end;
end.
|
unit DW.Geodetic;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
type
TGeodetic = record
public
/// <summary>
/// Calculates distance between two locations, in metres
/// </summary>
/// <remarks>
/// At present, untested. Result may vary between OS's, and might change in future if their algorithm is changed
/// </remarks>
class function DistanceBetween(const ALatitudeFrom, ALongitudeFrom, ALatitudeTo, ALongitudeTo: Double): Double; static;
end;
implementation
uses
{$IF Defined(ANDROID)}
DW.Geodetic.Android;
{$ELSEIF Defined(IOS)}
DW.Geodetic.iOS;
{$ELSE}
DW.Geodetic.Default;
{$ENDIF}
{ TGeodetic }
class function TGeodetic.DistanceBetween(const ALatitudeFrom, ALongitudeFrom, ALatitudeTo, ALongitudeTo: Double): Double;
begin
Result := TPlatformGeodetic.DistanceBetween(ALatitudeFrom, ALongitudeFrom, ALatitudeTo, ALongitudeTo);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.