text stringlengths 14 6.51M |
|---|
unit CircularUnitControl;
interface
uses
Math, TypeControl, UnitControl;
type
TCircularUnit = class (TUnit)
private
FRadius: Double;
protected
constructor Create(const id: Int64; const x: Double; const y: Double; const radius: Double);
public
function GetRadius: Double;
property Radius: Double read GetRadius;
destructor Destroy; override;
end;
TCircularUnitArray = array of TCircularUnit;
implementation
constructor TCircularUnit.Create(const id: Int64; const x: Double; const y: Double; const radius: Double);
begin
inherited Create(id, x, y);
FRadius := radius;
end;
function TCircularUnit.GetRadius: Double;
begin
result := FRadius;
end;
destructor TCircularUnit.Destroy;
begin
inherited;
end;
end.
|
unit l3DateTimeBox;
{ $Id: l3DateTimeBox.pas,v 1.3 2011/11/23 12:23:44 fireton Exp $ }
// $Log: l3DateTimeBox.pas,v $
// Revision 1.3 2011/11/23 12:23:44 fireton
// - не падаем при неправильной дате, а просто возвращаем нулевую
//
// Revision 1.2 2011/07/22 12:25:03 fireton
// - доработка
//
// Revision 1.1 2011/07/12 13:51:02 fireton
// - работа с TDateTimeBox (интеграция с MDP)
//
interface
uses
IOUnit,
l3Date;
procedure l3DateTimeToBox(const aDateTime: TDateTime; out theBox: TDateTimeBox);
function l3BoxToDateTime(const aBox: TDateTimeBox): TDateTime;
procedure l3StDateToBox(const aDate: TStDate; out theBox: TDateTimeBox);
function l3BoxToStDate(const aBox: TDateTimeBox): TStDate;
implementation
uses
DateUtils;
procedure l3DateTimeToBox(const aDateTime: TDateTime; out theBox: TDateTimeBox);
begin
with theBox do
DecodeDateTime(aDateTime, Word(rYear), Word(rMounth), Word(rDay), Word(rHour), Word(rMinute),
Word(rSecond), Word(rMillisecond));
end;
function l3BoxToDateTime(const aBox: TDateTimeBox): TDateTime;
begin
with aBox do
if not TryEncodeDateTime(rYear, rMounth, rDay, rHour, rMinute, rSecond, rMillisecond, Result) then
Result := NullDate;
end;
procedure l3StDateToBox(const aDate: TStDate; out theBox: TDateTimeBox);
begin
l3DateTimeToBox(StDateToDateTime(aDate), theBox);
end;
function l3BoxToStDate(const aBox: TDateTimeBox): TStDate;
begin
Result := DateTimeToStDate(l3BoxToDateTime(aBox));
end;
end. |
unit BookPushFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
System.Generics.Collections, Vcl.Grids, task_1;
type
TFrame1 = class(TFrame)
LinkLabel1: TLinkLabel;
NameEdit: TLabeledEdit;
AuthorEdit: TLabeledEdit;
PriceEdit: TLabeledEdit;
DescriptionEdit: TLabeledEdit;
private
public
obj: TBook;
function get_data: TDictionary<String, String>;
procedure ClearEdits;
function get_obj: TBook;
end;
implementation
{$R *.dfm}
function TFrame1.get_data;
var data: TDictionary<String, String>;
begin
data := TDictionary<String, String>.Create;
data.Add('name', self.NameEdit.Text);
data.Add('price', self.PriceEdit.Text);
data.Add('author', self.AuthorEdit.Text);
data.Add('description', self.DescriptionEdit.Text);
result := data;
end;
function TFrame1.get_obj;
var data: TDictionary<String, String>;
begin
data := self.get_data;
result := TBook.__init__(data['name'], StrToInt(data['price']), data['author'], data['description']);
end;
procedure TFrame1.ClearEdits;
var i: Integer;
begin
for i := 0 to self.ComponentCount - 1 do
if self.Components[i] is TLabeledEdit then TLabeledEdit(self.Components[i]).Clear;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clEppServer;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, Windows, msxml, ActiveX,
{$ELSE}
System.Classes, System.SysUtils, Winapi.Windows, Winapi.msxml, Winapi.ActiveX,
{$ENDIF}
clUtils, clTcpServer, clTcpServerTls, clThreadPool, clUserMgr, clTcpCommandServer, clEppUtils;
type
EclEppServerError = class(EclTcpCommandServerError);
TclEppCommandConnection = class(TclUserConnectionTls)
private
FRequest: TStrings;
FRequestLength: Integer;
FReadBytes: Integer;
FIsAuthorized: Boolean;
FUserName: string;
FClientTransactionId: string;
FLastTransactionId: Integer;
function GetLastTransactionId: string;
protected
function GetNextTransactionId: string;
procedure InitRequest(ARequestLength: Integer);
function AddRequest(ARequest: TStream): Boolean;
procedure Reset; virtual;
procedure DoDestroy; override;
public
constructor Create;
property Request: TStrings read FRequest;
property IsAuthorized: Boolean read FIsAuthorized;
property UserName: string read FUserName;
property LastTransactionId: string read GetLastTransactionId;
property ClientTransactionId: string read FClientTransactionId;
end;
TclEppAuthenticateEvent = procedure (Sender: TObject; AConnection: TclEppCommandConnection;
var Account: TclUserAccountItem; const AUserName, APassword: string; var IsAuthorized, Handled: Boolean) of object;
TclEppConnectionEvent = procedure (Sender: TObject; AConnection: TclEppCommandConnection) of object;
TclEppCommandEvent = procedure (Sender: TObject; AConnection: TclEppCommandConnection; const ACommand: IXMLDomNode;
var Handled: Boolean) of object;
TclEppResponseEvent = procedure (Sender: TObject; AConnection: TclEppCommandConnection; AResponse: TStrings) of object;
TclEppServer = class(TclTcpServerTls)
private
FVersion: string;
FManagedExtensions: TStrings;
FUserAccounts: TclUserAccountList;
FPurpose: string;
FRecipient: string;
FAccess: string;
FRetention: string;
FManagedObjects: TStrings;
FResponseLanguages: TStrings;
FOnSendResponse: TclEppResponseEvent;
FOnReceiveRequest: TclEppConnectionEvent;
FOnAuthenticate: TclEppAuthenticateEvent;
FOnReceiveCommand: TclEppCommandEvent;
function GetCaseInsensitive: Boolean;
procedure SetCaseInsensitive(const Value: Boolean);
procedure SetManagedExtensions(const Value: TStrings);
procedure SetManagedObjects(const Value: TStrings);
procedure SetResponseLanguages(const Value: TStrings);
procedure SetUserAccounts(const Value: TclUserAccountList);
function Authenticate(AConnection: TclEppCommandConnection; Account: TclUserAccountItem;
const AUserName, APassword: string): Boolean;
procedure CheckAuthorized(AConnection: TclEppCommandConnection; IsAuthorized: Boolean);
function GetResponseTitle: string;
function GetResponseLanguages: string;
function GetManagedServices: string;
function GetServerDate: string;
procedure HandleGreeting(AConnection: TclEppCommandConnection);
procedure HandleLogin(AConnection: TclEppCommandConnection; const ACommand: IXMLDomNode);
procedure HandleLogout(AConnection: TclEppCommandConnection; const ACommand: IXMLDomNode);
protected
procedure ProcessRequest(AConnection: TclEppCommandConnection; ARequest: TStream); virtual;
procedure ProcessCommand(AConnection: TclEppCommandConnection; const ACommand: IXMLDomNode); virtual;
procedure ProcessUnhandledError(AConnection: TclEppCommandConnection; E: Exception); virtual;
procedure DoAuthenticate(AConnection: TclEppCommandConnection; var Account: TclUserAccountItem;
const AUserName, APassword: string; var IsAuthorized, Handled: Boolean); virtual;
procedure DoReceiveRequest(AConnection: TclEppCommandConnection); virtual;
procedure DoReceiveCommand(AConnection: TclEppCommandConnection; const ACommand: IXMLDomNode; var Handled: Boolean); virtual;
procedure DoSendResponse(AConnection: TclEppCommandConnection; AResponse: TStrings); virtual;
function CreateDefaultConnection: TclUserConnection; override;
procedure DoAcceptConnection(AConnection: TclUserConnection; var Handled: Boolean); override;
procedure DoReadConnection(AConnection: TclUserConnection; AData: TStream); override;
procedure DoDestroy; override;
function CreateThreadPool: TclThreadPool; override;
public
constructor Create(AOwner: TComponent); override;
procedure SendResponse(AConnection: TclEppCommandConnection; AResponse: TStrings);
procedure SendResponseAndClose(AConnection: TclEppCommandConnection; AResponse: TStrings);
function GetResponseStatus(AStatusCode: Integer; const AStatusText: string): string;
function GetTransactionInfo(AConnection: TclEppCommandConnection): string;
published
property Port default DefaultEppPort;
property UserAccounts: TclUserAccountList read FUserAccounts write SetUserAccounts;
property CaseInsensitive: Boolean read GetCaseInsensitive write SetCaseInsensitive default True;
property ManagedObjects: TStrings read FManagedObjects write SetManagedObjects;
property ManagedExtensions: TStrings read FManagedExtensions write SetManagedExtensions;
property ResponseLanguages: TStrings read FResponseLanguages write SetResponseLanguages;
property Version: string read FVersion write FVersion;
property Access: string read FAccess write FAccess;
property Purpose: string read FPurpose write FPurpose;
property Recipient: string read FRecipient write FRecipient;
property Retention: string read FRetention write FRetention;
property OnAuthenticate: TclEppAuthenticateEvent read FOnAuthenticate write FOnAuthenticate;
property OnReceiveRequest: TclEppConnectionEvent read FOnReceiveRequest write FOnReceiveRequest;
property OnReceiveCommand: TclEppCommandEvent read FOnReceiveCommand write FOnReceiveCommand;
property OnSendResponse: TclEppResponseEvent read FOnSendResponse write FOnSendResponse;
end;
resourcestring
cCommandCompleted = 'Command completed successfully';
cCommandCompletedEndSession = 'Command completed successfully; ending session';
cUnimplementedCommand = 'Unimplemented command';
cAuthenticationError = 'Authentication error';
cCommandFailed = 'Command failed';
cCommandUseError = 'Command use error';
const
cServerTransactionPrefix = 'svtr';
cCommandCompletedCode = 1000;
cCommandCompletedEndSessionCode = 1500;
cUnimplementedCommandCode = 2101;
cAuthenticationErrorCode = 2200;
cCommandFailedCode = 2400;
cCommandUseErrorCode = 2002;
implementation
uses
clXmlUtils;
{ TclEppServer }
function TclEppServer.Authenticate(AConnection: TclEppCommandConnection; Account: TclUserAccountItem;
const AUserName, APassword: string): Boolean;
var
handled: Boolean;
begin
handled := False;
Result := False;
DoAuthenticate(AConnection, Account, AUserName, APassword, Result, handled);
if (not handled) and (Account <> nil) then
begin
Result := Account.Authenticate(APassword);
end;
end;
procedure TclEppServer.CheckAuthorized(AConnection: TclEppCommandConnection; IsAuthorized: Boolean);
begin
if (Guard <> nil) then
begin
IsAuthorized := Guard.Login(AConnection.UserName, IsAuthorized, AConnection.PeerIP, Port);
end;
if (not IsAuthorized) then
begin
raise EclEppServerError.Create('login', cAuthenticationError, cAuthenticationErrorCode);
end;
end;
constructor TclEppServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FUserAccounts := TclUserAccountList.Create(Self, TclUserAccountItem);
CaseInsensitive := True;
Port := DefaultEppPort;
ServerName := 'Clever Internet Suite EPP service';
FManagedObjects := TStringList.Create();
FManagedExtensions := TStringList.Create();
FResponseLanguages := TStringList.Create();
FResponseLanguages.Add('en');
FVersion := '1.0';
FAccess := '<all/>';
FPurpose := '<admin/><other/><prov/>';
FRecipient := '<ours/><public/><unrelated/>';
FRetention := '<indefinite/>';
end;
function TclEppServer.CreateDefaultConnection: TclUserConnection;
begin
Result := TclEppCommandConnection.Create();
end;
function TclEppServer.CreateThreadPool: TclThreadPool;
begin
Result := inherited CreateThreadPool();
Result.InitializeCOM := True;
end;
procedure TclEppServer.DoAcceptConnection(AConnection: TclUserConnection; var Handled: Boolean);
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end;
{$ENDIF}
{$ENDIF}
inherited DoAcceptConnection(AConnection, Handled);
if Handled then Exit;
try
HandleGreeting(TclEppCommandConnection(AConnection));
except
on E: Exception do
begin
ProcessUnhandledError(TclEppCommandConnection(AConnection), E);
raise;
end;
end;
end;
procedure TclEppServer.DoAuthenticate(AConnection: TclEppCommandConnection; var Account: TclUserAccountItem;
const AUserName, APassword: string; var IsAuthorized, Handled: Boolean);
begin
if Assigned(OnAuthenticate) then
begin
OnAuthenticate(Self, AConnection, Account, AUserName, APassword, IsAuthorized, Handled);
end;
end;
procedure TclEppServer.DoDestroy;
begin
FResponseLanguages.Free();
FManagedExtensions.Free();
FManagedObjects.Free();
FUserAccounts.Free();
inherited DoDestroy();
end;
procedure TclEppServer.DoReadConnection(AConnection: TclUserConnection; AData: TStream);
var
connection: TclEppCommandConnection;
response: TStrings;
begin
inherited DoReadConnection(AConnection, AData);
connection := TclEppCommandConnection(AConnection);
try
ProcessRequest(connection, AData);
except
on E: EclTcpCommandServerError do
begin
response := TStringList.Create();
try
response.Add(GetResponseTitle());
response.Add('<response>');
response.Add(GetResponseStatus(E.ErrorCode, E.Message));
response.Add(GetTransactionInfo(connection));
response.Add('</response>');
response.Add('</epp>');
if (E.NeedClose) then
begin
SendResponseAndClose(connection, response);
end else
begin
SendResponse(connection, response);
end;
finally
response.Free();
end;
end;
on EAbort do ;
on E: Exception do
begin
ProcessUnhandledError(connection, E);
raise;
end;
end;
end;
procedure TclEppServer.DoReceiveCommand(AConnection: TclEppCommandConnection; const ACommand: IXMLDomNode; var Handled: Boolean);
begin
if Assigned(OnReceiveCommand) then
begin
OnReceiveCommand(Self, AConnection, ACommand, Handled);
end;
end;
procedure TclEppServer.DoReceiveRequest(AConnection: TclEppCommandConnection);
begin
if Assigned(OnReceiveRequest) then
begin
OnReceiveRequest(Self, AConnection);
end;
end;
procedure TclEppServer.DoSendResponse(AConnection: TclEppCommandConnection; AResponse: TStrings);
begin
if Assigned(OnSendResponse) then
begin
OnSendResponse(Self, AConnection, AResponse);
end;
end;
function TclEppServer.GetCaseInsensitive: Boolean;
begin
Result := FUserAccounts.CaseInsensitive;
end;
function TclEppServer.GetManagedServices: string;
var
i: Integer;
begin
if (ManagedObjects.Count < 1) then
begin
raise EclEppServerError.Create('greeting', cCommandFailed, cCommandFailedCode);
end;
Result := '';
for i := 0 to ManagedObjects.Count - 1 do
begin
Result := Result + '<objURI>' + ManagedObjects[i] + '</objURI>';
end;
if (ManagedExtensions.Count > 0) then
begin
Result := Result + '<svcExtension>';
for i := 0 to ManagedExtensions.Count - 1 do
begin
Result := Result + '<extURI>' + ManagedExtensions[i] + '</extURI>';
end;
Result := Result + '</svcExtension>';
end;
end;
function TclEppServer.GetResponseLanguages: string;
var
i: Integer;
begin
Result := '';
for i := 0 to ResponseLanguages.Count - 1 do
begin
Result := Result + '<lang>' + ResponseLanguages[i] + '</lang>';
end;
end;
function TclEppServer.GetResponseStatus(AStatusCode: Integer; const AStatusText: string): string;
begin
Result := Format('<result code="%d">', [AStatusCode]);
Result := Result + '<msg>' + AStatusText + '</msg>';
Result := Result + '</result>';
end;
function TclEppServer.GetResponseTitle: string;
begin
Result := '<?xml version="1.0" encoding="UTF-8" standalone="no"?>';
Result := Result + '<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" ';
Result := Result + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
Result := Result + 'xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd">';
end;
function TclEppServer.GetServerDate: string;
begin
Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToGlobalTime(Now()));
end;
function TclEppServer.GetTransactionInfo(AConnection: TclEppCommandConnection): string;
begin
Result := '<trID>';
Result := Result + '<clTRID>' + AConnection.ClientTransactionId + '</clTRID>';
Result := Result + AConnection.GetNextTransactionId();
Result := Result + '</trID>';
end;
procedure TclEppServer.HandleGreeting(AConnection: TclEppCommandConnection);
var
ms: TMemoryStream;
response: TStrings;
begin
ms := nil;
response := nil;
try
ms := TMemoryStream.Create();
response := TStringList.Create();
response.Add(GetResponseTitle());
response.Add('<greeting>');
response.Add('<svID>' + ServerName + '</svID>');
response.Add('<svDate>' + GetServerDate() + '</svDate>');
response.Add('<svcMenu>');
response.Add('<version>' + Version + '</version>');
response.Add(GetResponseLanguages());
response.Add(GetManagedServices());
response.Add('</svcMenu>');
response.Add('<dcp>');
response.Add('<access>' + Access + '</access>');
response.Add('<statement>');
response.Add('<purpose>' + Purpose + '</purpose>');
response.Add('<recipient>' + Recipient + '</recipient>');
response.Add('<retention>' + Retention + '</retention>');
response.Add('</statement>');
response.Add('</dcp>');
response.Add('</greeting>');
response.Add('</epp>');
SendResponse(AConnection, response);
finally
response.Free();
ms.Free();
end;
end;
procedure TclEppServer.HandleLogin(AConnection: TclEppCommandConnection; const ACommand: IXMLDomNode);
var
loginNode: IXMLDomNode;
password: string;
isAuthorized: Boolean;
response: TStrings;
begin
loginNode := GetNodeByName(ACommand, 'login');
AConnection.FUserName := GetNodeValueByName(loginNode, 'clID');
password := GetNodeValueByName(loginNode, 'pw');
isAuthorized := Authenticate(AConnection, UserAccounts.AccountByUserName(AConnection.UserName), AConnection.UserName, password);
CheckAuthorized(AConnection, isAuthorized);
AConnection.FIsAuthorized := True;
response := TStringList.Create();
try
response.Add(GetResponseTitle());
response.Add('<response>');
response.Add(GetResponseStatus(cCommandCompletedCode, cCommandCompleted));
response.Add(GetTransactionInfo(AConnection));
response.Add('</response>');
response.Add('</epp>');
SendResponse(AConnection, response);
finally
response.Free();
end;
end;
procedure TclEppServer.HandleLogout(AConnection: TclEppCommandConnection; const ACommand: IXMLDomNode);
var
response: TStrings;
begin
if (not AConnection.IsAuthorized) then
begin
raise EclEppServerError.Create('logout', cCommandUseError, cCommandUseErrorCode);
end;
response := TStringList.Create();
try
response.Add(GetResponseTitle());
response.Add('<response>');
response.Add(GetResponseStatus(cCommandCompletedEndSessionCode, cCommandCompletedEndSession));
response.Add(GetTransactionInfo(AConnection));
response.Add('</response>');
response.Add('</epp>');
SendResponse(AConnection, response);
finally
response.Free();
end;
end;
procedure TclEppServer.ProcessCommand(AConnection: TclEppCommandConnection; const ACommand: IXMLDomNode);
var
handled: Boolean;
begin
AConnection.FClientTransactionId := GetNodeValueByName(ACommand, 'clTRID');
handled := False;
DoReceiveCommand(AConnection, ACommand, handled);
if (not handled) then
begin
if (GetNodeByName(ACommand, 'login') <> nil) then
begin
HandleLogin(AConnection, ACommand);
end else
if (GetNodeByName(ACommand, 'logout') <> nil) then
begin
HandleLogout(AConnection, ACommand);
end else
begin
raise EclEppServerError.Create('unknown', cUnimplementedCommand, cUnimplementedCommandCode);
end;
end;
end;
procedure TclEppServer.ProcessRequest(AConnection: TclEppCommandConnection; ARequest: TStream);
var
doc: IXMLDomDocument;
command: IXMLDomNode;
begin
if (AConnection.AddRequest(ARequest)) then
begin
DoReceiveRequest(AConnection);
doc := CoDOMDocument.Create();
doc.loadXML(WideString(AConnection.Request.Text));
if (not doc.parsed) then
begin
raise EclEppServerError.Create('unknown', doc.parseError.reason, doc.parseError.errorCode);
end;
command := GetNodeByName(doc.documentElement, 'command');
if (command <> nil) then
begin
ProcessCommand(AConnection, command);
end else
if (GetNodeByName(doc.documentElement, 'hello') <> nil) then
begin
HandleGreeting(AConnection);
end else
begin
raise EclEppServerError.Create('unknown', cUnimplementedCommand, cUnimplementedCommandCode);
end;
end;
end;
procedure TclEppServer.ProcessUnhandledError(AConnection: TclEppCommandConnection; E: Exception);
var
response: TStrings;
begin
response := TStringList.Create();
try
response.Add(GetResponseTitle());
response.Add('<response>');
response.Add(GetResponseStatus(cCommandFailedCode, E.Message));
response.Add(GetTransactionInfo(AConnection));
response.Add('</response>');
response.Add('</epp>');
SendResponse(AConnection, response);
finally
response.Free();
end;
end;
procedure TclEppServer.SendResponse(AConnection: TclEppCommandConnection; AResponse: TStrings);
var
ms: TMemoryStream;
utils: TclStringsUtils;
begin
ms := nil;
utils := nil;
try
ms := TMemoryStream.Create();
utils := TclStringsUtils.Create(AResponse, 'UTF-8');
EppWriteInt32(ms, DWORD(utils.GetStringsSize() + 4));
utils.SaveStrings(ms);
ms.Position := 0;
AConnection.WriteData(ms);
finally
utils.Free();
ms.Free();
end;
DoSendResponse(AConnection, AResponse);
end;
procedure TclEppServer.SendResponseAndClose(AConnection: TclEppCommandConnection; AResponse: TStrings);
var
ms: TMemoryStream;
utils: TclStringsUtils;
begin
ms := nil;
utils := nil;
try
ms := TMemoryStream.Create();
utils := TclStringsUtils.Create(AResponse, 'UTF-8');
EppWriteInt32(ms, DWORD(utils.GetStringsSize() + 4));
utils.SaveStrings(ms);
ms.Position := 0;
AConnection.WriteDataAndClose(ms);
finally
utils.Free();
ms.Free();
end;
DoSendResponse(AConnection, AResponse);
end;
procedure TclEppServer.SetCaseInsensitive(const Value: Boolean);
begin
FUserAccounts.CaseInsensitive := Value;
end;
procedure TclEppServer.SetManagedExtensions(const Value: TStrings);
begin
FManagedExtensions.Assign(Value);
end;
procedure TclEppServer.SetManagedObjects(const Value: TStrings);
begin
FManagedObjects.Assign(Value);
end;
procedure TclEppServer.SetResponseLanguages(const Value: TStrings);
begin
FResponseLanguages.Assign(Value);
end;
procedure TclEppServer.SetUserAccounts(const Value: TclUserAccountList);
begin
FUserAccounts.Assign(Value);
end;
{ TclEppCommandConnection }
function TclEppCommandConnection.AddRequest(ARequest: TStream): Boolean;
var
utils: TclStringsUtils;
begin
Result := False;
if (ARequest.Size < 1) then Exit;
ARequest.Position := 0;
if (FRequestLength = 0) then
begin
InitRequest(EppReadInt32(ARequest));
FReadBytes := ARequest.Size;
Request.Clear();
end else
begin
FReadBytes := FReadBytes + ARequest.Size;
end;
utils := TclStringsUtils.Create(Request, 'UTF-8');
try
utils.BatchSize := BatchSize;
utils.AddTextStream(ARequest, True);
finally
utils.Free();
end;
if (FReadBytes >= FRequestLength) then
begin
FRequestLength := 0;
Result := True;
end;
end;
constructor TclEppCommandConnection.Create;
begin
inherited Create();
FRequest := TStringList.Create();
Reset();
end;
procedure TclEppCommandConnection.DoDestroy;
begin
FRequest.Free();
inherited DoDestroy();
end;
function TclEppCommandConnection.GetLastTransactionId: string;
begin
Result := cServerTransactionPrefix + IntToStr(FLastTransactionId);
end;
function TclEppCommandConnection.GetNextTransactionId: string;
begin
Inc(FLastTransactionId);
Result := '<svTRID>' + cServerTransactionPrefix + IntToStr(FLastTransactionId) + '</svTRID>';
end;
procedure TclEppCommandConnection.InitRequest(ARequestLength: Integer);
begin
FRequest.Clear();
FRequestLength := ARequestLength;
FReadBytes := 0;
end;
procedure TclEppCommandConnection.Reset;
begin
InitRequest(0);
FIsAuthorized := False;
FUserName := '';
FLastTransactionId := 0;
end;
end.
|
unit VoiceHandler;
interface
uses
VoyagerInterfaces, VoyagerServerInterfaces, Classes, Controls, MPlayer, ExtCtrls, StarVoice, VoicePanelViewer;
type
TVoiceHandler =
class( TInterfacedObject, IMetaURLHandler, IURLHandler )
public
constructor Create;
destructor Destroy; override;
private
fSendTimer : TTimer;
fLimitTimer : TTimer;
fVoiceObj : TVoiceChat;
fVoicePanel : TVoicePanel;
// IMetaURLHandler
private
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL( URL : TURL ) : THandlingAbility;
function Instantiate : IURLHandler;
// IURLHandler
private
function HandleURL( URL : TURL ) : TURLHandlingResult;
function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler( URLHandler : IMasterURLHandler );
private
fMasterURLHandler : IMasterURLHandler;
fClientView : IClientView;
private
procedure OnSend( Sender : TObject );
procedure OnLimitTimer( Sender : TObject );
procedure OnDSoundRequest( Sender : TVoiceChat; Request : boolean );
private
fTxId : integer;
fNewTx : integer;
fLastOnAir : string;
fLastTxId : integer;
fWasOn : boolean;
fLimitCnt : integer;
fTalkRequest : boolean;
fIgnoreTx : boolean;
private
procedure StartOfVoiceRecording;
procedure EndOfVoiceRecording;
private
procedure threadedVoiceThis( const parms : array of const );
procedure threadedRequestVoiceTx( const parms : array of const );
procedure threadedVoiceTxOver( const parms : array of const );
procedure threadedCancelVoiceReq( const parms : array of const );
procedure threadedVoiceStatusChange( const parms : array of const );
procedure syncRequestVoiceTx( const parms : array of const );
end;
const
tidMetaHandler_Voice = 'VoiceHandler';
const
evnStartOfVoiceRecording = 3910;
evnEndOfVoiceRecording = 3911;
evnDSoundFreed = 3912;
evnDSoundRecreated = 3913;
implementation
uses
SoundLib, Events, ServerCnxEvents, Forms, Threads, SysUtils, MathUtils;
// TVoiceHandler
constructor TVoiceHandler.Create;
begin
inherited Create;
end;
destructor TVoiceHandler.Destroy;
begin
fSendTimer.Free;
fLimitTimer.Free;
fVoiceObj.Free;
fVoicePanel.Free;
inherited;
end;
function TVoiceHandler.getName : string;
begin
result := tidMetaHandler_Voice;
end;
function TVoiceHandler.getOptions : TURLHandlerOptions;
begin
result := [hopCacheable];
end;
function TVoiceHandler.getCanHandleURL( URL : TURL ) : THandlingAbility;
begin
result := 0;
end;
function TVoiceHandler.Instantiate : IURLHandler;
begin
result := self;
end;
function TVoiceHandler.HandleURL( URL : TURL ) : TURLHandlingResult;
begin
result := urlHandled;
end;
function TVoiceHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
var
VoiceMsgInfo : TVoiceMsgInfo absolute info;
//ErrorCode : TErrorCode;
begin
result := evnHandled;
case EventId of
evnVoiceMsg :
begin
//fClientView.SayThis( '', fLastOnAir + '->' + VoiceMsgInfo.From + ', NewTx: ' + IntToStr(integer(VoiceMsgInfo.NewTx)), ErrorCode );
if VoiceMsgInfo.NewTx
then fIgnoreTx := false;
if not fIgnoreTx
then
begin
if ((fLastOnAir <> VoiceMsgInfo.From) or (fLastTxId <> VoiceMsgInfo.TxId))
then
begin
fVoiceObj.ResetDecompressor;
// fClientView.SayThis( '', fLastOnAir + '->' + VoiceMsgInfo.From + '... reset was called.', ErrorCode );
fLastOnAir := VoiceMsgInfo.From;
fLastTxId := VoiceMsgInfo.TxId;
fVoicePanel.Speaker.Caption := VoiceMsgInfo.From;
end;
fVoiceObj.RecvFIFO.Write( VoiceMsgInfo.buffer, VoiceMsgInfo.len );
end;
end;
evnStartOfVoiceRecording :
begin
fTalkRequest := true;
fVoicePanel.PendingSign.PageIndex := 1;
Defer( threadedRequestVoiceTx, priNormal, [self] );
end;
evnVoiceMsgAuthorized :
if fTalkRequest
then StartOfVoiceRecording;
evnEndOfVoiceRecording :
begin
fTalkRequest := false;
EndOfVoiceRecording;
end;
evnHandlerExposed :
begin
fNewTx := 1;
fIgnoreTx := true;
Defer( threadedVoiceStatusChange, priNormal, [1] );
end;
evnHandlerUnexposed :
Defer( threadedVoiceStatusChange, priNormal, [0] );
evnLogonStarted:
fMasterURLHandler.HandleURL( '?' + 'frame_Id=' + tidMetaHandler_Voice + '&frame_Close=yes' );
end;
end;
function TVoiceHandler.getControl : TControl;
begin
if fVoicePanel = nil
then
begin
fSendTimer := TTimer.Create( nil );
fLimitTimer := TTimer.Create( nil );
fSendTimer.Enabled := false;
fSendTimer.Interval := 200;
fSendTimer.OnTimer := OnSend;
fLimitTimer.Interval := 1000;
fLimitTimer.Enabled := false;
fLimitTimer.OnTimer := OnLimitTimer;
fVoiceObj := TVoiceChat.Create( SoundLib.GetDSoundInstance );
fVoiceObj.OnDSoundRequest := OnDSoundRequest;
fVoicePanel := TVoicePanel.Create( nil );
fSendTimer.Enabled := true;
fVoiceObj.OnAir := false;
fVoicePanel.MasterURLHandler := fMasterURLHandler;
fVoicePanel.ClientView := fClientView;
end;
result := fVoicePanel;
end;
procedure TVoiceHandler.setMasterURLHandler( URLHandler : IMasterURLHandler );
begin
fMasterURLHandler := URLHandler;
URLHandler.HandleEvent( evnAnswerClientView, fClientView );
end;
procedure TVoiceHandler.OnSend( Sender : TObject );
const
BufferSize = 1024;
var
len : integer;
Buffer : array[0..pred(BufferSize)] of byte;
threadBuffer : PByteArray;
begin
repeat
fVoiceObj.SendFIFO.Read(Buffer, sizeof(Buffer), len);
if len > 0
then
begin
getmem( threadBuffer, len );
move( Buffer, threadBuffer^, len );
Defer( threadedVoiceThis, priNormal, [threadBuffer, len, fTxId, fNewTx] );
fNewTx := 0;
end;
until len = 0;
fVoiceObj.SendFIFO.GetSize( len );
if (len = 0) and not fVoiceObj.OnAir and fWasOn
then
begin
fVoiceObj.ResetCompressor;
inc( fTxId );
fNewTx := 1;
fWasOn := false;
Defer( threadedVoiceTxOver, priNormal, [self] );
end;
if fVoicePanel.VUGauge <> nil
then fVoicePanel.VUGauge.Position := round(fVoiceObj.VUMeter*100);
end;
procedure TVoiceHandler.OnLimitTimer( Sender : TObject );
const
LineLimit = 60;
BufferLimit = 20;
begin
inc( fLimitCnt );
fVoicePanel.TimeLimit.Position := (100*fLimitCnt) div LineLimit;
if fLimitCnt = LineLimit
then EndOfVoiceRecording;
end;
procedure TVoiceHandler.OnDSoundRequest( Sender : TVoiceChat; Request : boolean );
var
dummy : integer;
begin
if Request
then
begin
if SoundLib.GetLibStatus = 0
then
begin
SoundLib.InitDSoundEngine( Application.MainForm.Handle );
fMasterURLHandler.HandleEvent( evnDSoundRecreated, dummy );
end;
end
else
begin
SoundLib.DoneDSoundEngine;
fMasterURLHandler.HandleEvent( evnDSoundFreed, dummy );
end;
end;
procedure TVoiceHandler.StartOfVoiceRecording;
begin
fVoiceObj.OnAir := true;
fWasOn := true;
fLimitTimer.Enabled := true;
fVoicePanel.OnTheAirSign.PageIndex := 1;
fVoicePanel.PendingSign.PageIndex := 0;
fVoicePanel.BufferGauge.Position := 0;
fLimitCnt := 0;
end;
procedure TVoiceHandler.EndOfVoiceRecording;
begin
fVoiceObj.OnAir := false;
fVoicePanel.OnTheAirSign.PageIndex := 0;
fVoicePanel.PendingSign.PageIndex := 0;
fVoicePanel.TimeLimit.Position := 0;
fVoicePanel.BufferGauge.Position := 0;
fLimitTimer.Enabled := false;
fLimitCnt := 0;
Defer( threadedCancelVoiceReq, priNormal, [self] );
end;
procedure TVoiceHandler.threadedVoiceThis( const parms : array of const );
var
Buffer : PByteArray;
len : integer;
TxId : integer;
NewTx : integer;
ErrorCode : TErrorCode;
begin
try
Buffer := parms[0].vPointer;
len := parms[1].vInteger;
TxId := parms[2].vInteger;
NewTx := parms[3].vInteger;
try
fClientView.VoiceThis( Buffer^, Len, TxId, NewTx, ErrorCode );
finally
freemem( Buffer, len );
end;
except
end;
end;
procedure TVoiceHandler.threadedRequestVoiceTx( const parms : array of const );
var
ReqIdx : integer;
ErrorCode : TErrorCode;
begin
try
ReqIdx := fClientView.VoiceRequest( ErrorCode );
Join( syncRequestVoiceTx, [ReqIdx] );
except
end;
end;
procedure TVoiceHandler.threadedVoiceTxOver( const parms : array of const );
var
ErrorCode : TErrorCode;
begin
try
fClientView.VoiceTxOver( ErrorCode );
except
end;
end;
procedure TVoiceHandler.threadedCancelVoiceReq( const parms : array of const );
var
ErrorCode : TErrorCode;
begin
try
fClientView.CancelVoiceRequest( ErrorCode );
except
end;
end;
procedure TVoiceHandler.threadedVoiceStatusChange( const parms : array of const );
var
ErrorCode : TErrorCode;
begin
try
fClientView.VoiceStatusChanged( parms[0].vInteger, ErrorCode );
except
end;
end;
procedure TVoiceHandler.syncRequestVoiceTx( const parms : array of const );
var
ReqIdx : integer absolute parms[0].vInteger;
begin
if ReqIdx = 0
then fMasterURLHandler.HandleEvent( evnVoiceMsgAuthorized, self );
fVoicePanel.BufferGauge.Position := (100*min(4, ReqIdx)) div 4;
end;
end.
|
{
Ultibo Bitmap utility unit.
Copyright (C) 2016 - SoftOz Pty Ltd.
Arch
====
<All>
Boards
======
<All>
Licence
=======
LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt)
Credits
=======
Information for this unit was obtained from:
References
==========
uLiftBitmap
=======
Functions to draw or save a standard bitmap image to or from an Ultibo
graphics console window.
These functions originally appeared in the Ultibo forum and examples of
how to use them can be found there:
DrawBitmap: https://ultibo.org/forum/viewtopic.php?f=13&t=312
SaveBitmap: https://ultibo.org/forum/viewtopic.php?f=13&t=313
}
{$mode delphi} {Default to Delphi compatible syntax}
{$H+} {Default to AnsiString}
{$inline on} {Allow use of Inline procedures}
{$linklib dwtlift}
{$linklib libm}
unit uLiftBitmap;
interface
uses GlobalConfig,GlobalConst,GlobalTypes,Platform,Console,GraphicsConsole,Classes,SysUtils,BMPcomn,uBufferToC;
{==============================================================================}
{COMP1 TCP_DISTORATIO COMP2 FILTER}
function DrawBitmap(Handle:TWindowHandle;const Filename:String;X,Y:LongWord;DECOMP,ENCODE,COMP1,COMP2,COMP3,COMP4:Integer):Boolean;
function SaveBitmap(Handle:TWindowHandle;const Filename:String;X,Y,Width,Height,BPP:LongWord):Boolean;
{==============================================================================}
{==============================================================================}
implementation
{==============================================================================}
{==============================================================================}
function DrawBitmap(Handle:TWindowHandle;const Filename:String;X,Y:LongWord;DECOMP,ENCODE,COMP1,COMP2,COMP3,COMP4:Integer):Boolean;
{A function for drawing a standard bitmap image onto an Ultibo graphics console window}
{Handle: The handle of an existing graphics console window}
{Filename: The name of the file to load the bitmap from}
{X: The column position for the left edge of the bitmap}
{Y: The row position for the top row of the bitmap}
{Return: True if successful or False is an error occurred}
var
Size:LongWord;
Count:LongWord;
Offset:LongWord;
Format:LongWord;
Buffer:Pointer;
TopDown:Boolean;
LineSize:LongWord;
ReadSize:LongWord;
FileStream:TFileStream;
IBPP: Integer;
FILTER: Integer;
HImage:LongWord;
WImage:LongWord;
BitMapFileHeader:TBitMapFileHeader;
BitMapInfoHeader:TBitMapInfoHeader;
begin
{}
Result:=False;
ConsoleWindowWriteLn(Handle, 'Debug in uliftBitmap');
{There are a few different ways to load a bitmap file and draw it on the screen in Ultibo, in this example
we'll use a TFileStream class to read the file and then load the image data (the pixels) into a memory
buffer that we allocate. Finally we'll put the pixels onto the screen using the GraphicsWindowDrawImage()
function from the GraphicsConsole unit}
{Check the parameters}
if Handle = INVALID_HANDLE_VALUE then Exit;
if Length(Filename) = 0 then Exit;
{Check if the file exists}
if not FileExists(Filename) then Exit;
{Open the file using a TFileStream class}
FileStream:=TFileStream.Create(Filename,fmOpenRead or fmShareDenyNone);
try
{Check the file size}
if FileStream.Size < (SizeOf(TBitMapFileHeader) + SizeOf(TBitMapInfoHeader)) then Exit;
{Read the Bitmap file header}
if FileStream.Read(BitMapFileHeader,SizeOf(TBitMapFileHeader)) <> SizeOf(TBitMapFileHeader) then Exit;
{Check the magic number in the header}
if BitMapFileHeader.bfType = BMmagic then
begin
{Read the Bitmap info header}
if FileStream.Read(BitMapInfoHeader,SizeOf(TBitMapInfoHeader)) <> SizeOf(TBitMapInfoHeader) then Exit;
{Most Bitmaps are stored upside down in the file, but they can be right way up}
TopDown:=(BitMapInfoHeader.Height < 0);
BitMapInfoHeader.Height:=Abs(BitMapInfoHeader.Height);
HImage:= BitMapInfoHeader.Height;
WImage:= BitMapInfoHeader.Width;
{Check how many bits per pixel in this Bitmap, we only support 16, 24 and 32 in this function}
if BitMapInfoHeader.BitCount = 16 then
begin
{Check the compression format used, this function only supports raw RGB files so far}
if BitMapInfoHeader.Compression = BI_RGB then
begin
{Get the color format}
Format:=COLOR_FORMAT_RGB15;
{Now get the bytes per line}
LineSize:=BitMapInfoHeader.Width * 2;
{And also determine the actual number of bytes until the next line}
ReadSize:=(((BitMapInfoHeader.Width * 8 * 2) + 31) div 32) shl 2;
end
else
begin
Exit;
end;
end
else if BitMapInfoHeader.BitCount = 24 then
begin
{Check the compression}
if BitMapInfoHeader.Compression = BI_RGB then
begin
{Color format, bytes per line and actual bytes as again}
Format:=COLOR_FORMAT_RGB24;
LineSize:=BitMapInfoHeader.Width * 3;
ReadSize:=(((BitMapInfoHeader.Width * 8 * 3) + 31) div 32) shl 2;
end
else
begin
Exit;
end;
end
else if BitMapInfoHeader.BitCount = 32 then
begin
{Check the compression}
if BitMapInfoHeader.Compression = BI_RGB then
begin
{Color format, bytes per line and actual bytes as again}
Format:=COLOR_FORMAT_URGB32;
LineSize:=BitMapInfoHeader.Width * 4;
ReadSize:=(((BitMapInfoHeader.Width * 8 * 4) + 31) div 32) shl 2;
end
else
begin
Exit;
end;
end
else
begin
Exit;
end;
{Get the size of the Bitmap image not including the headers, just the actual pixels}
Size:=LineSize * BitMapInfoHeader.Height;
{Allocate a buffer to hold all the pixels}
Buffer:=GetMem(Size);
IBPP:=BitMapInfoHeader.BitCount;
try
Offset:=0;
{Check for a which way up}
if TopDown then
begin
{Right way up is a rare case}
for Count:=0 to BitMapInfoHeader.Height - 1 do
begin
{Update the position of the file stream}
FileStream.Position:=BitMapFileHeader.bfOffset + (Count * ReadSize);
{Read a full line of pixels from the file}
if FileStream.Read((Buffer + Offset)^,LineSize) <> LineSize then Exit;
{Update the offset of our buffer}
Inc(Offset,LineSize);
end;
end
else
begin
{Upside down is the normal case}
for Count:=BitMapInfoHeader.Height - 1 downto 0 do
begin
{Update the position of the file stream}
FileStream.Position:=BitMapFileHeader.bfOffset + (Count * ReadSize);
{Read a full line of pixels from the file}
if FileStream.Read((Buffer + Offset)^,LineSize) <> LineSize then Exit;
{Update the offset of our buffer}
Inc(Offset,LineSize);
end;
end;
ConsoleWindowWrite(Handle, 'Debug in uliftBitmap checking ENCODE ' + intToStr(ENCODE));
{Draw the entire image onto our graphics console window in one request}
//if GraphicsWindowDrawImage(Handle,X,Y,Buffer,BitMapInfoHeader.Width,BitMapInfoHeader.Height,Format) <> ERROR_SUCCESS then Exit;
if(ENCODE=1) then lift_config(DECOMP,ENCODE,COMP1,COMP2,COMP3,COMP4,IBPP,Size,HImage,WImage,Buffer);
ConsoleWindowWrite(Handle, 'Debug in uliftBitmap Calling C lift_config');
if GraphicsWindowDrawImage(Handle,X,Y,Buffer,BitMapInfoHeader.Width,BitMapInfoHeader.Height,Format) <> ERROR_SUCCESS then Exit;
Result:=True;
finally
FreeMem(Buffer);
end;
end;
finally
FileStream.Free;
end;
end;
{==============================================================================}
function SaveBitmap(Handle:TWindowHandle;const Filename:String;X,Y,Width,Height,BPP:LongWord):Boolean;
{A function for saving all or part of an Ultibo graphics console window to a standard bitmap file}
{Handle: The handle of an existing graphics console window}
{Filename: The name of the file to save the bitmap to}
{X: The column position for the left edge of the bitmap}
{Y: The row position for the top row of the bitmap}
{Width: The width (in pixels) of the bitmap}
{Height: The height (in pixels) of the bitmap}
{BPP: The bits per pixel value for the bitmap (eg 16, 24 or 32)}
{Return: True if successful or False is an error occurred}
var
Size:LongWord;
Count:LongWord;
Offset:LongWord;
Format:LongWord;
Buffer:Pointer;
LineSize:LongWord;
ReadSize:LongWord;
MemoryStream:TMemoryStream;
BitMapFileHeader:TBitMapFileHeader;
BitMapInfoHeader:TBitMapInfoHeader;
begin
{}
Result:=False;
try
{Saving all or part of the screen to a bitmap file can be done very simply using a number of different methods.
Here we get the image to be saved from the screen in a single to call GraphicsWindowGetImage() which copies the
image to a memory buffer we provide. From there we use a TMemoryStream class to write each row of pixels in the
image into the correct format for storing in a BMP file and finally the memory stream is saved to a file using the
SaveToFile() method}
{Check the parameters}
if Handle = INVALID_HANDLE_VALUE then Exit;
if Length(Filename) = 0 then Exit;
if (Width = 0) or (Height = 0) then Exit;
{Check the BPP (Bits Per Pixel) value. It must be 16, 24 or 32 for this function}
if BPP = 16 then
begin
{Get the color format}
Format:=COLOR_FORMAT_RGB15;
{Work ou the number ofbytes per line}
LineSize:=Width * 2;
{And the actual number of bytes until the next line}
ReadSize:=(((Width * 8 * 2) + 31) div 32) shl 2;
end
else if BPP = 24 then
begin
{Color format, bytes per line and actual bytes again}
Format:=COLOR_FORMAT_RGB24;
LineSize:=Width * 3;
ReadSize:=(((Width * 8 * 3) + 31) div 32) shl 2;
end
else if BPP = 32 then
begin
{Color format, bytes per line and actual bytes as above}
Format:=COLOR_FORMAT_URGB32;
LineSize:=Width * 4;
ReadSize:=(((Width * 8 * 4) + 31) div 32) shl 2;
end
else
begin
Exit;
end;
{Check the file does not exist}
if FileExists(Filename) then Exit;
{Create the TMemoryStream object}
MemoryStream:=TMemoryStream.Create;
try
{Get the total size of the image in the file (not including the headers)}
Size:=ReadSize * Height;
{Set the size of the memory stream (Adding the size of the headers)}
MemoryStream.Size:=Size + SizeOf(TBitMapFileHeader) + SizeOf(TBitMapInfoHeader);
MemoryStream.Position:=0;
{Create the Bitmap file header}
FillChar(BitMapFileHeader,SizeOf(TBitMapFileHeader),0);
BitMapFileHeader.bfType:=BMmagic;
BitMapFileHeader.bfSize:=Size + SizeOf(TBitMapFileHeader) + SizeOf(TBitMapInfoHeader);
BitMapFileHeader.bfReserved:=0;
BitMapFileHeader.bfOffset:=SizeOf(TBitMapFileHeader) + SizeOf(TBitMapInfoHeader);
if MemoryStream.Write(BitMapFileHeader,SizeOf(TBitMapFileHeader)) <> SizeOf(TBitMapFileHeader) then Exit;
{And create the Bitmap info header}
FillChar(BitMapInfoHeader,SizeOf(TBitMapInfoHeader),0);
BitMapInfoHeader.Size:=SizeOf(TBitMapInfoHeader);
BitMapInfoHeader.Width:=Width;
BitMapInfoHeader.Height:=Height;
BitMapInfoHeader.Planes:=1;
BitMapInfoHeader.BitCount:=BPP;
BitMapInfoHeader.Compression:=BI_RGB;
BitMapInfoHeader.SizeImage:=Size;
BitMapInfoHeader.XPelsPerMeter:=3780; {96 DPI} {(3780 / 1000) * 25.4}
BitMapInfoHeader.YPelsPerMeter:=3780; {96 DPI} {(3780 / 1000) * 25.4}
BitMapInfoHeader.ClrUsed:=0;
BitMapInfoHeader.ClrImportant:=0;
if MemoryStream.Write(BitMapInfoHeader,SizeOf(TBitMapInfoHeader)) <> SizeOf(TBitMapInfoHeader) then Exit;
{Get the size of the pixels to be copied from the screen}
Size:=LineSize * BitMapInfoHeader.Height;
{Allocate a buffer to copy to}
Buffer:=GetMem(Size);
try
Offset:=0;
{Get the entire image from the screen into our buffer. The function will translate the colors into the format we asked for}
if GraphicsWindowGetImage(Handle,X,Y,Buffer,BitMapInfoHeader.Width,BitMapInfoHeader.Height,Format) <> ERROR_SUCCESS then Exit;
{Go through each row in the image starting at the bottom because bitmaps are normally upside down}
for Count:=BitMapInfoHeader.Height - 1 downto 0 do
begin
{Update the position of the memory stream for the next row}
MemoryStream.Position:=BitMapFileHeader.bfOffset + (Count * ReadSize);
{Write a full line of pixels to the memory stream from our buffer}
if MemoryStream.Write((Buffer + Offset)^,LineSize) <> LineSize then Exit;
{Update the offet of our buffer}
Inc(Offset,LineSize);
end;
{Write the memory stream to the file}
MemoryStream.SaveToFile(Filename);
Result:=True;
finally
FreeMem(Buffer);
end;
finally
MemoryStream.Free;
end;
except
on E: Exception do
begin
{Log an error or return a message etc}
end;
end;
end;
{==============================================================================}
{==============================================================================}
end.
|
unit VehicleUpdateControl;
interface
uses
Math, TypeControl;
type
TVehicleUpdate = class
private
FId: Int64;
FX: Double;
FY: Double;
FDurability: LongInt;
FRemainingAttackCooldownTicks: LongInt;
FSelected: Boolean;
FGroups: TLongIntArray;
public
constructor Create(const id: Int64; const x: Double; const y: Double; const durability: LongInt;
const remainingAttackCooldownTicks: LongInt; const selected: Boolean; const groups: TLongIntArray);
function GetId: Int64;
property Id: Int64 read GetId;
function GetX: Double;
property X: Double read GetX;
function GetY: Double;
property Y: Double read GetY;
function GetDurability: LongInt;
property Durability: LongInt read GetDurability;
function GetRemainingAttackCooldownTicks: LongInt;
property RemainingAttackCooldownTicks: LongInt read GetRemainingAttackCooldownTicks;
function GetSelected: Boolean;
property IsSelected: Boolean read GetSelected;
function GetGroups: TLongIntArray;
property Groups: TLongIntArray read GetGroups;
destructor Destroy; override;
end;
TVehicleUpdateArray = array of TVehicleUpdate;
implementation
constructor TVehicleUpdate.Create(const id: Int64; const x: Double; const y: Double; const durability: LongInt;
const remainingAttackCooldownTicks: LongInt; const selected: Boolean; const groups: TLongIntArray);
begin
FId := id;
FX := x;
FY := y;
FDurability := durability;
FRemainingAttackCooldownTicks := remainingAttackCooldownTicks;
FSelected := selected;
if Assigned(groups) then begin
FGroups := Copy(groups, 0, Length(groups));
end else begin
FGroups := nil;
end;
end;
function TVehicleUpdate.GetId: Int64;
begin
result := FId;
end;
function TVehicleUpdate.GetX: Double;
begin
result := FX;
end;
function TVehicleUpdate.GetY: Double;
begin
result := FY;
end;
function TVehicleUpdate.GetDurability: LongInt;
begin
result := FDurability;
end;
function TVehicleUpdate.GetRemainingAttackCooldownTicks: LongInt;
begin
result := FRemainingAttackCooldownTicks;
end;
function TVehicleUpdate.GetSelected: Boolean;
begin
result := FSelected;
end;
function TVehicleUpdate.GetGroups: TLongIntArray;
begin
if Assigned(FGroups) then begin
result := Copy(FGroups, 0, Length(FGroups));
end else begin
result := nil;
end;
end;
destructor TVehicleUpdate.Destroy;
begin
inherited;
end;
end.
|
{ zlibar.pas can create and read a file that contains many compressed files
Copyright (C) 2005 Andrew Haines
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
}
{
See also the file COPYING.modifiedLGPL included with this file
}
unit zlibar;
// This Unit Provides methods to compress multiple files into an archive of one file and retrieve them
// Also you can use CompressStream and ExtractStream to just compress and decompress a tmemorystream
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, paszlib, md5;
type
PFileInfo = ^TFileInfo;
TFileInfo = record
CompressedSize: Int64;
Md5Sum: TMD5Digest;
end;
{ TZlibFilesList }
TZlibFilesList = class(TObject)
private
FFileList: TFpList;
FPathList: TFpList;
FFileInfoList: TFpList;
function GetFileName(AIndex: Integer): String;
function GetPath(AIndex: Integer): String;
procedure SetFileName(AIndex: Integer; AFIleName: String);
procedure SetPath(AIndex: Integer; APath: String);
function GetFileInfo(AIndex: Integer): TFileInfo;
procedure SetFileInfo(AIndex: Integer; AFileInfo: TFileInfo);
public
constructor Create;
destructor Destroy; override;
public
function Add(AFileName: String): Integer;
function AddPath(AFileName: String; APath: String): Integer;
function Insert(AIndex: Integer; AFileName: String): Integer;
function InsertPath(AIndex: Integer; AFileName: String; APath: String): Integer;
procedure Delete(AIndex: Integer);
procedure Clear;
function Count: Integer;
public
// this contains the full path to the file name on the current filesystem
property FileName[Index: Integer]: String read GetFileName write SetFileName;
// this is the relative path that you would like the file extracted to
property Path[Index: Integer]: String read GetPath write SetPath;
// used internally
property FileInfo[Index: Integer]: TFileInfo read GetFileInfo write SetFileInfo;
end;
TZlibArchiveHeader = packed record
FileType: array [0..3] of char;// = ('Z','A','R', 0);
MajorVersion,
MinorVersion,
MicroVersion: LongInt;
TOCLength: Int64; // overkill? :)
TOCMD5Sum: TMD5Digest;
end;
PTOCEntry = ^TTOCEntry;
TTOCEntry = packed record
FileName: String;
FilePath: String;
Position: Int64;
CompressedSize: Int64;
Md5sum: TMD5Digest;
end;
(*
A TOC Entry will stored like so:
1. Write File Name to be in archive
2 Write Empty Byte.
3. Write File Path
4. Write Empty Byte
5. Write File Position (Int64) 8 bytes
6. Write File Compressed Size(Int64)
7. Write md5sum (TMD5Digest)
Repeat 1-4
*)
TZlibCompressProgProc = procedure (Sender: TObject; FileIndex: Integer; FileSize, FilePos: Int64) of object;
TZlibExtractProgProc = procedure (Sender: TObject; FileSize, FilePos: Int64) of object;
TZlibErrorProc = procedure(Sender: TObject; var ErrorCode: Integer; ErrorStr: String) of object;
{ TZlibArchive }
{ TZlibWriteArchive }
TZlibWriteArchive = class(TObject)
private
fInputFiles: TZlibFilesList;
fOnCompress: TZlibCompressProgProc;
fOnError: TZlibErrorProc;
fStream: TStream;
fStreamOwner: Boolean;
procedure WriteHeader(AHeader: TZlibArchiveHeader);
procedure WriteTOCEntry(Entry: TTOCEntry; TOCStream: TStream);
procedure CheckStreamAssigned;
procedure DoError(ErrorCode: Integer; ErrorString: String);
function InternalCompressStream(FileIndex: Integer; InStream: TStream; OutStream: TStream): Integer;
procedure SetStream(AValue: TStream);
public
constructor Create;
destructor Destroy; override;
public
function CreateArchive: boolean;
property OnError: TZlibErrorProc read fOnError write fOnError;
property OnCompress : TZlibCompressProgProc read fOnCompress write fOnCompress;
published
property OutStream: TStream read fStream write SetStream;
property InputFiles: TZlibFilesList read fInputFiles;
end;
{ TZLibReadArchive }
TZLibReadArchive = class(TObject)
private
fTOCList: TFpList;
fOnError: TZlibErrorProc;
fOnExtract: TZlibExtractProgProc;
fHeader: TZlibArchiveHeader;
fStream: TStream;
fFileName: String;
procedure SetStream(AStream: TStream);
procedure VerifyFile;
procedure ReadTOC;
procedure FreeTOC;
function GetCount: Integer;
function GetTOCEntry(AIndex: Integer): TTOCEntry;
procedure DoError(ErrorCode: Integer; ErrorString: String);
function InternalExtractStream(InStream: TStream;var OutStream: TStream): Integer;
function FindFilePath(const AFilePath: String): Integer;
public
constructor Create;
constructor Create(InStream: TStream);
destructor Destroy; override;
public
procedure ExtractFileToStream(AIndex: Integer; Stream: TStream);
procedure ExtractFileToStream(const AFileName: String; Stream: TStream);
procedure ExtractFileToStream(const AFileName , APath: String; Stream: TStream);
property Header: TZlibArchiveHeader read fHeader;
property FilesInArchive[Index: Integer]: TTOCEntry read GetTOCEntry;
property Count: Integer read GetCount;
property OnError: TZlibErrorProc read fOnError write fOnError;
property OnExtract: TZlibExtractProgProc read fOnExtract write fOnExtract;
published
property InStream: TStream read fStream write SetStream;
end;
const
ZLibFileType: array [0..3] of char = ('Z','A','R', #0);
ZAR_MAJOR_VERSION : LongInt = 1;
ZAR_MINOR_VERSION : LongInt = 0;
ZAR_MICRO_VERSION : LongInt = 0;
ERR_CORRUPT_TOC = 1;
ERR_CORRUPT_FILE = 2;
ERR_CHECKSUM_FAILED = 3;
ERR_FILENAME_NOT_FOUND = 4;
ERR_UNKOWN_ERROR = 6;
function CompressStream(InStream: TStream; OutStream: TStream): Integer; //returns size of compressed file
function ExtractStream(InStream: TStream; OutStream: TStream): Integer;
function StreamMD5(Stream: TStream): TMD5Digest; // creates a md5digest from a tstream
implementation
///////////////////////////////////
// Generic Functions //
///////////////////////////////////
{*******************************************************************************
* This performs an md5 sum on the file and returns it as a TMD5Digest *
* *
*******************************************************************************}
function StreamMD5(Stream: TStream): TMD5Digest;
var
Buf : array [0..1023] of byte;
Context: TMD5Context;
Count : Longint;
begin
Stream.Position := 0;
MD5Init(Context);
repeat
Count := 1024;
Count := Stream.Read(Buf, Count);
If (Count>0) then
MD5Update(Context, Buf, Count);
until (Count<1024);
MD5Final(Context, Result);
end;
{*******************************************************************************
* This decompresses the data from InStream and Writes the decompressed data *
* to OutputStream *
*******************************************************************************}
function ExtractStream(InStream: TStream; OutStream: TStream): Integer;
var
err : integer;
z : TZstream;
const
MAX_IN_BUF_SIZE = 1024;
MAX_OUT_BUF_SIZE = 1024;
var
input_buffer : array[0..MAX_IN_BUF_SIZE-1] of byte;
output_buffer : array[0..MAX_OUT_BUF_SIZE-1] of byte;
FlushType: LongInt;
begin
Result := 0;
FillChar(z, SizeOf(z), 0);
FillChar(input_buffer, SizeOf(input_buffer), 0);
err := inflateInit(z);
InStream.Position := 0;
while InStream.Position < InStream.Size do
begin
z.next_in := @input_buffer;
z.avail_in := InStream.Read(input_buffer, MAX_IN_BUF_SIZE);
// wouldn't work for files > 2GB
//z.next_in := TMemoryStream(InStream).Memory;
//z.avail_in := InStream.Size;
if InStream.Position = InStream.Size then
FlushType := Z_FINISH
else
FlushType := Z_SYNC_FLUSH;
repeat
z.next_out := @output_buffer;
z.avail_out := MAX_OUT_BUF_SIZE;
err := inflate(z, FlushType);
Result += OutStream.Write(output_buffer, MAX_OUT_BUF_SIZE - z.avail_out);
if err = Z_STREAM_END then Break;
until Z.avail_out > 0;
if (err <> Z_OK) and (err <> Z_BUF_ERROR) then begin
break;
end;
end;
err := inflateEnd(z);
end;
{*******************************************************************************
* This compresses the data from InStream and Writes the compressed data *
* to OutputStream *
*******************************************************************************}
function CompressStream(InStream: TStream; OutStream: TStream): Integer;
var
err : integer;
z : TZstream;
const
MAX_IN_BUF_SIZE = 1024;
MAX_OUT_BUF_SIZE = 1024;
var
input_buffer : array[0..MAX_IN_BUF_SIZE-1] of byte;
output_buffer : array[0..MAX_OUT_BUF_SIZE-1] of byte;
FlushType: LongInt;
begin
Result := 0;
FillChar(input_buffer, SizeOf(input_buffer), 0);
err := deflateInit(z, -1); //default
InStream.Position := 0;
while InStream.Position < InStream.Size do
begin
z.next_in := @input_buffer;
z.avail_in := InStream.Read(input_buffer, MAX_IN_BUF_SIZE);
// wouldn't work for files > 2 gb :(
//z.next_in := TMemoryStream(InStream).Memory;
//z.avail_in := InStream.Size;
if InStream.Position = InStream.Size then
FlushType := Z_FINISH
else
FlushType := Z_NO_FLUSH;
repeat
z.next_out := @output_buffer;
z.avail_out := MAX_OUT_BUF_SIZE;
err := deflate(z, FlushType);
Result += OutStream.Write(output_buffer, MAX_OUT_BUF_SIZE - z.avail_out);
until Z.avail_out > 0;
if (err <> Z_OK) and (err <> Z_BUF_ERROR) then begin
break;
end;
end;
err := deflateEnd(z);
end;
////////////////////////////////
// Objects //
////////////////////////////////
{ TZlibArchive }
procedure TZlibWriteArchive.WriteHeader(AHeader: TZlibArchiveHeader);
var
X: Integer;
CompressedTOCStream: TMemoryStream;
TOCStream: TMemoryStream;
Position: Int64;
TOCEntry: TTOCEntry;
FileInfo:TFileInfo;
begin
try
CheckStreamAssigned;
TOCStream := TMemoryStream.Create;
Position := 0;
OutStream.Position := 0;
for X := 0 to fInputFiles.Count-1 do begin
TOCEntry.FileName := fInputFiles.FileName[X];
TOCEntry.FilePath := fInputFiles.Path[X];
TOCEntry.Position := Position;
FileInfo := fInputFiles.FileInfo[X];
TOCEntry.CompressedSize := FileInfo.CompressedSize;
TocEntry.Md5sum := FileInfo.Md5Sum;
WriteTOCEntry(TOCEntry, TOCStream);
Position += TOCEntry.CompressedSize;
end;
CompressedTOCStream:= TMemoryStream.Create;
CompressStream(TOCStream, CompressedTOCStream);
CompressedTOCStream.Position := 0;
AHeader.TOCLength := NtoLE(CompressedTOCStream.Size);
AHeader.TOCMd5Sum := StreamMd5(TOCStream);
OutStream.Write(AHeader, SizeOf(TZlibArchiveHeader));
OutStream.CopyFrom(CompressedTOCStream, CompressedTOCStream.Size);
finally
TOCStream.Free;
CompressedTOCStream.Free;
end;
end;
procedure TZlibWriteArchive.WriteTOCEntry(Entry: TTOCEntry; TOCStream: TStream);
var
Str: array [0..255]of char;
EmptyByte: Byte =0;
begin
Str := ExtractFileName(Entry.FileName);
TOCStream.Write(Str, Length(Trim(Str)));
TOCStream.WriteByte(EmptyByte);
Str := Entry.FilePath;
TOCStream.Write(Str, Length(Trim(Str)));
TOCStream.WriteByte(EmptyByte);
Entry.Position := NtoLE(Entry.Position);
TOCStream.Write(Entry.Position, SizeOf(Int64));
Entry.CompressedSize := NtoLE(Entry.CompressedSize);
TOCStream.Write(Entry.CompressedSize, SizeOf(Int64));
TOCStream.Write(Entry.Md5sum, SizeOf(TMD5Digest));
end;
procedure TZlibWriteArchive.CheckStreamAssigned;
begin
if fStream = nil then begin
fStream := TMemoryStream.Create;
fStreamOwner := True;
end;
end;
procedure TZlibWriteArchive.DoError(ErrorCode: Integer; ErrorString: String);
var
fErrCode: Integer;
begin
fErrCode := ErrorCode;
if Assigned(fOnError) then fOnError(Self, fErrCode, ErrorString);
if fErrCode <> 0 then Raise Exception.Create('ZLibError('+IntToStr(fErrCode)+') '+ErrorString);
end;
function TZlibWriteArchive.InternalCompressStream(FileIndex: Integer;
InStream: TStream; OutStream: TStream): Integer;
var
err : integer;
z : TZstream;
const
MAX_IN_BUF_SIZE = 1024;
MAX_OUT_BUF_SIZE = 1024;
var
input_buffer : array[0..MAX_IN_BUF_SIZE-1] of byte;
output_buffer : array[0..MAX_OUT_BUF_SIZE-1] of byte;
FlushType: LongInt;
begin
Result := 0;
FillChar(z, 0 , SizeOf(z));
FillChar(input_buffer, SizeOf(input_buffer), 0);
err := deflateInit(z, -1); //default
InStream.Position := 0;
while InStream.Position < InStream.Size do
begin
z.next_in := @input_buffer;
z.avail_in := InStream.Read(input_buffer, MAX_IN_BUF_SIZE);
// wouldn't work for files > 2 gb :(
//z.next_in := TMemoryStream(InStream).Memory;
//z.avail_in := InStream.Size;
if InStream.Position = InStream.Size then
FlushType := Z_FINISH
else
FlushType := Z_NO_FLUSH;
repeat
z.next_out := @output_buffer;
z.avail_out := MAX_OUT_BUF_SIZE;
err := deflate(z, FlushType);
Result += OutStream.Write(output_buffer, MAX_OUT_BUF_SIZE - z.avail_out);
until Z.avail_out > 0;
if fOnCompress <> nil then fOnCompress(Self, FileIndex, InStream.Size, InStream.Position);
if (err <> Z_OK) and (err <> Z_BUF_ERROR) then begin
break;
end;
end;
err := deflateEnd(z);
end;
procedure TZlibWriteArchive.SetStream(AValue: TStream);
begin
if AValue <> fStream then fStreamOwner := False;
fStream := AValue;
end;
constructor TZlibWriteArchive.Create;
begin
fInputFiles := TZlibFilesList.Create;
fStream := nil;
end;
destructor TZlibWriteArchive.Destroy;
begin
fInputFiles.Free;
if fStreamOwner then fStream.Free;
inherited Destroy;
end;
function TZlibWriteArchive.CreateArchive: boolean;
var
X: Integer;
AHeader: TZlibArchiveHeader;
TmpStream: TMemoryStream; // this holds all the compressed files temporarily
//TmpFile: TMemoryStream; // this holds the current file to be added to TmpStream
TmpFile: TFileStream; // this holds the current file to be added to TmpStream
FileInfo: TFileInfo;
begin
Result := False;
try
CheckStreamAssigned;
TmpStream := TMemoryStream.Create;
AHeader.FileType := ZLibFileType;
AHeader.MajorVersion := NtoLE(ZAR_MAJOR_VERSION);
AHeader.MinorVersion := NtoLE(ZAR_MINOR_VERSION);
AHeader.MicroVersion := NtoLE(ZAR_MICRO_VERSION);
for X := 0 to fInputFiles.Count-1 do begin
if FileExists(fInputFiles.FileName[X]) then begin
try
TmpFile := TFileStream.Create(fInputFiles.FileName[X],fmOpenRead or fmShareDenyNone);
FileInfo.CompressedSize := InternalCompressStream(X, TmpFile, TmpStream);
FileInfo.Md5Sum := StreamMD5(TmpFile);
fInputFiles.FileInfo[X] := FileInfo;//records the compressed length/size
finally
TmpFile.Free;
end;
end;
end;
//Write file header and Table of contents
WriteHeader(AHeader);
//WriteFiles
TmpStream.Position := 0;
OutStream.CopyFrom(TmpStream, TmpStream.Size);
Result := True;
finally
TmpStream.Free;
end;
end;
{ TZLibReadArchive }
procedure TZLibReadArchive.SetStream(AStream: TStream);
begin
fStream := AStream;
if AStream <> nil then begin
fStream.Position := 0;
fStream.Read(fHeader,SizeOf(TZlibArchiveHeader));
fHeader.MajorVersion := LEtoN(Header.MajorVersion);
fHeader.MinorVersion := LEtoN(Header.MinorVersion);
fHeader.MicroVersion := LetoN(Header.MicroVersion);
fHeader.TOCLength := LEtoN(Header.TOCLength);
VerifyFile;
ReadTOC;
end
else begin
FreeTOC;
end;
end;
procedure TZLibReadArchive.VerifyFile;
begin
if (fHeader.FileType <> ZLibFileType) then DoError(ERR_CORRUPT_FILE,'corrupt file or not a correct file type');
end;
procedure TZLibReadArchive.ReadTOC;
var
Entry: PTOCEntry;
PositionOffset: Int64;
fChar: Char;
TmpStream: TMemoryStream; // used to temporarily hold the compressed TOC
TOCStream: TMemoryStream; // the TOC will be extracted into this
begin
TmpStream:= TMemoryStream.Create;
TOCStream := TMemoryStream.Create;
try
fStream.Position := SizeOf(fHeader);
//Read The Compressed TOC into the TmpStream from the main fStream
TmpStream.CopyFrom(fStream, fHeader.TOCLength);
//Decompress TOC into TOCStream
ExtractStream(TmpStream, TOCStream);
if MD5Match(fHeader.TOCMD5Sum, StreamMd5(TOCStream)) = False then DoError(ERR_CORRUPT_TOC, 'corrupted table of contents');
TOCStream.Position := 0;
PositionOffset := fHeader.TOCLength + SizeOf(fHeader);
while TOCStream.Position <> TOCStream.Size do begin
Entry := New(pTocEntry);
fTOCList.Add(Entry);
// Read FileName
fChar := Char(TOCStream.ReadByte);
while fChar <> #0 do begin
Entry^.FileName += fChar;
fChar := Char(TOCStream.ReadByte);
end;
//Read FilePath
fChar := Char(TOCStream.ReadByte);
while fChar <> #0 do begin
Entry^.FilePath += fChar;
fChar := Char(TOCStream.ReadByte);
end;
//Read Position
TOCStream.Read(Entry^.Position, SizeOf(Int64));
Entry^.Position := LEtoN(Entry^.Position) + PositionOffset;
//Read Compressed Size
TOCStream.Read(Entry^.CompressedSize, SizeOf(Int64));
Entry^.CompressedSize := LEtoN(Entry^.CompressedSize);
//Read Md5sum
TOCStream.Read(Entry^.Md5sum, SizeOf(TMD5Digest));
end;
finally
TmpStream.Free;
end;
end;
procedure TZLibReadArchive.FreeTOC;
var
X: Integer;
begin
for X := 0 to fTOCList.Count-1 do begin
Dispose(PTOCEntry(fTocList.Items[X]));
fTocList.Items[X] := nil;
end;
fTOCList.Clear;
end;
function TZLibReadArchive.GetCount: Integer;
begin
Result := fTOCList.Count;
end;
function TZLibReadArchive.GetTOCEntry(AIndex: Integer): TTOCEntry;
begin
Result := PTOCEntry(fTOCList.Items[AIndex])^;
end;
procedure TZLibReadArchive.DoError(ErrorCode: Integer; ErrorString: String);
var
fErrCode: Integer;
begin
fErrCode := ErrorCode;
if Assigned(fOnError) then fOnError(Self, fErrCode, ErrorString);
if fErrCode <> 0 then Raise Exception.Create('ZLibError('+IntToStr(fErrCode)+') '+ErrorString);
end;
function TZLibReadArchive.InternalExtractStream(InStream: TStream;
var OutStream: TStream): Integer;
var
err : integer;
z : TZstream;
const
MAX_IN_BUF_SIZE = 1024;
MAX_OUT_BUF_SIZE = 1024;
var
input_buffer : array[0..MAX_IN_BUF_SIZE-1] of byte;
output_buffer : array[0..MAX_OUT_BUF_SIZE-1] of byte;
FlushType: LongInt;
begin
Result := 0;
FillChar(z, 0 , SizeOf(z));
FillChar(input_buffer, SizeOf(input_buffer), 0);
err := inflateInit(z);
InStream.Position := 0;
while InStream.Position < InStream.Size do
begin
z.next_in := @input_buffer;
z.avail_in := InStream.Read(input_buffer, MAX_IN_BUF_SIZE);
// wouldn't work for files > 2GB
//z.next_in := TMemoryStream(InStream).Memory;
//z.avail_in := InStream.Size;
if InStream.Position = InStream.Size then
FlushType := Z_FINISH
else
FlushType := Z_SYNC_FLUSH;
repeat
z.next_out := @output_buffer;
z.avail_out := MAX_OUT_BUF_SIZE;
err := inflate(z, FlushType);
Result += OutStream.Write(output_buffer, MAX_OUT_BUF_SIZE - z.avail_out);
if err = Z_STREAM_END then Break;
until Z.avail_out > 0;
if fOnExtract <> nil then fOnExtract(Self, InStream.Size, InStream.Position);
if (err <> Z_OK) and (err <> Z_BUF_ERROR) then begin
break;
end;
end;
err := inflateEnd(z);
end;
function TZLibReadArchive.FindFilePath(const AFilePath: String): Integer;
var
i: Integer;
begin
Result:= -1;
for i:= 0 to fTOCList.Count - 1 do begin
if AFilePath = PTOCEntry(fTOCList[i])^.FilePath+PTOCEntry(fTOCList[i])^.FileName then
begin
Result:=i;
Break;
end;
end;
end;
constructor TZLibReadArchive.Create;
begin
fStream := TMemoryStream.Create;
fFileName := '';
fTOCList := TFpList.Create;
end;
constructor TZLibReadArchive.Create(InStream: TStream);
begin
Create;
SetStream(InStream);
end;
destructor TZLibReadArchive.Destroy;
begin
FreeTOC;
fTOCList.Free;
inherited Destroy;
end;
procedure TZLibReadArchive.ExtractFileToStream(AIndex: Integer; Stream: TStream);
var
TmpStream: TMemoryStream;
Md5Sum: TMD5Digest;
begin
if Stream = nil then Stream := TMemoryStream.Create;
Stream.Position := 0;
Stream.Size := 0;
TmpStream := TMemoryStream.Create;
try
// Move to the position of the compressed file in the archive
fStream.Position := FilesInArchive[AIndex].Position;
// read the compressed file into a temp stream
TmpStream.CopyFrom(fStream, FilesInArchive[AIndex].CompressedSize);
// decompress the tmp stream into the output stream
InternalExtractStream(TmpStream, Stream);
//Check Md5 sum
Md5Sum := StreamMD5(Stream);
if not MD5Match(Md5Sum, FilesInArchive[AIndex].Md5sum) then begin
DoError(ERR_CHECKSUM_FAILED, 'Saved=' + MD5Print(FilesInArchive[AIndex].Md5sum) +' Found='+ MD5Print(Md5sum));
end;
finally
TmpStream.Free;
end;
end;
procedure TZLibReadArchive.ExtractFileToStream(const AFileName: String; Stream: TStream);
begin
ExtractFileToStream(AFileName,'/',Stream);
end;
procedure TZLibReadArchive.ExtractFileToStream(const AFileName, APath: String; Stream: TStream);
var
i: Integer;
begin
i:=FindFilePath(APath+AFileName);
if i <> -1 then
ExtractFileToStream(i,Stream)
else
DoError(ERR_FILENAME_NOT_FOUND,'Could not find '+APath+AFileName+' in '+fFileName);
end;
{ TZlibFilesList }
function TZlibFilesList.GetFileName(AIndex: Integer): String;
begin
Result := PString(FFileList.Items[AIndex])^;
end;
function TZlibFilesList.GetPath(AIndex: Integer): String;
begin
Result := PString(FPathList.Items[AIndex])^;
end;
procedure TZlibFilesList.SetFileName(AIndex: Integer; AFIleName: String);
begin
PString(FFileList.Items[AIndex])^ := AFileName;
end;
procedure TZlibFilesList.SetPath(AIndex: Integer; APath: String);
begin
PString(FPathList.Items[AIndex])^ := APath;
end;
function TZlibFilesList.GetFileInfo(AIndex: Integer): TFileInfo;
begin
Result := PFileInfo(FFileInfoList.Items[AIndex])^;
end;
procedure TZlibFilesList.SetFileInfo(AIndex: Integer; AFileInfo: TFileInfo);
begin
PFileInfo(FFileInfoList.Items[AIndex])^ := AFileInfo;
end;
constructor TZlibFilesList.Create;
begin
FFileList := TFpList.Create;
FPathList := TFpList.Create;
FFileInfoList := TFpList.Create;
end;
destructor TZlibFilesList.Destroy;
begin
Clear;
Inherited Destroy;
end;
function TZlibFilesList.Add(AFileName: String): Integer;
begin
Result := InsertPath(Count, AFileName,'/');
end;
function TZlibFilesList.AddPath(AFileName: String; APath: String): Integer;
begin
Result := InsertPath(Count, AFileName, APath);
end;
function TZlibFilesList.Insert(AIndex: Integer; AFileName: String): Integer;
begin
Result := InsertPath(AIndex, AFileName, '/');
end;
function TZlibFilesList.InsertPath(AIndex: Integer; AFileName: String;
APath: String): Integer;
var
FFile,
FPath: PString;
FFileInfo: PFileInfo;
begin
Result := 0;
if AIndex > Count then Result := Count
else Result := AIndex;
FFile := New(PString);
FPath := New(PString);
FFileInfo := New(PFileInfo);
FFile^ := AFileName;
FPath^ := APAth;
FFileList.Insert(AIndex, FFile);
FPathList.Insert(AIndex, FPath);
FFileInfoList.Insert(AIndex, FFileInfo);
end;
procedure TZlibFilesList.Delete(AIndex: Integer);
begin
Dispose(PString(FFileList.Items[AIndex]));
Dispose(PString(FPathList.Items[AIndex]));
Dispose(PFileInfo(FFileInfoList.Items[AIndex]));
FFileList.Delete(AIndex);
FPathList.Delete(AIndex);
FFileInfoList.Delete(AIndex);
end;
procedure TZlibFilesList.Clear;
begin
While Count > 0 do
Delete(Count-1);
end;
function TZlibFilesList.Count: Integer;
begin
Result := FFileList.Count;
end;
end.
|
unit eInterestSimulator.Controller.Observer.Interfaces;
interface
uses
eInterestSimulator.Model.Interfaces, System.Generics.Collections;
type
iObserverResultado = interface
['{4FEF09C8-26FE-4921-A04C-98A834D3C5BB}']
function UpdateResultado(Value: Tlist<iResultado>): iObserverResultado;
end;
iSubjectResultado = interface
['{1FFF8EBB-3565-44AB-8B78-36A9327F99B7}']
function Add(Value: iObserverResultado): iSubjectResultado;
function Notify(Value: Tlist<iResultado>): iSubjectResultado;
end;
implementation
end.
|
{ Subroutine SST_SET_VAL_CONVERT (VAL,DTYPE,SUCCESS)
*
* Convert the SET constant value in VAL to the data type defined by the data
* type descriptor DTYPE. SUCCESS is set to TRUE if the conversion was
* successful. The values in VAL are changed directly. It is an error if
* VAL does not contain a SET value, or if DTYPE is not a SET data type.
*
* If the data types already match, then this is considered success.
* The only conversion allowed is if the set in VAL is a subrange that is a
* subset of the possible set elements implied by DTYPE. In any case,
* if SUCCESS is TRUE, then the data type pointer in VAL for the set value
* will be pointing to DTYPE.
}
module sst_SET_VAL_CONVERT;
define sst_set_val_convert;
%include 'sst2.ins.pas';
procedure sst_set_val_convert ( {convert set value expression data type}
in out val: sst_var_value_t; {set value to convert}
in dtype: sst_dtype_t; {desired target SET data type}
out success: boolean); {TRUE if conversion was successful}
var
dt_set_p: sst_dtype_p_t; {pnt to base dtype descriptor for set dtype}
dt_set: sst_dtype_k_t; {base set data type ID}
dt_out_p: sst_dtype_p_t; {pnt to base desired dtype descriptor}
dt_out: sst_dtype_k_t; {base desired data type ID}
ord1_out: sys_int_max_t; {ordinal value of first ele in output set}
ord1_val: sys_int_max_t; {ordinal value of first ele in input set}
word_val_p: sys_int_conv32_p_t; {points to input set data word}
word_out_p: sys_int_conv32_p_t; {points to output set data word}
mask_val, mask_out: sys_int_conv32_t; {mask words for input and output set word}
val_old: sst_var_value_t; {local copy of old VAL descriptor}
i: sys_int_machine_t; {loop counter}
ele_val, ele_out: sys_int_machine_t; {input and output set element numbers}
label
successful;
begin
success := false; {init to conversion was NOT successful}
if val.dtype <> sst_dtype_set_k then begin {value descriptor is not for a set ?}
sys_message_bomb ('sst', 'value_not_a_set', nil, 0);
end;
if val.set_dtype_p = addr(dtype) {already set to desired data type ?}
then goto successful;
sst_dtype_resolve ( {resolve set's base data types}
val.set_dtype_p^, {data type of set's elements}
dt_set_p, dt_set); {returned base data types}
sst_dtype_resolve ( {resolve desired base data types}
dtype.set_dtype_p^, {data type of desired set's elements}
dt_out_p, dt_out); {returned base desired data types}
if dt_out_p^.dtype <> sst_dtype_set_k then begin {desired data type not SET type}
sys_message_bomb ('sst', 'dtype_target_not_a_set', nil, 0);
end;
if dt_set_p = dt_out_p {already sets of the same data type ?}
then goto successful;
{
* The set has a different data type descriptor than the target, and the
* elements also use a different data type descriptor than the target.
}
if dt_set_p^.dtype <> sst_dtype_range_k {VAL not a set of a subrange ?}
then return; {unsuccessful}
if dt_set <> dt_out {set elements not same base data type ID}
then return; {unsuccessful}
case dt_out_p^.dtype of {what data type are the desired set elements ?}
sst_dtype_enum_k, {desired data type is set of ENUMERATED}
sst_dtype_bool_k, {desired data type is set of BOOLEAN}
sst_dtype_char_k: begin {desired data type is set of CHAR}
ord1_out := 0; {first element is at ordinal value 0}
end;
sst_dtype_range_k: begin {desired data type is set of SUBRANGE}
ord1_out := dt_out_p^.range_ord_first; {get ordinal value of first element}
end;
otherwise {illegal base data type for SET}
return; {unsuccessful}
end;
ord1_val := dt_set_p^.set_dtype_p^.range_ord_first; {ord val of first VAL ele}
if {VAL not a proper subset of DTYPE ?}
(ord1_val < ord1_out) or
((ord1_val + dt_set_p^.bits_min) > (ord1_out + dtype.bits_min))
then return;
if {both sets use same memory layout ?}
(ord1_val = ord1_out) and
(dt_set_p^.set_n_ent = dtype.set_n_ent)
then goto successful;
{
* Conversion is possible. The set in VAL is a set of a SUBRANGE data type,
* and the desired set is either a set of the same base data type, or a
* superset SUBRANGE of the same base data type.
}
val_old := val; {save original copy of VAL}
val_old.set_dtype_p := dt_set_p; {point directly to base dtype descriptor}
sst_mem_alloc_scope ( {allocate new memory for set storage}
sizeof(val.set_val_p^) * dtype.set_n_ent, {amount of memory to allocate}
val.set_val_p); {returned pointer to new memory}
val.set_dtype_p := dt_out_p; {point VAL to its new base dtype descriptor}
{
* VAL is set up with the new data type and has a new storage area for the
* set elements. VAL_OLD is a local copy of the old VAL. First, initialize
* all the output bits to zero, then copy all the input set elements one
* at a time.
}
for i := 0 to dtype.set_n_ent-1 do begin {once for each output set word}
val.set_val_p^[i] := 0; {clear all the bits in each word}
end;
ele_out := ord1_val - ord1_out; {out set ele number of first in set element}
for ele_val := 0 to dt_set_p^.bits_min-1 do begin {once for each input set ele}
sst_set_ele_find ( {get handle to input set element}
val_old, {whole value descriptor}
ele_val, {set element number}
word_val_p, {will point to word containing element}
mask_val); {mask word to select particular element}
sst_set_ele_find ( {get handle to output set element}
val,
ele_out,
word_out_p,
mask_out);
if (word_val_p^ & mask_val) <> 0 {copy element from input to output set}
then word_out_p^ := word_out_p^ ! mask_out;
ele_out := ele_out + 1; {make number of next output set element}
end; {back for next input set element}
successful: {common exit point if conversion successful}
val.set_dtype_p := addr(dtype); {point value descriptor to desired data type}
success := true; {indicate conversion DID succeed}
end;
|
// SAX for Pascal, Simple API for XML Buffered Extension Interfaces in Pascal.
// Ver 1.1 July 4, 2003
// http://xml.defined.net/SAX (this will change!)
// Based on http://www.saxproject.org/
// No warranty; no copyright -- use this as you will.
unit BSAXExt;
interface
uses
SAX, BSAX;
const
{$IFDEF SAX_WIDESTRINGS}
IID_IBufferedDeclHandler = '{97D7C698-3CA7-4352-9B2A-42421B6FCF13}';
IID_IBufferedLexicalHandler = '{60A76959-D143-4115-99A6-C8D7C1D44FD7}';
IID_IBufferedAttributes2 = '{DD2C7AF0-F8E8-4667-94C8-2ADB1CB28E61}';
{$ELSE}
IID_IBufferedDeclHandler = '{8B1D7EA7-4F60-4ECF-8607-9AD0AB9BB285}';
IID_IBufferedLexicalHandler = '{BEAC09EF-F04C-4419-99D6-3C5229E2FE7E}';
IID_IBufferedAttributes2 = '{638BEF5C-7741-48E9-979E-8C6800405E9D}';
{$ENDIF}
type
IBufferedDeclHandler = interface;
IBufferedLexicalHandler = interface;
IBufferedAttributes2 = interface;
// SAX2 extension handler for DTD declaration events.
//
// <blockquote>
// <em>This module, both source code and documentation, is in the
// Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
// </blockquote>
//
// <p>This is an optional extension handler for SAX2 to provide more
// complete information about DTD declarations in an XML document.
// XML readers are not required to recognize this handler, and it
// is not part of core-only SAX2 distributions.</p>
//
// <p>Note that data-related DTD declarations (unparsed entities and
// notations) are already reported through the <a href="../BSAX/IBufferedDTDHandler.html">IBufferedDTDHandler</a>
// interface.</p>
//
// <p>If you are using the declaration handler together with a lexical
// handler, all of the events will occur between the
// <a href="../BSAXExt/IBufferedLexicalHandler.html#startDTD">startDTD</a> and the
// <a href="../BSAXExt/IBufferedLexicalHandler.html#endDTD">endDTD</a> events.</p>
//
// <p>To set the DeclHandler for an XML reader, use the
// <a href="../BSAX/IBufferedXMLReader.html#getProperty">getProperty</a> method
// with the property name
// <code>http://xml.org/sax/properties/declaration-handler</code>
// and an object implementing this interface (or nil) as the value.
// If the reader does not report declaration events, it will throw a
// <a href="../SAX/ESAXNotRecognizedException.html">ESAXNotRecognizedException</a>
// when you attempt to register the handler.</p>
//
// <p>For reasons of generality and efficiency, strings that are returned
// from the interface are declared as pointers (PSAXChar) and lengths.
// This requires that the model use procedural out parameters rather
// than functions as in the original interfaces.</p>
//
// @since SAX 2.0 (extensions 1.0)
// @see <a href="../BSAX/IBufferedXMLReader.html">IBufferedXMLReader</a>
//
IBufferedDeclHandler = interface(IUnknown)
[IID_IBufferedDeclHandler]
// Report an element type declaration.
//
// <p>The content model will consist of the string "EMPTY", the
// string "ANY", or a parenthesised group, optionally followed
// by an occurrence indicator. The model will be normalized so
// that all parameter entities are fully resolved and all whitespace
// is removed,and will include the enclosing parentheses. Other
// normalization (such as removing redundant parentheses or
// simplifying occurrence indicators) is at the discretion of the
// parser.</p>
//
// @param name The element type name.
// @param nameLength The length of the name buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param model The content model as a normalized string.
// @param modelLength The length of the model buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @exception ESAXException The application may raise an exception.
///
procedure elementDecl(name : PSAXChar; nameLength : Integer;
model : PSAXChar; modelLength : Integer);
// Report an attribute type declaration.
//
// <p>Only the effective (first) declaration for an attribute will
// be reported. The type will be one of the strings "CDATA",
// "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY",
// "ENTITIES", a parenthesized token group with
// the separator "|" and all whitespace removed, or the word
// "NOTATION" followed by a space followed by a parenthesized
// token group with all whitespace removed.</p>
//
// <p>The value will be the value as reported to applications,
// appropriately normalized and with entity and character
// references expanded.</p>
//
// @param eName The name of the associated element.
// @param eNameLength The length of the eName buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param aName The name of the attribute.
// @param aNameLength The length of the aName buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param attrType A string representing the attribute type.
// @param attrTypeLength The length of the attrType buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param mode A string representing the attribute defaulting mode
// ("#IMPLIED", "#REQUIRED", or "#FIXED") or '' if
// none of these applies.
// @param modeLength The length of the mode buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param value A string representing the attribute's default value,
// or an empty string if there is none.
// @param valueLength The length of the value buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @exception ESAXException The application may raise an exception.
procedure attributeDecl(eName : PSAXChar; eNameLength : Integer;
aName : PSAXChar; aNameLength : Integer;
attrType : PSAXChar; attrTypeLength : Integer;
mode : PSAXChar; modeLength : Integer;
value : PSAXChar; valueLength : Integer);
// Report an internal entity declaration.
//
// <p>Only the effective (first) declaration for each entity
// will be reported. All parameter entities in the value
// will be expanded, but general entities will not.</p>
//
// @param name The name of the entity. If it is a parameter
// entity, the name will begin with '%'.
// @param nameLength The length of the name buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param value The replacement text of the entity.
// @param valueLength The length of the value buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @exception ESAXException The application may raise an exception.
// @see <a href="../BSAXExt/IBufferedDeclHandler.html#externalEntityDecl">IBufferedDeclHandler.externalEntityDecl</a>
// @see <a href="../BSAX/IBufferedDTDHandler.html#unparsedEntityDecl">IBufferedDTDHandler.unparsedEntityDecl</a>
procedure internalEntityDecl(name : PSAXChar;
nameLength : Integer; value : PSAXChar;
valueLength : Integer);
// Report a parsed external entity declaration.
//
// <p>Only the effective (first) declaration for each entity
// will be reported.</p>
//
// @param name The name of the entity. If it is a parameter
// entity, the name will begin with '%'.
// @param nameLength The length of the name buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param publicId The declared public identifier of the entity, or
// the empty string if none was declared.
// @param publicIdLength The length of the publicId buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param systemId The declared system identifier of the entity.
// @param systemIdLength The length of the systemId buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @exception ESAXException The application may raise an exception.
// @see <a href="../BSAXExt/IBufferedDeclHandler.html#internalEntityDecl">IBufferedDeclHandler.internalEntityDecl</a>
// @see <a href="../BSAX/IBufferedDTDHandler.html#unparsedEntityDecl">IBufferedDTDHandler.unparsedEntityDecl</a>
procedure externalEntityDecl(name : PSAXChar;
nameLength : Integer; publicId : PSAXChar;
publicIdLength : Integer; systemId : PSAXChar;
systemIdLength : Integer);
end;
// SAX2 extension handler for lexical events.
//
// <blockquote>
// <em>This module, both source code and documentation, is in the
// Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
// </blockquote>
//
// <p>This is an optional extension handler for SAX2 to provide
// lexical information about an XML document, such as comments
// and CDATA section boundaries.
// XML readers are not required to recognize this handler, and it
// is not part of core-only SAX2 distributions.</p>
//
// <p>The events in the lexical handler apply to the entire document,
// not just to the document element, and all lexical handler events
// must appear between the content handler's startDocument and
// endDocument events.</p>
//
// <p>To set the LexicalHandler for an XML reader, use the
// <a href="../BSAX/IBufferedXMLReader.html#getProperty">getProperty</a> method
// with the property name
// <code>http://xml.org/sax/properties/lexical-handler</code>
// and an object implementing this interface (or nil) as the value.
// If the reader does not report lexical events, it will throw a
// <a href="../SAX/ESAXNotRecognizedException.html">ESAXNotRecognizedException</a>
// when you attempt to register the handler.</p>
//
// <p>For reasons of generality and efficiency, strings that are returned
// from the interface are declared as pointers (PSAXChar) and lengths.
// This requires that the model use procedural out parameters rather
// than functions as in the original interfaces.</p>
//
// @since SAX 2.0 (extensions 1.0)
IBufferedLexicalHandler = interface(IUnknown)
[IID_IBufferedLexicalHandler]
// Report the start of DTD declarations, if any.
//
// <p>This method is intended to report the beginning of the
// DOCTYPE declaration; if the document has no DOCTYPE declaration,
// this method will not be invoked.</p>
//
// <p>All declarations reported through
// <a href="../BSAX/IBufferedDTDHandler.html">IBufferedDTDHandler</a> or
// <a href="../BSAXExt/IBufferedDeclHandler.html">IBufferedDeclHandler</a> events must appear
// between the startDTD and <a href="../BSAXExt/IBufferedLexicalHandler.html#endDTD">endDTD</a> events.
// Declarations are assumed to belong to the internal DTD subset
// unless they appear between <a href="../BSAXExt/IBufferedLexicalHandler.html#startEntity">startEntity</a>
// and <a href="../BSAXExt/IBufferedLexicalHandler.html#endEntity">endEntity</a> events. Comments and
// processing instructions from the DTD should also be reported
// between the startDTD and endDTD events, in their original
// order of (logical) occurrence; they are not required to
// appear in their correct locations relative to DTDHandler
// or DeclHandler events, however.</p>
//
// <p>Note that the start/endDTD events will appear within
// the start/endDocument events from IContentHandler and
// before the first
// <a href="../BSAX/IBufferedContentHandler.html#startElement">startElement</a>
// event.</p>
//
// @param name The document type name.
// @param nameLength The length of the name buffer.
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param publicId The declared public identifier for the
// external DTD subset, or an empty string if none was declared.
// @param publicIdLength The length of the publicId buffer.
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param systemId The declared system identifier for the
// external DTD subset, or an empty string if none was declared.
// (Note that this is not resolved against the document
// base URI.)
// @param systemIdLength The length of the systemId buffer.
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @exception ESAXException The application may raise an
// exception.
// @see <a href="../BSAXExt/IBufferedLexicalHandler.html#endDTD">IBufferedLexicalHandler.endDTD</a>
// @see <a href="../BSAXExt/IBufferedLexicalHandler.html#startEntity">IBufferedLexicalHandler.startEntity</a>
procedure startDTD(name : PSAXChar; nameLength : Integer;
publicId : PSAXChar; publicIdLength : Integer;
systemId : PSAXChar; systemIdLength : Integer);
// Report the end of DTD declarations.
//
// <p>This method is intended to report the end of the
// DOCTYPE declaration; if the document has no DOCTYPE declaration,
// this method will not be invoked.</p>
//
// @exception ESAXException The application may raise an exception.
// @see <a href="../BSAXExt/IBufferedLexicalHandler.html#startDTD">IBufferedLexicalHandler.startDTD</a>
procedure endDTD();
// Report the beginning of some internal and external XML entities.
//
// <p>The reporting of parameter entities (including
// the external DTD subset) is optional, and SAX2 drivers that
// report IBufferedLexicalHandler events may not implement it; you can use the
// <code
// >http://xml.org/sax/features/lexical-handler/parameter-entities</code>
// feature to query or control the reporting of parameter entities.</p>
//
// <p>General entities are reported with their regular names,
// parameter entities have '%' prepended to their names, and
// the external DTD subset has the pseudo-entity name "[dtd]".</p>
//
// <p>When a SAX2 driver is providing these events, all other
// events must be properly nested within start/end entity
// events. There is no additional requirement that events from
// <a href="../BSAXExt/IBufferedDeclHandler.html">IBufferedDeclHandler</a> or
// <a href="../BSAX/IBufferedDTDHandler.html">IBufferedDTDHandler</a> be properly ordered.</p>
//
// <p>Note that skipped entities will be reported through the
// <a href="../BSAX/IBufferedContentHandler.html#skippedEntity">skippedEntity</a>
// event, which is part of the IContentHandler interface.</p>
//
// <p>Because of the streaming event model that SAX uses, some
// entity boundaries cannot be reported under any
// circumstances:</p>
//
// <ul>
// <li>general entities within attribute values</li>
// <li>parameter entities within declarations</li>
// </ul>
//
// <p>These will be silently expanded, with no indication of where
// the original entity boundaries were.</p>
//
// <p>Note also that the boundaries of character references (which
// are not really entities anyway) are not reported.</p>
//
// <p>All start/endEntity events must be properly nested.</p>
//
// @param name The name of the entity. If it is a parameter
// entity, the name will begin with '%', and if it is the
// external DTD subset, it will be '[dtd]'.
// @param nameLength The length of the name buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @exception SAXException The application may raise an exception.
// @see <a href="../BSAXExt/IBufferedLexicalHandler.html#endEntity">IBufferedLexicalHandler.endEntity</a>
// @see <a href="../BSAXExt/IBufferedDeclHandler.html#internalEntityDecl">IBufferedDeclHandler.internalEntityDecl</a>
// @see <a href="../BSAXExt/IBufferedDeclHandler.html#externalEntityDecl">IBufferedDeclHandler.externalEntityDecl</a>
///
procedure startEntity(name : PSAXChar; nameLength : Integer);
// Report the end of an entity.
//
// @param name The name of the entity that is ending.
// @param nameLength The length of the name buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @exception ESAXException The application may raise an exception.
// @see <a href="../BSAXExt/IBufferedLexicalHandler.html#startEntity">IBufferedLexicalHandler.startEntity</a>
procedure endEntity(name : PSAXChar; nameLength : Integer);
// Report the start of a CDATA section.
//
// <p>The contents of the CDATA section will be reported through
// the regular <a href="../BSAX/IBufferedContentHandler.html#characters">characters</a>
// event; this event is intended only to report
// the boundary.</p>
//
// @exception ESAXException The application may raise an exception.
// @see <a href="../BSAXExt/IBufferedLexicalHandler.html#endCDATA">IBufferedLexicalHandler.endCDATA</a>
procedure startCDATA();
// Report the end of a CDATA section.
//
// @exception ESAXException The application may raise an exception.
// @see <a href="../BSAXExt/IBufferedLexicalHandler.html#startCDATA">IBufferedLexicalHandler.startCDATA</a>
procedure endCDATA();
// Report an XML comment anywhere in the document.
//
// <p>This callback will be used for comments inside or outside the
// document element, including comments in the external DTD
// subset (if read). Comments in the DTD must be properly
// nested inside start/endDTD and start/endEntity events (if
// used).</p>
//
// @param ch An array holding the characters in the comment.
// @param chLength The length of the ch buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @exception ESAXException The application may raise an exception.
procedure comment(ch : PSAXChar; chLength : Integer);
end;
// SAX2 extension to augment the per-attribute information
// provided though <a href="../BSAX/IBufferedAttributes.html">IBufferedAttributes</a>.
// If an implementation supports this extension, the attributes
// provided in <a href="../BSAX/IBufferedContentHandler.html#startElement">IBufferedContentHandler.startElement</a>
// will implement this interface,
// and the <em>http://xml.org/sax/features/use-attributes2</em>
// feature flag will have the value <em>true</em>.
//
// <blockquote>
// <em>This module, both source code and documentation, is in the
// Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
// </blockquote>
//
// <p> XMLReader implementations are not required to support this
// information, and it is not part of core-only SAX2 distributions.</p>
//
// <p>Note that if an attribute was defaulted (<em>not isSpecified()</em>)
// it will of necessity also have been declared (<em>isDeclared()</em>)
// in the DTD.
// Similarly if an attribute's type is anything except CDATA, then it
// must have been declared.
// </p>
//
// @since SAX 2.0 (extensions 1.1 alpha)
IBufferedAttributes2 = interface(IBufferedAttributes)
[IID_IBufferedAttributes2]
// Returns false unless the attribute was declared in the DTD.
// This helps distinguish two kinds of attributes that SAX reports
// as CDATA: ones that were declared (and hence are usually valid),
// and those that were not (and which are never valid).
//
// @param index The attribute index (zero-based).
// @return true if the attribute was declared in the DTD,
// false otherwise.
// @exception Exception When the
// supplied index does not identify an attribute.
//
function isDeclared(index : Integer) : Boolean; overload;
// Returns false unless the attribute was declared in the DTD.
// This helps distinguish two kinds of attributes that SAX reports
// as CDATA: ones that were declared (and hence are usually valid),
// and those that were not (and which are never valid).
//
// @param qName The XML 1.0 qualified name.
// @param qNameLength The length of the uri buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @return true if the attribute was declared in the DTD,
// false otherwise.
// @exception ESAXIllegalArgumentException When the
// supplied name does not identify an attribute.
function isDeclared(qName : PSAXChar;
qNameLength : Integer) : Boolean; overload;
// Returns false unless the attribute was declared in the DTD.
// This helps distinguish two kinds of attributes that SAX reports
// as CDATA: ones that were declared (and hence are usually valid),
// and those that were not (and which are never valid).
//
// <p>Remember that since DTDs do not "understand" namespaces, the
// namespace URI associated with an attribute may not have come from
// the DTD. The declaration will have applied to the attribute's
// <em>qName</em>.</p>
//
// @param uri The Namespace URI, or the empty string if
// the name has no Namespace URI.
// @param uriLength The length of the uri buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param localName The attribute's local name.
// @param localNameLength The length of the localName buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @return true if the attribute was declared in the DTD,
// false otherwise.
// @exception ESAXIllegalArgumentException When the
// supplied names do not identify an attribute.
function isDeclared(uri : PSAXChar; uriLength : Integer;
localName : PSAXChar; localNameLength : Integer) : Boolean; overload;
// Returns true unless the attribute value was provided
// by DTD defaulting.
//
// @param index The attribute index (zero-based).
// @return true if the value was found in the XML text,
// false if the value was provided by DTD defaulting.
// @exception ESAXIllegalArgumentException When the
// supplied index does not identify an attribute.
function isSpecified(index : Integer) : Boolean; overload;
// Returns true unless the attribute value was provided
// by DTD defaulting.
//
// <p>Remember that since DTDs do not "understand" namespaces, the
// namespace URI associated with an attribute may not have come from
// the DTD. The declaration will have applied to the attribute's
// <em>qName</em>.</p>
//
// @param uri The Namespace URI, or the empty string if
// the name has no Namespace URI.
// @param uriLength The length of the uri buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @param localName The attribute's local name.
// @param localNameLength The length of the localName buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @return true if the value was found in the XML text,
// false if the value was provided by DTD defaulting.
// @exception ESAXIllegalArgumentException When the
// supplied names do not identify an attribute.
function isSpecified(uri : PSAXChar; uriLength : Integer;
localName : PSAXChar; localNameLength : Integer) : Boolean; overload;
// Returns true unless the attribute value was provided
// by DTD defaulting.
//
// @param qName The XML 1.0 qualified name.
// @param qNameLength The length of the qName buffer
// The value may be -1 which indicates that the buffer is
// null-terminated. If the value is 0 then the buffer may be nil.
// @return true if the value was found in the XML text,
// false if the value was provided by DTD defaulting.
// @exception ESAXIllegalArgumentException When the
// supplied name does not identify an attribute.
function isSpecified(qName : PSAXChar;
qNameLength : Integer) : Boolean; overload;
end;
implementation
end.
|
unit DAO.TabelaDistribuicao;
interface
uses DAO.Base, Model.TabelasDistribuicao, Generics.Collections, System.Classes;
type
TTabelaDistribuicaoDAO = class(TDAO)
function Insert(aTabela: Model.TabelasDistribuicao.TTabelasDistribuicao): Boolean;
function Update(aTabela: Model.TabelasDistribuicao.TTabelasDistribuicao): Boolean;
function Delete(sFiltro: String): Boolean;
function FindTabela(sFiltro: String): TObjectList<Model.TabelasDistribuicao.TTabelasDistribuicao>;
end;
const
TABLENAME = 'tbtabelasdistribuicao';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TTabelaDistribuicaoDAO.Insert(aTabela: TTabelasDistribuicao): Boolean;
var
sSQL: String;
begin
Result := False;
aTabela.ID := GetKeyValue(TABLENAME,'ID_TABELA');
sSQL := 'INSERT INTO ' + TABLENAME + ' '+
'(ID_TABELA, DAT_TABELA, COD_TABELA, COD_GRUPO, COD_TIPO, COD_ENTREGADOR, DES_LOG) ' +
'VALUES ' +
'(:ID, :DATA, :TABELA, :GRUPO, :TIPO, :ENTREGADOR, :LOG);';
Connection.ExecSQL(sSQL,[aTabela.ID, aTabela.Data, aTabela.Tabela, aTabela.Grupo, aTabela.Tipo, aTabela.Entregador, aTabela.Log],
[ftInteger, ftDate, ftInteger, ftInteger, ftInteger, ftInteger, ftString]);
Result := True;
end;
function TTabelaDistribuicaoDAO.Update(aTabela: TTabelasDistribuicao): Boolean;
var
sSQL: System.string;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'DAT_TABELA = :DATA, COD_TABELA = :TABELA, COD_GRUPO = :GRUPO, COD_TIPO = :TIPO, ' +
'COD_ENTREGADOR = :ENTREGADOR, DES_LOG = :LOG ' +
'WHERE ID_TABELA = :ID';
Connection.ExecSQL(sSQL,[aTabela.Data, aTabela.Tabela, aTabela.Grupo, aTabela.Tipo, aTabela.Entregador, aTabela.Log,
aTabela.ID], [ftDate, ftInteger, ftInteger, ftInteger, ftInteger, ftString, ftInteger]);
Result := True;
end;
function TTabelaDistribuicaoDAO.Delete(sFiltro: string): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + ' ';
if not sFiltro.IsEmpty then
begin
sSQl := sSQL + sFiltro;
end
else
begin
Exit;
end;
Connection.ExecSQL(sSQL);
Result := True;
end;
function TTabelaDistribuicaoDAO.FindTabela(sFiltro: string): TObjectList<Model.TabelasDistribuicao.TTabelasDistribuicao>;
var
FDQuery: TFDQuery;
tabelas: TObjectList<TTabelasDistribuicao>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if not sFiltro.IsEmpty then
begin
FDQuery.SQL.Add(sFiltro);
end;
FDQuery.Open();
tabelas := TObjectList<TTabelasDistribuicao>.Create();
while not FDQuery.Eof do
begin
tabelas.Add(TTabelasDistribuicao.Create(FDQuery.FieldByName('ID_TABELA').AsInteger,
FDQuery.FieldByName('DAT_TABELA').AsInteger, FDQuery.FieldByName('COD_TABELA').AsInteger,
FDQuery.FieldByName('COD_GRUPO').AsInteger, FDQuery.FieldByName('COD_TIPO').AsInteger,
FDQuery.FieldByName('COD_ENTREGADOR').AsInteger, FDQuery.FieldByName('DES_LOG').AsString));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := tabelas;
end;
end.
|
{
2002.06.13.
Fixed:
- 'q' can quit now gently even when the application is in fullscreen mode
- SRCBUFFERBPP was not really used, the BPP is determined by FourCC...
- No more problem with minimizing/maximizing/restoring/resizing when the application is in fullscreen mode
- Closing VMAN when the application closes
Added:
- more comments.:)
}
Program VMAN_Proba;
{$PMTYPE PM}
uses os2def, os2base, os2pmapi, os2mm, GRADD, PMGRE, FSDIVE;
var hmodVMAN:hmodule; // Handle of loaded VMAN.DLL module
VMIEntry:FNVMIENTRY; // The entry of VMAN.DLL
NumVideoModes:longint; // Number of supported video modes
ModeInfo:pGDDModeInfo; // List of all supported video modes
DesktopModeInfo:GDDModeInfo; // One video mode, that is used as desktop
NewModeInfo:pGDDModeInfo; // New video mode for fullscreen
fInFullScreenNow:boolean; // Flag to show if the Dive and the Desktop
// is in Fullscreen or windowed mode now
const AppTitle:pchar='VMAN and FSDIVE Test Application';
FULLSCREENWIDTH:longint=640; // Parameters of the fullscreen mode we want to use
FULLSCREENHEIGHT:longint=480;
FULLSCREENBPP:longint=32;
SRCBUFFERWIDTH:longint=640; // Parameters of the source buffer
SRCBUFFERHEIGHT:longint=480;
SRCBUFFERFOURCC:ulong=ord('L') +
ord('U') shl 8 +
ord('T') shl 16 +
ord('8') shl 24;
const ImageUpdateWait=30; // Time in msec to wait between image updates
var ab:HAB; // Anchor block
mq:HMQ; // Message queue
msg:QMSG; // One message (used by main message loop)
hFrame, hClient:HWND; // Window handle of frame and client
hDiveInst: hDive; // Dive instance number
ulImage:ulong; // Handle of image buffer allocated by Dive
fVRNDisabled:boolean; // flag to show if VRN is disabled or not
fFullScreenMode:boolean; // Flag to show if the application is running in fullscreen mode or not.
// Note, that it doesn't mean that the desktop if in fullscreen mode now,
// because it only shows that when the application gets focus, it should
// run in fullscreen mode (or not).
// To check the actual mode, see fInFullscreenNow!
const TMR_DRAWING=1; // ID of our timer, used to update screen
// ----------------------------------------- VMAN --------------------------------------
///////////////////////////////////////
// UnloadVMAN
//
// Unloads VMAN.DLL
//
function UnloadVMAN:boolean;
begin
result:=(DosFreeModule(hmodVMAN)=no_error);
Writeln('VMAN Unloaded!');
end;
///////////////////////////////////////
// LoadVMAN
//
// Loads VMAN.DLL and queries its entry
// point into VMIEntry variable
//
function LoadVMAN:boolean;
var rc:apiret;
begin
rc:=DosLoadModule(Nil, 0, 'VMAN', hmodVMAN); // Load VMAN.DLL
if rc<>no_error then
begin // No VMAN.DLL... Maybe no GRADD driver installed???
writeln('Could not load VMAN! rc=',rc);
result:=false;
exit;
end;
rc:=DosQueryProcAddr(hmodVMAN, 0, 'VMIEntry', pfn(@VMIEntry)); // Query entry point address
if rc<>no_error then
begin
writeln('Could not query VMIEntry address! rc=',rc);
UnloadVMAN;
end;
result:=(rc=no_error);
end;
///////////////////////////////////////
// InitVMIEntry
//
// Sends a INITPROC command to VMAN, so
// informs VMAN that a new process is
// about to use its services
//
function InitVMIEntry:boolean;
var rc:apiret;
ipo:INITPROCOUT;
begin
rc:=VMIEntry(0, VMI_CMD_INITPROC, nil, @ipo);
if rc<>no_error then
begin
writeln('VMI_CMD_INITPROC rc=',rc);
end;
fInFullScreenNow:=false;
result:=rc=no_error;
end;
///////////////////////////////////////
// UninitVMIEntry
//
// Sends a TERMPROC command to VMAN, so
// informs VMAN that this process has
// stopped using its services
//
function UninitVMIEntry:boolean;
var rc:apiret;
begin
rc:=VMIEntry(0, VMI_CMD_TERMPROC, nil, nil);
if rc<>no_error then
begin
writeln('VMI_CMD_TERMPROC rc=',rc);
end;
result:=rc=no_error;
end;
///////////////////////////////////////
// QueryModeInfo
//
// Queries the number of available video
// modes to NumVideoModes, allocates memory
// for information of all the video modes,
// and queries video mode informations into
// ModeInfo.
//
function QueryModeInfo:boolean;
var rc:apiret;
ModeOperation:longint;
OneModeInfo:pGDDModeInfo;
begin
result:=false;
ModeOperation:=QUERYMODE_NUM_MODES;
rc:=VMIEntry(0, VMI_CMD_QUERYMODES, @ModeOperation, @NumVideoModes);
if rc<>no_error then
begin
NumVideoModes:=0;
writeln('VMI_CMD_QUERYMODES rc=',rc);
exit;
end;
getmem(ModeInfo,NumVideoModes*sizeof(GDDModeInfo));
if ModeInfo=Nil then
begin
Writeln('Could not allocate memory for ModeInfo list!');
NumVideoModes:=0;
exit;
end;
ModeOperation:=QUERYMODE_MODE_DATA;
rc:=VMIEntry(0, VMI_CMD_QUERYMODES, @ModeOperation, ModeInfo);
if rc<>no_error then
begin
writeln('Could not query ModeInfo list! rc=',rc);
freemem(ModeInfo); ModeInfo:=Nil;
NumVideoModes:=0;
exit;
end;
result:=true;
end;
///////////////////////////////////////
// FreeModeInfo
//
// Frees the memory allocated by
// QueryModeInfo
//
function FreeModeInfo:boolean;
begin
freemem(ModeInfo); ModeInfo:=Nil;
NumVideoModes:=0;
result:=true;
end;
////////////////////////////////////////
// Some helper functions/procedures
//
function FourCCToString(fcc:ulong):string;
begin
if fcc=0 then result:='' else
result:=chr((fcc and $FF))+
chr((fcc and $FF00) shr 8)+
chr((fcc and $FF0000) shr 16)+
chr((fcc and $FF000000) shr 24);
end;
procedure WriteModeInfo(OneModeInfo:pGDDModeInfo);
begin
with OneModeInfo^ do
begin
writeln('Mode ID: ',ulModeID);
writeln(' ',ulHorizResolution,'x',ulVertResolution,'/',ulBpp,' (',ulRefreshRate,' Hz)');
writeln(' Num of colors: ',cColors,' FourCC: ',FourCCToString(fccColorEncoding));
end;
end;
///////////////////////////////////////
// FindNewModeInfo
//
// Searches for
// FULLSCREENWIDTH x FULLSCREENHEIGHT x FULLSCREENBPP
// videomode in ModeInfo structure, and
// sets the NewModeInfo pointer to point
// to that part of ModeInfo, if found.
//
function FindNewModeInfo:boolean;
var l:longint;
OneModeInfo:pGDDModeInfo;
begin
result:=false;
// writeln('Available GRADD Video Modes: ',NumVideoModes);
NewModeInfo:=Nil;
if ModeInfo=Nil then exit;
OneModeInfo:=ModeInfo;
for l:=1 to NumVideoModes do
begin
// WriteModeInfo(OneModeInfo);
if (OneModeInfo^.ulHorizResolution=FULLSCREENWIDTH) and
(OneModeInfo^.ulVertResolution=FULLSCREENHEIGHT) and
(OneModeInfo^.ulBpp=FULLSCREENBPP) then NewModeInfo:=OneModeInfo;
longint(OneModeInfo):=longint(OneModeInfo)+Sizeof(GDDModeInfo);
end;
result:=NewModeInfo<>nil;
end;
///////////////////////////////////////
// QueryCurrentMode
//
// Queries the current video mode, and
// stores it in DesktopModeInfo
//
function QueryCurrentMode:boolean;
var rc:apiret;
begin
rc:=VMIEntry(0, VMI_CMD_QUERYCURRENTMODE, Nil, @DesktopModeInfo);
if rc<>no_error then
begin
writeln('Could not query DesktopModeInfo! rc=',rc);
end;
result:=rc=no_error;
end;
///////////////////////////////////////
// KillPM
//
// Simulates a switching to fullscreen mode,
// from the PM's point of view
//
procedure KillPM;
var _hab:HAB;
_hwnd:HWND;
_hdc:HDC;
rc:APIRET;
begin
_hab:=WinQueryAnchorBlock(HWND_DESKTOP);
_hwnd:=WinQueryDesktopWindow(_hab, 0);
_hdc:=WinQueryWindowDC(_hwnd); // Get HDC of desktop
WinLockWindowUpdate(HWND_DESKTOP, HWND_DESKTOP); // Don't let other applications write to screen anymore!
rc:=GreDeath(_hdc); // This is the standard way to tell the graphical engine
// that a switching to full-screen mode is about to come!
// (see gradd.inf)
end;
///////////////////////////////////////
// RestorePM
//
// Simulates a switching back from fullscreen mode,
// from the PM's point of view
//
procedure RestorePM;
var _hab:HAB;
_hwnd:HWND;
_hdc:HDC;
rc:APIRET;
begin
_hab:=WinQueryAnchorBlock(HWND_DESKTOP);
_hwnd:=WinQueryDesktopWindow(_hab, 0);
_hdc:=WinQueryWindowDC(_hwnd);
rc:=GreResurrection(_hdc, 0, nil); // This is the standard way of telling the graphical engine
// that somebody has switched back from a fullscreen session to PM.
WinLockWindowUpdate(HWND_DESKTOP, 0); // Let others write to the screen again...
WinInvalidateRect(_hwnd, nil, true); // Let everyone redraw itself! (Build the screen)
end;
///////////////////////////////////////
// SetPointerVisibility
//
// Shows/hides the mouse pointer
//
function SetPointerVisibility(fState:boolean):apiret;
var hwspi:HWSHOWPTRIN;
begin
hwspi.ulLength:=sizeof(hwspi);
hwspi.fShow:=fState;
result:=VMIEntry(0, VMI_CMD_SHOWPTR, @hwspi, nil);
end;
///////////////////////////////////////
// SwitchToFullscreen
//
// Switches to fullscreen-mode
//
function SwitchToFullscreen(OneMode:pGDDModeInfo):boolean;
var ModeID:longint;
rc:apiret;
DIVEAperture:Aperture;
DIVEfbinfo:FBINFO;
begin
// Setup Aperture and FBINFO for FSDIVE
fillchar(DIVEfbinfo, sizeof(FBINFO), 0);
DIVEfbinfo.ulLength := sizeof(FBINFO);
DIVEfbinfo.ulCaps := 0;
DIVEfbinfo.ulBPP := OneMode^.ulBPP;
DIVEfbinfo.ulXRes := OneMode^.ulHorizResolution;
DIVEfbinfo.ulYRes := OneMode^.ulVertResolution;
DIVEfbinfo.ulScanLineBytes := OneMode^.ulScanLineSize;
DIVEfbinfo.ulNumENDIVEDrivers := 0; // unknown
DIVEfbinfo.fccColorEncoding:= OneMode^.fccColorEncoding;
DIVEaperture.ulPhysAddr := longint(OneMode^.pbVRAMPhys);
DIVEaperture.ulApertureSize := OneMode^.ulApertureSize;
DIVEaperture.ulScanLineSize := OneMode^.ulScanLineSize;
DIVEaperture.rctlScreen.yBottom := OneMode^.ulVertResolution - 1;
DIVEaperture.rctlScreen.xRight := OneMode^.ulHorizResolution - 1;
DIVEaperture.rctlScreen.yTop := 0;
DIVEaperture.rctlScreen.xLeft := 0;
SetPointerVisibility(False); // Hide mouse
KillPM; // Tell PM that we're switching away!
DosSleep(256); // Give some time for it...
ModeID:=OneMode^.ulModeID;
rc:=VMIEntry(0, VMI_CMD_SETMODE, @ModeID, nil); // Set new video mode
if rc<>no_error then
begin // Rollback if something went wrong
RestorePM;
SetPointerVisibility(True);
end else
begin
DiveFullScreenInit(@DIVEAperture, @DIVEfbinfo); // Tell DIVE that it can work in this
fInFullScreenNow:=True; // fullscreen mode now!
end;
result:=rc=no_error;
end;
///////////////////////////////////////
// SwitchBackToDesktop
//
// Switches back from fullscreen-mode
//
function SwitchBackToDesktop:boolean;
var ModeID:longint;
rc:apiret;
begin
ModeID:=DesktopModeInfo.ulModeID;
rc:=VMIEntry(0, VMI_CMD_SETMODE, @ModeID, nil); // Set old video mode
DosSleep(256);
DiveFullScreenTerm; // Tell DIVE that end of fullscreen mode
RestorePM; // Tell PM that we're switching back
fInFullScreenNow:=false;
SetPointerVisibility(True); // Restore mouse pointer
end;
///////////////////////////////////////
// VMANCleanUpExitProc
//
// ExitProc, to cleanup VMAN resources
// at application termination.
//
procedure VMANCleanUpExitProc;
begin
// Restore desktop mode if the program left in FS mode!
//
// Note that in this case, there will be problems with future DIVE applications
// until the desktop is restarted, because SwitchBackToDesktop uses
// DiveFullScreenTerm, which must be called before closing Dive (and Dive is already
// closed when the execution gets here), but at least the desktop will be in its
// original video mode!
//
if fInFullScreenNow then SwitchBackToDesktop;
FreeModeInfo;
UninitVMIEntry;
UnloadVMAN;
end;
// -------------------------------------- Window procedure -----------------------------
procedure RenderScene; forward;
function WndProc (Wnd: HWnd; Msg: ULong; Mp1, Mp2: MParam): MResult; cdecl;
var active:boolean;
ps:HPS;
_swp:SWP;
rcl:RECTL;
rgn:HRGN;
rgnCtl:RGNRECT;
pl:PointL;
rcls:array[0..49] of RECTL;
SetupBlitter:Setup_Blitter;
begin
result:=0;
case Msg of
WM_CREATE: begin // Window creation time
WinStartTimer(WinQueryAnchorBlock(Wnd), wnd, TMR_DRAWING, ImageUpdateWait);
end;
WM_TIMER: begin // Timer event
if SHORT1FROMMP(mp1)=TMR_DRAWING then WinPostMsg(Wnd, WM_PAINT, 0, 0);
end;
WM_SIZE, // Window resizing
WM_MINMAXFRAME: begin // Window minimize/maximize/restore
if fFullscreenMode then
begin // do nothing if in fullscreen mode!
result:=0; exit;
end; // else do the normal processing.
end;
WM_ACTIVATE: begin // activation/deactivation of window
active := Boolean(mp1);
if not Active then
begin // Switching away from the applicatoin
if fInFullscreenNow then // Switching away from the application, that is in FS mode!
begin
SwitchBackToDesktop;
WinShowWindow(hFrame, false); // hide window
WinSetVisibleRegionNotify( hClient, FALSE ); // turn VRN off
WinPostMsg(Wnd, WM_VRNDISABLED, 0, 0); // make sure dive turns off itself too
WinSetCapture(HWND_DESKTOP, 0); // release captured mouse
end;
end else
begin // Switching to the application
if fFullScreenMode then // Switching to the application that should run in FS mode!
begin
WinShowWindow(hFrame, true); // make window visible
WinSetVisibleRegionNotify( hClient, TRUE ); // turn on VRN
WinPostMsg(Wnd, WM_VRNENABLED, 0, 0); // setup dive
WinSetCapture(HWND_DESKTOP, hClient); // capture mouse
SwitchToFullScreen(NewModeInfo); // and do switching!
end;
end;
end;
WM_VRNDISABLED: begin // Visible region notification
fVrnDisabled := TRUE;
// Dive must be protected by mutex semaphore if it can be accessed
// from another thread too. It cannot be in our case, so no need
// for the mutex semaphore.
//
// DosRequestMutexSem (hmtxDiveMutex, -1L);
DiveSetupBlitter (hDiveInst, Nil);
// DosReleaseMutexSem (hmtxDiveMutex);
end;
WM_VRNENABLED: begin // Visible region notification
ps := WinGetPS (wnd);
rgn := GpiCreateRegion (ps, 0, NIL);
WinQueryVisibleRegion (wnd, rgn);
rgnCtl.ircStart := 1;
rgnCtl.crc := 50;
rgnCtl.ulDirection := 1;
// Get the all ORed rectangles
GpiQueryRegionRects (ps, rgn, NIL, rgnCtl, rcls[0]);
GpiDestroyRegion (ps, rgn);
WinReleasePS (ps);
// Now find the window position and size, relative to parent.
WinQueryWindowPos ( wnd, _swp );
// Convert the point to offset from desktop lower left.
pl.x := _swp.x;
pl.y := _swp.y;
WinMapWindowPoints ( hFrame, HWND_DESKTOP, pl, 1 );
// Tell DIVE about the new settings.
SetupBlitter.ulStructLen := sizeof( SETUP_BLITTER );
SetupBlitter.fccSrcColorFormat := SRCBUFFERFOURCC;
SetupBlitter.ulSrcWidth := SRCBUFFERWIDTH;
SetupBlitter.ulSrcHeight := SRCBUFFERHEIGHT;
SetupBlitter.ulSrcPosX := 0;
SetupBlitter.ulSrcPosY := 0;
SetupBlitter.fInvert := TRUE; // Invert, so the first line of buffer is the bottom-most line of image
SetupBlitter.ulDitherType := 1;
SetupBlitter.fccDstColorFormat := 0; // = FOURCC_SCRN constant in C;
SetupBlitter.lDstPosX := 0;
SetupBlitter.lDstPosY := 0;
if (not fFullScreenMode) then
begin
SetupBlitter.ulDstWidth := _swp.cx;
SetupBlitter.ulDstHeight := _swp.cy;
SetupBlitter.lScreenPosX := pl.x;
SetupBlitter.lScreenPosY := pl.y;
SetupBlitter.ulNumDstRects := rgnCtl.crcReturned;
SetupBlitter.pVisDstRects := @rcls;
end
else
begin
SetupBlitter.ulDstWidth := FULLSCREENWIDTH;
SetupBlitter.ulDstHeight := FULLSCREENHEIGHT;
SetupBlitter.lScreenPosX := 0;
SetupBlitter.lScreenPosY := 0;
SetupBlitter.ulNumDstRects := DIVE_FULLY_VISIBLE;
SetupBlitter.pVisDstRects := NIL;
end;
// DosRequestMutexSem(hmtxDiveMutex, -1L);
DiveSetupBlitter ( hDiveInst, @SetupBlitter );
// DosReleaseMutexSem(hmtxDiveMutex);
fVrnDisabled := FALSE;
end;
WM_CHAR: begin // Keypress notification
if(SHORT1FROMMP ( mp2 ) = ord('f')) then
begin
if fFullScreenMode then
begin // Switch to windowed
SwitchBackToDesktop;
WinSetCapture(HWND_DESKTOP, 0);
end else
begin // Switch to full screen
SwitchToFullscreen(NewModeInfo);
WinSetCapture(HWND_DESKTOP, hClient);
end;
WinShowWindow(hFrame, true);
WinSetVisibleRegionNotify( hClient, TRUE );
WinPostMsg(Wnd, WM_VRNENABLED, 0, 0);
fFullScreenMode:=fInFullScreenNow;
end;
if(SHORT1FROMMP ( mp2 ) = ord('q')) then WinPostMsg(wnd, WM_CLOSE, 0, 0);
result:=0;
exit;
end;
WM_PAINT: begin // Window redraw!
ps := WinBeginPaint(wnd,0,@rcl);
RenderScene;
WinEndPaint(ps);
result:=0;
exit;
end;
WM_CLOSE: begin // Window close
if fFullScreenMode then
begin // Switch to windowed
SwitchBackToDesktop;
WinSetCapture(HWND_DESKTOP, 0);
WinShowWindow(hFrame, true);
WinSetVisibleRegionNotify( hClient, TRUE );
WinPostMsg(Wnd, WM_VRNENABLED, 0, 0);
fFullScreenMode:=fInFullScreenNow;
end;
WinPostMsg (wnd, WM_QUIT, 0, 0);
result:=0;
end;
end;
if result=0 then result:=WinDefWindowProc(Wnd, Msg, Mp1, Mp2);
end;
// ------------------------ Procedures for simple PM usage -----------------------------
///////////////////////////////////////
// InitPM
//
// Initializes PM, creates a message queue,
// and creates the main window.
//
procedure InitPM;
var fcf:ulong;
begin
ab:=WinInitialize(0);
mq:=WinCreateMsgQueue(ab,0);
if mq=0 then
begin
Writeln('Could not create message queue!');
end;
WinRegisterClass( ab, 'MainDIVEWindowClass', WndProc, CS_SIZEREDRAW, 0);
fcf:=FCF_TITLEBAR or
FCF_SYSMENU or
FCF_MINBUTTON or
FCF_MAXBUTTON or
FCF_SIZEBORDER or
FCF_TASKLIST;
hFrame:=WinCreateStdWindow( HWND_DESKTOP, 0, fcf,
'MainDIVEWindowClass', AppTitle, 0,//WS_CLIPCHILDREN or WS_CLIPSIBLINGS,
0, 0, @hClient);
fFullScreenMode:=false;
end;
///////////////////////////////////////
// SetupMainWindow
//
// Sets the size/position of the main window,
// and makes it visible.
//
procedure SetupMainWindow;
begin
WinSetWindowPos( hFrame,
HWND_TOP,
(WinQuerySysValue (HWND_DESKTOP, SV_CXSCREEN) - SRCBUFFERWIDTH) div 2,
(WinQuerySysValue (HWND_DESKTOP, SV_CYSCREEN) - SRCBUFFERHEIGHT) div 2,
SRCBUFFERWIDTH,
SRCBUFFERHEIGHT + WinQuerySysValue (HWND_DESKTOP, SV_CYTITLEBAR)
+ WinQuerySysValue (HWND_DESKTOP, SV_CYDLGFRAME)*2
+ 1,
SWP_SIZE or SWP_ACTIVATE or SWP_SHOW or SWP_MOVE);
end;
///////////////////////////////////////
// UninitPM
//
// Destroys main window, and uninitializes
// PM.
//
procedure UninitPM;
begin
WinDestroyWindow(hFrame);
WinDestroyMsgQueue(mq);
WinTerminate(ab);
end;
// -------------------------------------------------- DIVE -----------------------------
///////////////////////////////////////
// ShutdownDIVE
//
// Switches back to Windowed mode if
// necessary, then frees allocated
// image buffer, and closes Dive.
//
procedure ShutdownDIVE;
begin
// We must switch back to windowed mode before closing Dive!
// (Because switching uses Dive too!)
if fInFullscreenNow then
SwitchBackToDesktop;
WinSetVisibleRegionNotify( hClient, false );
DiveFreeImageBuffer( hDiveInst, ulImage );
DiveClose( hDiveInst );
end;
///////////////////////////////////////
// SetupDIVE
//
// Opens Dive, allocates image buffer,
// and sets VRN, and sets up Dive for
// the first time (WM_VRNENABLED msg.)
//
procedure SetupDIVE;
var pFrameBuffer:pointer;
begin
fVrnDisabled := TRUE;
DiveOpen( hDiveInst, FALSE, pFrameBuffer );
DiveAllocImageBuffer( hDiveInst, ulImage, SRCBUFFERFOURCC, SRCBUFFERWIDTH, SRCBUFFERHEIGHT, 0, nil) ;
WinSetVisibleRegionNotify( hClient, TRUE );
WinPostMsg( hFrame, WM_VRNENABLED, 0, 0 );
end;
///////////////////////////////////////
// RenderScene
//
// Updates the image buffer, then
// blits it using Dive.
//
var basecolor:byte;
procedure RenderScene;
var pbBuffer: pointer;
i,j:longint;
ulScanLineBytes, ulScanLines:ulong;
pC:^Byte;
begin
if (ulImage=0) or
(fVRNDisabled) then exit;
DiveBeginImageBufferAccess(hDiveInst, ulImage, pbBuffer, ulScanLineBytes, ulScanLines);
// Move image down:
for j:=ulScanLines-2 downto 0 do
begin
move(mem[ulong(pbBuffer)+j*ulScanLineBytes], mem[ulong(pbBuffer)+(j+1)*ulScanLineBytes], ulScanLineBytes);
end;
// Create new firstline
pc:=pbBuffer;
inc(basecolor);
for i:=0 to ulScanLineBytes-1 do
begin
if random(100)<10 then
pc^:=random(256)
else
pc^:=BaseColor;
ulong(pc):=ulong(pc)+1;
end;
// fillchar(mem[longint(pbBuffer)+(j-1)*ulScanLineBytes], ulScanLineBytes, random(256));
DiveEndImageBufferAccess(hDiveInst, ulImage);
DiveBlitImage(hDiveInst, ulImage, DIVE_BUFFER_SCREEN );
end;
// ------------------------------------------ General stuff ----------------------------
///////////////////////////////////////
// ProcessParams
//
// Processes command line parameters
//
procedure ProcessParams;
var s,s2:string;
xpos:longint;
code:longint;
begin
if paramcount>0 then
begin
// First parameter: e.g. 1024x768x16 (fullscreen videomode)
s:=paramstr(1);
xpos:=pos('x',s);
s2:=copy(s,1, xpos-1); val(s2,FULLSCREENWIDTH, code);
delete(s,1, xpos);
xpos:=pos('x',s);
s2:=copy(s,1, xpos-1); val(s2,FULLSCREENHEIGHT, code);
delete(s,1, xpos);
val(s,FULLSCREENBPP, code);
s2:=paramstr(2);
if s2<>'' then
begin // Second parameter: source buffer (1024x768xR565)
s:=paramstr(2);
xpos:=pos('x',s);
s2:=copy(s,1, xpos-1); val(s2,SRCBUFFERWIDTH, code);
delete(s,1, xpos);
xpos:=pos('x',s);
s2:=copy(s,1, xpos-1); val(s2,SRCBUFFERHEIGHT, code);
delete(s,1, xpos);
SRCBUFFERFOURCC:=mmioFourCC(s[1],s[2],s[3],s[4]);
end;
end;
end;
// ------------------------------------------------ Main -------------------------------
begin
processparams;
// ---------------------- VMAN initialization -----------------
if not LoadVMAN then halt; // Load VMAN
if not InitVMIEntry then // Send "Hi! New process is here!" info to VMAN
begin
UnloadVMAN;
halt;
end;
if not QueryModeInfo then // Query available video modes
begin
UninitVMIEntry;
UnloadVMAN;
halt;
end;
if not FindNewModeInfo then // Find the fullscreen video mode
begin
writeln('Could not find video mode: ',FULLSCREENWIDTH,' x ',FULLSCREENHEIGHT,' x ',FULLSCREENBPP,'bpp!');
FreeModeInfo;
UninitVMIEntry;
UnloadVMAN;
halt;
end;
if not QueryCurrentMode then // Save the actual (desktop) video mode
begin
FreeModeInfo;
UninitVMIEntry;
UnloadVMAN;
halt;
end;
// Ok, VMAN has been initialized.
AddExitProc(VMANCleanUpExitProc); // Setup VMAN cleanup-process
// ---------------------- PM Initialization -------------------
InitPM;
// Setup DIVE
SetupDIVE;
// Setup and make visible the main window
SetupMainWindow;
// ---------------------- Main message loop -------------------
while WinGetMsg(Ab, Msg, 0, 0, 0) do
WinDispatchMsg(Ab, Msg);
// Shut down DIVE
ShutdownDIVE;
// ---------------------- PM uninitialization -----------------
UninitPM;
// ---------------------- VMAN Uninitialization ---------------
// Done by VMANCleanUpExitProc
end.
|
unit StockDayData_Get_163;
interface
uses
BaseApp,
Sysutils,
define_price,
UtilsHttp,
win.iobuffer,
define_data_163,
define_dealitem,
StockDayDataAccess;
type
PRT_DealDayData_Header163 = ^TRT_DealDayData_Header163;
TRT_DealDayData_Header163 = record
IsReady : Byte;
HeadColumnCount : Byte;
DateFormat_163: Sysutils.TFormatSettings;
HeadNameIndex : array[TDealDayDataHeadName_163] of SmallInt;
end;
PRT_DealData_163 = ^TRT_DealData_163;
TRT_DealData_163 = record
Stock : PRT_DealItem;
Day : Integer;
Code : AnsiString;
Name : AnsiString;
// price
Price_Close : double;
Price_High : double;
Price_Low : double;
Price_Open : double;
Price_PrevClose : double;
Price_Change : double;
Price_ChangeRate : double;
// deal
Deal_VolumeRate : double;
Deal_Volume : int64;
Deal_Amount : int64;
// value
Total_Value : int64;
Deal_Value : int64;
end;
function GetStockDataDay_163(App: TBaseApp;
AStockItem: PRT_DealItem;
AIsForceAll: Boolean;
AHttpSession: PHttpClientSession;
AHttpData: PIOBuffer): Boolean;
implementation
uses
Classes,
Windows,
Define_DataSrc,
define_dealstore_file,
//UtilsLog,
define_stock_quotes,
StockDayData_Load,
StockDayData_Save;
{$IFNDEF RELEASE}
const
LOGTAG = 'StockDayData_Get_163.pas';
{$ENDIF}
function ParseDataHeader_163(A163HeadData: PRT_DealDayData_Header163; AData: string; AParseDatas: TStringList): Boolean;
var
tmpHeader: TDealDayDataHeadName_163;
tmpHeader2: TDealDayDataHeadName_163;
tmpInt: integer;
begin
Result := false;
for tmpHeader := Low(TDealDayDataHeadName_163) to High(TDealDayDataHeadName_163) do
A163HeadData.HeadNameIndex[tmpHeader] := -1;
AParseDatas.Text := StringReplace(AData, ',', #13#10, [rfReplaceAll]);
for tmpInt := 0 to AParseDatas.Count - 1 do
begin
tmpHeader2 := headNone;
for tmpHeader := Low(TDealDayDataHeadName_163) to High(TDealDayDataHeadName_163) do
begin
if DealDayDataHeadNames_163[tmpHeader] = AParseDatas[tmpInt] then
begin
tmpHeader2 := tmpHeader;
Break;
end;
end;
if tmpHeader2 <> headNone then
begin
Result := true;
A163HeadData.HeadColumnCount := A163HeadData.HeadColumnCount + 1;
A163HeadData.HeadNameIndex[tmpHeader2] := tmpInt + 1;
end;
end;
end;
function ParseData_163(A163Data: PRT_DealData_163; A163HeadData: PRT_DealDayData_Header163; AData: string; AParseDatas: TStringList): Boolean;
function Get163Int64Value(value: string): int64;
var
s: string;
p: integer;
s1: string;
s2: string;
v1: double;
begin
Result := 0;
s := lowercase(value);
if '' <> s then
begin
p := Pos('e+', s);
if 0 < p then
begin
// '1.47514908121e+12'
s1 := copy(s, 1, p - 1);
s2 := copy(s, p + 2, maxint);
v1 := StrToFloatDef(s1, 0);
if 0 <> v1 then
begin
p := strtointdef(s2, 0);
Result := 1;
while 0 < p do
begin
Result := Result * 10;
p := p - 1;
end;
Result := Round(Result * v1);
end;
end else
begin
p := Pos('.', s);
if 0 < P then
begin
Result := StrToInt64Def(Copy(s, 1, p - 1), 0);
end else
begin
Result := StrToInt64Def(s, 0);
end;
end;
end;
end;
function GetParseTypeValue(AHeadNameType: TDealDayDataHeadName_163): string;
begin
Result := '';
if 0 < A163HeadData.HeadNameIndex[AHeadNameType] then
begin
//Log(LOGTAG, 'Column:' + IntToStr(A163HeadData.HeadNameIndex[AHeadNameType]) + '/' + IntToStr(AParseDatas.Count));
Result := AParseDatas[A163HeadData.HeadNameIndex[AHeadNameType] - 1];
end;
end;
var
tmpstr: string;
tmpDate: TDateTime;
tmpInt: integer;
begin
Result := false;
if 1 > A163HeadData.HeadColumnCount then
exit;
tmpstr := StringReplace(AData, #9, '', [rfReplaceAll]);
tmpstr := StringReplace(tmpstr, #13, '', [rfReplaceAll]);
tmpstr := StringReplace(tmpstr, #10, '', [rfReplaceAll]);
tmpstr := Trim(tmpstr);
AParseDatas.Text := StringReplace(tmpstr, ',', #13#10, [rfReplaceAll]);
tmpInt := Integer(High(TDealDayDataHeadName_163));
if AParseDatas.Count >= tmpInt then
begin
tmpstr := GetParseTypeValue(headDay);
TryStrToDate(tmpstr, tmpDate, A163HeadData.DateFormat_163);
if tmpDate <> 0 then
begin
A163Data.Code := GetParseTypeValue(headCode);
A163Data.Name := GetParseTypeValue(headName);
A163Data.Name := StringReplace(A163Data.Name, #32, '', [rfReplaceAll]);
A163Data.Day := Trunc(TmpDate);
// price
A163Data.Price_Close := StrToFloatDef(GetParseTypeValue(headPrice_Close), 0);
A163Data.Price_High := StrToFloatDef(GetParseTypeValue(headPrice_High), 0);
A163Data.Price_Low := StrToFloatDef(GetParseTypeValue(headPrice_Low), 0);
A163Data.Price_Open := StrToFloatDef(GetParseTypeValue(headPrice_Open), 0);
A163Data.Price_PrevClose := StrToFloatDef(GetParseTypeValue(headPrice_PrevClose), 0);
A163Data.Price_Change := StrToFloatDef(GetParseTypeValue(headPrice_Change), 0);
A163Data.Price_ChangeRate := StrToFloatDef(GetParseTypeValue(headPrice_ChangeRate), 0);
// deal
A163Data.Deal_VolumeRate := StrToFloatDef(GetParseTypeValue(headDeal_VolumeRate), 0);
A163Data.Deal_Volume := Get163Int64Value(GetParseTypeValue(headDeal_Volume));
A163Data.Deal_Amount := Get163Int64Value(GetParseTypeValue(headDeal_Amount));
// value
A163Data.Total_Value := Get163Int64Value(GetParseTypeValue(headTotal_Value));
A163Data.Deal_Value := Get163Int64Value(GetParseTypeValue(headDeal_Value));
Result := true;
end;
end;
end;
function ParseStockDataDay_163(ADataAccess: TStockDayDataAccess; AData: PIOBuffer): Boolean;
var
tmp163data: TRT_DealData_163;
tmp163header: TRT_DealDayData_Header163;
tmpRowDatas: TStringList;
tmpParseDatas: TStringList;
i: integer;
tmpDealData: PRT_Quote_Day;
tmpIsCheckedName: Boolean;
tmpHttpHeadParse: THttpHeadParseSession;
begin
Result := false;
if nil = AData then
exit;
//SDLog(LOGTAG, 'ParseStockDataDay_163:' + ADataAccess.StockItem.sCode);
FillChar(tmpHttpHeadParse, SizeOf(tmpHttpHeadParse), 0);
HttpBufferHeader_Parser(AData, @tmpHttpHeadParse);
if 1 > tmpHttpHeadParse.HeadEndPos then
begin
//SDLog(LOGTAG, 'ParseStockDataDay_163 Fail:' + IntToStr(tmpHttpHeadParse.RetCode));
//SDLog(LOGTAG, PAnsiChar(@PIOBuffer(AData).Data[0]));
//SDLog(LOGTAG, 'ParseStockDataDay_163 Fail');
end else
begin
tmpIsCheckedName := false;
FillChar(tmp163header, SizeOf(tmp163header), 0);
tmpRowDatas := TStringList.Create;
tmpParseDatas := TStringList.Create;
try
tmpRowDatas.Text := PAnsiChar(@AData.Data[tmpHttpHeadParse.HeadEndPos + 1]);
//SDLog('', 'ParseStockDataDay_163:' + tmpRowDatas.Text);
if 1 < tmpRowDatas.Count then
begin
for i := 0 to tmpRowDatas.Count - 1 do
begin
if 0 = tmp163header.IsReady then
begin
if ParseDataHeader_163(@tmp163header, tmpRowDatas[i], tmpParseDatas) then
begin
tmp163header.IsReady := 1;
tmp163header.DateFormat_163.DateSeparator := '-';
tmp163header.DateFormat_163.TimeSeparator := ':';
tmp163header.DateFormat_163.ListSeparator := ';';
tmp163header.DateFormat_163.ShortDateFormat := 'yyyy-mm-dd';
tmp163header.DateFormat_163.LongDateFormat := 'yyyy-mm-dd';
end;
end else
begin
if ParseData_163(@tmp163data, @tmp163header, tmpRowDatas[i], tmpParseDatas) then
begin
Result := true;
// 网易是倒叙排的 以最早的为准
if not tmpIsCheckedName then
begin
tmpIsCheckedName := true;
if tmp163data.Name <> ADataAccess.StockItem.Name then
begin
ADataAccess.StockItem.Name := tmp163data.Name;
ADataAccess.StockItem.IsDataChange := 1;
end;
end;
if (0 < tmp163data.Day) and (tmp163data.Price_Low > 0) and (tmp163data.Price_High > 0) and
(tmp163data.Deal_Amount > 0) and (tmp163data.Deal_Volume > 0) then
begin
if (Trunc(Now) >= tmp163data.Day) then
begin
tmpDealData := ADataAccess.CheckOutRecord(tmp163data.Day);
if (nil <> tmpDealData) then
begin
SetRTPricePack(@tmpDealData.PriceRange.PriceHigh, tmp163data.Price_High);
SetRTPricePack(@tmpDealData.PriceRange.PriceLow, tmp163data.Price_Low);
SetRTPricePack(@tmpDealData.PriceRange.PriceOpen, tmp163data.Price_Open);
SetRTPricePack(@tmpDealData.PriceRange.PriceClose, tmp163data.Price_Close);
tmpDealData.DealVolume := tmp163data.Deal_Volume;
tmpDealData.DealAmount := tmp163data.Deal_Amount;
tmpDealData.TotalValue := tmp163data.Total_Value;
tmpDealData.DealValue := tmp163data.Deal_Value;
end;
end;
end;
end;
end;
end;
end;
finally
tmpRowDatas.Free;
tmpParseDatas.Free;
end;
ADataAccess.Sort;
end;
end;
function GetStockDataDay_163(
App: TBaseApp;
AStockItem: PRT_DealItem;
AIsForceAll: Boolean;
AHttpSession: PHttpClientSession;
AHttpData: PIOBuffer): Boolean;
var
tmpStockDataAccess: TStockDayDataAccess;
tmpUrl: string;
tmpLastDealDate: Word;
tmpInt: integer;
tmpQuoteDay: PRT_Quote_Day;
tmpHttpData: PIOBuffer;
tmpHour, tmpMinute, tmpSecond, tmpMSec: Word;
tmpIsWorkDay: Boolean;
begin
//Log(LOGTAG, 'GetStockDataDay_163:' + IntToStr(AStockItem.iCode));
Result := false;
tmpLastDealDate := Trunc(now());
tmpInt := DayOfWeek(tmpLastDealDate);
tmpIsWorkDay := true;
if 1 = tmpInt then
begin
tmpLastDealDate := tmpLastDealDate - 2;
tmpIsWorkDay := false;
end;
if 7 = tmpInt then
begin
tmpLastDealDate := tmpLastDealDate - 1;
tmpIsWorkDay := false;
end;
if tmpIsWorkDay then
begin
DecodeTime(now, tmpHour, tmpMinute, tmpSecond, tmpMSec);
if tmpHour < 17 then
begin
tmpLastDealDate := tmpLastDealDate - 1;
end;
end;
tmpStockDataAccess := TStockDayDataAccess.Create(AStockItem, Src_163, weightNone);
try
LoadStockDayData(App, tmpStockDataAccess);
if AIsForceAll or CheckNeedLoadStockDayData(App, tmpStockDataAccess, tmpLastDealDate) then
begin
tmpUrl := Base163DayUrl1 + 'code=' + GetStockCode_163(AStockItem);
if not AIsForceAll then
begin
if tmpStockDataAccess.LastDealDate > 0 then
begin
if tmpLastDealDate >= tmpStockDataAccess.LastDealDate + 1 then
begin
tmpUrl := tmpUrl +
'&start=' + FormatDateTime('yyyymmdd', tmpStockDataAccess.LastDealDate - 1) +
'&end=' + FormatDateTime('yyyymmdd', tmpLastDealDate) +
'&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP';
//SDLog('', 'Downloader_Download 163:' + tmpUrl);
end else
begin
exit;
end;
end;
end;
end else
begin
exit;
end;
if RunStatus_Active <> App.RunStatus then
exit;
//Log(LOGTAG, 'GetStockDataDay_163_' + IntToStr(AStockItem.iCode) + '_' + AStockItem.sCode + ':' + tmpUrl);
// parse result data
tmpHttpData := GetHttpUrlData(tmpUrl, AHttpSession, AHttpData);
if nil <> tmpHttpData then
begin
try
if ParseStockDataDay_163(tmpStockDataAccess, tmpHttpData) then
begin
Result := true;
tmpStockDataAccess.Sort;
SaveStockDayData(App, tmpStockDataAccess);
end;
finally
if AHttpData <> tmpHttpData then
begin
CheckInIOBuffer(tmpHttpData);
end;
end;
end;
finally
if 0 = AStockItem.FirstDealDate then
begin
if 0 < tmpStockDataAccess.RecordCount then
begin
tmpQuoteDay := tmpStockDataAccess.RecordItem[0];
AStockItem.FirstDealDate := tmpQuoteDay.DealDate.Value;
AStockItem.IsDataChange := 1;
end;
end;
tmpStockDataAccess.Free;
end;
end;
end.
|
//Exercicio 28: Escreva um algoritmo que peça ao operador o nome de usuário e uma senha. Para ter acesso o nome de usuário
//deve ser "user" ou "USER" e a senha deve ser "adoroalgoritmos" ou "ADOROALGORITMOS". Após a digitação dos dados,
//exibir na tela: "Acesso Permitido!" ou "Acesso Negado!".
{ Solução em Portugol
Algoritmo Exercicio ; //A = (usuario = "user") ou (usuario = "USER") --> se(A e B) [Avaliar a tabela]
Var //B = (senha = "adoroalgoritmos") ou (senha = "ADOROALGORITMOS") A e B = verdadeiro, então exibe acesso perimitido
usuario, senha: caracter; ///////////////////////////////////// A e B = falso, então exibe acesso negado.
Inicio // A B A e B //
exiba("Tela de acesso."); // V F F //
exiba("Digite o nome de usuário: "); // F V F //
leia(usuario); // V V V //
exiba("Digite a senha: "); // F F F //
leia(senha); /////////////////////////////////////
se(((usuario = "user") ou (usuario = "USER")) e ((senha = "adoroalgoritmos") ou (senha = "ADOROALGORITMOS")))
então exiba("Acesso Permitido!")
senão exiba("Acesso Negado!");
fimse;
Fim.
}
// Solução em Pascal
Program Exercicio;
uses crt;
var
usuario, senha: string;
begin
clrscr;
writeln('Tela de acesso.');
writeln('Digite o nome de usuário: ');
readln(usuario);
writeln('Digite a senha: ');
readln(senha);
if(((usuario = 'user') or (usuario = 'USER')) and ((senha = 'adoroalgoritmos') or (senha = 'ADOROALGORITMOS')))
then writeln('Acesso Permitido!')
else writeln('Acesso Negado!');
repeat until keypressed;
end. |
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Description: This sample program show how to use TNntpCli to write a news
enabled application.
Creation: December 24, 1997
Version: 6.00
EMail: http://www.overbyte.be francois.piette@overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1997-2006 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
Updates:
Dec 29, 1997 V0.91 Adapted to be compatible with Delphi 1
Jan 04, 1998 V0.92 Added LIST OVERVIEW.FMT, XOVER and DATE
Jan 31, 1998 V0.93 Added the UserEditBox (used for Post command)
Added code to get UserName and EMail from IE settings
Aug 14, 1999 V0.94 Added support for XHDR and MODE READER.
Corrected a bug that let Connect and Abort button
disabled when DNS lookup failed.
Jan 11, 2004 V1.00 Jumped to version 1.00.
Add ListMOTD button
Mar 25, 2006 V6.00 New version 6 started from V5.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsNewsReader1;
interface
uses
WinTypes, WinProcs, Messages, SysUtils, Classes, Controls, Forms,
StdCtrls, ExtCtrls, IniFiles,
OverbyteIcsWndControl, OverbyteIcsNntpCli;
const
NewsRdrVersion = 100;
CopyRight : String = ' NewsRdr (c) 1997-2006 F. Piette V1.00 ';
type
TNNTPForm = class(TForm)
NntpCli1: TNntpCli;
Panel1: TPanel;
ServerEdit: TEdit;
ConnectButton: TButton;
Label1: TLabel;
DisplayMemo: TMemo;
AbortButton: TButton;
GroupButton: TButton;
GroupEdit: TEdit;
ArticleNumEdit: TEdit;
ArticleByNumberButton: TButton;
ArticleByIDButton: TButton;
NextButton: TButton;
LastButton: TButton;
HeadByNumberButton: TButton;
HeadByIDButton: TButton;
BodyByNumberButton: TButton;
BodyByIDButton: TButton;
StatByNumberButton: TButton;
StatByIDButton: TButton;
ListButton: TButton;
ArticleIDEdit: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
PostButton: TButton;
QuitButton: TButton;
FileEdit: TEdit;
Label5: TLabel;
NewGroupsButton: TButton;
NewNewsButton: TButton;
HelpButton: TButton;
XOverButton: TButton;
OverViewFmtButton: TButton;
DateButton: TButton;
UserEdit: TEdit;
Label6: TLabel;
Label7: TLabel;
UserNameEdit: TEdit;
Label8: TLabel;
PasswordEdit: TEdit;
AuthenticateButton: TButton;
ModeReaderButton: TButton;
XHdrButton: TButton;
ListMotdButton: TButton;
procedure ConnectButtonClick(Sender: TObject);
procedure NntpCli1SessionConnected(Sender: TObject; Error: Word);
procedure NntpCli1SessionClosed(Sender: TObject; Error: Word);
procedure AbortButtonClick(Sender: TObject);
procedure GroupButtonClick(Sender: TObject);
procedure NntpCli1RequestDone(Sender: TObject; RqType: TNntpRequest; Error: Word);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ArticleByNumberButtonClick(Sender: TObject);
procedure NntpCli1DataAvailable(Sender: TObject; Error: Word);
procedure NntpCli1MessageLine(Sender: TObject);
procedure NntpCli1MessageBegin(Sender: TObject);
procedure NntpCli1MessageEnd(Sender: TObject);
procedure ArticleByIDButtonClick(Sender: TObject);
procedure NextButtonClick(Sender: TObject);
procedure LastButtonClick(Sender: TObject);
procedure HeadByIDButtonClick(Sender: TObject);
procedure HeadByNumberButtonClick(Sender: TObject);
procedure BodyByIDButtonClick(Sender: TObject);
procedure BodyByNumberButtonClick(Sender: TObject);
procedure StatByIDButtonClick(Sender: TObject);
procedure StatByNumberButtonClick(Sender: TObject);
procedure ListButtonClick(Sender: TObject);
procedure PostButtonClick(Sender: TObject);
procedure QuitButtonClick(Sender: TObject);
procedure NewGroupsButtonClick(Sender: TObject);
procedure NewNewsButtonClick(Sender: TObject);
procedure HelpButtonClick(Sender: TObject);
procedure XOverButtonClick(Sender: TObject);
procedure OverViewFmtButtonClick(Sender: TObject);
procedure DateButtonClick(Sender: TObject);
procedure AuthenticateButtonClick(Sender: TObject);
procedure ModeReaderButtonClick(Sender: TObject);
procedure XHdrButtonClick(Sender: TObject);
procedure NntpCli1XHdrBegin(Sender: TObject);
procedure NntpCli1XHdrEnd(Sender: TObject);
procedure NntpCli1XHdrLine(Sender: TObject);
procedure ListMotdButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FIniFileName : String;
FInitialized : Boolean;
FDataStream : TStream;
function GetStream : TStream;
procedure Display(Msg : String);
procedure LineToStream(Buf : String);
end;
var
NNTPForm: TNNTPForm;
implementation
{$R *.DFM}
{$IFNDEF VER80}
uses
Registry;
{$ENDIF}
const
SectionWindow = 'Window';
KeyTop = 'Top';
KeyLeft = 'Left';
KeyWidth = 'Width';
KeyHeight = 'Height';
SectionData = 'Data';
KeyServer = 'Server';
KeyGroup = 'Group';
KeyArticleNum = 'ArticleNum';
KeyArticleID = 'ArticleID';
KeyFile = 'File';
KeyUser = 'User';
KeyUserName = 'UserName';
KeyPassword = 'Password';
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF VER80}
function TrimRight(Str : String) : String;
var
i : Integer;
begin
i := Length(Str);
while (i > 0) and (Str[i] = ' ') do
i := i - 1;
Result := Copy(Str, 1, i);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TrimLeft(Str : String) : String;
var
I : Integer;
begin
if Str[1] <> ' ' then
Result := Str
else begin
I := 1;
while (I <= Length(Str)) and (Str[I] = ' ') do
I := I + 1;
Result := Copy(Str, I, Length(Str) - I + 1);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function Trim(Str : String) : String;
begin
Result := TrimLeft(TrimRight(Str));
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.FormCreate(Sender: TObject);
begin
FIniFileName := LowerCase(ExtractFileName(Application.ExeName));
FIniFileName := Copy(FIniFileName, 1, Length(FIniFileName) - 3) + 'ini';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.FormShow(Sender: TObject);
var
IniFile : TIniFile;
EMail : String;
UserName : String;
{$IFNDEF VER80}
Reg : TRegistry;
Key : String;
{$ENDIF}
begin
if FInitialized then
Exit;
FInitialized := TRUE;
EMail := 'your.name@yourcompany.domain';
UserName := 'Your Name';
{$IFNDEF VER80}
{ Get username and EMail from the Internet Explorer settings }
{ Should add code for Netscape Navigator... }
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
Key := '\Software\Microsoft\Internet Mail and News\Mail';
if Reg.OpenKey(Key, FALSE) then begin
EMail := Reg.ReadString('Sender EMail');
UserName := Reg.ReadString('Sender Name');
end;
Reg.CloseKey;
Reg.Free;
{$ENDIF}
IniFile := TIniFile.Create(FIniFileName);
Top := IniFile.ReadInteger(SectionWindow, KeyTop, Top);
Left := IniFile.ReadInteger(SectionWindow, KeyLeft, Left);
Width := IniFile.ReadInteger(SectionWindow, KeyWidth, Width);
Height := IniFile.ReadInteger(SectionWindow, KeyHeight, Height);
ServerEdit.Text := IniFile.ReadString(SectionData, KeyServer, '');
ArticleNumEdit.Text := IniFile.ReadString(SectionData, KeyArticleNum, '');
ArticleIDEdit.Text := IniFile.ReadString(SectionData, KeyArticleID, '');
FileEdit.Text := IniFile.ReadString(SectionData, KeyFile,
'nntprdr.txt');
UserNameEdit.Text := IniFile.ReadString(SectionData, KeyUserName, '');
PasswordEdit.Text := IniFile.ReadString(SectionData, KeyPassword, '');
UserEdit.Text := IniFile.ReadString(SectionData, KeyUser,
'"' + UserName + '" <' + EMail + '>');
GroupEdit.Text := IniFile.ReadString(SectionData, KeyGroup,
'borland.public.delphi.thirdparty-tools');
IniFile.Free;
DisplayMemo.Clear;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.FormClose(Sender: TObject; var Action: TCloseAction);
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(FIniFileName);
IniFile.WriteString(SectionData, KeyServer, ServerEdit.Text);
IniFile.WriteString(SectionData, KeyGroup, GroupEdit.Text);
IniFile.WriteString(SectionData, KeyArticleNum, ArticleNumEdit.Text);
IniFile.WriteString(SectionData, KeyArticleID, ArticleIDEdit.Text);
IniFile.WriteString(SectionData, KeyFile, FileEdit.Text);
IniFile.WriteString(SectionData, KeyUser, UserEdit.Text);
IniFile.WriteString(SectionData, KeyUserName, UserNameEdit.Text);
IniFile.WriteString(SectionData, KeyPassword, PasswordEdit.Text);
IniFile.WriteInteger(SectionWindow, KeyTop, Top);
IniFile.WriteInteger(SectionWindow, KeyLeft, Left);
IniFile.WriteInteger(SectionWindow, KeyWidth, Width);
IniFile.WriteInteger(SectionWindow, KeyHeight, Height);
IniFile.Free;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.Display(Msg : String);
begin
{ Limit the memo to 100 lines }
while DisplayMemo.Lines.Count > 100 do
DisplayMemo.Lines.Delete(1);
DisplayMemo.Lines.Add(Msg);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.NntpCli1SessionConnected(Sender: TObject; Error: Word);
begin
AbortButton.Enabled := TRUE;
Display('Connected, StatusCode = ' + IntToStr(NntpCli1.StatusCode));
if NntpCli1.PostingPermited then
Display('Posting permited')
else
Display('Posting not permited');
Display(NntpCli1.LastResponse);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.NntpCli1SessionClosed(Sender: TObject; Error: Word);
begin
AbortButton.Enabled := FALSE;
ConnectButton.Enabled := TRUE;
Display('Connection closed');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called for each NNTP command when the command has }
{ been exected (correctly or not). }
procedure TNNTPForm.NntpCli1RequestDone(
Sender: TObject;
RqType: TNntpRequest;
Error: Word);
begin
Display('Request done. LastResponse = ' +
NntpCli1.LastResponse);
if Error = 0 then
Display('No error')
else
Display('Error #' + IntToStr(Error));
case RqType of
nntpConnect:
begin
if Error <> 0 then begin
AbortButton.Enabled := FALSE;
ConnectButton.Enabled := TRUE;
Display('Connect failed');
end;
end;
nntpGroup:
begin
Display('ArticleEstimated = ' + IntToStr(NntpCli1.ArticleEstimated));
Display('ArticleFirst = ' + IntToStr(NntpCli1.ArticleFirst));
Display('ArticleLast = ' + IntToStr(NntpCli1.ArticleLast));
ArticleNumEdit.Text := IntToStr(NntpCli1.ArticleFirst);
end;
nntpPost, nntpQuit, nntpAbort, nntpHelp, nntpNewGroups, nntpNewNews,
nntpXOver, nntpListOverViewFmt, nntpAuthenticate, nntpModeReader,
nntpXHdr:
begin
{ Nothing to do }
end;
nntpDate:
begin
Display('Server Date is ' + DateTimeToStr(NntpCli1.ServerDate));
end;
nntpStatByNumber, nntpStatByID,
nntpHeadByNumber, nntpHeadByID,
nntpBodyByNumber, nntpBodyByID,
nntpArticleByNumber, nntpArticleByID,
nntpNext, nntpLast:
begin
Display('ArticleNumber = ' +
IntToStr(NntpCli1.ArticleNumber));
Display('ArticleID = ' +
'<' + NntpCli1.ArticleID + '>');
if Error = 0 then begin
ArticleNumEdit.Text := IntToStr(NntpCli1.ArticleNumber);
ArticleIDEdit.Text := NntpCli1.ArticleID;
end;
end;
else
Display('Unknown request type.');
end;
{ If any stream where used, destroy it }
if Assigned(FDataStream) then begin
FDataStream.Free;
FDataStream := nil;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called by TNntpCli when it has received data and }
{ don't know what to do with it. It should normally not occur ! }
procedure TNNTPForm.NntpCli1DataAvailable(Sender: TObject; Error: Word);
begin
Display('Data: ' + NntpCli1.LastResponse);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called by TNntpCli component just before the }
{ component will begin receiving a message. It's a good place to open a }
{ file or start a progress bar. }
procedure TNNTPForm.NntpCli1MessageBegin(Sender: TObject);
begin
Display('Message begin');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called by TNntpCli component for each line of an }
{ incomming message. Header line as well as body lines are comming here. }
{ It's a good place to write to a file or update screen or progress bar. }
{ It's also the place to intercept header lines. }
procedure TNNTPForm.NntpCli1MessageLine(Sender: TObject);
var
NewsGroupName : String;
LastArticle : Integer;
FirstArticle : Integer;
PostingFlag : Char;
begin
Display('Line: ' + NntpCli1.LastResponse);
ParseListLine(NntpCli1.LastResponse,
NewsGroupName,
LastArticle,
FirstArticle,
PostingFlag);
{ It the place to do something with NewsGroupName, LastArticle, }
{ FirstArticle and PostingFlag }
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called by TNntpCli component when a message has }
{ been received completely. It's a good place to close a file, delete the }
{ progress bar and alert user. }
procedure TNNTPForm.NntpCli1MessageEnd(Sender: TObject);
begin
Display('Message End');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This function is called internally to create a TFileStream if any file }
{ name is specified in the FileEdit box. If the edit box is blank, nil is }
{ returned. The TFileStream will be supplyed to the comoponent for every }
{ command which can take a TStream to store data such as ArticleByNum. }
{ The stream is destroyed in the OnRequestDone event handler. }
function TNNTPForm.GetStream : TStream;
begin
{ Delete the previous stream if not already done }
if Assigned(FDataStream) then begin
FDataStream.Free;
FDataStream := nil;
end;
if Trim(FileEdit.Text) = '' then
FDataStream := nil
else begin
{ Try to open the file stream. Trap errors. }
try
FDataStream := TFileStream.Create(Trim(FileEdit.Text), fmCreate);
except
on E:Exception do begin
{ Display an error message in our TMemo }
Display(E.Message);
FDataStream := nil;
raise; { Show the exception box }
end;
end;
end;
Result := FDataStream;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.ConnectButtonClick(Sender: TObject);
begin
DisplayMemo.Clear;
ConnectButton.Enabled := FALSE;
NntpCli1.Host := ServerEdit.Text;
NntpCli1.Connect;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.AbortButtonClick(Sender: TObject);
begin
NntpCli1.Abort;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.QuitButtonClick(Sender: TObject);
begin
NntpCli1.Quit;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.GroupButtonClick(Sender: TObject);
begin
NntpCli1.Group(GroupEdit.Text);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.NextButtonClick(Sender: TObject);
begin
NntpCli1.Next;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.LastButtonClick(Sender: TObject);
begin
NntpCli1.Last;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.ArticleByIDButtonClick(Sender: TObject);
begin
NntpCli1.ArticleByID(ArticleIDEdit.Text, GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.ArticleByNumberButtonClick(Sender: TObject);
begin
NntpCli1.ArticleByNumber(StrToInt(ArticleNumEdit.Text), GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.HeadByIDButtonClick(Sender: TObject);
begin
NntpCli1.HeadByID(ArticleIDEdit.Text, GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.HeadByNumberButtonClick(Sender: TObject);
begin
NntpCli1.HeadByNumber(StrToInt(ArticleNumEdit.Text), GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.BodyByIDButtonClick(Sender: TObject);
begin
NntpCli1.BodyByID(ArticleIDEdit.Text, GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.BodyByNumberButtonClick(Sender: TObject);
begin
NntpCli1.BodyByNumber(StrToInt(ArticleNumEdit.Text), GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.StatByIDButtonClick(Sender: TObject);
begin
NntpCli1.StatByID(ArticleIDEdit.Text);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.StatByNumberButtonClick(Sender: TObject);
begin
NntpCli1.StatByNumber(StrToInt(ArticleNumEdit.Text));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.ListButtonClick(Sender: TObject);
begin
if Application.MessageBox('This could take a VERY long time, proceed ? ',
'Warning', MB_YESNO) <> ID_YES then
Exit;
NntpCli1.List(GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.NewGroupsButtonClick(Sender: TObject);
begin
NntpCli1.NewGroups(Now - 10, FALSE, '', GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.NewNewsButtonClick(Sender: TObject);
begin
NntpCli1.NewNews(Now - 1, FALSE, GroupEdit.Text, '', GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.HelpButtonClick(Sender: TObject);
begin
NntpCli1.Help(GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNntpForm.LineToStream(Buf : String);
begin
Display('Line: ' + Buf);
Buf := Buf + #13#10;
FDataStream.WriteBuffer(Buf[1], Length(Buf));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Posting a message require to build the message, including his header. }
{ Here we use a TMemoryStream to create a message on the fly. Normally we }
{ should use a TFileStream to get the message from a file where it has }
{ been written by some user interface. }
procedure TNNTPForm.PostButtonClick(Sender: TObject);
begin
{ Delete the stream if not already done }
if Assigned(FDataStream) then begin
FDataStream.Free;
FDataStream := nil;
end;
{ Create a new stream in memory }
FDataStream := TMemoryStream.Create;
{ Write the message header }
LineToStream('From: ' + UserEdit.Text);
LineToStream('Newsgroups: ' + GroupEdit.Text);
LineToStream('Subject: Internet Components Suite (ICS)');
LineToStream('Organization: None');
LineToStream('X-Newsreader: NNTP component ' +
'(http://www.overbyte.be)');
{ End of header is a blank line }
LineToStream('');
{ Write the message body }
LineToStream('');
LineToStream('The Internet Component Suite is a set of native');
LineToStream('components for Borland Delphi (all versions,');
LineToStream('including 16 bits) and Borland C++ Builder. The');
LineToStream('major TCP/IP protocols are supported for building');
LineToStream('client/server, intranet or Internet applications.');
LineToStream('');
LineToStream('TCP, UDP, TELNET, FTP, SMTP, POP3, PING, FINGER, HTTP,');
LineToStream('NNTP and more. Each component has samples writen');
LineToStream('in Delphi and in C++ Builder. Several client/server');
LineToStream('applications, including an event-driven and a');
LineToStream('multi-threaded server, a complete FTP client and');
LineToStream('TELNET client with ansi emulation are provided.');
LineToStream('Full source code provided for everything.');
LineToStream('');
LineToStream('The Internet Component Suite is freeware, royalty');
LineToStream('free and support is done using a mailing list.');
LineToStream('Visit our website and download now from');
LineToStream('http://www.overbyte.be');
{ Set stream pointer to beginning of stream because TNntpCli will post }
{ from the current position }
FDataStream.Seek(0, soFromBeginning );
{ Ask the component to post the stream. The posting occurs in the }
{ background ! We will receive the OnRequestDone event when done. }
{ It's in this event handler that the stream must be destroyed }
NntpCli1.Post(FDataStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.XOverButtonClick(Sender: TObject);
begin
NntpCli1.XOver(ArticleNumEdit.Text, GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.OverViewFmtButtonClick(Sender: TObject);
begin
NntpCli1.ListOverViewFmt(GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.DateButtonClick(Sender: TObject);
begin
NntpCli1.Date;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.AuthenticateButtonClick(Sender: TObject);
begin
NntpCli1.UserName := UserNameEdit.Text;
NntpCli1.Password := PasswordEdit.Text;
NntpCli1.Authenticate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.ModeReaderButtonClick(Sender: TObject);
begin
NntpCli1.ModeReader;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.XHdrButtonClick(Sender: TObject);
begin
NntpCli1.XHdr(GetStream, 'subject', ArticleNumEdit.Text);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.NntpCli1XHdrBegin(Sender: TObject);
begin
Display('XHdr begin');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.NntpCli1XHdrEnd(Sender: TObject);
begin
Display('Xhdr End');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.NntpCli1XHdrLine(Sender: TObject);
begin
Display('XHdr: ' + NntpCli1.LastResponse);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TNNTPForm.ListMotdButtonClick(Sender: TObject);
begin
NntpCli1.ListMotd(GetStream);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit Excel_TLB_Constants;
// ************************************************************************ //
// NOTE
// -------
// This file is created by importing the Excel Type Library and then extracting
// the constants section of the TLB.pas file. Other declaraitons are not required.
// ************************************************************************ //
// $Rev: 52393 $
// File generated on 27 Dec 2019 19:52:33 from Type Library described below.
// ************************************************************************
//86\Microsoft Shared\OFFICE16\MSO.DLL)
// (2) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb)
// (3) v5.3 VBIDE, (C:\Program Files (x86)\Microsoft Office\Root\VFS\ProgramFilesCommonX86\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB)
// Type Lib: C:\Program Files (x86)\Microsoft Office\Root\Office16\EXCEL.EXE (1)
// LIBID: {00020813-0000-0000-C000-000000000046}
// LCID: 0
// Helpfile: C:\Program Files (x86)\Microsoft Office\Root\Office16\VBAXL10.CHM
// SYS_KIND: SYS_WIN32
// Errors:
// Hint: Symbol 'IFont' renamed to 'ExcelIFont'
Interface
// *********************************************************************//
// Declaration of Enumerations defined in Type Library
//
// *********************************************************************//
const
// Constants for enum Constants
xlAll = $FFFFEFF8;
xlAutomatic = $FFFFEFF7;
xlBoth = $00000001;
xlCenter = $FFFFEFF4;
xlChecker = $00000009;
xlCircle = $00000008;
xlCorner = $00000002;
xlCrissCross = $00000010;
xlCross = $00000004;
xlDiamond = $00000002;
xlDistributed = $FFFFEFEB;
xlDoubleAccounting = $00000005;
xlFixedValue = $00000001;
xlFormats = $FFFFEFE6;
xlGray16 = $00000011;
xlGray8 = $00000012;
xlGrid = $0000000F;
xlHigh = $FFFFEFE1;
xlInside = $00000002;
xlJustify = $FFFFEFDE;
xlLightDown = $0000000D;
xlLightHorizontal = $0000000B;
xlLightUp = $0000000E;
xlLightVertical = $0000000C;
xlLow = $FFFFEFDA;
xlManual = $FFFFEFD9;
xlMinusValues = $00000003;
xlModule = $FFFFEFD3;
xlNextToAxis = $00000004;
xlNone = $FFFFEFD2;
xlNotes = $FFFFEFD0;
xlOff = $FFFFEFCE;
xlOn = $00000001;
xlPercent = $00000002;
xlPlus = $00000009;
xlPlusValues = $00000002;
xlSemiGray75 = $0000000A;
xlShowLabel = $00000004;
xlShowLabelAndPercent = $00000005;
xlShowPercent = $00000003;
xlShowValue = $00000002;
xlSimple = $FFFFEFC6;
xlSingle = $00000002;
xlSingleAccounting = $00000004;
xlSolid = $00000001;
xlSquare = $00000001;
xlStar = $00000005;
xlStError = $00000004;
xlToolbarButton = $00000002;
xlTriangle = $00000003;
xlGray25 = $FFFFEFE4;
xlGray50 = $FFFFEFE3;
xlGray75 = $FFFFEFE2;
xlBottom = $FFFFEFF5;
xlLeft = $FFFFEFDD;
xlRight = $FFFFEFC8;
xlTop = $FFFFEFC0;
xl3DBar = $FFFFEFFD;
xl3DSurface = $FFFFEFF9;
xlBar = $00000002;
xlColumn = $00000003;
xlCombination = $FFFFEFF1;
xlCustom = $FFFFEFEE;
xlDefaultAutoFormat = $FFFFFFFF;
xlMaximum = $00000002;
xlMinimum = $00000004;
xlOpaque = $00000003;
xlTransparent = $00000002;
xlBidi = $FFFFEC78;
xlLatin = $FFFFEC77;
xlContext = $FFFFEC76;
xlLTR = $FFFFEC75;
xlRTL = $FFFFEC74;
xlFullScript = $00000001;
xlPartialScript = $00000002;
xlMixedScript = $00000003;
xlMixedAuthorizedScript = $00000004;
xlVisualCursor = $00000002;
xlLogicalCursor = $00000001;
xlSystem = $00000001;
xlPartial = $00000003;
xlHindiNumerals = $00000003;
xlBidiCalendar = $00000003;
xlGregorian = $00000002;
xlComplete = $00000004;
xlScale = $00000003;
xlClosed = $00000003;
xlColor1 = $00000007;
xlColor2 = $00000008;
xlColor3 = $00000009;
xlConstants = $00000002;
xlContents = $00000002;
xlBelow = $00000001;
xlCascade = $00000007;
xlCenterAcrossSelection = $00000007;
xlChart4 = $00000002;
xlChartSeries = $00000011;
xlChartShort = $00000006;
xlChartTitles = $00000012;
xlClassic1 = $00000001;
xlClassic2 = $00000002;
xlClassic3 = $00000003;
xl3DEffects1 = $0000000D;
xl3DEffects2 = $0000000E;
xlAbove = $00000000;
xlAccounting1 = $00000004;
xlAccounting2 = $00000005;
xlAccounting3 = $00000006;
xlAccounting4 = $00000011;
xlAdd = $00000002;
xlDebugCodePane = $0000000D;
xlDesktop = $00000009;
xlDirect = $00000001;
xlDivide = $00000005;
xlDoubleClosed = $00000005;
xlDoubleOpen = $00000004;
xlDoubleQuote = $00000001;
xlEntireChart = $00000014;
xlExcelMenus = $00000001;
xlExtended = $00000003;
xlFill = $00000005;
xlFirst = $00000000;
xlFloating = $00000005;
xlFormula = $00000005;
xlGeneral = $00000001;
xlGridline = $00000016;
xlIcons = $00000001;
xlImmediatePane = $0000000C;
xlInteger = $00000002;
xlLast = $00000001;
xlLastCell = $0000000B;
xlList1 = $0000000A;
xlList2 = $0000000B;
xlList3 = $0000000C;
xlLocalFormat1 = $0000000F;
xlLocalFormat2 = $00000010;
xlLong = $00000003;
xlLotusHelp = $00000002;
xlMacrosheetCell = $00000007;
xlMixed = $00000002;
xlMultiply = $00000004;
xlNarrow = $00000001;
xlNoDocuments = $00000003;
xlOpen = $00000002;
xlOutside = $00000003;
xlReference = $00000004;
xlSemiautomatic = $00000002;
xlShort = $00000001;
xlSingleQuote = $00000002;
xlStrict = $00000002;
xlSubtract = $00000003;
xlTextBox = $00000010;
xlTiled = $00000001;
xlTitleBar = $00000008;
xlToolbar = $00000001;
xlVisible = $0000000C;
xlWatchPane = $0000000B;
xlWide = $00000003;
xlWorkbookTab = $00000006;
xlWorksheet4 = $00000001;
xlWorksheetCell = $00000003;
xlWorksheetShort = $00000005;
xlAllExceptBorders = $00000007;
xlLeftToRight = $00000002;
xlTopToBottom = $00000001;
xlVeryHidden = $00000002;
xlDrawingObject = $0000000E;
// Constants for enum XlCreator
xlCreatorCode = $5843454C;
// Constants for enum XlChartGallery
xlBuiltIn = $00000015;
xlUserDefined = $00000016;
xlAnyGallery = $00000017;
// Constants for enum XlColorIndex
xlColorIndexAutomatic = $FFFFEFF7;
xlColorIndexNone = $FFFFEFD2;
// Constants for enum XlEndStyleCap
xlCap = $00000001;
xlNoCap = $00000002;
// Constants for enum XlRowCol
xlColumns = $00000002;
xlRows = $00000001;
// Constants for enum XlScaleType
xlScaleLinear = $FFFFEFDC;
xlScaleLogarithmic = $FFFFEFDB;
// Constants for enum XlDataSeriesType
xlAutoFill = $00000004;
xlChronological = $00000003;
xlGrowth = $00000002;
xlDataSeriesLinear = $FFFFEFDC;
// Constants for enum XlAxisCrosses
xlAxisCrossesAutomatic = $FFFFEFF7;
xlAxisCrossesCustom = $FFFFEFEE;
xlAxisCrossesMaximum = $00000002;
xlAxisCrossesMinimum = $00000004;
// Constants for enum XlAxisGroup
xlPrimary = $00000001;
xlSecondary = $00000002;
// Constants for enum XlBackground
xlBackgroundAutomatic = $FFFFEFF7;
xlBackgroundOpaque = $00000003;
xlBackgroundTransparent = $00000002;
// Constants for enum XlWindowState
xlMaximized = $FFFFEFD7;
xlMinimized = $FFFFEFD4;
xlNormal = $FFFFEFD1;
// Constants for enum XlAxisType
xlCategory = $00000001;
xlSeriesAxis = $00000003;
xlValue = $00000002;
// Constants for enum XlArrowHeadLength
xlArrowHeadLengthLong = $00000003;
xlArrowHeadLengthMedium = $FFFFEFD6;
xlArrowHeadLengthShort = $00000001;
// Constants for enum XlVAlign
xlVAlignBottom = $FFFFEFF5;
xlVAlignCenter = $FFFFEFF4;
xlVAlignDistributed = $FFFFEFEB;
xlVAlignJustify = $FFFFEFDE;
xlVAlignTop = $FFFFEFC0;
// Constants for enum XlTickMark
xlTickMarkCross = $00000004;
xlTickMarkInside = $00000002;
xlTickMarkNone = $FFFFEFD2;
xlTickMarkOutside = $00000003;
// Constants for enum XlErrorBarDirection
xlX = $FFFFEFB8;
xlY = $00000001;
// Constants for enum XlErrorBarInclude
xlErrorBarIncludeBoth = $00000001;
xlErrorBarIncludeMinusValues = $00000003;
xlErrorBarIncludeNone = $FFFFEFD2;
xlErrorBarIncludePlusValues = $00000002;
// Constants for enum XlDisplayBlanksAs
xlInterpolated = $00000003;
xlNotPlotted = $00000001;
xlZero = $00000002;
// Constants for enum XlArrowHeadStyle
xlArrowHeadStyleClosed = $00000003;
xlArrowHeadStyleDoubleClosed = $00000005;
xlArrowHeadStyleDoubleOpen = $00000004;
xlArrowHeadStyleNone = $FFFFEFD2;
xlArrowHeadStyleOpen = $00000002;
// Constants for enum XlArrowHeadWidth
xlArrowHeadWidthMedium = $FFFFEFD6;
xlArrowHeadWidthNarrow = $00000001;
xlArrowHeadWidthWide = $00000003;
// Constants for enum XlHAlign
xlHAlignCenter = $FFFFEFF4;
xlHAlignCenterAcrossSelection = $00000007;
xlHAlignDistributed = $FFFFEFEB;
xlHAlignFill = $00000005;
xlHAlignGeneral = $00000001;
xlHAlignJustify = $FFFFEFDE;
xlHAlignLeft = $FFFFEFDD;
xlHAlignRight = $FFFFEFC8;
// Constants for enum XlTickLabelPosition
xlTickLabelPositionHigh = $FFFFEFE1;
xlTickLabelPositionLow = $FFFFEFDA;
xlTickLabelPositionNextToAxis = $00000004;
xlTickLabelPositionNone = $FFFFEFD2;
// Constants for enum XlLegendPosition
xlLegendPositionBottom = $FFFFEFF5;
xlLegendPositionCorner = $00000002;
xlLegendPositionLeft = $FFFFEFDD;
xlLegendPositionRight = $FFFFEFC8;
xlLegendPositionTop = $FFFFEFC0;
xlLegendPositionCustom = $FFFFEFBF;
// Constants for enum XlChartPictureType
xlStackScale = $00000003;
xlStack = $00000002;
xlStretch = $00000001;
// Constants for enum XlChartPicturePlacement
xlSides = $00000001;
xlEnd = $00000002;
xlEndSides = $00000003;
xlFront = $00000004;
xlFrontSides = $00000005;
xlFrontEnd = $00000006;
xlAllFaces = $00000007;
// Constants for enum XlOrientation
xlDownward = $FFFFEFB6;
xlHorizontal = $FFFFEFE0;
xlUpward = $FFFFEFB5;
xlVertical = $FFFFEFBA;
// Constants for enum XlTickLabelOrientation
xlTickLabelOrientationAutomatic = $FFFFEFF7;
xlTickLabelOrientationDownward = $FFFFEFB6;
xlTickLabelOrientationHorizontal = $FFFFEFE0;
xlTickLabelOrientationUpward = $FFFFEFB5;
xlTickLabelOrientationVertical = $FFFFEFBA;
// Constants for enum XlBorderWeight
xlHairline = $00000001;
xlMedium = $FFFFEFD6;
xlThick = $00000004;
xlThin = $00000002;
// Constants for enum XlDataSeriesDate
xlDay = $00000001;
xlMonth = $00000003;
xlWeekday = $00000002;
xlYear = $00000004;
// Constants for enum XlUnderlineStyle
xlUnderlineStyleDouble = $FFFFEFE9;
xlUnderlineStyleDoubleAccounting = $00000005;
xlUnderlineStyleNone = $FFFFEFD2;
xlUnderlineStyleSingle = $00000002;
xlUnderlineStyleSingleAccounting = $00000004;
// Constants for enum XlErrorBarType
xlErrorBarTypeCustom = $FFFFEFEE;
xlErrorBarTypeFixedValue = $00000001;
xlErrorBarTypePercent = $00000002;
xlErrorBarTypeStDev = $FFFFEFC5;
xlErrorBarTypeStError = $00000004;
// Constants for enum XlTrendlineType
xlExponential = $00000005;
xlLinear = $FFFFEFDC;
xlLogarithmic = $FFFFEFDB;
xlMovingAvg = $00000006;
xlPolynomial = $00000003;
xlPower = $00000004;
// Constants for enum XlLineStyle
xlContinuous = $00000001;
xlDash = $FFFFEFED;
xlDashDot = $00000004;
xlDashDotDot = $00000005;
xlDot = $FFFFEFEA;
xlDouble = $FFFFEFE9;
xlSlantDashDot = $0000000D;
xlLineStyleNone = $FFFFEFD2;
// Constants for enum XlDataLabelsType
xlDataLabelsShowNone = $FFFFEFD2;
xlDataLabelsShowValue = $00000002;
xlDataLabelsShowPercent = $00000003;
xlDataLabelsShowLabel = $00000004;
xlDataLabelsShowLabelAndPercent = $00000005;
xlDataLabelsShowBubbleSizes = $00000006;
// Constants for enum XlMarkerStyle
xlMarkerStyleAutomatic = $FFFFEFF7;
xlMarkerStyleCircle = $00000008;
xlMarkerStyleDash = $FFFFEFED;
xlMarkerStyleDiamond = $00000002;
xlMarkerStyleDot = $FFFFEFEA;
xlMarkerStyleNone = $FFFFEFD2;
xlMarkerStylePicture = $FFFFEFCD;
xlMarkerStylePlus = $00000009;
xlMarkerStyleSquare = $00000001;
xlMarkerStyleStar = $00000005;
xlMarkerStyleTriangle = $00000003;
xlMarkerStyleX = $FFFFEFB8;
// Constants for enum XlPictureConvertorType
xlBMP = $00000001;
xlCGM = $00000007;
xlDRW = $00000004;
xlDXF = $00000005;
xlEPS = $00000008;
xlHGL = $00000006;
xlPCT = $0000000D;
xlPCX = $0000000A;
xlPIC = $0000000B;
xlPLT = $0000000C;
xlTIF = $00000009;
xlWMF = $00000002;
xlWPG = $00000003;
// Constants for enum XlPattern
xlPatternAutomatic = $FFFFEFF7;
xlPatternChecker = $00000009;
xlPatternCrissCross = $00000010;
xlPatternDown = $FFFFEFE7;
xlPatternGray16 = $00000011;
xlPatternGray25 = $FFFFEFE4;
xlPatternGray50 = $FFFFEFE3;
xlPatternGray75 = $FFFFEFE2;
xlPatternGray8 = $00000012;
xlPatternGrid = $0000000F;
xlPatternHorizontal = $FFFFEFE0;
xlPatternLightDown = $0000000D;
xlPatternLightHorizontal = $0000000B;
xlPatternLightUp = $0000000E;
xlPatternLightVertical = $0000000C;
xlPatternNone = $FFFFEFD2;
xlPatternSemiGray75 = $0000000A;
xlPatternSolid = $00000001;
xlPatternUp = $FFFFEFBE;
xlPatternVertical = $FFFFEFBA;
xlPatternLinearGradient = $00000FA0;
xlPatternRectangularGradient = $00000FA1;
// Constants for enum XlChartSplitType
xlSplitByPosition = $00000001;
xlSplitByPercentValue = $00000003;
xlSplitByCustomSplit = $00000004;
xlSplitByValue = $00000002;
// Constants for enum XlDisplayUnit
xlHundreds = $FFFFFFFE;
xlThousands = $FFFFFFFD;
xlTenThousands = $FFFFFFFC;
xlHundredThousands = $FFFFFFFB;
xlMillions = $FFFFFFFA;
xlTenMillions = $FFFFFFF9;
xlHundredMillions = $FFFFFFF8;
xlThousandMillions = $FFFFFFF7;
xlMillionMillions = $FFFFFFF6;
// Constants for enum XlDataLabelPosition
xlLabelPositionCenter = $FFFFEFF4;
xlLabelPositionAbove = $00000000;
xlLabelPositionBelow = $00000001;
xlLabelPositionLeft = $FFFFEFDD;
xlLabelPositionRight = $FFFFEFC8;
xlLabelPositionOutsideEnd = $00000002;
xlLabelPositionInsideEnd = $00000003;
xlLabelPositionInsideBase = $00000004;
xlLabelPositionBestFit = $00000005;
xlLabelPositionMixed = $00000006;
xlLabelPositionCustom = $00000007;
// Constants for enum XlTimeUnit
xlDays = $00000000;
xlMonths = $00000001;
xlYears = $00000002;
// Constants for enum XlCategoryType
xlCategoryScale = $00000002;
xlTimeScale = $00000003;
xlAutomaticScale = $FFFFEFF7;
// Constants for enum XlBarShape
xlBox = $00000000;
xlPyramidToPoint = $00000001;
xlPyramidToMax = $00000002;
xlCylinder = $00000003;
xlConeToPoint = $00000004;
xlConeToMax = $00000005;
// Constants for enum XlChartType
xlColumnClustered = $00000033;
xlColumnStacked = $00000034;
xlColumnStacked100 = $00000035;
xl3DColumnClustered = $00000036;
xl3DColumnStacked = $00000037;
xl3DColumnStacked100 = $00000038;
xlBarClustered = $00000039;
xlBarStacked = $0000003A;
xlBarStacked100 = $0000003B;
xl3DBarClustered = $0000003C;
xl3DBarStacked = $0000003D;
xl3DBarStacked100 = $0000003E;
xlLineStacked = $0000003F;
xlLineStacked100 = $00000040;
xlLineMarkers = $00000041;
xlLineMarkersStacked = $00000042;
xlLineMarkersStacked100 = $00000043;
xlPieOfPie = $00000044;
xlPieExploded = $00000045;
xl3DPieExploded = $00000046;
xlBarOfPie = $00000047;
xlXYScatterSmooth = $00000048;
xlXYScatterSmoothNoMarkers = $00000049;
xlXYScatterLines = $0000004A;
xlXYScatterLinesNoMarkers = $0000004B;
xlAreaStacked = $0000004C;
xlAreaStacked100 = $0000004D;
xl3DAreaStacked = $0000004E;
xl3DAreaStacked100 = $0000004F;
xlDoughnutExploded = $00000050;
xlRadarMarkers = $00000051;
xlRadarFilled = $00000052;
xlSurface = $00000053;
xlSurfaceWireframe = $00000054;
xlSurfaceTopView = $00000055;
xlSurfaceTopViewWireframe = $00000056;
xlBubble = $0000000F;
xlBubble3DEffect = $00000057;
xlStockHLC = $00000058;
xlStockOHLC = $00000059;
xlStockVHLC = $0000005A;
xlStockVOHLC = $0000005B;
xlCylinderColClustered = $0000005C;
xlCylinderColStacked = $0000005D;
xlCylinderColStacked100 = $0000005E;
xlCylinderBarClustered = $0000005F;
xlCylinderBarStacked = $00000060;
xlCylinderBarStacked100 = $00000061;
xlCylinderCol = $00000062;
xlConeColClustered = $00000063;
xlConeColStacked = $00000064;
xlConeColStacked100 = $00000065;
xlConeBarClustered = $00000066;
xlConeBarStacked = $00000067;
xlConeBarStacked100 = $00000068;
xlConeCol = $00000069;
xlPyramidColClustered = $0000006A;
xlPyramidColStacked = $0000006B;
xlPyramidColStacked100 = $0000006C;
xlPyramidBarClustered = $0000006D;
xlPyramidBarStacked = $0000006E;
xlPyramidBarStacked100 = $0000006F;
xlPyramidCol = $00000070;
xl3DColumn = $FFFFEFFC;
xlLine = $00000004;
xl3DLine = $FFFFEFFB;
xl3DPie = $FFFFEFFA;
xlPie = $00000005;
xlXYScatter = $FFFFEFB7;
xl3DArea = $FFFFEFFE;
xlArea = $00000001;
xlDoughnut = $FFFFEFE8;
xlRadar = $FFFFEFC9;
xlTreemap = $00000075;
xlHistogram = $00000076;
xlWaterfall = $00000077;
xlSunburst = $00000078;
xlBoxwhisker = $00000079;
xlPareto = $0000007A;
xlFunnel = $0000007B;
xlRegionMap = $0000008C;
// Constants for enum XlChartItem
xlDataLabel = $00000000;
xlChartArea = $00000002;
xlSeries = $00000003;
xlChartTitle = $00000004;
xlWalls = $00000005;
xlCorners = $00000006;
xlDataTable = $00000007;
xlTrendline = $00000008;
xlErrorBars = $00000009;
xlXErrorBars = $0000000A;
xlYErrorBars = $0000000B;
xlLegendEntry = $0000000C;
xlLegendKey = $0000000D;
xlShape = $0000000E;
xlMajorGridlines = $0000000F;
xlMinorGridlines = $00000010;
xlAxisTitle = $00000011;
xlUpBars = $00000012;
xlPlotArea = $00000013;
xlDownBars = $00000014;
xlAxis = $00000015;
xlSeriesLines = $00000016;
xlFloor = $00000017;
xlLegend = $00000018;
xlHiLoLines = $00000019;
xlDropLines = $0000001A;
xlRadarAxisLabels = $0000001B;
xlNothing = $0000001C;
xlLeaderLines = $0000001D;
xlDisplayUnitLabel = $0000001E;
xlPivotChartFieldButton = $0000001F;
xlPivotChartDropZone = $00000020;
xlPivotChartExpandEntireFieldButton = $00000021;
xlPivotChartCollapseEntireFieldButton = $00000022;
// Constants for enum XlSizeRepresents
xlSizeIsWidth = $00000002;
xlSizeIsArea = $00000001;
// Constants for enum XlInsertShiftDirection
xlShiftDown = $FFFFEFE7;
xlShiftToRight = $FFFFEFBF;
// Constants for enum XlDeleteShiftDirection
xlShiftToLeft = $FFFFEFC1;
xlShiftUp = $FFFFEFBE;
// Constants for enum XlDirection
xlDown = $FFFFEFE7;
xlToLeft = $FFFFEFC1;
xlToRight = $FFFFEFBF;
xlUp = $FFFFEFBE;
// Constants for enum XlConsolidationFunction
xlAverage = $FFFFEFF6;
xlCount = $FFFFEFF0;
xlCountNums = $FFFFEFEF;
xlMax = $FFFFEFD8;
xlMin = $FFFFEFD5;
xlProduct = $FFFFEFCB;
xlStDev = $FFFFEFC5;
xlStDevP = $FFFFEFC4;
xlSum = $FFFFEFC3;
xlVar = $FFFFEFBC;
xlVarP = $FFFFEFBB;
xlUnknown = $000003E8;
xlDistinctCount = $0000000B;
// Constants for enum XlSheetType
xlChart = $FFFFEFF3;
xlDialogSheet = $FFFFEFEC;
xlExcel4IntlMacroSheet = $00000004;
xlExcel4MacroSheet = $00000003;
xlWorksheet = $FFFFEFB9;
// Constants for enum XlLocationInTable
xlColumnHeader = $FFFFEFF2;
xlColumnItem = $00000005;
xlDataHeader = $00000003;
xlDataItem = $00000007;
xlPageHeader = $00000002;
xlPageItem = $00000006;
xlRowHeader = $FFFFEFC7;
xlRowItem = $00000004;
xlTableBody = $00000008;
// Constants for enum XlFindLookIn
xlFormulas = $FFFFEFE5;
xlComments = $FFFFEFD0;
xlValues = $FFFFEFBD;
xlCommentsThreaded = $FFFFEFA8;
xlFormulas2 = $FFFFEFA7;
// Constants for enum XlWindowType
xlChartAsWindow = $00000005;
xlChartInPlace = $00000004;
xlClipboard = $00000003;
xlInfo = $FFFFEFDF;
xlWorkbook = $00000001;
// Constants for enum XlPivotFieldDataType
xlDate = $00000002;
xlNumber = $FFFFEFCF;
xlText = $FFFFEFC2;
// Constants for enum XlCopyPictureFormat
xlBitmap = $00000002;
xlPicture = $FFFFEFCD;
// Constants for enum XlPivotTableSourceType
xlScenario = $00000004;
xlConsolidation = $00000003;
xlDatabase = $00000001;
xlExternal = $00000002;
xlPivotTable = $FFFFEFCC;
// Constants for enum XlReferenceStyle
xlA1 = $00000001;
xlR1C1 = $FFFFEFCA;
// Constants for enum XlMSApplication
xlMicrosoftAccess = $00000004;
xlMicrosoftFoxPro = $00000005;
xlMicrosoftMail = $00000003;
xlMicrosoftPowerPoint = $00000002;
xlMicrosoftProject = $00000006;
xlMicrosoftSchedulePlus = $00000007;
xlMicrosoftWord = $00000001;
// Constants for enum XlMouseButton
xlNoButton = $00000000;
xlPrimaryButton = $00000001;
xlSecondaryButton = $00000002;
// Constants for enum XlCutCopyMode
xlCopy = $00000001;
xlCut = $00000002;
// Constants for enum XlFillWith
xlFillWithAll = $FFFFEFF8;
xlFillWithContents = $00000002;
xlFillWithFormats = $FFFFEFE6;
// Constants for enum XlFilterAction
xlFilterCopy = $00000002;
xlFilterInPlace = $00000001;
// Constants for enum XlOrder
xlDownThenOver = $00000001;
xlOverThenDown = $00000002;
// Constants for enum XlLinkType
xlLinkTypeExcelLinks = $00000001;
xlLinkTypeOLELinks = $00000002;
// Constants for enum XlApplyNamesOrder
xlColumnThenRow = $00000002;
xlRowThenColumn = $00000001;
// Constants for enum XlEnableCancelKey
xlDisabled = $00000000;
xlErrorHandler = $00000002;
xlInterrupt = $00000001;
// Constants for enum XlPageBreak
xlPageBreakAutomatic = $FFFFEFF7;
xlPageBreakManual = $FFFFEFD9;
xlPageBreakNone = $FFFFEFD2;
// Constants for enum XlOLEType
xlOLEControl = $00000002;
xlOLEEmbed = $00000001;
xlOLELink = $00000000;
// Constants for enum XlPageOrientation
xlLandscape = $00000002;
xlPortrait = $00000001;
// Constants for enum XlLinkInfo
xlEditionDate = $00000002;
xlUpdateState = $00000001;
xlLinkInfoStatus = $00000003;
// Constants for enum XlCommandUnderlines
xlCommandUnderlinesAutomatic = $FFFFEFF7;
xlCommandUnderlinesOff = $FFFFEFCE;
xlCommandUnderlinesOn = $00000001;
// Constants for enum XlOLEVerb
xlVerbOpen = $00000002;
xlVerbPrimary = $00000001;
// Constants for enum XlCalculation
xlCalculationAutomatic = $FFFFEFF7;
xlCalculationManual = $FFFFEFD9;
xlCalculationSemiautomatic = $00000002;
// Constants for enum XlFileAccess
xlReadOnly = $00000003;
xlReadWrite = $00000002;
// Constants for enum XlEditionType
xlPublisher = $00000001;
xlSubscriber = $00000002;
// Constants for enum XlObjectSize
xlFitToPage = $00000002;
xlFullPage = $00000003;
xlScreenSize = $00000001;
// Constants for enum XlLookAt
xlPart = $00000002;
xlWhole = $00000001;
// Constants for enum XlMailSystem
xlMAPI = $00000001;
xlNoMailSystem = $00000000;
xlPowerTalk = $00000002;
// Constants for enum XlLinkInfoType
xlLinkInfoOLELinks = $00000002;
xlLinkInfoPublishers = $00000005;
xlLinkInfoSubscribers = $00000006;
// Constants for enum XlCVError
xlErrBlocked = $000007FF;
xlErrCalc = $00000802;
xlErrConnect = $000007FE;
xlErrDiv0 = $000007D7;
xlErrField = $00000801;
xlErrGettingData = $000007FB;
xlErrNA = $000007FA;
xlErrName = $000007ED;
xlErrSpill = $000007FD;
xlErrNull = $000007D0;
xlErrNum = $000007F4;
xlErrRef = $000007E7;
xlErrUnknown = $00000800;
xlErrValue = $000007DF;
// Constants for enum XlEditionFormat
xlBIFF = $00000002;
xlPICT = $00000001;
xlRTF = $00000004;
xlVALU = $00000008;
// Constants for enum XlLink
xlExcelLinks = $00000001;
xlOLELinks = $00000002;
xlPublishers = $00000005;
xlSubscribers = $00000006;
// Constants for enum XlCellType
xlCellTypeBlanks = $00000004;
xlCellTypeConstants = $00000002;
xlCellTypeFormulas = $FFFFEFE5;
xlCellTypeLastCell = $0000000B;
xlCellTypeComments = $FFFFEFD0;
xlCellTypeVisible = $0000000C;
xlCellTypeAllFormatConditions = $FFFFEFB4;
xlCellTypeSameFormatConditions = $FFFFEFB3;
xlCellTypeAllValidation = $FFFFEFB2;
xlCellTypeSameValidation = $FFFFEFB1;
// Constants for enum XlArrangeStyle
xlArrangeStyleCascade = $00000007;
xlArrangeStyleHorizontal = $FFFFEFE0;
xlArrangeStyleTiled = $00000001;
xlArrangeStyleVertical = $FFFFEFBA;
// Constants for enum XlMousePointer
xlIBeam = $00000003;
xlDefault = $FFFFEFD1;
xlNorthwestArrow = $00000001;
xlWait = $00000002;
// Constants for enum XlEditionOptionsOption
xlAutomaticUpdate = $00000004;
xlCancel = $00000001;
xlChangeAttributes = $00000006;
xlManualUpdate = $00000005;
xlOpenSource = $00000003;
xlSelect = $00000003;
xlSendPublisher = $00000002;
xlUpdateSubscriber = $00000002;
// Constants for enum XlAutoFillType
xlFillCopy = $00000001;
xlFillDays = $00000005;
xlFillDefault = $00000000;
xlFillFormats = $00000003;
xlFillMonths = $00000007;
xlFillSeries = $00000002;
xlFillValues = $00000004;
xlFillWeekdays = $00000006;
xlFillYears = $00000008;
xlGrowthTrend = $0000000A;
xlLinearTrend = $00000009;
xlFlashFill = $0000000B;
// Constants for enum XlAutoFilterOperator
xlAnd = $00000001;
xlBottom10Items = $00000004;
xlBottom10Percent = $00000006;
xlOr = $00000002;
xlTop10Items = $00000003;
xlTop10Percent = $00000005;
xlFilterValues = $00000007;
xlFilterCellColor = $00000008;
xlFilterFontColor = $00000009;
xlFilterIcon = $0000000A;
xlFilterDynamic = $0000000B;
xlFilterNoFill = $0000000C;
xlFilterAutomaticFontColor = $0000000D;
xlFilterNoIcon = $0000000E;
// Constants for enum XlClipboardFormat
xlClipboardFormatBIFF12 = $0000003F;
xlClipboardFormatBIFF = $00000008;
xlClipboardFormatBIFF2 = $00000012;
xlClipboardFormatBIFF3 = $00000014;
xlClipboardFormatBIFF4 = $0000001E;
xlClipboardFormatBinary = $0000000F;
xlClipboardFormatBitmap = $00000009;
xlClipboardFormatCGM = $0000000D;
xlClipboardFormatCSV = $00000005;
xlClipboardFormatDIF = $00000004;
xlClipboardFormatDspText = $0000000C;
xlClipboardFormatEmbeddedObject = $00000015;
xlClipboardFormatEmbedSource = $00000016;
xlClipboardFormatLink = $0000000B;
xlClipboardFormatLinkSource = $00000017;
xlClipboardFormatLinkSourceDesc = $00000020;
xlClipboardFormatMovie = $00000018;
xlClipboardFormatNative = $0000000E;
xlClipboardFormatObjectDesc = $0000001F;
xlClipboardFormatObjectLink = $00000013;
xlClipboardFormatOwnerLink = $00000011;
xlClipboardFormatPICT = $00000002;
xlClipboardFormatPrintPICT = $00000003;
xlClipboardFormatRTF = $00000007;
xlClipboardFormatScreenPICT = $0000001D;
xlClipboardFormatStandardFont = $0000001C;
xlClipboardFormatStandardScale = $0000001B;
xlClipboardFormatSYLK = $00000006;
xlClipboardFormatTable = $00000010;
xlClipboardFormatText = $00000000;
xlClipboardFormatToolFace = $00000019;
xlClipboardFormatToolFacePICT = $0000001A;
xlClipboardFormatVALU = $00000001;
xlClipboardFormatWK1 = $0000000A;
// Constants for enum XlFileFormat
xlAddIn = $00000012;
xlCSV = $00000006;
xlCSVMac = $00000016;
xlCSVMSDOS = $00000018;
xlCSVWindows = $00000017;
xlDBF2 = $00000007;
xlDBF3 = $00000008;
xlDBF4 = $0000000B;
xlDIF = $00000009;
xlExcel2 = $00000010;
xlExcel2FarEast = $0000001B;
xlExcel3 = $0000001D;
xlExcel4 = $00000021;
xlExcel5 = $00000027;
xlExcel7 = $00000027;
xlExcel9795 = $0000002B;
xlExcel4Workbook = $00000023;
xlIntlAddIn = $0000001A;
xlIntlMacro = $00000019;
xlWorkbookNormal = $FFFFEFD1;
xlSYLK = $00000002;
xlTemplate = $00000011;
xlCurrentPlatformText = $FFFFEFC2;
xlTextMac = $00000013;
xlTextMSDOS = $00000015;
xlTextPrinter = $00000024;
xlTextWindows = $00000014;
xlWJ2WD1 = $0000000E;
xlWK1 = $00000005;
xlWK1ALL = $0000001F;
xlWK1FMT = $0000001E;
xlWK3 = $0000000F;
xlWK4 = $00000026;
xlWK3FM3 = $00000020;
xlWKS = $00000004;
xlWorks2FarEast = $0000001C;
xlWQ1 = $00000022;
xlWJ3 = $00000028;
xlWJ3FJ3 = $00000029;
xlUnicodeText = $0000002A;
xlHtml = $0000002C;
xlWebArchive = $0000002D;
xlXMLSpreadsheet = $0000002E;
xlExcel12 = $00000032;
xlOpenXMLWorkbook = $00000033;
xlOpenXMLWorkbookMacroEnabled = $00000034;
xlOpenXMLTemplateMacroEnabled = $00000035;
xlTemplate8 = $00000011;
xlOpenXMLTemplate = $00000036;
xlAddIn8 = $00000012;
xlOpenXMLAddIn = $00000037;
xlExcel8 = $00000038;
xlOpenDocumentSpreadsheet = $0000003C;
xlOpenXMLStrictWorkbook = $0000003D;
xlCSVUTF8 = $0000003E;
xlWorkbookDefault = $00000033;
// Constants for enum XlApplicationInternational
xl24HourClock = $00000021;
xl4DigitYears = $0000002B;
xlAlternateArraySeparator = $00000010;
xlColumnSeparator = $0000000E;
xlCountryCode = $00000001;
xlCountrySetting = $00000002;
xlCurrencyBefore = $00000025;
xlCurrencyCode = $00000019;
xlCurrencyDigits = $0000001B;
xlCurrencyLeadingZeros = $00000028;
xlCurrencyMinusSign = $00000026;
xlCurrencyNegative = $0000001C;
xlCurrencySpaceBefore = $00000024;
xlCurrencyTrailingZeros = $00000027;
xlDateOrder = $00000020;
xlDateSeparator = $00000011;
xlDayCode = $00000015;
xlDayLeadingZero = $0000002A;
xlDecimalSeparator = $00000003;
xlGeneralFormatName = $0000001A;
xlHourCode = $00000016;
xlLeftBrace = $0000000C;
xlLeftBracket = $0000000A;
xlListSeparator = $00000005;
xlLowerCaseColumnLetter = $00000009;
xlLowerCaseRowLetter = $00000008;
xlMDY = $0000002C;
xlMetric = $00000023;
xlMinuteCode = $00000017;
xlMonthCode = $00000014;
xlMonthLeadingZero = $00000029;
xlMonthNameChars = $0000001E;
xlNoncurrencyDigits = $0000001D;
xlNonEnglishFunctions = $00000022;
xlRightBrace = $0000000D;
xlRightBracket = $0000000B;
xlRowSeparator = $0000000F;
xlSecondCode = $00000018;
xlThousandsSeparator = $00000004;
xlTimeLeadingZero = $0000002D;
xlTimeSeparator = $00000012;
xlUpperCaseColumnLetter = $00000007;
xlUpperCaseRowLetter = $00000006;
xlWeekdayNameChars = $0000001F;
xlYearCode = $00000013;
xlUICultureTag = $0000002E;
// Constants for enum XlPageBreakExtent
xlPageBreakFull = $00000001;
xlPageBreakPartial = $00000002;
// Constants for enum XlCellInsertionMode
xlOverwriteCells = $00000000;
xlInsertDeleteCells = $00000001;
xlInsertEntireRows = $00000002;
// Constants for enum XlFormulaLabel
xlNoLabels = $FFFFEFD2;
xlRowLabels = $00000001;
xlColumnLabels = $00000002;
xlMixedLabels = $00000003;
// Constants for enum XlHighlightChangesTime
xlSinceMyLastSave = $00000001;
xlAllChanges = $00000002;
xlNotYetReviewed = $00000003;
// Constants for enum XlCommentDisplayMode
xlNoIndicator = $00000000;
xlCommentIndicatorOnly = $FFFFFFFF;
xlCommentAndIndicator = $00000001;
// Constants for enum XlFormatConditionType
xlCellValue = $00000001;
xlExpression = $00000002;
xlColorScale = $00000003;
xlDatabar = $00000004;
xlTop10 = $00000005;
xlIconSets = $00000006;
xlUniqueValues = $00000008;
xlTextString = $00000009;
xlBlanksCondition = $0000000A;
xlTimePeriod = $0000000B;
xlAboveAverageCondition = $0000000C;
xlNoBlanksCondition = $0000000D;
xlErrorsCondition = $00000010;
xlNoErrorsCondition = $00000011;
// Constants for enum XlFormatConditionOperator
xlBetween = $00000001;
xlNotBetween = $00000002;
xlEqual = $00000003;
xlNotEqual = $00000004;
xlGreater = $00000005;
xlLess = $00000006;
xlGreaterEqual = $00000007;
xlLessEqual = $00000008;
// Constants for enum XlEnableSelection
xlNoRestrictions = $00000000;
xlUnlockedCells = $00000001;
xlNoSelection = $FFFFEFD2;
// Constants for enum XlDVType
xlValidateInputOnly = $00000000;
xlValidateWholeNumber = $00000001;
xlValidateDecimal = $00000002;
xlValidateList = $00000003;
xlValidateDate = $00000004;
xlValidateTime = $00000005;
xlValidateTextLength = $00000006;
xlValidateCustom = $00000007;
// Constants for enum XlIMEMode
xlIMEModeNoControl = $00000000;
xlIMEModeOn = $00000001;
xlIMEModeOff = $00000002;
xlIMEModeDisable = $00000003;
xlIMEModeHiragana = $00000004;
xlIMEModeKatakana = $00000005;
xlIMEModeKatakanaHalf = $00000006;
xlIMEModeAlphaFull = $00000007;
xlIMEModeAlpha = $00000008;
xlIMEModeHangulFull = $00000009;
xlIMEModeHangul = $0000000A;
// Constants for enum XlDVAlertStyle
xlValidAlertStop = $00000001;
xlValidAlertWarning = $00000002;
xlValidAlertInformation = $00000003;
// Constants for enum XlChartLocation
xlLocationAsNewSheet = $00000001;
xlLocationAsObject = $00000002;
xlLocationAutomatic = $00000003;
// Constants for enum XlPaperSize
xlPaper10x14 = $00000010;
xlPaper11x17 = $00000011;
xlPaperA3 = $00000008;
xlPaperA4 = $00000009;
xlPaperA4Small = $0000000A;
xlPaperA5 = $0000000B;
xlPaperB4 = $0000000C;
xlPaperB5 = $0000000D;
xlPaperCsheet = $00000018;
xlPaperDsheet = $00000019;
xlPaperEnvelope10 = $00000014;
xlPaperEnvelope11 = $00000015;
xlPaperEnvelope12 = $00000016;
xlPaperEnvelope14 = $00000017;
xlPaperEnvelope9 = $00000013;
xlPaperEnvelopeB4 = $00000021;
xlPaperEnvelopeB5 = $00000022;
xlPaperEnvelopeB6 = $00000023;
xlPaperEnvelopeC3 = $0000001D;
xlPaperEnvelopeC4 = $0000001E;
xlPaperEnvelopeC5 = $0000001C;
xlPaperEnvelopeC6 = $0000001F;
xlPaperEnvelopeC65 = $00000020;
xlPaperEnvelopeDL = $0000001B;
xlPaperEnvelopeItaly = $00000024;
xlPaperEnvelopeMonarch = $00000025;
xlPaperEnvelopePersonal = $00000026;
xlPaperEsheet = $0000001A;
xlPaperExecutive = $00000007;
xlPaperFanfoldLegalGerman = $00000029;
xlPaperFanfoldStdGerman = $00000028;
xlPaperFanfoldUS = $00000027;
xlPaperFolio = $0000000E;
xlPaperLedger = $00000004;
xlPaperLegal = $00000005;
xlPaperLetter = $00000001;
xlPaperLetterSmall = $00000002;
xlPaperNote = $00000012;
xlPaperQuarto = $0000000F;
xlPaperStatement = $00000006;
xlPaperTabloid = $00000003;
xlPaperUser = $00000100;
// Constants for enum XlPasteSpecialOperation
xlPasteSpecialOperationAdd = $00000002;
xlPasteSpecialOperationDivide = $00000005;
xlPasteSpecialOperationMultiply = $00000004;
xlPasteSpecialOperationNone = $FFFFEFD2;
xlPasteSpecialOperationSubtract = $00000003;
// Constants for enum XlPasteType
xlPasteAll = $FFFFEFF8;
xlPasteAllUsingSourceTheme = $0000000D;
xlPasteAllMergingConditionalFormats = $0000000E;
xlPasteAllExceptBorders = $00000007;
xlPasteFormats = $FFFFEFE6;
xlPasteFormulas = $FFFFEFE5;
xlPasteComments = $FFFFEFD0;
xlPasteValues = $FFFFEFBD;
xlPasteColumnWidths = $00000008;
xlPasteValidation = $00000006;
xlPasteFormulasAndNumberFormats = $0000000B;
xlPasteValuesAndNumberFormats = $0000000C;
// Constants for enum XlPhoneticCharacterType
xlKatakanaHalf = $00000000;
xlKatakana = $00000001;
xlHiragana = $00000002;
xlNoConversion = $00000003;
// Constants for enum XlPhoneticAlignment
xlPhoneticAlignNoControl = $00000000;
xlPhoneticAlignLeft = $00000001;
xlPhoneticAlignCenter = $00000002;
xlPhoneticAlignDistributed = $00000003;
// Constants for enum XlPictureAppearance
xlPrinter = $00000002;
xlScreen = $00000001;
// Constants for enum XlPivotFieldOrientation
xlColumnField = $00000002;
xlDataField = $00000004;
xlHidden = $00000000;
xlPageField = $00000003;
xlRowField = $00000001;
// Constants for enum XlPivotFieldCalculation
xlDifferenceFrom = $00000002;
xlIndex = $00000009;
xlNoAdditionalCalculation = $FFFFEFD1;
xlPercentDifferenceFrom = $00000004;
xlPercentOf = $00000003;
xlPercentOfColumn = $00000007;
xlPercentOfRow = $00000006;
xlPercentOfTotal = $00000008;
xlRunningTotal = $00000005;
xlPercentOfParentRow = $0000000A;
xlPercentOfParentColumn = $0000000B;
xlPercentOfParent = $0000000C;
xlPercentRunningTotal = $0000000D;
xlRankAscending = $0000000E;
xlRankDecending = $0000000F;
// Constants for enum XlPlacement
xlFreeFloating = $00000003;
xlMove = $00000002;
xlMoveAndSize = $00000001;
// Constants for enum XlPlatform
xlMacintosh = $00000001;
xlMSDOS = $00000003;
xlWindows = $00000002;
// Constants for enum XlPrintLocation
xlPrintSheetEnd = $00000001;
xlPrintInPlace = $00000010;
xlPrintNoComments = $FFFFEFD2;
// Constants for enum XlPriority
xlPriorityHigh = $FFFFEFE1;
xlPriorityLow = $FFFFEFDA;
xlPriorityNormal = $FFFFEFD1;
// Constants for enum XlPTSelectionMode
xlLabelOnly = $00000001;
xlDataAndLabel = $00000000;
xlDataOnly = $00000002;
xlOrigin = $00000003;
xlButton = $0000000F;
xlBlanks = $00000004;
xlFirstRow = $00000100;
// Constants for enum XlRangeAutoFormat
xlRangeAutoFormat3DEffects1 = $0000000D;
xlRangeAutoFormat3DEffects2 = $0000000E;
xlRangeAutoFormatAccounting1 = $00000004;
xlRangeAutoFormatAccounting2 = $00000005;
xlRangeAutoFormatAccounting3 = $00000006;
xlRangeAutoFormatAccounting4 = $00000011;
xlRangeAutoFormatClassic1 = $00000001;
xlRangeAutoFormatClassic2 = $00000002;
xlRangeAutoFormatClassic3 = $00000003;
xlRangeAutoFormatColor1 = $00000007;
xlRangeAutoFormatColor2 = $00000008;
xlRangeAutoFormatColor3 = $00000009;
xlRangeAutoFormatList1 = $0000000A;
xlRangeAutoFormatList2 = $0000000B;
xlRangeAutoFormatList3 = $0000000C;
xlRangeAutoFormatLocalFormat1 = $0000000F;
xlRangeAutoFormatLocalFormat2 = $00000010;
xlRangeAutoFormatLocalFormat3 = $00000013;
xlRangeAutoFormatLocalFormat4 = $00000014;
xlRangeAutoFormatReport1 = $00000015;
xlRangeAutoFormatReport2 = $00000016;
xlRangeAutoFormatReport3 = $00000017;
xlRangeAutoFormatReport4 = $00000018;
xlRangeAutoFormatReport5 = $00000019;
xlRangeAutoFormatReport6 = $0000001A;
xlRangeAutoFormatReport7 = $0000001B;
xlRangeAutoFormatReport8 = $0000001C;
xlRangeAutoFormatReport9 = $0000001D;
xlRangeAutoFormatReport10 = $0000001E;
xlRangeAutoFormatClassicPivotTable = $0000001F;
xlRangeAutoFormatTable1 = $00000020;
xlRangeAutoFormatTable2 = $00000021;
xlRangeAutoFormatTable3 = $00000022;
xlRangeAutoFormatTable4 = $00000023;
xlRangeAutoFormatTable5 = $00000024;
xlRangeAutoFormatTable6 = $00000025;
xlRangeAutoFormatTable7 = $00000026;
xlRangeAutoFormatTable8 = $00000027;
xlRangeAutoFormatTable9 = $00000028;
xlRangeAutoFormatTable10 = $00000029;
xlRangeAutoFormatPTNone = $0000002A;
xlRangeAutoFormatNone = $FFFFEFD2;
xlRangeAutoFormatSimple = $FFFFEFC6;
// Constants for enum XlReferenceType
xlAbsolute = $00000001;
xlAbsRowRelColumn = $00000002;
xlRelative = $00000004;
xlRelRowAbsColumn = $00000003;
// Constants for enum XlLayoutFormType
xlTabular = $00000000;
xlOutline = $00000001;
// Constants for enum XlRoutingSlipDelivery
xlAllAtOnce = $00000002;
xlOneAfterAnother = $00000001;
// Constants for enum XlRoutingSlipStatus
xlNotYetRouted = $00000000;
xlRoutingComplete = $00000002;
xlRoutingInProgress = $00000001;
// Constants for enum XlRunAutoMacro
xlAutoActivate = $00000003;
xlAutoClose = $00000002;
xlAutoDeactivate = $00000004;
xlAutoOpen = $00000001;
// Constants for enum XlSaveAction
xlDoNotSaveChanges = $00000002;
xlSaveChanges = $00000001;
// Constants for enum XlSaveAsAccessMode
xlExclusive = $00000003;
xlNoChange = $00000001;
xlShared = $00000002;
// Constants for enum XlSaveConflictResolution
xlLocalSessionChanges = $00000002;
xlOtherSessionChanges = $00000003;
xlUserResolution = $00000001;
// Constants for enum XlSearchDirection
xlNext = $00000001;
xlPrevious = $00000002;
// Constants for enum XlSearchOrder
xlByColumns = $00000002;
xlByRows = $00000001;
// Constants for enum XlSheetVisibility
xlSheetVisible = $FFFFFFFF;
xlSheetHidden = $00000000;
xlSheetVeryHidden = $00000002;
// Constants for enum XlSortMethod
xlPinYin = $00000001;
xlStroke = $00000002;
// Constants for enum XlSortMethodOld
xlCodePage = $00000002;
xlSyllabary = $00000001;
// Constants for enum XlSortOrder
xlAscending = $00000001;
xlDescending = $00000002;
// Constants for enum XlSortOrientation
xlSortRows = $00000002;
xlSortColumns = $00000001;
// Constants for enum XlSortType
xlSortLabels = $00000002;
xlSortValues = $00000001;
// Constants for enum XlSpecialCellsValue
xlErrors = $00000010;
xlLogical = $00000004;
xlNumbers = $00000001;
xlTextValues = $00000002;
// Constants for enum XlSubscribeToFormat
xlSubscribeToPicture = $FFFFEFCD;
xlSubscribeToText = $FFFFEFC2;
// Constants for enum XlSummaryRow
xlSummaryAbove = $00000000;
xlSummaryBelow = $00000001;
// Constants for enum XlSummaryColumn
xlSummaryOnLeft = $FFFFEFDD;
xlSummaryOnRight = $FFFFEFC8;
// Constants for enum XlSummaryReportType
xlSummaryPivotTable = $FFFFEFCC;
xlStandardSummary = $00000001;
// Constants for enum XlTabPosition
xlTabPositionFirst = $00000000;
xlTabPositionLast = $00000001;
// Constants for enum XlTextParsingType
xlDelimited = $00000001;
xlFixedWidth = $00000002;
// Constants for enum XlTextQualifier
xlTextQualifierDoubleQuote = $00000001;
xlTextQualifierNone = $FFFFEFD2;
xlTextQualifierSingleQuote = $00000002;
// Constants for enum XlWBATemplate
xlWBATChart = $FFFFEFF3;
xlWBATExcel4IntlMacroSheet = $00000004;
xlWBATExcel4MacroSheet = $00000003;
xlWBATWorksheet = $FFFFEFB9;
// Constants for enum XlWindowView
xlNormalView = $00000001;
xlPageBreakPreview = $00000002;
xlPageLayoutView = $00000003;
// Constants for enum XlXLMMacroType
xlCommand = $00000002;
xlFunction = $00000001;
xlNotXLM = $00000003;
// Constants for enum XlYesNoGuess
xlGuess = $00000000;
xlNo = $00000002;
xlYes = $00000001;
// Constants for enum XlBordersIndex
xlInsideHorizontal = $0000000C;
xlInsideVertical = $0000000B;
xlDiagonalDown = $00000005;
xlDiagonalUp = $00000006;
xlEdgeBottom = $00000009;
xlEdgeLeft = $00000007;
xlEdgeRight = $0000000A;
xlEdgeTop = $00000008;
// Constants for enum XlToolbarProtection
xlNoButtonChanges = $00000001;
xlNoChanges = $00000004;
xlNoDockingChanges = $00000003;
xlToolbarProtectionNone = $FFFFEFD1;
xlNoShapeChanges = $00000002;
// Constants for enum XlBuiltInDialog
xlDialogOpen = $00000001;
xlDialogOpenLinks = $00000002;
xlDialogSaveAs = $00000005;
xlDialogFileDelete = $00000006;
xlDialogPageSetup = $00000007;
xlDialogPrint = $00000008;
xlDialogPrinterSetup = $00000009;
xlDialogArrangeAll = $0000000C;
xlDialogWindowSize = $0000000D;
xlDialogWindowMove = $0000000E;
xlDialogRun = $00000011;
xlDialogSetPrintTitles = $00000017;
xlDialogFont = $0000001A;
xlDialogDisplay = $0000001B;
xlDialogProtectDocument = $0000001C;
xlDialogCalculation = $00000020;
xlDialogExtract = $00000023;
xlDialogDataDelete = $00000024;
xlDialogSort = $00000027;
xlDialogDataSeries = $00000028;
xlDialogTable = $00000029;
xlDialogFormatNumber = $0000002A;
xlDialogAlignment = $0000002B;
xlDialogStyle = $0000002C;
xlDialogBorder = $0000002D;
xlDialogCellProtection = $0000002E;
xlDialogColumnWidth = $0000002F;
xlDialogClear = $00000034;
xlDialogPasteSpecial = $00000035;
xlDialogEditDelete = $00000036;
xlDialogInsert = $00000037;
xlDialogPasteNames = $0000003A;
xlDialogDefineName = $0000003D;
xlDialogCreateNames = $0000003E;
xlDialogFormulaGoto = $0000003F;
xlDialogFormulaFind = $00000040;
xlDialogGalleryArea = $00000043;
xlDialogGalleryBar = $00000044;
xlDialogGalleryColumn = $00000045;
xlDialogGalleryLine = $00000046;
xlDialogGalleryPie = $00000047;
xlDialogGalleryScatter = $00000048;
xlDialogCombination = $00000049;
xlDialogGridlines = $0000004C;
xlDialogAxes = $0000004E;
xlDialogAttachText = $00000050;
xlDialogPatterns = $00000054;
xlDialogMainChart = $00000055;
xlDialogOverlay = $00000056;
xlDialogScale = $00000057;
xlDialogFormatLegend = $00000058;
xlDialogFormatText = $00000059;
xlDialogParse = $0000005B;
xlDialogUnhide = $0000005E;
xlDialogWorkspace = $0000005F;
xlDialogActivate = $00000067;
xlDialogCopyPicture = $0000006C;
xlDialogDeleteName = $0000006E;
xlDialogDeleteFormat = $0000006F;
xlDialogNew = $00000077;
xlDialogRowHeight = $0000007F;
xlDialogFormatMove = $00000080;
xlDialogFormatSize = $00000081;
xlDialogFormulaReplace = $00000082;
xlDialogSelectSpecial = $00000084;
xlDialogApplyNames = $00000085;
xlDialogReplaceFont = $00000086;
xlDialogSplit = $00000089;
xlDialogOutline = $0000008E;
xlDialogSaveWorkbook = $00000091;
xlDialogCopyChart = $00000093;
xlDialogFormatFont = $00000096;
xlDialogNote = $0000009A;
xlDialogSetUpdateStatus = $0000009F;
xlDialogColorPalette = $000000A1;
xlDialogChangeLink = $000000A6;
xlDialogAppMove = $000000AA;
xlDialogAppSize = $000000AB;
xlDialogMainChartType = $000000B9;
xlDialogOverlayChartType = $000000BA;
xlDialogOpenMail = $000000BC;
xlDialogSendMail = $000000BD;
xlDialogStandardFont = $000000BE;
xlDialogConsolidate = $000000BF;
xlDialogSortSpecial = $000000C0;
xlDialogGallery3dArea = $000000C1;
xlDialogGallery3dColumn = $000000C2;
xlDialogGallery3dLine = $000000C3;
xlDialogGallery3dPie = $000000C4;
xlDialogView3d = $000000C5;
xlDialogGoalSeek = $000000C6;
xlDialogWorkgroup = $000000C7;
xlDialogFillGroup = $000000C8;
xlDialogUpdateLink = $000000C9;
xlDialogPromote = $000000CA;
xlDialogDemote = $000000CB;
xlDialogShowDetail = $000000CC;
xlDialogObjectProperties = $000000CF;
xlDialogSaveNewObject = $000000D0;
xlDialogApplyStyle = $000000D4;
xlDialogAssignToObject = $000000D5;
xlDialogObjectProtection = $000000D6;
xlDialogCreatePublisher = $000000D9;
xlDialogSubscribeTo = $000000DA;
xlDialogShowToolbar = $000000DC;
xlDialogPrintPreview = $000000DE;
xlDialogEditColor = $000000DF;
xlDialogFormatMain = $000000E1;
xlDialogFormatOverlay = $000000E2;
xlDialogEditSeries = $000000E4;
xlDialogDefineStyle = $000000E5;
xlDialogGalleryRadar = $000000F9;
xlDialogEditionOptions = $000000FB;
xlDialogZoom = $00000100;
xlDialogInsertObject = $00000103;
xlDialogSize = $00000105;
xlDialogMove = $00000106;
xlDialogFormatAuto = $0000010D;
xlDialogGallery3dBar = $00000110;
xlDialogGallery3dSurface = $00000111;
xlDialogCustomizeToolbar = $00000114;
xlDialogWorkbookAdd = $00000119;
xlDialogWorkbookMove = $0000011A;
xlDialogWorkbookCopy = $0000011B;
xlDialogWorkbookOptions = $0000011C;
xlDialogSaveWorkspace = $0000011D;
xlDialogChartWizard = $00000120;
xlDialogAssignToTool = $00000125;
xlDialogPlacement = $0000012C;
xlDialogFillWorkgroup = $0000012D;
xlDialogWorkbookNew = $0000012E;
xlDialogScenarioCells = $00000131;
xlDialogScenarioAdd = $00000133;
xlDialogScenarioEdit = $00000134;
xlDialogScenarioSummary = $00000137;
xlDialogPivotTableWizard = $00000138;
xlDialogPivotFieldProperties = $00000139;
xlDialogOptionsCalculation = $0000013E;
xlDialogOptionsEdit = $0000013F;
xlDialogOptionsView = $00000140;
xlDialogAddinManager = $00000141;
xlDialogMenuEditor = $00000142;
xlDialogAttachToolbars = $00000143;
xlDialogOptionsChart = $00000145;
xlDialogVbaInsertFile = $00000148;
xlDialogVbaProcedureDefinition = $0000014A;
xlDialogRoutingSlip = $00000150;
xlDialogMailLogon = $00000153;
xlDialogInsertPicture = $00000156;
xlDialogGalleryDoughnut = $00000158;
xlDialogChartTrend = $0000015E;
xlDialogWorkbookInsert = $00000162;
xlDialogOptionsTransition = $00000163;
xlDialogOptionsGeneral = $00000164;
xlDialogFilterAdvanced = $00000172;
xlDialogMailNextLetter = $0000017A;
xlDialogDataLabel = $0000017B;
xlDialogInsertTitle = $0000017C;
xlDialogFontProperties = $0000017D;
xlDialogMacroOptions = $0000017E;
xlDialogWorkbookUnhide = $00000180;
xlDialogWorkbookName = $00000182;
xlDialogGalleryCustom = $00000184;
xlDialogAddChartAutoformat = $00000186;
xlDialogChartAddData = $00000188;
xlDialogTabOrder = $0000018A;
xlDialogSubtotalCreate = $0000018E;
xlDialogWorkbookTabSplit = $0000019F;
xlDialogWorkbookProtect = $000001A1;
xlDialogScrollbarProperties = $000001A4;
xlDialogPivotShowPages = $000001A5;
xlDialogTextToColumns = $000001A6;
xlDialogCheckboxProperties = $000001B3;
xlDialogLabelProperties = $000001B4;
xlDialogListboxProperties = $000001B5;
xlDialogEditboxProperties = $000001B6;
xlDialogOpenText = $000001B9;
xlDialogPushbuttonProperties = $000001BD;
xlDialogFilter = $000001BF;
xlDialogFunctionWizard = $000001C2;
xlDialogSaveCopyAs = $000001C8;
xlDialogOptionsListsAdd = $000001CA;
xlDialogSeriesAxes = $000001CC;
xlDialogSeriesX = $000001CD;
xlDialogSeriesY = $000001CE;
xlDialogErrorbarX = $000001CF;
xlDialogErrorbarY = $000001D0;
xlDialogFormatChart = $000001D1;
xlDialogSeriesOrder = $000001D2;
xlDialogMailEditMailer = $000001D6;
xlDialogStandardWidth = $000001D8;
xlDialogScenarioMerge = $000001D9;
xlDialogProperties = $000001DA;
xlDialogSummaryInfo = $000001DA;
xlDialogFindFile = $000001DB;
xlDialogActiveCellFont = $000001DC;
xlDialogVbaMakeAddin = $000001DE;
xlDialogFileSharing = $000001E1;
xlDialogAutoCorrect = $000001E5;
xlDialogCustomViews = $000001ED;
xlDialogInsertNameLabel = $000001F0;
xlDialogSeriesShape = $000001F8;
xlDialogChartOptionsDataLabels = $000001F9;
xlDialogChartOptionsDataTable = $000001FA;
xlDialogSetBackgroundPicture = $000001FD;
xlDialogDataValidation = $0000020D;
xlDialogChartType = $0000020E;
xlDialogChartLocation = $0000020F;
_xlDialogPhonetic = $0000021A;
xlDialogChartSourceData = $0000021C;
_xlDialogChartSourceData = $0000021D;
xlDialogSeriesOptions = $0000022D;
xlDialogPivotTableOptions = $00000237;
xlDialogPivotSolveOrder = $00000238;
xlDialogPivotCalculatedField = $0000023A;
xlDialogPivotCalculatedItem = $0000023C;
xlDialogConditionalFormatting = $00000247;
xlDialogInsertHyperlink = $00000254;
xlDialogProtectSharing = $0000026C;
xlDialogOptionsME = $00000287;
xlDialogPublishAsWebPage = $0000028D;
xlDialogPhonetic = $00000290;
xlDialogNewWebQuery = $0000029B;
xlDialogImportTextFile = $0000029A;
xlDialogExternalDataProperties = $00000212;
xlDialogWebOptionsGeneral = $000002AB;
xlDialogWebOptionsFiles = $000002AC;
xlDialogWebOptionsPictures = $000002AD;
xlDialogWebOptionsEncoding = $000002AE;
xlDialogWebOptionsFonts = $000002AF;
xlDialogPivotClientServerSet = $000002B1;
xlDialogPropertyFields = $000002F2;
xlDialogSearch = $000002DB;
xlDialogEvaluateFormula = $000002C5;
xlDialogDataLabelMultiple = $000002D3;
xlDialogChartOptionsDataLabelMultiple = $000002D4;
xlDialogErrorChecking = $000002DC;
xlDialogWebOptionsBrowsers = $00000305;
xlDialogCreateList = $0000031C;
xlDialogPermission = $00000340;
xlDialogMyPermission = $00000342;
xlDialogDocumentInspector = $0000035E;
xlDialogNameManager = $000003D1;
xlDialogNewName = $000003D2;
xlDialogSparklineInsertLine = $0000046D;
xlDialogSparklineInsertColumn = $0000046E;
xlDialogSparklineInsertWinLoss = $0000046F;
xlDialogSlicerSettings = $0000049B;
xlDialogSlicerCreation = $0000049E;
xlDialogSlicerPivotTableConnections = $000004A0;
xlDialogPivotTableSlicerConnections = $0000049F;
xlDialogPivotTableWhatIfAnalysisSettings = $00000481;
xlDialogSetManager = $00000455;
xlDialogSetMDXEditor = $000004B8;
xlDialogSetTupleEditorOnRows = $00000453;
xlDialogSetTupleEditorOnColumns = $00000454;
xlDialogManageRelationships = $000004F7;
xlDialogCreateRelationship = $000004F8;
xlDialogRecommendedPivotTables = $000004EA;
xlDialogForecastETS = $00000514;
xlDialogPivotDefaultLayout = $00000550;
// Constants for enum XlParameterType
xlPrompt = $00000000;
xlConstant = $00000001;
xlRange = $00000002;
// Constants for enum XlParameterDataType
xlParamTypeUnknown = $00000000;
xlParamTypeChar = $00000001;
xlParamTypeNumeric = $00000002;
xlParamTypeDecimal = $00000003;
xlParamTypeInteger = $00000004;
xlParamTypeSmallInt = $00000005;
xlParamTypeFloat = $00000006;
xlParamTypeReal = $00000007;
xlParamTypeDouble = $00000008;
xlParamTypeVarChar = $0000000C;
xlParamTypeDate = $00000009;
xlParamTypeTime = $0000000A;
xlParamTypeTimestamp = $0000000B;
xlParamTypeLongVarChar = $FFFFFFFF;
xlParamTypeBinary = $FFFFFFFE;
xlParamTypeVarBinary = $FFFFFFFD;
xlParamTypeLongVarBinary = $FFFFFFFC;
xlParamTypeBigInt = $FFFFFFFB;
xlParamTypeTinyInt = $FFFFFFFA;
xlParamTypeBit = $FFFFFFF9;
xlParamTypeWChar = $FFFFFFF8;
// Constants for enum XlFormControl
xlButtonControl = $00000000;
xlCheckBox = $00000001;
xlDropDown = $00000002;
xlEditBox = $00000003;
xlGroupBox = $00000004;
xlLabel = $00000005;
xlListBox = $00000006;
xlOptionButton = $00000007;
xlScrollBar = $00000008;
xlSpinner = $00000009;
// Constants for enum XlSourceType
xlSourceWorkbook = $00000000;
xlSourceSheet = $00000001;
xlSourcePrintArea = $00000002;
xlSourceAutoFilter = $00000003;
xlSourceRange = $00000004;
xlSourceChart = $00000005;
xlSourcePivotTable = $00000006;
xlSourceQuery = $00000007;
// Constants for enum XlHtmlType
xlHtmlStatic = $00000000;
xlHtmlCalc = $00000001;
xlHtmlList = $00000002;
xlHtmlChart = $00000003;
// Constants for enum XlPivotFormatType
xlReport1 = $00000000;
xlReport2 = $00000001;
xlReport3 = $00000002;
xlReport4 = $00000003;
xlReport5 = $00000004;
xlReport6 = $00000005;
xlReport7 = $00000006;
xlReport8 = $00000007;
xlReport9 = $00000008;
xlReport10 = $00000009;
xlTable1 = $0000000A;
xlTable2 = $0000000B;
xlTable3 = $0000000C;
xlTable4 = $0000000D;
xlTable5 = $0000000E;
xlTable6 = $0000000F;
xlTable7 = $00000010;
xlTable8 = $00000011;
xlTable9 = $00000012;
xlTable10 = $00000013;
xlPTClassic = $00000014;
xlPTNone = $00000015;
// Constants for enum XlCmdType
xlCmdCube = $00000001;
xlCmdSql = $00000002;
xlCmdTable = $00000003;
xlCmdDefault = $00000004;
xlCmdList = $00000005;
xlCmdTableCollection = $00000006;
xlCmdExcel = $00000007;
xlCmdDAX = $00000008;
// Constants for enum XlColumnDataType
xlGeneralFormat = $00000001;
xlTextFormat = $00000002;
xlMDYFormat = $00000003;
xlDMYFormat = $00000004;
xlYMDFormat = $00000005;
xlMYDFormat = $00000006;
xlDYMFormat = $00000007;
xlYDMFormat = $00000008;
xlSkipColumn = $00000009;
xlEMDFormat = $0000000A;
// Constants for enum XlQueryType
xlODBCQuery = $00000001;
xlDAORecordset = $00000002;
xlWebQuery = $00000004;
xlOLEDBQuery = $00000005;
xlTextImport = $00000006;
xlADORecordset = $00000007;
// Constants for enum XlWebSelectionType
xlEntirePage = $00000001;
xlAllTables = $00000002;
xlSpecifiedTables = $00000003;
// Constants for enum XlCubeFieldType
xlHierarchy = $00000001;
xlMeasure = $00000002;
xlSet = $00000003;
// Constants for enum XlWebFormatting
xlWebFormattingAll = $00000001;
xlWebFormattingRTF = $00000002;
xlWebFormattingNone = $00000003;
// Constants for enum XlDisplayDrawingObjects
xlDisplayShapes = $FFFFEFF8;
xlHide = $00000003;
xlPlaceholders = $00000002;
// Constants for enum XlSubtototalLocationType
xlAtTop = $00000001;
xlAtBottom = $00000002;
// Constants for enum XlPivotTableVersionList
xlPivotTableVersion2000 = $00000000;
xlPivotTableVersion10 = $00000001;
xlPivotTableVersion11 = $00000002;
xlPivotTableVersion12 = $00000003;
xlPivotTableVersion14 = $00000004;
xlPivotTableVersion15 = $00000005;
xlPivotTableVersionCurrent = $FFFFFFFF;
// Constants for enum XlPrintErrors
xlPrintErrorsDisplayed = $00000000;
xlPrintErrorsBlank = $00000001;
xlPrintErrorsDash = $00000002;
xlPrintErrorsNA = $00000003;
// Constants for enum XlPivotCellType
xlPivotCellValue = $00000000;
xlPivotCellPivotItem = $00000001;
xlPivotCellSubtotal = $00000002;
xlPivotCellGrandTotal = $00000003;
xlPivotCellDataField = $00000004;
xlPivotCellPivotField = $00000005;
xlPivotCellPageFieldItem = $00000006;
xlPivotCellCustomSubtotal = $00000007;
xlPivotCellDataPivotField = $00000008;
xlPivotCellBlankCell = $00000009;
// Constants for enum XlPivotTableMissingItems
xlMissingItemsDefault = $FFFFFFFF;
xlMissingItemsNone = $00000000;
xlMissingItemsMax = $00007EF4;
xlMissingItemsMax2 = $00100000;
// Constants for enum XlCalculationState
xlDone = $00000000;
xlCalculating = $00000001;
xlPending = $00000002;
// Constants for enum XlCalculationInterruptKey
xlNoKey = $00000000;
xlEscKey = $00000001;
xlAnyKey = $00000002;
// Constants for enum XlSortDataOption
xlSortNormal = $00000000;
xlSortTextAsNumbers = $00000001;
// Constants for enum XlUpdateLinks
xlUpdateLinksUserSetting = $00000001;
xlUpdateLinksNever = $00000002;
xlUpdateLinksAlways = $00000003;
// Constants for enum XlLinkStatus
xlLinkStatusOK = $00000000;
xlLinkStatusMissingFile = $00000001;
xlLinkStatusMissingSheet = $00000002;
xlLinkStatusOld = $00000003;
xlLinkStatusSourceNotCalculated = $00000004;
xlLinkStatusIndeterminate = $00000005;
xlLinkStatusNotStarted = $00000006;
xlLinkStatusInvalidName = $00000007;
xlLinkStatusSourceNotOpen = $00000008;
xlLinkStatusSourceOpen = $00000009;
xlLinkStatusCopiedValues = $0000000A;
// Constants for enum XlSearchWithin
xlWithinSheet = $00000001;
xlWithinWorkbook = $00000002;
// Constants for enum XlCorruptLoad
xlNormalLoad = $00000000;
xlRepairFile = $00000001;
xlExtractData = $00000002;
// Constants for enum XlRobustConnect
xlAsRequired = $00000000;
xlAlways = $00000001;
xlNever = $00000002;
// Constants for enum XlErrorChecks
xlEvaluateToError = $00000001;
xlTextDate = $00000002;
xlNumberAsText = $00000003;
xlInconsistentFormula = $00000004;
xlOmittedCells = $00000005;
xlUnlockedFormulaCells = $00000006;
xlEmptyCellReferences = $00000007;
xlListDataValidation = $00000008;
xlInconsistentListFormula = $00000009;
xlMisleadingFormat = $0000000A;
// Constants for enum XlDataLabelSeparator
xlDataLabelSeparatorDefault = $00000001;
// Constants for enum XlSmartTagDisplayMode
xlIndicatorAndButton = $00000000;
xlDisplayNone = $00000001;
xlButtonOnly = $00000002;
// Constants for enum XlRangeValueDataType
xlRangeValueDefault = $0000000A;
xlRangeValueXMLSpreadsheet = $0000000B;
xlRangeValueMSPersistXML = $0000000C;
// Constants for enum XlSpeakDirection
xlSpeakByRows = $00000000;
xlSpeakByColumns = $00000001;
// Constants for enum XlInsertFormatOrigin
xlFormatFromLeftOrAbove = $00000000;
xlFormatFromRightOrBelow = $00000001;
// Constants for enum XlArabicModes
xlArabicNone = $00000000;
xlArabicStrictAlefHamza = $00000001;
xlArabicStrictFinalYaa = $00000002;
xlArabicBothStrict = $00000003;
// Constants for enum XlImportDataAs
xlQueryTable = $00000000;
xlPivotTableReport = $00000001;
xlTable = $00000002;
// Constants for enum XlCalculatedMemberType
xlCalculatedMember = $00000000;
xlCalculatedSet = $00000001;
xlCalculatedMeasure = $00000002;
// Constants for enum XlHebrewModes
xlHebrewFullScript = $00000000;
xlHebrewPartialScript = $00000001;
xlHebrewMixedScript = $00000002;
xlHebrewMixedAuthorizedScript = $00000003;
// Constants for enum XlListObjectSourceType
xlSrcExternal = $00000000;
xlSrcRange = $00000001;
xlSrcXml = $00000002;
xlSrcQuery = $00000003;
xlSrcModel = $00000004;
// Constants for enum XlTextVisualLayoutType
xlTextVisualLTR = $00000001;
xlTextVisualRTL = $00000002;
// Constants for enum XlListDataType
xlListDataTypeNone = $00000000;
xlListDataTypeText = $00000001;
xlListDataTypeMultiLineText = $00000002;
xlListDataTypeNumber = $00000003;
xlListDataTypeCurrency = $00000004;
xlListDataTypeDateTime = $00000005;
xlListDataTypeChoice = $00000006;
xlListDataTypeChoiceMulti = $00000007;
xlListDataTypeListLookup = $00000008;
xlListDataTypeCheckbox = $00000009;
xlListDataTypeHyperLink = $0000000A;
xlListDataTypeCounter = $0000000B;
xlListDataTypeMultiLineRichText = $0000000C;
// Constants for enum XlTotalsCalculation
xlTotalsCalculationNone = $00000000;
xlTotalsCalculationSum = $00000001;
xlTotalsCalculationAverage = $00000002;
xlTotalsCalculationCount = $00000003;
xlTotalsCalculationCountNums = $00000004;
xlTotalsCalculationMin = $00000005;
xlTotalsCalculationMax = $00000006;
xlTotalsCalculationStdDev = $00000007;
xlTotalsCalculationVar = $00000008;
xlTotalsCalculationCustom = $00000009;
// Constants for enum XlXmlLoadOption
xlXmlLoadPromptUser = $00000000;
xlXmlLoadOpenXml = $00000001;
xlXmlLoadImportToList = $00000002;
xlXmlLoadMapXml = $00000003;
// Constants for enum XlSmartTagControlType
xlSmartTagControlSmartTag = $00000001;
xlSmartTagControlLink = $00000002;
xlSmartTagControlHelp = $00000003;
xlSmartTagControlHelpURL = $00000004;
xlSmartTagControlSeparator = $00000005;
xlSmartTagControlButton = $00000006;
xlSmartTagControlLabel = $00000007;
xlSmartTagControlImage = $00000008;
xlSmartTagControlCheckbox = $00000009;
xlSmartTagControlTextbox = $0000000A;
xlSmartTagControlListbox = $0000000B;
xlSmartTagControlCombo = $0000000C;
xlSmartTagControlActiveX = $0000000D;
xlSmartTagControlRadioGroup = $0000000E;
// Constants for enum XlListConflict
xlListConflictDialog = $00000000;
xlListConflictRetryAllConflicts = $00000001;
xlListConflictDiscardAllConflicts = $00000002;
xlListConflictError = $00000003;
// Constants for enum XlXmlExportResult
xlXmlExportSuccess = $00000000;
xlXmlExportValidationFailed = $00000001;
// Constants for enum XlXmlImportResult
xlXmlImportSuccess = $00000000;
xlXmlImportElementsTruncated = $00000001;
xlXmlImportValidationFailed = $00000002;
// Constants for enum XlRemoveDocInfoType
xlRDIComments = $00000001;
xlRDIRemovePersonalInformation = $00000004;
xlRDIEmailHeader = $00000005;
xlRDIRoutingSlip = $00000006;
xlRDISendForReview = $00000007;
xlRDIDocumentProperties = $00000008;
xlRDIDocumentWorkspace = $0000000A;
xlRDIInkAnnotations = $0000000B;
xlRDIScenarioComments = $0000000C;
xlRDIPublishInfo = $0000000D;
xlRDIDocumentServerProperties = $0000000E;
xlRDIDocumentManagementPolicy = $0000000F;
xlRDIContentType = $00000010;
xlRDIDefinedNameComments = $00000012;
xlRDIInactiveDataConnections = $00000013;
xlRDIPrinterPath = $00000014;
xlRDIInlineWebExtensions = $00000015;
xlRDITaskpaneWebExtensions = $00000016;
xlRDIExcelDataModel = $00000017;
xlRDIAll = $00000063;
// Constants for enum XlRgbColor
rgbAliceBlue = $00FFF8F0;
rgbAntiqueWhite = $00D7EBFA;
rgbAqua = $00FFFF00;
rgbAquamarine = $00D4FF7F;
rgbAzure = $00FFFFF0;
rgbBeige = $00DCF5F5;
rgbBisque = $00C4E4FF;
rgbBlack = $00000000;
rgbBlanchedAlmond = $00CDEBFF;
rgbBlue = $00FF0000;
rgbBlueViolet = $00E22B8A;
rgbBrown = $002A2AA5;
rgbBurlyWood = $0087B8DE;
rgbCadetBlue = $00A09E5F;
rgbChartreuse = $0000FF7F;
rgbCoral = $00507FFF;
rgbCornflowerBlue = $00ED9564;
rgbCornsilk = $00DCF8FF;
rgbCrimson = $003C14DC;
rgbDarkBlue = $008B0000;
rgbDarkCyan = $008B8B00;
rgbDarkGoldenrod = $000B86B8;
rgbDarkGreen = $00006400;
rgbDarkGray = $00A9A9A9;
rgbDarkGrey = $00A9A9A9;
rgbDarkKhaki = $006BB7BD;
rgbDarkMagenta = $008B008B;
rgbDarkOliveGreen = $002F6B55;
rgbDarkOrange = $00008CFF;
rgbDarkOrchid = $00CC3299;
rgbDarkRed = $0000008B;
rgbDarkSalmon = $007A96E9;
rgbDarkSeaGreen = $008FBC8F;
rgbDarkSlateBlue = $008B3D48;
rgbDarkSlateGray = $004F4F2F;
rgbDarkSlateGrey = $004F4F2F;
rgbDarkTurquoise = $00D1CE00;
rgbDarkViolet = $00D30094;
rgbDeepPink = $009314FF;
rgbDeepSkyBlue = $00FFBF00;
rgbDimGray = $00696969;
rgbDimGrey = $00696969;
rgbDodgerBlue = $00FF901E;
rgbFireBrick = $002222B2;
rgbFloralWhite = $00F0FAFF;
rgbForestGreen = $00228B22;
rgbFuchsia = $00FF00FF;
rgbGainsboro = $00DCDCDC;
rgbGhostWhite = $00FFF8F8;
rgbGold = $0000D7FF;
rgbGoldenrod = $0020A5DA;
rgbGray = $00808080;
rgbGreen = $00008000;
rgbGrey = $00808080;
rgbGreenYellow = $002FFFAD;
rgbHoneydew = $00F0FFF0;
rgbHotPink = $00B469FF;
rgbIndianRed = $005C5CCD;
rgbIndigo = $0082004B;
rgbIvory = $00F0FFFF;
rgbKhaki = $008CE6F0;
rgbLavender = $00FAE6E6;
rgbLavenderBlush = $00F5F0FF;
rgbLawnGreen = $0000FC7C;
rgbLemonChiffon = $00CDFAFF;
rgbLightBlue = $00E6D8AD;
rgbLightCoral = $008080F0;
rgbLightCyan = $008B8B00;
rgbLightGoldenrodYellow = $00D2FAFA;
rgbLightGray = $00D3D3D3;
rgbLightGreen = $0090EE90;
rgbLightGrey = $00D3D3D3;
rgbLightPink = $00C1B6FF;
rgbLightSalmon = $007AA0FF;
rgbLightSeaGreen = $00AAB220;
rgbLightSkyBlue = $00FACE87;
rgbLightSlateGray = $00998877;
rgbLightSlateGrey = $00998877;
rgbLightSteelBlue = $00DEC4B0;
rgbLightYellow = $00E0FFFF;
rgbLime = $0000FF00;
rgbLimeGreen = $0032CD32;
rgbLinen = $00E6F0FA;
rgbMaroon = $00000080;
rgbMediumAquamarine = $00AAFF66;
rgbMediumBlue = $00CD0000;
rgbMediumOrchid = $00D355BA;
rgbMediumPurple = $00DB7093;
rgbMediumSeaGreen = $0071B33C;
rgbMediumSlateBlue = $00EE687B;
rgbMediumSpringGreen = $009AFA00;
rgbMediumTurquoise = $00CCD148;
rgbMediumVioletRed = $008515C7;
rgbMidnightBlue = $00701919;
rgbMintCream = $00FAFFF5;
rgbMistyRose = $00E1E4FF;
rgbMoccasin = $00B5E4FF;
rgbNavajoWhite = $00ADDEFF;
rgbNavy = $00800000;
rgbNavyBlue = $00800000;
rgbOldLace = $00E6F5FD;
rgbOlive = $00008080;
rgbOliveDrab = $00238E6B;
rgbOrange = $0000A5FF;
rgbOrangeRed = $000045FF;
rgbOrchid = $00D670DA;
rgbPaleGoldenrod = $006BE8EE;
rgbPaleGreen = $0098FB98;
rgbPaleTurquoise = $00EEEEAF;
rgbPaleVioletRed = $009370DB;
rgbPapayaWhip = $00D5EFFF;
rgbPeachPuff = $00B9DAFF;
rgbPeru = $003F85CD;
rgbPink = $00CBC0FF;
rgbPlum = $00DDA0DD;
rgbPowderBlue = $00E6E0B0;
rgbPurple = $00800080;
rgbRed = $000000FF;
rgbRosyBrown = $008F8FBC;
rgbRoyalBlue = $00E16941;
rgbSalmon = $007280FA;
rgbSandyBrown = $0060A4F4;
rgbSeaGreen = $00578B2E;
rgbSeashell = $00EEF5FF;
rgbSienna = $002D52A0;
rgbSilver = $00C0C0C0;
rgbSkyBlue = $00EBCE87;
rgbSlateBlue = $00CD5A6A;
rgbSlateGray = $00908070;
rgbSlateGrey = $00908070;
rgbSnow = $00FAFAFF;
rgbSpringGreen = $007FFF00;
rgbSteelBlue = $00B48246;
rgbTan = $008CB4D2;
rgbTeal = $00808000;
rgbThistle = $00D8BFD8;
rgbTomato = $004763FF;
rgbTurquoise = $00D0E040;
rgbYellow = $0000FFFF;
rgbYellowGreen = $0032CD9A;
rgbViolet = $00EE82EE;
rgbWheat = $00B3DEF5;
rgbWhite = $00FFFFFF;
rgbWhiteSmoke = $00F5F5F5;
// Constants for enum XlStdColorScale
xlColorScaleRYG = $00000001;
xlColorScaleGYR = $00000002;
xlColorScaleBlackWhite = $00000003;
xlColorScaleWhiteBlack = $00000004;
// Constants for enum XlConditionValueTypes
xlConditionValueNone = $FFFFFFFF;
xlConditionValueNumber = $00000000;
xlConditionValueLowestValue = $00000001;
xlConditionValueHighestValue = $00000002;
xlConditionValuePercent = $00000003;
xlConditionValueFormula = $00000004;
xlConditionValuePercentile = $00000005;
xlConditionValueAutomaticMin = $00000006;
xlConditionValueAutomaticMax = $00000007;
// Constants for enum XlFormatFilterTypes
xlFilterBottom = $00000000;
xlFilterTop = $00000001;
xlFilterBottomPercent = $00000002;
xlFilterTopPercent = $00000003;
// Constants for enum XlContainsOperator
xlContains = $00000000;
xlDoesNotContain = $00000001;
xlBeginsWith = $00000002;
xlEndsWith = $00000003;
// Constants for enum XlAboveBelow
xlAboveAverage = $00000000;
xlBelowAverage = $00000001;
xlEqualAboveAverage = $00000002;
xlEqualBelowAverage = $00000003;
xlAboveStdDev = $00000004;
xlBelowStdDev = $00000005;
// Constants for enum XlLookFor
xlLookForBlanks = $00000000;
xlLookForErrors = $00000001;
xlLookForFormulas = $00000002;
// Constants for enum XlTimePeriods
xlToday = $00000000;
xlYesterday = $00000001;
xlLast7Days = $00000002;
xlThisWeek = $00000003;
xlLastWeek = $00000004;
xlLastMonth = $00000005;
xlTomorrow = $00000006;
xlNextWeek = $00000007;
xlNextMonth = $00000008;
xlThisMonth = $00000009;
// Constants for enum XlDupeUnique
xlUnique = $00000000;
xlDuplicate = $00000001;
// Constants for enum XlTopBottom
xlTop10Top = $00000001;
xlTop10Bottom = $00000000;
// Constants for enum XlIconSet
xlCustomSet = $FFFFFFFF;
xl3Arrows = $00000001;
xl3ArrowsGray = $00000002;
xl3Flags = $00000003;
xl3TrafficLights1 = $00000004;
xl3TrafficLights2 = $00000005;
xl3Signs = $00000006;
xl3Symbols = $00000007;
xl3Symbols2 = $00000008;
xl4Arrows = $00000009;
xl4ArrowsGray = $0000000A;
xl4RedToBlack = $0000000B;
xl4CRV = $0000000C;
xl4TrafficLights = $0000000D;
xl5Arrows = $0000000E;
xl5ArrowsGray = $0000000F;
xl5CRV = $00000010;
xl5Quarters = $00000011;
xl3Stars = $00000012;
xl3Triangles = $00000013;
xl5Boxes = $00000014;
// Constants for enum XlThemeFont
xlThemeFontNone = $00000000;
xlThemeFontMajor = $00000001;
xlThemeFontMinor = $00000002;
// Constants for enum XlPivotLineType
xlPivotLineRegular = $00000000;
xlPivotLineSubtotal = $00000001;
xlPivotLineGrandTotal = $00000002;
xlPivotLineBlank = $00000003;
// Constants for enum XlCheckInVersionType
xlCheckInMinorVersion = $00000000;
xlCheckInMajorVersion = $00000001;
xlCheckInOverwriteVersion = $00000002;
// Constants for enum XlPropertyDisplayedIn
xlDisplayPropertyInPivotTable = $00000001;
xlDisplayPropertyInTooltip = $00000002;
xlDisplayPropertyInPivotTableAndTooltip = $00000003;
// Constants for enum XlConnectionType
xlConnectionTypeOLEDB = $00000001;
xlConnectionTypeODBC = $00000002;
xlConnectionTypeXMLMAP = $00000003;
xlConnectionTypeTEXT = $00000004;
xlConnectionTypeWEB = $00000005;
xlConnectionTypeDATAFEED = $00000006;
xlConnectionTypeMODEL = $00000007;
xlConnectionTypeWORKSHEET = $00000008;
xlConnectionTypeNOSOURCE = $00000009;
// Constants for enum XlActionType
xlActionTypeUrl = $00000001;
xlActionTypeRowset = $00000010;
xlActionTypeReport = $00000080;
xlActionTypeDrillthrough = $00000100;
// Constants for enum XlLayoutRowType
xlCompactRow = $00000000;
xlTabularRow = $00000001;
xlOutlineRow = $00000002;
// Constants for enum XlMeasurementUnits
xlInches = $00000000;
xlCentimeters = $00000001;
xlMillimeters = $00000002;
// Constants for enum XlPivotFilterType
xlTopCount = $00000001;
xlBottomCount = $00000002;
xlTopPercent = $00000003;
xlBottomPercent = $00000004;
xlTopSum = $00000005;
xlBottomSum = $00000006;
xlValueEquals = $00000007;
xlValueDoesNotEqual = $00000008;
xlValueIsGreaterThan = $00000009;
xlValueIsGreaterThanOrEqualTo = $0000000A;
xlValueIsLessThan = $0000000B;
xlValueIsLessThanOrEqualTo = $0000000C;
xlValueIsBetween = $0000000D;
xlValueIsNotBetween = $0000000E;
xlCaptionEquals = $0000000F;
xlCaptionDoesNotEqual = $00000010;
xlCaptionBeginsWith = $00000011;
xlCaptionDoesNotBeginWith = $00000012;
xlCaptionEndsWith = $00000013;
xlCaptionDoesNotEndWith = $00000014;
xlCaptionContains = $00000015;
xlCaptionDoesNotContain = $00000016;
xlCaptionIsGreaterThan = $00000017;
xlCaptionIsGreaterThanOrEqualTo = $00000018;
xlCaptionIsLessThan = $00000019;
xlCaptionIsLessThanOrEqualTo = $0000001A;
xlCaptionIsBetween = $0000001B;
xlCaptionIsNotBetween = $0000001C;
xlSpecificDate = $0000001D;
xlNotSpecificDate = $0000001E;
xlBefore = $0000001F;
xlBeforeOrEqualTo = $00000020;
xlAfter = $00000021;
xlAfterOrEqualTo = $00000022;
xlDateBetween = $00000023;
xlDateNotBetween = $00000024;
xlDateTomorrow = $00000025;
xlDateToday = $00000026;
xlDateYesterday = $00000027;
xlDateNextWeek = $00000028;
xlDateThisWeek = $00000029;
xlDateLastWeek = $0000002A;
xlDateNextMonth = $0000002B;
xlDateThisMonth = $0000002C;
xlDateLastMonth = $0000002D;
xlDateNextQuarter = $0000002E;
xlDateThisQuarter = $0000002F;
xlDateLastQuarter = $00000030;
xlDateNextYear = $00000031;
xlDateThisYear = $00000032;
xlDateLastYear = $00000033;
xlYearToDate = $00000034;
xlAllDatesInPeriodQuarter1 = $00000035;
xlAllDatesInPeriodQuarter2 = $00000036;
xlAllDatesInPeriodQuarter3 = $00000037;
xlAllDatesInPeriodQuarter4 = $00000038;
xlAllDatesInPeriodJanuary = $00000039;
xlAllDatesInPeriodFebruary = $0000003A;
xlAllDatesInPeriodMarch = $0000003B;
xlAllDatesInPeriodApril = $0000003C;
xlAllDatesInPeriodMay = $0000003D;
xlAllDatesInPeriodJune = $0000003E;
xlAllDatesInPeriodJuly = $0000003F;
xlAllDatesInPeriodAugust = $00000040;
xlAllDatesInPeriodSeptember = $00000041;
xlAllDatesInPeriodOctober = $00000042;
xlAllDatesInPeriodNovember = $00000043;
xlAllDatesInPeriodDecember = $00000044;
// Constants for enum XlCredentialsMethod
xlCredentialsMethodIntegrated = $00000000;
xlCredentialsMethodNone = $00000001;
xlCredentialsMethodStored = $00000002;
// Constants for enum XlCubeFieldSubType
xlCubeHierarchy = $00000001;
xlCubeMeasure = $00000002;
xlCubeSet = $00000003;
xlCubeAttribute = $00000004;
xlCubeCalculatedMeasure = $00000005;
xlCubeKPIValue = $00000006;
xlCubeKPIGoal = $00000007;
xlCubeKPIStatus = $00000008;
xlCubeKPITrend = $00000009;
xlCubeKPIWeight = $0000000A;
xlCubeImplicitMeasure = $0000000B;
// Constants for enum XlSortOn
xlSortOnValues = $00000000;
xlSortOnCellColor = $00000001;
xlSortOnFontColor = $00000002;
xlSortOnIcon = $00000003;
// Constants for enum XlDynamicFilterCriteria
xlFilterToday = $00000001;
xlFilterYesterday = $00000002;
xlFilterTomorrow = $00000003;
xlFilterThisWeek = $00000004;
xlFilterLastWeek = $00000005;
xlFilterNextWeek = $00000006;
xlFilterThisMonth = $00000007;
xlFilterLastMonth = $00000008;
xlFilterNextMonth = $00000009;
xlFilterThisQuarter = $0000000A;
xlFilterLastQuarter = $0000000B;
xlFilterNextQuarter = $0000000C;
xlFilterThisYear = $0000000D;
xlFilterLastYear = $0000000E;
xlFilterNextYear = $0000000F;
xlFilterYearToDate = $00000010;
xlFilterAllDatesInPeriodQuarter1 = $00000011;
xlFilterAllDatesInPeriodQuarter2 = $00000012;
xlFilterAllDatesInPeriodQuarter3 = $00000013;
xlFilterAllDatesInPeriodQuarter4 = $00000014;
xlFilterAllDatesInPeriodJanuary = $00000015;
xlFilterAllDatesInPeriodFebruray = $00000016;
xlFilterAllDatesInPeriodMarch = $00000017;
xlFilterAllDatesInPeriodApril = $00000018;
xlFilterAllDatesInPeriodMay = $00000019;
xlFilterAllDatesInPeriodJune = $0000001A;
xlFilterAllDatesInPeriodJuly = $0000001B;
xlFilterAllDatesInPeriodAugust = $0000001C;
xlFilterAllDatesInPeriodSeptember = $0000001D;
xlFilterAllDatesInPeriodOctober = $0000001E;
xlFilterAllDatesInPeriodNovember = $0000001F;
xlFilterAllDatesInPeriodDecember = $00000020;
xlFilterAboveAverage = $00000021;
xlFilterBelowAverage = $00000022;
// Constants for enum XlFilterAllDatesInPeriod
xlFilterAllDatesInPeriodYear = $00000000;
xlFilterAllDatesInPeriodMonth = $00000001;
xlFilterAllDatesInPeriodDay = $00000002;
xlFilterAllDatesInPeriodHour = $00000003;
xlFilterAllDatesInPeriodMinute = $00000004;
xlFilterAllDatesInPeriodSecond = $00000005;
// Constants for enum XlTableStyleElementType
xlWholeTable = $00000000;
xlHeaderRow = $00000001;
xlTotalRow = $00000002;
xlGrandTotalRow = $00000002;
xlFirstColumn = $00000003;
xlLastColumn = $00000004;
xlGrandTotalColumn = $00000004;
xlRowStripe1 = $00000005;
xlRowStripe2 = $00000006;
xlColumnStripe1 = $00000007;
xlColumnStripe2 = $00000008;
xlFirstHeaderCell = $00000009;
xlLastHeaderCell = $0000000A;
xlFirstTotalCell = $0000000B;
xlLastTotalCell = $0000000C;
xlSubtotalColumn1 = $0000000D;
xlSubtotalColumn2 = $0000000E;
xlSubtotalColumn3 = $0000000F;
xlSubtotalRow1 = $00000010;
xlSubtotalRow2 = $00000011;
xlSubtotalRow3 = $00000012;
xlBlankRow = $00000013;
xlColumnSubheading1 = $00000014;
xlColumnSubheading2 = $00000015;
xlColumnSubheading3 = $00000016;
xlRowSubheading1 = $00000017;
xlRowSubheading2 = $00000018;
xlRowSubheading3 = $00000019;
xlPageFieldLabels = $0000001A;
xlPageFieldValues = $0000001B;
xlSlicerUnselectedItemWithData = $0000001C;
xlSlicerUnselectedItemWithNoData = $0000001D;
xlSlicerSelectedItemWithData = $0000001E;
xlSlicerSelectedItemWithNoData = $0000001F;
xlSlicerHoveredUnselectedItemWithData = $00000020;
xlSlicerHoveredSelectedItemWithData = $00000021;
xlSlicerHoveredUnselectedItemWithNoData = $00000022;
xlSlicerHoveredSelectedItemWithNoData = $00000023;
xlTimelineSelectionLabel = $00000024;
xlTimelineTimeLevel = $00000025;
xlTimelinePeriodLabels1 = $00000026;
xlTimelinePeriodLabels2 = $00000027;
xlTimelineSelectedTimeBlock = $00000028;
xlTimelineUnselectedTimeBlock = $00000029;
xlTimelineSelectedTimeBlockSpace = $0000002A;
// Constants for enum XlPivotConditionScope
xlSelectionScope = $00000000;
xlFieldsScope = $00000001;
xlDataFieldScope = $00000002;
// Constants for enum XlCalcFor
xlAllValues = $00000000;
xlRowGroups = $00000001;
xlColGroups = $00000002;
// Constants for enum XlThemeColor
xlThemeColorDark1 = $00000001;
xlThemeColorLight1 = $00000002;
xlThemeColorDark2 = $00000003;
xlThemeColorLight2 = $00000004;
xlThemeColorAccent1 = $00000005;
xlThemeColorAccent2 = $00000006;
xlThemeColorAccent3 = $00000007;
xlThemeColorAccent4 = $00000008;
xlThemeColorAccent5 = $00000009;
xlThemeColorAccent6 = $0000000A;
xlThemeColorHyperlink = $0000000B;
xlThemeColorFollowedHyperlink = $0000000C;
// Constants for enum XlFixedFormatType
// Modified.
XlFixedFormatType_xlTypePDF = $00000000;
XlFixedFormatType_xlTypeXPS = $00000001;
// Constants for enum XlFixedFormatQuality
xlQualityStandard = $00000000;
xlQualityMinimum = $00000001;
// Constants for enum XlChartElementPosition
xlChartElementPositionAutomatic = $FFFFEFF7;
xlChartElementPositionCustom = $FFFFEFEE;
// Constants for enum XlGenerateTableRefs
xlGenerateTableRefA1 = $00000000;
xlGenerateTableRefStruct = $00000001;
// Constants for enum XlGradientFillType
xlGradientFillLinear = $00000000;
xlGradientFillPath = $00000001;
// Constants for enum XlThreadMode
xlThreadModeAutomatic = $00000000;
xlThreadModeManual = $00000001;
// Constants for enum XlOartHorizontalOverflow
xlOartHorizontalOverflowOverflow = $00000000;
xlOartHorizontalOverflowClip = $00000001;
// Constants for enum XlOartVerticalOverflow
xlOartVerticalOverflowOverflow = $00000000;
xlOartVerticalOverflowClip = $00000001;
xlOartVerticalOverflowEllipsis = $00000002;
// Constants for enum XlSparkScale
xlSparkScaleGroup = $00000001;
xlSparkScaleSingle = $00000002;
xlSparkScaleCustom = $00000003;
// Constants for enum XlSparkType
xlSparkLine = $00000001;
xlSparkColumn = $00000002;
xlSparkColumnStacked100 = $00000003;
// Constants for enum XlSparklineRowCol
xlSparklineNonSquare = $00000000;
xlSparklineRowsSquare = $00000001;
xlSparklineColumnsSquare = $00000002;
// Constants for enum XlDataBarFillType
xlDataBarFillSolid = $00000000;
xlDataBarFillGradient = $00000001;
// Constants for enum XlDataBarBorderType
xlDataBarBorderNone = $00000000;
xlDataBarBorderSolid = $00000001;
// Constants for enum XlDataBarAxisPosition
xlDataBarAxisAutomatic = $00000000;
xlDataBarAxisMidpoint = $00000001;
xlDataBarAxisNone = $00000002;
// Constants for enum XlDataBarNegativeColorType
xlDataBarColor = $00000000;
xlDataBarSameAsPositive = $00000001;
// Constants for enum XlAllocation
xlManualAllocation = $00000001;
xlAutomaticAllocation = $00000002;
// Constants for enum XlAllocationValue
xlAllocateValue = $00000001;
xlAllocateIncrement = $00000002;
// Constants for enum XlAllocationMethod
xlEqualAllocation = $00000001;
xlWeightedAllocation = $00000002;
// Constants for enum XlCellChangedState
xlCellNotChanged = $00000001;
xlCellChanged = $00000002;
xlCellChangeApplied = $00000003;
// Constants for enum XlPivotFieldRepeatLabels
xlDoNotRepeatLabels = $00000001;
xlRepeatLabels = $00000002;
// Constants for enum XlPieSliceIndex
xlOuterCounterClockwisePoint = $00000001;
xlOuterCenterPoint = $00000002;
xlOuterClockwisePoint = $00000003;
xlMidClockwiseRadiusPoint = $00000004;
xlCenterPoint = $00000005;
xlMidCounterClockwiseRadiusPoint = $00000006;
xlInnerClockwisePoint = $00000007;
xlInnerCenterPoint = $00000008;
xlInnerCounterClockwisePoint = $00000009;
// Constants for enum XlSpanishModes
xlSpanishTuteoOnly = $00000000;
xlSpanishTuteoAndVoseo = $00000001;
xlSpanishVoseoOnly = $00000002;
// Constants for enum XlSlicerCrossFilterType
xlSlicerNoCrossFilter = $00000001;
xlSlicerCrossFilterShowItemsWithDataAtTop = $00000002;
xlSlicerCrossFilterShowItemsWithNoData = $00000003;
xlSlicerCrossFilterHideButtonsWithNoData = $00000004;
// Constants for enum XlSlicerSort
xlSlicerSortDataSourceOrder = $00000001;
xlSlicerSortAscending = $00000002;
xlSlicerSortDescending = $00000003;
// Constants for enum XlIcon
xlIconNoCellIcon = $FFFFFFFF;
xlIconGreenUpArrow = $00000001;
xlIconYellowSideArrow = $00000002;
xlIconRedDownArrow = $00000003;
xlIconGrayUpArrow = $00000004;
xlIconGraySideArrow = $00000005;
xlIconGrayDownArrow = $00000006;
xlIconGreenFlag = $00000007;
xlIconYellowFlag = $00000008;
xlIconRedFlag = $00000009;
xlIconGreenCircle = $0000000A;
xlIconYellowCircle = $0000000B;
xlIconRedCircleWithBorder = $0000000C;
xlIconBlackCircleWithBorder = $0000000D;
xlIconGreenTrafficLight = $0000000E;
xlIconYellowTrafficLight = $0000000F;
xlIconRedTrafficLight = $00000010;
xlIconYellowTriangle = $00000011;
xlIconRedDiamond = $00000012;
xlIconGreenCheckSymbol = $00000013;
xlIconYellowExclamationSymbol = $00000014;
xlIconRedCrossSymbol = $00000015;
xlIconGreenCheck = $00000016;
xlIconYellowExclamation = $00000017;
xlIconRedCross = $00000018;
xlIconYellowUpInclineArrow = $00000019;
xlIconYellowDownInclineArrow = $0000001A;
xlIconGrayUpInclineArrow = $0000001B;
xlIconGrayDownInclineArrow = $0000001C;
xlIconRedCircle = $0000001D;
xlIconPinkCircle = $0000001E;
xlIconGrayCircle = $0000001F;
xlIconBlackCircle = $00000020;
xlIconCircleWithOneWhiteQuarter = $00000021;
xlIconCircleWithTwoWhiteQuarters = $00000022;
xlIconCircleWithThreeWhiteQuarters = $00000023;
xlIconWhiteCircleAllWhiteQuarters = $00000024;
xlIcon0Bars = $00000025;
xlIcon1Bar = $00000026;
xlIcon2Bars = $00000027;
xlIcon3Bars = $00000028;
xlIcon4Bars = $00000029;
xlIconGoldStar = $0000002A;
xlIconHalfGoldStar = $0000002B;
xlIconSilverStar = $0000002C;
xlIconGreenUpTriangle = $0000002D;
xlIconYellowDash = $0000002E;
xlIconRedDownTriangle = $0000002F;
xlIcon4FilledBoxes = $00000030;
xlIcon3FilledBoxes = $00000031;
xlIcon2FilledBoxes = $00000032;
xlIcon1FilledBox = $00000033;
xlIcon0FilledBoxes = $00000034;
// Constants for enum XlProtectedViewCloseReason
xlProtectedViewCloseNormal = $00000000;
xlProtectedViewCloseEdit = $00000001;
xlProtectedViewCloseForced = $00000002;
// Constants for enum XlProtectedViewWindowState
xlProtectedViewWindowNormal = $00000000;
xlProtectedViewWindowMinimized = $00000001;
xlProtectedViewWindowMaximized = $00000002;
// Constants for enum XlFileValidationPivotMode
xlFileValidationPivotDefault = $00000000;
xlFileValidationPivotRun = $00000001;
xlFileValidationPivotSkip = $00000002;
// Constants for enum XlPieSliceLocation
xlHorizontalCoordinate = $00000001;
xlVerticalCoordinate = $00000002;
// Constants for enum XlPortugueseReform
xlPortuguesePreReform = $00000001;
xlPortuguesePostReform = $00000002;
xlPortugueseBoth = $00000003;
// Constants for enum XlQuickAnalysisMode
xlLensOnly = $00000000;
xlFormatConditions = $00000001;
xlRecommendedCharts = $00000002;
xlTotals = $00000003;
xlTables = $00000004;
xlSparklines = $00000005;
// Constants for enum XlSlicerCacheType
xlSlicer = $00000001;
xlTimeline = $00000002;
// Constants for enum XlCategoryLabelLevel
xlCategoryLabelLevelNone = $FFFFFFFD;
xlCategoryLabelLevelCustom = $FFFFFFFE;
xlCategoryLabelLevelAll = $FFFFFFFF;
// Constants for enum XlSeriesNameLevel
xlSeriesNameLevelNone = $FFFFFFFD;
xlSeriesNameLevelCustom = $FFFFFFFE;
xlSeriesNameLevelAll = $FFFFFFFF;
// Constants for enum XlCalcMemNumberFormatType
xlNumberFormatTypeDefault = $00000000;
xlNumberFormatTypeNumber = $00000001;
xlNumberFormatTypePercent = $00000002;
// Constants for enum XlTimelineLevel
xlTimelineLevelYears = $00000000;
xlTimelineLevelQuarters = $00000001;
xlTimelineLevelMonths = $00000002;
xlTimelineLevelDays = $00000003;
// Constants for enum XlFilterStatus
xlFilterStatusOK = $00000000;
xlFilterStatusDateWrongOrder = $00000001;
xlFilterStatusDateHasTime = $00000002;
xlFilterStatusInvalidDate = $00000003;
// Constants for enum XlModelChangeSource
xlChangeByExcel = $00000000;
xlChangeByPowerPivotAddIn = $00000001;
// Constants for enum XlParentDataLabelOptions
xlParentDataLabelOptionsNone = $00000000;
xlParentDataLabelOptionsBanner = $00000001;
xlParentDataLabelOptionsOverlapping = $00000002;
// Constants for enum XlBinsType
xlBinsTypeAutomatic = $00000000;
xlBinsTypeCategorical = $00000001;
xlBinsTypeManual = $00000002;
xlBinsTypeBinSize = $00000003;
xlBinsTypeBinCount = $00000004;
// Constants for enum XlForecastDataCompletion
xlForecastDataCompletionZeros = $00000000;
xlForecastDataCompletionInterpolate = $00000001;
// Constants for enum XlForecastAggregation
xlForecastAggregationAverage = $00000001;
xlForecastAggregationCount = $00000002;
xlForecastAggregationCountA = $00000003;
xlForecastAggregationMax = $00000004;
xlForecastAggregationMedian = $00000005;
xlForecastAggregationMin = $00000006;
xlForecastAggregationSum = $00000007;
// Constants for enum XlForecastChartType
xlForecastChartTypeLine = $00000000;
xlForecastChartTypeColumn = $00000001;
// Constants for enum XlPublishToDocsDisclosureScope
msoPublic = $00000000;
msoLimited = $00000001;
msoOrganization = $00000002;
msoNoOverwrite = $00000003;
// Constants for enum XlCategorySortOrder
xlIndexAscending = $00000000;
xlIndexDescending = $00000001;
xlCategoryAscending = $00000002;
xlCategoryDescending = $00000003;
// Constants for enum XlValueSortOrder
xlValueNone = $00000000;
xlValueAscending = $00000001;
xlValueDescending = $00000002;
// Constants for enum XlGeoProjectionType
xlGeoProjectionTypeAutomatic = $00000000;
xlGeoProjectionTypeMercator = $00000001;
xlGeoProjectionTypeMiller = $00000002;
xlGeoProjectionTypeAlbers = $00000003;
xlGeoProjectionTypeRobinson = $00000004;
// Constants for enum XlGeoMappingLevel
xlGeoMappingLevelAutomatic = $00000000;
xlGeoMappingLevelDataOnly = $00000001;
xlGeoMappingLevelPostalCode = $00000002;
xlGeoMappingLevelCounty = $00000003;
xlGeoMappingLevelState = $00000004;
xlGeoMappingLevelCountryRegion = $00000005;
xlGeoMappingLevelCountryRegionList = $00000006;
xlGeoMappingLevelWorld = $00000007;
// Constants for enum XlRegionLabelOptions
xlRegionLabelOptionsNone = $00000000;
xlRegionLabelOptionsBestFitOnly = $00000001;
xlRegionLabelOptionsShowAll = $00000002;
// Constants for enum XlPublishToPBIPublishType
msoPBIExport = $00000000;
msoPBIUpload = $00000001;
// Constants for enum XlPublishToPBINameConflictAction
msoPBIIgnore = $00000000;
msoPBIAbort = $00000001;
msoPBIOverwrite = $00000002;
// Constants for enum XlSeriesColorGradientStyle
xlSeriesColorGradientStyleSequential = $00000000;
xlSeriesColorGradientStyleDiverging = $00000001;
// Constants for enum XlGradientStopPositionType
xlGradientStopPositionTypeExtremeValue = $00000000;
xlGradientStopPositionTypeNumber = $00000001;
xlGradientStopPositionTypePercent = $00000002;
// Constants for enum XlLinkedDataTypeState
xlLinkedDataTypeStateNone = $00000000;
xlLinkedDataTypeStateValidLinkedData = $00000001;
xlLinkedDataTypeStateDisambiguationNeeded = $00000002;
xlLinkedDataTypeStateBrokenLinkedData = $00000003;
xlLinkedDataTypeStateFetchingData = $00000004;
// Constants for enum XlFormulaVersion
xlReplaceFormula = $00000000;
xlReplaceFormula2 = $00000001;
implementation
end. |
unit ServiceControllForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,ShellAPI,
FMX.Objects, FMX.Layouts,Data.Win.ADODB, OLEDB, ActiveX, ComObj,WinApi.winSvc,ServiceControll,
Winapi.Messages,Winapi.Windows,FMX.Platform.Win,Preferences,System.Rtti;
type
TServiceControllForm = class(TForm)
InstallImage: TImage;
UninstallImage: TImage;
PauseImage: TImage;
SettingsImage: TImage;
StopImage: TImage;
StartImage: TImage;
ButtonsLayout: TLayout;
Timer1: TTimer;
ServiceStatusLabel: TLabel;
SmallTopVisualFixLayout: TLayout;
OpenDialog: TOpenDialog;
Layout1: TLayout;
Layout2: TLayout;
Layout3: TLayout;
Layout4: TLayout;
Layout5: TLayout;
Layout6: TLayout;
InstallServiceButton: TButton;
UnInstallServiceButton: TButton;
SetServiceSettingsButton: TButton;
StartServiceButton: TButton;
StopServiceButton: TButton;
PauseServiceButton: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Layout7: TLayout;
Brush1: TBrushObject;
procedure Timer1Timer(Sender: TObject);
procedure InstallServiceButtonClick(Sender: TObject);
procedure UnInstallServiceButtonClick(Sender: TObject);
procedure SetServiceSettingsButtonClick(Sender: TObject);
procedure StartServiceButtonClick(Sender: TObject);
procedure StopServiceButtonClick(Sender: TObject);
procedure PauseServiceButtonClick(Sender: TObject);
private
function CheckConnection(ConnectionString : string) : boolean;
procedure EnableAllButtons;
{ Private declarations }
public
{ Public declarations }
end;
var
ServiceControllForm1: TServiceControllForm;
implementation
{$R *.fmx}
function TServiceControllForm.CheckConnection(
ConnectionString: string): boolean;
var
AdoConnect : TAdoConnection;
RS : _Recordset;
begin
try
AdoConnect := TADOConnection.Create(nil);
AdoConnect.ConnectionString :=ConnectionString;
AdoConnect.Connected := true;
Result := true;
except
Result := false;
end;
AdoConnect.Free;
end;
procedure TServiceControllForm.EnableAllButtons;
var
i : integer;
begin
for i := 0 to ComponentCount-1 do
begin
if Components[i].ClassNameIs('TButton') then
TButton(Components[i]).Enabled := true;
end;
end;
procedure TServiceControllForm.InstallServiceButtonClick(Sender: TObject);
var
Res : integer;
AnsiString : PAnsiString;
AChar : PAnsiChar;
begin
if ServiceIsinstalled('NoteService') then
begin
Res := MessageDlg('Сервис уже установлен, желаете переустановить?'
, TMsgDlgType.mtInformation, [TMsgDlgBtn.mbYes,TMsgDlgBtn.mbNo], 0);
case Res of
mrYes :
begin
//Действия в случае, когда пользователь нажал кнопку "Yes".
if OpenDialog.Execute then
begin
// установка с exe-шника сервиса
ServiceControll.UnInstallService('NoteService');
ShellExecute( FmxHandleToHWND(Handle), 'open',PChar(OpenDialog.FileName), '-install', nil, SW_SHOWNORMAL);
end;
end;
mrNo :
begin
//Действия в случае, когда пользователь нажал кнопку "No".
ShowMessage('установка отменена');
end;
end;
end
else
begin
if OpenDialog.Execute then
begin
// установка с exe-шника сервиса
ShellExecute( FmxHandleToHWND(Handle), 'open',PChar(OpenDialog.FileName), '-install', nil, SW_SHOWNORMAL);
end;
end;
end;
procedure TServiceControllForm.PauseServiceButtonClick(Sender: TObject);
begin
if GetServiceStatusCode('NoteService') = SERVICE_RUNNING then
ServiceControll.PauseService('NoteService');
end;
procedure TServiceControllForm.SetServiceSettingsButtonClick(Sender: TObject);
var
ConnetcionString : string;
Settings : TPreferences;
begin
Settings := TPreferences.Create;
ConnetcionString := Settings.LoadSetting('SQLConnection','ConnectionString');
ConnetcionString := PromptDataSource(FmxHandleToHWND(Handle),ConnetcionString);
if ConnetcionString<>'' then begin
if CheckConnection(ConnetcionString) then
begin
ShowMessage('Подключено');
Settings.SaveSetting('SQLConnection','ConnectionString',ConnetcionString);
end
else
begin
ShowMessage('Не удалось подключиться');
end;
end;
Settings.Free;
end;
procedure TServiceControllForm.StartServiceButtonClick(Sender: TObject);
begin
if GetServiceStatusCode('NoteService') = SERVICE_STOPPED then
ServiceControll.StartService('NoteService');
if GetServiceStatusCode('NoteService') = SERVICE_PAUSED then
ServiceControll.UnPauseService('NoteService');
end;
procedure TServiceControllForm.StopServiceButtonClick(Sender: TObject);
begin
if GetServiceStatusCode('NoteService') = SERVICE_RUNNING then
ServiceControll.StopService('NoteService');
end;
procedure TServiceControllForm.Timer1Timer(Sender: TObject);
var
ServStatus : integer;
begin
ServStatus :=GetServiceStatusCode('NoteService');
EnableAllButtons;
SetServiceSettingsButton.Enabled := false;
ServiceStatusLabel.Text := 'Состояние сервиса : '+
GetServiceStatusString(ServStatus);
if ServStatus = SERVICE_STOPPED then
begin
StopServiceButton.Enabled := false;
SetServiceSettingsButton.Enabled := true;
PauseServiceButton.Enabled := false;
end;
if ServStatus = SERVICE_RUNNING then
begin
UnInstallServiceButton.Enabled := false;
InstallServiceButton.Enabled := false;
end;
if ServStatus = SERVICE_PAUSED then
begin
UnInstallServiceButton.Enabled := false;
InstallServiceButton.Enabled := false;
PauseServiceButton.Enabled := false;
StopServiceButton.Enabled := false;
end;
end;
procedure TServiceControllForm.UnInstallServiceButtonClick(Sender: TObject);
begin
if GetServiceStatusCode('NoteService') = SERVICE_STOPPED then
ServiceControll.UnInstallService('NoteService');
if GetServiceStatusCode('NoteService') = SERVICE_RUNNING then
ShowMessage('Перед удалением необходимо остановить сервис!');
end;
end.
|
{
File: UnicodeUtilities.p
Contains: Types, constants, prototypes for Unicode Utilities (Unicode input and text utils)
Version: Technology: Mac OS 9.0
Release: Universal Interfaces 3.4.2
Copyright: © 1997-2002 by Apple Computer, Inc., all rights reserved.
Bugs?: For bug reports, consult the following page on
the World Wide Web:
http://www.freepascal.org/bugs.html
}
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit UnicodeUtilities;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses MacTypes,MacLocales,TextCommon;
{$ALIGN MAC68K}
{
-------------------------------------------------------------------------------------------------
CONSTANTS & DATA STRUCTURES for UCKeyTranslate & UCKeyboardLayout ('uchr' resource)
-------------------------------------------------------------------------------------------------
}
{
-------------------------------------------------------------------------------------------------
UCKeyOutput & related stuff
The interpretation of UCKeyOutput depends on bits 15-14.
If they are 01, then bits 0-13 are an index in UCKeyStateRecordsIndex (resource-wide list).
If they are 10, then bits 0-13 are an index in UCKeySequenceDataIndex (resource-wide list),
or if UCKeySequenceDataIndex is not present or the index is beyond the end of the list,
then bits 0-15 are a single Unicode character.
Otherwise, bits 0-15 are a single Unicode character; a value of 0xFFFE-0xFFFF means no character
output.
UCKeyCharSeq is similar, but does not support indices in UCKeyStateRecordsIndex. For bits 15-14:
If they are 10, then bits 0-13 are an index in UCKeySequenceDataIndex (resource-wide list),
or if UCKeySequenceDataIndex is not present or the index is beyond the end of the list,
then bits 0-15 are a single Unicode character.
Otherwise, bits 0-15 are a single Unicode character; a value of 0xFFFE-0xFFFF means no character
output.
-------------------------------------------------------------------------------------------------
}
type
UCKeyOutput = UInt16;
UCKeyCharSeq = UInt16;
const
kUCKeyOutputStateIndexMask = $4000;
kUCKeyOutputSequenceIndexMask = $8000;
kUCKeyOutputTestForIndexMask = $C000; { test bits 14-15 }
kUCKeyOutputGetIndexMask = $3FFF; { get bits 0-13 }
{
-------------------------------------------------------------------------------------------------
UCKeyStateRecord & related stuff
The UCKeyStateRecord information is used as follows. If the current state is zero,
output stateZeroCharData and set the state to stateZeroNextState. If the current state
is non-zero and there is an entry for it in stateEntryData, then output the corresponding
charData and set the state to nextState. Otherwise, output the state terminator from
UCKeyStateTerminators for the current state (or nothing if there is no UCKeyStateTerminators
table or it has no entry for the current state), then output stateZeroCharData and set the
state to stateZeroNextState.
-------------------------------------------------------------------------------------------------
}
type
UCKeyStateRecordPtr = ^UCKeyStateRecord;
UCKeyStateRecord = record
stateZeroCharData: UCKeyCharSeq;
stateZeroNextState: UInt16;
stateEntryCount: UInt16;
stateEntryFormat: UInt16;
{ This is followed by an array of stateEntryCount elements }
{ in the specified format. Here we just show a dummy array. }
stateEntryData: array [0..0] of UInt32;
end;
{
Here are the codes for entry formats currently defined.
Each entry maps from curState to charData and nextState.
}
const
kUCKeyStateEntryTerminalFormat = $0001;
kUCKeyStateEntryRangeFormat = $0002;
{
For UCKeyStateEntryTerminal -
nextState is always 0, so we don't have a field for it
}
type
UCKeyStateEntryTerminalPtr = ^UCKeyStateEntryTerminal;
UCKeyStateEntryTerminal = record
curState: UInt16;
charData: UCKeyCharSeq;
end;
{
For UCKeyStateEntryRange -
If curState >= curStateStart and curState <= curStateStart+curStateRange,
then it matches the entry, and we transform charData and nextState as follows:
If charData < 0xFFFE, then charData += (curState-curStateStart)*deltaMultiplier
If nextState != 0, then nextState += (curState-curStateStart)*deltaMultiplier
}
UCKeyStateEntryRangePtr = ^UCKeyStateEntryRange;
UCKeyStateEntryRange = record
curStateStart: UInt16;
curStateRange: SInt8;
deltaMultiplier: SInt8;
charData: UCKeyCharSeq;
nextState: UInt16;
end;
{
-------------------------------------------------------------------------------------------------
UCKeyboardLayout & related stuff
The UCKeyboardLayout struct given here is only for the resource header. It specifies
offsets to the various subtables which each have their own structs, given below.
The keyboardTypeHeadList array selects table offsets that depend on keyboardType. The
first entry in keyboardTypeHeadList is the default entry, which will be used if the
keyboardType passed to UCKeyTranslate does not match any other entry - i.e. does not fall
within the range keyboardTypeFirst..keyboardTypeLast for some entry. The first entry
should have keyboardTypeFirst = keyboardTypeLast = 0.
-------------------------------------------------------------------------------------------------
}
UCKeyboardTypeHeaderPtr = ^UCKeyboardTypeHeader;
UCKeyboardTypeHeader = record
keyboardTypeFirst: UInt32; { first keyboardType in this entry }
keyboardTypeLast: UInt32; { last keyboardType in this entry }
keyModifiersToTableNumOffset: ByteOffset; { required }
keyToCharTableIndexOffset: ByteOffset; { required }
keyStateRecordsIndexOffset: ByteOffset; { 0 => no table }
keyStateTerminatorsOffset: ByteOffset; { 0 => no table }
keySequenceDataIndexOffset: ByteOffset; { 0 => no table }
end;
UCKeyboardLayoutPtr = ^UCKeyboardLayout;
UCKeyboardLayout = record
{ header only; other tables accessed via offsets }
keyLayoutHeaderFormat: UInt16; { =kUCKeyLayoutHeaderFormat }
keyLayoutDataVersion: UInt16; { 0x0100 = 1.0, 0x0110 = 1.1, etc. }
keyLayoutFeatureInfoOffset: ByteOffset; { may be 0 }
keyboardTypeCount: ItemCount; { Dimension for keyboardTypeHeadList[] }
keyboardTypeList: array [0..0] of UCKeyboardTypeHeader;
end;
{ ------------------------------------------------------------------------------------------------- }
UCKeyLayoutFeatureInfoPtr = ^UCKeyLayoutFeatureInfo;
UCKeyLayoutFeatureInfo = record
keyLayoutFeatureInfoFormat: UInt16; { =kUCKeyLayoutFeatureInfoFormat }
reserved: UInt16;
maxOutputStringLength: UniCharCount; { longest possible output string }
end;
{ ------------------------------------------------------------------------------------------------- }
UCKeyModifiersToTableNumPtr = ^UCKeyModifiersToTableNum;
UCKeyModifiersToTableNum = record
keyModifiersToTableNumFormat: UInt16; { =kUCKeyModifiersToTableNumFormat }
defaultTableNum: UInt16; { For modifier combos not in tableNum[] }
modifiersCount: ItemCount; { Dimension for tableNum[] }
tableNum: SInt8;
{ Then there is padding to a 4-byte boundary with bytes containing 0, if necessary. }
end;
{ ------------------------------------------------------------------------------------------------- }
UCKeyToCharTableIndexPtr = ^UCKeyToCharTableIndex;
UCKeyToCharTableIndex = record
keyToCharTableIndexFormat: UInt16; { =kUCKeyToCharTableIndexFormat }
keyToCharTableSize: UInt16; { Max keyCode (128 for ADB keyboards) }
keyToCharTableCount: ItemCount; { Dimension for keyToCharTableOffsets[] (usually 6 to 12 tables) }
keyToCharTableOffsets: array [0..0] of ByteOffset;
{ Each offset in keyToCharTableOffsets is from the beginning of the resource to a }
{ table as follows: }
{ UCKeyOutput keyToCharData[keyToCharTableSize]; }
{ These tables follow the UCKeyToCharTableIndex. }
{ Then there is padding to a 4-byte boundary with bytes containing 0, if necessary. }
end;
{ ------------------------------------------------------------------------------------------------- }
UCKeyStateRecordsIndexPtr = ^UCKeyStateRecordsIndex;
UCKeyStateRecordsIndex = record
keyStateRecordsIndexFormat: UInt16; { =kUCKeyStateRecordsIndexFormat }
keyStateRecordCount: UInt16; { Dimension for keyStateRecordOffsets[] }
keyStateRecordOffsets: array [0..0] of ByteOffset;
{ Each offset in keyStateRecordOffsets is from the beginning of the resource to a }
{ UCKeyStateRecord. These UCKeyStateRecords follow the keyStateRecordOffsets[] array. }
{ Then there is padding to a 4-byte boundary with bytes containing 0, if necessary. }
end;
{ ------------------------------------------------------------------------------------------------- }
UCKeyStateTerminatorsPtr = ^UCKeyStateTerminators;
UCKeyStateTerminators = record
keyStateTerminatorsFormat: UInt16; { =kUCKeyStateTerminatorsFormat }
keyStateTerminatorCount: UInt16; { Dimension for keyStateTerminators[] (# of nonzero states) }
keyStateTerminators: array [0..0] of UCKeyCharSeq;
{ Note: keyStateTerminators[0] is terminator for state 1, etc. }
{ Then there is padding to a 4-byte boundary with bytes containing 0, if necessary. }
end;
{ ------------------------------------------------------------------------------------------------- }
UCKeySequenceDataIndexPtr = ^UCKeySequenceDataIndex;
UCKeySequenceDataIndex = record
keySequenceDataIndexFormat: UInt16; { =kUCKeySequenceDataIndexFormat }
charSequenceCount: UInt16; { Dimension of charSequenceOffsets[] is charSequenceCount+1 }
charSequenceOffsets: array [0..0] of UInt16;
{ Each offset in charSequenceOffsets is in bytes, from the beginning of }
{ UCKeySequenceDataIndex to a sequence of UniChars; the next offset indicates the }
{ end of the sequence. The UniChar sequences follow the UCKeySequenceDataIndex. }
{ Then there is padding to a 4-byte boundary with bytes containing 0, if necessary. }
end;
{ ------------------------------------------------------------------------------------------------- }
{ Current format codes for the various tables (bits 12-15 indicate which table) }
const
kUCKeyLayoutHeaderFormat = $1002;
kUCKeyLayoutFeatureInfoFormat = $2001;
kUCKeyModifiersToTableNumFormat = $3001;
kUCKeyToCharTableIndexFormat = $4001;
kUCKeyStateRecordsIndexFormat = $5001;
kUCKeyStateTerminatorsFormat = $6001;
kUCKeySequenceDataIndexFormat = $7001;
{
-------------------------------------------------------------------------------------------------
Constants for keyAction parameter in UCKeyTranslate()
-------------------------------------------------------------------------------------------------
}
kUCKeyActionDown = 0; { key is going down }
kUCKeyActionUp = 1; { key is going up }
kUCKeyActionAutoKey = 2; { auto-key down }
kUCKeyActionDisplay = 3; { get information for key display (as in Key Caps) }
{
-------------------------------------------------------------------------------------------------
Bit assignments & masks for keyTranslateOptions parameter in UCKeyTranslate()
-------------------------------------------------------------------------------------------------
}
kUCKeyTranslateNoDeadKeysBit = 0; { Prevents setting any new dead-key states }
kUCKeyTranslateNoDeadKeysMask = $00000001;
{
-------------------------------------------------------------------------------------------------
CONSTANTS & DATA STRUCTURES for Unicode Collation
-------------------------------------------------------------------------------------------------
}
{ constant for LocaleOperationClass }
kUnicodeCollationClass = FourCharCode('ucol');
type
CollatorRef = ^SInt32; { an opaque 32-bit type }
CollatorRefPtr = ^CollatorRef; { when a var xx:CollatorRef parameter can be nil, it is changed to xx: CollatorRefPtr }
UCCollateOptions = UInt32;
const
{ Sensitivity options }
kUCCollateComposeInsensitiveMask = $00000002;
kUCCollateWidthInsensitiveMask = $00000004;
kUCCollateCaseInsensitiveMask = $00000008;
kUCCollateDiacritInsensitiveMask = $00000010; { Other general options }
kUCCollatePunctuationSignificantMask = $00008000; { Number-handling options }
kUCCollateDigitsOverrideMask = $00010000;
kUCCollateDigitsAsNumberMask = $00020000;
kUCCollateStandardOptions = $00000006;
{
Special values to specify various invariant orders for UCCompareTextNoLocale.
These values use the high 8 bits of UCCollateOptions.
}
kUCCollateTypeHFSExtended = 1;
{ These constants are used for masking and shifting the invariant order type. }
kUCCollateTypeSourceMask = $000000FF;
kUCCollateTypeShiftBits = 24;
kUCCollateTypeMask = $FF000000;
type
UCCollationValue = UInt32;
UCCollationValuePtr = ^UCCollationValue;
{
-------------------------------------------------------------------------------------------------
CONSTANTS & DATA STRUCTURES for Unicode TextBreak
-------------------------------------------------------------------------------------------------
}
{ constant for LocaleOperationClass }
const
kUnicodeTextBreakClass = FourCharCode('ubrk');
type
TextBreakLocatorRef = ^SInt32; { an opaque 32-bit type }
TextBreakLocatorRefPtr = ^TextBreakLocatorRef; { when a var xx:TextBreakLocatorRef parameter can be nil, it is changed to xx: TextBreakLocatorRefPtr }
UCTextBreakType = UInt32;
const
kUCTextBreakCharMask = $00000001;
kUCTextBreakClusterMask = $00000004;
kUCTextBreakWordMask = $00000010;
kUCTextBreakLineMask = $00000040;
type
UCTextBreakOptions = UInt32;
const
kUCTextBreakLeadingEdgeMask = $00000001;
kUCTextBreakGoBackwardsMask = $00000002;
kUCTextBreakIterateMask = $00000004;
{
-------------------------------------------------------------------------------------------------
function PROTOTYPES
-------------------------------------------------------------------------------------------------
}
{
* UCKeyTranslate()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesCoreLib 8.5 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCKeyTranslate(const (*var*) keyLayoutPtr: UCKeyboardLayout; virtualKeyCode: UInt16; keyAction: UInt16; modifierKeyState: UInt32; keyboardType: UInt32; keyTranslateOptions: OptionBits; var deadKeyState: UInt32; maxStringLength: UniCharCount; var actualStringLength: UniCharCount; unicodeString: UniCharPtr): OSStatus; external name '_UCKeyTranslate';
{ Standard collation functions }
{
* UCCreateCollator()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesLib 8.6 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCCreateCollator(locale: LocaleRef; opVariant: LocaleOperationVariant; options: UCCollateOptions; var collatorRef_: CollatorRef): OSStatus; external name '_UCCreateCollator';
{
* UCGetCollationKey()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesLib 8.6 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCGetCollationKey(collatorRef_: CollatorRef; textPtr: ConstUniCharPtr; textLength: UniCharCount; maxKeySize: ItemCount; var actualKeySize: ItemCount; collationKey: UCCollationValuePtr): OSStatus; external name '_UCGetCollationKey';
{
* UCCompareCollationKeys()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesCoreLib 8.6 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCCompareCollationKeys(key1Ptr: UCCollationValuePtr; key1Length: ItemCount; key2Ptr: UCCollationValuePtr; key2Length: ItemCount; var equivalent: boolean; var order: SInt32): OSStatus; external name '_UCCompareCollationKeys';
{
* UCCompareText()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesLib 8.6 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCCompareText(collatorRef_: CollatorRef; text1Ptr: ConstUniCharPtr; text1Length: UniCharCount; text2Ptr: ConstUniCharPtr; text2Length: UniCharCount; var equivalent: boolean; var order: SInt32): OSStatus; external name '_UCCompareText';
{
* UCDisposeCollator()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesLib 8.6 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCDisposeCollator(var collatorRef_: CollatorRef): OSStatus; external name '_UCDisposeCollator';
{ Simple collation using default locale }
{
* UCCompareTextDefault()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesLib 8.6 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCCompareTextDefault(options: UCCollateOptions; text1Ptr: ConstUniCharPtr; text1Length: UniCharCount; text2Ptr: ConstUniCharPtr; text2Length: UniCharCount; var equivalent: boolean; var order: SInt32): OSStatus; external name '_UCCompareTextDefault';
{ Simple locale-independent collation }
{
* UCCompareTextNoLocale()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesCoreLib 8.6 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCCompareTextNoLocale(options: UCCollateOptions; text1Ptr: ConstUniCharPtr; text1Length: UniCharCount; text2Ptr: ConstUniCharPtr; text2Length: UniCharCount; var equivalent: boolean; var order: SInt32): OSStatus; external name '_UCCompareTextNoLocale';
{ Standard text break (text boundary) functions }
{
* UCCreateTextBreakLocator()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesLib 9.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCCreateTextBreakLocator(locale: LocaleRef; opVariant: LocaleOperationVariant; breakTypes: UCTextBreakType; var breakRef: TextBreakLocatorRef): OSStatus; external name '_UCCreateTextBreakLocator';
{
* UCFindTextBreak()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesLib 9.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCFindTextBreak(breakRef: TextBreakLocatorRef; breakType: UCTextBreakType; options: UCTextBreakOptions; textPtr: ConstUniCharPtr; textLength: UniCharCount; startOffset: UniCharArrayOffset; var breakOffset: UniCharArrayOffset): OSStatus; external name '_UCFindTextBreak';
{
* UCDisposeTextBreakLocator()
*
* Availability:
* Non-Carbon CFM: in UnicodeUtilitiesLib 9.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function UCDisposeTextBreakLocator(var breakRef: TextBreakLocatorRef): OSStatus; external name '_UCDisposeTextBreakLocator';
{$ALIGN MAC68K}
end.
|
{ Subroutine SST_INIT (SYMBOL_LEN,PARENT_MEM)
*
* Init the translator data structures. This must be the first SST call in an
* application. SYMBOL_LEN is the maximum length of any symbol. This is used
* to configure the hash tables. PARENT_MEM is the memory context under which
* a new memory context will be created. All translator dynamic memory will be
* allocated subordinate to this new context.
}
module sst_INIT;
define sst_init;
%include 'sst2.ins.pas';
procedure sst_init ( {init translator data stuctures}
in symbol_len: sys_int_machine_t; {max length allowed for a symbol}
in out parent_mem: util_mem_context_t); {parent memory context to use}
var
m_p: util_mem_context_p_t; {scratch memory context pointer}
begin
max_symbol_len := symbol_len; {save max allowed symbol length}
sst_hash_buckets := 128; {number of buckets for new hash tables}
util_mem_context_get (parent_mem, mem_p); {create our own memory context}
mem_p^.pool_size := sst_mem_pool_size; {set size we want for our memory pools}
mem_p^.max_pool_chunk := sst_mem_pool_chunk; {max size chunk to alloc from pool}
{
* Init top level scope.
}
util_mem_context_get (mem_p^, m_p); {make mem context for top scope}
util_mem_grab ( {allocate top scope block}
sizeof(sst_scope_p^), m_p^, false, sst_scope_p);
sst_scope_p^.mem_p := m_p; {set mem context for this scope}
sst_scope_p^.parent_p := nil; {top scope has no parent}
sst_scope_p^.symbol_p := nil;
sst_scope_p^.flag_ref_used := false; {init to not flag references symbols as used}
string_hash_create ( {init input name hash table for top scope}
sst_scope_p^.hash_h, {handle to new hash table}
512, {number of buckets in top hash table}
max_symbol_len, {max length of any entry name in hash table}
sizeof(sst_symbol_p_t), {amount of user memory for hash entries}
[ string_hashcre_memdir_k, {use parent memory context directly}
string_hashcre_nodel_k], {won't need to individually deallocate entries}
sst_scope_p^.mem_p^); {parent memory context for hash table}
string_hash_create ( {init output name hash table for top scope}
sst_scope_p^.hash_out_h, {handle to new hash table}
512, {number of buckets in top hash table}
max_symbol_len, {max length of any entry name in hash table}
sizeof(sst_symbol_p_t), {amount of user memory for hash entries}
[ string_hashcre_memdir_k, {use parent memory context directly}
string_hashcre_nodel_k], {won't need to individually deallocate entries}
sst_scope_p^.mem_p^); {parent memory context for hash table}
sst_names_p := sst_scope_p; {init lowest name space to same as curr scope}
sst_scope_root_p := sst_scope_p; {set pointer to root scope}
sst_align := sst_align_natural_k; {init current alignment rule}
sst_opc_first_p := nil; {init to no opcodes in opcodes list}
sst_opc_p := nil;
sst_opc_next_pp := addr(sst_opc_first_p);
{
* Init the front end call table to "default" routines.
}
sst_r.doit := nil;
{
* Init back end call table to "default" routines.
}
sst_w.allow_break := addr(sst_out_allow_break);
sst_w.append := addr(sst_out_append);
sst_w.appendn := addr(sst_out_appendn);
sst_w.appends := addr(sst_out_appends);
sst_w.append_sym_name := addr(sst_out_append_sym_name);
sst_w.blank_line := addr(sst_out_blank_line);
sst_w.break := addr(sst_out_break);
sst_w.comment_end := addr(sst_out_comment_end);
sst_w.comment_set := addr(sst_out_comment_set);
sst_w.comment_start := addr(sst_out_comment_start);
sst_w.delimit := addr(sst_out_delimit);
sst_w.doit := nil;
sst_w.indent := addr(sst_out_indent);
sst_w.line_close := addr(sst_out_line_close);
sst_w.line_insert := addr(sst_out_line_insert);
sst_w.line_new := addr(sst_out_line_new);
sst_w.line_new_cont := addr(sst_out_line_new_cont);
sst_w.name := addr(sst_out_name);
sst_w.name_sym := addr(sst_out_name_sym);
sst_w.notify_src_range := addr(sst_out_notify_src_range);
sst_w.tab_indent := addr(sst_out_tab_indent);
sst_w.undent := addr(sst_out_undent);
sst_w.undent_all := addr(sst_out_undent_all);
sst_w.write := addr(sst_out_write);
{
* Init state controlling writing characters to internal description of
* output file.
}
util_mem_context_get (mem_p^, sst_out.mem_p); {make mem context for output lines}
sst_out.first_str_p := nil;
sst_out.wrap_len := 60;
sst_out.indent_size := 2;
sst_out.dyn_p := addr(sst_out_dyn);
sst_out.dyn_p^.str_p := nil;
sst_out.dyn_p^.indent_chars := 0;
sst_out.dyn_p^.indent_level := 0;
sst_out.dyn_p^.break_len := 0;
sst_out.dyn_p^.break_start := 0;
sst_out.dyn_p^.wpos := sst_wpos_before_k;
sst_out.dyn_p^.comm.max := sizeof(sst_out.dyn_p^.comm.str);
sst_out.dyn_p^.comm.len := 0;
sst_out.dyn_p^.commented_pos := 0;
sst_out.comm_start.max := sizeof(sst_out.comm_start.str);
sst_out.comm_start.len := 0;
sst_out.comm_end.max := sizeof(sst_out.comm_end.str);
sst_out.comm_end.len := 0;
sst_out.comm_pos := 40;
{
* Init the front/back end stack. We set up this stack, it is exclusively for
* use by the front and back ends.
}
util_stack_alloc (mem_p^, sst_stack); {create the stack}
{
* Init other stuff in the common block.
}
sst_dtype_none.symbol_p := nil;
sst_dtype_none.dtype := sst_dtype_undef_k;
sst_dtype_none.bits_min := 0;
sst_dtype_none.align_nat := 1;
sst_dtype_none.align := 1;
sst_dtype_none.size_used := 0;
sst_dtype_none.size_align := 0;
end;
|
unit DragDrop;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
interface
uses
Classes, Windows, Messages, ShellAPI;
// Drag&Drop Target -----------------------------------------------------------------
type
TFileDroppedEvent = procedure( Sender : TObject; const DropPoint : TPoint; const FileName : string ) of object;
TFileListDroppedEvent = procedure( Sender : TObject; const DropPoint : TPoint; const Files : TStringList ) of object;
type
TDropTarget =
class
protected
fHandle : HWND;
fOnFileListDropped : TFileListDroppedEvent;
fOnFileDropped : TFileDroppedEvent;
fOldAcceptFiles : boolean;
fWndProcData : integer;
fAcceptOnlyOneFile : boolean;
public
property Handle : HWND read fHandle;
public
property OnFileDropped : TFileDroppedEvent read fOnFileDropped write fOnFileDropped;
property OnFileListDropped : TFileListDroppedEvent read fOnFileListDropped write fOnFileListDropped;
property AcceptOnlyOneFile : boolean read fAcceptOnlyOneFile write fAcceptOnlyOneFile;
public
constructor Create( WinHandle : HWND );
destructor Destroy; override;
protected
procedure HandleDropFilesMessage( DropHandle : HDROP );
end;
// Drag&Drop Source -----------------------------------------------------------------
function DropFile( WinHandle : HWND; const FileName : string ) : boolean;
// Low level routines
function DropCreate : HDROP;
function DropAddFile( var Handle : HDROP; FileName : pchar ) : boolean;
function DragCreateFiles( const aMousePos : TPoint; aInNonClientArea : BOOL; aUnicode : BOOL ): HDROP;
function DragAppendFile( DropHandle : HDROP; PathName : pointer ): HDROP; cdecl;
implementation
uses
WinUtils;
var
DropTargets : TList = nil;
function DragDropWndProc( WinHandle : HWND; Msg : integer; wPar : WPARAM; lPar : LPARAM ) : LRESULT; stdcall;
var
i : integer;
begin
try
i := 0;
while (i < DropTargets.Count) and (TDropTarget(DropTargets[i]).Handle <> WinHandle) do
inc( i );
with TDropTarget(DropTargets[i]) do // This will raise an exception if indx not found
if Msg = WM_DROPFILES
then
begin
HandleDropFilesMessage( wPar );
Result := 0;
end
else Result := CallWindowProc( PrevWndProc( fWndProcData ), WinHandle, Msg, wPar, lPar );
except
Result := 0;
end;
end;
constructor TDropTarget.Create( WinHandle : HWND );
begin
inherited Create;
fHandle := WinHandle;
fWndProcData := ChangeWndProc( fHandle, @DragDropWndProc );
if not Assigned( DropTargets )
then DropTargets := TList.Create;
DropTargets.Add( Self );
fOldAcceptFiles := WindowIsDropTarget( fHandle );
if not fOldAcceptFiles
then DragAcceptFiles( fHandle, true );
end;
destructor TDropTarget.Destroy;
begin
if Assigned( DropTargets )
then
begin
if not fOldAcceptFiles
then DragAcceptFiles( fHandle, false );
RestoreWndProc( fHandle, fWndProcData );
DropTargets.Remove( Self );
DropTargets.Pack;
if DropTargets.Count = 0
then
begin
DropTargets.Free;
DropTargets := nil;
end;
end;
inherited;
end;
procedure TDropTarget.HandleDropFilesMessage( DropHandle : HDROP );
var
i : integer;
DropPoint : TPoint;
DropCount : integer;
DroppedFiles : TStringList;
Filename : string;
FilenameSize : integer;
begin
DroppedFiles := TStringList.Create;
DragQueryPoint( DropHandle, DropPoint );
if AcceptOnlyOneFile
then DropCount := 1
else DropCount := DragQueryFile( DropHandle, -1, nil, 0 );
for i := 0 to DropCount - 1 do
begin
FileNameSize := DragQueryFile( DropHandle, i, nil, 0 );
SetLength( Filename, FilenameSize );
DragQueryFile( DropHandle, i, pchar(Filename), FilenameSize + 1 );
DroppedFiles.Add( Filename );
end;
if Assigned( OnFileListDropped )
then OnFileListDropped( Self, DropPoint, DroppedFiles );
if Assigned( OnFileDropped )
then
for i := 0 to DropCount - 1 do
OnFileDropped( Self, DropPoint, DroppedFiles[i] );
DragFinish( DropHandle );
DroppedFiles.Free;
end;
// Drag&Drop Source -----------------------------------------------------------------
type
PDropFileStruct = ^TDropFileStruct;
TDropFileStruct =
packed record
Size : word;
MousePos : TPoint;
InNonClientArea : BOOL;
Unicode : BOOL;
end;
function DropFile( WinHandle : HWND; const FileName : string ) : boolean;
var
DropHandle : HDROP;
begin
try
DropHandle := DropCreate;
if DropAddFile( DropHandle, pchar(FileName) )
then
begin
Result := true;
PostMessage( WinHandle, WM_DROPFILES, DropHandle, 0 );
end
else Result := false;
except
Result := false;
end;
end;
// Low level routines
function DropCreate : HDROP;
begin
Result := DragCreateFiles( Point( 0, 0 ), false, false );
end;
function DropAddFile( var Handle : HDROP; FileName : pchar ) : boolean;
var
DropHandle : HDROP;
begin
DropHandle := DragAppendFile( Handle, FileName );
if DropHandle <> 0
then
begin
Result := true;
Handle := DropHandle;
end
else Result := false;
end;
//
function DragCreateFiles( const aMousePos : TPoint; aInNonClientArea : BOOL; aUnicode : BOOL ): HDROP;
var
DropFileStruct : PDropFileStruct;
begin
// Allocate dynamic memory for the DROPFILESTRUCT data
// structure and for the extra zero-character identifying
// that there are no pathnames in the block yet.
if aUnicode
then Result := GlobalAlloc( GMEM_MOVEABLE or GMEM_ZEROINIT, sizeof(TDropFileStruct) + sizeof(WideChar) )
else Result := GlobalAlloc( GMEM_MOVEABLE or GMEM_ZEROINIT, sizeof(TDropFileStruct) + sizeof(AnsiChar) );
if Result <> 0
then
begin
// Lock block and initialize the data members
DropFileStruct := GlobalLock( Result );
with DropFileStruct^ do
begin
Size := sizeof( TDropFileStruct );
MousePos := aMousePos;
InNonClientArea := aInNonClientArea;
Unicode := aUnicode;
end;
GlobalUnlock( Result );
end;
end;
function DragAppendFile( DropHandle : HDROP; PathName : pointer ): HDROP;
var
DropFileStruct : PDropFileStruct;
PathNameAnsi : PAnsiChar absolute PathName;
PathNameUnicode : PWideChar absolute PathName;
PathAnsi : PAnsiChar;
PathUnicode : PWideChar;
OffsetOfNewPathname : integer;
PathSize : integer;
begin
DropFileStruct := GlobalLock( DropHandle );
// Point to first pathname in list
PathAnsi := PAnsiChar(DropFileStruct) + sizeof(TDropFileStruct);
PathUnicode := pointer(PathAnsi);
if DropFileStruct.Unicode
then
begin
// Search for a pathname where 1st char is a zero-char
while PathUnicode[0] <> #0 do // While the 1st char is non-zero
begin
while PathUnicode[0] <> #0 do // Find end of current path
inc( PathUnicode );
inc( PathUnicode ); // Skip over the zero-char
end;
// Get the offset from the beginning of the block
// where the new pathname should go
OffsetOfNewPathname := PAnsiChar(PathUnicode) - PAnsiChar(DropFileStruct);
// Get the number of bytes needed for the new pathname,
// it's terminating zero-char, and the zero-length
// pathname that marks the end of the list of pathnames
PathSize := sizeof(WideChar) * (lstrlenW(PathnameUnicode) + 2);
end
else
begin
// Search for a pathname where 1st char is a zero-char
while PathAnsi[0] <> #0 do // While the 1st char is non-zero
begin
while PathAnsi[0] <> #0 do // Find end of current path
inc( PathAnsi );
inc( PathAnsi ); // Skip over the zero-char
end;
// Get the offset from the beginning of the block
// where the new pathname should go
OffsetOfNewPathname := PAnsiChar(PathAnsi) - PAnsiChar(DropFileStruct);
// Get the number of bytes needed for the new pathname,
// it's terminating zero-char, and the zero-length
// pathname that marks the end of the list of pathnames
PathSize := sizeof(AnsiChar) * (lstrlenA(PathnameAnsi) + 2);
end;
GlobalUnlock( DropHandle );
// Increase block size to accommodate new pathname
Result := GlobalRealloc( DropHandle, PathSize + OffsetOfNewPathname, GMEM_MOVEABLE or GMEM_ZEROINIT );
if Result <> 0
then
begin
DropFileStruct := GlobalLock( Result );
with DropFileStruct^ do
begin
// Append the pathname to the end of the block
if Unicode
then Move( PathnameUnicode[0], PAnsiChar(DropFileStruct)[OffsetOfNewPathname], lstrlenW(PathnameUnicode) * sizeof(WideChar) )
else Move( PathnameAnsi[0], PAnsiChar(DropFileStruct)[OffsetOfNewPathname], lstrlenA(PathnameAnsi) * sizeof(AnsiChar) );
GlobalUnlock( Result );
end;
end;
end;
end.
|
unit TerritoryActionsUnit;
interface
uses
SysUtils, BaseActionUnit,
TerritoryUnit, NullableBasicTypesUnit, TerritoryContourUnit;
type
TTerritoryActions = class(TBaseAction)
public
/// <summary>
/// Create a new territory
/// </summary>
function Add(Name: String; Color: String; Contour: TTerritoryContour;
out ErrorString: String): NullableString; overload;
// todo 5: если даже отправлять список адресов на сервер, то в ответе он обнуляется
function Add(Name: String; Color: String; Contour: TTerritoryContour;
AddressIds: TArray<integer>; out ErrorString: String): NullableString; overload;
/// <summary>
/// UPDATE a specified Territory
/// </summary>
function Update(Territory: TTerritory; out ErrorString: String): TTerritory;
/// <summary>
/// DELETE a specified Territory.
/// </summary>
function Remove(TerritoryId: String; out ErrorString: String): boolean; overload;
function Remove(TerritoryIds: TArray<String>; out ErrorString: String): boolean; overload;
/// <summary>
/// GET all of the Territories defined by a user.
/// </summary>
function GetList(out ErrorString: String): TTerritoryList;
/// <summary>
/// Get a specified Territory by ID.
/// </summary>
function Get(TerritoryId: String; GetEnclosedAddresses: boolean;
out ErrorString: String): TTerritory;
end;
implementation
uses
SettingsUnit, StatusResponseUnit, GenericParametersUnit, GetTerritoriesResponseUnit,
UpdateTerritoryRequestUnit;
function TTerritoryActions.Add(Name: String; Color: String;
Contour: TTerritoryContour; out ErrorString: String): NullableString;
var
Response: TTerritory;
Parameters: TTerritory;
begin
Result := NullableString.Null;
Parameters := TTerritory.Create(Name, Color, Contour);
try
Response := FConnection.Post(TSettings.EndPoints.Territory, Parameters,
TTerritory, ErrorString) as TTerritory;
try
if (Response <> nil) then
Result := Response.Id
else
ErrorString := 'Territory not added';
finally
FreeAndNil(Response);
end;
finally
FreeAndNil(Parameters);
end;
end;
function TTerritoryActions.Add(Name, Color: String; Contour: TTerritoryContour;
AddressIds: TArray<integer>; out ErrorString: String): NullableString;
var
Response: TTerritory;
Parameters: TTerritory;
i: integer;
begin
Result := NullableString.Null;
Parameters := TTerritory.Create(Name, Color, Contour);
try
for i := 0 to High(AddressIds) do
Parameters.AddAddressId(AddressIds[i]);
Response := FConnection.Post(TSettings.EndPoints.Territory, Parameters,
TTerritory, ErrorString) as TTerritory;
try
if (Response <> nil) then
Result := Response.Id
else
ErrorString := 'Territory not added';
finally
FreeAndNil(Response);
end;
finally
FreeAndNil(Parameters);
end;
end;
// {"territory_name":"Circle Territory","territory_color":"ff0000","addresses":[{"value":123},{"value":789}],"territory":{"data":["37.5697528227865,-77.4783325195313","5000"],"type":"circle"}}>
function TTerritoryActions.Get(TerritoryId: String; GetEnclosedAddresses: boolean;
out ErrorString: String): TTerritory;
var
Request: TGenericParameters;
begin
Request := TGenericParameters.Create();
try
Request.AddParameter('territory_id', TerritoryId);
if GetEnclosedAddresses then
Request.AddParameter('addresses', '1');
Result := FConnection.Get(TSettings.EndPoints.Territory, Request,
TTerritory, ErrorString) as TTerritory;
if (Result = nil) and (ErrorString = EmptyStr) then
ErrorString := 'Get Territory fault';
finally
FreeAndNil(Request);
end;
end;
function TTerritoryActions.GetList(out ErrorString: String): TTerritoryList;
var
Response: TGetTerritoriesResponse;
Parameters: TGenericParameters;
i: integer;
begin
Result := TTerritoryList.Create;
Parameters := TGenericParameters.Create();
try
Response := FConnection.Get(TSettings.EndPoints.Territory, Parameters,
TGetTerritoriesResponse, ErrorString) as TGetTerritoriesResponse;
try
if (Response <> nil) then
begin
for i := 0 to Length(Response.Territories) - 1 do
Result.Add(Response.Territories[i]);
end;
finally
FreeAndNil(Response);
end;
finally
FreeAndNil(Parameters);
end;
end;
function TTerritoryActions.Remove(TerritoryIds: TArray<String>;
out ErrorString: String): boolean;
var
Query: TGenericParameters;
i: integer;
AErrorString: String;
Response: TStatusResponse;
begin
Result := True;
ErrorString := EmptyStr;
Query := TGenericParameters.Create;
try
for i := 0 to High(TerritoryIds) do
begin
Query.ReplaceParameter('territory_id', TerritoryIds[i]);
Response := FConnection.Delete(TSettings.EndPoints.Territory, Query,
TStatusResponse, AErrorString) as TStatusResponse;
try
Result := Result and (Response <> nil) and (Response.Status);
if (AErrorString <> EmptyStr) then
ErrorString := ErrorString + '; ' + AErrorString;
finally
FreeAndNil(Response);
end;
end;
finally
FreeAndNil(Query);
end;
end;
function TTerritoryActions.Remove(TerritoryId: String;
out ErrorString: String): boolean;
begin
Result := Remove([TerritoryId], ErrorString);
end;
function TTerritoryActions.Update(Territory: TTerritory;
out ErrorString: String): TTerritory;
var
Request: TUpdateTerritoryRequest;
begin
Request := TUpdateTerritoryRequest.Create(Territory);
try
Result := FConnection.Put(TSettings.EndPoints.Territory, Request,
TTerritory, ErrorString) as TTerritory;
finally
FreeAndNil(Request);
end;
end;
end.
|
unit MoveControl;
interface
uses
Math, TypeControl, ActionTypeControl, VehicleTypeControl;
type
TMove = class
private
FAction: TActionType;
FGroup: LongInt;
FLeft: Double;
FTop: Double;
FRight: Double;
FBottom: Double;
FX: Double;
FY: Double;
FAngle: Double;
FFactor: Double;
FMaxSpeed: Double;
FMaxAngularSpeed: Double;
FVehicleType: TVehicleType;
FFacilityId: Int64;
FVehicleId: Int64;
public
constructor Create;
function GetAction: TActionType;
procedure SetAction(action: TActionType);
property Action: TActionType read GetAction write SetAction;
function GetGroup: LongInt;
procedure SetGroup(group: LongInt);
property Group: LongInt read GetGroup write SetGroup;
function GetLeft: Double;
procedure SetLeft(left: Double);
property Left: Double read GetLeft write SetLeft;
function GetTop: Double;
procedure SetTop(top: Double);
property Top: Double read GetTop write SetTop;
function GetRight: Double;
procedure SetRight(right: Double);
property Right: Double read GetRight write SetRight;
function GetBottom: Double;
procedure SetBottom(bottom: Double);
property Bottom: Double read GetBottom write SetBottom;
function GetX: Double;
procedure SetX(x: Double);
property X: Double read GetX write SetX;
function GetY: Double;
procedure SetY(y: Double);
property Y: Double read GetY write SetY;
function GetAngle: Double;
procedure SetAngle(angle: Double);
property Angle: Double read GetAngle write SetAngle;
function GetFactor: Double;
procedure SetFactor(factor: Double);
property Factor: Double read GetFactor write SetFactor;
function GetMaxSpeed: Double;
procedure SetMaxSpeed(maxSpeed: Double);
property MaxSpeed: Double read GetMaxSpeed write SetMaxSpeed;
function GetMaxAngularSpeed: Double;
procedure SetMaxAngularSpeed(maxAngularSpeed: Double);
property MaxAngularSpeed: Double read GetMaxAngularSpeed write SetMaxAngularSpeed;
function GetVehicleType: TVehicleType;
procedure SetVehicleType(vehicleType: TVehicleType);
property VehicleType: TVehicleType read GetVehicleType write SetVehicleType;
function GetFacilityId: Int64;
procedure SetFacilityId(facilityId: Int64);
property FacilityId: Int64 read GetFacilityId write SetFacilityId;
function GetVehicleId: Int64;
procedure SetVehicleId(vehicleId: Int64);
property VehicleId: Int64 read GetVehicleId write SetVehicleId;
destructor Destroy; override;
end;
TMoveArray = array of TMove;
implementation
constructor TMove.Create;
begin
FAction := _ACTION_UNKNOWN_;
FGroup := 0;
FLeft := 0.0;
FTop := 0.0;
FRight := 0.0;
FBottom := 0.0;
FX := 0.0;
FY := 0.0;
FAngle := 0.0;
FFactor := 0.0;
FMaxSpeed := 0.0;
FMaxAngularSpeed := 0.0;
FVehicleType := _VEHICLE_UNKNOWN_;
FFacilityId := -1;
FVehicleId := -1;
end;
function TMove.GetAction: TActionType;
begin
result := FAction;
end;
procedure TMove.SetAction(action: TActionType);
begin
FAction := action;
end;
function TMove.GetGroup: LongInt;
begin
result := FGroup;
end;
procedure TMove.SetGroup(group: LongInt);
begin
FGroup := group;
end;
function TMove.GetLeft: Double;
begin
result := FLeft;
end;
procedure TMove.SetLeft(left: Double);
begin
FLeft := left;
end;
function TMove.GetTop: Double;
begin
result := FTop;
end;
procedure TMove.SetTop(top: Double);
begin
FTop := top;
end;
function TMove.GetRight: Double;
begin
result := FRight;
end;
procedure TMove.SetRight(right: Double);
begin
FRight := right;
end;
function TMove.GetBottom: Double;
begin
result := FBottom;
end;
procedure TMove.SetBottom(bottom: Double);
begin
FBottom := bottom;
end;
function TMove.GetX: Double;
begin
result := FX;
end;
procedure TMove.SetX(x: Double);
begin
FX := x;
end;
function TMove.GetY: Double;
begin
result := FY;
end;
procedure TMove.SetY(y: Double);
begin
FY := y;
end;
function TMove.GetAngle: Double;
begin
result := FAngle;
end;
procedure TMove.SetAngle(angle: Double);
begin
FAngle := angle;
end;
function TMove.GetFactor: Double;
begin
result := FFactor;
end;
procedure TMove.SetFactor(factor: Double);
begin
FFactor := factor;
end;
function TMove.GetMaxSpeed: Double;
begin
result := FMaxSpeed;
end;
procedure TMove.SetMaxSpeed(maxSpeed: Double);
begin
FMaxSpeed := maxSpeed;
end;
function TMove.GetMaxAngularSpeed: Double;
begin
result := FMaxAngularSpeed;
end;
procedure TMove.SetMaxAngularSpeed(maxAngularSpeed: Double);
begin
FMaxAngularSpeed := maxAngularSpeed;
end;
function TMove.GetVehicleType: TVehicleType;
begin
result := FVehicleType;
end;
procedure TMove.SetVehicleType(vehicleType: TVehicleType);
begin
FVehicleType := vehicleType;
end;
function TMove.GetFacilityId: Int64;
begin
result := FFacilityId;
end;
procedure TMove.SetFacilityId(facilityId: Int64);
begin
FFacilityId := facilityId;
end;
function TMove.GetVehicleId: Int64;
begin
result := FVehicleId;
end;
procedure TMove.SetVehicleId(vehicleId: Int64);
begin
FVehicleId := vehicleId;
end;
destructor TMove.Destroy;
begin
inherited;
end;
end.
|
unit IngDoc;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGrids, ComCtrls, ExtCtrls, Db, DBTables, DBActns, ActnList,
Menus, ImgList, ToolWin, DateUtils, StdCtrls, Wwdbigrd, Wwdbgrid,
JvMemTable;
type
TFIngDoc = class(TForm)
ToolBar1: TToolBar;
MainMenu1: TMainMenu;
PopupMenu1: TPopupMenu;
ImageList1: TImageList;
ActionList1: TActionList;
Ventana1: TMenuItem;
Salir1: TMenuItem;
Cancel1: TDataSetCancel;
Delete1: TDataSetDelete;
Edit1: TDataSetEdit;
First1: TDataSetFirst;
Insert1: TDataSetInsert;
Last1: TDataSetLast;
Next1: TDataSetNext;
Post1: TDataSetPost;
Prior1: TDataSetPrior;
Refresh1: TDataSetRefresh;
DataSource1: TDataSource;
Panel1: TPanel;
StatusBar1: TStatusBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ToolButton9: TToolButton;
Editar1: TMenuItem;
Primero1: TMenuItem;
Anterior1: TMenuItem;
Siguiente1: TMenuItem;
Ultimo1: TMenuItem;
Anular1: TMenuItem;
N1: TMenuItem;
Agregar1: TMenuItem;
Borrar1: TMenuItem;
Anular2: TMenuItem;
Grabar1: TMenuItem;
Anular3: TMenuItem;
N2: TMenuItem;
Actualiza1: TMenuItem;
Ayuda1: TMenuItem;
Informacion1: TMenuItem;
Panel2: TPanel;
Label1: TLabel;
Total: TLabel;
ToolButton7: TToolButton;
wwDBGrid1: TwwDBGrid;
ToolButton8: TToolButton;
ToolButton10: TToolButton;
Table1: TJvMemoryTable;
Table1vencto: TDateField;
Table1Importe: TFloatField;
Table1PesDol: TBooleanField;
Table1Coef: TFloatField;
Table1Saldo: TFloatField;
Table1FIRMANTE: TStringField;
procedure Salir1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Table1BeforePost(DataSet: TDataSet);
procedure Table1CalcFields(DataSet: TDataSet);
procedure Table1NewRecord(DataSet: TDataSet);
procedure Table1BeforeEdit(DataSet: TDataSet);
procedure Table1BeforeCancel(DataSet: TDataSet);
procedure Table1BeforeDelete(DataSet: TDataSet);
procedure DBGrid1Exit(Sender: TObject);
procedure Table1AfterPost(DataSet: TDataSet);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ToolButton10Click(Sender: TObject);
private
{ Private declarations }
FPesDol: boolean;
nVieVal: double;
public
{ Public declarations }
nSaldo: double;
procedure EnHint( Sender: TObject );
end;
var
FIngDoc: TFIngDoc;
implementation
{$R *.DFM}
procedure TFIngDoc.Salir1Click(Sender: TObject);
begin
Close;
end;
procedure TFIngDoc.FormCreate(Sender: TObject);
begin
FPesDol := true;
Table1.Open;
end;
procedure TFIngDoc.EnHint(Sender: TObject);
begin
StatusBar1.SimpleText := Application.Hint;
end;
procedure TFIngDoc.Table1BeforePost(DataSet: TDataSet);
begin
if ( Table1VENCTO.value = 0) then
raise exception.create( 'Por favor, ingrese un vencimiento valido' );
if ( Table1IMPORTE.value <= 0 ) then
raise exception.create( 'Por favor, ingrese importe de documento' );
nSaldo := nSaldo + ( Table1IMPORTE.value * Table1COEF.value ) - nVieVal;
nVieVal := 0;
Total.Caption := format( '%12.2m', [ nSaldo ] );
end;
procedure TFIngDoc.Table1CalcFields(DataSet: TDataSet);
begin
Table1SALDO.value := Table1IMPORTE.value * Table1COEF.value;
end;
procedure TFIngDoc.Table1NewRecord(DataSet: TDataSet);
begin
Table1PESDOL.value := FPesDol;
Table1COEF.value := 1;
Table1VENCTO.value := date;
nVieVal := 0;
end;
procedure TFIngDoc.Table1BeforeEdit(DataSet: TDataSet);
begin
nVieVal := Table1SALDO.value * Table1COEF.value;
end;
procedure TFIngDoc.Table1BeforeCancel(DataSet: TDataSet);
begin
nVieVal := 0;
end;
procedure TFIngDoc.Table1BeforeDelete(DataSet: TDataSet);
begin
if nVieVal > 0 then
nSaldo := nSaldo - nVieVal
else
nSaldo := nSaldo - ( Table1SALDO.value * Table1COEF.value );
nVieVal := 0;
Total.Caption := format( '%12.2m', [ nSaldo ] );
end;
procedure TFIngDoc.DBGrid1Exit(Sender: TObject);
begin
try
if Table1.state in [ dsEdit, dsInsert ] then
Table1.post;
except
Table1.cancel;
end;
end;
procedure TFIngDoc.Table1AfterPost(DataSet: TDataSet);
begin
FPesDol := Table1PESDOL.value;
end;
procedure TFIngDoc.FormClose(Sender: TObject; var Action: TCloseAction);
begin
DbGrid1Exit( Sender );
end;
procedure TFIngDoc.ToolButton10Click(Sender: TObject);
begin
Close;
end;
end.
|
unit QueryCardInterfaces;
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Search\QueryCardInterfaces.pas"
// Стереотип: "ControllerInterfaces"
// Элемент модели: "QueryCardInterfaces" MUID: (4AA5503000D7)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin)}
uses
l3IntfUses
, SearchUnit
{$If NOT Defined(NoVCM)}
, vcmInterfaces
{$IfEnd} // NOT Defined(NoVCM)
, SearchInterfaces
, SimpleListInterfaces
, l3InternalInterfaces
, l3TreeInterfaces
, SearchDomainInterfaces
{$If NOT Defined(NoVCM)}
, vcmControllers
{$IfEnd} // NOT Defined(NoVCM)
;
type
IdeQuery = IQuery;
{* Данные для инициализации форм поиска }
IdsQuery = interface(IvcmViewAreaController)
{* БОС для карточек запроса }
['{51C5A41E-41B2-463E-8671-275D172E3B48}']
function pm_GetQuery: IdeQuery;
function pm_GetIsQuerySaved: Boolean;
procedure pm_SetIsQuerySaved(aValue: Boolean);
property Query: IdeQuery
read pm_GetQuery;
property IsQuerySaved: Boolean
read pm_GetIsQuerySaved
write pm_SetIsQuerySaved;
end;//IdsQuery
IdsSaveLoad = interface(IvcmViewAreaController)
{* Бизнес объект контейнера карточки поиска }
['{E5584C58-C6DF-42D0-B1AE-ACB317071F37}']
end;//IdsSaveLoad
IsdsAttributeSelect = interface(IvcmUseCaseController)
{* Форма выбора реквизитов }
['{DE5652A0-CBAC-4E05-863F-16A1F094E89B}']
function pm_GetSearch: IdeSearch;
property Search: IdeSearch
read pm_GetSearch;
{* информация для заполнения дерева реквизита }
end;//IsdsAttributeSelect
IdsTreeAttributeFirstLevel = interface(IdsSituation)
{* Бизнес объекта формы "enTreeAttributeFirstLevel" }
['{5995C2CA-E6BD-4FB7-A029-94E0AB2A037C}']
end;//IdsTreeAttributeFirstLevel
IsdsSituation = interface(IsdsAttributeSelect)
['{53453074-B221-4E0D-8FB1-538D5C3A930D}']
function pm_GetDsFilters: IdsFilters;
function pm_GetDsTreeAttributeFirstLevel: IdsTreeAttributeFirstLevel;
function pm_GetDsSaveLoad: IdsSaveLoad;
function pm_GetDsSelectedAttributes: IdsSelectedAttributes;
function pm_GetDsTreeAttributeSelect: IdsTreeAttributeSelect;
function pm_GetDsAttributeSelect: IdsAttributeSelect;
function As_IucpFilters: IucpFilters;
{* Метод приведения нашего интерфейса к IucpFilters }
function As_IbsCurrentChangedListener: IbsCurrentChangedListener;
{* Метод приведения нашего интерфейса к IbsCurrentChangedListener }
function As_IbsSelectedAttributes: IbsSelectedAttributes;
{* Метод приведения нашего интерфейса к IbsSelectedAttributes }
property dsFilters: IdsFilters
read pm_GetDsFilters;
{* БОС формы фильтры }
property dsTreeAttributeFirstLevel: IdsTreeAttributeFirstLevel
read pm_GetDsTreeAttributeFirstLevel;
{* БОС формы "Ситуации первого уровня" }
property dsSaveLoad: IdsSaveLoad
read pm_GetDsSaveLoad;
{* БОС формы контейнер карточек запроса }
property dsSelectedAttributes: IdsSelectedAttributes
read pm_GetDsSelectedAttributes;
{* БОС формы выбранные атрибуты }
property dsTreeAttributeSelect: IdsTreeAttributeSelect
read pm_GetDsTreeAttributeSelect;
{* БОС формы выбора атрибутов }
property dsAttributeSelect: IdsAttributeSelect
read pm_GetDsAttributeSelect;
{* Бизнес-объект формы cfAttributeSelect }
end;//IsdsSituation
TnsFilterForm = (
{* Типы карточек используемых при редактировании фильтров }
ns_ffAttributeSearch
{* ППР 6.х }
, ns_ffPublishSource
{* ППиО }
, ns_ffSituation
{* ППС }
, ns_ffOldSituation
{* старая карточка ППС }
, ns_ffBaseSearch
{* Базовый поиск }
, ns_ffInpharmSearch
);//TnsFilterForm
TnsSearchListType = (
{* Типы используемые для получения списка в nsSearchManager }
ns_sltWithoutClass
, ns_sltWithoutKey
, ns_sltWithoutInluded
);//TnsSearchListType
{$IfEnd} // NOT Defined(Admin)
implementation
{$If NOT Defined(Admin)}
uses
l3ImplUses
;
{$IfEnd} // NOT Defined(Admin)
end.
|
{
$Project$
$Workfile$
$Revision: 1.3 $
$DateUTC$
$Id: IdHMAC.pas,v 1.3 2015/06/16 12:31:45 lukyanets Exp $
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log: IdHMAC.pas,v $
Revision 1.3 2015/06/16 12:31:45 lukyanets
Новый Indy 10
}
{
HMAC specification on the NIST website
http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf
}
unit IdHMAC;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFIPS,
IdGlobal, IdHash;
type
TIdHMACKeyBuilder = class(TObject)
public
class function Key(const ASize: Integer) : TIdBytes;
class function IV(const ASize: Integer) : TIdBytes;
end;
TIdHMAC = class
protected
FHashSize: Integer; // n bytes
FBlockSize: Integer; // n bytes
FKey: TIdBytes;
FHash: TIdHash;
FHashName: string;
procedure InitHash; virtual; abstract;
procedure InitKey;
procedure SetHashVars; virtual; abstract;
function HashValueNative(const ABuffer: TIdBytes; const ATruncateTo: Integer = -1) : TIdBytes; // for now, supply in bytes
function HashValueIntF(const ABuffer: TIdBytes; const ATruncateTo: Integer = -1) : TIdBytes; // for now, supply in bytes
function IsIntFAvail : Boolean; virtual;
function InitIntFInst(const AKey : TIdBytes) : TIdHMACIntCtx; virtual; abstract;
public
constructor Create; virtual;
destructor Destroy; override;
function HashValue(const ABuffer: TIdBytes; const ATruncateTo: Integer = -1) : TIdBytes; // for now, supply in bytes
property HashSize: Integer read FHashSize;
property BlockSize: Integer read FBlockSize;
property HashName: string read FHashName;
property Key: TIdBytes read FKey write FKey;
end;
implementation
uses
SysUtils;
{ TIdHMACKeyBuilder }
class function TIdHMACKeyBuilder.Key(const ASize: Integer): TIdBytes;
var
I: Integer;
begin
SetLength(Result, ASize);
for I := Low(Result) to High(Result) do begin
Result[I] := Byte(Random(255));
end;
end;
class function TIdHMACKeyBuilder.IV(const ASize: Integer): TIdBytes;
var
I: Integer;
begin
SetLength(Result, ASize);
for I := Low(Result) to High(Result) do begin
Result[I] := Byte(Random(255));
end;
end;
{ TIdHMAC }
constructor TIdHMAC.Create;
begin
inherited Create;
SetLength(FKey, 0);
SetHashVars;
if IsHMACAvail then begin
FHash := nil;
end else begin
InitHash;
end;
end;
destructor TIdHMAC.Destroy;
begin
FreeAndNil(FHash);
inherited Destroy;
end;
function TIdHMAC.HashValueNative(const ABuffer: TIdBytes; const ATruncateTo: Integer = -1) : TIdBytes; // for now, supply in bytes
const
CInnerPad : Byte = $36;
COuterPad : Byte = $5C;
var
TempBuffer1: TIdBytes;
TempBuffer2: TIdBytes;
LKey: TIdBytes;
I: Integer;
begin
InitKey;
LKey := Copy(FKey, 0, MaxInt);
SetLength(LKey, FBlockSize);
SetLength(TempBuffer1, FBlockSize + Length(ABuffer));
for I := Low(LKey) to High(LKey) do begin
TempBuffer1[I] := LKey[I] xor CInnerPad;
end;
CopyTIdBytes(ABuffer, 0, TempBuffer1, Length(LKey), Length(ABuffer));
TempBuffer2 := FHash.HashBytes(TempBuffer1);
SetLength(TempBuffer1, 0);
SetLength(TempBuffer1, FBlockSize + FHashSize);
for I := Low(LKey) to High(LKey) do begin
TempBuffer1[I] := LKey[I] xor COuterPad;
end;
CopyTIdBytes(TempBuffer2, 0, TempBuffer1, Length(LKey), Length(TempBuffer2));
Result := FHash.HashBytes(TempBuffer1);
SetLength(TempBuffer1, 0);
SetLength(TempBuffer2, 0);
SetLength(LKey, 0);
if ATruncateTo > -1 then begin
SetLength(Result, ATruncateTo);
end;
end;
function TIdHMAC.HashValueIntF(const ABuffer: TIdBytes; const ATruncateTo: Integer = -1) : TIdBytes; // for now, supply in bytes
var
LCtx : TIdHMACIntCtx;
begin
if FKey = nil then begin
FKey := TIdHMACKeyBuilder.Key(FHashSize);
end;
LCtx := InitIntFInst(FKey);
try
UpdateHMACInst(LCtx,ABuffer);
finally
Result := FinalHMACInst(LCtx);
end;
if (ATruncateTo >-1) and (ATruncateTo < Length(Result)) then begin
SetLength(Result, ATruncateTo);
end;
end;
function TIdHMAC.HashValue(const ABuffer: TIdBytes; const ATruncateTo: Integer = -1): TIdBytes; // for now, supply in bytes
begin
if IsIntFAvail then begin
Result := HashValueIntF(ABuffer,ATruncateTo);
end else begin
Result := HashValueNative(ABuffer,ATruncateTo);
end;
end;
procedure TIdHMAC.InitKey;
begin
if FKey = nil then begin
FKey := TIdHMACKeyBuilder.Key(FHashSize);
end
else if Length(FKey) > FBlockSize then begin
FKey := FHash.HashBytes(FKey);
end;
end;
function TIdHMAC.IsIntFAvail: Boolean;
begin
Result := IsHMACAvail;
end;
initialization
Randomize;
end.
|
unit kwPopEditorWheelScroll;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorWheelScroll.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_WheelScroll
//
// *Формат:* aUp aVeritcal anEditorControl pop:editor:WheelScroll
// *Описание:* Прокручивает документ к позиции скроллера. aVeritcal - если true, то скроллируем
// повертикали. aUp - сроллировать вверх, если true
// *Пример:*
// {code}
// false true focused:control:push anEditorControl pop:editor:WheelScroll
// {code}
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
evCustomEditorWindow,
tfwScriptingInterfaces,
Controls,
Classes
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas}
TkwPopEditorWheelScroll = {final} class(_kwEditorFromStackWord_)
{* *Формат:* aUp aVeritcal anEditorControl pop:editor:WheelScroll
*Описание:* Прокручивает документ к позиции скроллера. aVeritcal - если true, то скроллируем повертикали. aUp - сроллировать вверх, если true
*Пример:*
[code]
false true focused:control:push anEditorControl pop:editor:WheelScroll
[code] }
protected
// realized methods
procedure DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow); override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopEditorWheelScroll
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
tfwAutoregisteredDiction,
tfwScriptEngine,
Windows,
afwFacade,
Forms
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwPopEditorWheelScroll;
{$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas}
// start class TkwPopEditorWheelScroll
procedure TkwPopEditorWheelScroll.DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow);
//#UC START# *4F4CB81200CA_4F4F5A730085_var*
var
l_Up : Boolean;
l_Vertical : Boolean;
//#UC END# *4F4CB81200CA_4F4F5A730085_var*
begin
//#UC START# *4F4CB81200CA_4F4F5A730085_impl*
if aCtx.rEngine.IsTopBool then
l_Vertical := aCtx.rEngine.PopBool
else
Assert(False, 'Не задана ориентация прокрукти!');
if aCtx.rEngine.IsTopBool then
l_Up := aCtx.rEngine.PopBool
else
Assert(False, 'Не задано направление прокрукти!');
with anEditor.View.Scroller[l_Vertical] do
if l_Up then
WheelUp
else
WheelDown;
//#UC END# *4F4CB81200CA_4F4F5A730085_impl*
end;//TkwPopEditorWheelScroll.DoWithEditor
class function TkwPopEditorWheelScroll.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'pop:editor:WheelScroll';
end;//TkwPopEditorWheelScroll.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit TTSNMSRTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSNMSRRecord = record
PLenderNum: String[4];
PCifFlag: String[1];
PLoanNum: String[20];
PEntryNum: String[1];
PSearchKey: String[15];
PBranch: String[8];
PNameA: String[40];
PNameB: String[40];
PCollateral1: String[60];
PCollateral2: String[60];
End;
TTTSNMSRBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSNMSRRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSNMSR = (TTSNMSRPrimaryKey, TTSNMSRByName, TTSNMSRByBranchName);
TTTSNMSRTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFCifFlag: TStringField;
FDFLoanNum: TStringField;
FDFEntryNum: TStringField;
FDFSearchKey: TStringField;
FDFBranch: TStringField;
FDFNameA: TStringField;
FDFNameB: TStringField;
FDFCollateral1: TStringField;
FDFCollateral2: TStringField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPCifFlag(const Value: String);
function GetPCifFlag:String;
procedure SetPLoanNum(const Value: String);
function GetPLoanNum:String;
procedure SetPEntryNum(const Value: String);
function GetPEntryNum:String;
procedure SetPSearchKey(const Value: String);
function GetPSearchKey:String;
procedure SetPBranch(const Value: String);
function GetPBranch:String;
procedure SetPNameA(const Value: String);
function GetPNameA:String;
procedure SetPNameB(const Value: String);
function GetPNameB:String;
procedure SetPCollateral1(const Value: String);
function GetPCollateral1:String;
procedure SetPCollateral2(const Value: String);
function GetPCollateral2:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEITTSNMSR);
function GetEnumIndex: TEITTSNMSR;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSNMSRRecord;
procedure StoreDataBuffer(ABuffer:TTTSNMSRRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFCifFlag: TStringField read FDFCifFlag;
property DFLoanNum: TStringField read FDFLoanNum;
property DFEntryNum: TStringField read FDFEntryNum;
property DFSearchKey: TStringField read FDFSearchKey;
property DFBranch: TStringField read FDFBranch;
property DFNameA: TStringField read FDFNameA;
property DFNameB: TStringField read FDFNameB;
property DFCollateral1: TStringField read FDFCollateral1;
property DFCollateral2: TStringField read FDFCollateral2;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PCifFlag: String read GetPCifFlag write SetPCifFlag;
property PLoanNum: String read GetPLoanNum write SetPLoanNum;
property PEntryNum: String read GetPEntryNum write SetPEntryNum;
property PSearchKey: String read GetPSearchKey write SetPSearchKey;
property PBranch: String read GetPBranch write SetPBranch;
property PNameA: String read GetPNameA write SetPNameA;
property PNameB: String read GetPNameB write SetPNameB;
property PCollateral1: String read GetPCollateral1 write SetPCollateral1;
property PCollateral2: String read GetPCollateral2 write SetPCollateral2;
published
property Active write SetActive;
property EnumIndex: TEITTSNMSR read GetEnumIndex write SetEnumIndex;
end; { TTTSNMSRTable }
procedure Register;
implementation
function TTTSNMSRTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TTTSNMSRTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TTTSNMSRTable.GenerateNewFieldName }
function TTTSNMSRTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TTTSNMSRTable.CreateField }
procedure TTTSNMSRTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFCifFlag := CreateField( 'CifFlag' ) as TStringField;
FDFLoanNum := CreateField( 'LoanNum' ) as TStringField;
FDFEntryNum := CreateField( 'EntryNum' ) as TStringField;
FDFSearchKey := CreateField( 'SearchKey' ) as TStringField;
FDFBranch := CreateField( 'Branch' ) as TStringField;
FDFNameA := CreateField( 'NameA' ) as TStringField;
FDFNameB := CreateField( 'NameB' ) as TStringField;
FDFCollateral1 := CreateField( 'Collateral1' ) as TStringField;
FDFCollateral2 := CreateField( 'Collateral2' ) as TStringField;
end; { TTTSNMSRTable.CreateFields }
procedure TTTSNMSRTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSNMSRTable.SetActive }
procedure TTTSNMSRTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSNMSRTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSNMSRTable.SetPCifFlag(const Value: String);
begin
DFCifFlag.Value := Value;
end;
function TTTSNMSRTable.GetPCifFlag:String;
begin
result := DFCifFlag.Value;
end;
procedure TTTSNMSRTable.SetPLoanNum(const Value: String);
begin
DFLoanNum.Value := Value;
end;
function TTTSNMSRTable.GetPLoanNum:String;
begin
result := DFLoanNum.Value;
end;
procedure TTTSNMSRTable.SetPEntryNum(const Value: String);
begin
DFEntryNum.Value := Value;
end;
function TTTSNMSRTable.GetPEntryNum:String;
begin
result := DFEntryNum.Value;
end;
procedure TTTSNMSRTable.SetPSearchKey(const Value: String);
begin
DFSearchKey.Value := Value;
end;
function TTTSNMSRTable.GetPSearchKey:String;
begin
result := DFSearchKey.Value;
end;
procedure TTTSNMSRTable.SetPBranch(const Value: String);
begin
DFBranch.Value := Value;
end;
function TTTSNMSRTable.GetPBranch:String;
begin
result := DFBranch.Value;
end;
procedure TTTSNMSRTable.SetPNameA(const Value: String);
begin
DFNameA.Value := Value;
end;
function TTTSNMSRTable.GetPNameA:String;
begin
result := DFNameA.Value;
end;
procedure TTTSNMSRTable.SetPNameB(const Value: String);
begin
DFNameB.Value := Value;
end;
function TTTSNMSRTable.GetPNameB:String;
begin
result := DFNameB.Value;
end;
procedure TTTSNMSRTable.SetPCollateral1(const Value: String);
begin
DFCollateral1.Value := Value;
end;
function TTTSNMSRTable.GetPCollateral1:String;
begin
result := DFCollateral1.Value;
end;
procedure TTTSNMSRTable.SetPCollateral2(const Value: String);
begin
DFCollateral2.Value := Value;
end;
function TTTSNMSRTable.GetPCollateral2:String;
begin
result := DFCollateral2.Value;
end;
procedure TTTSNMSRTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('CifFlag, String, 1, N');
Add('LoanNum, String, 20, N');
Add('EntryNum, String, 1, N');
Add('SearchKey, String, 15, N');
Add('Branch, String, 8, N');
Add('NameA, String, 40, N');
Add('NameB, String, 40, N');
Add('Collateral1, String, 60, N');
Add('Collateral2, String, 60, N');
end;
end;
procedure TTTSNMSRTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;CifFlag;LoanNum;EntryNum, Y, Y, N, N');
Add('ByName, LenderNum;SearchKey, N, N, Y, N');
Add('ByBranchName, LenderNum;Branch;SearchKey, N, N, Y, N');
end;
end;
procedure TTTSNMSRTable.SetEnumIndex(Value: TEITTSNMSR);
begin
case Value of
TTSNMSRPrimaryKey : IndexName := '';
TTSNMSRByName : IndexName := 'ByName';
TTSNMSRByBranchName : IndexName := 'ByBranchName';
end;
end;
function TTTSNMSRTable.GetDataBuffer:TTTSNMSRRecord;
var buf: TTTSNMSRRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PCifFlag := DFCifFlag.Value;
buf.PLoanNum := DFLoanNum.Value;
buf.PEntryNum := DFEntryNum.Value;
buf.PSearchKey := DFSearchKey.Value;
buf.PBranch := DFBranch.Value;
buf.PNameA := DFNameA.Value;
buf.PNameB := DFNameB.Value;
buf.PCollateral1 := DFCollateral1.Value;
buf.PCollateral2 := DFCollateral2.Value;
result := buf;
end;
procedure TTTSNMSRTable.StoreDataBuffer(ABuffer:TTTSNMSRRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFCifFlag.Value := ABuffer.PCifFlag;
DFLoanNum.Value := ABuffer.PLoanNum;
DFEntryNum.Value := ABuffer.PEntryNum;
DFSearchKey.Value := ABuffer.PSearchKey;
DFBranch.Value := ABuffer.PBranch;
DFNameA.Value := ABuffer.PNameA;
DFNameB.Value := ABuffer.PNameB;
DFCollateral1.Value := ABuffer.PCollateral1;
DFCollateral2.Value := ABuffer.PCollateral2;
end;
function TTTSNMSRTable.GetEnumIndex: TEITTSNMSR;
var iname : string;
begin
result := TTSNMSRPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSNMSRPrimaryKey;
if iname = 'BYNAME' then result := TTSNMSRByName;
if iname = 'BYBRANCHNAME' then result := TTSNMSRByBranchName;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSNMSRTable, TTTSNMSRBuffer ] );
end; { Register }
function TTTSNMSRBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..10] of string = ('LENDERNUM','CIFFLAG','LOANNUM','ENTRYNUM','SEARCHKEY','BRANCH'
,'NAMEA','NAMEB','COLLATERAL1','COLLATERAL2' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 10) and (flist[x] <> s) do inc(x);
if x <= 10 then result := x else result := 0;
end;
function TTTSNMSRBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
end;
end;
function TTTSNMSRBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PCifFlag;
3 : result := @Data.PLoanNum;
4 : result := @Data.PEntryNum;
5 : result := @Data.PSearchKey;
6 : result := @Data.PBranch;
7 : result := @Data.PNameA;
8 : result := @Data.PNameB;
9 : result := @Data.PCollateral1;
10 : result := @Data.PCollateral2;
end;
end;
end.
|
unit crt_acad;
interface
function achou(a:integer):integer;
function achounome(a:string):integer;
procedure Abrir;
procedure Cadastro;
procedure Alterar;
procedure Excluir;
procedure Pesquisa_nome;
procedure Pesquisa_cod;
procedure Relatorio;
implementation
Type academia=record
cod, idade:integer;
nome, status, sexo:string;
End;
Var ArqAcad:file of academia;
Aluno:academia;
c, i:integer;
opcao1:char;
procedure Abrir;
Begin
Assign (ArqAcad, 'academia.txt');
{$I-}
Reset(ArqAcad);
{$I+}
If ( IOResult <> 0) then
Rewrite(ArqAcad);
End;
function achou(a:integer):integer;
var indicebusca:integer;
AlunoTemp:academia;
begin
Seek (ArqAcad, 0);
indicebusca:=-1;
while (not eof(ArqAcad)) do
begin
read (ArqAcad, AlunoTemp);
if (a=AlunoTemp.cod) then
begin
indicebusca:=filepos(ArqAcad)-1;
Seek (ArqAcad, filesize(ArqAcad));
end;
end;
achou:=indicebusca;
End;
function achounome(a:string):integer;
var indicebusca1:integer;
begin
Seek (ArqAcad, 0);
indicebusca1:=-1;
while (not eof(ArqAcad)) do
begin
read (ArqAcad, Aluno);
if (a=Aluno.nome) then
begin
indicebusca1:=filepos(ArqAcad)-1;
Seek (ArqAcad, filesize(ArqAcad));
end;
end;
achounome:=indicebusca1;
End;
procedure Cadastro;
var cod, cont:integer;
nome:string;
Begin
REPEAT
clrscr;
Seek (ArqAcad, filesize(ArqAcad));
writeln ('>> Cadastro do Aluno <<');
writeln;
cont:=filesize(ArqAcad);
writeln ('Código: ',cont);
write ('Nome: ');
readln (nome);
while achounome(nome)<>-1 do
begin
textcolor(4);
writeln ('Nome já cadastrado. Informe novamente.');
textcolor(15);
writeln;
write ('Nome: ');
readln (nome);
end;
Aluno.nome:=nome;
Aluno.cod:=cont;
write ('Idade: ');
readln (Aluno.idade);
while (Aluno.idade<0) or (Aluno.idade>150) do
begin
textcolor(4);
writeln ('Idade inválida. Informe novamente.');
textcolor(15);
writeln;
write ('Idade: ');
readln (Aluno.idade);
end;
write ('Sexo (M/F): ');
readln (Aluno.sexo);
while (Aluno.sexo<>'M') and (Aluno.sexo<>'m') and (Aluno.sexo<>'F') and (Aluno.sexo<>'f') do
begin
textcolor(4);
writeln ('Sexo inválido. Informe novamente.');
textcolor(15);
writeln;
write ('Sexo (M/F): ');
readln (Aluno.sexo);
end;
Aluno.status:='Ativo';
write (ArqAcad, Aluno);
textcolor(2);
writeln;
writeln ('Aluno cadastrado com sucesso!');
textcolor(15);
writeln;
writeln ('>> Deseja realizar outro cadastro? S/N <<');
readln (opcao1);
UNTIL (opcao1='N') or (opcao1='n');
End;
procedure Alterar;
var codaluno, guardaidade:integer;
guardanome, guardasexo, guardastatus:string;
campoAlterar:char;
Begin
REPEAT
clrscr;
write ('Informe o código do Aluno a ser alterado: ');
readln (codaluno);
i:=achou(codaluno);
if i<>-1 then
begin
writeln;
textcolor(2);
writeln ('Busca realizada com sucesso!');
textcolor(15);
writeln;
Seek (ArqAcad, i);
read (ArqAcad, Aluno);
writeln ('Código: ',Aluno.cod);
writeln ('Nome: ',Aluno.nome);
writeln ('Idade: ',Aluno.idade);
if (Aluno.sexo='M') or (Aluno.sexo='m') then
begin
writeln ('Sexo: Masculino');
end;
if (Aluno.sexo='F') or (Aluno.sexo='f') then
begin
writeln ('Sexo: Feminino');
end;
if (Aluno.status='Ativo') or (Aluno.status='ativo') then
begin
Aluno.status:='Ativo';
textcolor(2);
writeln ('Status: ',Aluno.status);
textcolor(15);
end;
if (Aluno.status='Inativo') or (Aluno.status='inativo') then
begin
Aluno.status:='Inativo';
textcolor(4);
writeln ('Status: ',Aluno.status);
textcolor(15);
end;
guardanome:=Aluno.nome;
guardaidade:=Aluno.idade;
guardasexo:=Aluno.sexo;
guardastatus:=Aluno.status;
writeln;
end;
if achou(codaluno)=-1 then
begin
writeln;
textcolor(4);
writeln ('Aluno não cadastrado.');
textcolor(15);
writeln;
writeln ('Pressione alguma tecla para voltar ao MENU.');
readkey;
break;
end;
REPEAT
gotoxy (1, 11);
writeln ('>> Dados a serem alterados <<');
writeln;
writeln ('1. Nome');
writeln ('2. Idade');
writeln ('3. Sexo');
writeln ('4. Salvar e sair');
writeln ('5. Sair sem salvar');
writeln;
writeln ('Qual a opção desejada?');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
gotoxy(1, 21);
readln (campoAlterar);
case campoAlterar of
'1':
begin
writeln;
write ('Novo nome: ');
readln (Aluno.nome);
gotoxy (1, 6);
write ('Nome: ', Aluno.nome, ' ');
end;
'2':
begin
writeln;
write ('Nova idade: ');
readln (Aluno.idade);
while (Aluno.idade<0) or (Aluno.idade>150) do
begin
textcolor(4);
writeln ('Idade inválida. Informe novamente.');
textcolor(15);
writeln;
write ('Nova idade: ');
readln (Aluno.idade);
end;
gotoxy (1, 7);
writeln ('Idade: ',Aluno.idade, ' ');
end;
'3':
begin
writeln;
write ('Novo sexo(M/F): ');
readln (Aluno.sexo);
while (Aluno.sexo<>'M') and (Aluno.sexo<>'m') and (Aluno.sexo<>'F') and (Aluno.sexo<>'f') do
begin
textcolor(4);
writeln ('Sexo inválido. Informe novamente.');
textcolor(15);
writeln;
write ('Novo sexo (M/F): ');
readln (Aluno.sexo);
end;
if (Aluno.sexo='M') or (Aluno.sexo='m') then
begin
gotoxy (1, 8);
writeln ('Sexo: Masculino ');
end;
if (Aluno.sexo='F') or (Aluno.sexo='f') then
begin
gotoxy (1, 8);
writeln ('Sexo: Feminino ');
end;
end;
'4':
begin
Seek (ArqAcad, i);
write (ArqAcad, Aluno);
end;
'5':
begin
gotoxy (1, 6);
writeln ('Nome: ',guardanome,' ');
gotoxy (1, 7);
writeln ('Idade: ',guardaidade,' ');
gotoxy (1, 8);
if (guardasexo='M') or (guardasexo='m') then
begin
writeln ('Sexo: Masculino ');
end;
if (guardasexo='F') or (guardasexo='f') then
begin
writeln ('Sexo: Feminino ');
end;
gotoxy (1, 9);
if (guardastatus='Ativo') or (guardastatus='ativo') then
begin
guardastatus:='Ativo';
textcolor(2);
writeln ('Status: ',guardastatus);
textcolor(15);
end;
if (guardastatus='Inativo') or (guardastatus='inativo') then
begin
guardastatus:='Inativo';
textcolor(4);
writeln ('Status: ',guardastatus);
textcolor(15);
end;
end;
end;
UNTIL (campoAlterar='4') or (campoAlterar='5');
gotoxy (1, 22);
writeln;
writeln ('>> Deseja realizar outra alteração? S/N <<');
writeln;
readln (opcao1);
UNTIL (opcao1='N') or (opcao1='n');
End;
procedure Excluir;
var codaluno:integer;
Begin
REPEAT
clrscr;
write ('Informe o código do Aluno a ser ativado/inativado: ');
readln (codaluno);
i:=achou(codaluno);
if i<>-1 then
begin
writeln;
textcolor(2);
writeln ('Busca realizada com sucesso!');
textcolor(15);
writeln;
Seek (ArqAcad, i);
read (ArqAcad, Aluno);
writeln ('Código: ',Aluno.cod);
writeln ('Nome: ',Aluno.nome);
writeln ('Idade: ',Aluno.idade);
if (Aluno.sexo='M') or (Aluno.sexo='m') then
begin
Aluno.sexo:='Masculino';
writeln ('Sexo: ',Aluno.sexo);
Aluno.sexo:='M';
end;
if (Aluno.sexo='F') or (Aluno.sexo='f') then
begin
Aluno.sexo:='Feminino';
writeln ('Sexo: ',Aluno.sexo);
Aluno.sexo:='F';
end;
if (Aluno.status='Ativo') or (Aluno.status='ativo') then
begin
Aluno.status:='Ativo';
textcolor(2);
writeln ('Status: ',Aluno.status);
textcolor(15);
end;
if (Aluno.status='Inativo') or (Aluno.status='inativo') then
begin
Aluno.status:='Inativo';
textcolor(4);
writeln ('Status: ',Aluno.status);
textcolor(15);
end;
writeln;
end;
if achou(codaluno)=-1 then
begin
writeln;
textcolor(4);
writeln ('Aluno não cadastrado.');
textcolor(15);
writeln;
writeln ('Pressione alguma tecla para voltar ao MENU.');
readkey;
break;
end;
writeln ('>> Ativar/inativar cadastro <<');
writeln;
writeln ('Informe Ativo ou Inativo.');
writeln;
write ('Status: ');
readln (Aluno.status);
while (Aluno.status<>'Ativo') and (Aluno.status<>'ativo') and (Aluno.status<>'Inativo') and (Aluno.status<>'inativo') do
begin
textcolor(4);
writeln ('Status inválido.');
textcolor(15);
writeln;
write ('Status: ');
readln (Aluno.status);
writeln;
end;
if (Aluno.status='Ativo') or (Aluno.status='ativo') then
begin
Aluno.status:='Ativo';
gotoxy (1, 9);
textcolor(2);
write ('Status: ', Aluno.status, ' ');
textcolor(15);
end;
if (Aluno.status='Inativo') or (Aluno.status='inativo') then
begin
Aluno.status:='Inativo';
gotoxy (1, 9);
textcolor(4);
write ('Status: ', Aluno.status, ' ');
textcolor(15);
end;
Seek (ArqAcad, i);
write (ArqAcad, Aluno);
writeln;
gotoxy (1, 13);
textcolor(2);
writeln ('Status alterado com sucesso!');
textcolor(15);
gotoxy (1, 15);
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln (' ');
writeln;
gotoxy (1, 15);
writeln ('>> Deseja realizar outra alteração? S/N <<');
writeln;
readln (opcao1);
UNTIL (opcao1='N') or (opcao1='n');
End;
procedure Pesquisa_nome;
var nomealuno:string;
begin
REPEAT
clrscr;
write ('Informe o nome do Aluno a ser consultado: ');
readln (nomealuno);
i:=achounome(nomealuno);
begin
if i<>-1 then
begin
writeln;
textcolor(2);
writeln ('Busca realizada com sucesso!');
textcolor(15);
writeln;
Seek (ArqAcad, i);
read (ArqAcad, Aluno);
writeln ('Código: ',Aluno.cod);
writeln ('Nome: ',Aluno.nome);
writeln ('Idade: ',Aluno.idade);
if (Aluno.sexo='M') or (Aluno.sexo='m') then
begin
Aluno.sexo:='Masculino';
writeln ('Sexo: ',Aluno.sexo);
Aluno.sexo:='M';
end;
if (Aluno.sexo='F') or (Aluno.sexo='f') then
begin
Aluno.sexo:='Feminino';
writeln ('Sexo: ',Aluno.sexo);
Aluno.sexo:='F';
end;
if (Aluno.status='Ativo') or (Aluno.status='ativo') then
begin
Aluno.status:='Ativo';
textcolor(2);
writeln ('Status: ',Aluno.status);
textcolor(15);
end;
if (Aluno.status='Inativo') or (Aluno.status='inativo') then
begin
Aluno.status:='Inativo';
textcolor(4);
writeln ('Status: ',Aluno.status);
textcolor(15);
end;
writeln;
end;
end;
if i=-1 then
begin
writeln;
textcolor(4);
writeln ('Aluno não cadastrado.');
textcolor(15);
writeln;
end;
writeln ('>> Deseja realizar outra pesquisa? S/N <<');
readln (opcao1);
UNTIL (opcao1='N') or (opcao1='n');
End;
procedure Pesquisa_cod;
var codaluno:integer;
begin
REPEAT
clrscr;
write ('Informe o código do Aluno a ser consultado: ');
readln (codaluno);
i:=achou(codaluno);
if i<>-1 then
begin
writeln;
textcolor(2);
writeln ('Busca realizada com sucesso!');
textcolor(15);
writeln;
Seek (ArqAcad, i);
read (ArqAcad, Aluno);
writeln ('Código: ',Aluno.cod);
writeln ('Nome: ',Aluno.nome);
writeln ('Idade: ',Aluno.idade);
if (Aluno.sexo='M') or (Aluno.sexo='m') then
begin
Aluno.sexo:='Masculino';
writeln ('Sexo: ',Aluno.sexo);
Aluno.sexo:='M';
end;
if (Aluno.sexo='F') or (Aluno.sexo='f') then
begin
Aluno.sexo:='Feminino';
writeln ('Sexo: ',Aluno.sexo);
Aluno.sexo:='F';
end;
if (Aluno.status='Ativo') or (Aluno.status='ativo') then
begin
Aluno.status:='Ativo';
textcolor(2);
writeln ('Status: ',Aluno.status);
textcolor(15);
end;
if (Aluno.status='Inativo') or (Aluno.status='inativo') then
begin
Aluno.status:='Inativo';
textcolor(4);
writeln ('Status: ',Aluno.status);
textcolor(15);
end;
writeln;
end;
if i=-1 then
begin
writeln;
textcolor(4);
writeln ('Aluno não cadastrado.');
textcolor(15);
writeln;
end;
writeln ('>> Deseja realizar outra pesquisa? S/N <<');
readln (opcao1);
UNTIL (opcao1='N') or (opcao1='n');
End;
procedure Relatorio;
var opcao2:integer;
begin
REPEAT
clrscr;
writeln ('>> Relatório de Cadastros <<');
writeln;
writeln ('1. Relatório de todos os cadastros');
writeln ('2. Relatório de cadastros ativos');
writeln ('3. Relatório de cadastros inativos');
writeln ('4. Voltar ao MENU PRINCIPAL');
writeln;
writeln ('Qual a opção desejada?');
readln (opcao2);
CASE opcao2 OF
1:
begin
clrscr;
writeln ('>> Relatório de todos cadastros <<');
writeln;
Seek (ArqAcad, 0);
while (not eof(ArqAcad)) do
begin
read (ArqAcad, Aluno);
writeln ('Código: ',Aluno.cod);
writeln ('Nome: ',Aluno.nome);
writeln ('Idade: ',Aluno.idade);
if (Aluno.sexo='M') or (Aluno.sexo='m') then
begin
writeln ('Sexo: Masculino');
end;
if (Aluno.sexo='F') or (Aluno.sexo='f') then
begin
writeln ('Sexo: Feminino');
end;
if (Aluno.status='Ativo') or (Aluno.status='ativo') then
begin
textcolor(2);
writeln ('Status: Ativo');
textcolor(15);
end;
if (Aluno.status='Inativo') or (Aluno.status='inativo') then
begin
textcolor(4);
writeln ('Status: Inativo');
textcolor(15);
end;
writeln;
end;
if filesize(ArqAcad)=0 then
begin
textcolor(4);
writeln ('Nenhum cadastro realizado.');
textcolor(15);
end;
writeln;
writeln ('Pressione alguma tecla para voltar ao MENU.');
readkey;
writeln;
end;
2:
begin
clrscr;
writeln ('>> Relatório de cadastros ativos <<');
writeln;
Seek (ArqAcad, 0);
while (not eof(ArqAcad)) do
begin
read (ArqAcad, Aluno);
IF (aluno.status='Ativo') or (aluno.status='ativo') then
begin
writeln ('Código: ',Aluno.cod);
writeln ('Nome: ',Aluno.nome);
writeln ('Idade: ',Aluno.idade);
if (Aluno.sexo='M') or (Aluno.sexo='m') then
begin
writeln ('Sexo: Masculino');
end;
if (Aluno.sexo='F') or (Aluno.sexo='f') then
begin
writeln ('Sexo: Feminino');
end;
if (Aluno.status='Ativo') or (Aluno.status='ativo') then
begin
textcolor(2);
writeln ('Status: Ativo');
textcolor(15);
end;
writeln;
end;
end;
if filesize(ArqAcad)=0 then
begin
textcolor(4);
writeln ('Nenhum cadastro realizado.');
textcolor(15);
end;
writeln;
writeln ('Pressione alguma tecla para voltar ao MENU.');
readkey;
end;
3:
begin
clrscr;
writeln ('>> Relatório de cadastros inativos <<');
writeln;
Seek (ArqAcad, 0);
while (not eof(ArqAcad)) do
begin
read (ArqAcad, Aluno);
IF (aluno.status='Inativo') or (aluno.status='inativo') then
begin
writeln ('Código: ',Aluno.cod);
writeln ('Nome: ',Aluno.nome);
writeln ('Idade: ',Aluno.idade);
if (Aluno.sexo='M') or (Aluno.sexo='m') then
begin
writeln ('Sexo: Masculino');
end;
if (Aluno.sexo='F') or (Aluno.sexo='f') then
begin
writeln ('Sexo: Feminino');
end;
if (Aluno.status='Inativo') or (Aluno.status='inativo') then
begin
textcolor(4);
writeln ('Status: Inativo');
textcolor(15);
end;
writeln;
end;
end;
if filesize(ArqAcad)=0 then
begin
textcolor(4);
writeln ('Nenhum cadastro realizado.');
textcolor(15);
end;
writeln;
writeln ('Pressione alguma tecla para voltar ao MENU.');
readkey;
end;
end;//end do case
UNTIL opcao2=4;
End;
End.
|
{
This file is part of the Free Pascal run time library.
A file in Amiga system run time library.
Copyright (c) 1998-2003 by Nils Sjoholm
member of the Amiga RTL development team.
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
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.
**********************************************************************}
{
History:
Added the defines use_amiga_smartlink and
use_auto_openlib. Implemented autoopening
of the library.
13 Jan 2003.
Update for AmigaOS 3.9.
FUNCTION GetDiskFontCtrl
PROCEDURE SetDiskFontCtrlA
Varargs for SetDiskFontCtrl is in
systemvartags.
Changed startup for library.
01 Feb 2003.
Changed cardinal > longword.
09 Feb 2003.
nils.sjoholm@mailbox.swipnet.se Nils Sjoholm
}
{$I useamigasmartlink.inc}
{$ifdef use_amiga_smartlink}
{$smartlink on}
{$endif use_amiga_smartlink}
unit diskfont;
INTERFACE
uses exec, graphics,utility;
Const
MAXFONTPATH = 256;
Type
pFontContents = ^tFontContents;
tFontContents = record
fc_FileName : Array [0..MAXFONTPATH-1] of Char;
fc_YSize : Word;
fc_Style : Byte;
fc_Flags : Byte;
end;
pTFontContents = ^tTFontContents;
tTFontContents = record
tfc_FileName : Array[0..MAXFONTPATH-3] of Char;
tfc_TagCount : Word;
tfc_YSize : Word;
tfc_Style,
tfc_Flags : Byte;
END;
Const
FCH_ID = $0f00;
TFCH_ID = $0f02;
OFCH_ID = $0f03;
Type
pFontContentsHeader = ^tFontContentsHeader;
tFontContentsHeader = record
fch_FileID : Word;
fch_NumEntries : Word;
end;
Const
DFH_ID = $0f80;
MAXFONTNAME = 32;
Type
pDiskFontHeader = ^tDiskFontHeader;
tDiskFontHeader = record
dfh_DF : tNode;
dfh_FileID : Word;
dfh_Revision : Word;
dfh_Segment : Longint;
dfh_Name : Array [0..MAXFONTNAME-1] of Char;
dfh_TF : tTextFont;
end;
Const
AFB_MEMORY = 0;
AFF_MEMORY = 1;
AFB_DISK = 1;
AFF_DISK = 2;
AFB_SCALED = 2;
AFF_SCALED = $0004;
AFB_BITMAP = 3;
AFF_BITMAP = $0008;
AFB_TAGGED = 16;
AFF_TAGGED = $10000;
Type
pAvailFonts = ^tAvailFonts;
tAvailFonts = record
af_Type : Word;
af_Attr : tTextAttr;
end;
pTAvailFonts = ^tTAvailFonts;
tTAvailFonts = record
taf_Type : Word;
taf_Attr : tTTextAttr;
END;
pAvailFontsHeader = ^tAvailFontsHeader;
tAvailFontsHeader = record
afh_NumEntries : Word;
end;
const
DISKFONTNAME : PChar = 'diskfont.library';
VAR DiskfontBase : pLibrary;
FUNCTION AvailFonts(buffer : pCHAR; bufBytes : LONGINT; flags : LONGINT) : LONGINT;
PROCEDURE DisposeFontContents(fontContentsHeader : pFontContentsHeader);
FUNCTION NewFontContents(fontsLock : BPTR; fontName : pCHAR) : pFontContentsHeader;
FUNCTION NewScaledDiskFont(sourceFont : pTextFont; destTextAttr : pTextAttr) : pDiskFontHeader;
FUNCTION OpenDiskFont(textAttr : pTextAttr) : pTextFont;
FUNCTION GetDiskFontCtrl(tagid : LONGINT) : LONGINT;
PROCEDURE SetDiskFontCtrlA(taglist : pTagItem);
{Here we read how to compile this unit}
{You can remove this include and use a define instead}
{$I useautoopenlib.inc}
{$ifdef use_init_openlib}
procedure InitDISKFONTLibrary;
{$endif use_init_openlib}
{This is a variable that knows how the unit is compiled}
var
DISKFONTIsCompiledHow : longint;
IMPLEMENTATION
{
If you don't use array of const then just remove tagsarray
}
uses
{$ifndef dont_use_openlib}
msgbox;
{$endif dont_use_openlib}
FUNCTION AvailFonts(buffer : pCHAR; bufBytes : LONGINT; flags : LONGINT) : LONGINT;
BEGIN
ASM
MOVE.L A6,-(A7)
MOVEA.L buffer,A0
MOVE.L bufBytes,D0
MOVE.L flags,D1
MOVEA.L DiskfontBase,A6
JSR -036(A6)
MOVEA.L (A7)+,A6
MOVE.L D0,@RESULT
END;
END;
PROCEDURE DisposeFontContents(fontContentsHeader : pFontContentsHeader);
BEGIN
ASM
MOVE.L A6,-(A7)
MOVEA.L fontContentsHeader,A1
MOVEA.L DiskfontBase,A6
JSR -048(A6)
MOVEA.L (A7)+,A6
END;
END;
FUNCTION NewFontContents(fontsLock : BPTR; fontName : pCHAR) : pFontContentsHeader;
BEGIN
ASM
MOVE.L A6,-(A7)
MOVEA.L fontsLock,A0
MOVEA.L fontName,A1
MOVEA.L DiskfontBase,A6
JSR -042(A6)
MOVEA.L (A7)+,A6
MOVE.L D0,@RESULT
END;
END;
FUNCTION NewScaledDiskFont(sourceFont : pTextFont; destTextAttr : pTextAttr) : pDiskFontHeader;
BEGIN
ASM
MOVE.L A6,-(A7)
MOVEA.L sourceFont,A0
MOVEA.L destTextAttr,A1
MOVEA.L DiskfontBase,A6
JSR -054(A6)
MOVEA.L (A7)+,A6
MOVE.L D0,@RESULT
END;
END;
FUNCTION OpenDiskFont(textAttr : pTextAttr) : pTextFont;
BEGIN
ASM
MOVE.L A6,-(A7)
MOVEA.L textAttr,A0
MOVEA.L DiskfontBase,A6
JSR -030(A6)
MOVEA.L (A7)+,A6
MOVE.L D0,@RESULT
END;
END;
FUNCTION GetDiskFontCtrl(tagid : LONGINT) : LONGINT;
BEGIN
ASM
MOVE.L A6,-(A7)
MOVE.L tagid,D0
MOVEA.L DiskfontBase,A6
JSR -060(A6)
MOVEA.L (A7)+,A6
MOVE.L D0,@RESULT
END;
END;
PROCEDURE SetDiskFontCtrlA(taglist : pTagItem);
BEGIN
ASM
MOVE.L A6,-(A7)
MOVEA.L taglist,A0
MOVEA.L DiskfontBase,A6
JSR -066(A6)
MOVEA.L (A7)+,A6
END;
END;
const
{ Change VERSION and LIBVERSION to proper values }
VERSION : string[2] = '0';
LIBVERSION : longword = 0;
{$ifdef use_init_openlib}
{$Info Compiling initopening of diskfont.library}
{$Info don't forget to use InitDISKFONTLibrary in the beginning of your program}
var
diskfont_exit : Pointer;
procedure ClosediskfontLibrary;
begin
ExitProc := diskfont_exit;
if DiskfontBase <> nil then begin
CloseLibrary(DiskfontBase);
DiskfontBase := nil;
end;
end;
procedure InitDISKFONTLibrary;
begin
DiskfontBase := nil;
DiskfontBase := OpenLibrary(DISKFONTNAME,LIBVERSION);
if DiskfontBase <> nil then begin
diskfont_exit := ExitProc;
ExitProc := @ClosediskfontLibrary;
end else begin
MessageBox('FPC Pascal Error',
'Can''t open diskfont.library version ' + VERSION + #10 +
'Deallocating resources and closing down',
'Oops');
halt(20);
end;
end;
begin
DISKFONTIsCompiledHow := 2;
{$endif use_init_openlib}
{$ifdef use_auto_openlib}
{$Info Compiling autoopening of diskfont.library}
var
diskfont_exit : Pointer;
procedure ClosediskfontLibrary;
begin
ExitProc := diskfont_exit;
if DiskfontBase <> nil then begin
CloseLibrary(DiskfontBase);
DiskfontBase := nil;
end;
end;
begin
DiskfontBase := nil;
DiskfontBase := OpenLibrary(DISKFONTNAME,LIBVERSION);
if DiskfontBase <> nil then begin
diskfont_exit := ExitProc;
ExitProc := @ClosediskfontLibrary;
DISKFONTIsCompiledHow := 1;
end else begin
MessageBox('FPC Pascal Error',
'Can''t open diskfont.library version ' + VERSION + #10 +
'Deallocating resources and closing down',
'Oops');
halt(20);
end;
{$endif use_auto_openlib}
{$ifdef dont_use_openlib}
begin
DISKFONTIsCompiledHow := 3;
{$Warning No autoopening of diskfont.library compiled}
{$Warning Make sure you open diskfont.library yourself}
{$endif dont_use_openlib}
END. (* UNIT DISKFONT *)
|
unit ScanImageForma;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, DelphiTwain, DelphiTwain_Vcl, Vcl.StdCtrls,
Vcl.ExtCtrls, Vcl.Mask, DBCtrlsEh, Vcl.ExtDlgs, PropFilerEh,
PropStorageEh;
type
TScanImageForm = class(TForm)
PnlTop: TPanel;
ImgHolder: TImage;
BtnScanWithDialog: TButton;
BtnScanWithoutDialog: TButton;
btnSave: TButton;
cbbDevice: TDBComboBoxEh;
lbl1: TLabel;
btnCancel: TButton;
dlgOpenPic: TOpenPictureDialog;
edtFile: TDBEditEh;
lbl2: TLabel;
chkSave: TDBCheckBoxEh;
PropStorageEh: TPropStorageEh;
procedure BtnScanWithDialogClick(Sender: TObject);
procedure BtnScanWithoutDialogClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure cbbDeviceEditButtons0Click(Sender: TObject; var Handled: Boolean);
procedure cbbDeviceChange(Sender: TObject);
procedure edtFileEditButtons0Click(Sender: TObject; var Handled: Boolean);
private
Twain: TDelphiTwain;
FTempFile: String;
FFileLoaded: Boolean;
procedure ReloadSources;
procedure TwainTwainAcquire(Sender: TObject; const Index: Integer; Image: TBitmap; var Cancel: Boolean);
protected
procedure DoCreate; override;
procedure DoDestroy; override;
public
property TempFile: String Read FTempFile;
end;
function ScanDocument(const itsPassport : Boolean; var SaveFile : Boolean): String;
implementation
{$R *.dfm}
uses JPEG, pngimage, GIFImg, System.IOUtils, PrjConst;
{ TScanImageForm }
function ScanDocument(const itsPassport : Boolean; var SaveFile : Boolean): String;
begin
with TScanImageForm.Create(application) do
try
chkSave.Visible := itsPassport;
if itsPassport then begin
btnSave.Caption := rsRecognize;
end
else btnSave.Caption := rsSave;
if showmodal = mrOk then begin
Result := TempFile;
SaveFile := chkSave.Checked and ItsPassport;
end;
finally
Free;
end;
end;
procedure TScanImageForm.btnSaveClick(Sender: TObject);
var
jpg_img: TJPEGImage;
TempPath, TmpFile, Prefix: string;
R: Cardinal;
begin
if FFileLoaded then begin
FTempFile := edtFile.Text;
end
else begin
Prefix := 'Scan_';
R := GetTempPath(0, nil);
SetLength(TempPath, R);
R := GetTempPath(R, PChar(TempPath));
if R <> 0 then begin
SetLength(TempPath, StrLen(PChar(TempPath)));
SetLength(TmpFile, MAX_PATH);
R := GetTempFileName(PChar(TempPath), PChar(Prefix), 0, PChar(TmpFile));
if R <> 0 then begin
SetLength(TmpFile, StrLen(PChar(TmpFile)));
// TmpFile := ChangeFileExt(TmpFile, '.jpg');
end;
end;
if TmpFile.IsEmpty then
TmpFile := ExtractFilePath(application.ExeName) + Prefix + '.jpg';
FTempFile := TmpFile;
jpg_img := TJPEGImage.Create;
try
jpg_img.Assign(ImgHolder.Picture.Bitmap);
jpg_img.DIBNeeded;
jpg_img.CompressionQuality := 75; // от 0 до 100, где 100 -самое лучшее качество
jpg_img.Compress;
jpg_img.SaveToFile(FTempFile);
finally
jpg_img.Free;
end;
end;
end;
procedure TScanImageForm.BtnScanWithDialogClick(Sender: TObject);
begin
Twain.SelectedSourceIndex := cbbDevice.ItemIndex;
if Assigned(Twain.SelectedSource) then begin
// Load source, select transference method and enable (display interface)}
Twain.SelectedSource.Loaded := True;
Twain.SelectedSource.ShowUI := True; // display interface
Twain.SelectedSource.Enabled := True;
end;
end;
procedure TScanImageForm.BtnScanWithoutDialogClick(Sender: TObject);
begin
Twain.SelectedSourceIndex := cbbDevice.ItemIndex;
if Assigned(Twain.SelectedSource) then begin
// Load source, select transference method and enable (display interface)}
Twain.SelectedSource.Loaded := True;
Twain.SelectedSource.ShowUI := False;
Twain.SelectedSource.Enabled := True;
end;
end;
procedure TScanImageForm.cbbDeviceChange(Sender: TObject);
begin
BtnScanWithDialog.Enabled := not cbbDevice.Text.IsEmpty;
BtnScanWithoutDialog.Enabled := not cbbDevice.Text.IsEmpty;
end;
procedure TScanImageForm.cbbDeviceEditButtons0Click(Sender: TObject; var Handled: Boolean);
begin
if Twain.SourceManagerLoaded then
ReloadSources;
Handled := True;
end;
procedure TScanImageForm.DoCreate;
begin
inherited;
Twain := TDelphiTwain.Create;
Twain.OnTwainAcquire := TwainTwainAcquire;
if Twain.LoadLibrary then begin
// Load source manager
Twain.SourceManagerLoaded := True;
ReloadSources;
end
else begin
ShowMessage('Twain is not installed.');
end;
end;
procedure TScanImageForm.DoDestroy;
begin
Twain.Free; // Don't forget to free Twain!
inherited;
end;
procedure TScanImageForm.edtFileEditButtons0Click(Sender: TObject; var Handled: Boolean);
begin
if dlgOpenPic.Execute then begin
edtFile.Text := dlgOpenPic.FileName;
ImgHolder.Picture.LoadFromFile(dlgOpenPic.FileName);
FFileLoaded := True;
btnSave.Enabled := True;
end
end;
procedure TScanImageForm.ReloadSources;
var
I: Integer;
begin
cbbDevice.Items.Clear;
cbbDevice.KeyItems.Clear;
for I := 0 to Twain.SourceCount - 1 do begin
cbbDevice.Items.Add(Twain.Source[I].ProductName);
cbbDevice.KeyItems.Add(I.ToString);
end;
if cbbDevice.Items.Count > 0 then
cbbDevice.ItemIndex := 0;
end;
procedure TScanImageForm.TwainTwainAcquire(Sender: TObject; const Index: Integer; Image: TBitmap; var Cancel: Boolean);
begin
ImgHolder.Picture.Assign(Image);
Cancel := True; // Only want one image
FFileLoaded := False;
edtFile.Text := '';
btnSave.Enabled := True;
end;
end.
|
{$I ACBr.inc}
unit ASCIOT;
interface
uses
Classes, Sysutils,
{$IFDEF VisualCLX}
QDialogs,
{$ELSE}
Dialogs,
{$ENDIF}
Forms,
smtpsend, ssl_openssl, mimemess, mimepart, // units para enviar email
pciotCIOT, pcnConversao,
ACBrUtil, ACBrDFeUtil, ASCIOTUtil,
ASCIOTConfiguracoes,
ASCIOTWebServices;//, ACBrCTeDACTeClass;
const
AmsCIOT_VERSAO = '1.00';
type
TAmSCIOTAboutInfo = (ACBrCIOTAbout);
EAmSCIOTException = class(Exception);
{ Evento para gerar log das mensagens do Componente }
TAmSCIOTLog = procedure(const Mensagem : String) of object;
TAmSCIOT = class(TComponent)
private
fsAbout: TAmSCIOTAboutInfo;
// FDACTe : TACBrCTeDACTeClass;
// FOperacoesTransporte: TOperacoesTransporte;
FWebServices: TWebServices;
FConfiguracoes: TConfiguracoes;
FStatus : TStatusACBrCIOT;
FOnStatusChange: TNotifyEvent;
FOnGerarLog : TAmSCIOTLog;
FVeiculos: TCIOTVeiculo;
FMotoristas: TCIOTMotorista;
FProprietario: TCIOTProprietario;
FOT: TCIOTOperacaoTransporte;
// procedure SetDACTe(const Value: TACBrCTeDACTeClass);
procedure EnviaEmailThread(const sSmtpHost, sSmtpPort, sSmtpUser,
sSmtpPasswd, sFrom, sTo, sAssunto: String; sMensagem: TStrings;
SSL: Boolean; sCC, Anexos: TStrings; PedeConfirma, AguardarEnvio: Boolean;
NomeRemetente: String; TLS: Boolean; StreamCTe: TStringStream;
NomeArq: String; HTML: Boolean = False);
procedure EnviarEmailNormal(const sSmtpHost, sSmtpPort, sSmtpUser,
sSmtpPasswd, sFrom, sTo, sAssunto: String; sMensagem: TStrings;
SSL: Boolean; sCC, Anexos: TStrings; PedeConfirma, AguardarEnvio: Boolean;
NomeRemetente: String; TLS: Boolean; StreamCTe: TStringStream;
NomeArq: String);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Veiculos: TCIOTVeiculo read FVeiculos write FVeiculos;
property Motoristas: TCIOTMotorista read FMotoristas write FMotoristas;
property Proprietario: TCIOTProprietario read FProprietario write FProprietario;
property OT: TCIOTOperacaoTransporte read FOT write FOT;
property WebServices: TWebServices read FWebServices write FWebServices;
property Status: TStatusACBrCIOT read FStatus;
procedure SetStatus( const stNewStatus : TStatusACBrCIOT );
procedure EnviaEmail(const sSmtpHost,
sSmtpPort,
sSmtpUser,
sSmtpPasswd,
sFrom,
sTo,
sAssunto: String;
sMensagem : TStrings;
SSL : Boolean;
sCC: TStrings = nil;
Anexos:TStrings=nil;
PedeConfirma: Boolean = False;
AguardarEnvio: Boolean = False;
NomeRemetente: String = '';
TLS : Boolean = True;
StreamCTe : TStringStream = nil;
NomeArq : String = '';
UsarThread: Boolean = True;
HTML: Boolean = False);
published
property Configuracoes: TConfiguracoes read FConfiguracoes write FConfiguracoes;
property OnStatusChange: TNotifyEvent read FOnStatusChange write FOnStatusChange;
// property DACTe: TACBrCTeDACTeClass read FDACTe write SetDACTe;
property AbouTAmSCIOT : TAmSCIOTAboutInfo read fsAbout write fsAbout
stored false;
property OnGerarLog : TAmSCIOTLog read FOnGerarLog write FOnGerarLog;
end;
procedure ACBrAboutDialog;
implementation
procedure ACBrAboutDialog;
var
Msg : String;
begin
Msg := 'Componente AmSCIOT'+#10+
'Versão: '+AmSCIOT_VERSAO+#10+#10+
'Automação Comercial Brasil'+#10+#10+
'http://acbr.sourceforge.net'+#10+#10+
'Projeto Cooperar - PCN'+#10+#10+
'http://www.projetocooperar.org/pcn/';
MessageDlg(Msg ,mtInformation ,[mbOk],0);
end;
{ TAmSCIOT }
constructor TAmSCIOT.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FConfiguracoes := TConfiguracoes.Create( self );
FConfiguracoes.Name:= 'Configuracoes';
{$IFDEF COMPILER6_UP}
FConfiguracoes.SetSubComponent( true );{ para gravar no DFM/XFM }
{$ENDIF}
FVeiculos := TCIOTVeiculo.Create(Self);
FMotoristas := TCIOTMotorista.Create(Self);
FProprietario := TCIOTProprietario.Create(Self);
FOT := TCIOTOperacaoTransporte.Create(Self);
FWebServices := TWebServices.Create(Self);
if FConfiguracoes.WebServices.Tentativas <= 0 then
FConfiguracoes.WebServices.Tentativas := 5;
{$IFDEF ACBrCTeOpenSSL}
if FConfiguracoes.Geral.IniFinXMLSECAutomatico then
CIOTUtil.InitXmlSec;
{$ENDIF}
FOnGerarLog := nil;
end;
destructor TAmSCIOT.Destroy;
begin
FConfiguracoes.Free;
FVeiculos.Free;
FMotoristas.Free;
FProprietario.Free;
FOT.Free;
FWebServices.Free;
{$IFDEF ACBrCTeOpenSSL}
if FConfiguracoes.Geral.IniFinXMLSECAutomatico then
CIOTUtil.ShutDownXmlSec;
{$ENDIF}
inherited;
end;
procedure TAmSCIOT.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
// if (Operation = opRemove) and (FDACTe <> nil) and (AComponent is TACBrCTeDACTeClass) then
// FDACTe := nil;
end;
//
//procedure TAmSCIOT.SetDACTe(const Value: TACBrCTeDACTeClass);
// Var OldValue: TACBrCTeDACTeClass;
//begin
// if Value <> FDACTe then
// begin
// if Assigned(FDACTe) then
// FDACTe.RemoveFreeNotification(Self);
//
// OldValue := FDACTe; // Usa outra variavel para evitar Loop Infinito
// FDACTe := Value; // na remoção da associação dos componentes
//
// if Assigned(OldValue) then
// if Assigned(OldValue.ACBrCTe) then
// OldValue.ACBrCTe := nil;
//
// if Value <> nil then
// begin
// Value.FreeNotification(self);
// Value.ACBrCTe := self;
// end;
// end;
//end;
procedure TAmSCIOT.SetStatus( const stNewStatus : TStatusACBrCIOT );
begin
if ( stNewStatus <> FStatus ) then
begin
FStatus := stNewStatus;
if Assigned(fOnStatusChange) then
FOnStatusChange(Self);
end;
end;
procedure TAmSCIOT.EnviaEmailThread(const sSmtpHost, sSmtpPort, sSmtpUser,
sSmtpPasswd, sFrom, sTo, sAssunto: String; sMensagem: TStrings;
SSL: Boolean; sCC, Anexos: TStrings; PedeConfirma,
AguardarEnvio: Boolean; NomeRemetente: String; TLS: Boolean;
StreamCTe: TStringStream; NomeArq: String; HTML: Boolean = False);
var
ThreadSMTP : TSendMailThread;
m:TMimemess;
p: TMimepart;
i: Integer;
begin
m:=TMimemess.create;
ThreadSMTP := TSendMailThread.Create; // Não Libera, pois usa FreeOnTerminate := True;
try
p := m.AddPartMultipart('mixed', nil);
if sMensagem <> nil then
begin
if HTML = true then
m.AddPartHTML(sMensagem, p)
else
m.AddPartText(sMensagem, p);
end;
if StreamCTe <> nil then
m.AddPartBinary(StreamCTe,NomeArq, p);
if assigned(Anexos) then
for i := 0 to Anexos.Count - 1 do
begin
m.AddPartBinaryFromFile(Anexos[i], p);
end;
m.header.tolist.add(sTo);
if Trim(NomeRemetente) <> '' then
m.header.From := Format('%s<%s>', [NomeRemetente, sFrom])
else
m.header.From := sFrom;
m.header.subject:= sAssunto;
m.Header.ReplyTo := sFrom;
if PedeConfirma then
m.Header.CustomHeaders.Add('Disposition-Notification-To: '+sFrom);
m.EncodeMessage;
ThreadSMTP.sFrom := sFrom;
ThreadSMTP.sTo := sTo;
if sCC <> nil then
ThreadSMTP.sCC.AddStrings(sCC);
ThreadSMTP.slmsg_Lines.AddStrings(m.Lines);
ThreadSMTP.smtp.UserName := sSmtpUser;
ThreadSMTP.smtp.Password := sSmtpPasswd;
ThreadSMTP.smtp.TargetHost := sSmtpHost;
if not EstaVazio( sSmtpPort ) then // Usa default
ThreadSMTP.smtp.TargetPort := sSmtpPort;
ThreadSMTP.smtp.FullSSL := SSL;
ThreadSMTP.smtp.AutoTLS := TLS;
if (TLS) then
ThreadSMTP.smtp.StartTLS;
SetStatus( stCIOTEmail );
ThreadSMTP.Resume; // inicia a thread
if AguardarEnvio then
begin
repeat
Sleep(1000);
Application.ProcessMessages;
until ThreadSMTP.Terminado;
end;
SetStatus( stCIOTIdle );
finally
m.free;
end;
end;
procedure TAmSCIOT.EnviarEmailNormal(const sSmtpHost, sSmtpPort, sSmtpUser,
sSmtpPasswd, sFrom, sTo, sAssunto: String; sMensagem: TStrings;
SSL: Boolean; sCC, Anexos: TStrings; PedeConfirma,
AguardarEnvio: Boolean; NomeRemetente: String; TLS: Boolean;
StreamCTe: TStringStream; NomeArq: String);
var
smtp: TSMTPSend;
msg_lines: TStringList;
m:TMimemess;
p: TMimepart;
I : Integer;
CorpoEmail: TStringList;
begin
SetStatus( stCIOTEmail );
msg_lines := TStringList.Create;
CorpoEmail := TStringList.Create;
smtp := TSMTPSend.Create;
m:=TMimemess.create;
try
p := m.AddPartMultipart('mixed', nil);
if sMensagem <> nil then
begin
CorpoEmail.Text := sMensagem.Text;
m.AddPartText(CorpoEmail, p);
end;
if StreamCTe <> nil then
m.AddPartBinary(StreamCTe, NomeArq, p);
if assigned(Anexos) then
for i := 0 to Anexos.Count - 1 do
begin
m.AddPartBinaryFromFile(Anexos[i], p);
end;
m.header.tolist.add(sTo);
m.header.From := sFrom;
m.header.subject := sAssunto;
m.EncodeMessage;
msg_lines.Add(m.Lines.Text);
smtp.UserName := sSmtpUser;
smtp.Password := sSmtpPasswd;
smtp.TargetHost := sSmtpHost;
smtp.TargetPort := sSmtpPort;
smtp.FullSSL := SSL;
smtp.AutoTLS := TLS;
if (TLS) then
smtp.StartTLS;
if not smtp.Login then
raise Exception.Create('SMTP ERROR: Login: ' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text);
if not smtp.MailFrom(sFrom, Length(sFrom)) then
raise Exception.Create('SMTP ERROR: MailFrom: ' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text);
if not smtp.MailTo(sTo) then
raise Exception.Create('SMTP ERROR: MailTo: ' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text);
if sCC <> nil then
begin
for I := 0 to sCC.Count - 1 do
begin
if not smtp.MailTo(sCC.Strings[i]) then
raise Exception.Create('SMTP ERROR: MailTo: ' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text);
end;
end;
if not smtp.MailData(msg_lines) then
raise Exception.Create('SMTP ERROR: MailData: ' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text);
if not smtp.Logout then
raise Exception.Create('SMTP ERROR: Logout: ' + smtp.EnhCodeString+sLineBreak+smtp.FullResult.Text);
finally
msg_lines.Free;
CorpoEmail.Free;
smtp.Free;
m.free;
SetStatus( stCIOTIdle );
end;
end;
procedure TAmSCIOT.EnviaEmail(const sSmtpHost, sSmtpPort, sSmtpUser,
sSmtpPasswd, sFrom, sTo, sAssunto: String; sMensagem: TStrings;
SSL: Boolean; sCC, Anexos: TStrings; PedeConfirma,
AguardarEnvio: Boolean; NomeRemetente: String; TLS: Boolean;
StreamCTe: TStringStream; NomeArq: String; UsarThread: Boolean; HTML: Boolean);
begin
if UsarThread then
begin
EnviaEmailThread(
sSmtpHost,
sSmtpPort,
sSmtpUser,
sSmtpPasswd,
sFrom,
sTo,
sAssunto,
sMensagem,
SSL,
sCC,
Anexos,
PedeConfirma,
AguardarEnvio,
NomeRemetente,
TLS,
StreamCTe,
NomeArq,
HTML
);
end
else
begin
EnviarEmailNormal(
sSmtpHost,
sSmtpPort,
sSmtpUser,
sSmtpPasswd,
sFrom,
sTo,
sAssunto,
sMensagem,
SSL,
sCC,
Anexos,
PedeConfirma,
AguardarEnvio,
NomeRemetente,
TLS,
StreamCTe,
NomeArq
);
end;
end;
end.
|
{$include lem_directives.inc}
unit GameInterfaces;
{-------------------------------------------------------------------------------
Unit with shared interfaces between game and it's controls
-------------------------------------------------------------------------------}
interface
uses
GR32,
LemCore;
type
// drawing of info and toolbarbuttons
IGameToolbar = interface
procedure DrawSkillCount(aButton: TSkillPanelButton; aNumber: Integer);
procedure DrawButtonSelector(aButton: TSkillPanelButton; SelectorOn: Boolean);
procedure DrawMinimap(Map: TBitmap32);
procedure SetInfoCursorLemming(const Lem: string; HitCount: Integer);
procedure SetInfoLemmingsOut(Num: Integer);
procedure SetInfoLemmingsIn(Num, Max: Integer);
procedure SetInfoMinutes(Num: Integer);
procedure SetInfoSeconds(Num: Integer);
procedure RefreshInfo;
end;
implementation
end.
|
unit IRCCommands;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TIRCCommand }
TAlias = array[0..1] of string;
TIRCCommand = class
private
function FormatCommand(const Raw: string): string;
function GetCommandFromInput(const RawInput: string): string;
function RemoveSlash(const Value: string): string;
function ReplaceAlias(const Command: string): string;
function FixChannelName(const Command: string): string;
public
function GetRawCommand(const RawInput: string): string;
end;
implementation
const
CommandAlias: array[0..0] of TAlias = (
('J', 'JOIN')
);
{ TIRCCommand }
function TIRCCommand.FormatCommand(const Raw: string): string;
var
UserCommand, NewCommand: string;
begin
UserCommand := GetCommandFromInput(Raw);
NewCommand := ReplaceAlias(UpperCase(UserCommand));
Result := StringReplace(Raw, UserCommand, NewCommand, []);
if NewCommand = '/JOIN' then
Result := FixChannelName(Result);
Result := RemoveSlash(Result);
end;
function TIRCCommand.GetCommandFromInput(const RawInput: string): string;
var
CommandEnd: Integer;
begin
CommandEnd := Pos(' ', RawInput);
if CommandEnd = 0 then
CommandEnd := MaxInt;
Result := Copy(RawInput, 1, CommandEnd -1)
end;
function TIRCCommand.RemoveSlash(const Value: string): string;
begin
Result := StringReplace(Value, '/', '', []);
end;
function TIRCCommand.ReplaceAlias(const Command: string): string;
var
I: Integer;
function AddSlash(const Value: string): string;
begin
Result := '/' + Value;
end;
function Replace: string;
begin
Result := StringReplace(Command, AddSlash(CommandAlias[I][0]), AddSlash(CommandAlias[I][1]), []);
end;
begin
Result := Command;
for I := Low(CommandAlias) to High(CommandAlias) do
begin
if Command <> AddSlash(CommandAlias[I][0]) then
Continue;
Exit(Replace);
end;
end;
function TIRCCommand.FixChannelName(const Command: string): string;
var
Channel: string;
begin
Channel := Trim(Copy(Command, Pos(' ', Command), MaxInt));
if (Channel = '') then
Exit;
Result := Command;
if Channel[1] <> '#' then
Result := StringReplace(Result, Channel, '#' + Channel, [])
end;
function TIRCCommand.GetRawCommand(const RawInput: string): string;
begin
if Pos('/', RawInput) <> 1 then
Exit('');
Result := FormatCommand(RawInput);
end;
end.
|
Program syntx_analizator;
const lenghtString = 255;
var source : string;
operations, letters, digits : set of char;
identificators : array[1..15] of string;
function CheckBrackets(source : string) : boolean;
var cOpened, cClosed : integer;
i : integer;
begin
cOpened := 0;
cClosed := 0;
for i := 1 to length(source) do
begin
if(source[i] = '(') then inc(cOpened);
if(source[i] = ')') then inc(cClosed);
end;
if(cOpened = cClosed) then CheckBrackets := true
else CheckBrackets := false;
end;
procedure CleanupSpaces(var source : string);
var i: integer;
begin
source := trim(source);
for i:= 1 to length(source) do
begin
if( i = length(source)) then break;
if(source[i] = ' ') then
while(source[i+1] = ' ') do delete(source, i, 1);
end;
end;
procedure _Initialization();
begin
operations := ['+', '-', '*', '/'];
letters := ['A'..'Z'];
digits := ['0'..'9'];
end;
function isSpace(s : char) : boolean;
begin
if(s = ' ') then isSpace := true
else isSpace := false;
end;
function isLetter(s : char) : boolean;
begin
if(UpCase(s) in letters) then isLetter := true
else isLetter := false;
end;
function isDigit(s : char) : boolean;
begin
if(s in digits) then isDigit := true
else isDigit := false;
end;
function isOperation(s : char) : boolean;
begin
if(s in operations) then isOperation := true
else isOperation := false;
end;
procedure Parse(source : string[lenghtString]);
var literal : char;
i, idCount : integer;
buff : string;
begin
i := 1;
idCount := 0;
while i < length(source) do
begin
literal := source[i];
if(isLetter(literal)) then
begin
inc(idCount);
while(isLetter(source[i]) or isDigit(source[i]) or not isSpace(source[i])) do
begin
if( i = length(source)) then begin
identificators[idCount] += source[i];
break;
end;
identificators[idCount] += source[i];
inc(i);
end;
end;
if(isDigit(literal)) then
begin
inc(idCount);
while(isDigit(source[i]) or not isSpace(source[i])) do
begin
if( i = length(source)) then begin
identificators[idCount] += source[i];
break;
end;
identificators[idCount] += source[i];
inc(i);
end;
end;
if(isOperation(literal)) then
begin
inc(idCount);
identificators[idCount] += source[i];
end;
if((source[i] = 'd') and (source[i+1] = 'i') and (source[i+2] = 'v')) then
begin
inc(idCount);
identificators[idCount] += 'div';
end;
if((source[i] = 'd') and (source[i+1] = 'i') and (source[i+2] = 'v')) then
begin
inc(idCount);
identificators[idCount] += 'mod';
end;
if(literal = '(') then
begin
inc(idCount);
identificators[idCount] += literal;
end;
if(literal = ')') then
begin
inc(idCount);
identificators[idCount] += literal;
end;
inc(i);
end;
end;
Begin
_Initialization();
writeln('Введите выражение: ');
readln(source);
CleanupSpaces(source);
Parse(source);
writeln('Результаты парсинга');
writeln(identificators);
End. |
unit VLEUtil;
interface
uses
// VCL
Windows, SysUtils, Graphics, ValEdit, Grids, Classes;
procedure VLE_SETPickPropertyValue(AVLE: TValueListEditor; AName: string; AValue: Integer);
function VLE_GetPickPropertyValue(AVLE: TValueListEditor; AName: string): Integer;
function VLE_GetPropertyValue(AVLE: TValueListEditor; AName: string): string;
procedure VLE_AddProperty(AVLE: TValueListEditor; AName: string; AValueDef: string);
procedure VLE_AddPickProperty(AVLE: TValueListEditor; AName: string; AValueDef: string;
APickItemNames: array of string; APickItemValues: array of Integer);
procedure VLE_AddSeparator(AVLE: TValueListEditor; AName: string);
procedure VLE_SetPropertyValue(AVLE: TValueListEditor; AName: string; AValue: string);
procedure VLE_DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
function VLEParamsToString(AVLE: TValueListEditor): string;
procedure StringToVLEParams(AVLE: TValueListEditor; AStr: string);
implementation
procedure VLE_AddPickProperty(AVLE: TValueListEditor; AName: string; AValueDef: string;
APickItemNames: array of string; APickItemValues: array of Integer);
var
i: Integer;
begin
if not Assigned(AVLE) then
Exit;
AVLE.InsertRow(AName, AValueDef, True);
if High(APickItemNames) = 0 then
Exit;
if High(APickItemNames) <> High(APickItemValues) then
Exit;
for i := 0 to High(APickItemnames) do
begin
AVLE.ItemProps[AName].EditStyle := esPickList;
AVLE.ItemProps[AName].ReadOnly := True;
AVLE.ItemProps[AName].PickList.AddObject(APickItemNames[i],
TObject(APickItemValues[i]));
end;
end;
procedure VLE_AddProperty(AVLE: TValueListEditor; AName: string; AValueDef: string);
begin
VLE_AddPickProperty(AVLE, AName, AValueDef, [], []);
end;
function VLE_GetPropertyValue(AVLE: TValueListEditor; AName: string): string;
begin
Result := AVLE.Values[AName];
end;
function VLE_GetPickPropertyValue(AVLE: TValueListEditor; AName: string): Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to AVLE.ItemProps[AName].PickList.Count - 1 do
if AVLE.ItemProps[AName].PickList.Strings[i] = AVLE.Values[AName] then
begin
Result := Integer(AVLE.ItemProps[AName].PickList.Objects[i]);
Break;
end;
end;
procedure VLE_SetPropertyValue(AVLE: TValueListEditor; AName: string; AValue: string);
begin
AVLE.Values[AName] := AValue;
end;
procedure VLE_SETPickPropertyValue(AVLE: TValueListEditor; AName: string; AValue: Integer);
var
i: Integer;
begin
for i := 0 to AVLE.ItemProps[AName].PickList.Count - 1 do
if Integer(AVLE.ItemProps[AName].PickList.Objects[i]) = AValue then
begin
AVLE.Values[AName] := AVLE.ItemProps[AName].PickList.Strings[i];
Break;
end;
end;
procedure VLE_AddSeparator(AVLE: TValueListEditor; AName: string);
begin
AVLE.InsertRow('|;separator;|' + AName, '', True);
AVLE.ItemProps['|;separator;|' + AName].ReadOnly := True;
end;
procedure VLE_DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
HT: Integer;
HR: Integer;
s: string;
VLE: TValueListEditor;
begin
if Sender is TValueListEditor then
VLE := TValueListEditor(Sender)
else
Exit;
if Pos('|;separator;|', VLE.Cells[ACol, ARow]) > 0 then
begin
VLE.Canvas.Brush.Color := VLE.Canvas.Pen.Color;
VLE.Canvas.Rectangle(Rect);
VLE.Canvas.Font.Style := [fsBold];
HR := Rect.Bottom - Rect.Top;
HT := VLE.Canvas.TextHeight(VLE.Cells[ACol, ARow]);
s := VLE.Cells[ACol, ARow];
Delete(s, 1, 13);
VLE.Canvas.TextOut(Rect.Left + 10, Rect.Top + (HR-HT) div 2, s);
end;
end;
function VLEParamsToString(AVLE: TValueListEditor): string;
var
i: Integer;
SL: TStringList;
begin
SL := TStringList.Create;
try
for i := 1 to AVLE.RowCount - 1 do
SL.Add(AVLE.Cells[1, i]);
Result := SL.Text;
finally
SL.Free;
end;
end;
procedure StringToVLEParams(AVLE: TValueListEditor; AStr: string);
var
i: Integer;
SL: TStringList;
begin
SL := TStringList.Create;
SL.Text := AStr;
try
if SL.Count <> (AVLE.RowCount - 1) then Exit;
for i := 1 to AVLE.RowCount - 1 do
begin
AVLE.Cells[1, i] := SL[i - 1];
end;
finally
SL.Free;
end;
end;
end.
|
unit udmLocaisRetirada;
interface
uses
Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS;
type
TdmLocaisRetirada = class(TdmPadrao)
qryManutencaoCGC: TStringField;
qryManutencaoCODIGO: TStringField;
qryManutencaoENDERECO: TStringField;
qryManutencaoCIDADE: TStringField;
qryManutencaoESTADO: TStringField;
qryManutencaoCEP: TStringField;
qryManutencaoACESSOS: TBlobField;
qryManutencaoTIPO: TStringField;
qryManutencaoDT_ALTERACAO: TDateTimeField;
qryManutencaoOPERADOR: TStringField;
qryManutencaoEND_COMPL: TStringField;
qryManutencaoEND_NRO: TStringField;
qryLocalizacaoCGC: TStringField;
qryLocalizacaoCODIGO: TStringField;
qryLocalizacaoENDERECO: TStringField;
qryLocalizacaoCIDADE: TStringField;
qryLocalizacaoESTADO: TStringField;
qryLocalizacaoCEP: TStringField;
qryLocalizacaoACESSOS: TBlobField;
qryLocalizacaoTIPO: TStringField;
qryLocalizacaoDT_ALTERACAO: TDateTimeField;
qryLocalizacaoOPERADOR: TStringField;
qryLocalizacaoEND_NRO: TStringField;
qryLocalizacaoEND_COMPL: TStringField;
protected
procedure MontaSQLBusca(DataSet: TDataSet = nil); override;
procedure MontaSQLRefresh; override;
private
FCod_Cliente: string;
FCod_Local: string;
{ Private declarations }
public
{ Public declarations }
property Cod_Cliente: string read FCod_Cliente write FCod_Cliente;
property Cod_Local: string read FCod_Local write FCod_Local;
function LocalizarPorCliente(DataSet: TDataSet = nil): Boolean;
end;
const
SQL_DEFAULT = 'SELECT CGC, ' +
' CODIGO, ' +
' ENDERECO, ' +
' CIDADE, ' +
' ESTADO, ' +
' CEP, ' +
' ACESSOS, ' +
' TIPO, ' +
' DT_ALTERACAO, ' +
' OPERADOR, ' +
' END_NRO, ' +
' END_COMPL ' +
' FROM STWSACTLRE' ;
var
dmLocaisRetirada: TdmLocaisRetirada;
implementation
{$R *.dfm}
{ TdmLocaisRetirada }
procedure TdmLocaisRetirada.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE CGC = :CGC AND CODIGO = :CODIGO ');
SQL.Add('ORDER BY CGC, CODIGO');
Params[0].AsString := FCod_Cliente;
Params[1].AsString := FCod_Local;
end;
end;
procedure TdmLocaisRetirada.MontaSQLRefresh;
begin
inherited;
with qryManutencao do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('ORDER BY CGC, CODIGO');
end;
end;
function TdmLocaisRetirada.LocalizarPorCliente(DataSet: TDataSet): Boolean;
begin
if DataSet = nil then
DataSet := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
Close;
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE CGC = :CGC');
SQL.Add('ORDER BY CGC, CODIGO');
Params[0].AsString := FCod_Cliente;
Open;
Result := not IsEmpty;
end;
end;
end.
|
{@html(<hr>)
@abstract(Telemetry recipient class (API control and data receiver).)
@author(František Milt <fmilt@seznam.cz>)
@created(2013-10-07)
@lastmod(2014-05-04)
@bold(@NoAutoLink(TelemetryRecipient))
©František Milt, all rights reserved.
This unit contains TTelemetryRecipient class used to control the telmetry API
(see class declaration for details) and few classes used to manage multicast
events for the recipient, namely:
@preformatted(
TMulticastLogEvent
TMulticastEventRegisterEvent
TMulticastEventEvent
TMulticastChannelRegisterEvent
TMulticastChannelUnregisterEvent
TMulticastChannelEvent
TMulticastConfigEvent
)
Included files:@preformatted(
.\Inc\TelemetryRecipient_MulticastEvents.pas
Contains declarations and implementations of multicast event classes.)
Last change: 2014-05-04
Change List:@unorderedList(
@item(2013-10-07 - First stable version.)
@item(2013-04-18 - Following parameters in event types were changed to
@code(TelemetryString):@unorderedList(
@itemSpacing(Compact)
@item(TChannelRegisterEvent - parameter @code(Name))
@item(TChannelUnregisterEvent - parameter @code(Name))
@item(TChannelEvent - parameter @code(Name))
@item(TConfigEvent - parameter @code(Name))))
@item(2014-04-18 - Type of parameters @code(Name) changed to
@code(TelemetryString) in following methods:
@unorderedList(
@itemSpacing(Compact)
@item(TTelemetryRecipient.ChannelHandler)
@item(TTelemetryRecipient.ChannelRegistered)
@item(TTelemetryRecipient.ChannelRegister)
@item(TTelemetryRecipient.ChannelUnregister)
@item(TTelemetryRecipient.ConfigStored)
@item(TTelemetryRecipient.ChannelStored)))
@item(2014-04-18 - Type of following fields and properties changed to
@code(TelemetryString):@unorderedList(
@itemSpacing(Compact)
@item(TTelemetryRecipient.fGameName)
@item(TTelemetryRecipient.fGameID)
@item(TTelemetryRecipient.GameName)
@item(TTelemetryRecipient.GameID)))
@item(2014-04-19 - Following multicast event classes were added:
@unorderedList(
@itemSpacing(Compact)
@item(TMulticastLogEvent)
@item(TMulticastEventRegisterEvent)
@item(TMulticastEventEvent)
@item(TMulticastChannelRegisterEvent)
@item(TMulticastChannelUnregisterEvent)
@item(TMulticastChannelEvent)
@item(TMulticastConfigEvent)))
@item(2014-04-19 - Added following multicast events:@unorderedList(
@itemSpacing(Compact)
@item(TTelemetryRecipient.OnDestroyMulti)
@item(TTelemetryRecipient.OnLogMulti)
@item(TTelemetryRecipient.OnEventRegisterMulti)
@item(TTelemetryRecipient.OnEventUnregisterMulti)
@item(TTelemetryRecipient.OnEventMulti)
@item(TTelemetryRecipient.OnChannelRegisterMulti)
@item(TTelemetryRecipient.OnChannelUnregisterMulti)
@item(TTelemetryRecipient.OnChannelMulti)
@item(TTelemetryRecipient.OnConfigMulti)))
@item(2014-04-19 - Added following methods:@unorderedList(
@itemSpacing(Compact)
@item(TTelemetryRecipient.DoOnDestroy)
@item(TTelemetryRecipient.DoOnLog)
@item(TTelemetryRecipient.DoOnEventRegister)
@item(TTelemetryRecipient.DoOnEventUnregister)
@item(TTelemetryRecipient.DoOnEvent)
@item(TTelemetryRecipient.DoOnChannelRegister)
@item(TTelemetryRecipient.DoOnChannelUnregister)
@item(TTelemetryRecipient.DoOnChannel)
@item(TTelemetryRecipient.DoOnConfig)
@item(TTelemetryRecipient.EventRegisterByIndex)
@item(TTelemetryRecipient.EventUnregisterIndex)
@item(TTelemetryRecipient.EventUnregisterByIndex)
@item(TTelemetryRecipient.ChannelRegisterByIndex)
@item(TTelemetryRecipient.ChannelRegisterByName)
@item(TTelemetryRecipient.ChannelUnregisterIndex)
@item(TTelemetryRecipient.ChannelUnregisterByIndex)
@item(TTelemetryRecipient.ChannelUnregisterByName)))
@item(2014-04-27 - Added parameter @code(ShowDescriptors) to methods
TTelemetryRecipient.EventGetDataAsString and
TTelemetryRecipient.ChannelGetValueAsString.)
@item(2014-05-01 - Added method
TTelemetryRecipient.HighestSupportedGameVersion.)
@item(2014-05-04 - Following callback functions were added:@unorderedList(
@itemSpacing(Compact)
@item(RecipientGetChannelIDFromName)
@item(RecipientGetChannelNameFromID)
@item(RecipientGetConfigIDFromName)
@item(RecipientGetConfigNameFromID))))
@html(<hr>)}
unit TelemetryRecipient;
interface
{$INCLUDE '.\Telemetry_defs.inc'}
uses
Classes,
{$IFDEF MulticastEvents}
MulticastEvent,
{$ENDIF}
TelemetryCommon,
TelemetryIDs,
TelemetryLists,
TelemetryVersionObjects,
TelemetryInfoProvider,
{$IFDEF Documentation}
TelemetryConversions,
TelemetryStrings,
{$ENDIF}
{$IFDEF UseCondensedHeader}
SCS_Telemetry_Condensed;
{$ELSE}
scssdk,
scssdk_value,
scssdk_telemetry,
scssdk_telemetry_event,
scssdk_telemetry_channel;
{$ENDIF}
{==============================================================================}
{------------------------------------------------------------------------------}
{ Declarations }
{------------------------------------------------------------------------------}
{==============================================================================}
const
// Maximum allowed channel index, see TTelemetryRecipient.ChannelRegisterAll
// method for details.
{$IFDEF MaxIndexedChannelCount8}
cMaxChannelIndex = 7;
{$ELSE}
cMaxChannelIndex = 99;
{$ENDIF}
type
// Enumerated type used in method TTelemetryRecipient.SetGameCallback to set
// one particular game callback.
TGameCallback = (gcbLog, gcbEventReg, gcbEventUnreg, gcbChannelReg, gcbChannelUnreg);
// Event type used when recipient writes to game log.
TLogEvent = procedure(Sender: TObject; LogType: scs_log_type_t; const LogText: String) of object;
// Event type used when telemetry event is registered or unregistered.
TEventRegisterEvent = procedure(Sender: TObject; Event: scs_event_t) of object;
// Event type used when telemetery event occurs.
TEventEvent = procedure(Sender: TObject; Event: scs_event_t; Data: Pointer) of object;
// Event type used when telemetry channel is registered.
TChannelRegisterEvent = procedure(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t) of Object;
// Event type used when telemetry channel is unregistered.
TChannelUnregisterEvent = procedure(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t) of Object;
// Event type used when telemetery channel callback occurs.
TChannelEvent = procedure(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t) of Object;
// Event type used when config is parsed from configuration telemetry event.
TConfigEvent = procedure(Sender: TObject; const Name: TelemetryString; ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t) of object;
{$IFDEF MulticastEvents}
{$DEFINE DeclarationPart}
{$INCLUDE '.\Inc\TelemetryRecipient_MulticastEvents.pas'}
{$UNDEF DeclarationPart}
{$ENDIF}
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryRecipient }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TTelemetryRecipient // Class declaration }
{==============================================================================}
{
@abstract(@NoAutoLink(TTelemetryRecipient) is used as a main way to control
the telemetry API.)
It provides methods for events and channels registration, unregistration and
many others. It also provides object events that wraps API event and channel
callbacks.@br
Before instance of this class is created, a check if it supports required
telemetry and game version must be performed. For that purpose, it has class
methods that can be called on class itself (before creating class instance).
If required versions are not supported, do not @noAutoLink(create) instance of
this class!
@bold(Note) - Because recipient internally creates instance of
TTelemetryInfoProvider, the provider must support required versions of
telemetry and game as well.
@member(fInfoProvider See TelemetryInfoProvider property.)
@member(fRegisteredEvents See RegisteredEvents property.)
@member(fRegisteredChannels See RegisteredChannels property.)
@member(fStoredConfigs See StoredConfigs property.)
@member(fStoredChannelsValues See StoredChannelsValues property.)
@member(fLastTelemetryResult See LastTelemetryResult property.)
@member(fTelemetryVersion See TelemetryVersion property.)
@member(fGameName See GameName property.)
@member(fGameID See GameID property.)
@member(fGameVersion See GameVersion property.)
@member(fKeepUtilityEvents See KeepUtilityEvents property.)
@member(fStoreConfigurations See StoreConfigurations property.)
@member(fManageIndexedChannels See ManageIndexedChannels property.)
@member(fStoreChannelsValues See StoreChannelsValues property.)
@member(cbLog
Holds pointer to game callback routine intended for writing messages into
game log.@br
Assigned in constructor from passed parameters, or set to @nil.)
@member(cbRegisterEvent
Holds pointer to game callback routine used for telemetry event
registration.@br
Assigned in constructor from passed parameters, or set to @nil.)
@member(cbUnregisterEvent
Holds pointer to game callback routine used for telemetry event
unregistration.@br
Assigned in constructor from passed parameters, or set to @nil.)
@member(cbRegisterChannel
Holds pointer to game callback routine used for telemetry channel
registration.@br
Assigned in constructor from passed parameters, or set to @nil.)
@member(cbUnregisterChannel
Holds pointer to game callback routine used for telemetry channel
unregistration.@br
Assigned in constructor from passed parameters, or set to @nil.)
@member(fOnDestroy Holds referece to OnDestroy event handler.)
@member(fOnLog Holds referece to OnLog event handler.)
@member(fOnEventRegister Holds referece to OnEventRegister event handler.)
@member(fOnEventUnregister Holds referece to OnEventUnregister event handler.)
@member(fOnEvent Holds referece to OnEvent event handler.)
@member(fOnChannelRegister Holds referece to OnChannelRegister event handler.)
@member(fOnChannelUnregister Holds referece to OnChannelUnregister event
handler.)
@member(fOnChannel Holds referece to OnChannel event handler.)
@member(fOnConfig Holds referece to OnConfig event handler.)
@member(fOnDestroyMulti Object managing multicast OnDestroyMulti event.)
@member(fOnLogMulti Object managing multicast OnLogMulti event.)
@member(fOnEventRegisterMulti Object managing multicast OnEventRegisterMulti
event.)
@member(fOnEventUnregisterMulti Object managing multicast OnEventUnregisterMulti
event.)
@member(fOnEventMulti Object managing multicast OnEventMulti event.)
@member(fOnChannelRegisterMulti Object managing multicast OnChannelRegisterMulti
event.)
@member(fOnChannelUnregisterMulti Object managing multicast OnChannelUnregister
event.)
@member(fOnChannelMulti Object managing multicast OnChannelMulti event.)
@member(fOnConfigMulti Object managing multicast OnConfigMulti event.)
@member(SetKeepUtilityEvents
Setter for KeepUtilityEvents property.
@param Value New value to be stored in fKeepUtilityEvents.)
@member(SetStoreConfigurations
Setter for StoreConfigurations property.
@param Value New value to be stored in fStoreConfigurations.)
@member(SetStoreChannelsValues
Setter for StoreChannelsValues property.
@param Value New value to be stored in fStoreChannelsValues.)
@member(EventHandler
Method called by plugin callback routine set to receive telemetry events.@br
OnEvent event is called and received telemetry event is then processed.
@param Event Telemetry event identification number.
@param(Data Pointer to data received alongside the telemetry event. Can be
@nil.))
@member(ChannelHandler
Method called by plugin callback routine set to receive telemetry
channels.@br
@param Name Name of received telemetry channel.
@param ID ID of received channel.
@param Index Index of received channel.
@param Value Pointer to actual value of received channel. Can be @nil.)
@member(ProcessConfigurationEvent
Method used for processing configuration events. It is called from
EventHandler method when configuration event is received and
StoreConfigurations is set to @true.@br
Received data are parsed and configuration informations are extracted and
stored in StoredConfigs list. OnConfig event is called for every extracted
config (after it is stored / its stored value changed).@br
When ManageIndexedChannels is set to @true, then indexed channels are too
managed in this method (refer to source code for details).
@param Data Structure holding actual configuration data.)
@member(PrepareForTelemetryVersion
Performs any preparations necessary to support required telemetry
version.@br
TelemetryVersion property is set in this method when successful.
@param(aTelemetryVersion Version of telemetry for which the object should be
prepared.)
@returns(@True when preparation for given version were done successfully,
otherwise @false.))
@member(PrepareForGameVersion
Performs preparations necessary to support required game and its version.@br
GameName, GameID and GameVersion properties are set in this method when
successful.
@param aGameName Name of the game.
@param aGameID Game identifier.
@param aGameVersion Version of game.
@returns(@True when preparation for given game and its version were done
successfully, otherwise @false.))
These methods: @preformatted(
HighestSupportedTelemetryVersion
SupportsTelemetryVersion
SupportsTelemetryMajorVersion
SupportsGameVersion
SupportsTelemetryAndGameVersion)
...can and actually must be called directly on class.
They should be used to check whether both this class and
TTelemetryInfoProvider class supports required telemetry and game version
before instantiation (creation of class instance).
@member(DoOnDestroy
Calls hanler(s) of OnDestroy event.)
@member(DoOnLog
Calls hanler(s) of OnLog event.)
@member(DoOnEventRegister
Calls hanler(s) of OnEventRegister event.)
@member(DoOnEventUnregister
Calls hanler(s) of OnEventUnregister event.)
@member(DoOnEvent
Calls hanler(s) of OnEvent event.)
@member(DoOnChannelRegister
Calls hanler(s) of OnChannelRegister event.)
@member(DoOnChannelUnregister
Calls hanler(s) of OnChannelUnregister event.)
@member(DoOnChannel
Calls hanler(s) of OnChannel event.)
@member(DoOnConfig
Calls hanler(s) of OnConfig event.)
@member(HighestSupportedTelemetryVersion
@returns Highest supported telemetry version.)
@member(HighestSupportedGameVersion
@param GameID Game identifier.
@returns Highest supported version of passed game.)
@member(SupportsTelemetryVersion
@param TelemetryVersion Version of telemetry.
@returns @True when given telemetry version is supported, otherwise @false.)
@member(SupportsTelemetryMajorVersion
@param TelemetryVersion Version of telemetry.
@returns(@True when given telemetry major version is supported (minor part
is ignored), otherwise @false.))
@member(SupportsGameVersion
@param GameID Game identifier.
@param GameVersion Version of game.
@returns(@True when given game and its version are supported, otherwise
@false.))
@member(SupportsTelemetryAndGameVersion
@param TelemetryVersion Version of telemetry.
@param GameID Game identifier.
@param GameVersion Version of game.
@returns(@True when given telemetry, game and its version are supported,
otherwise @false.))
@member(SupportsTelemetryAndGameVersionParam
@param TelemetryVersion Version of telemetry.
@param Parameters Structure containing other version informations.
@returns(@True when given telemetry, game and its version are supported,
otherwise @false.))
@member(Create
Object constructor.@br
If passed telemetry/game versions are not supported then an exception is
raised.
@param(TelemetryVersion Version of telemetry for which the object should
prepare.)
@param(Parameters Structure containing other parameters used in
constructor (callbacks pointers, game version,
etc.).))
@member(Destroy
Object destructor.@br
Internal objects are automatically cleared in destructor, so it is
unnecessary to free them explicitly.@br
Also, all telemetry events and channels are unregistered.)
@member(SetGameCallbacks
Use this method to set all game callbacks in one call.
@param(Parameters Structure provided by telemetry API that contains all
necessary callback pointers.))
@member(SetGameCallback
Use this method to set one specific game callback.@br
Can be used to set specific callback to nil and thus disabling it (all
calls to any callback are preceded by check for assignment).
@bold(Warning) - @code(CallbackFunction) pointer is not checked for actual
type.
@param(Callback Indicates to which callback assign given function
pointer from second parameter.)
@param CallbackFunction Pointer to be assigned.)
@member(EventRegistered
Checks whether given event is present in RegisteredEvents list, when
included, it is assumed that this event is registered in telemetry API.
@param Event Event to be checked.
@returns @True when given event is found in list, otherwise @false.)
@member(EventRegister
Registers specific telemetry event.@br
Works only when cbRegisterEvent callback is assigned, when it is not,
function returns false and LastTelemetryResult is set to
@code(SCS_RESULT_generic_error).
@param Event Event to be registered.
@returns(@True when registration was successful, otherwise @false (property
LastTelemetryResult contains result code).))
@member(EventRegisterByIndex
Registers telemetry event that is listed in known events list at position
given by @code(Index) parameter. When index falls out of allowed boundaries,
no event is registered and function returns @false.
@param Index Index of requested event in known events list.
@returns @True when requested event was registered, @false otherwise.)
@member(EventUnregister
Unregisters specific telemetry event.@br
Works only when cbUnregisterEvent callback is assigned, when it is not,
function returns false and LastTelemetryResult is set to
@code(SCS_RESULT_generic_error).
@param Event Event to be unregistered.
@returns(@True when unregistration was successful, otherwise @false
(property LastTelemetryResult contains result code).))
@member(EventUnregisterIndex
Unregister telemetry event that is listed in registered events list at
position given by @code(Index) parameter.@br
When index falls out of allowed boundaries, no channel is unregistered and
function returns @false.
@param Index Index of event in registered events list.
@returns @True when requested event was unregistered, @false otherwise.)
@member(EventUnregisterByIndex
Unregisters telemetry event that is listed in known events list at position
given by @code(Index) parameter. When index falls out of allowed boundaries,
no event is unregistered and function returns @false.
@param Index Index of requested event in known events list.
@returns @True when requested event was unregistered, @false otherwise.)
@member(EventRegisterAll
Registers all events that TTelemetryInfoProvider class is aware of for
current telemetry and game version.
@returns Number of successfully registered events.)
@member(EventUnregisterAll
Unregisters all events listed in RegisteredEvents list.
@returns Number of successfully unregistered events.)
@member(EventGetDataAsString
Returns textual representation of event data (e.g. for displaying to user).
If no data can be converted to text, only name of event is returned. When
@code(TypeName) is set to true, all values are marked with type identifiers.
@param Event Type of event that is converted to text.
@param Data Data for given event. Can be @nil.
@param(TypeName Indicating whether type identifiers should be
included in resulting text.)
@param(ShowDescriptors When set, fields descriptors are shown for composite
values.)
@returns Textual representation of event (event name) and its data.)
@member(ChannelRegistered
Checks whether given channel is present in RegisteredChannels list, when
included, it is assumed that this channel is registered in telemetry API.
@param Name Name of channel to be checked.
@param Index Index of channel.
@param ValueType Value type of checked channel.
@returns @True when given channel is found in list, otherwise @false.)
@member(ChannelRegister
Registers specific telemetry channel.@br
Works only when cbRegisterChannel callback is assigned, when it is not,
function returns false and LastTelemetryResult is set to
@code(SCS_RESULT_generic_error).
@param Name Name of registered channel.
@param Index Index of registered channel.
@param ValueType Value type of registered channel.
@param Flags Registration flags.
@returns(@True when registration was successful, otherwise @false (property
LastTelemetryResult contains result code).))
@member(ChannelRegisterByIndex
Registers telemetry channel that is listed in known channels list at
position given by @code(Index) parameter.@br
When channel is marked as indexed then all index-versions of such channel
are registered.@br
Channel is registered only for its primary value type.@br
When index falls out of allowed boundaries, no channel is registered and
function returns @false.
@param Index Index of requested channel in known channels list.
@returns @True when requested channel was registered, @false otherwise.)
@member(ChannelRegisterByName
Registers telemetry channel of given name. Channel of this name must be
listed in known channels list as other informations required for
registration are taken from there.@br
When channel is marked as indexed then all index-versions of such channel
are registered.@br
Channel is registered only for its primary value type.@br
When channel of given name is not listed between known channels, then no
channel is registered and function returns @false.
@param Name Name of channel to be registered.
@returns @True when requested channel was registered, @false otherwise.)
@member(ChannelUnregister
Unregister specific telemetry channel.
Works only when cbUnregisterChannel callback is assigned, when it is not,
function returns false and LastTelemetryResult is set to
@code(SCS_RESULT_generic_error).
@param Name Name of channel to be unregistered.
@param Index Index of channel.
@param ValueType Value type of channel.
@returns(@True when unregistration was successful, otherwise @false
(property LastTelemetryResult contains result code).))
@member(ChannelUnregisterIndex
Unregister telemetry channel that is listed in registered channels list at
position given by @code(Index) parameter.@br
When index falls out of allowed boundaries, no channel is unregistered and
function returns @false.
@param Index Index of channel in registered channels list.
@returns @True when requested channel was unregistered, @false otherwise.)
@member(ChannelUnregisterByIndex
Unregisters all registered telemetry channels with the same name as channel
that is listed in known channels list at position given by @code(Index)
parameter.@br
When index falls out of allowed boundaries, no channel is unregistered and
function returns @false.
@param Index Index of requested channel in known channels list.
@returns @True when requested channel was unregistered, @false otherwise.)
@member(ChannelUnregisterByName
Unregisters all registered telemetry channels with the given name.@br
@param Name Name of channel(s) to be unregistered.
@returns @True when requested channel was unregistered, @false otherwise.)
@member(ChannelRegisterAll
This method registers all channels that the TTelemetryInfoProvider class is
aware of for current telemetry and game version.@br
When channel is marked as indexed, then all channel and index combinations
are registered (see implementation of this method for details), otherwise
only channels with index set to SCS_U32_NIL are registered. When
ManageIndexedChannels and StoreConfigurations properties are both set to
@true, then top index for indexed channel registration is taken from
appropriate stored configuration value.@br
Set RegPrimaryTypes, RegSecondaryTypes and RegTertiaryTypes to true to
register respective channel value type. If all three parameters are set
to false, the method executes but nothing is registered.
@param RegPrimaryTypes Register primary value type.
@param RegSecondaryTypes Register secondary value type.
@param RegTertiaryTypes Register tertiary value type.
@Returns Number of successfully registered channels.)
@member(ChannelUnregisterAll
Unregisters all channels listed in RegisteredChannels list.
@returns Number of successfully unregistered channels.)
@member(ChannelGetValueAsString
Returns textual representation of channel value.
When @code(TypeName) is set to true, all values are marked with type
identifiers.
@param Value Pointer to actual channel value. Can be @nil.
@param(TypeName Indicating whether type identifiers should be
included in resulting text.)
@param(ShowDescriptors When set, fields descriptors are shown for composite
values.)
@returns(Textual representation of channel value, an empty string when
value is not assigned.))
@member(ConfigStored
Checks whether given config is stored in StoredConfigs list.
@param Name Name of checked configuration.
@param Index Index of checked configuration.
@returns @True when given config is found in list, otherwise @false.)
@member(ChannelStored
Checks whether given channel is stored in StoredChannelValues list.
@param Name Name of checked channel.
@param Index Index of checked channel.
@param ValueType Value type of checked channel.
@returns @True when given channel is found in list, otherwise @false.)
@member(TelemetryInfoProvider
This object provides lists of known events, channels and configs along with
some methods around these lists/structures.@br
Its main use is in registration of all known events and channels.@br
It is created in constructor as automatically managed, so the lists are
filled automatically accordingly to telemetry and game versions passed to
it.)
@member(RegisteredEvents
Internal list that stores contexts for registered events.@br
Its content is manager automatically during telemetry events
(un)registrations.)
@member(RegisteredChannels
Internal list that stores contexts for registered channel.@br
Its content is manager automatically during telemetry channels
(un)registrations.)
@member(StoredConfigs
Internal list used to store received configurations when StoreConfigurations
switch is set to @true.)
@member(StoredChannelsValues
Internal list used to store received channels values when
StoreChannelsValues switch is set to @true.)
@member(LastTelemetryResult
Result code of last executed API function.@br
Initialized to SCS_RESULT_ok.)
@member(TelemetryVersion
Telemetry version for which this object was created.@br
Initialized to SCS_U32_NIL.)
@member(GameName
Name of the game for which this object was created.@br
Initialized to an empty string.)
@member(GameID
ID of game for which this object was created.@br
Initialized to an empty string.)
@member(GameVersion
Version of game for which this object was created.@br
Initialized to an SCS_U32_NIL.)
@member(KeepUtilityEvents
When set to @true, the recipient automatically registers all known events
marked as utility and refuses to unregister such events.@br
This property is intended to ensure the recipient will stay responsive,
because events and channels can be (un)registered only in events callbacks.
If no event would be registered, then such call will not occur, rendering
recipient unresponsive.@br
Initialized to @true.)
@member(StoreConfigurations
If @true, any configuration data passed from the game are parsed and
stored.@br
When set to @true, the configuration event is automatically registered.@br
When set to @false, StoredConfigs list is cleared.@br
Initialized to @true.)
@member(ManageIndexedChannels
When @true, registration and unregistration of indexed channels that are
index-binded to some configuration is automatically managed.@br
Affected methods:
@unorderedList(
@item(ChannelRegisterAll - binded channels are registered up to index
(count - 1) stored in appropriate config. If such config is not stored,
they are registered in the same way as not binded channels.)
@item(ProcessConfigurationEvent - when binded config is parsed, all
registered channels are scanned and those binded to this config are
proccessed in following way:@br
New config value is greater than old value: channels with indices
above new config value are unregistered.@br
New config value is smaller than old value: when channels with all
indices from old config value are registered, then new channels with
indices up to the new value are registered.))
Initialized to @false.)
@member(StoreChannelsValues
When @true, all incoming channels along with their values are stored in
StoredChannelsValues list.@br
When set to @false, StoredChannelsValues list is cleared.@br
Initialized to @false.)
@member(OnDestroy
Event called before destruction of instance. It is called AFTER all
registered channels and events are unregistered and KeepUtilityEvents is set
to @false.)
@member(OnLog
Event called when recipient attempts to write to game log.)
@member(OnEventRegister
Event called on every @bold(successful) event registration.@br
It can be called multiple times when method EventRegisterAll is executed.)
@member(OnEventUnregister
Event called on every @bold(successful) event unregistration.@br
It can be called multiple times when method EventUnregisterAll is executed.)
@member(OnEvent
Event called whenever the recipient receives any event from telemetry API.)
@member(OnChannelRegister
Event called on every @bold(successful) channel registration.@br
It can be called multiple times when method ChannelRegisterAll is executed.)
@member(OnChannelUnregister
Event called on every @bold(successful) channel unregistration.@br
It can be called multiple times when method ChannelUnregisterAll is
executed.)
@member(OnChannel
Event called whenever the recipient receives any channel call from telemetry
API.
@bold(Warning) - this event can be called quite often (usually many times
per frame).)
@member(OnConfig
Event called when config is parsed from configuration telemetry event data
(possible only when StoreConfigurations is set to true).)
@member(OnDestroyMulti
Multicast event called before destruction of instance. It is called AFTER
all registered channels and events are unregistered and KeepUtilityEvents is
set to @false.)
@member(OnLogMulti
Multicast event called when recipient attempts to write to game log.)
@member(OnEventRegisterMulti
Multicast event called on every @bold(successful) event registration.@br
It can be called multiple times when method EventRegisterAll is executed.)
@member(OnEventUnregisterMulti
Multicast event called on every @bold(successful) event unregistration.@br
It can be called multiple times when method EventUnregisterAll is executed.)
@member(OnEventMulti
Multicast event called whenever the recipient receives any event from
telemetry API.)
@member(OnChannelRegisterMulti
Multicast event called on every @bold(successful) channel registration.@br
It can be called multiple times when method ChannelRegisterAll is executed.)
@member(OnChannelUnregisterMulti
Multicast event called on every @bold(successful) channel unregistration.@br
It can be called multiple times when method ChannelUnregisterAll is
executed.)
@member(OnChannelMulti
Multicast event called whenever the recipient receives any channel call from
telemetry API.
@bold(Warning) - this event can be called quite often (usually many times
per frame).)
@member(OnConfigMulti
Multicast event called when config is parsed from configuration telemetry
event data (possible only when StoreConfigurations is set to true).)
}
TTelemetryRecipient = class(TTelemetryVersionPrepareObject)
private
fInfoProvider: TTelemetryInfoProvider;
fRegisteredEvents: TRegisteredEventsList;
fRegisteredChannels: TRegisteredChannelsList;
fStoredConfigs: TStoredConfigsList;
fStoredChannelsValues: TStoredChannelsValuesList;
fLastTelemetryResult: scs_result_t;
fTelemetryVersion: scs_u32_t;
fGameName: TelemetryString;
fGameID: TelemetryString;
fGameVersion: scs_u32_t;
fKeepUtilityEvents: Boolean;
fStoreConfigurations: Boolean;
fManageIndexedChannels: Boolean;
fStoreChannelsValues: Boolean;
cbLog: scs_log_t;
cbRegisterEvent: scs_telemetry_register_for_event_t;
cbUnregisterEvent: scs_telemetry_unregister_from_event_t;
cbRegisterChannel: scs_telemetry_register_for_channel_t;
cbUnregisterChannel: scs_telemetry_unregister_from_channel_t;
fOnDestroy: TNotifyEvent;
fOnLog: TLogEvent;
fOnEventRegister: TEventRegisterEvent;
fOnEventUnregister: TEventRegisterEvent;
fOnEvent: TEventEvent;
fOnChannelRegister: TChannelRegisterEvent;
fOnChannelUnregister: TChannelUnregisterEvent;
fOnChannel: TChannelEvent;
fOnConfig: TConfigEvent;
{$IFDEF MulticastEvents}
fOnDestroyMulti: TMulticastNotifyEvent;
fOnLogMulti: TMulticastLogEvent;
fOnEventRegisterMulti: TMulticastEventRegisterEvent;
fOnEventUnregisterMulti: TMulticastEventRegisterEvent;
fOnEventMulti: TMulticastEventEvent;
fOnChannelRegisterMulti: TMulticastChannelRegisterEvent;
fOnChannelUnregisterMulti: TMulticastChannelUnregisterEvent;
fOnChannelMulti: TMulticastChannelEvent;
fOnConfigMulti: TMulticastConfigEvent;
{$ENDIF}
procedure SetKeepUtilityEvents(Value: Boolean);
procedure SetStoreConfigurations(Value: Boolean);
procedure SetStoreChannelsValues(Value: Boolean);
protected
procedure EventHandler(Event: scs_event_t; Data: Pointer); virtual;
procedure ChannelHandler(const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t); virtual;
procedure ProcessConfigurationEvent(const Data: scs_telemetry_configuration_t); virtual;
Function PrepareForTelemetryVersion(TelemetryVersion: scs_u32_t): Boolean; override;
Function PrepareForGameVersion(const GameName,GameID: TelemetryString; GameVersion: scs_u32_t): Boolean; override;
public
procedure DoOnDestroy(Sender: TObject); virtual;
procedure DoOnLog(Sender: TObject; LogType: scs_log_type_t; const LogText: String); virtual;
procedure DoOnEventRegister(Sender: TObject; Event: scs_event_t); virtual;
procedure DoOnEventUnregister(Sender: TObject; Event: scs_event_t); virtual;
procedure DoOnEvent(Sender: TObject; Event: scs_event_t; Data: Pointer); virtual;
procedure DoOnChannelRegister(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t); virtual;
procedure DoOnChannelUnregister(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t); virtual;
procedure DoOnChannel(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t); virtual;
procedure DoOnConfig(Sender: TObject; const Name: TelemetryString; ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t); virtual;
class Function HighestSupportedTelemetryVersion: scs_u32_t; override;
class Function HighestSupportedGameVersion(GameID: scs_string_t): scs_u32_t; override;
class Function SupportsTelemetryVersion(TelemetryVersion: scs_u32_t): Boolean; override;
class Function SupportsTelemetryMajorVersion(TelemetryVersion: scs_u32_t): Boolean; override;
class Function SupportsGameVersion(GameID: scs_string_t; GameVersion: scs_u32_t): Boolean; override;
class Function SupportsTelemetryAndGameVersion(TelemetryVersion: scs_u32_t; GameID: scs_string_t; GameVersion: scs_u32_t): Boolean; override;
class Function SupportsTelemetryAndGameVersionParam(TelemetryVersion: scs_u32_t; Parameters: scs_telemetry_init_params_t): Boolean; override;
constructor Create(TelemetryVersion: scs_u32_t; Parameters: scs_telemetry_init_params_t);
destructor Destroy; override;
procedure SetGameCallbacks(Parameters: scs_telemetry_init_params_t); virtual;
procedure SetGameCallback(Callback: TGameCallback; CallbackFunction: Pointer); virtual;
{
Use this method to write typed message to game log.@br
Works only when cbLog callback is assigned.
@param(LogType Type of message (i.e. if it is error, warning or
normal message).)
@param LogText Actual message text.
}
procedure Log(LogType: scs_log_type_t; const LogText: String); overload; virtual;
{
Use this method to write message to game log. Message will be written as
normal text (LogType set to SCS_LOG_TYPE_message).@br
Works only when cbLog callback is assigned.
@param LogText Actual message text.
}
procedure Log(const LogText: String); overload; virtual;
Function EventRegistered(Event: scs_event_t): Boolean; virtual;
Function EventRegister(Event: scs_event_t): Boolean; virtual;
Function EventRegisterByIndex(Index: Integer): Boolean; virtual;
Function EventUnregister(Event: scs_event_t): Boolean; virtual;
Function EventUnregisterIndex(Index: Integer): Boolean; virtual;
Function EventUnregisterByIndex(Index: Integer): Boolean; virtual;
Function EventRegisterAll: Integer; virtual;
Function EventUnregisterAll: Integer; virtual;
Function EventGetDataAsString(Event: scs_event_t; Data: Pointer; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String; virtual;
Function ChannelRegistered(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Boolean; virtual;
Function ChannelRegister(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t = SCS_TELEMETRY_CHANNEL_FLAG_none): Boolean; virtual;
Function ChannelRegisterByIndex(Index: Integer): Boolean; virtual;
Function ChannelRegisterByName(const Name: TelemetryString): Boolean; virtual;
Function ChannelUnregister(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Boolean; virtual;
Function ChannelUnregisterIndex(Index: Integer): Boolean; virtual;
Function ChannelUnregisterByIndex(Index: Integer): Boolean; virtual;
Function ChannelUnregisterByName(const Name: TelemetryString): Boolean; virtual;
Function ChannelRegisterAll(RegPrimaryTypes: Boolean = True; RegSecondaryTypes: Boolean = False; RegTertiaryTypes: Boolean = False): Integer; virtual;
Function ChannelUnregisterAll: Integer; virtual;
Function ChannelGetValueAsString(Value: p_scs_value_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String; virtual;
Function ConfigStored(const Name: TelemetryString; Index: scs_u32_t = SCS_U32_NIL): Boolean; virtual;
Function ChannelStored(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Boolean; virtual;
published
property TelemetryInfoProvider: TTelemetryInfoProvider read fInfoProvider;
property RegisteredEvents: TRegisteredEventsList read fRegisteredEvents;
property RegisteredChannels: TRegisteredChannelsList read fRegisteredChannels;
property StoredConfigs: TStoredconfigsList read fStoredConfigs;
property StoredChannelsValues: TStoredChannelsValuesList read fStoredChannelsValues write fStoredChannelsValues;
property LastTelemetryResult: scs_result_t read fLastTelemetryResult;
property TelemetryVersion: scs_u32_t read fTelemetryVersion;
property GameName: TelemetryString read fGameName;
property GameID: TelemetryString read fGameID;
property GameVersion: scs_u32_t read fGameVersion;
property KeepUtilityEvents: Boolean read fKeepUtilityEvents write SetKeepUtilityEvents;
property StoreConfigurations: Boolean read fStoreConfigurations write SetStoreConfigurations;
property ManageIndexedChannels: Boolean read fManageIndexedChannels write fManageIndexedChannels;
property StoreChannelsValues: Boolean read fStoreChannelsValues write SetStoreChannelsValues;
property OnDestroy: TNotifyEvent read fOnDestroy write fOnDestroy;
property OnLog: TLogEvent read fOnLog write fOnLog;
property OnEventRegister: TEventRegisterEvent read fOnEventRegister write fOnEventRegister;
property OnEventUnregister: TEventRegisterEvent read fOnEventUnregister write fOnEventUnregister;
property OnEvent: TEventEvent read fOnEvent write fOnEvent;
property OnChannelRegister: TChannelRegisterEvent read fOnChannelRegister write fOnChannelRegister;
property OnChannelUnregister: TChannelUnregisterEvent read fOnChannelUnregister write fOnChannelUnregister;
property OnChannel: TChannelEvent read fOnChannel write fOnChannel;
property OnConfig: TConfigEvent read fOnConfig write fOnConfig;
{$IFDEF MulticastEvents}
property OnDestroyMulti: TMulticastNotifyEvent read fOnDestroyMulti;
property OnLogMulti: TMulticastLogEvent read fOnLogMulti;
property OnEventRegisterMulti: TMulticastEventRegisterEvent read fOnEventRegisterMulti;
property OnEventUnregisterMulti: TMulticastEventRegisterEvent read fOnEventUnregisterMulti;
property OnEventMulti: TMulticastEventEvent read fOnEventMulti;
property OnChannelRegisterMulti: TMulticastChannelRegisterEvent read fOnChannelRegisterMulti;
property OnChannelUnregisterMulti: TMulticastChannelUnregisterEvent read fOnChannelUnregisterMulti;
property OnChannelMulti: TMulticastChannelEvent read fOnChannelMulti;
property OnConfigMulti: TMulticastConfigEvent read fOnConfigMulti;
{$ENDIF}
end;
{==============================================================================}
{ Unit Functions and procedures // Declaration }
{==============================================================================}
{
@abstract(Function intended as callback for streaming functions, converting
channel name to ID.)
@code(UserData) passed to streaming function along with this callback must
contain valid TTelemetryRecipient object.
@param Name Channel name to be converted to ID.
@param(Recipient TTelemetryRecipient object that will be used for actual
conversion.)
@returns Channel ID obtained from passed name.
}
Function RecipientGetChannelIDFromName(const Name: TelemetryString; Recipient: Pointer): TChannelID;
{
@abstract(Function intended as callback for streaming functions, converting
channel ID to name.)
@code(UserData) passed to streaming function along with this callback must
contain valid TTelemetryRecipient object.
@param ID Channel ID to be converted to name.
@param(Recipient TTelemetryRecipient object that will be used for actual
conversion.)
@returns Channel name obtained from passed ID.
}
Function RecipientGetChannelNameFromID(ID: TChannelID; Recipient: Pointer): TelemetryString;
{
@abstract(Function intended as callback for streaming functions, converting
config name to ID.)
@code(UserData) passed to streaming function along with this callback must
contain valid TTelemetryRecipient object.
@param Name Config name to be converted to ID.
@param(Recipient TTelemetryRecipient object that will be used for actual
conversion.)
@returns Config ID obtained from passed name.
}
Function RecipientGetConfigIDFromName(const Name: TelemetryString; Recipient: Pointer): TConfigID;
{
@abstract(Function intended as callback for streaming functions, converting
ID to config name.)
@code(UserData) passed to streaming function along with this callback must
contain valid TTelemetryRecipient object.
@param ID Config ID to be converted to name.
@param(Recipient TTelemetryRecipient object that will be used for actual
conversion.)
@returns Config name obtained from passed ID.
}
Function RecipientGetConfigNameFromID(ID: TConfigID; Recipient: Pointer): TelemetryString;
implementation
uses
SysUtils, Math,
TelemetryConversions, TelemetryStrings;
{$IFDEF MulticastEvents}
{$DEFINE ImplementationPart}
{$INCLUDE '.\Inc\TelemetryRecipient_MulticastEvents.pas'}
{$UNDEF ImplementationPart}
{$ENDIF}
{==============================================================================}
{ Unit Functions and procedures // Implementation }
{==============================================================================}
Function RecipientGetChannelIDFromName(const Name: TelemetryString; Recipient: Pointer): TChannelID;
begin
Result := TTelemetryRecipient(Recipient).TelemetryInfoProvider.KnownChannels.ChannelNameToID(Name);
end;
//------------------------------------------------------------------------------
Function RecipientGetChannelNameFromID(ID: TChannelID; Recipient: Pointer): TelemetryString;
begin
Result := TTelemetryRecipient(Recipient).TelemetryInfoProvider.KnownChannels.ChannelIDToName(ID);
end;
//------------------------------------------------------------------------------
Function RecipientGetConfigIDFromName(const Name: TelemetryString; Recipient: Pointer): TConfigID;
begin
Result := TTelemetryRecipient(Recipient).TelemetryInfoProvider.KnownConfigs.ConfigNameToID(Name);
end;
//------------------------------------------------------------------------------
Function RecipientGetConfigNameFromID(ID: TConfigID; Recipient: Pointer): TelemetryString;
begin
Result := TTelemetryRecipient(Recipient).TelemetryInfoProvider.KnownConfigs.ConfigIDToName(ID);
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ Plugin (library) callbacks }
{------------------------------------------------------------------------------}
{==============================================================================}
{
Following two procedures are passed to game as plugin/library callbacks, because
methods (of the TTelemetryRecipient) cannot be passed to API (method pointers
and function/procedure pointers are fundamentally different - see
ObjectPascal/Delphi documentation).
They are implemented pretty much only as wrappers to recipient methods.
}
// Procedure used as library callback to receive events.
procedure EventReceiver(event: scs_event_t; event_info: Pointer; context: scs_context_t); stdcall;
begin
If Assigned(context) then
If Assigned(PEventContext(context)^.Recipient) then
TTelemetryRecipient(PEventContext(context)^.Recipient).EventHandler(event,event_info);
end;
//------------------------------------------------------------------------------
// Procedure used as library callback to receive channels.
procedure ChannelReceiver(name: scs_string_t; index: scs_u32_t; value: p_scs_value_t; context: scs_context_t); stdcall;
begin
If Assigned(context) then
If Assigned(PChannelContext(context)^.Recipient) then
with PChannelContext(context)^ do
TTelemetryRecipient(Recipient).ChannelHandler(APIStringToTelemetryString(name),ChannelInfo.ID,index,value);
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryRecipient }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TTelemetryRecipient // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryRecipient // Constants, types, variables, etc... }
{------------------------------------------------------------------------------}
const
// Default (initial) values for TTelemeryRecipient properties.
def_KeepUtilityEvents = True;
def_StoreConfigurations = True;
def_ManageIndexedChannels = False;
def_StoreChannelsValues = False;
{------------------------------------------------------------------------------}
{ TTelemetryRecipient // Private methods }
{------------------------------------------------------------------------------}
procedure TTelemetryRecipient.SetKeepUtilityEvents(Value: Boolean);
var
i: Integer;
begin
If fKeepUtilityEvents <> Value then
begin
If Value then
For i := 0 to (fInfoProvider.KnownEvents.Count - 1) do
If fInfoProvider.KnownEvents[i].Utility and
not EventRegistered(fInfoProvider.KnownEvents[i].Event) then
EventRegister(fInfoProvider.KnownEvents[i].Event);
fKeepUtilityEvents := Value;
end;
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.SetStoreConfigurations(Value: Boolean);
begin
If fStoreConfigurations <> Value then
begin
If Value then
begin
If not EventRegistered(SCS_TELEMETRY_EVENT_configuration) then
fStoreConfigurations := EventRegister(SCS_TELEMETRY_EVENT_configuration)
else fStoreConfigurations := Value;
end
else fStoreConfigurations := Value;
end;
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.SetStoreChannelsValues(Value: Boolean);
begin
If fStoreChannelsValues <> Value then
begin
If not Value then fStoredChannelsValues.Clear;
fStoreChannelsValues := Value;
end;
end;
{------------------------------------------------------------------------------}
{ TTelemetryRecipient // Protected methods }
{------------------------------------------------------------------------------}
procedure TTelemetryRecipient.EventHandler(Event: scs_event_t; Data: Pointer);
begin
DoOnEvent(Self,Event,Data);
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.ChannelHandler(const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t);
begin
DoOnChannel(Self,Name,Id,Index,Value);
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.ProcessConfigurationEvent(const Data: scs_telemetry_configuration_t);
var
TempName: TelemetryString;
TempAttr: p_scs_named_value_t;
TempValue: scs_value_localized_t;
procedure ManageBindedChannels(ConfigID: TConfigID; NewMaxIndex: scs_u32_t);
var
i,j: Integer;
// New channels can be registered only if all old indexes were used (i.e.
// all channels for given index were registered, and number of them was
// greater than zero).
Function CanRegisterNew(ChannelID: TChannelID): Boolean;
var
ii: Integer;
OldMaxIndex: scs_u32_t;
Counter: LongWord;
begin
OldMaxIndex := 0;
Counter := 0;
ii := fStoredConfigs.IndexOf(ConfigID);
If ii >= 0 then
If fStoredConfigs[ii].Value.ValueType = SCS_VALUE_TYPE_u32 then
OldMaxIndex := fStoredConfigs[ii].Value.BinaryData.value_u32.value - 1;
For ii := 0 to OldMaxIndex do
If fRegisteredChannels.IndexOf(ChannelID,ii) >= 0 then Inc(Counter);
Result := Counter > OldMaxIndex;
end;
begin
// Unregister all channels above current max index.
For i := (fRegisteredChannels.Count - 1) downto 0 do
If fRegisteredChannels[i].IndexConfigID = ConfigID then
If fRegisteredChannels[i].Index > NewMaxIndex then
ChannelUnregister(fRegisteredChannels[i].Name,fRegisteredChannels[i].Index,fRegisteredChannels[i].ValueType);
// Register new channels up to current max index.
For i := 0 to (fInfoProvider.KnownChannels.Count - 1) do
If fInfoProvider.KnownChannels[i].IndexConfigID = ConfigID then
If CanRegisterNew(fInfoProvider.KnownChannels[i].ID) then
For j := 0 to NewMaxIndex do
If not ChannelRegistered(fInfoProvider.KnownChannels[i].Name,j,fInfoProvider.KnownChannels[i].PrimaryType) then
ChannelRegister(fInfoProvider.KnownChannels[i].Name,j,fInfoProvider.KnownChannels[i].PrimaryType,SCS_TELEMETRY_CHANNEL_FLAG_none);
end;
begin
TempAttr := Data.attributes;
while Assigned(TempAttr^.name) do
begin
TempName := APIStringToTelemetryString(Data.id) + cConfigFieldsSeparator + APIStringToTelemetryString(TempAttr^.name);
TempValue := scs_value_localized(TempAttr^.value);
If ManageIndexedChannels then
If (TempAttr^.value._type = SCS_VALUE_TYPE_u32) and fInfoProvider.KnownConfigs.IsBinded(TempName) then
ManageBindedChannels(GetItemID(TempName),TempAttr^.value.value_u32.value - 1);
If fStoredConfigs.ChangeConfigValue(TempName,TempAttr^.index,TempValue) < 0 then
fStoredConfigs.Add(TempName,TempAttr^.index,TempValue,fInfoProvider.KnownConfigs.IsBinded(TempName));
DoOnConfig(Self,TempName,GetItemID(TempName),TempAttr^.index,TempValue);
Inc(TempAttr);
end;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.PrepareForTelemetryVersion(TelemetryVersion: scs_u32_t): Boolean;
begin
Result := inherited PrepareForTelemetryVersion(TelemetryVersion);
If Result then fTelemetryVersion := TelemetryVersion;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.PrepareForGameVersion(const GameName,GameID: TelemetryString; GameVersion: scs_u32_t): Boolean;
begin
Result := inherited PrepareForGameVersion(GameName,GameID,GameVersion);
If Result then
begin
fGameName := GameName;
fGameID := GameID;
fGameVersion := GameVersion;
end;
end;
{------------------------------------------------------------------------------}
{ TTelemetryRecipient // Public methods }
{------------------------------------------------------------------------------}
procedure TTelemetryRecipient.DoOnDestroy(Sender: TObject);
begin
If Assigned(fOnDestroy) then fOnDestroy(Sender);
{$IFDEF MulticastEvents}
fOnDestroyMulti.Call(Sender);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.DoOnLog(Sender: TObject; LogType: scs_log_type_t; const LogText: String);
begin
If Assigned(fOnLog) then fOnLog(Sender,LogType,LogText);
{$IFDEF MulticastEvents}
fOnLogMulti.Call(Sender,LogType,LogText);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.DoOnEventRegister(Sender: TObject; Event: scs_event_t);
begin
If Assigned(fOnEventRegister) then fOnEventRegister(Sender,Event);
{$IFDEF MulticastEvents}
fOnEventRegisterMulti.Call(Sender,Event);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.DoOnEventUnregister(Sender: TObject; Event: scs_event_t);
begin
If Assigned(fOnEventUnregister) then fOnEventUnregister(Sender,Event);
{$IFDEF MulticastEvents}
fOnEventUnregisterMulti.Call(Sender,Event);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.DoOnEvent(Sender: TObject; Event: scs_event_t; Data: Pointer);
begin
If (Event = SCS_TELEMETRY_EVENT_configuration) and StoreConfigurations then
ProcessConfigurationEvent(p_scs_telemetry_configuration_t(Data)^);
If Assigned(fOnEvent) then fOnEvent(Sender,Event,Data);
{$IFDEF MulticastEvents}
fOnEventMulti.Call(Sender,Event,Data);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.DoOnChannelRegister(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t);
begin
If Assigned(fOnChannelRegister) then fOnChannelRegister(Sender,Name,ID,Index,ValueType,Flags);
{$IFDEF MulticastEvents}
fOnChannelRegisterMulti.Call(Sender,Name,ID,Index,ValueType,Flags);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.DoOnChannelUnregister(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t);
begin
If Assigned(fOnChannelUnregister) then fOnChannelUnregister(Sender,Name,ID,Index,ValueType);
{$IFDEF MulticastEvents}
fOnChannelUnregisterMulti.Call(Sender,Name,ID,Index,ValueType);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.DoOnChannel(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t);
begin
If StoreChannelsValues then fStoredChannelsValues.StoreChannelValue(Name,ID,Index,Value);
If Assigned(fOnChannel) then fOnChannel(Sender,Name,ID,Index,Value);
{$IFDEF MulticastEvents}
fOnChannelMulti.Call(Sender,Name,ID,Index,Value);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.DoOnConfig(Sender: TObject; const Name: TelemetryString; ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t);
begin
If Assigned(fOnConfig) then fOnConfig(Sender,Name,ID,Index,Value);
{$IFDEF MulticastEvents}
fOnConfigMulti.Call(Sender,Name,ID,Index,Value);
{$ENDIF}
end;
//------------------------------------------------------------------------------
class Function TTelemetryRecipient.HighestSupportedTelemetryVersion: scs_u32_t;
begin
Result := Min(inherited HighestSupportedTelemetryVersion,
TTelemetryInfoProvider.HighestSupportedTelemetryVersion);
end;
//------------------------------------------------------------------------------
class Function TTelemetryRecipient.HighestSupportedGameVersion(GameID: scs_string_t): scs_u32_t;
begin
Result := Min(inherited HighestSupportedGameVersion(GameID),
TTelemetryInfoProvider.HighestSupportedGameVersion(GameID));
end;
//------------------------------------------------------------------------------
class Function TTelemetryRecipient.SupportsTelemetryVersion(TelemetryVersion: scs_u32_t): Boolean;
begin
Result := inherited SupportsTelemetryVersion(TelemetryVersion) and
TTelemetryInfoProvider.SupportsTelemetryVersion(TelemetryVersion);
end;
//------------------------------------------------------------------------------
class Function TTelemetryRecipient.SupportsTelemetryMajorVersion(TelemetryVersion: scs_u32_t): Boolean;
begin
Result := inherited SupportsTelemetryMajorVersion(TelemetryVersion) and
TTelemetryInfoProvider.SupportsTelemetryMajorVersion(TelemetryVersion);
end;
//------------------------------------------------------------------------------
class Function TTelemetryRecipient.SupportsGameVersion(GameID: scs_string_t; GameVersion: scs_u32_t): Boolean;
begin
Result := inherited SupportsGameVersion(GameID,GameVersion) and
TTelemetryInfoProvider.SupportsGameVersion(GameID,GameVersion);
end;
//------------------------------------------------------------------------------
class Function TTelemetryRecipient.SupportsTelemetryAndGameVersion(TelemetryVersion: scs_u32_t; GameID: scs_string_t; GameVersion: scs_u32_t): Boolean;
begin
Result := inherited SupportsTelemetryAndGameVersion(TelemetryVersion,GameID,GameVersion) and
TTelemetryInfoProvider.SupportsTelemetryAndGameVersion(TelemetryVersion,GameID,GameVersion);
end;
//------------------------------------------------------------------------------
class Function TTelemetryRecipient.SupportsTelemetryAndGameVersionParam(TelemetryVersion: scs_u32_t; Parameters: scs_telemetry_init_params_t): Boolean;
begin
Result := inherited SupportsTelemetryAndGameVersionParam(TelemetryVersion,Parameters) and
TTelemetryInfoProvider.SupportsTelemetryAndGameVersionParam(TelemetryVersion,Parameters);
end;
//------------------------------------------------------------------------------
constructor TTelemetryRecipient.Create(TelemetryVersion: scs_u32_t; Parameters: scs_telemetry_init_params_t);
begin
inherited Create;
// These fields are filled in preparation routines, so they must be initialized
// before these routines are called.
fTelemetryVersion := SCS_U32_NIL;
fGameName := '';
fGameID := '';
fGameVersion := SCS_U32_NIL;
// Prepare support for selected game and telemetry versions.
// Raise exception for unsupported telemetry/game.
If not PrepareForTelemetryVersion(TelemetryVersion) then
raise Exception.Create('TTelemetryRecipient.Create: Telemetry version (' +
SCSGetVersionAsString(TelemetryVersion) + ') not supported');
If not PrepareForGameVersion(APIStringToTelemetryString(Parameters.common.game_name),
APIStringToTelemetryString(Parameters.common.game_id),
Parameters.common.game_version) then
raise Exception.Create('TTelemetryRecipient.Create: Game version (' +
TelemetryStringDecode(APIStringToTelemetryString(Parameters.common.game_id)) + '; ' +
SCSGetVersionAsString(Parameters.common.game_version) + ') not supported');
// Create telemetry info provider (list of known event, channels, etc.).
fInfoProvider := TTelemetryInfoProvider.Create(TelemetryVersion,
Parameters.common.game_id,
Parameters.common.game_version);
// Set game callbacks from passed prameters.
cbLog := nil;
cbRegisterEvent := nil;
cbUnregisterEvent := nil;
cbRegisterChannel := nil;
cbUnregisterChannel := nil;
SetGameCallBacks(Parameters);
// Fields initialization.
fRegisteredEvents := TRegisteredEventsList.Create;
fRegisteredChannels := TRegisteredChannelsList.Create;
fStoredConfigs := TStoredConfigsList.Create;
fStoredChannelsValues := TStoredChannelsValuesList.Create;
{$IFDEF MulticastEvents}
fOnDestroyMulti := TMulticastNotifyEvent.Create(Self);
fOnLogMulti := TMulticastLogEvent.Create(Self);
fOnEventRegisterMulti := TMulticastEventRegisterEvent.Create(Self);
fOnEventUnregisterMulti := TMulticastEventRegisterEvent.Create(Self);
fOnEventMulti := TMulticastEventEvent.Create(Self);
fOnChannelRegisterMulti := TMulticastChannelRegisterEvent.Create(Self);
fOnChannelUnregisterMulti := TMulticastChannelUnregisterEvent.Create(Self);
fOnChannelMulti := TMulticastChannelEvent.Create(Self);
fOnConfigMulti := TMulticastConfigEvent.Create(Self);
{$ENDIF}
fLastTelemetryResult := SCS_RESULT_ok;
KeepUtilityEvents := def_KeepUtilityEvents;
StoreConfigurations := def_StoreConfigurations;
ManageIndexedChannels := def_ManageIndexedChannels;
StoreChannelsValues := def_StoreChannelsValues;
end;
//------------------------------------------------------------------------------
destructor TTelemetryRecipient.Destroy;
begin
{$IFDEF MulticastEvents}
// Free all multicast events handling objects.
fOnDestroyMulti.Free;
fOnLogMulti.Free;
fOnEventRegisterMulti.Free;
fOnEventUnregisterMulti.Free;
fOnEventMulti.Free;
fOnChannelRegisterMulti.Free;
fOnChannelUnregisterMulti.Free;
fOnChannelMulti.Free;
fOnConfigMulti.Free;
{$ENDIF}
// Set KeepUtilityEvents to false to allow unregistration of all events.
KeepUtilityEvents := False;
ChannelUnregisterAll;
EventUnregisterAll;
DoOnDestroy(Self);
// Free all contexts and stored configurations.
fStoredChannelsValues.Free;
fStoredConfigs.Free;
fRegisteredChannels.Free;
fRegisteredEvents.Free;
// Free information provider object.
fInfoProvider.Free;
inherited;
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.SetGameCallbacks(Parameters: scs_telemetry_init_params_t);
begin
cbLog := Parameters.common.log;
cbRegisterEvent := Parameters.register_for_event;
cbUnregisterEvent := Parameters.unregister_from_event;
cbRegisterChannel := Parameters.register_for_channel;
cbUnregisterChannel := Parameters.unregister_from_channel;
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.SetGameCallback(Callback: TGameCallback; CallbackFunction: Pointer);
begin
case Callback of
gcbLog: cbLog := CallbackFunction;
gcbEventReg: cbRegisterEvent := CallbackFunction;
gcbEventUnreg: cbUnregisterEvent := CallbackFunction;
gcbChannelReg: cbRegisterChannel := CallbackFunction;
gcbChannelUnreg: cbUnregisterChannel := CallbackFunction;
else
// No action.
end;
end;
//------------------------------------------------------------------------------
procedure TTelemetryRecipient.Log(LogType: scs_log_type_t; const LogText: String);
var
TempStr: TelemetryString;
begin
TempStr := TelemetryStringEncode(LogText);
If Assigned(cbLog) then cbLog(LogType,scs_string_t(TempStr));
DoOnLog(Self,LogType,LogText);
end;
procedure TTelemetryRecipient.Log(const LogText: String);
begin
Log(SCS_LOG_TYPE_message,LogText);
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.EventRegistered(Event: scs_event_t): Boolean;
begin
Result := fRegisteredEvents.IndexOf(Event) >= 0;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.EventRegister(Event: scs_event_t): Boolean;
var
NewEventContext: PEventContext;
begin
Result := False;
If Assigned(cbRegisterEvent) then
begin
NewEventContext := fRegisteredEvents.CreateContext(Self,Event,fInfoProvider.KnownEvents.IsUtility(Event));
fLastTelemetryResult := cbRegisterEvent(Event,EventReceiver,NewEventContext);
If LastTelemetryResult = SCS_RESULT_ok then
begin
If fRegisteredEvents.Add(NewEventContext) >= 0 then
begin
DoOnEventRegister(Self,Event);
Result := True;
end
else fRegisteredEvents.FreeContext(NewEventContext);
end
else fRegisteredEvents.FreeContext(NewEventContext);
end
else fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.EventRegisterByIndex(Index: Integer): Boolean;
begin
Result := False;
If (Index >=0) and (Index < fInfoProvider.KnownEvents.Count) then
Result := EventRegister(fInfoProvider.KnownEvents[Index].Event)
else fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.EventUnregister(Event: scs_event_t): Boolean;
begin
Result := False;
If Assigned(cbUnregisterEvent) and
not (KeepUtilityEvents and fInfoProvider.KnownEvents.IsUtility(Event)) then
begin
fLastTelemetryResult := cbUnregisterEvent(Event);
If LastTelemetryResult = SCS_RESULT_ok then
begin
fRegisteredEvents.Remove(Event);
DoOnEventUnregister(Self,Event);
Result := True;
end;
end
else fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.EventRegisterAll: Integer;
var
i: Integer;
begin
Result := 0;
If Assigned(cbRegisterEvent) then
For i := 0 to (fInfoProvider.KnownEvents.Count - 1) do
If not EventRegistered(fInfoProvider.KnownEvents[i].Event) then
If fInfoProvider.KnownEvents[i].Valid then
If EventRegister(fInfoProvider.KnownEvents[i].Event) then Inc(Result);
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.EventUnregisterByIndex(Index: Integer): Boolean;
begin
Result := False;
If (Index >=0) and (Index < fInfoProvider.KnownEvents.Count) then
Result := EventUnregister(fInfoProvider.KnownEvents[Index].Event)
else fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.EventUnregisterIndex(Index: Integer): Boolean;
begin
Result := False;
If Assigned(cbUnregisterEvent) and (Index >= 0) and (Index < fRegisteredEvents.Count) then
Result := EventUnregister(fRegisteredEvents[Index].Event)
else
fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.EventUnregisterAll: Integer;
var
i: Integer;
begin
Result := 0;
If Assigned(cbUnregisterEvent) then
For i := (fRegisteredEvents.Count - 1) downto 0 do
If EventUnregister(fRegisteredEvents[i].Event) then Inc(Result);
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.EventGetDataAsString(Event: scs_event_t; Data: Pointer; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
begin
If Assigned(Data) then
case Event of
SCS_TELEMETRY_EVENT_frame_start:
Result := TelemetryEventFrameStartToStr(p_scs_telemetry_frame_start_t(Data)^,TypeName);
SCS_TELEMETRY_EVENT_configuration:
Result := TelemetryEventConfigurationToStr(p_scs_telemetry_configuration_t(Data)^,TypeName,ShowDescriptors);
else
Result := '';
end;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelRegistered(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Boolean;
begin
Result := fRegisteredChannels.IndexOf(Name,Index,ValueType) >= 0;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelRegister(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t = SCS_TELEMETRY_CHANNEL_FLAG_none): Boolean;
var
NewChannelContext: PChannelContext;
begin
Result := False;
If Assigned(cbRegisterChannel) then
begin
NewChannelContext := fRegisteredChannels.CreateContext(Self,Name,Index,ValueType,Flags,
fInfoProvider.KnownChannels.ChannelIndexConfigID(Name));
fLastTelemetryResult := cbRegisterChannel(scs_string_t(Name),Index,ValueType,Flags,ChannelReceiver,NewChannelContext);
If LastTelemetryResult = SCS_RESULT_ok then
begin
If fRegisteredChannels.Add(NewChannelContext) >= 0 then
begin
DoOnChannelRegister(Self,Name,GetItemID(Name),Index,ValueType,Flags);
Result := True;
end
else fRegisteredChannels.FreeContext(NewChannelContext);
end
else fRegisteredChannels.FreeContext(NewChannelContext);
end
else fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelRegisterByIndex(Index: Integer): Boolean;
var
i,Counter: Integer;
KnownChannelInfo: TKnownChannel;
MaxIndex: Integer;
begin
Result := False;
If Assigned(cbRegisterChannel) and (Index >= 0) and (Index < fInfoProvider.KnownChannels.Count) then
begin
KnownChannelInfo := fInfoProvider.KnownChannels[Index];
If KnownChannelInfo.Indexed then
begin
If KnownChannelInfo.MaxIndex <> SCS_U32_NIL then MaxIndex := KnownChannelInfo.MaxIndex
else MaxIndex := cMaxChannelIndex;
If ManageIndexedChannels and StoreConfigurations and (KnownChannelInfo.IndexConfigID <> 0) then
begin
Index := fStoredConfigs.IndexOf(KnownChannelInfo.IndexConfigID);
If Index >= 0 then
If fStoredConfigs[Index].Value.ValueType = SCS_VALUE_TYPE_u32 then
MaxIndex := fStoredConfigs[Index].Value.BinaryData.value_u32.value - 1;
end;
Counter := 0;
For i := 0 to MaxIndex do
If ChannelRegister(KnownChannelInfo.Name,i,KnownChannelInfo.PrimaryType) then Inc(Counter);
Result := Counter > 0;
end
else Result := ChannelRegister(KnownChannelInfo.Name,SCS_U32_NIL,KnownChannelInfo.PrimaryType);
end
else fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelRegisterByName(const Name: TelemetryString): Boolean;
begin
Result := ChannelRegisterByIndex(fInfoProvider.KnownChannels.IndexOf(Name));
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelUnregister(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Boolean;
begin
Result := False;
If Assigned(cbUnregisterChannel) then
begin
fLastTelemetryResult := cbUnregisterChannel(scs_string_t(Name),Index,ValueType);
If LastTelemetryResult = SCS_RESULT_ok then
begin
fRegisteredChannels.Remove(Name,Index,ValueType);
DoOnChannelUnregister(Self,Name,GetItemID(Name),Index,ValueType);
Result := True;
end;
end
else fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelUnregisterIndex(Index: Integer): Boolean;
begin
Result := False;
If Assigned(cbUnregisterChannel) and (Index >= 0) and (Index < fRegisteredChannels.Count) then
begin
Result := ChannelUnregister(fRegisteredChannels[Index].Name,
fRegisteredChannels[Index].Index,
fRegisteredChannels[Index].ValueType);
end
else fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelUnregisterByIndex(Index: Integer): Boolean;
begin
Result := False;
If (Index >= 0) and (Index < fInfoProvider.KnownChannels.Count) then
Result := ChannelUnregisterByName(fInfoProvider.KnownChannels[Index].Name)
else fLastTelemetryResult := SCS_RESULT_generic_error;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelUnregisterByName(const Name: TelemetryString): Boolean;
var
i,Counter: Integer;
begin
Counter := 0;
If Assigned(cbUnregisterEvent) then
For i := (fRegisteredChannels.Count - 1) downto 0 do
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(fRegisteredChannels[i].Name,Name) then
{$ELSE}
If TelemetrySameStr(fRegisteredChannels[i].Name,Name) then
{$ENDIF}
If ChannelUnregister(fRegisteredChannels[i].Name,
fRegisteredChannels[i].Index,
fRegisteredChannels[i].ValueType) then Inc(Counter);
Result := Counter > 0;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelRegisterAll(RegPrimaryTypes: Boolean = True; RegSecondaryTypes: Boolean = False; RegTertiaryTypes: Boolean = False): Integer;
var
i,j: Integer;
KnownChannelInfo: TKnownChannel;
MaxIndex: Integer;
Function CheckAndRegister(Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Boolean;
begin
Result := False;
If ValueType <> SCS_VALUE_TYPE_INVALID then
begin
If not ChannelRegistered(Name,Index,ValueType) then
Result := ChannelRegister(Name,Index,ValueType,SCS_TELEMETRY_CHANNEL_FLAG_none)
else Result := True;
end;
end;
begin
Result := 0;
If Assigned(cbRegisterChannel) then
For i := 0 to (fInfoProvider.KnownChannels.Count - 1) do
begin
KnownChannelInfo := fInfoProvider.KnownChannels[i];
If fInfoProvider.KnownChannels[i].Indexed then
begin
// Channel is indexed.
// If channel is binded to some configuration, and this config is found,
// then value from config is used as upper index limit, otherwise
// MaxIndex for given channel is used (cMaxChannelIndex constant is used
// if MaxIndex for given channel is not properly set).
If KnownChannelInfo.MaxIndex <> SCS_U32_NIL then MaxIndex := KnownChannelInfo.MaxIndex
else MaxIndex := cMaxChannelIndex;
If ManageIndexedChannels and StoreConfigurations and (KnownChannelInfo.IndexConfigID <> 0) then
begin
j := fStoredConfigs.IndexOf(KnownChannelInfo.IndexConfigID);
If j >= 0 then
If fStoredConfigs[j].Value.ValueType = SCS_VALUE_TYPE_u32 then
MaxIndex := fStoredConfigs[j].Value.BinaryData.value_u32.value - 1;
end;
// The recipient tries to register all indexes from 0 to upper index
// limit until the first failed registration.
For j := 0 to MaxIndex do
begin
If RegPrimaryTypes then
begin
If CheckAndRegister(KnownChannelInfo.Name,j,
KnownChannelInfo.PrimaryType) then Inc(Result) else Break;
end;
If RegSecondaryTypes then
begin
If CheckAndRegister(KnownChannelInfo.Name,j,
KnownChannelInfo.SecondaryType) then Inc(Result) else Break;
end;
If RegTertiaryTypes then
begin
If CheckAndRegister(KnownChannelInfo.Name,j,
KnownChannelInfo.TertiaryType) then Inc(Result) else Break;
end;
end;
end
else
begin
// Channel is not indexed.
If RegPrimaryTypes then
begin
If CheckAndRegister(KnownChannelInfo.Name,SCS_U32_NIL,
KnownChannelInfo.PrimaryType) then Inc(Result);
end;
If RegSecondaryTypes then
begin
If CheckAndRegister(KnownChannelInfo.Name,SCS_U32_NIL,
KnownChannelInfo.SecondaryType) then Inc(Result);
end;
If RegTertiaryTypes then
begin
If CheckAndRegister(KnownChannelInfo.Name,SCS_U32_NIL,
KnownChannelInfo.TertiaryType) then Inc(Result);
end;
end;
end;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelUnregisterAll: Integer;
var
i: Integer;
begin
Result := 0;
If Assigned(cbUnregisterEvent) then
For i := (fRegisteredChannels.Count - 1) downto 0 do
with fRegisteredChannels[i] do
If ChannelUnregister(Name,Index,ValueType) then Inc(Result);
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelGetValueAsString(Value: p_scs_value_t; TypeName: Boolean = False; ShowDescriptors: Boolean = False): String;
begin
If Assigned(Value) then Result := SCSValueToStr(Value^,TypeName,ShowDescriptors)
else Result := '';
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ConfigStored(const Name: TelemetryString; Index: scs_u32_t = SCS_U32_NIL): Boolean;
begin
Result := fStoredConfigs.IndexOf(Name,Index) >= 0;
end;
//------------------------------------------------------------------------------
Function TTelemetryRecipient.ChannelStored(const Name: TelemetryString; Index: scs_u32_t; ValueType: scs_value_type_t): Boolean;
begin
Result := fStoredChannelsValues.IndexOf(Name,Index,ValueType) >= 0;
end;
end.
|
namespace Sugar.Test;
interface
uses
Sugar,
Sugar.IO,
RemObjects.Elements.EUnit;
type
FileTest = public class (Test)
private
Dir: Folder;
Data: File;
public
method Setup; override;
method TearDown; override;
method TestCopy;
method Delete;
method Move;
method Rename;
method FromPath;
method PathProperty;
method Name;
end;
implementation
method FileTest.Setup;
begin
Dir := Folder.UserLocal.CreateFolder("SugarFileTest", true);
Assert.IsNotNil(Dir);
Data := Dir.CreateFile("SugarTest.dat", true);
Assert.IsNotNil(Data);
end;
method FileTest.TearDown;
begin
if Dir <> nil then
Dir.Delete;
end;
method FileTest.TestCopy;
begin
var Temp := Dir.CreateFolder("Temp", true);
Assert.IsNotNil(Temp);
var Value := Data.Copy(Temp);
Assert.IsNotNil(Value);
Assert.IsNotNil(Temp.GetFile("SugarTest.dat"));
Assert.IsNotNil(Dir.GetFile("SugarTest.dat"));
Assert.Throws(->Value.Copy(Dir));
Assert.Throws(->Value.Copy(nil));
Value.Delete;
Value := Data.Copy(Temp, "Test.dat");
Assert.IsNotNil(Value);
Assert.IsNotNil(Temp.GetFile("Test.dat"));
Assert.IsNotNil(Dir.GetFile("SugarTest.dat"));
Assert.Throws(->Value.Copy(Dir, "SugarTest.dat"));
Assert.Throws(->Value.Copy(nil, "1"));
Assert.Throws(->Value.Copy(Dir, nil));
Assert.Throws(->Value.Copy(Dir, ""));
end;
method FileTest.Delete;
begin
Assert.AreEqual(length(Dir.GetFiles), 1);
Assert.IsNotNil(Dir.GetFile("SugarTest.dat"));
Data.Delete;
Assert.AreEqual(length(Dir.GetFiles), 0);
Assert.IsNil(Dir.GetFile("SugarTest.dat"));
Assert.Throws(->Data.Delete);
end;
method FileTest.Move;
begin
var Temp := Dir.CreateFolder("Temp", true);
Assert.IsNotNil(Temp);
var Value := Data.Move(Temp);
Assert.IsNotNil(Value);
Assert.IsNotNil(Temp.GetFile("SugarTest.dat"));
Assert.IsNil(Dir.GetFile("SugarTest.dat"));
Assert.Throws(->Value.Move(Temp));
Assert.Throws(->Value.Move(nil));
Value := Value.Move(Dir, "Test.dat");
Assert.IsNotNil(Value);
Assert.IsNotNil(Dir.GetFile("Test.dat"));
Assert.IsNil(Temp.GetFile("SugarTest.dat"));
Assert.Throws(->Value.Move(Dir, "Test.dat"));
Assert.Throws(->Value.Move(nil, "1"));
Assert.Throws(->Value.Move(Dir, nil));
Assert.Throws(->Value.Move(Dir, ""));
end;
method FileTest.Rename;
begin
var Value := Data.Rename("Test.dat");
Assert.IsNotNil(Value);
Assert.AreEqual(Value.Name, "Test.dat");
Assert.IsNotNil(Dir.GetFile("Test.dat"));
Assert.IsNil(Dir.GetFile("SugarTest.dat"));
Assert.Throws(->Data.Rename("Test.dat"));
Assert.Throws(->Data.Rename(nil));
Assert.Throws(->Data.Rename("/"));
Assert.Throws(->Data.Rename(""));
end;
method FileTest.FromPath;
begin
Assert.IsNotNil(Dir.CreateFile("1.txt", true));
Assert.IsNotNil(new File(Path.Combine(Dir.Path, "1.txt")));
Assert.Throws(->new File(Path.Combine(Dir.Path, "2.txt")));
Assert.Throws(->new File(nil));
end;
method FileTest.PathProperty;
begin
Assert.IsFalse(String.IsNullOrEmpty(Data.Path));
Assert.IsNotNil(Dir.CreateFile("1.txt", true));
var Value := new File(Path.Combine(Dir.Path, "1.txt"));
Assert.IsNotNil(Value);
Assert.IsFalse(String.IsNullOrEmpty(Value.Path));
end;
method FileTest.Name;
begin
Assert.IsFalse(String.IsNullOrEmpty(Data.Name));
Assert.IsNotNil(Dir.CreateFile("1.txt", true));
var Value := new File(Path.Combine(Dir.Path, "1.txt"));
Assert.IsNotNil(Value);
Assert.IsFalse(String.IsNullOrEmpty(Value.Name));
Assert.AreEqual(Value.Name, "1.txt");
end;
end. |
unit TTSPasswordTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSPasswordRecord = record
PUserName: String[10];
PPassword: String[50];
PCreated: TDateTime;
PInvalidAttempts: Integer;
PLastLoginAttempt: TDateTime;
PModifiedBy: String[10];
PStatus: String[10];
End;
TTTSPasswordBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSPasswordRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSPassword = (TTSPasswordByUserPassword, TTSPasswordByUserCreated, TTSPasswordByUserStatus, TTSPasswordByUserPasswordStatus);
TTTSPasswordTable = class( TDBISAMTableAU )
private
FDFUserName: TStringField;
FDFPassword: TStringField;
FDFCreated: TDateTimeField;
FDFInvalidAttempts: TIntegerField;
FDFLastLoginAttempt: TDateTimeField;
FDFModifiedBy: TStringField;
FDFStatus: TStringField;
procedure SetPUserName(const Value: String);
function GetPUserName:String;
procedure SetPPassword(const Value: String);
function GetPPassword:String;
procedure SetPCreated(const Value: TDateTime);
function GetPCreated:TDateTime;
procedure SetPInvalidAttempts(const Value: Integer);
function GetPInvalidAttempts:Integer;
procedure SetPLastLoginAttempt(const Value: TDateTime);
function GetPLastLoginAttempt:TDateTime;
procedure SetPModifiedBy(const Value: String);
function GetPModifiedBy:String;
procedure SetPStatus(const Value: String);
function GetPStatus:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEITTSPassword);
function GetEnumIndex: TEITTSPassword;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSPasswordRecord;
procedure StoreDataBuffer(ABuffer:TTTSPasswordRecord);
property DFUserName: TStringField read FDFUserName;
property DFPassword: TStringField read FDFPassword;
property DFCreated: TDateTimeField read FDFCreated;
property DFInvalidAttempts: TIntegerField read FDFInvalidAttempts;
property DFLastLoginAttempt: TDateTimeField read FDFLastLoginAttempt;
property DFModifiedBy: TStringField read FDFModifiedBy;
property DFStatus: TStringField read FDFStatus;
property PUserName: String read GetPUserName write SetPUserName;
property PPassword: String read GetPPassword write SetPPassword;
property PCreated: TDateTime read GetPCreated write SetPCreated;
property PInvalidAttempts: Integer read GetPInvalidAttempts write SetPInvalidAttempts;
property PLastLoginAttempt: TDateTime read GetPLastLoginAttempt write SetPLastLoginAttempt;
property PModifiedBy: String read GetPModifiedBy write SetPModifiedBy;
property PStatus: String read GetPStatus write SetPStatus;
published
property Active write SetActive;
property EnumIndex: TEITTSPassword read GetEnumIndex write SetEnumIndex;
end; { TTTSPasswordTable }
procedure Register;
implementation
function TTTSPasswordTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TTTSPasswordTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TTTSPasswordTable.GenerateNewFieldName }
function TTTSPasswordTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TTTSPasswordOptionsTable.CreateField }
procedure TTTSPasswordTable.CreateFields;
begin
FDFUserName := CreateField( 'UserName' ) as TStringField;
FDFPassword := CreateField( 'Password' ) as TStringField;
FDFCreated := CreateField( 'Created' ) as TDateTimeField;
FDFInvalidAttempts := CreateField( 'InvalidAttempts' ) as TIntegerField;
FDFLastLoginAttempt := CreateField( 'LastLoginAttempt' ) as TDateTimeField;
FDFModifiedBy := CreateField( 'ModifiedBy' ) as TStringField;
FDFStatus := CreateField( 'Status' ) as TStringField;
end; { TTTSPasswordTable.CreateFields }
procedure TTTSPasswordTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSPasswordTable.SetActive }
procedure TTTSPasswordTable.SetPUserName(const Value: String);
begin
DFUserName.Value := Value;
end;
function TTTSPasswordTable.GetPUserName:String;
begin
result := DFUserName.Value;
end;
procedure TTTSPasswordTable.SetPPassword(const Value: String);
begin
DFPassword.Value := Value;
end;
function TTTSPasswordTable.GetPPassword:String;
begin
result := DFPassword.Value;
end;
procedure TTTSPasswordTable.SetPCreated(const Value: TDateTime);
begin
DFCreated.Value := Value;
end;
function TTTSPasswordTable.GetPCreated:TDateTime;
begin
result := DFCreated.Value;
end;
procedure TTTSPasswordTable.SetPInvalidAttempts(const Value: Integer);
begin
DFInvalidAttempts.Value := Value;
end;
function TTTSPasswordTable.GetPInvalidAttempts:Integer;
begin
result := DFInvalidAttempts.Value;
end;
procedure TTTSPasswordTable.SetPLastLoginAttempt(const Value: TDateTime);
begin
DFLastLoginAttempt.Value := Value;
end;
function TTTSPasswordTable.GetPLastLoginAttempt:TDateTime;
begin
result := DFLastLoginAttempt.Value;
end;
procedure TTTSPasswordTable.SetPModifiedBy(const Value: String);
begin
DFModifiedBy.Value := Value;
end;
function TTTSPasswordTable.GetPModifiedBy:String;
begin
result := DFModifiedBy.Value;
end;
procedure TTTSPasswordTable.SetPStatus(const Value: String);
begin
DFStatus.Value := Value;
end;
function TTTSPasswordTable.GetPStatus:String;
begin
result := DFStatus.Value;
end;
procedure TTTSPasswordTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
//VG 260717: RecId added as a primary key, because otherwise DBISAM4 ads one automatically, which causes the VerifyStructure to fail
Add('RecId, AutoInc, 0, N');
Add('UserName, String, 10, N');
Add('Password, String, 50, N');
Add('Created, TDateTime, 0, N');
Add('InvalidAttempts, Integer, 0, N');
Add('LastLoginAttempt, TDateTime, 0, N');
Add('ModifiedBy, String, 10, N');
Add('Status, String, 10, N');
end;
end;
procedure TTTSPasswordTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, RecId, Y, Y, N, N');
Add('ByUserPassword, UserName;Password, N, N, N, N');
Add('ByUserCreated, UserName;Created, N, N, N, N');
Add('ByUserStatus, UserName;Status, N, N, N, N');
Add('ByUserPasswordStatus, UserName;Password;Status, N, N, N, N');
end;
end;
procedure TTTSPasswordTable.SetEnumIndex(Value: TEITTSPassword);
begin
case Value of
TTSPasswordByUserPassword: IndexName := 'ByUserPassword';
TTSPasswordByUserCreated : IndexName := 'ByUserCreated';
TTSPasswordByUserStatus : IndexName := 'ByUserStatus';
TTSPasswordByUserPasswordStatus : IndexName := 'ByUserPasswordStatus';
end;
end;
function TTTSPasswordTable.GetDataBuffer:TTTSPasswordRecord;
var buf: TTTSPasswordRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PUserName := DFUserName.Value;
buf.PPassword := DFPassword.Value;
buf.PCreated := DFCreated.Value;
buf.PInvalidAttempts := DFInvalidAttempts.Value;
buf.PLastLoginAttempt := DFLastLoginAttempt.Value;
buf.PModifiedBy := DFModifiedBy.Value;
buf.PStatus := DFStatus.Value;
result := buf;
end;
procedure TTTSPasswordTable.StoreDataBuffer(ABuffer:TTTSPasswordRecord);
begin
DFUserName.Value := ABuffer.PUserName;
DFPassword.Value := ABuffer.PPassword;
DFCreated.Value := ABuffer.PCreated;
DFInvalidAttempts.Value := ABuffer.PInvalidAttempts;
DFLastLoginAttempt.Value := ABuffer.PLastLoginAttempt;
DFModifiedBy.Value := ABuffer.PModifiedBy;
DFStatus.Value := ABuffer.PStatus;
end;
function TTTSPasswordTable.GetEnumIndex: TEITTSPassword;
var iname : string;
begin
result := TTSPasswordByUserPassword;
iname := uppercase(indexname);
if iname = '' then result := TTSPasswordByUserPassword;
if iname = 'BYUSERCREATED' then result := TTSPasswordByUserCreated;
if iname = 'BYUSERSTATUS' then result := TTSPasswordByUserStatus;
if iname = 'BYUSERPASSWORDSTATUS' then result := TTSPasswordByUserPasswordStatus;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSPasswordTable, TTTSPasswordBuffer ] );
end; { Register }
function TTTSPasswordBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..7] of string = ('USERNAME','PASSWORD','CREATED','INVALIDATTEMPTS','LASTLOGINATTEMPT','MODIFIEDBY'
,'STATUS' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 7) and (flist[x] <> s) do inc(x);
if x <= 7 then result := x else result := 0;
end;
function TTTSPasswordBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftDateTime;
4 : result := ftInteger;
5 : result := ftDateTime;
6 : result := ftString;
7 : result := ftString;
end;
end;
function TTTSPasswordBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PUserName;
2 : result := @Data.PPassword;
3 : result := @Data.PCreated;
4 : result := @Data.PInvalidAttempts;
5 : result := @Data.PLastLoginAttempt;
6 : result := @Data.PModifiedBy;
7 : result := @Data.PStatus;
end;
end;
end. |
unit UUsuario;
interface
type
//classe sem heranca, sempre herda de TObject
TUsuario = class
private
FAtivo: String;
FID: Integer;
FPorcDesc: Real;
FNome: String;
FPorcDescB: Real;
FPassword: String;
procedure SetAtivo(const Value: String);
procedure SetID(const Value: Integer);
procedure SetNome(const Value: String);
procedure SetPorcDesc(const Value: Real);
procedure SetPorcDescB(const Value: Real);
procedure SetPassword(const Value: String);
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
constructor Create(ID: Integer; Nome, Password: String; PorcDesc, PorcDescB: Real);overload;
constructor Create(); overload;
destructor Destroy; override;
procedure limpaDados;
published
{ published declarations }
property ID : Integer read FID write SetID;
property Nome : String read FNome write SetNome;
property PorcDesc : Real read FPorcDesc write SetPorcDesc;
property PorcDescB : Real read FPorcDescB write SetPorcDescB;
property Ativo : String read FAtivo write SetAtivo;
property Password : String read FPassword write SetPassword;
end;
implementation
uses
Vcl.Dialogs;
{ TUsuario }
constructor TUsuario.Create(ID: Integer; Nome, Password: String; PorcDesc, PorcDescB: Real);
begin
self.ID :=ID;
self.Nome :=Nome;
self.Password :=Password;
self.PorcDesc :=PorcDesc;
self.PorcDescB :=PorcDescB;
end;
constructor TUsuario.Create;
begin
//
end;
destructor TUsuario.Destroy;
begin
inherited;
end;
procedure TUsuario.limpaDados;
begin
self.Nome :='';
self.PorcDesc :=0;
self.PorcDescB :=0;
end;
procedure TUsuario.SetAtivo(const Value: String);
begin
FAtivo := Value;
end;
procedure TUsuario.SetID(const Value: Integer);
begin
//Quando seta o ID limpa as propriedades
limpaDados;
FID := Value;
end;
procedure TUsuario.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TUsuario.SetPassword(const Value: String);
begin
FPassword := Value;
end;
procedure TUsuario.SetPorcDesc(const Value: Real);
begin
FPorcDesc := Value;
end;
procedure TUsuario.SetPorcDescB(const Value: Real);
begin
FPorcDescB := Value;
end;
end.
|
unit IrcConversationD;
interface
uses
irc_abstract, systemx, typex, stringx, betterobject, classes, irc_monitor, dirfile, sysutils;
type
TIRCConversationDaemon = class(TSharedObject)
private
procedure DoSendHelpHEader;
protected
conversation: Iholder<TIRCConversation>;
irc: TIRCMultiUserClient;
procedure SendHelp();
procedure SendHelpOverView();virtual;
procedure SendhelpCommands();virtual;
function GetConversation: TIRCConversation;
procedure SendHelpHeader;
procedure SendHelpLine(sCommand, sParams, sHelp: string);
procedure SendHelpFooter;
public
constructor Create(irc: TIRCMultiUserClient; channel: string); reintroduce;virtual;
procedure Detach; override;
function OnCommand(sOriginalLine, sCmd: string; params: TStringList): boolean;virtual;
procedure SayHello;virtual;
procedure TestUTF8;
property conv: TIRCConversation read Getconversation;
end;
implementation
{ TIRCConversationDaemon }
constructor TIRCConversationDaemon.Create(irc: TIRCMultiUserClient; channel: string);
begin
inherited Create;
if zcopy(channel, 0,1) <> '#' then
channel := '#'+channel;
self.irc := irc;
conversation := irc.NewConversation(channel);
conversation.o.fOnCommand := function (sOriginalLine, sCmd: string; params: TStringList): boolean
begin
result := OnCommand(sOriginalLine, sCmd, params);
end;
if irc.WaitForState(irccsStarted) then begin
try
SayHello;
except
end;
end;
end;
procedure TIRCConversationDaemon.Detach;
begin
if detached then exit;
irc.EndConversation(conversation);
conversation := nil;
inherited;
end;
procedure TIRCConversationDaemon.DoSendHelpHEader;
begin
conversation.o.PrivMsg('Help for '+classname);
end;
function TIRCConversationDaemon.GetConversation: TIRCConversation;
begin
result := conversation.o;
end;
function TIRCConversationDaemon.OnCommand(sOriginalLine, sCmd: string;
params: TStringList): boolean;
begin
result := false;
if not result then begin
if sCmd = 'help' then begin
SendHelp();
exit(true);
end else
if sCmd = 'hello' then begin
Sayhello;
end;
if sCmd = 'testutf8' then begin
TestUTF8;
end;
end;
end;
procedure TIRCConversationDaemon.SayHello;
begin
var d: TDateTime;
d := dirfile.GetFileDate(dllname);
conversation.o.PrivMsg(' _ _ _ _ ');
conversation.o.PrivMsg(' | | | | | | | ');
conversation.o.PrivMsg(' | |__| | ___| | | ___ ');
conversation.o.PrivMsg(' | __ |/ _ \ | |/ _ \');
conversation.o.PrivMsg(' | | | | __/ | | (_) |');
conversation.o.PrivMsg(' |_| |_|\___|_|_|\___/ ');
conversation.o.PrivMsg(' ');
conversation.o.PrivMsg('Hi from '+self.ClassName+' in '+extractfilename(dllname)+' dated '+datetimetostr(d));
end;
procedure TIRCConversationDaemon.SendHelp;
begin
SendHelpHeader;
SendHelpCommands;
SendHelpFooter;
end;
procedure TIRCConversationDaemon.SendhelpCommands;
begin
SendHelpLine('hello', '','causes server to reply with "hello", essentially a ping');
SendHelpLine('testutf8 ','','a test of utf8 encoding, if you get a bunch of ?s then utf8 is not supported currently');
end;
procedure TIRCConversationDaemon.SendHelpFooter;
begin
conv.PM(ESCIRC+'</table>');
conv.PM(ESCIRC+'<span color=red>To Send a command, type ! followed by the command name, space, and params (if applicable)</span>');
end;
procedure TIRCConversationDaemon.SendHelpHeader;
begin
conv.PMHold(ESCIRC+'<table><tr><th align=left colspan=3><h2>Help for '+classname+'</h2></th></tr>');
conv.PMHold(ESCIRC+'<tr><th align=left>Command</th><th align=left>Params</th><th align=left>Details</th></tr>');
end;
procedure TIRCConversationDaemon.SendHelpLine(sCommand, sParams, sHelp: string);
begin
// conv.PM(ESCIRC+'<tr><td><b>'+sCommand+'</b></td><td>'+AmpEncode(sHelp)+'</td></tr>');
conv.PMHold(ESCIRC+'<tr><td><b>'+sCommand+'</b></td><td><i>'+AmpEncode(sParams)+'</i></td><td>'+AmpEncode(sHelp)+'</td></tr>');
end;
procedure TIRCConversationDaemon.SendHelpOverView;
begin
//''
end;
procedure TIRCConversationDaemon.TestUTF8;
begin
conversation.o.PrivMsg(' ██░ ██ ▓█████ ██▓ ██▓ ▒█████');
conversation.o.PrivMsg('▓██░ ██▒▓█ ▀ ▓██▒ ▓██▒ ▒██▒ ██▒');
conversation.o.PrivMsg('▒██▀▀██░▒███ ▒██░ ▒██░ ▒██░ ██▒');
conversation.o.PrivMsg('░▓█ ░██ ▒▓█ ▄ ▒██░ ▒██░ ▒██ ██░');
conversation.o.PrivMsg('░▓█▒░██▓░▒████▒░██████▒░██████▒░ ████▓▒░');
conversation.o.PrivMsg(' ▒ ░░▒░▒░░ ▒░ ░░ ▒░▓ ░░ ▒░▓ ░░ ▒░▒░▒░');
conversation.o.PrivMsg(' ▒ ░▒░ ░ ░ ░ ░░ ░ ▒ ░░ ░ ▒ ░ ░ ▒ ▒░');
conversation.o.PrivMsg(' ░ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ');
conversation.o.PrivMsg(' ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ');
end;
end.
|
unit DownloadObj;
interface
type TDownload=class
private
FUrl: string;
FTimeOut: integer;
FName: string;
FExtension: string;
FDirectory: string;
published
property url: string read FUrl write FUrl;
property timeOut: integer read FTimeOut write FTimeOut;
property name: string read FName write FName;
property extension: string read FExtension write FExtension;
property directory: string read FDirectory write FDirectory;
public
constructor Create; overload;
constructor Create(const aUrl: string;
const aTimeOut: integer;
const aName: string;
const aExtension: string;
const aDirectory: string); overload;
destructor Destroy; override;
end;
implementation
{ TDownload }
constructor TDownload.Create;
begin
url := '';
timeout := 10000;
name := '';
extension := '';
directory := '';
end;
constructor TDownload.Create(
const aUrl: string;
const aTimeOut: integer;
const aName, aExtension, aDirectory: string);
begin
url := aUrl;
timeout := aTimeOut;
name := aName;
extension := aExtension;
directory := aDirectory;
end;
destructor TDownload.Destroy;
begin
inherited;
end;
end.
|
unit INFOINFOTAGTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TINFOINFOTAGRecord = record
PAutoInc: Integer;
PRecordAutoinc: Integer;
PRecordNumber: String[6];
PSeperatedby: String[10];
PGroupby: String[10];
PSortby: String[60];
End;
TINFOINFOTAGBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TINFOINFOTAGRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIINFOINFOTAG = (INFOINFOTAGPrimaryKey, INFOINFOTAGBySort, INFOINFOTAGByRecordNumber);
TINFOINFOTAGTable = class( TDBISAMTableAU )
private
FDFAutoInc: TAutoIncField;
FDFRecordAutoinc: TIntegerField;
FDFRecordNumber: TStringField;
FDFSeperatedby: TStringField;
FDFGroupby: TStringField;
FDFSortby: TStringField;
procedure SetPRecordAutoinc(const Value: Integer);
function GetPRecordAutoinc:Integer;
procedure SetPRecordNumber(const Value: String);
function GetPRecordNumber:String;
procedure SetPSeperatedby(const Value: String);
function GetPSeperatedby:String;
procedure SetPGroupby(const Value: String);
function GetPGroupby:String;
procedure SetPSortby(const Value: String);
function GetPSortby:String;
procedure SetEnumIndex(Value: TEIINFOINFOTAG);
function GetEnumIndex: TEIINFOINFOTAG;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TINFOINFOTAGRecord;
procedure StoreDataBuffer(ABuffer:TINFOINFOTAGRecord);
property DFAutoInc: TAutoIncField read FDFAutoInc;
property DFRecordAutoinc: TIntegerField read FDFRecordAutoinc;
property DFRecordNumber: TStringField read FDFRecordNumber;
property DFSeperatedby: TStringField read FDFSeperatedby;
property DFGroupby: TStringField read FDFGroupby;
property DFSortby: TStringField read FDFSortby;
property PRecordAutoinc: Integer read GetPRecordAutoinc write SetPRecordAutoinc;
property PRecordNumber: String read GetPRecordNumber write SetPRecordNumber;
property PSeperatedby: String read GetPSeperatedby write SetPSeperatedby;
property PGroupby: String read GetPGroupby write SetPGroupby;
property PSortby: String read GetPSortby write SetPSortby;
published
property Active write SetActive;
property EnumIndex: TEIINFOINFOTAG read GetEnumIndex write SetEnumIndex;
end; { TINFOINFOTAGTable }
procedure Register;
implementation
procedure TINFOINFOTAGTable.CreateFields;
begin
FDFAutoInc := CreateField( 'AutoInc' ) as TAutoIncField;
FDFRecordAutoinc := CreateField( 'RecordAutoinc' ) as TIntegerField;
FDFRecordNumber := CreateField( 'RecordNumber' ) as TStringField;
FDFSeperatedby := CreateField( 'Seperatedby' ) as TStringField;
FDFGroupby := CreateField( 'Groupby' ) as TStringField;
FDFSortby := CreateField( 'Sortby' ) as TStringField;
end; { TINFOINFOTAGTable.CreateFields }
procedure TINFOINFOTAGTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TINFOINFOTAGTable.SetActive }
procedure TINFOINFOTAGTable.SetPRecordAutoinc(const Value: Integer);
begin
DFRecordAutoinc.Value := Value;
end;
function TINFOINFOTAGTable.GetPRecordAutoinc:Integer;
begin
result := DFRecordAutoinc.Value;
end;
procedure TINFOINFOTAGTable.SetPRecordNumber(const Value: String);
begin
DFRecordNumber.Value := Value;
end;
function TINFOINFOTAGTable.GetPRecordNumber:String;
begin
result := DFRecordNumber.Value;
end;
procedure TINFOINFOTAGTable.SetPSeperatedby(const Value: String);
begin
DFSeperatedby.Value := Value;
end;
function TINFOINFOTAGTable.GetPSeperatedby:String;
begin
result := DFSeperatedby.Value;
end;
procedure TINFOINFOTAGTable.SetPGroupby(const Value: String);
begin
DFGroupby.Value := Value;
end;
function TINFOINFOTAGTable.GetPGroupby:String;
begin
result := DFGroupby.Value;
end;
procedure TINFOINFOTAGTable.SetPSortby(const Value: String);
begin
DFSortby.Value := Value;
end;
function TINFOINFOTAGTable.GetPSortby:String;
begin
result := DFSortby.Value;
end;
procedure TINFOINFOTAGTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('AutoInc, AutoInc, 0, N');
Add('RecordAutoinc, Integer, 0, N');
Add('RecordNumber, String, 6, N');
Add('Seperatedby, String, 10, N');
Add('Groupby, String, 10, N');
Add('Sortby, String, 60, N');
end;
end;
procedure TINFOINFOTAGTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, AutoInc, Y, Y, N, N');
Add('BySort, Seperatedby;Groupby;Sortby, N, N, N, N');
Add('ByRecordNumber, RecordNumber, N, N, N, N');
end;
end;
procedure TINFOINFOTAGTable.SetEnumIndex(Value: TEIINFOINFOTAG);
begin
case Value of
INFOINFOTAGPrimaryKey : IndexName := '';
INFOINFOTAGBySort : IndexName := 'BySort';
INFOINFOTAGByRecordNumber : IndexName := 'ByRecordNumber';
end;
end;
function TINFOINFOTAGTable.GetDataBuffer:TINFOINFOTAGRecord;
var buf: TINFOINFOTAGRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PAutoInc := DFAutoInc.Value;
buf.PRecordAutoinc := DFRecordAutoinc.Value;
buf.PRecordNumber := DFRecordNumber.Value;
buf.PSeperatedby := DFSeperatedby.Value;
buf.PGroupby := DFGroupby.Value;
buf.PSortby := DFSortby.Value;
result := buf;
end;
procedure TINFOINFOTAGTable.StoreDataBuffer(ABuffer:TINFOINFOTAGRecord);
begin
DFRecordAutoinc.Value := ABuffer.PRecordAutoinc;
DFRecordNumber.Value := ABuffer.PRecordNumber;
DFSeperatedby.Value := ABuffer.PSeperatedby;
DFGroupby.Value := ABuffer.PGroupby;
DFSortby.Value := ABuffer.PSortby;
end;
function TINFOINFOTAGTable.GetEnumIndex: TEIINFOINFOTAG;
var iname : string;
begin
result := INFOINFOTAGPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := INFOINFOTAGPrimaryKey;
if iname = 'BYSORT' then result := INFOINFOTAGBySort;
if iname = 'BYRECORDNUMBER' then result := INFOINFOTAGByRecordNumber;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TINFOINFOTAGTable, TINFOINFOTAGBuffer ] );
end; { Register }
function TINFOINFOTAGBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..6] of string = ('AUTOINC','RECORDAUTOINC','RECORDNUMBER','SEPERATEDBY','GROUPBY','SORTBY'
);
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 6) and (flist[x] <> s) do inc(x);
if x <= 6 then result := x else result := 0;
end;
function TINFOINFOTAGBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftAutoInc;
2 : result := ftInteger;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
end;
end;
function TINFOINFOTAGBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PAutoInc;
2 : result := @Data.PRecordAutoinc;
3 : result := @Data.PRecordNumber;
4 : result := @Data.PSeperatedby;
5 : result := @Data.PGroupby;
6 : result := @Data.PSortby;
end;
end;
end.
|
unit kwHistoryDeleteBackItem;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwHistoryDeleteBackItem.pas"
// Начат: 28.09.2011 11:37
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::CommonWords::history_DeleteBackItem
//
// Удаляет один элемент истории из списка Back.
// *Пример:*
// {code}
// моп::Поиск_Поиск_лекарственного_средства
// 'AT_PHARM_NAME' 'Аргинин' Search:SetAttribute
// 'AT_PHARM_ATC' 'A. Пищеварительный тракт и обмен веществ' Search:SetAttribute
// 'AT_PHARM_ATC' 'B. Препараты влияющие на кроветворение и кровь' Search:SetAttribute
// Ok
// OnTest
// history:DeleteBackItem
// {code}
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts) AND not defined(NoVCM)}
uses
tfwScriptingInterfaces
;
{$IfEnd} //not NoScripts AND not NoVCM
{$If not defined(NoScripts) AND not defined(NoVCM)}
type
{$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas}
_VCMWord_Parent_ = _tfwAutoregisteringWord_;
{$Include ..\ScriptEngine\VCMWord.imp.pas}
TkwHistoryDeleteBackItem = class(_VCMWord_)
{* Удаляет один элемент истории из списка Back.
*Пример:*
[code]
моп::Поиск_Поиск_лекарственного_средства
'AT_PHARM_NAME' 'Аргинин' Search:SetAttribute
'AT_PHARM_ATC' 'A. Пищеварительный тракт и обмен веществ' Search:SetAttribute
'AT_PHARM_ATC' 'B. Препараты влияющие на кроветворение и кровь' Search:SetAttribute
Ok
OnTest
history:DeleteBackItem
[code] }
protected
// realized methods
procedure DoDoIt(const aCtx: TtfwContext); override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwHistoryDeleteBackItem
{$IfEnd} //not NoScripts AND not NoVCM
implementation
{$If not defined(NoScripts) AND not defined(NoVCM)}
uses
tfwAutoregisteredDiction,
tfwScriptEngine,
vcmForm,
Controls,
StdResPrim,
vcmBase
{$If defined(nsTest)}
,
afwAnswer
{$IfEnd} //nsTest
;
{$IfEnd} //not NoScripts AND not NoVCM
{$If not defined(NoScripts) AND not defined(NoVCM)}
type _Instance_R_ = TkwHistoryDeleteBackItem;
{$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas}
{$Include ..\ScriptEngine\VCMWord.imp.pas}
// start class TkwHistoryDeleteBackItem
procedure TkwHistoryDeleteBackItem.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_4E82CEBA0299_var*
//#UC END# *4DAEEDE10285_4E82CEBA0299_var*
begin
//#UC START# *4DAEEDE10285_4E82CEBA0299_impl*
if (vcmDispatcher.History <> nil) then
vcmDispatcher.History.DeleteBackItem;
//#UC END# *4DAEEDE10285_4E82CEBA0299_impl*
end;//TkwHistoryDeleteBackItem.DoDoIt
class function TkwHistoryDeleteBackItem.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'history:DeleteBackItem';
end;//TkwHistoryDeleteBackItem.GetWordNameForRegister
{$IfEnd} //not NoScripts AND not NoVCM
initialization
{$If not defined(NoScripts) AND not defined(NoVCM)}
{$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas}
{$IfEnd} //not NoScripts AND not NoVCM
end. |
unit CleanArch_EmbrConf.Infra.Repository.SQL;
interface
uses
CleanArch_EmbrConf.Core.Repository.Interfaces,
CleanArch_EmbrConf.Core.Entity.Interfaces, System.JSON,
CleanArch_EmbrConf.Infra.Database.Interfaces,
CleanArch_EmbrConf.Infra.Database.Impl.Database,
CleanArch_EmbrConf.Adapter.Impl.ParkingLotAdapter;
type
TParkingLotRepositorySQL = class(TInterfacedObject, iParkingLotRepository)
private
FDatabase : iDatabase;
public
constructor Create;
destructor Destroy; override;
class function New : iParkingLotRepository;
function getParkingLot(Code : String) : iParkingLot;
function getParkingLotJSON(Code : String) : TJSONArray; overload;
function saveParkedCar(Value : iParkedCar) : iParkingLotRepository;
end;
implementation
constructor TParkingLotRepositorySQL.Create;
begin
FDatabase := TDatabase.New;
end;
destructor TParkingLotRepositorySQL.Destroy;
begin
inherited;
end;
function TParkingLotRepositorySQL.getParkingLot(Code: String): iParkingLot;
var
lParkingLotData : iParkingLot;
begin
lParkingLotData := FDatabase.getOneOrNone('select *, (select count(*) '+
'from parked_car pc where pc.code = pl.code) as occupied_spaces '+
'from parking_lot pl where pl.code = :code', [code]);
Result := TParkingLotAdapter.New
.Code(lParkingLotData.Code)
.Capacity(lParkingLotData.Capacity)
.OpenHour(lParkingLotData.OpenHour)
.CloseHour(lParkingLotData.CloseHour)
.OccupiedSpaces(lParkingLotData.OccupiedSpaces)
.ParkingLot;
end;
function TParkingLotRepositorySQL.getParkingLotJSON(Code: String): TJSONArray;
begin
Result := FDatabase.OneOrNone('select *, (select count(*) '+
'from parked_car pc where pc.code = pl.code) as occupied_spaces '+
'from parking_lot pl where pl.code = :code', [code]);
end;
class function TParkingLotRepositorySQL.New : iParkingLotRepository;
begin
Result := Self.Create;
end;
function TParkingLotRepositorySQL.saveParkedCar(
Value: iParkedCar): iParkingLotRepository;
begin
Result := Self;
FDatabase.postPark('insert into parked_car (code, plate, data) values '+
'(:code, :plate, :data)', [Value.Code, Value.Plate, Value.Data]);
end;
end.
|
unit TurnOnTimeMachine_Form;
////////////////////////////////////////////////////////////////////////////////
// Библиотека : Проект Немезис.
// Назначение : Диалог включения машины времени.
// Версия : $Id: TurnOnTimeMachine_Form.pas,v 1.7 2013/05/15 14:31:45 morozov Exp $
////////////////////////////////////////////////////////////////////////////////
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
Mask,
ExtCtrls,
vtCombo,
vtDateEdit,
vtLabel,
vtRadioButton,
vtButton,
vcmComponent,
vcmBaseEntities,
vcmEntities,
vcmInterfaces,
vcmBase,
vcmEntityForm,
l3InterfacedComponent,
PresentationInterfaces,
PrimTurnOnTimeMachine_Form,
PrimTurnOnTimeMachineOptions_Form, eeButton
;
type
Ten_TurnOnTimeMachine = class(TvcmEntityFormRef)
Entities : TvcmEntities;
pbDialogIcon: TPaintBox;
lblTurnOnTimeMachineInfo: TvtLabel;
rb_totmOnDate: TvtRadioButton;
rb_totmOnCurrentRedation: TvtRadioButton;
btnOk: TvtButton;
btnCancel: TvtButton;
deDate: TvtDblClickDateEdit;
procedure btnOkClick(Sender: TObject);
procedure deDateChange(Sender: TObject);
procedure pbDialogIconPaint(Sender: TObject);
procedure vcmEntityFormRefCreate(Sender: TObject);
procedure vcmEntityFormRefShow(Sender: TObject);
end;
implementation
uses
vcmForm,
vcmExternalInterfaces,
nsConst,
StdRes
;
{$R *.DFM}
procedure Ten_TurnOnTimeMachine.btnOkClick(Sender: TObject);
begin
DoOk;
end;
procedure Ten_TurnOnTimeMachine.deDateChange(Sender: TObject);
begin
rb_totmOnDate.Checked := True;
end;
procedure Ten_TurnOnTimeMachine.pbDialogIconPaint(Sender: TObject);
begin
with Sender as TPaintBox do
dmStdRes.LargeImageList.Draw(Canvas,
Width - c_LargeSizeIcon,
(Height - c_LargeSizeIcon) div 2,
cTimeMachineOn);
end;
procedure Ten_TurnOnTimeMachine.vcmEntityFormRefCreate(Sender: TObject);
begin
rb_totmOnDate.Font.Charset := RUSSIAN_CHARSET;
rb_totmOnCurrentRedation.Font.Charset := RUSSIAN_CHARSET;
end;
procedure Ten_TurnOnTimeMachine.vcmEntityFormRefShow(Sender: TObject);
//http://mdp.garant.ru/pages/viewpage.action?pageId=449678181
begin
rb_totmOnDate.Top := lblTurnOnTimeMachineInfo.Top +
lblTurnOnTimeMachineInfo.Height + 11;
deDate.Top := rb_totmOnDate.Top + rb_totmOnDate.Height + 11;
rb_totmOnCurrentRedation.Top := deDate.Top + deDate.Height + 10;
btnOk.Top := rb_totmOnCurrentRedation.Top + rb_totmOnCurrentRedation.Height + 24;
btnCancel.Top := btnOk.Top;
Self.ClientHeight := btnOk.Top + btnOk.Height + 18;
end;
end.
|
{ CSI 1101-X, Winter 1999 }
{ Mark Sattolo, student# 428500 }
{ tutorial group DGD-4, t.a. = Jensen Boire }
program testing (input,output) ;
uses Ptr_fxns ;
label 310 ;
{ variable for the main program - NOT to be referenced anywhere else }
var YESorNO: char ;
procedure test ;
var
L: list ;
Val: element ;
Same: boolean ;
Num, Ins : real ;
choice: char ;
begin
create_empty( L ) ;
writeln('Enter a list of reals, all values on one line: ') ;
while (not eoln)
do begin
read(val) ;
insert_at_end(L,val)
end ;
readln ; { clear the empty line }
writeln ;
writeln('Here is the list you entered');
write_list(L);
writeln ;
repeat
writeln('Choose a procedure to test: ' );
writeln('A: are values all the same?') ;
writeln('B: insert number before val.') ;
writeln('C: insert number after val.') ;
writeln('D: delete first element of list.') ;
writeln('E: insert at end of list.') ;
writeln('F: insert at front of list.') ;
writeln('I: is list sorted in increasing order?') ;
writeln('L: delete last element of list.') ;
writeln('V: delete all occurrences of val.') ;
writeln('X : exit.') ;
writeln ;
write('Choice: ') ;
readln(choice) ;
case choice of
'A', 'a' : begin
all_the_same(L, Same);
write ('The values ARE ') ;
if not Same then write('NOT ') ;
write ('all the same.') ;
writeln ;
end;
'B', 'b' : begin
write('Enter a number to insert: ') ;
readln(num) ;
write('Enter value to insert before: ') ;
readln(ins) ;
insert_before_val(L, num, ins) ;
end ;
'C', 'c' : begin
write('Enter a number to insert: ') ;
readln(num) ;
write('Enter value to insert after: ') ;
readln(ins) ;
insert_after_val(L, ins, num) ;
end ;
'D', 'd' : Delete_first(L) ;
'E', 'e' : begin
write('Enter a number to insert: ') ;
readln(num) ;
Insert_at_end(L, num) ;
end ;
'F', 'f' : begin
write('Enter a number to insert: ') ;
readln(num) ;
Insert_at_front(L, num) ;
end ;
'I', 'i' : writeln('The list ', Is_increasing(L) ) ;
'L', 'l' : Delete_last(L) ;
'V', 'v' : begin
write('Enter a value to delete: ') ;
readln(num) ;
Delete_all_vals(L, num) ;
end ;
'X', 'x' : begin
writeln('Exiting list processing procedures.') ;
choice := 'X' ;
end ;
else
begin
writeln('Invalid choice: ', choice, ': exiting procedure.') ;
choice := 'X' ;
end ;
end; { case }
if (choice <> 'X') then
begin
writeln('Here is the modified list: ');
write_list(L);
writeln ;
end ;
until choice = 'X' ;
destroy( L ) { Return all the nodes in all lists back to the global pool }
end; { procedure test }
begin { main program }
mem_count := 0 ;
repeat
test ;
310: writeln('Amount of dynamic memory allocated but not returned (should be 0): ', mem_count:0) ;
writeln('Do you wish to continue (y or n) ?') ;
readln(YESorNO);
until (YESorNO in ['N', 'n'])
end.
|
unit MFichas.Model.Conexao.SQL;
interface
uses
System.SysUtils,
System.Classes,
System.IOUtils,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef,
FireDAC.Stan.ExprFuncs,
FireDAC.FMXUI.Wait,
FireDAC.Comp.Client,
FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.DApt.Intf,
FireDAC.DApt,
FireDAC.Comp.DataSet,
FireDAC.Comp.UI,
FireDAC.ConsoleUI.Wait,
Data.DB,
ORMBR.Factory.Interfaces,
ORMBR.Factory.FireDAC,
ORMBR.Types.DataBase,
ORMBR.DDL.Generator.SQLite,
ORMBR.DML.Generator.SQLite,
MFichas.Model.Conexao.Interfaces;
const
CaminhoDoBancoSQLiteLocal = 'C:\PROJETOS\Bancos\SQLite\FICHAS.db3';
CaminhoDoBancoSQLiteMobile = 'FICHAS.db3';
type
TModelConexaoSQL = class(TInterfacedObject, iModelConexaoSQL)
private
FFDConnection: TFDConnection;
FFDQuery : TFDQuery;
FConn : IDBConnection;
constructor Create;
procedure CriarFDConnection;
procedure CriarFDQuery;
public
destructor Destroy; override;
class function New: iModelConexaoSQL;
function Conn: iDBConnection;
function Query: TFDQuery;
end;
implementation
{ TModelConexaoSQL }
function TModelConexaoSQL.Conn: iDBConnection;
begin
Result := FConn;
end;
constructor TModelConexaoSQL.Create;
begin
CriarFDConnection;
CriarFDQuery;
FConn := TFactoryFireDAC.Create(FFDConnection, dnSQLite);
end;
procedure TModelConexaoSQL.CriarFDConnection;
begin
FFDConnection := TFDConnection.Create(nil);
{$IFDEF MSWINDOWS}
FFDConnection.Params.Database := CaminhoDoBancoSQLiteLocal;
{$ELSE}
FFDConnection.Params.Values['Database'] := TPath.Combine(TPath.GetDocumentsPath, CaminhoDoBancoSQLiteMobile);
{$ENDIF}
FFDConnection.DriverName := 'SQLite';
FFDConnection.Params.DriverID := 'SQLite';
FFDConnection.Params.Add('LockingMode=Normal');
FFDConnection.Connected := True;
end;
procedure TModelConexaoSQL.CriarFDQuery;
begin
FFDQuery := TFDQuery.Create(nil);
FFDQuery.Connection := FFDConnection;
end;
destructor TModelConexaoSQL.Destroy;
begin
{$IFDEF MSWINDOWS}
FreeAndNil(FFDConnection);
FreeAndNil(FFDQuery);
{$ELSE}
FFDConnection.Free;
FFDConnection.DisposeOf;
FFDQuery.Free;
FFDQuery.DisposeOf;
{$ENDIF}
inherited;
end;
class function TModelConexaoSQL.New: iModelConexaoSQL;
begin
Result := Self.Create;
end;
function TModelConexaoSQL.Query: TFDQuery;
begin
Result := FFDQuery;
end;
end.
|
unit ffsException;
interface
uses sysutils, controls;
type
// general exception to determine the original source of an eception
EffsException = class(Exception);
EffsValidate = class(EffsException);
EffsRequiredData = class(EffsValidate)
public
constructor createDefault;
end;
EffsValidateControl = class(EffsValidate)
public
InvalidControl : TWinControl;
constructor create(msg:string;Acontrol:TWinControl);
end;
EffsSG = class(EffsException);
EffsModCount = class(Exception);
implementation
constructor EffsRequiredData.createDefault;
begin
inherited create('This field may not be left blank.');
end;
constructor EffsValidateControl.create(msg:string;AControl:TWinControl);
begin
inherited create(msg);
InvalidControl := AControl;
end;
end.
|
unit Base.System.Json.Helper;
interface
Uses System.Classes, System.SysUtils, System.Rtti, System.TypInfo, System.Json;
type
TJsonRecord<T:Record> = class
public
class function ToJson(O: T): string;
class procedure FromJson(O:T;AJson:string);
end;
implementation
class procedure TJsonRecord<T>.FromJson(O: T; AJson: string);
var js:TJsonObject;
AContext : TRttiContext;
AField : TRttiField;
ARecord : TRttiRecordType;
AFldName : String;
AValue : TValue;
begin
js:= TJsonObject.ParseJSONValue(AJson) as TJsonObject;
try
AContext := TRttiContext.Create;
try
ARecord := AContext.GetType(TypeInfo(T)).AsRecord;
for AField in ARecord.GetFields do
begin
AFldName := AField.Name;
AValue := js.GetValue(AFldName);
AField.SetValue(@O,AValue);
end;
finally
AContext.free;
end;
finally
js.Free;
end;
end;
class function TJsonRecord<T>.ToJson(O: T): string;
var
AContext : TRttiContext;
AField : TRttiField;
ARecord : TRttiRecordType;
AFldName : String;
AValue : TValue;
ArrFields : TArray<TRttiField>;
i:integer;
js:TJsonObject;
begin
js := TJsonObject.Create;
AContext := TRttiContext.Create;
try
ARecord := AContext.GetType(TypeInfo(T)).AsRecord;
ArrFields := ARecord.GetFields;
i := 0;
for AField in ArrFields do
begin
AFldName := AField.Name;
AValue := AField.GetValue(@O);
try
if AValue.IsEmpty then
js.addPair(AFldName,'NULL')
else
case AField.FieldType.TypeKind of
tkInteger,tkInt64:
try
js.addPair(AFldName,TJSONNumber.Create(Avalue.AsInt64));
except
js.addPair(AFldName,TJSONNumber.Create(0));
end;
tkEnumeration:
js.addPair(AFldName,TJSONNumber.Create(Avalue.AsInteger));
tkFloat:
begin
if AField.FieldType.ToString.Equals('TDateTime') then
js.addPair(AFldName, FormatDateTime('yyyy-mm-dd HH:nn:ss', AValue.AsExtended))
else
if AField.FieldType.ToString.Equals('TDate') then
js.addPair(AFldName, FormatDateTime('yyyy-mm-dd', AValue.AsExtended))
else
if AField.FieldType.ToString.Equals('TTime') then
js.addPair(AFldName, FormatDateTime('HH:nn:ss', AValue.AsExtended))
else
try
js.addPair(AFldName,TJSONNumber.Create(Avalue.AsExtended));
except
js.addPair(AFldName,TJSONNumber.Create(0));
end;
end
else
js.addPair(AFldName,AValue.asString)
end;
except
js.addPair(AFldName,'NULL')
end;
end;
result := js.ToString;
finally
js.Free;
AContext.Free;
end;
end;
end.
|
unit Tutorial;
interface
uses
SysUtils, Tasks, BackupInterfaces, CacheAgent;
const
tidTask_Tutorial = 'Tutorial';
tidTask_TutorialWelcome = 'Welcome';
tidTask_WhoYouAre = 'WhoYouAre';
tidTask_YourProfile = 'YourProfile';
tidTask_TheSpider = 'TheSpider';
tidTask_IndustryAndStore = 'Industry&Store';
tidChoiceIndustry = 'ChoiceIndustry';
tidTask_BuildFarm = 'bFarm';
tidTask_BuildFoodProc = 'bFoodProc';
tidTask_BuildClothesIndustry = 'bClothes';
tidTask_BuildHHAIndustry = 'bHousehold';
tidTask_BuildFoodSore = 'bFoodStore';
tidTask_BuildClothesSore = 'bClothesStore';
tidTask_BuildHHASore = 'bHHAStore';
tidTask_GrowMoney = 'GrowMoney';
tidTask_TutorialFarewell = 'Farewell';
tidTask_CloseTutor = 'CloseTutor';
const
MaxProfTurns = 50;
type
TTutorialTask =
class(TSuperTask)
public
constructor Create(aMetaTask : TMetaTask; aSuperTask : TSuperTask; aContext : ITaskContext); override;
private
fActive : boolean;
fDone : boolean;
fNotTycoon : boolean;
public
property NotTycoon : boolean read fNotTycoon write fNotTycoon;
public
function GetActive : boolean; override;
procedure SetActive(Value : boolean); override;
procedure LoadFromBackup(Reader : IBackupReader); override;
procedure StoreToBackup (Writer : IBackupWriter); override;
procedure StoreToCache(Prefix : string; Cache : TObjectCache); override;
function GetTaskNumber : integer; override;
function GetNotTycoon : boolean; override;
procedure SetNotTycoon(value : boolean); override;
private
procedure PickCompanyAndTown;
public
function Execute : TTaskResult; override;
end;
TMetaBuildIndustryAndStore =
class(TMetaTask)
private
fProdCookieName : string;
fProdCookieValue : string;
public
property ProdCookieName : string read fProdCookieName write fProdCookieName;
property ProdCookieValue : string read fProdCookieValue write fProdCookieValue;
end;
TBuildIndustryAndStore =
class(TTask)
protected
class procedure SetCompletionCookies(MetaTask : TMetaTask; SuperTask : TTask; canceled : boolean); override;
end;
TGrowMoneyTask =
class(TAtomicTask)
private
fProfTurns : byte;
public
function Execute : TTaskResult; override;
end;
procedure RegisterTasks;
procedure RegisterBackup;
implementation
uses
Kernel, Standards, Protocol, InformativeTask, ClusterTask, HeadquarterTasks,
ResidentialTasks, BuildFacilitiesTask, BuildWarehouse, ChoiceTask, TaskUtils,
FacIds, FoodStore, ClothesShop, HHAStore, MathUtils, CommonTasks, MakeProfitTask,
ResearchTask, HireOfferTask, LoanMoneyTask, PGITutorial, DissidentTutorial,
MoabTutorial, MarikoTutorial, WhoYouAre, YourProfile, TheSpider, BuyAdsTask,
CloneAdsTask, SellAllTask, UpgradeFacTask, ManuallyConnectTask;
// TTutorialTask
constructor TTutorialTask.Create(aMetaTask : TMetaTask; aSuperTask : TSuperTask; aContext : ITaskContext);
begin
inherited;
fActive := true;
end;
function TTutorialTask.GetActive : boolean;
begin
result := fActive;
end;
procedure TTutorialTask.SetActive(Value : boolean);
begin
fActive := Value;
end;
procedure TTutorialTask.LoadFromBackup(Reader : IBackupReader);
begin
inherited;
fActive := Reader.ReadBoolean('Active', true);
fDone := Reader.ReadBoolean('Done', false);
end;
procedure TTutorialTask.StoreToBackup (Writer : IBackupWriter);
begin
inherited;
Writer.WriteBoolean('Active', fActive);
Writer.WriteBoolean('Done', fDone);
end;
procedure TTutorialTask.StoreToCache(Prefix : string; Cache : TObjectCache);
begin
inherited;
Cache.WriteBoolean('Done', fDone);
end;
function TTutorialTask.GetTaskNumber : integer;
begin
result := 0;
end;
function TTutorialTask.GetNotTycoon : boolean;
begin
result := fNotTycoon;
end;
procedure TTutorialTask.SetNotTycoon(value : boolean);
begin
fNotTycoon := value;
end;
procedure TTutorialTask.PickCompanyAndTown;
var
Tycoon : TTycoon;
Company : TCompany;
HqFac : TFacility;
i : integer;
begin
Tycoon := TTycoon(Context.getContext(tcIdx_Tycoon));
if (Tycoon <> nil) and (Tycoon.AllCompaniesCount > 0)
then
begin
Company := TCompany(Context.getContext(tcIdx_Company));
i := 0;
while (Company = nil) and (i < Tycoon.AllCompaniesCount) do
begin
if (UpperCase(Tycoon.AllCompanies[i].Cluster.Id) <> 'UW')
then Company := Tycoon.AllCompanies[i];
inc(i);
end;
if Company <> nil
then
begin
Context.setContext(tcIdx_Company, Company);
if TaskUtils.FindFacility(FID_MainHeadquarter, Company, HqFac)
then Context.setContext(tcIdx_Town, HqFac.Town);
end;
end;
end;
function TTutorialTask.Execute : TTaskResult;
var
Company : TCompany;
Town : TTown;
begin
if not fDone
then
begin
Company := TCompany(Context.getContext(tcIdx_Company));
Town := TTown(Context.getContext(tcIdx_Town));
if (Company = nil) or (Town = nil)
then PickCompanyAndTown;
if Company <> nil
then result := inherited Execute
else result := trContinue;
fDone := result = trFinished;
end
else result := trFinished;
end;
// TBuildIndustryAndStore
class procedure TBuildIndustryAndStore.SetCompletionCookies(MetaTask : TMetaTask; SuperTask : TTask; canceled : boolean);
begin
inherited;
if SuperTask <> nil
then SuperTask.AddCookie(TMetaBuildIndustryAndStore(MetaTask).ProdCookieName, TMetaBuildIndustryAndStore(MetaTask).ProdCookieValue);
end;
// TGrowMoneyTask
function TGrowMoneyTask.Execute : TTaskResult;
var
Tycoon : TTycoon;
begin
Tycoon := TTycoon(Context.getContext(tcIdx_Tycoon));
if Tycoon.NetProfit > 0
then fProfTurns := max(MaxProfTurns, fProfTurns + 1)
else fProfTurns := min(0, fProfTurns - 1);
{
if fProfTurns = MaxProfTurns
then result := trFinished
else result := trContinue;
// >> REMOVE!!!!
}
result := trFinished;
end;
// Register Tasks
procedure RegisterTasks;
begin
// Tutorial
with TMetaTask.Create(
tidTask_Tutorial,
'Tutorial',
'', // No description
'', // None
10,
TTutorialTask) do
begin
Register(tidClassFamily_Tasks);
end;
// Tutorial Welcome
with TMetaTask.Create(
tidTask_TutorialWelcome,
'Tutorial Welcome',
'', // No description
tidTask_Tutorial,
6,
TInformativeTask) do
begin
NotTitle :=
'Welcome to LEGACY Online Tutorial. In case you close this window ' +
'you can access this tutorial page from the TUTORIAL button ' +
'located in the PROFILE page.';
Priority := tprHighest;
KindId := 'Welcome';
StageCount := 2;
Register(tidClassFamily_Tasks);
end;
// Who You Are
with TMetaWhoYouAreTask.Create(
tidTask_WhoYouAre,
'Who You Are',
'', // No description
tidTask_Tutorial, // This is a Template
1, // Once every 4 virtual-day
TWhoYouAreTask) do
begin
StageCount := 3;
Priority := tprHighest - 1;
KindId := 'WhoYouAre';
NotTitle := 'Introduction to the Tutorial';
Register(tidClassFamily_Tasks);
end;
// Your Profile
with TMetaYourProfile.Create(
tidTask_YourProfile,
'Who You Are',
'', // No description
tidTask_Tutorial, // This is a Template
1, // Once every 4 virtual-day
TYourProfileTask) do
begin
StageCount := 3;
Priority := tprHighest - 2;
KindId := 'YourProfile';
NotTitle := 'All About Your Account';
Register(tidClassFamily_Tasks);
end;
// The Spider
with TMetaYourProfile.Create(
tidTask_TheSpider,
'The Spider',
'', // No description
tidTask_Tutorial, // This is a Template
1, // Once every 4 virtual-day
TTheSpiderTask) do
begin
StageCount := 3;
Priority := tprHighest - 3;
KindId := 'TheSpider';
NotTitle := 'World Atlas';
Register(tidClassFamily_Tasks);
end;
CommonTasks.RegisterTasks;
PGITutorial.RegisterTasks;
DissidentTutorial.RegisterTasks;
MoabTutorial.RegisterTasks;
MarikoTutorial.RegisterTasks;
// Tutorial Farewell
with TMetaTask.Create(
tidTask_TutorialFarewell,
'Tutorial Farewell',
'', // No description
tidTask_Tutorial,
1,
TInformativeTask) do
begin
NotTitle :=
'Welcome to LEGACY Online Tutorial. In case you close this window ' +
'you can access this tutorial page from the TUTORIAL button ' +
'located in the PROFILE page.';
Priority := tprLow - 1;
KindId := 'Farewell';
StageCount := 1;
Register(tidClassFamily_Tasks);
end;
// Tutorial Farewell
with TMetaTask.Create(
tidTask_CloseTutor,
'Close Tutor',
'', // No description
tidTask_Tutorial,
1,
TInformativeTask) do
begin
NotTitle := 'Closing Tutor';
NotOptions := nopTutorial_OFF;
Priority := tprLow - 2;
KindId := 'Farewell';
StageCount := 0;
Register(tidClassFamily_Tasks);
end;
end;
procedure RegisterBackup;
begin
RegisterClass(TTutorialTask);
RegisterClass(TBuildIndustryAndStore);
RegisterClass(TGrowMoneyTask);
InformativeTask.RegisterBackup;
HeadquarterTasks.RegisterBackup;
ResidentialTasks.RegisterBackup;
BuildFacilitiesTask.RegisterBackup;
ChoiceTask.RegisterBackup;
ClusterTask.RegisterBackup;
MakeProfitTask.RegisterBackup;
ResearchTask.RegisterBackup;
BuildWarehouse.RegisterBackup;
HireOfferTask.RegisterBackup;
LoanMoneyTask.RegisterBackup;
WhoYouAre.RegisterBackup;
YourProfile.RegisterBackup;
TheSpider.RegisterBackup;
BuyAdsTask.RegisterBackup;
CloneAdsTask.RegisterBackup;
SellAllTask.RegisterBackup;
UpgradeFacTask.RegisterBackup;
ManuallyConnectTask.RegisterBackup
end;
end.
|
unit atFileInitializer;
// Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atFileInitializer.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TatFileInitializer" MUID: (50294907000B)
interface
uses
l3IntfUses
, Windows
, Classes
;
type
TatFileInitializer = class(TObject)
private
f_GuardFile: THandle;
f_FileName: AnsiString;
f_Handle: THandle;
f_Stream: TStream;
public
function DupHandle: THandle; virtual;
function TryInit: Boolean; virtual;
procedure FinishInit; virtual;
constructor Create(const aFileName: AnsiString = ''); reintroduce;
destructor Destroy; override;
public
property FileName: AnsiString
read f_FileName;
property Handle: THandle
read f_Handle;
property Stream: TStream
read f_Stream;
end;//TatFileInitializer
implementation
uses
l3ImplUses
, SysUtils
//#UC START# *50294907000Bimpl_uses*
//#UC END# *50294907000Bimpl_uses*
;
function TatFileInitializer.DupHandle: THandle;
//#UC START# *50294A39012E_50294907000B_var*
//#UC END# *50294A39012E_50294907000B_var*
begin
//#UC START# *50294A39012E_50294907000B_impl*
if NOT DuplicateHandle(GetCurrentProcess, Handle, GetCurrentProcess, @Result, 0, false, DUPLICATE_SAME_ACCESS) then
Result := INVALID_HANDLE_VALUE;
//#UC END# *50294A39012E_50294907000B_impl*
end;//TatFileInitializer.DupHandle
function TatFileInitializer.TryInit: Boolean;
//#UC START# *50294A550017_50294907000B_var*
//#UC END# *50294A550017_50294907000B_var*
begin
//#UC START# *50294A550017_50294907000B_impl*
Result := f_GuardFile <> INVALID_HANDLE_VALUE;
//#UC END# *50294A550017_50294907000B_impl*
end;//TatFileInitializer.TryInit
procedure TatFileInitializer.FinishInit;
//#UC START# *50294A61033F_50294907000B_var*
//#UC END# *50294A61033F_50294907000B_var*
begin
//#UC START# *50294A61033F_50294907000B_impl*
FreeAndNil(f_Stream);
// закрываем открытый на запись файл
if f_Handle <> INVALID_HANDLE_VALUE then
begin
CloseHandle(f_Handle);
f_Handle := INVALID_HANDLE_VALUE;
end;
// переоткрываем файл на чтение с запретом записи
while true do
begin
f_Handle := CreateFile(PAnsiChar(f_FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if f_Handle = INVALID_HANDLE_VALUE then
Sleep(100) // файл еще открыт на запись
else
break;
end;
f_Stream := THandleStream.Create(Handle);
//
if f_GuardFile <> INVALID_HANDLE_VALUE then
begin
CloseHandle(f_GuardFile);
f_GuardFile := INVALID_HANDLE_VALUE;
end;
//#UC END# *50294A61033F_50294907000B_impl*
end;//TatFileInitializer.FinishInit
constructor TatFileInitializer.Create(const aFileName: AnsiString = '');
//#UC START# *50294A7E0284_50294907000B_var*
var
l_GuardFileName : String;
function GetTemporary : String;
var
l_Path, l_Name : array [0..MAX_PATH] of AnsiChar;
begin
if (GetTempPath(SizeOf(l_Path), l_Path) <>0) AND (GetTempFileName(l_Path, nil, 0, l_Name) <> 0) then
Result := l_Name;
end;
//#UC END# *50294A7E0284_50294907000B_var*
begin
//#UC START# *50294A7E0284_50294907000B_impl*
f_Handle := INVALID_HANDLE_VALUE;
f_GuardFile := INVALID_HANDLE_VALUE;
if aFileName <> '' then
f_FileName := aFileName
else
f_FileName := GetTemporary;
// открываем файл на эксклюзивную запись
f_Handle := CreateFile(PAnsiChar(f_FileName), GENERIC_WRITE or GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_DELETE, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if f_Handle <> INVALID_HANDLE_VALUE then
begin
l_GuardFileName := f_FileName + '.guard';
f_GuardFile := CreateFile(PAnsiChar(l_GuardFileName), GENERIC_WRITE, FILE_SHARE_READ, nil, OPEN_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE or FILE_ATTRIBUTE_HIDDEN, 0);
end;
if f_GuardFile = INVALID_HANDLE_VALUE then // файл не захвачен на запись, либо захвачен повторно
FinishInit
else
f_Stream := THandleStream.Create(Handle);
//#UC END# *50294A7E0284_50294907000B_impl*
end;//TatFileInitializer.Create
destructor TatFileInitializer.Destroy;
//#UC START# *48077504027E_50294907000B_var*
//#UC END# *48077504027E_50294907000B_var*
begin
//#UC START# *48077504027E_50294907000B_impl*
FreeAndNil(f_Stream);
if f_Handle <> INVALID_HANDLE_VALUE then
begin
CloseHandle(f_Handle);
f_Handle := INVALID_HANDLE_VALUE;
end;
DeleteFile(PAnsiChar(f_FileName)); // удалится, только если никто не использует
if f_GuardFile <> INVALID_HANDLE_VALUE then
begin
CloseHandle(f_GuardFile);
f_GuardFile := INVALID_HANDLE_VALUE;
end;
//
inherited;
//#UC END# *48077504027E_50294907000B_impl*
end;//TatFileInitializer.Destroy
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.4 12/2/2004 4:23:50 PM JPMugaas
Adjusted for changes in Core.
Rev 1.3 1/21/2004 2:12:40 PM JPMugaas
InitComponent
Rev 1.2 1/17/2003 05:35:18 PM JPMugaas
Now compiles with new design.
Rev 1.1 1-1-2003 20:12:48 BGooijen
Changed to support the new TIdContext class
Rev 1.0 11/14/2002 02:17:06 PM JPMugaas
2000-Apr-22: J Peter Mugass
-Ported to Indy
1999-Apr-13
-Final Version
2000-JAN-13 MTL
-Moved to new Palette Scheme (Winshoes Servers)
}
unit IdDayTimeServer;
{
Original Author: Ozz Nixon
}
interface
{$i IdCompilerDefines.inc}
uses
{$IFDEF WORKAROUND_INLINE_CONSTRUCTORS}
Classes,
{$ENDIF}
IdAssignedNumbers,
IdContext,
IdCustomTCPServer;
Type
TIdDayTimeServer = class(TIdCustomTCPServer)
protected
FTimeZone: String;
//
function DoExecute(AContext:TIdContext): boolean; override;
procedure InitComponent; override;
{$IFDEF WORKAROUND_INLINE_CONSTRUCTORS}
public
constructor Create(AOwner: TComponent); reintroduce; overload;
{$ENDIF}
published
property TimeZone: String read FTimeZone write FTimeZone;
property DefaultPort default IdPORT_DAYTIME;
end;
implementation
uses
IdGlobal, SysUtils;
{$IFDEF WORKAROUND_INLINE_CONSTRUCTORS}
constructor TIdDayTimeServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
{$ENDIF}
procedure TIdDayTimeServer.InitComponent;
begin
inherited InitComponent;
DefaultPort := IdPORT_DAYTIME;
FTimeZone := 'EST'; {Do not Localize}
end;
function TIdDayTimeServer.DoExecute(AContext:TIdContext ): boolean;
begin
Result := True;
with AContext.Connection do begin
IOHandler.WriteLn(FormatDateTime('dddd, mmmm dd, yyyy hh:nn:ss', Now) + '-' + FTimeZone); {Do not Localize}
Disconnect;
end;
end;
end.
|
unit uBar;
interface
uses Graphics;
type
TBar = class(TObject)
private
FB, FBar, FBarBG: TBitmap;
FG: array[0..3] of TBitmap;
FNeedRender: Boolean;
procedure SetNeedRender(const Value: Boolean);
public
property NeedRender: Boolean read FNeedRender write SetNeedRender;
procedure Click();
procedure Render;
//** Конструктор.
constructor Create;
destructor Destroy; override;
end;
var
Bar: TBar;
implementation
uses SysUtils, Classes, uUtils, uBox, uSCR, uVars, uInvBox, uScene, uMain;
const
B: array[0..3]of string = ('BarRed.bmp', 'BarBlue.bmp', 'BarGold.bmp',
'BarGreen.bmp');
T: array[0..16]of char = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'C', 'I', 'Q', 'A', 'L', 'M', 'S');
P: array[0..1]of 0..1 = (1, 0);
{ TBar }
procedure TBar.Click;
procedure PressKey(AKey: Word);
var
Key: Word;
H: TShiftState;
begin
Key := AKey;
fMain.FormKeyDown(Self, Key, H);
end;
begin
if IsMouseInRect(120, 565, 680, 600) and not IsMenu then
PressKey(Ord(T[(MouseX - 120) div 33]));
end;
constructor TBar.Create;
var
I: Integer;
begin
NeedRender := True;
FB := TBitMap.Create;
FBar := TBitmap.Create;
FBar.LoadFromFile(Path + 'Data\Images\GUI\Bar.bmp');
FBar.Canvas.Font.Size := 6;
FBar.Canvas.Font.Color := clWhite;
FBar.Canvas.Brush.Style := bsClear;
FBarBG := TBitmap.Create;
FBarBG.LoadFromFile(Path + 'Data\Images\GUI\BarBG.bmp');
for I := 0 to 3 do
begin
FG[I] := TBitmap.Create;
FG[I].LoadFromFile(Path + 'Data\Images\GUI\' + B[I]);
end;
end;
destructor TBar.Destroy;
var
I: Integer;
begin
for I := 0 to 3 do
FG[I].Free;
FBarBG.Free;
FBar.Free;
FB.Free;
inherited;
end;
procedure TBar.Render;
var
I, J: Integer;
C: Char;
begin
if not NeedRender or IsMenu then Exit;
with SCR.BG.Canvas do begin
Draw(0, 565, FBar);
with InvBox do
begin
for I := 0 to Belt.SlotCount - 1 do
if (Belt[I] <> '') then
Draw(119 + (I * 33), 566,
InvBitmap[Belt.InvItems[I].ImageIndex]);
end;
FB.Assign(FG[0]);
FB.Width := BarWidth(VM.GetInt('Hero.HP'), VM.GetInt('Hero.MHP'));
Draw(1, 566, FB);
FB.Assign(FG[1]);
FB.Width := BarWidth(VM.GetInt('Hero.MP'), VM.GetInt('Hero.MMP'));
Draw(1, 583, FB);
FB.Assign(FG[2]);
FB.Width := BarWidth(VM.GetInt('Hero.Exp'), VM.GetInt('Hero.NextExp'));
Draw(681, 566, FB);
FB.Assign(FG[3]);
FB.Width := BarWidth(VM.GetInt('Hero.Hunger'), 1000);
Draw(681, 583, FB);
Font.Size := 12;
Font.Color := 0;
Font.Style := [fsBold];
for J := 0 to High(P) do
begin
if (P[J] = 0) then Font.Color := clWhite;
for I := 0 to 16 do TextOut(I * 33 + 122 + P[J], 582 + P[J], T[I]);
end;
J := VM.GetInt('Enemy.HP');
if (J > 0) then
begin
I := 347;
FB.Assign(FG[0]);
FB.Width := BarWidth(J, VM.GetInt('Enemy.MHP'));
if IsRightFrame then I := 147;
if IsLeftFrame or (ShowLogLevel = 2) then I := 547;
Draw(I, 10, FBarBG);
Draw(I + 1, 11, FB);
end;
end;
end;
procedure TBar.SetNeedRender(const Value: Boolean);
begin
FNeedRender := Value;
end;
initialization
Bar := TBar.Create;
finalization
Bar.Free;
end.
|
unit GX_eFindDelimiter;
{$I GX_CondDefine.inc}
interface
uses
Classes, ToolsAPI, GX_EditorExpert;
type
TSourceLanguage = (ltPas, ltCpp);
type
TBaseDelimiterExpert = class(TEditorExpert)
private
LastActionBackward: Boolean;
ThreeDelimiters: Boolean;
public
procedure DoDelimiterAction(Editor: IOTASourceEditor;
Offset: Integer;
SChar, EChar: TOTACharPos); virtual; abstract;
procedure Execute(Sender: TObject); override;
function HasConfigOptions: Boolean; override;
end;
TLocateDelimiter = class(TBaseDelimiterExpert)
public
class function GetName: string; override;
constructor Create; override;
function GetDefaultShortCut: TShortCut; override;
function GetDisplayName: string; override;
procedure DoDelimiterAction(Editor: IOTASourceEditor;
Offset: Integer;
SChar, EChar: TOTACharPos); override;
function GetHelpString: string; override;
end;
type
TMoveToDelimiter = class(TBaseDelimiterExpert)
public
class function GetName: string; override;
constructor Create; override;
function GetDefaultShortCut: TShortCut; override;
function GetDisplayName: string; override;
procedure DoDelimiterAction(Editor: IOTASourceEditor;
Offset: Integer;
SChar, EChar: TOTACharPos); override;
function GetHelpString: string; override;
end;
implementation
uses
SysUtils, Windows, Dialogs,
mwPasTokenList, mwBCBTokenList,
GX_EditReader, GX_GenericUtils, GX_OtaUtils;
resourcestring
SDelimiterHelpPrefix =
' This expert enables you to quickly ';
SDelimiterHelpSuffix = ' a matching beginning/ending delimiter for the following Delphi '+
'tokens: begin, try, case, repeat, for, with, while, asm, do, if, then, else, class, record, '+
'array, interface, implementation, uses, private, protected, public, published, until, '+
'end, try, finally, except, (/), and [/], .' +sLineBreak+
' It also supports the following C++ tokens: {/}, (/), and [/]';
SDelimiterMoveToMessage = 'move to';
SDelimiterLocateMessage = 'locate';
SDelimiterUsage =
sLineBreak +
'The following steps are taken to match delimiters:' + sLineBreak +
' - Beginning at the current cursor position, the expert looks to the left '+
'on the current line for a delimiter token such as "begin".'+ sLineBreak +
' - If a delimiter token is found, the expert scans for the matching '+
'token, such as "end" in the above instance.' + sLineBreak +
' - If no delimiter is found to the left, as in the case "if|(i=0)" (where ''|'' represents the cursor), the ' +
'expert attempts to find a delimiter token to the right of the current '+
'cursor position. In the mentioned example, this will identify the opening '+
'parenthesis, and an attempt is made to locate the closing parenthesis.';
SNotValidIdentifier = '"%s" is not a supported delimiter.';
SNoMatchingEndFound = 'No matching closing delimiter was found.';
{ TBaseDelimiterExpert }
function GetFileContent(out FileContent: string; const FileName: string;
var EditorLine: string): Integer;
var
EditRead: TEditReader;
CharPos: TOTACharPos;
begin
// Since this edit reader is destroyed almost
// immediately, do not call FreeFileData.
EditRead := TEditReader.Create(FileName);
try
FileContent := EditRead.GetText;
CharPos :=EditRead.GetCurrentCharPos;
Result := LinePosToCharPos(Point(CharPos.CharIndex + 1, CharPos.Line), FileContent);
finally
FreeAndNil(EditRead);
end;
end;
{ TODO 4 -oAnyone -cCleanup:
TBaseDelimiterExpert.Execute method is far too complex.
It needs to be broken up into some more manageable chunks. }
procedure TBaseDelimiterExpert.Execute(Sender: TObject);
resourcestring
SPasOrCFilesOnly = 'This expert is for use in .pas, .dpr, .inc, .cpp, .c, .h or .hpp files only';
SCouldNotGetSourceBuffer = 'Could not get source code from editor buffer. Is a special selection active?';
const
Offsets: array[0..2] of Integer=(0, -1, 1);
var
FileContent: string;
C: Integer;
SPos: Integer;
EPos: Integer;
Point: TPoint;
SChar: TOTACharPos;
EChar: TOTACharPos;
Module: IOTAModule;
SourceEditor: IOTASourceEditor;
TextToken: string;
EditorLine: string;
FileName: string;
Language: TSourceLanguage;
Backward: Boolean;
Offset: Integer;
function ExecutePas: Boolean;
var
I: Integer;
Parser: TPasTokenList;
StartToken: TTokenKind;
ExtraStartTokens: set of TTokenKind;
EndTokens: set of TTokenKind;
begin
ExtraStartTokens := [];
Result := False;
Parser := TPasTokenList.Create;
try
Parser.SetOrigin(@FileContent[1], Length(FileContent));
if Parser.Origin = nil then
begin
MessageDlg(SCouldNotGetSourceBuffer, mtError, [mbOK], 0);
Exit;
end;
for i := 0 to 2 do
begin
// We try current token, previous token and finally next token
Parser.RunIndex := Parser.PositionToIndex(SPos) + Offsets[i];
StartToken := Parser.RunID;
case Parser.RunID of
tkBegin, tkCase, tkAsm:
begin
EndTokens := [tkEnd];
Backward := False;
Break;
end;
tkTry:
begin
if ThreeDelimiters then
EndTokens := [tkFinally, tkExcept]
else
EndTokens := [tkEnd];
Backward := False;
Break;
end;
tkWith, tkWhile, tkThen, tkDo, tkIf, tkElse, tkFor:
begin
EndTokens := []; // We figure this out later based on context
Backward := False;
Break;
end;
tkFinally, tkExcept:
if LastActionBackward then
begin
EndTokens := [tkTry];
if Parser.RunID = tkExcept then
ExtraStartTokens := [tkFinally]
else
ExtraStartTokens := [tkExcept];
Backward := True;
Break;
end
else
begin
EndTokens := [tkEnd];
Backward := False;
Break;
end;
tkRoundOpen:
begin
EndTokens := [tkRoundClose];
Backward := False;
Break;
end;
tkSquareOpen:
begin
EndTokens := [tkSquareClose];
Backward := False;
Break;
end;
tkRepeat:
begin
EndTokens := [tkUntil];
Backward := False;
Break;
end;
tkClass, tkRecord:
begin
Parser.NextNonJunk;
if Parser.RunID in [tkSemicolon, tkOf] then // Forward declaration or class of Foo;
EndTokens := [tkSemicolon]
else
EndTokens := [tkEnd];
Parser.PreviousNonJunk;
Backward := False;
Break;
end;
tkArray:
begin
Backward := False;
EndTokens := [tkConst, tkSemiColon, tkRoundClose];
Break;
end;
tkInterface:
begin
Backward := False;
Parser.NextNonJunk;
if Parser.RunID = tkSemicolon then // Forward declaration
begin
EndTokens := [tkSemicolon];
Parser.PreviousNonJunk;
end
else
begin
Parser.PreviousNonJunk; // Back to the interface
Parser.PreviousNonJunk; // Previous token
if Parser.RunID = tkEqual then // Interface declaration
EndTokens := [tkEnd]
else
EndTokens := [tkImplementation]; // interface section
Parser.NextNonJunk;
end;
Break;
end;
tkImplementation:
begin
EndTokens := [tkInterface];
Backward := True;
Break;
end;
tkUses:
begin
EndTokens := [tkSemiColon];
Backward:= False;
Break;
end;
tkEnd:
begin
if ThreeDelimiters then
EndTokens := [tkBegin, tkCase, tkRecord, tkClass, tkAsm, tkFinally, tkExcept]
else
EndTokens := [tkBegin, tkCase, tkRecord, tkClass, tkAsm, tkTry];
Backward := True;
Break;
end;
tkPrivate, tkProtected, tkPublic, tkPublished:
begin
EndTokens := [tkEnd, tkPrivate, tkProtected, tkPublic, tkPublished];
Backward := False;
Break;
end;
tkRoundClose:
begin
EndTokens := [tkRoundOpen];
Backward := True;
Break;
end;
tkSquareClose:
begin
EndTokens := [tkSquareOpen];
Backward := True;
Break;
end;
tkUntil:
begin
EndTokens := [tkRepeat];
Backward := True;
Break;
end;
else
if i = 0 then begin
TextToken := Parser.RunToken;
if TextToken = CRLF then
TextToken := '<cr><lf>'
else
TextToken := HackBadEditorStringToNativeString(TextToken)
end else if i = 2 then
begin
MessageDlg(Format(SNotValidIdentifier, [TextToken]), mtError, [mbOK], 0);
Exit;
end;
end; // case
end; // for
c := 1;
if Backward then
begin
SPos := Parser.RunPosition + Length(Parser.RunToken);
while (c > 0) and (Parser.RunIndex > 0) do
begin
Parser.PreviousNonJunk;
if (Parser.RunID = StartToken) or (Parser.RunID in ExtraStartTokens) then
Inc(c);
if Parser.RunID in EndTokens then
begin
if StartToken = tkImplementation then
begin
Parser.PreviousNonJunk;
if Parser.RunID <> tkEqual then
Dec(c);
Parser.NextNonJunk;
end
else
Dec(c);
end;
end;
EPos := Parser.RunPosition;
Offset := 0;
end
else // Forward scan
begin
SPos := Parser.RunPosition;
// If/then/else jump to the end of the if/else action statement or the next matching else
// TODO 3 -cBug -oAnyone: Nested else/if without a begin/end can confuse the parser here
if StartToken in [tkIf, tkThen, tkElse] then
begin
// An else can not stop at itself
if Parser.RunID = tkElse then
Parser.Next;
while (not (Parser.RunID in [tkElse, tkSemicolon, tkBegin, tkCase, tkTry, tkNull])) and (EndTokens = []) do
begin
Parser.NextNonJunk;
case Parser.RunID of
tkNull:
Exit;
tkBegin, tkCase, tkTry:
EndTokens := [tkEnd];
tkSemiColon:
begin
EndTokens := [tkSemiColon];
Parser.Previous; // Since this is the terminator, skip back
end;
tkElse:
begin
EndTokens := [tkElse];
Parser.Previous;
end;
end;
end;
end;
// A with/while/do/for might have to scan from there to tkEnd or tkSemicolon
if StartToken in [tkWith, tkWhile, tkDo, tkFor] then
begin
while (not (Parser.RunID in [tkSemicolon, tkBegin, tkCase, tkTry, tkNull])) and (EndTokens = []) do
begin
Parser.NextNonJunk;
case Parser.RunID of
tkNull:
Exit;
tkBegin, tkCase, tkTry:
EndTokens := [tkEnd];
tkSemiColon:
begin
EndTokens := [tkSemiColon];
Parser.Previous; // Since this is the terminator, skip back
end;
end;
end;
end;
while (c > 0) and (Parser.RunID <> tkNull) do
begin
Parser.NextNonJunk;
case StartToken of
tkBegin, tkCase, tkExcept, tkFinally, tkWith, tkWhile, tkThen, tkDo, tkIf, tkElse, tkFor, tkRecord:
begin
if Parser.RunID in [tkBegin, tkTry, tkCase, tkAsm] then
Inc(c);
end;
tkTry:
begin
if ThreeDelimiters then
begin
if Parser.RunID = StartToken then
Inc(c);
end
else if Parser.RunID in [tkBegin, tkTry, tkCase, tkAsm] then
Inc(c);
end;
tkRoundOpen, tkSquareOpen, tkRepeat:
begin
if Parser.RunID = StartToken then
Inc(c);
end;
tkArray:
begin
if Parser.RunID = tkRoundOpen then
Inc(c);
end;
end;
if Parser.RunID in EndTokens then
begin
if StartToken = tkArray then
begin
if C > 1 then
begin
if not (Parser.RunID in [tkSemicolon, tkConst]) then
Dec(c);
end
else
Dec(c); // End the checks
end
else
Dec(c);
end;
end;
if Parser.RunID = tkNull then
Exit;
EPos := Parser.RunPosition + Length(Parser.RunToken);
Offset := Length(Parser.RunToken);
end;
if c = 0 then
begin
if ThreeDelimiters then
LastActionBackward := Backward
else
LastActionBackward := not LastActionBackward;
end;
Result := True;
finally
FreeAndNil(Parser);
end;
end;
function ExecuteCpp: Boolean;
var
I: Integer;
CParser: TBCBTokenList;
CStartToken: TCTokenKind;
CEndToken: TCTokenKind;
begin
Result := False;
CEndToken := ctknull;
CParser := TBCBTokenList.Create;
try
CParser.SetOrigin(@FileContent[1], Length(FileContent));
if CParser.Origin = nil then
begin
MessageDlg(SCouldNotGetSourceBuffer, mtError, [mbOK], 0);
Exit;
end;
for i := 0 to 2 do
begin
// We try current token, previous token and finally next token
CParser.RunIndex := CParser.PositionToIndex(SPos) + Offsets[i];
CStartToken := CParser.RunID;
case CParser.RunID of
ctkbraceopen:
begin
CEndToken := ctkbraceclose;
Break;
end;
ctkroundopen:
begin
CEndToken := ctkroundclose;
Break;
end;
ctksquareopen:
begin
CEndToken := ctksquareclose;
Break;
end;
ctkbraceclose:
begin
CEndToken := ctkbraceopen;
Break;
end;
ctkroundclose:
begin
CEndToken := ctkroundopen;
Break;
end;
ctksquareclose:
begin
CEndToken := ctksquareopen;
Break;
end;
else
if i = 0 then
TextToken := HackBadEditorStringToNativeString(CParser.RunToken)
else if i = 2 then
begin
MessageDlg(Format(SNotValidIdentifier, [TextToken]), mtError, [mbOK], 0);
Exit;
end;
end; // case
end;
c := 1;
if CParser.RunID in [ctkbraceopen, ctkroundopen, ctksquareopen] then
begin
SPos := CParser.RunPosition;
while (c > 0) and (CParser.RunID <> ctknull) do
begin
if CParser.RunIndex = CParser.Count - 1 then
Break;
CParser.Next;
if CStartToken = CParser.RunID then
Inc(c);
if CParser.RunID = CEndToken then
Dec(c);
end;
EPos := CParser.RunPosition + Length(CParser.RunToken);
Offset := Length(CParser.RunToken);
end
else
begin
SPos := CParser.RunPosition + Length(CParser.RunToken);
while (c > 0) and (CParser.RunIndex > 0 )do
begin
CParser.Previous;
if CStartToken = CParser.RunID then
Inc(c);
if CParser.RunID = CEndToken then
Dec(c);
end;
EPos := CParser.RunPosition;
Offset := 0;
end;
Result := True;
finally
FreeAndNil(CParser);
end;
end;
begin
FileName := GxOtaGetTopMostEditBufferFileName;
if IsCpp(FileName) or IsC(FileName) or IsH(FileName) then
Language := ltCpp
else if IsDprOrPas(FileName) or IsInc(FileName) then
Language := ltPas
else
raise Exception.Create(SPasOrCFilesOnly);
Module := GxOtaGetCurrentModule;
if (not Assigned(Module)) or not GxOtaTryGetCurrentSourceEditor(SourceEditor) then
Exit;
SPos := GetFileContent(FileContent, SourceEditor.FileName, EditorLine);
if Language = ltPas then
begin
if not ExecutePas then
Exit;
end
else
if not ExecuteCpp then
Exit;
if c <> 0 then
begin
MessageDlg(SNoMatchingEndFound, mtInformation, [mbOK], 0);
Exit;
end;
// A matching delimiter was found
Point := CharPosToLinePos(SPos + 1, FileContent);
SChar.Line := Point.Y;
SChar.CharIndex := Point.X - 1;
Point := CharPosToLinePos(EPos + 1, FileContent);
EChar.Line := Point.Y;
EChar.CharIndex := Point.X - 1;
DoDelimiterAction(SourceEditor, Offset, SChar, EChar);
end;
function TBaseDelimiterExpert.HasConfigOptions: Boolean;
begin
Result := False;
end;
{ TMoveToDelimiter }
constructor TMoveToDelimiter.Create;
begin
inherited Create;
ThreeDelimiters := True;
end;
procedure TMoveToDelimiter.DoDelimiterAction(Editor: IOTASourceEditor;
Offset: Integer; SChar, EChar: TOTACharPos);
var
EditView: IOTAEditView;
EditPos: TOTAEditPos;
begin
EditView := GxOtaGetTopMostEditView(Editor);
EditView.ConvertPos(False, EditPos, EChar);
EditPos.Col := EditPos.Col - Offset;
if EditPos.Col < 1 then
EditPos.Col := 1;
EditView.CursorPos := EditPos;
EditView.MoveViewToCursor;
EditView.Paint;
end;
function TMoveToDelimiter.GetDefaultShortCut: TShortCut;
begin
Result := scCtrl + scAlt + VK_RIGHT;
end;
function TMoveToDelimiter.GetDisplayName: string;
resourcestring
SMoveToExpertName = 'Move to Matching Delimiter';
begin
Result := SMoveToExpertName;
end;
function TMoveToDelimiter.GetHelpString: string;
begin
Result := SDelimiterHelpPrefix + SDelimiterMoveToMessage +
SDelimiterHelpSuffix + SDelimiterUsage;
end;
class function TMoveToDelimiter.GetName: string;
begin
Result := 'MoveToDelimiter';
end;
{ TLocateDelimiter }
constructor TLocateDelimiter.Create;
begin
inherited Create;
ThreeDelimiters := False;
end;
procedure TLocateDelimiter.DoDelimiterAction(Editor: IOTASourceEditor;
Offset: Integer; SChar, EChar: TOTACharPos);
var
EditView: IOTAEditView;
EditPos: TOTAEditPos;
begin
EditView := GxOtaGetTopMostEditView(Editor);
EditView.ConvertPos(False, EditPos, SChar);
EditView.CursorPos := EditPos;
if (EChar.Line > SChar.Line) or ((EChar.Line = SChar.Line) and (EChar.CharIndex > SChar.CharIndex)) then
GxOtaSelectBlock(Editor, SChar, EChar)
else
GxOtaSelectBlock(Editor, EChar, SChar);
end;
function TLocateDelimiter.GetDefaultShortCut: TShortCut;
begin
Result := scCtrl + scAlt + VK_LEFT;
end;
function TLocateDelimiter.GetDisplayName: string;
resourcestring
SLocateDelimiterName = 'Locate Matching Delimiter';
begin
Result := SLocateDelimiterName;
end;
function TLocateDelimiter.GetHelpString: string;
begin
Result := SDelimiterHelpPrefix + SDelimiterLocateMessage +
SDelimiterHelpSuffix + SDelimiterUsage;
end;
class function TLocateDelimiter.GetName: string;
begin
Result := 'LocateDelimiter';
end;
initialization
RegisterEditorExpert(TLocateDelimiter);
RegisterEditorExpert(TMoveToDelimiter);
end.
|
unit evSavedCursor;
{* Объект для сохранения курсора. }
// Модуль: "w:\common\components\gui\Garant\Everest\evSavedCursor.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "evSavedCursor" MUID: (47E3E20C02D1)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
{$If Defined(evUseVisibleCursors)}
uses
l3IntfUses
, l3ProtoObject
, nevTools
;
type
PevSavedCursor = ^TevSavedCursor;
TevSavedCursor = class(Tl3ProtoObject)
{* Объект для сохранения курсора. }
private
f_Cursor: InevBasePoint;
{* курсор, который изменялся. }
f_Old: IevSavedCursor;
{* старое значение курсора. }
f_New: IevSavedCursor;
{* новое значение курсора. }
protected
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure ClearFields; override;
public
constructor Create(const aCursor: InevBasePoint;
const aOld: IevSavedCursor;
const aNew: IevSavedCursor); reintroduce;
public
property Cursor: InevBasePoint
read f_Cursor
write f_Cursor;
{* курсор, который изменялся. }
property Old: IevSavedCursor
read f_Old
write f_Old;
{* старое значение курсора. }
property New: IevSavedCursor
read f_New
write f_New;
{* новое значение курсора. }
end;//TevSavedCursor
{$IfEnd} // Defined(evUseVisibleCursors)
implementation
{$If Defined(evUseVisibleCursors)}
uses
l3ImplUses
//#UC START# *47E3E20C02D1impl_uses*
//#UC END# *47E3E20C02D1impl_uses*
;
constructor TevSavedCursor.Create(const aCursor: InevBasePoint;
const aOld: IevSavedCursor;
const aNew: IevSavedCursor);
//#UC START# *47E3E1DE01E5_47E3DFD00379_var*
//#UC END# *47E3E1DE01E5_47E3DFD00379_var*
begin
//#UC START# *47E3E1DE01E5_47E3DFD00379_impl*
inherited Create;
Cursor := aCursor;
Old := aOld;
New := aNew;
//#UC END# *47E3E1DE01E5_47E3DFD00379_impl*
end;//TevSavedCursor.Create
procedure TevSavedCursor.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_47E3DFD00379_var*
//#UC END# *479731C50290_47E3DFD00379_var*
begin
//#UC START# *479731C50290_47E3DFD00379_impl*
Cursor := nil;
Old := nil;
New := nil;
inherited;
//#UC END# *479731C50290_47E3DFD00379_impl*
end;//TevSavedCursor.Cleanup
procedure TevSavedCursor.ClearFields;
begin
Cursor := nil;
Old := nil;
New := nil;
inherited;
end;//TevSavedCursor.ClearFields
{$IfEnd} // Defined(evUseVisibleCursors)
end.
|
unit UInstagramDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSCloudBase,
FMX.TMSCloudInstagram, FMX.StdCtrls, FMX.Objects,
FMX.Layouts, FMX.ListBox, FMX.TMSCloudImage, FMX.ListView.Types, FMX.ListView,
FMX.TabControl, FMX.Edit, IOUtils, FMX.TMSCloudBaseFMX,
FMX.TMSCloudCustomInstagram;
type
TForm1017 = class(TForm)
TMSFMXCloudInstagram1: TTMSFMXCloudInstagram;
ToolBar1: TToolBar;
ConnectBtn: TButton;
DisconnectBtn: TButton;
Button1: TButton;
TMSFMXCloudImage1: TTMSFMXCloudImage;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
ListView1: TListView;
ListView2: TListView;
Button2: TButton;
Label1: TLabel;
TabControl1: TTabControl;
TabItem1: TTabItem;
TabItem2: TTabItem;
edSearchUsers: TEdit;
Button3: TButton;
ListView3: TListView;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
Label17: TLabel;
Label18: TLabel;
Label19: TLabel;
Label20: TLabel;
Label21: TLabel;
TMSFMXCloudImage2: TTMSFMXCloudImage;
Button4: TButton;
procedure FormCreate(Sender: TObject);
procedure ConnectBtnClick(Sender: TObject);
procedure DisconnectBtnClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TMSFMXCloudInstagram1ReceivedAccessToken(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ListView1Change(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure ListView3Change(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
Connected: Boolean;
FCurrentUser: TInstagramUser;
procedure GetUserProfile;
procedure GetPhotoInfo;
procedure GetUserInfo;
procedure LoadFeed;
public
{ Public declarations }
end;
var
Form1017: TForm1017;
implementation
{$R *.fmx}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// InstagramAppkey = 'xxxxxxxxx';
// InstagramAppSecret = 'yyyyyyyy';
{$I APPIDS.INC}
procedure TForm1017.Button1Click(Sender: TObject);
begin
if not Connected then
begin
ShowMessage('Please authenticate first');
Exit;
end;
LoadFeed;
end;
procedure TForm1017.Button2Click(Sender: TObject);
begin
if not Connected then
begin
ShowMessage('Please authenticate first');
Exit;
end;
if ListView1.ItemIndex > -1 then
ShowMessage(TMSFMXCloudInstagram1.Photos[ListView1.ItemIndex].Link);
end;
procedure TForm1017.Button3Click(Sender: TObject);
var
I: Integer;
begin
if not Connected then
begin
ShowMessage('Please authenticate first');
Exit;
end;
if edSearchUsers.Text <> '' then
begin
TMSFMXCloudInstagram1.Users.Clear;
TMSFMXCloudInstagram1.Tags.Clear;
TMSFMXCloudInstagram1.SearchUsers(edSearchUsers.Text);
ListView3.Items.Clear;
for I := 0 to TMSFMXCloudInstagram1.Users.Count - 1 do
ListView3.Items.Add.Text := TMSFMXCloudInstagram1.Users[I].User.UserName;
end;
end;
procedure TForm1017.Button4Click(Sender: TObject);
var
I: integer;
begin
if ListView1.Items.Count > 0 then
begin
Button4.Enabled := TMSFMXCloudInstagram1.GetFeed(20,TMSFMXCloudInstagram1.Photos[TMSFMXCloudInstagram1.Photos.Count - 1].ID,'');
ListView1.Items.Clear;
for I := 0 to TMSFMXCloudInstagram1.Photos.Count - 1 do
begin
if TMSFMXCloudInstagram1.Photos[I].Caption <> '' then
ListView1.Items.Add.Text := TMSFMXCloudInstagram1.Photos[I].Caption
else
ListView1.Items.Add.Text := 'Photo ' + IntToStr(I + 1);
end;
ListView1.ItemIndex := 0;
GetPhotoInfo;
end;
end;
procedure TForm1017.ConnectBtnClick(Sender: TObject);
var
acc: boolean;
begin
FCurrentUser := TInstagramUser.Create;
TMSFMXCloudInstagram1.App.Key := InstagramAppkey;
TMSFMXCloudInstagram1.App.Secret := InstagramAppSecret;
if TMSFMXCloudInstagram1.App.Key <> '' then
begin
TMSFMXCloudInstagram1.PersistTokens.Key := TPath.GetDocumentsPath + '/Instagram.ini';
TMSFMXCloudInstagram1.PersistTokens.Section := 'tokens';
TMSFMXCloudInstagram1.LoadTokens;
acc := TMSFMXCloudInstagram1.TestTokens;
if not acc then
begin
TMSFMXCloudInstagram1.RefreshAccess;
acc := TMSFMXCloudInstagram1.TestTokens;
if not acc then
TMSFMXCloudInstagram1.DoAuth;
end
else
begin
Connected := true;
GetUserProfile;
end;
end
else
ShowMessage('Please provide a valid application ID for the client component');
end;
procedure TForm1017.DisconnectBtnClick(Sender: TObject);
begin
if Assigned(FCurrentUser) then
begin
FCurrentUser.Free;
FCurrentUser := nil;
end;
TMSFMXCloudInstagram1.LogOut;
TMSFMXCloudInstagram1.ClearTokens;
TMSFMXCloudImage1.URL := '';
TMSFMXCloudImage2.URL := '';
Label1.Text := '';
Connected := false;
edSearchUsers.Text := '';
ListView1.Items.Clear;
ListView2.Items.Clear;
ListView3.Items.Clear;
Label3.Text := '';
Label4.Text := '';
Label6.Text := '';
Label8.Text := '';
Label10.Text := '';
Label13.Text := '';
label20.Text := '';
Label16.Text := '';
Label19.Text := '';
Label17.Text := '';
end;
procedure TForm1017.FormCreate(Sender: TObject);
begin
Connected := false;
end;
procedure TForm1017.FormDestroy(Sender: TObject);
begin
if Assigned(FCurrentUser) then
begin
FCurrentUser.Free;
FCurrentUser := nil;
end;
end;
procedure TForm1017.GetPhotoInfo;
var
ph: TInstagramPhoto;
I: Integer;
li: TListViewITem;
begin
if ListView1.ItemIndex > -1 then
begin
ph := TMSFMXCloudInstagram1.Photos[ListView1.ItemIndex];
TMSFMXCloudImage1.URL := ph.Images.Thumbnail.URL;
Label3.Text := ph.Location.Summary;
Label4.Text := ph.Filter;
Label6.Text := ph.Link;
Label8.Text := DateTimeToStr(ph.CreatedTime);
Label10.Text := IntToStr(ph.LikesCount);
Label13.Text := ph.From.FullName;
ListView2.Items.Clear;
for I := 0 to ph.Comments.Count - 1 do
begin
li := ListView2.Items.Add;
li.Detail := ph.Comments[I].From.FullName;
li.Text := ph.Comments[I].Text;
end;
end;
end;
procedure TForm1017.GetUserInfo;
var
User: TInstagramUser;
begin
if ListView3.ItemIndex > -1 then
begin
if TMSFMXCloudInstagram1.Users.Count > 0 then
begin
User := TMSFMXCloudInstagram1.Users[ListView3.ItemIndex].User;
TMSFMXCloudInstagram1.GetProfile(User.ID, User);
end
else
User := TMSFMXCloudInstagram1.Profile;
TMSFMXCloudImage2.URL := User.ProfilePicture;
Label20.Text := User.UserName;
Label16.Text := User.Bio;
Label19.Text := User.Website;
Label17.Text := 'Photos: ' + IntToStr(User.Photos)
+ ' Followers: ' + IntToStr(User.Followers)
+ ' Following: ' + IntToStr(User.Following);
end;
end;
procedure TForm1017.GetUserProfile;
begin
TMSFMXCloudInstagram1.GetProfile('', FCurrentUser);
if FCurrentUser.UserName <> '' then
Label1.Text := 'Welcome ' + FCurrentUser.UserName;
end;
procedure TForm1017.ListView1Change(Sender: TObject);
begin
GetPhotoInfo;
end;
procedure TForm1017.ListView3Change(Sender: TObject);
begin
GetUserInfo;
end;
procedure TForm1017.LoadFeed;
var
I: integer;
begin
Button4.Enabled := TMSFMXCloudInstagram1.GetFeed;
if TMSFMXCloudInstagram1.Photos.Count > 0 then
begin
ListView1.Items.Clear;
for I := 0 to TMSFMXCloudInstagram1.Photos.Count - 1 do
begin
if TMSFMXCloudInstagram1.Photos[I].Caption <> '' then
ListView1.Items.Add.Text := TMSFMXCloudInstagram1.Photos[I].Caption
else
ListView1.Items.Add.Text := 'Photo ' + IntToStr(I + 1);
end;
ListView1.ItemIndex := 0;
end;
end;
procedure TForm1017.TMSFMXCloudInstagram1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudInstagram1.SaveTokens;
Connected := true;
GetUserProfile;
end;
end.
|
unit fmIOCPSvrInfo;
interface
{$I in_iocp.inc} // 模式设置
uses
Windows, Messages, SysUtils, Variants, Classes,
Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls,
Grids, iocp_server;
type
TFrameIOCPSvrInfo = class(TFrame)
lbl1: TLabel;
lblStartTime: TLabel;
lblCliPool: TLabel;
lblClientInfo: TLabel;
lbl3: TLabel;
lblIODataInfo: TLabel;
lbl6: TLabel;
lblThreadInfo: TLabel;
lblLeftEdge: TLabel;
lblDataPackInf: TLabel;
lbl14: TLabel;
lblDBConCount: TLabel;
lbl16: TLabel;
lblDataByteInfo: TLabel;
lblMemeryUsed: TLabel;
lblMemUsed: TLabel;
lbl19: TLabel;
lblWorkTimeLength: TLabel;
bvl1: TBevel;
lbl12: TLabel;
lblCheckTime: TLabel;
lblAcceptExCount: TLabel;
lblAcceptExCnt: TLabel;
Label3: TLabel;
lblWorkCount: TLabel;
private
{ Private declarations }
FServer: TInIOCPServer; // 服务器
FTimer: TTimer; // 计算器
FRefreshCount: Cardinal; // 刷新次数
FShowing: Boolean; // 是否在前端显示
procedure GetServerInfo(Sender: TObject);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start(AServer: TInIOCPServer);
procedure Stop;
property Showing: Boolean read FShowing write FShowing;
end;
implementation
uses
iocp_base, iocp_utils;
var
FMaxInfo: TWorkThreadMaxInf; // 最大处理速度
{$R *.dfm}
{ TFrameIOCPSvrInfo }
constructor TFrameIOCPSvrInfo.Create(AOwner: TComponent);
begin
inherited;
FTimer := TTimer.Create(Self);
FTimer.Enabled := False;
FTimer.Interval := 1000; // 间隔一秒
FTimer.OnTimer := GetServerInfo;
FShowing := True;
lblStartTime.Caption := '未启动';
end;
destructor TFrameIOCPSvrInfo.Destroy;
begin
inherited;
end;
procedure TFrameIOCPSvrInfo.GetServerInfo(Sender: TObject);
var
ActiveCount: Integer;
CountA, CountB: Integer;
CountC, CountD, CountE: Integer;
WorkTotalCount: IOCP_LARGE_INTEGER;
CheckTimeOut: TDateTime;
ThreadSummary: TWorkThreadSummary;
begin
// 服务停止或不在前端,无需调用
Inc(FRefreshCount, 1); // 增加 1 秒
if (FShowing = False) or (FServer.Active = False) then
Exit;
FTimer.Enabled := False;
try
// 改为蓝色
if (Tag = 0) then
begin
Tag := 1;
lblWorkTimeLength.Font.Color := clBlue;
lblClientInfo.Font.Color := clBlue;
lblWorkCount.Font.Color := clBlue;
lblIODataInfo.Font.Color := clBlue;
lblThreadInfo.Font.Color := clBlue;
lblDataPackInf.Font.Color := clBlue;
lblDataByteInfo.Font.Color := clBlue;
lblCheckTime.Font.Color := clBlue;
lblAcceptExCnt.Font.Color := clBlue;
lblMemUsed.Font.Color := clBlue;
lblDBConCount.Font.Color := clBlue;
end;
lblWorkTimeLength.Caption := GetTimeLengthEx(FRefreshCount);
// 1. C/S、HTTP 模式:Socket 总数、连接数,活动数=在业务线程数
FServer.GetClientInfo(CountA, CountB, CountC,
CountD, ActiveCount, WorkTotalCount);
if Assigned(FServer.IOCPBroker) then // 代理模式无Http、推送功能
lblClientInfo.Caption := '总计:' + IntToStr(CountA + CountC) +
',C/S:' + IntToStr(CountB) { 连接的 } +
',活动:' + IntToStr(ActiveCount) + '.' { 在列的业务+推送数 }
else
lblClientInfo.Caption := '总计:' + IntToStr(CountA + CountC) +
',C/S:' + IntToStr(CountB) { 连接的 } +
',HTTP:' + IntToStr(CountD) { 连接的 } +
',活动:' + IntToStr(ActiveCount) + '.' { 在列的业务+推送数 } ;
lblWorkCount.Caption := IntToStr(WorkTotalCount);
// 2. TPerIOData 池:总数、C/S 使用、HTTP使用、推送列表使用
// Socket 的 RecvBuf 不回收,推送的 TPerIOData 回收,所以:
// CountA >= CountB + CountC + FServer.BusiWorkMgr.ThreadCount
FServer.GetIODataInfo(CountA, CountB, CountC, CountD, CountE);
if (Assigned(FServer.PushManager) = False) then // 无 Http、推送功能
lblIODataInfo.Caption := '总计:' + IntToStr(CountA) +
',C/S:' + IntToStr(CountB) { 活动的 } +
',发送器:' + IntToStr(CountE)
else
lblIODataInfo.Caption := '总计:' + IntToStr(CountA) +
',C/S:' + IntToStr(CountB) { 活动的 } +
',HTTP:' + IntToStr(CountC) { 活动的 } +
',发送器:' + IntToStr(CountE) +
',推送:' + IntToStr(CountD) + '.';
// 3. 线程使用:工作线程、超时检查、关闭套接字、
// 业务线程、推送线程(+1)、活动数
FServer.GetThreadInfo(@ThreadSummary, CountA, CountB, CountC, CountD, CheckTimeOut);
if (Assigned(FServer.PushManager) = False) then // 代理模式无推送功能
lblThreadInfo.Caption := '总计:' + IntToStr(FServer.WorkThreadCount + CountA + CountC + 2) +
',工作:' + IntToStr(ThreadSummary.ActiveCount) { 活动的 } + '/' +
IntToStr(FServer.WorkThreadCount) +
',业务:' + IntToStr(CountB) { 活动的 } + '/' + IntToStr(CountA) +
',超时:1,关闭:1.'
else
lblThreadInfo.Caption := '总计:' + IntToStr(FServer.WorkThreadCount + CountA + CountC + 3) +
',工作:' + IntToStr(ThreadSummary.ActiveCount) { 活动的 } + '/' +
IntToStr(FServer.WorkThreadCount) +
',业务:' + IntToStr(CountB) { 活动的 } + '/' + IntToStr(CountA) +
',推送:' + IntToStr(CountD) { 活动的 } + '/' + IntToStr(CountC) + '+1' +
',超时:1,关闭:1.';
// 4. 处理速度(包/秒)
if (ThreadSummary.PackInCount > FMaxInfo.MaxPackIn) then
FMaxInfo.MaxPackIn := ThreadSummary.PackInCount;
if (ThreadSummary.PackOutCount > FMaxInfo.MaxPackOut) then
FMaxInfo.MaxPackOut := ThreadSummary.PackOutCount;
lblDataPackInf.Caption := '总计:' + IntToStr(ThreadSummary.PackCount) + { '/' +
IntToStr(FMaxInfo.MaxPackIn + FMaxInfo.MaxPackOut) + }
',接收:' + IntToStr(ThreadSummary.PackInCount) + '/' +
IntToStr(FMaxInfo.MaxPackIn) +
',发送:' + IntToStr(ThreadSummary.PackOutCount) + '/' +
IntToStr(FMaxInfo.MaxPackOut);
// 5. 处理速度(字节/秒)
if (ThreadSummary.ByteInCount > FMaxInfo.MaxByteIn) then
FMaxInfo.MaxByteIn := ThreadSummary.ByteInCount;
if (ThreadSummary.ByteOutCount > FMaxInfo.MaxByteOut) then
FMaxInfo.MaxByteOut := ThreadSummary.ByteOutCount;
lblDataByteInfo.Caption := '总计:' + GetTransmitSpeed(ThreadSummary.ByteCount {,
FMaxInfo.MaxByteIn + FMaxInfo.MaxByteOut } ) +
',接收:' + GetTransmitSpeed(ThreadSummary.ByteInCount, FMaxInfo.MaxByteIn) +
',发送:' + GetTransmitSpeed(ThreadSummary.ByteOutCount, FMaxInfo.MaxByteOut);
// 6. 超时检查时间
if (CheckTimeOut > 0.1) then
lblCheckTime.Caption := TimeToStr(CheckTimeOut);
// 7. Socket 投放数, 内存使用情况
FServer.GetAcceptExCount(ActiveCount);
lblAcceptExCnt.Caption := IntToStr(ActiveCount);
lblMemUsed.Caption := GetTransmitSpeed(GetProcMemoryUsed);
// 7.1 数模实例数
if (lblDBConCount.Caption = '-') and
Assigned(TInIOCPServer(FServer).DatabaseManager) then
lblDBConCount.Caption := IntToStr(CountA) + '*' + // CountA 未改变
IntToStr(TInIOCPServer(FServer).DatabaseManager.DataModuleCount);
finally
// 解锁屏幕,刷新
FTimer.Enabled := True;
end;
end;
procedure TFrameIOCPSvrInfo.Start(AServer: TInIOCPServer);
begin
FServer := AServer;
FillChar(FMaxInfo, SizeOf(TWorkThreadMaxInf), 0);
if not FServer.Active then
FServer.Active := True;
if FServer.Active then
begin
FRefreshCount := 0;
lblStartTime.Font.Color := clBlue;
lblStartTime.Caption := FormatDateTime('yyyy-mm-dd hh:mm:ss', Now);
lblCheckTime.Caption := '';
FTimer.Enabled := True;
end;
end;
procedure TFrameIOCPSvrInfo.Stop;
begin
if Assigned(FServer) then
begin
if FTimer.Enabled then
FTimer.Enabled := False;
if FServer.Active then
FServer.Active := False;
lblStartTime.Font.Color := clRed;
lblStartTime.Caption := '服务停止';
end;
end;
end.
|
unit UnitData;
{*------------------------------------------------------------------------------
@author 侯叶飞
@version 2020/01/29 1.0 Initial revision.
@comment 存储图形数据的结构
每一种图形有4个方格组成
数组(长度应该是4) 你可以自己定义数组,也可以使用系统(Delphi)自带的
array 0...3 of TPoint TArray<T> array of T
使用TList<T>
每一种图形由4对坐标组成
我们使用TPoint来表示坐标,这个结构体本身就有两个字段是X,Y
4对坐标需要存储到一个容器,TList<T>
TList<TList<TPoint>>
-------------------------------------------------------------------------------}
interface
uses
System.Types, System.Generics.Collections;
type
TGameData = class
private
ActList: TList<TList<TPoint>>; //图形列表
Points: Tlist<Tpoint>; //我们每一种图形的数据
public
//该函数因为是类函数,所以不需要通过该类对象进行调用
function GetActByIndex(ActIndex: Integer): TList<TPoint>;
constructor Create(); overload;
end;
type
//该数据类型表示存储已经到达边界的方格的地图数据
TGameMap = array[0..17] of array[0..17] of Boolean;
implementation
{ TGameData }
{*------------------------------------------------------------------------------
根据编号(索引)返回对应的图形数据
@param ActIndex 图形编号,取值范围0---6
@return 指定的图形数据
-------------------------------------------------------------------------------}
constructor TGameData.Create;
begin
//创建列表对象
ActList := TList<TList<TPoint>>.Create;
//创建图形数据
Points := TList<TPoint>.Create();
//一字型
Points.Add(TPoint.create(6, 0));
Points.Add(TPoint.Create(7, 0));
Points.Add(TPoint.Create(8, 0));
Points.Add(TPoint.Create(9, 0));
//将该图形的数据存入列表
ActList.Add(Points);
Points := TList<TPoint>.Create();
//T字型
Points.Add(TPoint.Create(6, 0));
Points.Add(TPoint.Create(7, 0));
Points.Add(TPoint.Create(8, 0));
Points.Add(TPoint.Create(7, 1));
ActList.Add(Points);
//L字型
Points := TList<TPoint>.Create();
Points.Add(TPoint.Create(6, 0));
Points.Add(TPoint.Create(5, 0));
Points.Add(TPoint.Create(7, 0));
Points.Add(TPoint.Create(5, 1));
ActList.Add(Points);
//Z字型
Points := TList<TPoint>.Create();
Points.Add(TPoint.Create(6, 0));
Points.Add(TPoint.Create(7, 0));
Points.Add(TPoint.Create(5, 1));
Points.Add(TPoint.Create(6, 1));
ActList.Add(Points);
//反Z字型
Points := TList<TPoint>.Create();
Points.Add(TPoint.Create(6, 0));
Points.Add(TPoint.Create(5, 0));
Points.Add(TPoint.Create(6, 1));
Points.Add(TPoint.Create(7, 1));
ActList.Add(Points);
// 丁 字型
Points := TList<TPoint>.Create();
Points.Add(TPoint.Create(6, 0));
Points.Add(TPoint.Create(5, 0));
Points.Add(TPoint.Create(7, 0));
Points.Add(TPoint.Create(7, 1));
ActList.Add(Points);
//田字型
Points := TList<TPoint>.Create();
Points.Add(TPoint.Create(6, 0));
Points.Add(TPoint.Create(7, 0));
Points.Add(TPoint.Create(6, 1));
Points.Add(TPoint.Create(7, 1));
ActList.Add(Points);
end;
function TGameData.GetActByIndex(ActIndex: Integer): TList<TPoint>;
begin
Result := ActList.Items[ActIndex];
end;
initialization
end.
|
unit ce_inspectors;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, Dialogs, PropEdits;
type
TCEPathname = type string;
TCEFilename = type string;
TCustomPathType = (ptFile, ptFolder);
// base class for a property representing a path
// additionaly to the text field, a dialog can be opened
// to select the directory or the file.
TCECustomPathEditor = class(TStringPropertyEditor)
private
fType: TCustomPathType;
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TCEPathnameEditor = class(TCECustomPathEditor)
constructor Create(Hook: TPropertyEditorHook; APropCount: Integer); override;
end;
TCEFilenameEditor = class(TCECustomPathEditor)
constructor Create(Hook: TPropertyEditorHook; APropCount: Integer); override;
end;
implementation
function TCECustomPathEditor.GetAttributes: TPropertyAttributes;
begin
exit( inherited GetAttributes() + [paDialog]);
end;
procedure TCECustomPathEditor.Edit;
var
newValue: string;
begin
case fType of
ptFile:
with TOpenDialog.create(nil) do try
InitialDir := ExtractFileName(GetValue);
FileName := GetValue;
if Execute then SetValue(FileName);
finally
free;
end;
ptFolder:
if SelectDirectory(GetPropInfo^.Name, GetValue, newValue) then
SetValue(newValue);
end;
end;
constructor TCEPathnameEditor.Create(Hook: TPropertyEditorHook; APropCount: Integer);
begin
inherited;
fType := ptFolder;
end;
constructor TCEFilenameEditor.Create(Hook: TPropertyEditorHook; APropCount: Integer);
begin
inherited;
fType := ptFile;
end;
initialization
RegisterPropertyEditor(TypeInfo(TCEPathname), nil, '', TCEPathnameEditor);
RegisterPropertyEditor(TypeInfo(TCEFilename), nil, '', TCEfilenameEditor);
end.
|
unit dcComboBox;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, dbctrls, datacontroller,db, lucombo, lmdcombobox;
type
TOpMode = (opString, opInt);
TdcComboBox = class(TlmdComboBox)
private
Fclearing: boolean;
FOpMode: TOpMode;
FReturnBlankIfZero: boolean;
FSaveLength: integer;
procedure Setclearing(const Value: boolean);
procedure SetOpMode(const Value: TOpMode);
function GetDataBufIndex: integer;
procedure SetDataBufIndex(const Value: integer);
procedure SetReturnBlankIfZero(const Value: boolean);
procedure SetSaveLength(const Value: integer);
private
{ Private declarations }
fdcLink : TdcLink;
OriginalText : string;
OriginalIndex : integer;
property clearing:boolean read Fclearing write Setclearing;
protected
{ Protected declarations }
// std data awareness
function GetDataSource:TDataSource;
procedure SetDataSource(value:Tdatasource);
function GetDataField:string;
procedure SetDataField(value:string);
// data controller
function GetDataController:TDataController;
procedure SetDataController(value:TDataController);
procedure ReadData(sender:TObject);
procedure WriteData(sender:TObject);
public
{ Public declarations }
constructor Create(AOwner:Tcomponent);override;
destructor Destroy;override;
published
{ Published declarations }
property DataController : TDataController read GetDataController write setDataController;
property DataField : String read GetDataField write SetDataField;
property DataSource : TDataSource read getDataSource write SetDatasource;
property OpMode:TOpMode read FOpMode write SetOpMode;
property DataBufIndex:integer read GetDataBufIndex write SetDataBufIndex;
property ReturnBlankIfZero:boolean read FReturnBlankIfZero write SetReturnBlankIfZero;
property SaveLength:integer read FSaveLength write SetSaveLength;
end;
procedure Register;
implementation
constructor TdcComboBox.Create(AOwner:Tcomponent);
begin
inherited;
fdclink := tdclink.create(self);
fdclink.OnReadData := ReadData;
fdclink.OnWriteData := WriteData;
end;
destructor TdcComboBox.Destroy;
begin
fdclink.free;
inherited;
end;
procedure TdcComboBox.SetDataController(value:TDataController);
begin
fdcLink.datacontroller := value;
end;
function TdcComboBox.GetDataController:TDataController;
begin
result := fdcLink.DataController;
end;
procedure TdcComboBox.SetDataSource(value:TDataSource);
begin
end;
function TdcComboBox.GetDataField:string;
begin
result := fdclink.FieldName;
end;
function TdcComboBox.GetDataSource:TDataSource;
begin
result := fdclink.DataSource;
end;
procedure TdcComboBox.SetDataField(value:string);
begin
fdclink.FieldName := value;
end;
procedure TdcComboBox.ReadData;
var i : integer;
found : boolean;
begin
if not assigned(fdclink.DataController) then exit;
case OpMode of
opString : begin
OriginalText := '';
if (DataBufIndex = 0) and (DataField <> '') then OriginalText := fdcLink.DataController.dcStrings.StrVal[DataField]
else if assigned(fdclink.datacontroller.databuf) then OriginalText := fdclink.datacontroller.databuf.AsString[DataBufIndex];
if Style = csDropDownList then begin
if SaveLength > 0 then OriginalText := copy(OriginalText, 1, SaveLength);
i := 0;
found := false;
while (i < items.count) and (not found) do begin
if copy(items[i],1,length(OriginalText)) = OriginalText then found := true
else inc(i);
end;
if found then itemindex := i
else Itemindex := 0;
end
else Text := OriginalText;
end;
opInt : begin
OriginalIndex := 0;
if (DataBufIndex = 0) and (DataField <> '') then OriginalIndex := fdcLink.DataController.dcStrings.IntVal[DataField]
else if assigned(fdclink.datacontroller.databuf) then OriginalIndex := fdclink.datacontroller.databuf.AsInt[DataBufIndex];
itemindex := OriginalIndex;
end;
end;
end;
procedure TdcComboBox.WriteData;
var s : string;
begin
if not assigned(fdclink.DataController) then exit;
case OpMode of
opString : begin
if (style = csDropDownList) and (itemindex = 0) and (ReturnBlankIfZero) then s := ''
else s := Text;
if SaveLength > 0 then s := copy(s,1,SaveLength);
if (DataBufIndex = 0) and (DataField <> '') then fdcLink.DataController.dcStrings.StrVal[DataField] := s
else if assigned(fdclink.datacontroller.databuf) then fdclink.datacontroller.databuf.AsString[DataBufIndex] := s;
end;
opInt : if (DataBufIndex = 0) and (DataField <> '') then fdcLink.DataController.dcStrings.IntVal[DataField] := ItemIndex
else if assigned(fdclink.datacontroller.databuf) then fdclink.datacontroller.databuf.AsInt[DataBufIndex] := ItemIndex;
end;
end;
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TdcComboBox]);
end;
procedure TdcComboBox.Setclearing(const Value: boolean);
begin
Fclearing := Value;
end;
procedure TdcComboBox.SetOpMode(const Value: TOpMode);
begin
FOpMode := Value;
end;
function TdcComboBox.GetDataBufIndex: integer;
begin
result := 0;
if assigned(fdclink.Datacontroller) then
if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName);
end;
procedure TdcComboBox.SetDataBufIndex(const Value: integer);
begin
end;
procedure TdcComboBox.SetReturnBlankIfZero(const Value: boolean);
begin
FReturnBlankIfZero := Value;
end;
procedure TdcComboBox.SetSaveLength(const Value: integer);
begin
FSaveLength := Value;
end;
end.
|
unit uDV_Stavy;
interface
uses
Data.Win.ADODB, System.Classes, uMainDataSet;
type
TDV_Stavy = class
private
class function GetId: string; static;
class function GetStav: string; static;
class function GetIkona: string; static;
public
class function CreateDV_Stavy(AOwner: TComponent): TMainDataSet; static;
class function GetTabName: string;
class property Id: string read GetId;
class property Stav: string read GetStav;
class property Ikona: string read GetIkona;
end;
implementation
{ TDV_Stavy }
class function TDV_Stavy.CreateDV_Stavy(AOwner: TComponent): TMainDataSet;
begin
Result := TMainDataSet.Create(AOwner);
Result.CommandText := 'SELECT * FROM ' + TDV_Stavy.GetTabName;
end;
class function TDV_Stavy.GetId: string;
begin
Result := 'id';
end;
class function TDV_Stavy.GetIkona: string;
begin
Result := 'ikona';
end;
class function TDV_Stavy.GetStav: string;
begin
Result := 'stav';
end;
class function TDV_Stavy.GetTabName: string;
begin
Result := 'tabStavy';
end;
end.
|
unit TThrobber;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls;
type
{ TTThrobber }
TTThrobber = class(TImage)
private
ftimer:ttimer;
factive:boolean;
fframes,
findex,
finterval:integer;
fpath,
fimage,
fext:string;
procedure setactive(Value: boolean);
procedure Animate(Sender: TObject);// of object;
procedure setinterval(Value: integer);
Procedure setpath(value:string);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
Property Active:boolean read factive write setactive;
Property Path:string read fpath write setpath;
Property ImageFile:string read fimage write fimage;
Property Extension:string read fext write fext;
Property Frames:integer read fframes write fframes default 8;
Property Interval:integer read finterval write setinterval default 300;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Touch',[TTThrobber]);
end;
{ TTThrobber }
procedure TTThrobber.setactive(Value: boolean);
begin
factive:=value;
visible:=value;
BringToFront;
ftimer.Enabled:=value;
end;
procedure TTThrobber.Animate(Sender: TObject);
begin
if (fpath='') or (fext='') or (fimage='') then exit;
findex:=findex+1;
if findex>fframes then findex:=1;
picture.LoadFromFile(fpath+fimage+'_'+inttostr(findex)+fext);
end;
procedure TTThrobber.setinterval(Value: integer);
begin
finterval:=value;
ftimer.Interval:=value;
end;
procedure TTThrobber.setpath(value: string);
begin
fpath:=IncludeTrailingPathDelimiter(value);
end;
constructor TTThrobber.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ftimer:=ttimer.Create(aowner);
factive:=false;
fframes:=0;
fpath:='';
fimage:='';
fext:='.png';
findex:=0;
finterval:=300;
ftimer.OnTimer:=@animate;
ftimer.Interval:=finterval;
end;
destructor TTThrobber.Destroy;
begin
ftimer.Enabled:=false;
ftimer.free;
inherited Destroy;
end;
end.
|
unit ComponentsProcessingPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\ComponentsProcessingPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "ComponentsProcessingPack" MUID: (54F452710048)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, Classes
;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwClassLike
, tfwScriptingInterfaces
, TypInfo
, tfwPropertyLike
, tfwTypeInfo
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *54F452710048impl_uses*
//#UC END# *54F452710048impl_uses*
;
type
TkwPopComponentGetComponent = {final} class(TtfwClassLike)
{* Слово скрипта pop:Component:GetComponent }
private
function GetComponent(const aCtx: TtfwContext;
aComponent: TComponent;
anIndex: Integer): TComponent;
{* Реализация слова скрипта pop:Component:GetComponent }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopComponentGetComponent
TkwPopComponentFindComponent = {final} class(TtfwClassLike)
{* Слово скрипта pop:Component:FindComponent }
private
function FindComponent(const aCtx: TtfwContext;
aComponent: TComponent;
const aName: AnsiString): TComponent;
{* Реализация слова скрипта pop:Component:FindComponent }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopComponentFindComponent
TkwPopComponentComponentCount = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Component:ComponentCount }
private
function ComponentCount(const aCtx: TtfwContext;
aComponent: TComponent): Integer;
{* Реализация слова скрипта pop:Component:ComponentCount }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopComponentComponentCount
TkwPopComponentOwner = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Component:Owner }
private
function Owner(const aCtx: TtfwContext;
aComponent: TComponent): TComponent;
{* Реализация слова скрипта pop:Component:Owner }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopComponentOwner
TkwPopComponentName = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Component:Name }
private
function Name(const aCtx: TtfwContext;
aComponent: TComponent): AnsiString;
{* Реализация слова скрипта pop:Component:Name }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopComponentName
function TkwPopComponentGetComponent.GetComponent(const aCtx: TtfwContext;
aComponent: TComponent;
anIndex: Integer): TComponent;
{* Реализация слова скрипта pop:Component:GetComponent }
//#UC START# *54F9BCB401D4_54F9BCB401D4_479878FA0103_Word_var*
//#UC END# *54F9BCB401D4_54F9BCB401D4_479878FA0103_Word_var*
begin
//#UC START# *54F9BCB401D4_54F9BCB401D4_479878FA0103_Word_impl*
Result := aComponent.Components[anIndex];
//#UC END# *54F9BCB401D4_54F9BCB401D4_479878FA0103_Word_impl*
end;//TkwPopComponentGetComponent.GetComponent
class function TkwPopComponentGetComponent.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Component:GetComponent';
end;//TkwPopComponentGetComponent.GetWordNameForRegister
function TkwPopComponentGetComponent.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TComponent);
end;//TkwPopComponentGetComponent.GetResultTypeInfo
function TkwPopComponentGetComponent.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopComponentGetComponent.GetAllParamsCount
function TkwPopComponentGetComponent.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TComponent), TypeInfo(Integer)]);
end;//TkwPopComponentGetComponent.ParamsTypes
procedure TkwPopComponentGetComponent.DoDoIt(const aCtx: TtfwContext);
var l_aComponent: TComponent;
var l_anIndex: Integer;
begin
try
l_aComponent := TComponent(aCtx.rEngine.PopObjAs(TComponent));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aComponent: TComponent : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_anIndex := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(GetComponent(aCtx, l_aComponent, l_anIndex));
end;//TkwPopComponentGetComponent.DoDoIt
function TkwPopComponentFindComponent.FindComponent(const aCtx: TtfwContext;
aComponent: TComponent;
const aName: AnsiString): TComponent;
{* Реализация слова скрипта pop:Component:FindComponent }
begin
Result := aComponent.FindComponent(aName);
end;//TkwPopComponentFindComponent.FindComponent
class function TkwPopComponentFindComponent.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Component:FindComponent';
end;//TkwPopComponentFindComponent.GetWordNameForRegister
function TkwPopComponentFindComponent.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TComponent);
end;//TkwPopComponentFindComponent.GetResultTypeInfo
function TkwPopComponentFindComponent.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopComponentFindComponent.GetAllParamsCount
function TkwPopComponentFindComponent.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TComponent), @tfw_tiString]);
end;//TkwPopComponentFindComponent.ParamsTypes
procedure TkwPopComponentFindComponent.DoDoIt(const aCtx: TtfwContext);
var l_aComponent: TComponent;
var l_aName: AnsiString;
begin
try
l_aComponent := TComponent(aCtx.rEngine.PopObjAs(TComponent));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aComponent: TComponent : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aName := aCtx.rEngine.PopDelphiString;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(FindComponent(aCtx, l_aComponent, l_aName));
end;//TkwPopComponentFindComponent.DoDoIt
function TkwPopComponentComponentCount.ComponentCount(const aCtx: TtfwContext;
aComponent: TComponent): Integer;
{* Реализация слова скрипта pop:Component:ComponentCount }
begin
Result := aComponent.ComponentCount;
end;//TkwPopComponentComponentCount.ComponentCount
class function TkwPopComponentComponentCount.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Component:ComponentCount';
end;//TkwPopComponentComponentCount.GetWordNameForRegister
function TkwPopComponentComponentCount.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwPopComponentComponentCount.GetResultTypeInfo
function TkwPopComponentComponentCount.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopComponentComponentCount.GetAllParamsCount
function TkwPopComponentComponentCount.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TComponent)]);
end;//TkwPopComponentComponentCount.ParamsTypes
procedure TkwPopComponentComponentCount.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству ComponentCount', aCtx);
end;//TkwPopComponentComponentCount.SetValuePrim
procedure TkwPopComponentComponentCount.DoDoIt(const aCtx: TtfwContext);
var l_aComponent: TComponent;
begin
try
l_aComponent := TComponent(aCtx.rEngine.PopObjAs(TComponent));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aComponent: TComponent : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(ComponentCount(aCtx, l_aComponent));
end;//TkwPopComponentComponentCount.DoDoIt
function TkwPopComponentOwner.Owner(const aCtx: TtfwContext;
aComponent: TComponent): TComponent;
{* Реализация слова скрипта pop:Component:Owner }
begin
Result := aComponent.Owner;
end;//TkwPopComponentOwner.Owner
class function TkwPopComponentOwner.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Component:Owner';
end;//TkwPopComponentOwner.GetWordNameForRegister
function TkwPopComponentOwner.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TComponent);
end;//TkwPopComponentOwner.GetResultTypeInfo
function TkwPopComponentOwner.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopComponentOwner.GetAllParamsCount
function TkwPopComponentOwner.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TComponent)]);
end;//TkwPopComponentOwner.ParamsTypes
procedure TkwPopComponentOwner.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Owner', aCtx);
end;//TkwPopComponentOwner.SetValuePrim
procedure TkwPopComponentOwner.DoDoIt(const aCtx: TtfwContext);
var l_aComponent: TComponent;
begin
try
l_aComponent := TComponent(aCtx.rEngine.PopObjAs(TComponent));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aComponent: TComponent : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(Owner(aCtx, l_aComponent));
end;//TkwPopComponentOwner.DoDoIt
function TkwPopComponentName.Name(const aCtx: TtfwContext;
aComponent: TComponent): AnsiString;
{* Реализация слова скрипта pop:Component:Name }
begin
Result := aComponent.Name;
end;//TkwPopComponentName.Name
class function TkwPopComponentName.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Component:Name';
end;//TkwPopComponentName.GetWordNameForRegister
function TkwPopComponentName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiString;
end;//TkwPopComponentName.GetResultTypeInfo
function TkwPopComponentName.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopComponentName.GetAllParamsCount
function TkwPopComponentName.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TComponent)]);
end;//TkwPopComponentName.ParamsTypes
procedure TkwPopComponentName.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Name', aCtx);
end;//TkwPopComponentName.SetValuePrim
procedure TkwPopComponentName.DoDoIt(const aCtx: TtfwContext);
var l_aComponent: TComponent;
begin
try
l_aComponent := TComponent(aCtx.rEngine.PopObjAs(TComponent));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aComponent: TComponent : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushString(Name(aCtx, l_aComponent));
end;//TkwPopComponentName.DoDoIt
initialization
TkwPopComponentGetComponent.RegisterInEngine;
{* Регистрация pop_Component_GetComponent }
TkwPopComponentFindComponent.RegisterInEngine;
{* Регистрация pop_Component_FindComponent }
TkwPopComponentComponentCount.RegisterInEngine;
{* Регистрация pop_Component_ComponentCount }
TkwPopComponentOwner.RegisterInEngine;
{* Регистрация pop_Component_Owner }
TkwPopComponentName.RegisterInEngine;
{* Регистрация pop_Component_Name }
TtfwTypeRegistrator.RegisterType(TypeInfo(TComponent));
{* Регистрация типа TComponent }
TtfwTypeRegistrator.RegisterType(TypeInfo(Integer));
{* Регистрация типа Integer }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа AnsiString }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit TextViaEditorProcessor;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "TestFormsTest"
// Модуль: "w:/common/components/gui/Garant/Daily/TextViaEditorProcessor.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TTextViaEditorProcessor
//
// Обработчик текста через редактор
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
{$If defined(nsTest) AND not defined(NoVCM)}
uses
TextEditorVisitor,
PrimTextLoad_Form
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
type
TTextViaEditorProcessor = {abstract} class(TTextEditorVisitor)
{* Обработчик текста через редактор }
protected
// realized methods
procedure DoVisit(aForm: TPrimTextLoadForm); override;
{* Обработать текст }
protected
// overridden protected methods
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
protected
// protected methods
function EtalonFileExtension: AnsiString; virtual;
{* Расширение эталонного файла }
function HeaderBegin: AnsiChar; virtual;
procedure Process(aForm: TPrimTextLoadForm); virtual; abstract;
{* Собственно процесс обработки текста }
end;//TTextViaEditorProcessor
{$IfEnd} //nsTest AND not NoVCM
implementation
{$If defined(nsTest) AND not defined(NoVCM)}
uses
TestFrameWork
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// start class TTextViaEditorProcessor
function TTextViaEditorProcessor.EtalonFileExtension: AnsiString;
//#UC START# *4D0769150130_4BE111D30229_var*
//#UC END# *4D0769150130_4BE111D30229_var*
begin
//#UC START# *4D0769150130_4BE111D30229_impl*
Result := 'evd';
//#UC END# *4D0769150130_4BE111D30229_impl*
end;//TTextViaEditorProcessor.EtalonFileExtension
function TTextViaEditorProcessor.HeaderBegin: AnsiChar;
//#UC START# *4D07693F0262_4BE111D30229_var*
//#UC END# *4D07693F0262_4BE111D30229_var*
begin
//#UC START# *4D07693F0262_4BE111D30229_impl*
Result := '%';
//#UC END# *4D07693F0262_4BE111D30229_impl*
end;//TTextViaEditorProcessor.HeaderBegin
procedure TTextViaEditorProcessor.DoVisit(aForm: TPrimTextLoadForm);
//#UC START# *4BE419AF0217_4BE111D30229_var*
//#UC END# *4BE419AF0217_4BE111D30229_var*
begin
//#UC START# *4BE419AF0217_4BE111D30229_impl*
Process(aForm);
Save(aForm);
CheckOutputWithInput(KPage + EtalonSuffix + '.' + EtalonFileExtension, HeaderBegin);
//#UC END# *4BE419AF0217_4BE111D30229_impl*
end;//TTextViaEditorProcessor.DoVisit
function TTextViaEditorProcessor.GetFolder: AnsiString;
{-}
begin
Result := 'Everest';
end;//TTextViaEditorProcessor.GetFolder
function TTextViaEditorProcessor.GetModelElementGUID: AnsiString;
{-}
begin
Result := '4BE111D30229';
end;//TTextViaEditorProcessor.GetModelElementGUID
{$IfEnd} //nsTest AND not NoVCM
end. |
unit gtk3mybutton;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, GLib2, GObject2, Gtk3;
type
{ TMyButton }
TObjectProcedure = procedure of object;
PMyButton = ^TMyButton;
TMyButton = object(TGtkButton)
private
FOnClicked: TObjectProcedure;
saved_caption: String;
function OnTimer: GBoolean; cdecl;
procedure clicked;
procedure init;
public
function get_type: TGType; static;
function new: PMyButton; static;
procedure QuitProgram;
property OnClicked: TObjectProcedure read FOnClicked write FOnClicked;
end;
{ TMyButtonClass }
PMyButtonClass = ^TMyButtonClass;
TMyButtonClass = object(TGtkButtonClass)
origclicked: procedure(button: PGtkButton); cdecl;
procedure init;
end;
implementation
var
MY_BUTTON_TYPE: TGType = 0;
{ TMyButtonClass }
procedure TMyButtonClass.init;
begin
origclicked := clicked;
Pointer(clicked) := @TMyButton.clicked;
end;
{ TMyButton }
function TMyButton.OnTimer: GBoolean; cdecl;
var
klass: PMyButtonClass;
begin
Result := False;
label_ := PChar(saved_caption);
saved_caption:='';
if Assigned(FOnClicked) then
FOnClicked;
klass := PMyButtonClass(g_type_instance.g_class);
if Assigned(klass^.origclicked) then
klass^.origclicked(@self);
end;
procedure TMyButton.clicked;
begin
// we'll add a delay and update the text. the timer calls the inherited method.
g_timeout_add(3000, TGSourceFunc(@TMyButton.OnTimer), @Self);
saved_caption:=label_;
label_ := 'Wait for it...';
end;
procedure TMyButton.init;
begin
end;
function TMyButton.get_type: TGType;
var
Info: TGTypeInfo;
begin
if MY_BUTTON_TYPE = 0 then
begin
Info.class_size:=SizeOf(TMyButtonClass);
Info.base_init:= nil;
Info.base_finalize:=nil;
Info.class_init:= TGClassInitFunc(@TMyButtonClass.init);
Info.class_finalize:=nil;
Info.class_data:=nil;
Info.instance_size:=SizeOf(TMyButton);
Info.n_preallocs:=0;
Info.instance_init:=TGInstanceInitFunc(@TMyButton.init);
Info.value_table:=nil;
MY_BUTTON_TYPE := g_type_register_static(gtk_button_get_type, 'MyButton', @Info, 0);
end;
Result := MY_BUTTON_TYPE;
end;
function TMyButton.new: PMyButton;
begin
Result := PMyButton(g_object_new(TMyButton.get_type, nil, []));
end;
procedure TMyButton.QuitProgram;
begin
gtk_main_quit;
end;
end.
|
{***************************************************************
* Unit Name: GX_InsertAutoTodoExpert
* Purpose : Inserts to do comments for empty code blocks
* Authors : Peter Laman, Thomas Mueller
****************************************************************}
unit GX_InsertAutoTodo;
{$I GX_CondDefine.inc}
interface
uses
SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, Menus,
GX_BaseForm, GX_Experts, ExtCtrls;
type
TfmInsertAutoTodoForm = class(TfmBaseForm)
lblUsername: TLabel;
edtUsername: TEdit;
lblTextToInsert: TLabel;
btnLoadDetault: TButton;
btnInsertPlaceholder: TButton;
mmoTextToInsert: TMemo;
pmuPlaceholders: TPopupMenu;
lblStarWindows: TLabel;
pnlFooter: TPanel;
chkShowDoneDialog: TCheckBox;
btnOK: TButton;
btnCancel: TButton;
procedure btnLoadDetaultClick(Sender: TObject);
private
procedure InsertPlaceholderClick(Sender: TObject);
procedure SetData(const AUsername, ATextToInsert: string; ADoneDialogEnabled: Boolean);
procedure GetData(var AUsername, ATextToInsert: string; var ADoneDialogEnabled: Boolean);
public
constructor Create(Owner: TComponent); override;
end;
implementation
{$R *.dfm}
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
Registry, Actions, ActnList, ToolsAPI, Types,
GX_GExperts, GX_ConfigurationInfo, GX_uAutoTodoHandler, GX_dzVclUtils,
GX_OtaUtils, GX_GenericUtils, GX_AutoTodoDone;
type
EAutoTodo = class(Exception);
type
TGxInsertAutoTodoExpert = class(TGX_Expert)
private
FUsername: string;
FTextToInsert: string;
FDoneDialogEnabled: Boolean;
protected
procedure UpdateAction(Action: TCustomAction); override;
procedure SetActive(New: Boolean); override;
procedure InternalLoadSettings(Settings: TExpertSettings); override;
procedure InternalSaveSettings(Settings: TExpertSettings); override;
public
constructor Create; override;
destructor Destroy; override;
function GetActionCaption: string; override;
class function GetName: string; override;
function HasConfigOptions: Boolean; override;
function HasMenuItem: Boolean; override;
procedure Configure; override;
procedure Execute(Sender: TObject); override;
end;
type
TOffsetToCursorPos = class
private
FOffsets: array of integer;
public
constructor Create(_sl: TGXUnicodeStringList);
function CalcCursorPos(_Offset: integer): TPoint;
end;
{ TOffsetToCursorPos }
constructor TOffsetToCursorPos.Create(_sl: TGXUnicodeStringList);
var
cnt: integer;
i: Integer;
CrLfLen: integer;
Ofs: Integer;
begin
inherited Create;
{$IFDEF GX_VER190_up}
CrLfLen := Length(_sl.LineBreak);
{$ELSE}
// Delphi < 2007 does not have the LineBreak property
CrLfLen := 2;
{$ENDIF}
cnt := _sl.Count;
SetLength(FOffsets, cnt);
Ofs := 1;
for i := 0 to _sl.Count - 1 do begin
FOffsets[i] := Ofs;
Inc(Ofs, Length(_sl[i]) + CrLfLen);
end;
end;
function TOffsetToCursorPos.CalcCursorPos(_Offset: integer): TPoint;
var
i: integer;
begin
i := 0;
while (i < Length(FOffsets)) and (_Offset >= FOffsets[i]) do begin
Inc(i);
end;
Result.Y := i - 1;
Result.X := _Offset - FOffsets[Result.Y] + 1;
end;
{ TGxInsertAutoTodoExpert }
procedure TGxInsertAutoTodoExpert.Execute(Sender: TObject);
function PointToCharPos(_Pnt: TPoint): TOTACharPos;
begin
Result.Line :=_Pnt.Y + 1;
Result.CharIndex := _Pnt.X;
end;
resourcestring
str_NoEditor = 'No source editor';
str_UnsupportedFileTypeS = 'Unsupported file type: %s';
str_UnableToGetContentsS = 'Unable to get contents of %s';
var
SourceEditor: IOTASourceEditor;
FileName: string;
Handler: TAutoTodoHandler;
Patches: TStringList;
Writer: IOTAEditWriter;
Lines: TGXUnicodeStringList;
Source: TGXUnicodeString;
i: Integer;
CurPos: Integer;
PatchPos: Integer;
TextLength: Integer;
OffsToCP: TOffsetToCursorPos;
cp: TPoint;
EditView: IOTAEditView;
Offset: Integer;
begin
if not GxOtaTryGetCurrentSourceEditor(SourceEditor) then
raise EAutoTodo.Create(str_NoEditor);
FileName := SourceEditor.FileName;
if not (IsPascalSourceFile(FileName) or IsDelphiPackage(FileName) or FileMatchesExtension(FileName, '.tpl')) then
raise EAutoTodo.CreateFmt(str_UnsupportedFileTypeS, [ExtractFileName(FileName)]);
Lines := TGXUnicodeStringList.Create;
try
if not GxOtaGetActiveEditorText(Lines, false) then
raise EAutoTodo.CreateFmt(str_UnableToGetContentsS, [FileName]);
Source := Lines.Text;
if Source = '' then
exit;
TextLength := Length(Source);
Patches := TStringList.Create;
try
Handler := TAutoTodoHandler.Create;
try
if FUsername = '*' then
Handler.TodoUser := GetCurrentUser
else
Handler.TodoUser := FUsername;
Handler.TextToInsert := FTextToInsert;
Handler.Execute(Source, Patches);
finally
FreeAndNil(Handler);
end;
if Patches.Count > 0 then begin
EditView := GxOtaGetTopMostEditView(SourceEditor);
OffsToCP := TOffsetToCursorPos.Create(Lines);
try
// for i := Patches.Count - 1 downto 0 do
// Insert(Patches[i], Source, Integer(Patches.Objects[i]) + 1);
// due to the IDE using UTF-8 we need to convert PatchPos to line and offset
// and then convert line and offset to the Offset into the edit buffer
for i := 0 to Patches.Count - 1 do begin
PatchPos := Integer(Patches.Objects[i]);
cp := OffsToCP.CalcCursorPos(PatchPos);
Offset := EditView.CharPosToPos(PointToCharPos(cp));
Patches.Objects[i] := Pointer(Offset);
end;
finally
FreeAndNil(OffsToCP);
end;
EditView := nil;
Writer := SourceEditor.CreateUndoableWriter;
CurPos := 0;
for i := 0 to Patches.Count - 1 do begin
PatchPos := Integer(Patches.Objects[i]);
if PatchPos > CurPos then begin
Writer.CopyTo(PatchPos);
CurPos := PatchPos;
end;
Writer.Insert(PAnsiChar(ConvertToIDEEditorString(Patches[i])));
end;
if CurPos < TextLength then
Writer.CopyTo(TextLength);
end;
if FDoneDialogEnabled then begin
if TfmAutoTodoDone.Execute(Patches.Count) then begin
FDoneDialogEnabled := False;
SaveSettings;
end;
end;
finally
FreeAndNil(Patches);
end;
finally
FreeAndNil(Lines);
end;
end;
procedure TGxInsertAutoTodoExpert.Configure;
var
Dialog: tfmInsertAutoTodoForm;
begin
Dialog := tfmInsertAutoTodoForm.Create(nil);
try
Dialog.SetData(FUsername, FTextToInsert, FDoneDialogEnabled);
if Dialog.ShowModal = mrOk then
begin
Dialog.GetData(FUsername, FTextToInsert, FDoneDialogEnabled);
SaveSettings;
end;
finally
FreeAndNil(Dialog);
end;
end;
constructor TGxInsertAutoTodoExpert.Create;
begin
inherited Create;
FUsername := '*'; // '*' means 'use Windows username'
FTextToInsert := TAutoTodoHandler.GetDefaultTextToInsert;
FDoneDialogEnabled := True;
// we do not want a shortcut
// ShortCut := Menus.ShortCut(Word('Z'), [ssCtrl, ssShift, ssAlt]);
end;
destructor TGxInsertAutoTodoExpert.Destroy;
begin
// Free any created objects here
inherited Destroy;
end;
function TGxInsertAutoTodoExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Comment Empty Code Blocks...';
begin
Result := SMenuCaption;
end;
class function TGxInsertAutoTodoExpert.GetName: string;
begin
Result := 'InsertAutoToDo';
end;
function TGxInsertAutoTodoExpert.HasConfigOptions: Boolean;
begin
Result := True;
end;
function TGxInsertAutoTodoExpert.HasMenuItem: Boolean;
begin
Result := True;
end;
procedure TGxInsertAutoTodoExpert.InternalLoadSettings(Settings: TExpertSettings);
begin
inherited;
FUsername := Settings.ReadString('Username', FUsername);
FTextToInsert := Settings.ReadString('TextToInsert', FTextToInsert);
FDoneDialogEnabled := Settings.ReadBool('DoneDialogEnabled', FDoneDialogEnabled);
end;
procedure TGxInsertAutoTodoExpert.InternalSaveSettings(Settings: TExpertSettings);
begin
inherited;
Settings.WriteString('Username', FUsername);
Settings.WriteString('TextToInsert', FTextToInsert);
Settings.WriteBool('DoneDialogEnabled', FDoneDialogEnabled);
end;
procedure TGxInsertAutoTodoExpert.SetActive(New: Boolean);
begin
inherited SetActive(New);
// nothing else to do
end;
procedure TGxInsertAutoTodoExpert.UpdateAction(Action: TCustomAction);
const
SAllowableFileExtensions = '.pas;.dpr;.inc';
begin
Action.Enabled := FileMatchesExtensions(GxOtaGetCurrentSourceFile, SAllowableFileExtensions);
end;
{ TfmInsertAutoTodoForm }
constructor TfmInsertAutoTodoForm.Create(Owner: TComponent);
var
Placeholders: TStringList;
i: Integer;
begin
inherited;
Placeholders := TStringList.Create;
try
TAutoTodoHandler.GetPlaceholders(Placeholders);
for i := 0 to Placeholders.Count - 1 do
TPopupMenu_AppendMenuItem(pmuPlaceholders, Placeholders[i], InsertPlaceholderClick);
finally
FreeAndNil(Placeholders);
end;
TButton_AddDropdownMenu(btnInsertPlaceholder, pmuPlaceholders);
mmoTextToInsert.Lines.Text := TAutoTodoHandler.GetDefaultTextToInsert;
TControl_SetMinConstraints(Self);
Constraints.MaxHeight := Height;
end;
procedure TfmInsertAutoTodoForm.GetData(var AUsername, ATextToInsert: string;
var ADoneDialogEnabled: Boolean);
begin
AUsername := edtUsername.Text;
ATextToInsert := mmoTextToInsert.Lines.Text;
ADoneDialogEnabled := chkShowDoneDialog.Checked;
end;
procedure TfmInsertAutoTodoForm.SetData(const AUsername, ATextToInsert: string;
ADoneDialogEnabled: Boolean);
begin
edtUsername.Text := AUsername;
mmoTextToInsert.Lines.Text := ATextToInsert;
chkShowDoneDialog.Checked := ADoneDialogEnabled;
end;
procedure TfmInsertAutoTodoForm.btnLoadDetaultClick(Sender: TObject);
begin
mmoTextToInsert.Lines.Text := TAutoTodoHandler.GetDefaultTextToInsert;
end;
procedure TfmInsertAutoTodoForm.InsertPlaceholderClick(Sender: TObject);
var
MenuItem: TMenuItem;
Str: string;
begin
MenuItem := Sender as TMenuItem;
Str := StripHotKey(MenuItem.Caption);
mmoTextToInsert.SelText := '{' + Str + '}';
end;
initialization
RegisterGX_Expert(TGxInsertAutoTodoExpert);
end.
|
unit kwPopEditorDP2LP;
{* *Формат:* X Y anEditorControl pop:editor:DP2LP
*Описание:* Переводи значения точки из долей дюйма в пиксели.
*Пример:*
[code]
100 100 focused:control:push pop:editor:DP2LP
[code] }
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwPopEditorDP2LP.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "pop_editor_DP2LP" MUID: (503C650202E5)
// Имя типа: "TkwPopEditorDP2LP"
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, kwEditorFromStackWord
, tfwScriptingInterfaces
, evCustomEditorWindow
;
type
TkwPopEditorDP2LP = {final} class(TkwEditorFromStackWord)
{* *Формат:* X Y anEditorControl pop:editor:DP2LP
*Описание:* Переводи значения точки из долей дюйма в пиксели.
*Пример:*
[code]
100 100 focused:control:push pop:editor:DP2LP
[code] }
protected
procedure DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow); override;
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopEditorDP2LP
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, l3Units
, Windows
{$If NOT Defined(NoVCL)}
, Controls
{$IfEnd} // NOT Defined(NoVCL)
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
//#UC START# *503C650202E5impl_uses*
//#UC END# *503C650202E5impl_uses*
;
procedure TkwPopEditorDP2LP.DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow);
//#UC START# *4F4CB81200CA_503C650202E5_var*
var
l_X, l_Y : Integer;
l_SPoint : Tl3SPoint;
l_Point : Tl3Point;
//#UC END# *4F4CB81200CA_503C650202E5_var*
begin
//#UC START# *4F4CB81200CA_503C650202E5_impl*
l_X := 0;
l_Y := 0;
if aCtx.rEngine.IsTopInt then
l_Y := aCtx.rEngine.PopInt
else
Assert(False, 'Не задана координата Y.');
if aCtx.rEngine.IsTopInt then
l_X := aCtx.rEngine.PopInt
else
Assert(False, 'Не задана координата X.');
l_SPoint.Init(l_X, l_Y);
l_Point := anEditor.Canvas.DP2LP(l_SPoint);
aCtx.rEngine.PushInt(l_Point.Y);
aCtx.rEngine.PushInt(l_Point.X);
//#UC END# *4F4CB81200CA_503C650202E5_impl*
end;//TkwPopEditorDP2LP.DoWithEditor
class function TkwPopEditorDP2LP.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:editor:DP2LP';
end;//TkwPopEditorDP2LP.GetWordNameForRegister
initialization
TkwPopEditorDP2LP.RegisterInEngine;
{* Регистрация pop_editor_DP2LP }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit d_BatchDelAttr;
{ $Id: d_BatchDelAttr.pas,v 1.5 2012/02/17 09:32:44 kostitsin Exp $ }
// $Log: d_BatchDelAttr.pas,v $
// Revision 1.5 2012/02/17 09:32:44 kostitsin
// Переименовываем NumOfSelect в SelectedCount
//
// Revision 1.4 2010/09/24 12:15:44 voba
// - k : 235046326
//
// Revision 1.3 2009/02/03 07:39:35 narry
// - переименование заголовка
//
// Revision 1.2 2008/05/05 10:33:41 voba
// no message
//
// Revision 1.1 2007/12/18 08:48:17 fireton
// - первый коммит
//
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, BtnDlg, StdCtrls, Buttons, ExtCtrls, OvcBase, afwControl,
afwInputControl, vtLister,
dt_Types, dt_AttrSchema, DictsSup,
l3Base,
l3Interfaces, afwControlPrim, afwBaseControl;
type
TBADDResult = array of TdtAttribute;
TBatchAttrDelDlg = class(TBtnDlg)
lstAttrTypes: TvtLister;
procedure FormCreate(Sender: TObject);
procedure lstAttrTypesSelectChanged(Sender: TObject; Index: Integer;
var SelectedState: Integer);
procedure lstAttrTypesGetStrItem(Sender: TObject; Index: Integer;
var ItemString: Il3CString);
private
{ Private declarations }
public
{ Public declarations }
procedure GetSelectedAttrTypes(var theArray: TBADDResult);
end;
implementation
{$R *.dfm}
const
cDeletableAttrSet : array[0..10] of TdtAttribute =
(atSources, atTypes, atTerritories, atAccGroups, atBases, atNorms, atClasses,
atPrefixes, atKeyWords, atAnnoClasses, atServiceInfo);
procedure TBatchAttrDelDlg.FormCreate(Sender: TObject);
begin
inherited;
lstAttrTypes.Total := High(cDeletableAttrSet);
end;
procedure TBatchAttrDelDlg.GetSelectedAttrTypes(var theArray: TBADDResult);
var
l_Idx: Integer;
I: Integer;
begin
SetLength(theArray, High(cDeletableAttrSet));
l_Idx := 0;
for I := 0 to Pred(High(cDeletableAttrSet)) do
if lstAttrTypes.Selected[I] then
begin
theArray[l_Idx] := cDeletableAttrSet[I];
Inc(l_Idx);
end;
SetLength(theArray, l_Idx);
end;
procedure TBatchAttrDelDlg.lstAttrTypesSelectChanged(Sender: TObject;
Index: Integer; var SelectedState: Integer);
begin
Ok.Enabled := lstAttrTypes.SelectedCount > 0;
end;
procedure TBatchAttrDelDlg.lstAttrTypesGetStrItem(Sender: TObject;
Index: Integer; var ItemString: Il3CString);
begin
inherited;
ItemString := l3CStr(GetAttrName(cDeletableAttrSet[Index]));
end;
end.
|
unit HelpUtil;
{
Isolates platform-specific help access for Lazarus LCL.
Assumes Application.HelpFile is set.
Create THelpUtilManager object in main form's FormCreate handler and
call its Free method in main form's FormDestroy handler.
Display help topic by calling Application.HelpContext.
Author: Phil Hess.
Copyright: Copyright (C) 2007 Phil Hess. All rights reserved.
License: Modified LGPL. This means you can link your code to this
compiled unit (statically in a standalone executable or
dynamically in a library) without releasing your code. Only
changes to this unit need to be made publicly available.
}
interface
uses
SysUtils,
{$IFDEF MSWINDOWS}
Windows,
{$ELSE}
Unix,
{$ENDIF}
{$IFDEF LINUX}
FileUtil,
{$ENDIF}
Forms,
Dialogs,
HelpIntfs;
type
THelpUtilManager = class(THelpManager)
destructor Destroy; override;
procedure ShowError( ShowResult : TShowHelpResult;
const ErrMsg : string); override;
function ShowHelpForQuery( Query : THelpQuery;
AutoFreeQuery : Boolean;
var ErrMsg : string): TShowHelpResult; override;
end;
implementation
const
HELP_CONTEXT = 1;
HELP_QUIT = 2;
{$IFDEF MSWINDOWS} {LCL doesn't have TApplication.HelpCommand, so call Win API}
function DoHelpCommand(Command : Word;
Data : LongInt) : Boolean;
begin
Result := WinHelp(Application.MainForm.Handle,
PChar(Application.HelpFile),
Command, Data);
end; {DoHelpCommand}
{$ENDIF}
{THelpUtilManager}
destructor THelpUtilManager.Destroy;
begin
{$IFDEF MSWINDOWS}
DoHelpCommand(HELP_QUIT, 0);
{Shut down help application if running and not in use
by another instance of program}
{$ENDIF}
inherited Destroy;
end;
procedure THelpUtilManager.ShowError( ShowResult : TShowHelpResult;
const ErrMsg : string);
begin
if ShowResult = shrHelpNotFound then
MessageDlg('Help not implemented.', mtError, [mbOK], 0)
else if ShowResult = shrViewerNotFound then
MessageDlg('Help viewer not found.', mtError, [mbOK], 0)
else if ShowResult = shrViewerError then
MessageDlg('Unable to start help viewer.', mtError, [mbOK], 0)
else if ShowResult <> shrSuccess then
MessageDlg(ErrMsg, mtError, [mbOK], 0);
end;
function THelpUtilManager.ShowHelpForQuery( Query : THelpQuery;
AutoFreeQuery : Boolean;
var ErrMsg : string): TShowHelpResult;
{$IFDEF LINUX}
function SearchForBrowser(const BrowserFileName : string) : string;
begin
Result :=
SearchFileInPath(BrowserFileName, '', GetEnvironmentVariable('PATH'),
PathSeparator, [sffDontSearchInBasePath]);
end;
function GetBrowserPath : string;
begin
Result := SearchForBrowser('firefox');
if Result = '' then
Result := SearchForBrowser('konqueror'); {KDE browser}
if Result = '' then
Result := SearchForBrowser('epiphany'); {GNOME browser}
if Result = '' then
Result := SearchForBrowser('mozilla');
if Result = '' then
Result := SearchForBrowser('opera');
end;
{$ENDIF}
begin
if Query is THelpQueryContext then {Is a help context request?}
begin
{$IFDEF MSWINDOWS}
DoHelpCommand(HELP_CONTEXT, THelpQueryContext(Query).Context);
Result := shrSuccess;
{$ELSE}
{$IFDEF DARWIN}
if Shell('Open -a "HelpViewer" "' + Application.HelpFile + '"') = 127 then
// Note: Renamed from Help Viewer.app to HelpViewer.app with 10.5.
//
// Note: With OS X earlier than 10.4 (Tiger), if connected to network
// but not connected to Internet, takes Help Viewer 1-2 minutes to
// recover and turn off rotating ball! Can comment out previous Shell
// and uncomment next line to use default browser instead.
// if Shell('Open "' + Application.HelpFile + '"') = 127 then
Result := shrViewerError
else
Result := shrSuccess;
{$ELSE} {For now, shell to first browser found, passing help file name}
if GetBrowserPath <> '' then {Found a browser?}
begin
if Shell(GetBrowserPath + ' ' + Application.HelpFile) = 127 then
Result := shrViewerError
else
Result := shrSuccess;
end
else
Result := shrViewerNotFound;
{$ENDIF}
{$ENDIF}
end
else {Not a help context request?}
Result := inherited ShowHelpForQuery(Query, AutoFreeQuery, ErrMsg);
end; {THelpUtilManager.ShowHelpForQuery}
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
tmr1: TTimer;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
//Timer = class
//private
// FClock: TTimer;
// procedure ClockTimer(Sender: TObject);
//
//public
// constructor Create;
//end;
//
TPoint = object
private
x,y:Integer;
figure:TShape;
public
constructor Create(a,b:Integer; owner:TWinControl);
procedure Show;
procedure Hide;
procedure Draw(vis:Boolean); virtual;
procedure Set_Color(color:TColor);
procedure Move(dx,dy:Integer);
end;
//
TCircle= object(TPoint)
private
radius : Integer;
FClock: TTimer;
// procedure ClockTimer(Sender: TObject);
public
constructor Create(a,b,c:Integer; owner : TWinControl);
procedure Draw(vis:Boolean); virtual;
end;
var
Form1: TForm1;
Pointer : TPoint;
Circle : TCircle;
count : Integer;
i:Integer;
implementation
{$R *.dfm}
{ TPoint }
constructor TPoint.Create(a, b: Integer; owner: TWinControl);
begin
figure := TShape.Create(nil);
figure.Parent := owner;
figure.Visible := False;
x:=a; y:=b;
end;
procedure TPoint.Draw(vis: Boolean);
begin
with figure do
begin
shape := stCircle;
brush.Style := bsClear;
width :=500;
height := width;
left := x-1; top:= y-1;
visible := vis;
end
end;
procedure TPoint.Hide;
begin
Draw(false);
end;
procedure TPoint.Move(dx, dy: Integer);
begin
HIde;
with figure do
begin
x:=x+dx; y:=y+dy;
end;
Show;
end;
procedure TPoint.Set_Color(color: TColor);
begin
figure.Pen.Color:=color;
end;
procedure TPoint.Show;
begin
Draw(True);
end;
{ TCircle }
constructor TCircle.Create(a, b, c: Integer; owner: TWinControl);
var clock:TTimer;
begin
inherited Create(a,b,owner);
radius := c;
// clock := TTimer.Create(nil);
// clock.interval:=1000;
// clock.OnTimer := ClockTimer;
end;
//
procedure TCircle.Draw(vis: Boolean);
var timer:TTimer;
begin
inherited;
with figure do
begin
Left := x - radius;
top:= y - radius;
width := 2*radius;
Height := Width;
end;
end;
//
procedure TForm1.FormCreate(Sender: TObject);
var Point:TPoint; i,n,middleX,middleY:Integer;
begin
for n:=1 to 10 do
begin
i:=250-50;
count :=0;
middleX:=Form1.ClientWidth div 2; //кординпти форми
middleY:=Form1.Clientheight div 2;
Circle.Create(middleX,middleY,i,Form1); //по книжіц
Circle.Set_Color(clRed);
Circle.Show;
end;
// Point.Create(120, 30, Form1); // старе но непогане
// Point.Set_Color(clRed);
// Point.Show;
end;
procedure ClockTimer(Sender: TObject);
begin
i:=i-30;
end;
end.
|
unit RDOLogAgents;
interface
uses
RDOInterfaces;
type
TLogAgentRec =
record
Id : string;
Agent : IRDOLogAgent;
end;
PLogAgentArray = ^TLogAgentArray;
TLogAgentArray = array[0..0] of TLogAgentRec;
type
TRDOLogAgentRegistry =
class(TInterfacedObject, IRDOLogAgentRegistry)
public
constructor Create;
destructor Destroy; override;
private
fAgents : PLogAgentArray;
fCount : integer;
private
function GetLogAgent(aClassName : string) : IRDOLogAgent;
procedure RegisterAgent(aClassName : string; anAgent : IRDOLogAgent);
end;
implementation
// TRDOLogAgentRegistry
constructor TRDOLogAgentRegistry.Create;
begin
inherited;
end;
destructor TRDOLogAgentRegistry.Destroy;
begin
if fAgents <> nil
then
begin
Finalize(fAgents[0], fCount);
ReallocMem(fAgents, 0);
end;
inherited;
end;
function TRDOLogAgentRegistry.GetLogAgent(aClassName : string) : IRDOLogAgent;
var
i : integer;
begin
i := 0;
while (i < fCount) and (fAgents[i].Id <> aClassName) do
inc(i);
if i < fCount
then result := fAgents[i].Agent
else result := nil;
end;
procedure TRDOLogAgentRegistry.RegisterAgent(aClassName : string; anAgent : IRDOLogAgent);
begin
inc(fCount);
ReallocMem(fAgents, fCount*sizeof(fAgents[0]));
with fAgents[fCount - 1] do
begin
Id := aClassName;
Agent := anAgent;
end;
end;
end.
|
unit PerspectiveCorrect;
interface
uses
System.Math,
SimpleSVD,
GR32,
GR32_Transforms,
GR32_Math,
GR32_Blend;
type
TMyProjectiveTransformation = class(T3x3Transformation)
private
FDestHeight: TFloat;
FDestWidth: TFloat;
FQuadX: array [0..3] of TFloat;
FQuadY: array [0..3] of TFloat;
function GetDestHeight: TFloat;
function GetDestWidth: TFloat;
procedure SetX0(Value: TFloat); {$IFDEF UseInlining} inline; {$ENDIF}
procedure SetX1(Value: TFloat); {$IFDEF UseInlining} inline; {$ENDIF}
procedure SetX2(Value: TFloat); {$IFDEF UseInlining} inline; {$ENDIF}
procedure SetX3(Value: TFloat); {$IFDEF UseInlining} inline; {$ENDIF}
procedure SetY0(Value: TFloat); {$IFDEF UseInlining} inline; {$ENDIF}
procedure SetY1(Value: TFloat); {$IFDEF UseInlining} inline; {$ENDIF}
procedure SetY2(Value: TFloat); {$IFDEF UseInlining} inline; {$ENDIF}
procedure SetY3(Value: TFloat); {$IFDEF UseInlining} inline; {$ENDIF}
protected
procedure PrepareTransform; override;
procedure ReverseTransformFixed(DstX, DstY: TFixed; out SrcX, SrcY: TFixed); override;
procedure ReverseTransformFloat(DstX, DstY: TFloat; out SrcX, SrcY: TFloat); override;
procedure TransformFixed(SrcX, SrcY: TFixed; out DstX, DstY: TFixed); override;
procedure TransformFloat(SrcX, SrcY: TFloat; out DstX, DstY: TFloat); override;
public
function GetTransformedBounds(const ASrcRect: TFloatRect): TFloatRect; override;
property DestWidth: TFloat read GetDestWidth;
property DestHeight: TFloat read GetDestHeight;
published
property X0: TFloat read FQuadX[0] write SetX0;
property X1: TFloat read FQuadX[1] write SetX1;
property X2: TFloat read FQuadX[2] write SetX2;
property X3: TFloat read FQuadX[3] write SetX3;
property Y0: TFloat read FQuadY[0] write SetY0;
property Y1: TFloat read FQuadY[1] write SetY1;
property Y2: TFloat read FQuadY[2] write SetY2;
property Y3: TFloat read FQuadY[3] write SetY3;
end;
function getPerspectiveTransform(const src,
dst: TArray<TFloatPoint>): TFloatMatrix;
implementation
function getPerspectiveTransform(const src,
dst: TArray<TFloatPoint>): TFloatMatrix;
const
DECOMP_SVD = 1;
var
A, b, c: TMatrix;
M, N, i: Integer;
svd_deomposition: TSVD;
A_pinv: TMatrix;
Mat: TFloatMatrix;
begin
M := 8;
N := 8;
A := TMatrix.Create(M, N, 'A', TMatrix.AS_MATRIX);
b := TMatrix.Create(M, 1, 'b', TMatrix.AS_VECTOR);
c := TMatrix.Create(N, 1, 'c', TMatrix.AS_VECTOR);
for i := 0 to 3 do
begin
A[i,0] := src[i].X;
A[i+4,3] := src[i].X;
A[i,1] := src[i].Y;
a[i+4,4] := src[i].Y;
A[i,2] := 1;
A[i+4,5] := 1;
A[i,3] := 0;
A[i,4] := 0;
A[i,5] := 0;
A[i+4,0] := 0;
A[i+4,1] := 0;
A[i+4,2] := 0;
A[i,6] := -src[i].x*dst[i].x;
A[i,7] := -src[i].y*dst[i].x;
A[i+4,6] := -src[i].x*dst[i].y;
A[i+4,7] := -src[i].y*dst[i].y;
B.Mat[i] := dst[i].x;
B.Mat[i+4] := dst[i].y;
end;
svd_deomposition := TSVD.Create;
A_pinv := nil;
try
A_pinv := svd_deomposition.PinvCompute(A, A.Rows, A.Cols);
svd_deomposition.multiply(A_pinv, b, c);
Mat[0][0] := c.Mat[0];
Mat[1][0] := c.Mat[1];
Mat[2][0] := c.Mat[2];
Mat[0][1] := c.Mat[3];
Mat[1][1] := c.Mat[4];
Mat[2][1] := c.Mat[5];
Mat[0][2] := c.Mat[6];
Mat[1][2] := c.Mat[7];
Mat[2][2] := 1;
Result := Mat;
finally
A_pinv.Free;
svd_deomposition.Free;
end;
end;
{ TMyProjectiveTransformation }
function TMyProjectiveTransformation.GetDestHeight: TFloat;
begin
if not TransformValid then PrepareTransform;
Result := FDestHeight;
end;
function TMyProjectiveTransformation.GetDestWidth: TFloat;
begin
if not TransformValid then PrepareTransform;
Result := FDestWidth;
end;
function TMyProjectiveTransformation.GetTransformedBounds(
const ASrcRect: TFloatRect): TFloatRect;
var
p0, p1, p2, p3: TFloatPoint;
begin
p0 := Transform(FloatPoint(X0, Y0));
p1 := Transform(FloatPoint(X1, Y1));
p2 := Transform(FloatPoint(X2, Y2));
p3 := Transform(FloatPoint(X3, Y3));
// p0 := (FloatPoint(X0, Y0));
// p1 := (FloatPoint(X1, Y1));
// p2 := (FloatPoint(X2, Y2));
// p3 := (FloatPoint(X3, Y3));
Result.Left := Min(Min(p0.X, p1.X), Min(p2.X, p3.X));
Result.Right := Max(Max(p0.X, p1.X), Max(p2.X, p3.X));
Result.Top := Min(Min(p0.Y, p1.Y), Min(p2.Y, p3.Y));
Result.Bottom := Max(Max(p0.Y, p1.Y), Max(p2.Y, p3.Y));
end;
function Distance(P1, P2: TFloatPoint): Single;
begin
Result := Sqrt(Sqr(P1.X - P2.X) + Sqr(P1.Y - P2.Y));
end;
procedure TMyProjectiveTransformation.PrepareTransform;
var
widthA, widthB, heightA, heightB: TFloat;
src, dst: TArray<TFloatPoint>;
begin
src := TArray<TFloatPoint>.Create(
FloatPoint(X0, Y0),
FloatPoint(X1, Y1),
FloatPoint(X2, Y2),
FloatPoint(X3, Y3)
);
widthA := Distance(src[2], src[3]);
widthB := Distance(src[1], src[0]);
FDestWidth := Max(widthA, widthB);
heightA := Distance(src[1], src[2]);
heightB := Distance(src[0], src[3]);
FDestHeight := Max(heightA, heightB);
dst := TArray<TFloatPoint>.Create(
FloatPoint(0, 0),
FloatPoint(FDestWidth, 0),
FloatPoint(FDestWidth, FDestHeight),
FloatPoint(0, FDestHeight)
);
FMatrix := getPerspectiveTransform(src, dst);
// Invert(FMatrix);
inherited;
end;
procedure TMyProjectiveTransformation.ReverseTransformFixed(DstX, DstY: TFixed;
out SrcX, SrcY: TFixed);
var
Z: TFixed;
Zf: TFloat;
begin
Z := FixedMul(FInverseFixedMatrix[0, 2], DstX) +
FixedMul(FInverseFixedMatrix[1, 2], DstY) + FInverseFixedMatrix[2, 2];
if Z = 0 then Exit;
{$IFDEF UseInlining}
SrcX := FixedMul(DstX, FInverseFixedMatrix[0, 0]) +
FixedMul(DstY, FInverseFixedMatrix[1, 0]) + FInverseFixedMatrix[2, 0];
SrcY := FixedMul(DstX, FInverseFixedMatrix[0,1]) +
FixedMul(DstY, FInverseFixedMatrix[1, 1]) + FInverseFixedMatrix[2, 1];
{$ELSE}
inherited;
{$ENDIF}
if Z <> FixedOne then
begin
EMMS;
Zf := FixedOne / Z;
SrcX := Round(SrcX * Zf);
SrcY := Round(SrcY * Zf);
end;
end;
procedure TMyProjectiveTransformation.ReverseTransformFloat(DstX, DstY: TFloat;
out SrcX, SrcY: TFloat);
var
Z: TFloat;
begin
EMMS;
Z := FInverseMatrix[0, 2] * DstX + FInverseMatrix[1, 2] * DstY +
FInverseMatrix[2, 2];
if Z = 0 then Exit;
{$IFDEF UseInlining}
SrcX := DstX * FInverseMatrix[0, 0] + DstY * FInverseMatrix[1, 0] +
FInverseMatrix[2, 0];
SrcY := DstX * FInverseMatrix[0, 1] + DstY * FInverseMatrix[1, 1] +
FInverseMatrix[2, 1];
{$ELSE}
inherited;
{$ENDIF}
if Z <> 1 then
begin
Z := 1 / Z;
SrcX := SrcX * Z;
SrcY := SrcY * Z;
end;
end;
procedure TMyProjectiveTransformation.SetX0(Value: TFloat);
begin
FQuadX[0] := Value;
Changed;
end;
procedure TMyProjectiveTransformation.SetX1(Value: TFloat);
begin
FQuadX[1] := Value;
Changed;
end;
procedure TMyProjectiveTransformation.SetX2(Value: TFloat);
begin
FQuadX[2] := Value;
Changed;
end;
procedure TMyProjectiveTransformation.SetX3(Value: TFloat);
begin
FQuadX[3] := Value;
Changed;
end;
procedure TMyProjectiveTransformation.SetY0(Value: TFloat);
begin
FQuadY[0] := Value;
Changed;
end;
procedure TMyProjectiveTransformation.SetY1(Value: TFloat);
begin
FQuadY[1] := Value;
Changed;
end;
procedure TMyProjectiveTransformation.SetY2(Value: TFloat);
begin
FQuadY[2] := Value;
Changed;
end;
procedure TMyProjectiveTransformation.SetY3(Value: TFloat);
begin
FQuadY[3] := Value;
Changed;
end;
procedure TMyProjectiveTransformation.TransformFixed(SrcX, SrcY: TFixed;
out DstX, DstY: TFixed);
var
Z: TFixed;
Zf: TFloat;
begin
Z := FixedMul(FFixedMatrix[0, 2], SrcX) +
FixedMul(FFixedMatrix[1, 2], SrcY) + FFixedMatrix[2, 2];
if Z = 0 then Exit;
{$IFDEF UseInlining}
DstX := FixedMul(SrcX, FFixedMatrix[0, 0]) +
FixedMul(SrcY, FFixedMatrix[1, 0]) + FFixedMatrix[2, 0];
DstY := FixedMul(SrcX, FFixedMatrix[0, 1]) +
FixedMul(SrcY, FFixedMatrix[1, 1]) + FFixedMatrix[2, 1];
{$ELSE}
inherited;
{$ENDIF}
if Z <> FixedOne then
begin
EMMS;
Zf := FixedOne / Z;
DstX := Round(DstX * Zf);
DstY := Round(DstY * Zf);
end;
end;
procedure TMyProjectiveTransformation.TransformFloat(SrcX, SrcY: TFloat;
out DstX, DstY: TFloat);
var
Z: TFloat;
begin
EMMS;
Z := FMatrix[0, 2] * SrcX + FMatrix[1, 2] * SrcY + FMatrix[2, 2];
if Z = 0 then Exit;
{$IFDEF UseInlining}
DstX := SrcX * Matrix[0, 0] + SrcY * Matrix[1, 0] + Matrix[2, 0];
DstY := SrcX * Matrix[0, 1] + SrcY * Matrix[1, 1] + Matrix[2, 1];
{$ELSE}
inherited;
{$ENDIF}
if Z <> 1 then
begin
Z := 1 / Z;
DstX := DstX * Z;
DstY := DstY * Z;
end;
end;
end.
|
unit Hlavicka;
(* Trida THlavicka *)
interface
uses
Graphics, SysUtils, MyUtils;
type
THlavicka = class
private
FDruzstvo,FObdobi,FDatum,FMikrocyklus,FZamereniTreninku:String;
public
property Druzstvo:String read FDruzstvo write FDruzstvo;
property Obdobi:String read FObdobi write FObdobi;
property Datum:String read FDatum write FDatum;
property Mikrocyklus:String read FMikrocyklus write FMikrocyklus;
property ZamereniTreninku:String read FZamereniTreninku
write FZamereniTreninku;
procedure Vykresli(Cvs:TCanvas; sirka,vyska:integer; var now_y:integer);
constructor Create();
end;
implementation
(* procedure THlavicka.Vykresli
FUNKCE:
Do zadaneho Canvasu vykresli text hlavicky...
ARGUMENTY:
Cvs - Canvas do ktereho se ma kreslit
sirka - sirka plochy do ktere se kresli
vyska - vyska plochy do ktere se kresli
now_y - souradnice 'y' v plose kam se kresli (na jaky radek)
*)
procedure THlavicka.Vykresli(Cvs:TCanvas; sirka,vyska:integer; var now_y:integer);
var dilek_x,dilek_y,now_x:integer;
begin
dilek_x:=round(Sirka/190);
dilek_y:=round(Vyska/265);
with Cvs do begin
Font.Height:=dilek_y*(-4);
//tucne vypise nazvy poli
Font.Style:=[fsBold];
now_x:=dilek_x*2;
TextOut(now_x,now_y,'Družstvo:');
now_x:=round(sirka/4);
TextOut(now_x,now_y,'Datum:');
now_x:=round(sirka/5*3);
TextOut(now_x,now_y,'Období:');
//tucne vypise obsah polozek k polim
Font.Style:=[];
now_x:=dilek_x*2+TextWidth('Družstvo:')+dilek_x*5;
TextOut(now_x,now_y,Druzstvo);
now_x:=round(sirka/4)+TextWidth('Datum:')+dilek_x*5;
TextOut(now_x,now_y,Datum);
now_x:=round(sirka/5*3)+TextWidth('Období:')+dilek_x*5;
TextOut(now_x,now_y,Obdobi);
//novy radek
now_y:=now_y+TextHeight('M')+dilek_y;
//tucne vypise nazvy poli
Font.Style:=[fsBold];
now_x:=dilek_x*2;
TextOut(now_x,now_y,'Trénink č.:');
now_x:=round(sirka/4);
TextOut(now_x,now_y,'zaměřený na:');
//tucne vypise obsah polozek k polim
Font.Style:=[];
now_x:=dilek_x*2+TextWidth('Družstvo:')+dilek_x*5;
TextOut(now_x,now_y,Mikrocyklus);
now_x:=round(sirka/4)+TextWidth('zaměřený na:')+dilek_x*5;
VypisTextDoObrazku(Cvs,now_x,sirka-dilek_x*5,now_y,ZamereniTreninku);
end;
end;
constructor THlavicka.Create();
begin
Druzstvo:='';
Obdobi:='';
Datum:='';
ZamereniTreninku:='';
Mikrocyklus:='';
end;
end.
|
unit FliPlay;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
interface
uses
Windows, SysUtils, Classes,
ChunkStream, AnimPlay, Flics, FliPlayback, Dibs;
type
EFlicInvalid = Exception;
type
TFliStream =
class( TChunkStream )
procedure LoadFrameHeader; override;
function FrameHeaderSize : integer; override;
function CurrentFrameSize : integer; override;
end;
type
TFliDecoder =
class( TAnimDecoder )
protected
fHeader : TFliHeader;
fOfsFrame1 : integer;
fOfsFrame2 : integer;
function GetFrameDelay : longint; override;
function GetFirstAnimFrame : integer; override;
procedure SeekStart; override;
public
UnkChunkPlayer : TChunkPlayerProc;
procedure LoadFromStream( aStream : TStream ); override;
procedure SetFrameRange( aStartingFrame, aEndingFrame : integer ); override;
property OfsFrame1 : integer read fOfsFrame1;
property OfsFrame2 : integer read fOfsFrame2;
property Header : TFliHeader read fHeader;
end;
type
TFliPlayer =
class( TFliDecoder )
public
procedure ProcessFrame; override;
end;
resourcestring
sFliCorruptedFrame = 'Corrupted FLI/FLC frame found while playing back, file is damaged!!';
sFliInvalid = 'Error trying to load a corrupt or invalid .FLI/.FLC file!!';
implementation
// TFliStream
procedure TFliStream.LoadFrameHeader;
begin
fFrameHeader := Relock( fFrameHeader, FrameHeaderSize );
end;
function TFliStream.CurrentFrameSize : integer;
begin
assert( Assigned( fFrameHeader ), 'Frame Header not loaded in FliPlay.TFliStream.CurrentFrameSize!' );
Result := PFliFrame( fFrameHeader )^.Size;
end;
function TFliStream.FrameHeaderSize : integer;
begin
Result := sizeof( TFliFrame );
end;
// TFliPlayer
function TFliDecoder.GetFirstAnimFrame : integer;
begin
if (Header.Flags and idLooped) = 0
then Result := 1
else Result := 2;
end;
function TFliDecoder.GetFrameDelay : longint;
begin
if Header.Magic = idHeaderFLC
then Result := Header.Speed // Speed is in 'ms', OK
else Result := Header.Speed * 1427 div 100; // Speed is in 'jiffies', 1 jiffie = 14.27ms
end;
procedure TFliDecoder.SetFrameRange( aStartingFrame, aEndingFrame : integer );
begin
inherited;
if aStartingFrame = 1
then StartingFrame := FirstAnimFrame;
end;
procedure TFliDecoder.SeekStart;
begin
if ( CurrentFrameIndx > FrameCount ) and
( (Header.Flags and idLooped) <> 0 )
then
begin
Stream.Seek( OfsFrame2, soFromBeginning );
fCurrentFrameIndx := 2;
end
else
begin
Stream.Seek( OfsFrame1, soFromBeginning );
fCurrentFrameIndx := 1;
end;
end;
procedure TFliDecoder.LoadFromStream( aStream : TStream );
var
FliPrefix : TFliPrefix;
StartPos : integer;
begin
Detach;
StartPos := aStream.Position;
aStream.ReadBuffer( fHeader, sizeof(fHeader) ); // Load Fli Header
if (fHeader.Magic <> idHeaderFLC) and (fHeader.Magic <> idHeaderFLI)
then raise EFlicInvalid.Create( sFliInvalid )
else
begin
aStream.ReadBuffer( FliPrefix, sizeof(FliPrefix) ); // Skip Fli Prefix
if FliPrefix.Magic <> idPrefix
then FliPrefix.Size := 0;
aStream.Seek( FliPrefix.Size - sizeof(FliPrefix), soFromCurrent );
if fHeader.Size > aStream.Size // Bogus field, fix it!!
then fHeader.Size := aStream.Size;
fWidth := integer( fHeader.Width );
fHeight := integer( fHeader.Height );
fFrameCount := integer( fHeader.Frames );
fDiskSize := fHeader.Size;
fStream.Free;
StartPos := aStream.Position - StartPos;
fStream := TFliStream.Create( aStream, fHeader.Size - StartPos );
fSize := Point( Width, Height );
ResetFrameRange;
NextFrame;
fOfsFrame1 := 0;
fOfsFrame2 := Stream.Position;
// Fix header fields
fHeader.oFrame1 := fOfsFrame1 + StartPos;
fHeader.oFrame2 := fOfsFrame2 + StartPos;
end;
end;
// TFliPlayer
procedure TFliPlayer.ProcessFrame;
begin
if PFliFrame(CurrentFrame).Magic <> idFrame
then raise Exception.Create( sFliCorruptedFrame );
PlayFrame( CurrentFrame, Size, fBufferAddr, fBufferWidth, UnkChunkPlayer );
end;
end.
|
unit cCadFuncaoPessoa;
interface
uses System.Classes, Vcl.Controls,
Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils;
// LISTA DE UNITS
type
TFuncaoPessoa = class
private
// VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE
ConexaoDB: TFDConnection;
F_cod_func_pessoa: Integer;
F_cod_funcao: Integer;
F_nome_funcao: string;
F_cod_pessoa: Integer;
F_nome_pessoa: string;
F_dta_inclusao:TDateTime;
F_usuario_inclusao: string;
F_usuario_alteracao: string;
F_status: string;
public
constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE
destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA
function Inserir: Boolean;
function Atualizar: Boolean;
function Apagar: Boolean;
function Selecionar(id: Integer): Boolean;
published
// VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE
// PARA FORNECER INFORMAÇÕESD EM RUMTIME
property cod_func_pessoa: Integer read F_cod_func_pessoa
write F_cod_func_pessoa;
property cod_funcao: Integer read F_cod_funcao
write F_cod_funcao;
property nome_funcao: string read F_nome_funcao
write F_nome_funcao;
property cod_pessoa: Integer read F_cod_pessoa
write F_cod_pessoa;
property nome_pessoa: string read F_nome_pessoa
write F_nome_pessoa;
property dta_inclusao: TDateTime read F_dta_inclusao
write F_dta_inclusao;
property usuario_inclusao: string read F_usuario_inclusao
write F_usuario_inclusao;
property usuario_alteracao: string read F_usuario_alteracao
write F_usuario_alteracao;
property status: string read F_status
write F_status;
end;
implementation
{$REGION 'Constructor and Destructor'}
constructor TFuncaoPessoa.Create;
begin
ConexaoDB := aConexao;
end;
destructor TFuncaoPessoa.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'CRUD'}
function TFuncaoPessoa.Apagar: Boolean;
var
Qry: TFDQuery;
begin
if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' +
IntToStr(F_cod_func_pessoa) + #13 + 'Descrição: ' + F_nome_pessoa,
mtConfirmation, [mbYes, mbNo], 0) = mrNO then
begin
Result := false;
Abort;
end;
Try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM tb_func_pessoa '+
' WHERE cod_func_pessoa=:cod_func_pessoa ');
Qry.ParamByName('cod_func_pessoa').AsInteger := F_cod_func_pessoa;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
Finally
if Assigned(Qry) then
FreeAndNil(Qry)
End;
end;
function TFuncaoPessoa.Atualizar: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE tb_func_pessoa '+
' SET cod_funcao=:cod_funcao, nome_funcao=:nome_funcao, cod_pessoa=:cod_pessoa, '+
' nome_pessoa=:nome_pessoa, status=:status, dta_alteracao=CURRENT_TIMESTAMP, ' +
' usuario_alteracao=:usuario_alteracao '+
' WHERE cod_func_pessoa=:cod_func_pessoa');
Qry.ParamByName('cod_func_pessoa').AsInteger := F_cod_func_pessoa;
Qry.ParamByName('cod_funcao').AsInteger := F_cod_funcao;
Qry.ParamByName('nome_funcao').AsString := F_nome_funcao;
Qry.ParamByName('cod_pessoa').AsInteger := F_cod_pessoa;
Qry.ParamByName('nome_pessoa').AsString := F_nome_pessoa;
Qry.ParamByName('status').AsString := F_status;
Qry.ParamByName('usuario_alteracao').AsString := F_usuario_alteracao;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TFuncaoPessoa.Inserir: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO tb_func_pessoa '+
' (cod_funcao, nome_funcao, cod_pessoa, nome_pessoa, '+
' status, usuario_inclusao) '+
' VALUES(:cod_funcao,:nome_funcao,:cod_pessoa,:nome_pessoa, '+
' :status,:usuario_inclusao)');
Qry.ParamByName('cod_funcao').AsInteger := Self.F_cod_funcao;
Qry.ParamByName('nome_funcao').AsString := Self.F_nome_funcao;
Qry.ParamByName('cod_pessoa').AsInteger := Self.F_cod_pessoa;
Qry.ParamByName('nome_pessoa').AsString := Self.F_nome_pessoa;
Qry.ParamByName('usuario_inclusao').AsString := Self.F_usuario_inclusao;
Qry.ParamByName('status').AsString := Self.F_status;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TFuncaoPessoa.Selecionar(id: Integer): Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT cod_func_pessoa, cod_funcao, nome_funcao, cod_pessoa, '+
' nome_pessoa, dta_inclusao, status, dta_alteracao, usuario_inclusao, '+
' usuario_alteracao FROM igreja.tb_func_pessoa WHERE cod_func_pessoa=:cod_func_pessoa ');
Qry.ParamByName('cod_func_pessoa').AsInteger := id;
try
Qry.Open;
Self.F_cod_func_pessoa := Qry.FieldByName('cod_func_pessoa').AsInteger;
Self.F_cod_funcao := Qry.FieldByName('cod_funcao').AsInteger;
Self.F_nome_pessoa := Qry.FieldByName('nome_pessoa').AsString;
Self.F_cod_pessoa := Qry.FieldByName('cod_pessoa').AsInteger;
Self.F_dta_inclusao := Qry.FieldByName('dta_inclusao').AsDateTime;
Self.F_usuario_inclusao := Qry.FieldByName('usuario_inclusao').AsString;
Self.F_usuario_alteracao := Qry.FieldByName('usuario_alteracao').AsString;
Self.F_status := Qry.FieldByName('status').AsString;
Except
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
{$ENDREGION}
end.
|
unit GX_IdeProjectOptionsEnhancer;
{$I GX_CondDefine.inc}
interface
uses
SysUtils;
type
TGxIdeProjectOptionsEnhancer = class
public
class function GetEnabled: Boolean; // static;
class procedure SetEnabled(const Value: Boolean); //static;
end;
implementation
uses
Classes,
Messages,
Controls,
StdCtrls,
ExtCtrls,
Forms,
ActnList,
Menus,
GX_IdeFormEnhancer,
GX_dzVclUtils;
type
TComboboxDropHandler = class(TComponent)
private
// In Delphi 8-2007 the "Comboboxes" do not descend from TCustomComboBox. The only ancestor
// that is a standard control is TWinControl, everything else is only available in the
// IDE.
FCmb: TWinControl;
procedure HandleFilesDropped(_Sender: TObject; _Files: TStrings);
class function GenerateName(_cmb: TWinControl): string;
public
constructor Create(_Owner: TComponent); override;
class function IsAlreadyHooked(_cmb: TWinControl): Boolean;
end;
{ TComboboxDropHandler }
class function TComboboxDropHandler.GenerateName(_cmb: TWinControl): string;
begin
Result := _cmb.Name + '_FilesDropHandler';
end;
class function TComboboxDropHandler.IsAlreadyHooked(_cmb: TWinControl): Boolean;
begin
Result := _cmb.FindComponent(GenerateName(_cmb)) <> nil;
end;
constructor TComboboxDropHandler.Create(_Owner: TComponent);
begin
inherited Create(_Owner);
FCmb := _Owner as TWinControl;
Name := GenerateName(FCmb);
TWinControl_ActivateDropFiles(FCmb, HandleFilesDropped);
end;
procedure TComboboxDropHandler.HandleFilesDropped(_Sender: TObject; _Files:
TStrings);
// Since in Delphi 8-2007 FCmb is not a TCustomCombobBox, we cannot just typecast it
// but must send it the appropriate messages ourself. Just to complicate matters,
// we must pass the filename as a WideString.
type
{$IFDEF GX_VER160_up}
PThisChar = PWideString;
ThisString = WideString;
{$ELSE}
// Delphi 6/7
PThisChar = PChar;
ThisString = string;
{$ENDIF}
var
s: ThisString;
begin
s := _Files[0];
FCmb.Perform(WM_SETTEXT, 0, Integer(PThisChar(s)));
FCmb.Perform(CM_TEXTCHANGED, 0, 0);
end;
type
TProjectOptionsEnhancer = class
private
FFormCallbackHandle: TFormChangeHandle;
FControlCallbackHandle: TControlChangeHandle;
FOkBtn: TButton;
FConfigCombo: TCustomCombo;
///<summary>
/// frm can be nil </summary>
procedure HandleFormChanged(_Sender: TObject; _Form: TCustomForm);
function IsProjectOptionsForm(_Form: TCustomForm): Boolean;
// procedure HandleControlChanged(_Sender: TObject; _Form: TCustomForm; _Control: TWinControl);
function TryFindHistoryComboBox(_SettingsControl: TWinControl; _GrpBoxIdx:
Integer;
const _Name: string; out _cmb: TWinControl): Boolean;
function TryGetSettingsControl(_Form: TCustomForm; out _SettingsControl:
TWinControl): Boolean;
procedure ShiftCtrlO(_Sender: TObject);
procedure ShiftCtrlT(_Sender: TObject);
// function TryGetElementEdit(_Form: TCustomForm; out _ed: TEdit): Boolean;
public
constructor Create;
destructor Destroy; override;
end;
var
TheProjectOptionsEnhancer: TProjectOptionsEnhancer = nil;
{ TGxIdeProjectOptionsEnhancer }
class function TGxIdeProjectOptionsEnhancer.GetEnabled: Boolean;
begin
Result := Assigned(TheProjectOptionsEnhancer);
end;
class procedure TGxIdeProjectOptionsEnhancer.SetEnabled(const Value: Boolean);
begin
if Value then begin
if not Assigned(TheProjectOptionsEnhancer) then
TheProjectOptionsEnhancer := TProjectOptionsEnhancer.Create
end else
FreeAndNil(TheProjectOptionsEnhancer);
end;
{ TProjectOptionsEnhancer }
constructor TProjectOptionsEnhancer.Create;
begin
inherited Create;
FFormCallbackHandle := TIDEFormEnhancements.RegisterFormChangeCallback(HandleFormChanged)
end;
destructor TProjectOptionsEnhancer.Destroy;
begin
TIDEFormEnhancements.UnregisterFormChangeCallback(FFormCallbackHandle);
inherited;
end;
//procedure TProjectOptionsEnhancer.HandleControlChanged(_Sender: TObject; _Form: TCustomForm;
// _Control: TWinControl);
//var
// cmp: TComponent;
//begin
// cmp := _Form.FindComponent('HostAppInput');
// if Assigned(cmp) and (cmp.ClassName = 'THistoryPropComboBox') then begin
// TComboboxDropHandler.Create(cmp);
// TIDEFormEnhancements.UnregisterControlChangeCallback(FControlCallbackHandle);
// FControlCallbackHandle := nil;
// end;
//end;
function CheckControl(_Parent: TWinControl; _Idx: Integer; const _ClassName:
string;
out _AsWinCtrl: TWinControl): Boolean;
var
Ctrl: TControl;
i: Integer;
begin
Result := False;
if _Idx = -1 then begin
for i := 0 to _Parent.ControlCount - 1 do begin
Ctrl := _Parent.Controls[i];
if Ctrl.ClassName = _ClassName then begin
_AsWinCtrl := TWinControl(Ctrl);
Result := True;
end;
end;
end else begin
if _Parent.ControlCount <= _Idx then
Exit;
Ctrl := _Parent.Controls[_Idx];
if Ctrl.ClassName <> _ClassName then
Exit;
_AsWinCtrl := TWinControl(Ctrl);
Result := True;
end;
end;
function TProjectOptionsEnhancer.TryGetSettingsControl(_Form: TCustomForm;
out _SettingsControl: TWinControl): Boolean;
var
wctrl: TWinControl;
begin
Result := False;
{$IFDEF GX_VER180_up} // Delphi 2006 (BDS 3)
if not CheckControl(_Form, 3, 'TPanel', wctrl) then
Exit;
if not CheckControl(wctrl, 1, 'TPropertySheetControl', wctrl) then
Exit;
if not CheckControl(wctrl, -1, 'TDebuggerLocalPage', wctrl) then
Exit;
_SettingsControl := wctrl;
// in Delphi 10 there is an additional TPanel that contains the group boxes
if CheckControl(wctrl, 2, 'TPanel', wctrl) then
_SettingsControl := wctrl;
Result := True;
{$ELSE}{$IFDEF GX_VER170_up} // Delphi 9/2005 (BDS 2)
if not CheckControl(_Form, 2, 'TPanel', wctrl) then
Exit;
if not CheckControl(wctrl, 1, 'TPropertySheetControl', wctrl) then
Exit;
if not CheckControl(wctrl, -1, 'TDebuggerLocalPage', wctrl) then
Exit;
_SettingsControl := wctrl;
// in Delphi 10 there is an additional TPanel that contains the group boxes
if CheckControl(wctrl, 2, 'TPanel', wctrl) then
_SettingsControl := wctrl;
Result := True;
{$ELSE}{$IFDEF GX_VER140_up} // Delphi 6
if not CheckControl(_Form, 1, 'TPageControl', wctrl) then
Exit;
if not CheckControl(wctrl, 0, 'TTabSheet', wctrl) then
Exit;
_SettingsControl := wctrl;
Result := True;
{$ENDIF}{$ENDIF}{$ENDIF}
end;
function TProjectOptionsEnhancer.TryFindHistoryComboBox(_SettingsControl:
TWinControl;
_GrpBoxIdx: Integer; const _Name: string; out _cmb: TWinControl): Boolean;
var
wctrl: TWinControl;
begin
Result := False;
if not CheckControl(_SettingsControl, _GrpBoxIdx, 'TGroupBox', wctrl) then
Exit;
if not CheckControl(wctrl, 0, 'THistoryPropComboBox', wctrl) or (wctrl.Name <>
_Name) then
Exit;
_cmb := wctrl;
Result := True;
end;
type
TInputComboNamesArr = array[0..3] of string;
TInputComboIndexArr = array[0..3] of Integer;
const
// The names of the controls haven't changed, but their type
// and the index of the containing GroupBoxes, so we need to specify them by
// Delphi version, reduced a bit because it didn't change every time
INPUT_COMBO_NAMES: TInputComboNamesArr = (
'HostAppInput', 'ParamInput', 'CWDInput', 'SourcePathInput');
INPUT_COMBO_INDEXES: TInputComboIndexArr = (
{$IFDEF GX_VER230_up} // RAD Studio XE 2 (17; BDS 9)
0, 1, 2, 3
{$ELSE}{$IFDEF GX_VER220_up} // RAD Studio XE 1 (16; BDS 8)
1, 2, 3, 5
{$ELSE}{$IFDEF GX_VER210_up} // RAD Studio 2010 (15; BDS 7)
0, 1, 2, 4
{$ELSE}{$IFDEF GX_VER185_up} // Delphi 2007 (11; BDS 4)
0, 1, 2, 5
{$ELSE}{$IFDEF GX_VER170_up} // Delphi 9/2005 (BDS 2)
0, 1, 2, -1
{$ELSE}{$IFDEF GX_VER160_up} // Delphi 8 (BDS 1)
- 1, -1, -1, -1 // I have no idea, probably the same as Delphi 2005
{$ELSE}{$IFDEF GX_VER150_up} // Delphi 7
0, 1, 6, -1
{$ELSE}{$IFDEF GX_VER140_up} // Delphi 6
0, 1, -1, -1
{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}
);
{$IFDEF GX_VER230_up} // RAD Studio XE 2 (17; BDS 9)
RUN_PARAMS_DIALOG_CLASS = 'TDelphiProjectOptionsDialog';
RUN_PARAMS_DIALOG_NAME = 'DelphiProjectOptionsDialog';
{$ELSE}{$IFDEF GX_VER220_up} // RAD Studio XE 1 (16; BDS 8)
RUN_PARAMS_DIALOG_CLASS = 'TDelphiProjectOptionsDialog';
RUN_PARAMS_DIALOG_NAME = 'DelphiProjectOptionsDialog';
{$ELSE}{$IFDEF GX_VER210_up} // RAD Studio 2010 (15; BDS 7)
RUN_PARAMS_DIALOG_CLASS = 'TDelphiProjectOptionsDialog';
RUN_PARAMS_DIALOG_NAME = 'DelphiProjectOptionsDialog';
{$ELSE}{$IFDEF GX_VER185_up} // Delphi 2007 (11; BDS 4)
RUN_PARAMS_DIALOG_CLASS = 'TDelphiProjectOptionsDialog';
RUN_PARAMS_DIALOG_NAME = 'DelphiProjectOptionsDialog';
{$ELSE}{$IFDEF GX_VER170_up} // Delphi 9/2005 (BDS 2)
RUN_PARAMS_DIALOG_CLASS = 'TProjectOptionsDialog';
RUN_PARAMS_DIALOG_NAME = 'ProjectOptionsDialog';
{$ELSE}{$IFDEF GX_VER160_up} // Delphi 8 (BDS 1)
RUN_PARAMS_DIALOG_CLASS = 'TProjectOptionsDialog';
RUN_PARAMS_DIALOG_NAME = 'ProjectOptionsDialog';
{$ELSE}{$IFDEF GX_VER150_up} // Delphi 7
RUN_PARAMS_DIALOG_CLASS = 'TRunParamsDlg';
RUN_PARAMS_DIALOG_NAME = 'RunParamsDlg';
{$ELSE}{$IFDEF GX_VER140_up} // Delphi 6
RUN_PARAMS_DIALOG_CLASS = 'TRunParamsDlg';
RUN_PARAMS_DIALOG_NAME = 'RunParamsDlg';
{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}{$ENDIF}
procedure TProjectOptionsEnhancer.HandleFormChanged(_Sender: TObject; _Form:
TCustomForm);
function TryHookCombo(_SettingsPanel: TWinControl; _Index: Integer; const
_Name: string): Boolean;
var
cmb: TWinControl;
begin
Result := False;
if _Index < 0 then
Exit;
if TryFindHistoryComboBox(_SettingsPanel, _Index, _Name, cmb) then begin
if not TComboboxDropHandler.IsAlreadyHooked(cmb) then begin
TComboboxDropHandler.Create(cmb);
Result := True;
end;
end;
end;
const
GX_ACTION_LIST = 'GXProjectOptionsActionList'; // do no localize!
var
i: Integer;
SettingsControl: TWinControl;
al: TActionList;
lbl: TLabel;
begin
if not IsProjectOptionsForm(_Form) then begin
if Assigned(FControlCallbackHandle) then begin
TIDEFormEnhancements.UnregisterControlChangeCallback(FControlCallbackHandle);
FControlCallbackHandle := nil;
end;
Exit;
end;
if _Form.FindComponent(GX_ACTION_LIST) = nil then begin
al := TActionList.Create(_Form);
al.Name := GX_ACTION_LIST;
FOkBtn := _Form.FindComponent('OKButton') as TButton;
if Assigned(FOkBtn) then begin
TActionlist_Append(al, 'OK', ShiftCtrlO, ShortCut(Ord('O'), [ssShift, ssCtrl]));
FOkBtn.Caption := 'OK (s+c+O)';
end;
FConfigCombo := _Form.FindComponent('cbConfig') as TCustomCombo;
if Assigned(FConfigCombo) then begin
TActionlist_Append(al, 'Target', ShiftCtrlT, ShortCut(Ord('T'), [ssShift, ssCtrl]));
lbl := _Form.FindComponent('Label1') as TLabel; // sic!
if Assigned(lbl) then begin
lbl.AutoSize := False;
lbl.Top := FConfigCombo.Top;
lbl.Height := lbl.Height * 2;
lbl.Width := FConfigCombo.Left - lbl.Left;
lbl.WordWrap := True;
lbl.Caption := '&Target: (s+c+T)';
end;
end;
end;
// FControlCallbackHandle := TIDEFormEnhancements.RegisterControlChangeCallback(HandleControlChanged);
if not TryGetSettingsControl(_Form, SettingsControl) then
Exit;
for i := 0 to 3 do
TryHookCombo(SettingsControl, INPUT_COMBO_INDEXES[i], INPUT_COMBO_NAMES[i]);
end;
procedure TProjectOptionsEnhancer.ShiftCtrlO(_Sender: TObject);
begin
FOkBtn.Click;
end;
procedure TProjectOptionsEnhancer.ShiftCtrlT(_Sender: TObject);
begin
TWinControl_SetFocus(FConfigCombo);
end;
function TProjectOptionsEnhancer.IsProjectOptionsForm(_Form: TCustomForm):
Boolean;
begin
Result := (_Form.ClassName = RUN_PARAMS_DIALOG_CLASS) and (_Form.Name =
RUN_PARAMS_DIALOG_NAME);
end;
initialization
finalization
TGxIdeProjectOptionsEnhancer.SetEnabled(False);
end.
|
//Exercicio 42: Prepare um algoritmo que determine o valor de S, em que:
// S = 1/1 - 2/4 + 3/9 - 4/16 + 5/25 - 6/36 ... - 10/100
{ Solução em Portugol
Algoritmo Exercicio 42;
Var
S: real;
contador,alternador_sinal: inteiro;
Inicio
exiba("Programa que calcula uma soma maluca.");
S <- 0;
alternador_sinal <- 1;
para contador <-1 até 10 faca
S <- S + (contador/(contador*contador)) * alternador_sinal;
alternador_sinal <- alternador_sinal * (-1);
fimpara;
exiba("O valor da soma é: ",S);
Fim.
}
// Solução em Pascal
Program Exercicio42;
uses crt;
var
S: real;
contador,alternador_sinal: integer;
begin
clrscr;
writeln('Programa que calcula uma soma maluca.');
S := 0;
alternador_sinal := 1;
for contador := 1 to 10 do
begin
S := S + (contador/(contador*contador)) * alternador_sinal;
alternador_sinal := alternador_sinal * (-1);
end;
writeln('O valor da soma é: ',S:0:2);
repeat until keypressed;
end. |
unit Androidapi.JNI.Toast;
interface
{$IF RTLVersion < 30}
uses
Androidapi.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.GraphicsContentViewText;
{$ENDIF}
//Java bridge class imported by hand by Brian Long (http://blong.com)
type
{$IF RTLVersion < 30}
JToast = interface;
JToastClass = interface(JObjectClass)
['{69E2D233-B9D3-4F3E-B882-474C8E1D50E9}']
{Property methods}
function _GetLENGTH_LONG: Integer; cdecl;
function _GetLENGTH_SHORT: Integer; cdecl;
{Methods}
function init(context: JContext): JToast; cdecl; overload;
function makeText(context: JContext; text: JCharSequence; duration: Integer): JToast; cdecl;
{Properties}
property LENGTH_LONG: Integer read _GetLENGTH_LONG;
property LENGTH_SHORT: Integer read _GetLENGTH_SHORT;
end;
[JavaSignature('android/widget/Toast')]
JToast = interface(JObject)
['{FD81CC32-BFBC-4838-8893-9DD01DE47B00}']
{Methods}
procedure cancel; cdecl;
function getDuration: Integer; cdecl;
function getGravity: Integer; cdecl;
function getHorizontalMargin: Single; cdecl;
function getVerticalMargin: Single; cdecl;
function getView: JView; cdecl;
function getXOffset: Integer; cdecl;
function getYOffset: Integer; cdecl;
procedure setDuration(value: Integer); cdecl;
procedure setGravity(gravity, xOffset, yOffset: Integer); cdecl;
procedure setMargin(horizontalMargin, verticalMargin: Single); cdecl;
procedure setText(s: JCharSequence); cdecl;
procedure setView(view: JView); cdecl;
procedure show; cdecl;
end;
TJToast = class(TJavaGenericImport<JToastClass, JToast>) end;
{$ENDIF}
TToastLength = (LongToast, ShortToast);
procedure Toast(const Msg: string; Duration: TToastLength = ShortToast);
implementation
uses
{$IF RTLVersion >= 28}
Androidapi.Helpers,
{$ENDIF}
{$IF RTLVersion >= 30}
Androidapi.JNI.Widget,
Androidapi.JNI.JavaTypes,
{$ENDIF}
FMX.Helpers.Android;
procedure Toast(const Msg: string; Duration: TToastLength);
var
ToastLength: Integer;
begin
if Duration = ShortToast then
ToastLength := TJToast.JavaClass.LENGTH_SHORT
else
ToastLength := TJToast.JavaClass.LENGTH_LONG;
{$IF RTLVersion < 25} // Prior to 10.2 Tokyo FMX and Androi Java run on separate threads
CallInUiThread(
procedure
begin
{$ENDIF}
TJToast.JavaClass.makeText(
{$IF RTLVersion >= 30}
TAndroidHelper.Context,
{$ELSE}
SharedActivityContext,
{$ENDIF}
StrToJCharSequence(msg),
ToastLength).show
{$IF RTLVersion < 25}
end);
{$ENDIF}
end;
end.
|
unit ce_dcd;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, process, forms, strutils,
{$IFDEF WINDOWS}
windows,
{$ENDIF}
ce_common, ce_writableComponent, ce_interfaces, ce_observer, ce_synmemo, ce_project;
type
(**
* Wrap the dcd-server and dcd-client processes.
*
* Projects folders are automatically imported: ICEProjectObserver.
* Completion, hints and declaration finder automatically work on the current
* document: ICEMultiDocObserver.
*)
TCEDcdWrapper = class(TWritableLfmTextComponent, ICEProjectObserver, ICEMultiDocObserver)
private
fTempLines: TStringList;
fImportCache: TStringList;
//fPortNum: Word;
fServerWasRunning: boolean;
fClient, fServer: TProcess;
fAvailable: boolean;
fDoc: TCESynMemo;
fProj: TCEProject;
procedure killServer;
procedure terminateClient;
procedure waitClient;
//
procedure projNew(aProject: TCEProject);
procedure projChanged(aProject: TCEProject);
procedure projClosing(aProject: TCEProject);
procedure projFocused(aProject: TCEProject);
procedure projCompiling(aProject: TCEProject);
//
procedure docNew(aDoc: TCESynMemo);
procedure docFocused(aDoc: TCESynMemo);
procedure docChanged(aDoc: TCESynMemo);
procedure docClosing(aDoc: TCESynMemo);
public
constructor create(aOwner: TComponent); override;
destructor destroy; override;
//
procedure addImportFolder(const aFolder: string);
procedure getComplAtCursor(aList: TStrings);
procedure getCallTip(out tips: string);
procedure getDdocFromCursor(out aComment: string);
procedure getDeclFromCursor(out aFilename: string; out aPosition: Integer);
//
property available: boolean read fAvailable;
end;
var
DcdWrapper: TCEDcdWrapper;
implementation
{$REGION Standard Comp/Obj------------------------------------------------------}
constructor TCEDcdWrapper.create(aOwner: TComponent);
const
clientName = 'dcd-client' + exeExt;
serverName = 'dcd-server' + exeExt;
begin
inherited;
//
fAvailable := exeInSysPath(clientName) and exeInSysPath(serverName);
if not fAvailable then
exit;
//
fClient := TProcess.Create(self);
fClient.Executable := exeFullName(clientName);
fClient.Options := [poUsePipes{$IFDEF WINDOWS}, poNewConsole{$ENDIF}];
fClient.ShowWindow := swoHIDE;
//
fServerWasRunning := AppIsRunning((serverName));
if not fServerWasRunning then begin
fServer := TProcess.Create(self);
fServer.Executable := exeFullName(serverName);
fServer.Options := [{$IFDEF WINDOWS} poNewConsole{$ENDIF}];
{$IFNDEF DEBUG}
fServer.ShowWindow := swoHIDE;
{$ENDIF}
end;
fTempLines := TStringList.Create;
fImportCache := TStringList.Create;
if (fServer <> nil) then
fServer.Execute;
//
EntitiesConnector.addObserver(self);
end;
destructor TCEDcdWrapper.destroy;
begin
EntitiesConnector.removeObserver(self);
fImportCache.Free;
if fTempLines <> nil then
fTempLines.Free;
if fServer <> nil then begin
if not fServerWasRunning then killServer;
fServer.Free;
end;
fClient.Free;
inherited;
end;
{$ENDREGION}
{$REGION ICEProjectObserver ----------------------------------------------------}
procedure TCEDcdWrapper.projNew(aProject: TCEProject);
begin
fProj := aProject;
end;
procedure TCEDcdWrapper.projChanged(aProject: TCEProject);
var
i: Integer;
fold: string;
folds: TStringList;
begin
if fProj <> aProject then
exit;
if fProj = nil then
exit;
//
folds := TStringList.Create;
try
for i:= 0 to fProj.Sources.Count-1 do
begin
fold := extractFilePath(fProj.getAbsoluteSourceName(i));
if folds.IndexOf(fold) = -1 then
folds.Add(fold);
end;
for i := 0 to fProj.currentConfiguration.pathsOptions.importModulePaths.Count-1 do
begin
fold := fProj.currentConfiguration.pathsOptions.importModulePaths.Strings[i];
if DirectoryExists(fold) and (folds.IndexOf(fold) = -1) then
folds.Add(fold);
end;
for fold in folds do addImportFolder(fold);
finally
folds.Free;
end;
end;
procedure TCEDcdWrapper.projClosing(aProject: TCEProject);
begin
if fProj <> aProject then exit;
fProj := nil;
end;
procedure TCEDcdWrapper.projFocused(aProject: TCEProject);
begin
fProj := aProject;
end;
procedure TCEDcdWrapper.projCompiling(aProject: TCEProject);
begin
end;
{$ENDREGION}
{$REGION ICEMultiDocObserver ---------------------------------------------------}
procedure TCEDcdWrapper.docNew(aDoc: TCESynMemo);
begin
fDoc := aDoc;
end;
procedure TCEDcdWrapper.docFocused(aDoc: TCESynMemo);
begin
fDoc := aDoc;
end;
procedure TCEDcdWrapper.docChanged(aDoc: TCESynMemo);
begin
if fDoc <> aDoc then exit;
end;
procedure TCEDcdWrapper.docClosing(aDoc: TCESynMemo);
begin
if fDoc <> aDoc then exit;
fDoc := nil;
end;
{$ENDREGION}
{$REGION DCD things ------------------------------------------------------------}
procedure TCEDcdWrapper.terminateClient;
begin
if fClient.Running then
fClient.Terminate(0);
end;
procedure TCEDcdWrapper.killServer;
begin
if not fAvailable then exit;
//
fClient.Parameters.Clear;
fClient.Parameters.Add('--shutdown');
fClient.Execute;
{$IFDEF LINUX}
fClient.Terminate(0);
fServer.Terminate(0);
{$ENDIF}
{$IFDEF DARWIN}
//
{$ENDIF}
end;
procedure TCEDcdWrapper.waitClient;
begin
while fClient.Running do
sleep(5);
end;
procedure TCEDcdWrapper.addImportFolder(const aFolder: string);
begin
if not fAvailable then exit;
//
if fImportCache.IndexOf(aFolder) <> -1 then exit;
fImportCache.Add(aFolder);
fClient.Parameters.Clear;
fClient.Parameters.Add('-I' + aFolder);
fClient.Execute;
waitClient;
end;
procedure TCEDcdWrapper.getCallTip(out tips: string);
begin
if not fAvailable then exit;
if fDoc = nil then exit;
//
fTempLines.Assign(fDoc.Lines);
fTempLines.SaveToFile(fDoc.tempFilename);
//
terminateClient;
//
fClient.Parameters.Clear;
fClient.Parameters.Add('-c');
fClient.Parameters.Add(intToStr(fDoc.SelStart - 1));
fClient.Parameters.Add(fDoc.tempFilename);
fClient.Execute;
//
fTempLines.LoadFromStream(fClient.Output);
if fTempLines.Count = 0 then exit;
if not (fTempLines.Strings[0] = 'calltips') then exit;
//
fTempLines.Delete(0);
tips := fTempLines.Text;
tips := tips[1..length(tips)-2];
end;
procedure TCEDcdWrapper.getComplAtCursor(aList: TStrings);
var
i: Integer;
kind: Char;
item: string;
begin
if not fAvailable then exit;
if fDoc = nil then exit;
//
fTempLines.Assign(fDoc.Lines);
fTempLines.SaveToFile(fDoc.tempFilename);
//
terminateClient;
//
fClient.Parameters.Clear;
fClient.Parameters.Add('-c');
fClient.Parameters.Add(intToStr(fDoc.SelStart - 1));
fClient.Parameters.Add(fDoc.tempFilename);
fClient.Execute;
//
fTempLines.LoadFromStream(fClient.Output);
if fTempLines.Count = 0 then exit;
if not (fTempLines.Strings[0] = 'identifiers') then exit;
//
aList.Clear;
for i := 1 to fTempLines.Count-1 do
begin
item := fTempLines.Strings[i];
kind := item[length(item)];
setLength(item, length(item)-2);
case kind of
'c': item += ' (class) ';
'i': item += ' (interface) ';
's': item += ' (struct) ';
'u': item += ' (union) ';
'v': item += ' (variable) ';
'm': item += ' (member) ';
'k': item += ' (reserved word) ';
'f': item += ' (function) ';
'g': item += ' (enum) ';
'e': item += ' (enum member) ';
'P': item += ' (package) ';
'M': item += ' (module) ';
'a': item += ' (array) ';
'A': item += ' (associative array)';
'l': item += ' (alias) ';
't': item += ' (template) ';
'T': item += ' (mixin) ';
end;
aList.Add(item);
end;
end;
procedure TCEDcdWrapper.getDdocFromCursor(out aComment: string);
var
i: Integer;
begin
if not fAvailable then exit;
if fDoc = nil then exit;
//
i := fDoc.MouseStart;
if i = 0 then exit;
//
fTempLines.Assign(fDoc.Lines);
fTempLines.SaveToFile(fDoc.tempFilename);
//
terminateClient;
//
fClient.Parameters.Clear;
fClient.Parameters.Add('-d');
fClient.Parameters.Add('-c');
fClient.Parameters.Add(intToStr(i - 1));
fClient.Parameters.Add(fDoc.tempFilename);
fClient.Execute;
//
aComment := '';
fTempLines.LoadFromStream(fClient.Output);
for i := 0 to fTempLines.Count-1 do
aComment += ReplaceStr(fTempLines.Strings[i], '\n', LineEnding);
end;
procedure TCEDcdWrapper.getDeclFromCursor(out aFilename: string; out aPosition: Integer);
var
i: Integer;
str, loc: string;
begin
if not fAvailable then exit;
if fDoc = nil then exit;
//
fTempLines.Assign(fDoc.Lines);
fTempLines.SaveToFile(fDoc.tempFilename);
//
terminateClient;
//
fClient.Parameters.Clear;
fClient.Parameters.Add('-l');
fClient.Parameters.Add('-c');
fClient.Parameters.Add(intToStr(fDoc.SelStart - 1));
fClient.Parameters.Add(fDoc.tempFilename);
fClient.Execute;
//
str := 'a';
setlength(str, 256);
i := fClient.Output.Read(str[1], 256);
setLength(str, i);
if str <> '' then
begin
i := Pos(#9, str);
if i = -1 then
exit;
loc := str[i+1..length(str)];
aFilename := str[1..i-1];
loc := ReplaceStr(loc, LineEnding, '');
aPosition := strToIntDef(loc, -1);
end;
end;
{$ENDREGION}
initialization
DcdWrapper := TCEDcdWrapper.create(nil);
finalization
DcdWrapper.Free;
end.
|
unit uPrincipal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, System.Actions, Vcl.ActnList,
Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.ToolWin, Vcl.ActnCtrls,
System.ImageList, Vcl.ImgList;
type
TFprincipal = class(TForm)
MainMenu1: TMainMenu;
Lanamentos1: TMenuItem;
Apuraa1: TMenuItem;
FecharApuracao1: TMenuItem;
Despesas1: TMenuItem;
Faturamento1: TMenuItem;
Sair1: TMenuItem;
ActionToolBar1: TActionToolBar;
ActionManager1: TActionManager;
act_Despesas: TAction;
act_Faturamento: TAction;
act_ApuraAnual: TAction;
act_Sair: TAction;
ApuraesFinalizadas1: TMenuItem;
act_ApurFechadas: TAction;
ImageList1: TImageList;
Configuraes1: TMenuItem;
procedure Despesas1Click(Sender: TObject);
procedure Sair1Click(Sender: TObject);
procedure Faturamento1Click(Sender: TObject);
procedure act_DespesasExecute(Sender: TObject);
procedure act_FaturamentoExecute(Sender: TObject);
procedure act_SairExecute(Sender: TObject);
procedure FecharApuracao1Click(Sender: TObject);
procedure ApuraesFinalizadas1Click(Sender: TObject);
procedure act_ApuraAnualExecute(Sender: TObject);
procedure act_ApurFechadasExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Configuraes1Click(Sender: TObject);
private
{ Private declarations }
public
procedure pcdMensagem(psMensagem: String);
function fncValidaAno(psAno: String): Boolean;
{ Public declarations }
end;
var
Fprincipal: TFprincipal;
implementation
{$R *.dfm}
uses uCalculaDespesa, uFaturamento, uApuracao, uConfiguracao;
procedure TFprincipal.act_ApuraAnualExecute(Sender: TObject);
begin
FecharApuracao1.Click;
end;
procedure TFprincipal.act_ApurFechadasExecute(Sender: TObject);
begin
ApuraesFinalizadas1.Click;
end;
procedure TFprincipal.act_DespesasExecute(Sender: TObject);
begin
Despesas1.Click;
end;
procedure TFprincipal.act_FaturamentoExecute(Sender: TObject);
begin
Faturamento1.Click;
end;
procedure TFprincipal.act_SairExecute(Sender: TObject);
begin
Sair1.Click;
end;
procedure TFprincipal.ApuraesFinalizadas1Click(Sender: TObject);
begin
Application.CreateForm(TFApuracao, FApuracao);
FApuracao.vPaleta := 'Fechadas';
FApuracao.ShowModal;
FreeAndNil(FApuracao);
end;
procedure TFprincipal.Configuraes1Click(Sender: TObject);
begin
Application.CreateForm(TFConfiguracao, FConfiguracao);
FConfiguracao.ShowModal;
FreeAndNil(FConfiguracao);
end;
procedure TFprincipal.Despesas1Click(Sender: TObject);
begin
Application.CreateForm(TFCalculaDespesa, FCalculaDespesa);
FCalculaDespesa.ShowModal;
FreeAndNil(FCalculaDespesa);
end;
procedure TFprincipal.Sair1Click(Sender: TObject);
begin
Close;
end;
procedure TFprincipal.Faturamento1Click(Sender: TObject);
begin
Application.CreateForm(TFFaturamento, FFaturamento);
FFaturamento.ShowModal;
FreeAndNil(FFaturamento);
end;
procedure TFprincipal.FecharApuracao1Click(Sender: TObject);
begin
Application.CreateForm(TFApuracao, FApuracao);
FApuracao.vPaleta := 'Apuração';
FApuracao.ShowModal;
FreeAndNil(FApuracao);
end;
procedure TFprincipal.FormShow(Sender: TObject);
begin
Height := Screen.WorkAreaHeight;
Width := Screen.WorkAreaWidth;
end;
procedure TFprincipal.pcdMensagem(psMensagem: String);
begin
Application.MessageBox(PChar(psMensagem), 'Despesas', 0);
end;
function TFprincipal.fncValidaAno(psAno : String): Boolean;
var
psData : String;
begin
Result := True;
psData := Trim('01/01/'+psAno);
if Length(Trim(psAno)) < 4 then
begin
pcdMensagem('Ano inválido, verifique por favor!');
Result := False;
Exit;
end;
try
StrToDate(psData);
except
pcdMensagem('Ano inválido, verifique por favor!');
Result := False;
end;
end;
end.
|
unit GX_EditorExpertManager;
{$I GX_CondDefine.inc}
interface
uses
Classes, Contnrs, GX_GenericClasses, GX_EditorExpert;
type
TGxEditorExpertManager = class(TObject)
private
FEditorExpertList: TObjectList;
function GetEditorExpert(const Index: Integer): TEditorExpert;
function GetEditorExpertCount: Integer;
procedure LoadEditorExperts;
procedure FreeEditorExperts;
public
constructor Create;
destructor Destroy; override;
function FindExpert(const ExpertName: string; out Idx: integer): boolean;
function GetExpertList: TList;
property EditorExpertList[const Index: Integer]: TEditorExpert read GetEditorExpert;
property EditorExpertCount: Integer read GetEditorExpertCount;
end;
implementation
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
SysUtils, GX_ConfigurationInfo;
{ TGxEditorExpertManager }
constructor TGxEditorExpertManager.Create;
begin
inherited Create;
FEditorExpertList := TObjectList.Create(False);
LoadEditorExperts;
end;
destructor TGxEditorExpertManager.Destroy;
begin
FreeEditorExperts;
FreeAndNil(FEditorExpertList);
inherited Destroy;
end;
function TGxEditorExpertManager.GetEditorExpert(const Index: Integer): TEditorExpert;
begin
if Index < GetEditorExpertCount then
Result := FEditorExpertList[Index] as TEditorExpert
else
Result := nil;
end;
function TGxEditorExpertManager.GetEditorExpertCount: Integer;
begin
Result := FEditorExpertList.Count;
end;
function TGxEditorExpertManager.GetExpertList: TList;
begin
Result := FEditorExpertList;
end;
procedure TGxEditorExpertManager.LoadEditorExperts;
var
i: Integer;
EditorExpert: TEditorExpert;
begin
ConfigInfo.EditorExpertsEnabled := True;
for i := 0 to EditorExpertClassList.Count - 1 do
begin
EditorExpert := GetExpertClassByIndex(i).Create;
EditorExpert.LoadSettings;
FEditorExpertList.Add(EditorExpert);
end;
end;
function TGxEditorExpertManager.FindExpert(const ExpertName: string; out Idx: integer): boolean;
var
i: Integer;
begin
for i := 0 to EditorExpertCount - 1 do
begin
if SameText(EditorExpertList[i].GetName, ExpertName) then
begin
Idx := i;
Result := True;
Exit;
end;
end;
Result := False;
end;
procedure TGxEditorExpertManager.FreeEditorExperts;
var
i: Integer;
begin
{$IFOPT D+} SendDebug('Freeing the editor experts'); {$ENDIF}
if FEditorExpertList <> nil then
begin
for i := 0 to FEditorExpertList.Count - 1 do
FEditorExpertList[i].Free;
FEditorExpertList.Clear;
end;
end;
end.
|
unit ULiveCalendarDemo;
interface
uses
FMX.TMSCloudBase, FMX.TMSCloudLiveCalendar, FMX.Controls, SysUtils, DateUtils,
FMX.StdCtrls, FMX.ListBox, FMX.Edit, FMX.Grid, FMX.Layouts, FMX.Dialogs, UITypes,
FMX.TMSCloudListView, FMX.ExtCtrls, FMX.Objects, System.Classes, FMX.Types, FMX.Forms,
FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomLive, FMX.TMSCloudLiveFMX,
FMX.TMSCloudCustomLiveCalendar;
type
TForm1 = class(TForm)
StyleBook1: TStyleBook;
Panel1: TPanel;
Button1: TButton;
GroupBox1: TGroupBox;
ComboBox1: TComboBox;
dpCalStartDate: TCalendarEdit;
dpCalEndDate: TCalendarEdit;
btUpdate: TButton;
Label1: TLabel;
Label13: TLabel;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label11: TLabel;
Label10: TLabel;
Edit3: TEdit;
Edit4: TEdit;
Edit5: TEdit;
StartDate: TCalendarEdit;
EndDate: TCalendarEdit;
StartTime: TCalendarEdit;
EndTime: TCalendarEdit;
cbVisibility: TComboBox;
cbAllday: TCheckBox;
CloudListView1: TTMSFMXCloudListView;
Panel2: TPanel;
Button6: TButton;
Button7: TButton;
Button5: TButton;
TMSFMXCloudLiveCalendar1: TTMSFMXCloudLiveCalendar;
Image1: TImage;
btRemove: TButton;
procedure Button1Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
procedure FillCalendars();
procedure FillCalendarItems();
procedure FillCalendarItemDetails();
procedure ToggleControls();
procedure ToggleEditControls(Enabled: boolean);
procedure ClearControls();
procedure Init();
function ValidateForm(): boolean;
procedure SetCalendarItem(Item: TLiveCalendarItem);
procedure ComboBox1Change(Sender: TObject);
procedure TMSFMXCloudLiveCalendar1ReceivedAccessToken(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btUpdateClick(Sender: TObject);
procedure cbAlldayClick(Sender: TObject);
procedure btRemoveClick(Sender: TObject);
procedure CloudListView1Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Connected: boolean;
Inserting: boolean;
end;
var
Form1: TForm1;
implementation
{$R *.FMX}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// LiveAppkey = 'xxxxxxxxx';
// LiveAppSecret = 'yyyyyyyy';
{$I APPIDS.INC}
procedure TForm1.TMSFMXCloudLiveCalendar1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudLiveCalendar1.SaveTokens;
Init;
end;
procedure TForm1.btRemoveClick(Sender: TObject);
begin
TMSFMXCloudLiveCalendar1.ClearTokens;
Connected := false;
ToggleControls;
end;
procedure TForm1.btUpdateClick(Sender: TObject);
begin
FillCalendarItems;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TMSFMXCloudLiveCalendar1.App.Key := LiveAppKey;
TMSFMXCloudLiveCalendar1.App.Secret := LiveAppSecret;
TMSFMXCloudLiveCalendar1.Logging := true;
if not TMSFMXCloudLiveCalendar1.TestTokens then
TMSFMXCloudLiveCalendar1.RefreshAccess;
if not TMSFMXCloudLiveCalendar1.TestTokens then
TMSFMXCloudLiveCalendar1.DoAuth
else
Init;
end;
procedure TForm1.Button5Click(Sender: TObject);
var
li: TLiveCalendarItem;
begin
if not (Inserting) then
begin
ClearControls;
Edit3.SetFocus;
CloudListView1.ItemIndex := -1;
Button5.Text := 'Insert';
Inserting := true;
end
else
begin
if not (ValidateForm) then
exit;
Button5.Text := 'New';
li := TMSFMXCloudLiveCalendar1.Items.Add;
SetCalendarItem(li);
li.CalendarID := (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TLiveCalendar).ID;
TMSFMXCloudLiveCalendar1.Add(li);
FillCalendarItems;
Inserting := false;
end;
end;
procedure TForm1.Button6Click(Sender: TObject);
var
buttonSelected: integer;
begin
if CloudListView1.ItemIndex >= 0 then
begin
buttonSelected := MessageDlg('Are you sure you want to delete the selected Event?', TMsgDlgType.mtConfirmation, mbOKCancel, 0);
if buttonSelected = mrOk then
begin
TMSFMXCloudLiveCalendar1.Delete(CloudListView1.Items[CloudListView1.ItemIndex].Data);
FillCalendarItems;
ClearControls;
end;
end
else
begin
ShowMessage('Please select an Event first.');
end;
end;
procedure TForm1.Button7Click(Sender: TObject);
var
li: TLiveCalendarItem;
SelectedID: string;
begin
if CloudListView1.ItemIndex >= 0 then
begin
if not (ValidateForm) then
exit;
li := CloudListView1.Items[CloudListView1.ItemIndex].Data;
SetCalendarItem(li);
TMSFMXCloudLiveCalendar1.Update(li);
SelectedID := li.ID;
FillCalendarItems;
CloudListView1.ItemIndex := TMSFMXCloudLiveCalendar1.Items.Find(SelectedID).Index;
end
else
begin
ShowMessage('Please select an Event first.');
end;
end;
procedure TForm1.cbAlldayClick(Sender: TObject);
begin
StartTime.Enabled := not cbAllday.IsChecked;
EndTime.Enabled := not cbAllday.IsChecked;
end;
procedure TForm1.ClearControls;
begin
Edit3.Text := '';
Edit4.Text := '';
Edit5.Text := '';
cbVisibility.ItemIndex := 0;
cbAllday.IsChecked := false;
StartDate.Date := Now;
EndDate.Date := Now;
StartTime.Date := StrToDateTime(IntToStr(HourOf(IncHour(Time, 1))) + ':00');
EndTime.Date := IncHour(StartTime.Date, 2);
end;
procedure TForm1.CloudListView1Change(Sender: TObject);
begin
FillCalendarItemDetails;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
ClearControls;
FillCalendarItems;
end;
procedure TForm1.FillCalendarItems;
var
I: Integer;
LiveCalendar: TLiveCalendar;
li: TListItem;
begin
if ComboBox1.ItemIndex >= 0 then
begin
LiveCalendar := (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TLiveCalendar);
ToggleEditControls(not LiveCalendar.ReadOnly);
TMSFMXCloudLiveCalendar1.GetCalendar(LiveCalendar.ID, dpCalStartDate.Date, dpCalEndDate.Date);
CloudListView1.Items.Clear;
for I := 0 to TMSFMXCloudLiveCalendar1.Items.Count - 1 do
begin
li := CloudListView1.Items.Add;
li.Text := FormatDateTime('dd/mm/yyyy hh:nn', TMSFMXCloudLiveCalendar1.Items[I].StartTime);
li.SubItems.Add(FormatDateTime('dd/mm/yyyy hh:nn', TMSFMXCloudLiveCalendar1.Items[I].EndTime));
li.SubItems.Add(TMSFMXCloudLiveCalendar1.Items[I].Summary);
li.SubItems.Add(TMSFMXCloudLiveCalendar1.Items[I].Description);
li.Data := TMSFMXCloudLiveCalendar1.Items[I];
end;
end;
end;
procedure TForm1.FillCalendars;
var
I: Integer;
begin
TMSFMXCloudLiveCalendar1.GetCalendars();
ComboBox1.Items.Clear;
for I := 0 to TMSFMXCloudLiveCalendar1.Calendars.Count - 1 do
ComboBox1.Items.AddObject(TMSFMXCloudLiveCalendar1.Calendars[I].Summary, TMSFMXCloudLiveCalendar1.Calendars[I]);
ComboBox1.ItemIndex := 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
TMSFMXCloudLiveCalendar1.PersistTokens.Key := ExtractFilePath(ParamStr(0)) + 'live.ini';
TMSFMXCloudLiveCalendar1.PersistTokens.Section := 'tokens';
TMSFMXCloudLiveCalendar1.LoadTokens;
dpCalStartDate.Date := IncMonth(Now, -1);
dpCalEndDate.Date := IncMonth(Now, 2);
ClearControls;
Inserting := false;
Connected := false;
ToggleControls;
CloudListView1.ColumnByIndex(3).width := 370;
end;
procedure TForm1.Init;
begin
Connected := true;
ToggleControls;
FillCalendars;
FillCalendarItems;
end;
procedure TForm1.FillCalendarItemDetails();
var
li: TLiveCalendarItem;
begin
if CloudListView1.ItemIndex >= 0 then
begin
li := CloudListView1.Items[CloudListView1.ItemIndex].Data;
Edit3.Text := li.Summary;
Edit4.Text := li.Description;
Edit5.Text := li.Location;
StartDate.Date := li.StartTime;
EndDate.Date := li.EndTime;
StartTime.Date := li.StartTime;
EndTime.Date := li.EndTime;
cbVisibility.ItemIndex := Ord(li.Visibility);
cbAllday.IsChecked := li.IsAllDay;
end;
end;
procedure TForm1.SetCalendarItem(Item: TLiveCalendarItem);
begin
Item.Summary := Edit3.Text;
Item.Description := Edit4.Text;
Item.Location := Edit5.Text;
if cbAllday.IsChecked then
begin
Item.StartTime := EncodeDateTime(YearOf(StartDate.Date), MonthOf(StartDate.Date), DayOf(StartDate.Date), 0, 0, 0, 0);
Item.EndTime := EncodeDateTime(YearOf(EndDate.Date), MonthOf(EndDate.Date), DayOf(EndDate.Date), 0, 0, 0, 0);
Item.IsAllDay := true;
end
else
begin
Item.StartTime := EncodeDateTime(YearOf(StartDate.Date), MonthOf(StartDate.Date), DayOf(StartDate.Date), HourOf(StartTime.Date), MinuteOf(StartTime.Date), SecondOf(StartTime.Date),0);
Item.EndTime := EncodeDateTime(YearOf(EndDate.Date), MonthOf(EndDate.Date), DayOf(EndDate.Date), HourOf(EndTime.Date), MinuteOf(EndTime.Date), SecondOf(EndTime.Date),0);
Item.IsAllDay := false;
end;
Item.Visibility := TVisibility(cbVisibility.ItemIndex);
end;
procedure TForm1.ToggleControls;
begin
GroupBox1.Enabled := Connected;
GroupBox2.Enabled := Connected;
GroupBox3.Enabled := Connected;
Panel2.Enabled := Connected;
ComboBox1.Enabled := Connected;
dpCalStartDate.Enabled := Connected;
dpCalEndDate.Enabled := Connected;
btUpdate.Enabled := Connected;
CloudListView1.Enabled := Connected;
Edit3.Enabled := Connected;
Edit4.Enabled := Connected;
Edit5.Enabled := Connected;
cbVisibility.Enabled := Connected;
cbAllday.Enabled := Connected;
StartDate.Enabled := Connected;
EndDate.Enabled := Connected;
StartTime.Enabled := Connected;
EndTime.Enabled := Connected;
Button5.Enabled := Connected;
Button6.Enabled := Connected;
Button7.Enabled := Connected;
btRemove.Enabled := Connected;
Button1.Enabled := not Connected;
end;
procedure TForm1.ToggleEditControls(Enabled: boolean);
begin
Edit3.Enabled := Enabled;
Edit4.Enabled := Enabled;
Edit5.Enabled := Enabled;
cbVisibility.Enabled := Enabled;
cbAllday.Enabled := Enabled;
StartDate.Enabled := Enabled;
EndDate.Enabled := Enabled;
StartTime.Enabled := Enabled;
EndTime.Enabled := Enabled;
Button5.Enabled := Enabled;
Button6.Enabled := Enabled;
Button7.Enabled := Enabled;
end;
function TForm1.ValidateForm: boolean;
begin
Result := true;
if Edit3.Text = '' then
begin
ShowMessage('Name field cannot be empty');
Edit3.SetFocus;
Result := false;
end
else if Edit4.Text = '' then
begin
ShowMessage('Description field cannot be empty');
Edit4.SetFocus;
Result := false;
end;
end;
end.
|
unit romannumclock;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
OpenVG, {Include the OpenVG unit so we can use the various types and structures}
VGShapes, {Include the VGShapes unit to give us access to all the functions}
VC4;
var
Fontsize:Integer;
Width:Integer; {A few variables used by our shapes example}
Height:Integer;
procedure clock(gpstime:string; x,y,r:LongWord) ;
implementation
procedure clock(gpstime:string; x,y,r:LongWord );
var
Ticks:Integer;
PosNum:VGfloat;
PosT1:VGfloat;
PosT2:VGfloat;
Dial:VGfloat;
Dialsec:VGfloat;
Gpsint, code: Integer;
Hours:Integer;
Minutes:Integer;
Seconds:Integer;
begin
val(gpstime, Gpsint, code );
Hours := Gpsint div 10000;
Minutes := Gpsint mod 10000 div 100;
Seconds := Gpsint mod 100;
VGShapesTranslate(x,y);
PosT1:= r / 2 * 0.95;
PosT2:= r / 2 * 0.90;
PosNum:= r / 2 * 0.72;
Dial:= r * 1.0;
Dialsec:= r * 0.3;
VGShapesStrokeWidth(Dial / 30);
VGShapesStroke(181,166,66,1);
VGShapesFill(255,255,200,1);
VGShapesCircle(0,0, Dial);
VGShapesStrokeWidth(Dial * 0.005);
VGShapesStroke(0,0,0,1);
VGShapesFill(255,255,200,1);
VGShapesCircle(0,0,2 * PosT1);
VGShapesStrokeWidth(Dial * 0.005);
VGShapesStroke(0,0,0,1);
VGShapesFill(255,255,200,1);
VGShapesCircle(0,0,2 * PosT2);
//Fontsize:= 12;
//VGShapesFill(0,0,0,1);
//VGShapesTextMid(0,80,IntToStr(Hours),VGShapesSerifTypeface,Fontsize);
//VGShapesTextMid(0,60,IntToStr(Minutes),VGShapesSerifTypeface,Fontsize);
//VGShapesTextMid(0,40,IntToStr(Seconds),VGShapesSerifTypeface,Fontsize);
Fontsize:=Trunc(Dial * 0.08);
VGShapesFill(0,0,0,1);
VGShapesTextMid(0,PosNum,'XII',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum,'I',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum,'II',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum,'III',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum,'IIII',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum,'V',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum,'VI',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum,'VII',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum,'VII',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum, 'IX',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum, 'X',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesTextMid(0,PosNum, 'XI',VGShapesSerifTypeface,Fontsize);
VGShapesRotate(-30);
VGShapesStroke(0,0,0,1);
VGShapesFill(0,0,0,1);
VGShapesCircle(0,0,Dial * 0.08);
VGShapesRotate(Hours * -30);
VGShapesStrokeWidth(Dial * 0.025);
VGShapesLine(0,0, 0,PosNum);
VGShapesRotate(Hours * 30);
VGShapesRotate(Minutes * -6);
VGShapesStrokeWidth(Dial * 0.01);
VGShapesLine(0,0, 0,PosT2);
VGShapesRotate(Minutes * 6);
for Ticks := 0 to 59 do
Begin
if Ticks mod 5 = 0 then
VGShapesStrokeWidth(Dial * 0.025)
else
VGShapesStrokeWidth(Dial * 0.005);
VGShapesLine(0,PosT1, 0,PosT2);
VGShapesRotate(-6);
end;
VGShapesTranslate(0,-Dialsec * 0.8);
VGShapesStrokeWidth(Dialsec * 0.02);
VGShapesStroke(0,0,0,1);
VGShapesFill(255,255,200,1);
VGShapesCircle(0,0,Dialsec);
for Ticks := 0 to 59 do
Begin
if Ticks mod 5 = 0 then
VGShapesStrokeWidth(Dialsec * 0.03)
else
VGShapesStrokeWidth(Dialsec * 0.01);
VGShapesLine(0,Dialsec / 2 * 0.9, 0,Dialsec / 2);
VGShapesRotate(-6);
end;
VGShapesStroke(0,0,0,1);
VGShapesFill(0,0,0,1);
VGShapesCircle(0,0,Dialsec * 0.08);
VGShapesRotate(Seconds * -6);
VGShapesStrokeWidth(Dialsec * 0.02);
VGShapesLine(0,0, 0,Dialsec / 2 * 0.9);
VGShapesRotate(Seconds * 6);
//return to center
VGShapesTranslate(0,Dialsec * 0.8);
//draw hour minute hands over second dial
VGShapesStroke(0,0,0,1);
VGShapesFill(0,0,0,1);
VGShapesCircle(0,0,Dial * 0.08);
VGShapesRotate(Hours * -30);
VGShapesStrokeWidth(Dial * 0.025);
VGShapesLine(0,0, 0,PosNum);
VGShapesRotate(Hours * 30);
VGShapesRotate(Minutes * -6);
VGShapesStrokeWidth(Dial * 0.01);
VGShapesLine(0,0, 0,PosT2);
VGShapesRotate(Minutes * 6);
//reset back ot zero position
VGShapesTranslate(-x,-y);
end;
end.
|
unit Affixes;
interface
uses
// Delphi units
SysUtils, Classes, IniFiles,
// own units
uVars, UConfig;
type
{TODO: Add page for editing Affixes in HODBE}
{DONE: Kill AdvItem, replace its job to AffixConfig}
NAffixParam = (apID, apType, apName0, apName1, apName2, apName3, apBonus0,
apBonus1, apGroup, apLevel, apPrice);
NAffixType = (atSuffix, atPrefix);
TAffixConfig = class(TConfig)
private
function GetIntValue(Index: Integer; Param: NAffixParam): Integer;
procedure SetIntValue(Index: Integer; Param: NAffixParam;
const Value: Integer);
protected
function GetItem(Index: Integer; Param: NAffixParam): string;
procedure SetItem(Index: Integer; Param: NAffixParam; const Value: string);
function GetWItem(Index, Param: Integer): string; override;
procedure SetWItem(Index, Param: Integer; const Value: string); override;
function GetParamCnt: Integer; override;
function GetParamName(Param: Integer): string; override;
function BuidAffixParam(Param: string; Idx: Integer): NAffixParam;
public
property Items[Index: Integer; Param: NAffixParam]: string read GetItem write
SetItem;
property IntValues[Index: Integer; Param: NAffixParam]: Integer read GetIntValue write
SetIntValue;
function IDString(Index: Integer; Param: NAffixParam): string;
function GenAffix(AType: NAffixType; Level: Integer = -1;
Group: Integer = -1): Integer;
function AffixCountByType(AType: NAffixType): Integer;
function Bonus(AffIdx, BonusIdx: Integer; var Target: string; var Value: Integer): Boolean;
function Name(AffIdx: Integer; Gender: Integer): string;
end;
const
DefaultTextSection = 'Default';
Delim = '|';
AffixParamColWidths: array[NAffixParam] of Integer =
(20, 60, 90, 90, 90, 90, 90, 90, 20, 20, 20);
AffixParamColCount = Ord(High(NAffixParam)) + 1;
AffixParamType: array[NAffixParam] of NParamType = (npInteger, npList, npString,
npString, npString, npString, npString, npString, npInteger, npInteger, npInteger);
function AffixConfig(): TAffixConfig;
function BonusCount: Integer;
var
AffixParamNames: array[NAffixParam] of string;
implementation
uses
// Delphi units
TypInfo,
// Own units
uBox, uStrUtils, uUtils;
var
TheAffixConfig: TAffixConfig;
AffixParamEnumPtr: Pointer;
function AffixConfig(): TAffixConfig;
begin
Result := TheAffixConfig;
end;
function BonusCount: Integer;
var
ap: NAffixParam;
begin
Result := 0;
for ap := Low(NAffixParam) to High(NAffixParam) do
Inc(Result, Ord(Pos('Bonus', EnumText(AffixParamEnumPtr, Ord(ap), 0)) > 0));
end;
{ TAffixConfig }
function TAffixConfig.AffixCountByType(AType: NAffixType): Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to Count - 1 do
Inc(Result, Ord(Items[i, apType] = EnumText(AffixParamEnumPtr, Ord(AType), 0)));
end;
function TAffixConfig.Bonus(AffIdx, BonusIdx: Integer; var Target: string;
var Value: Integer): Boolean;
var
SR: TSplitResult;
ABonus: string;
begin
Target := '';
Value := 0;
ABonus := Items[AffIdx, BuidAffixParam('apBonus', BonusIdx)];
Result := ABonus <> '';
if not Result then
Exit;
SR := Explode(',', ABonus);
Target := SR[0];
Value := StrToInt(SR[1]);
end;
function TAffixConfig.BuidAffixParam(Param: string; Idx: Integer): NAffixParam;
begin
Result := NAffixParam(GetEnumValue(AffixParamEnumPtr, Param + IntToStr(Idx)));
end;
function TAffixConfig.GenAffix(AType: NAffixType; Level: Integer = -1;
Group: Integer = -1): Integer;
var
i, Cnt: Integer;
ptr: Pointer;
arr: array[0..511] of Integer;
begin
Result := 0;
Cnt := 0;
ptr := TypeInfo(NAffixType);
for i := 0 to Count - 1 do
if (Items[i, apType] = EnumText(ptr, Ord(AType), 0)) and
((Level = -1) or (IntValues[i, apLevel] = Level)) and
((Group = -1) or (IntValues[i, apGroup] = Group))
then
arr[PostInc(Cnt)] := IntValues[i, apID];
if Cnt = 0 then
Result := 0
else
Result := arr[Random(Cnt)];
end;
function TAffixConfig.GetIntValue(Index: Integer; Param: NAffixParam): Integer;
begin
Result := StrToIntDef(Items[Index, Param], 0);
end;
function TAffixConfig.GetItem(Index: Integer; Param: NAffixParam): string;
begin
if Param = apID then
Result := IntToStr(Index)
else
Result := FWrapper.ReadString(IDString(Index, Param));
end;
function TAffixConfig.GetParamCnt: Integer;
begin
Result := AffixParamColCount;
end;
function TAffixConfig.GetParamName(Param: Integer): string;
begin
Result := AffixParamNames[NAffixParam(Param)];
end;
function TAffixConfig.GetWItem(Index, Param: Integer): string;
begin
Result := Items[Index, NAffixParam(Param)];
end;
function TAffixConfig.IDString(Index: Integer; Param: NAffixParam): string;
begin
Result := Format('%d%s%s', [Index, FWrapper.Delim, AffixParamNames[Param]]);
end;
function TAffixConfig.Name(AffIdx, Gender: Integer): string;
begin
Result := Items[AffIdx, BuidAffixParam('apName', Gender)];
end;
procedure TAffixConfig.SetIntValue(Index: Integer; Param: NAffixParam;
const Value: Integer);
begin
Items[Index, Param] := IntToStr(Value);
end;
procedure TAffixConfig.SetItem(Index: Integer; Param: NAffixParam;
const Value: string);
begin
if Param <> apID then
FWrapper.WriteString(IDString(Index, Param), Value);
end;
procedure TAffixConfig.SetWItem(Index, Param: Integer; const Value: string);
begin
Items[Index, NAffixParam(Param)] := Value;
end;
var
I: NAffixParam;
initialization
AffixParamEnumPtr := TypeInfo(NAffixType);
TheAffixConfig := TAffixConfig.Create(TIniWrapper);
TheAffixConfig.LoadFromFile(Path + 'data\Affixes.ini');
for i := Low(NAffixParam) to High(NAffixParam) do
AffixParamNames[i] := EnumText(TypeInfo(NAffixParam), Ord(i));
finalization
FreeAndNil(TheAffixConfig);
end.
|
unit daemonmapper;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, DaemonApp;
type
{ TDaemonMapper1 }
TDaemonMapper1 = class(TDaemonMapper)
private
{ private declarations }
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
procedure ToDoOnInstall(Sender: TObject);
procedure ToDoOnRun(Sender: TObject);
procedure ToDoOnUninstall(Sender: TObject);
procedure ToDoOnDestroy(Sender: TObject);
end;
var
DaemonMapper1: TDaemonMapper1;
implementation
uses
settings{, logging};
{$R *.lfm}
constructor TDaemonMapper1.Create(AOwner: TComponent);
begin
SaveLog.Log(etInfo, 'DaemonMapper.Create');
inherited Create(AOwner);
with DaemonDefs.Add as TDaemonDef do
begin
DaemonClassName := 'TDaemon1';
Name := DaemonName;
Description := DaemonDescription;
DisplayName := Name;
RunArguments := '--run';
Options := [doAllowStop,doAllowPause];
Enabled := true;
with WinBindings do
begin
StartType := stBoot;
WaitHint := 0;
IDTag := 0;
ServiceType := stWin32;
ErrorSeverity := esNormal;//esIgnore;
end;
// OnCreateInstance := ?;
LogStatusReport := false;
end;
OnInstall := @Self.ToDoOnInstall;
OnRun := @Self.ToDoOnRun;
OnUnInstall := @Self.ToDoOnUninstall;
OnDestroy := @Self.ToDoOnDestroy;
SaveLog.Log(etInfo, 'DaemonMapper.Createted');
end;
procedure TDaemonMapper1.ToDoOnInstall(Sender: TObject);
begin
SaveLog.Log(etInfo, 'DaemonMapper.Install');
end;
procedure TDaemonMapper1.ToDoOnRun(Sender: TObject);
begin
SaveLog.Log(etInfo, 'DaemonMapper.Run');
end;
procedure TDaemonMapper1.ToDoOnUnInstall(Sender: TObject);
begin
SaveLog.Log(etInfo, 'DaemonMapper.Uninstall');
end;
procedure TDaemonMapper1.ToDoOnDestroy(Sender: TObject);
begin
//doesn't comes here
SaveLog.Log(etInfo, 'DaemonMapper.Destroy');
end;
initialization
RegisterDaemonMapper(TDaemonMapper1)
end.
|
unit MdiChilds.SplitDocByChapters;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.StdCtrls, Vcl.ExtCtrls,
MDIChilds.ProgressForm, GsDocument, ActionHandler;
type
TFmSplitDocsByChapter = class(TFmProcess)
lbFiles: TListBox;
JvDragDrop: TJvDragDrop;
procedure JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings);
private
{ Private declarations }
public
procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override;
procedure ExecuteDocument(AFileName: string);
end;
TSplitDocsByChapterActionHanler = class (TAbstractActionHandler)
public
procedure ExecuteAction(UserData: Pointer = nil); override;
end;
var
FmSplitDocsByChapter: TFmSplitDocsByChapter;
implementation
{$R *.dfm}
procedure TFmSplitDocsByChapter.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean);
var
I: Integer;
begin
ShowMessage := True;
ProgressForm.InitPB(lbFiles.Count);
ProgressForm.Show;
for I := 0 to lbFiles.Count - 1 do
begin
if not ProgressForm.InProcess then
Exit;
ProgressForm.StepIt(lbFiles.Items[I]);
ExecuteDocument(lbFiles.Items[I]);
end;
end;
procedure TFmSplitDocsByChapter.ExecuteDocument(AFileName: string);
var
Doc: TGsDocument;
I: Integer;
NewDoc: TGsDocument;
Chapter: TGsChapter;
begin
Doc := TGsDocument.Create;
try
Doc.LoadFromFile(AFileName);
for I := 0 to Doc.Chapters.Count - 1 do
begin
if Doc.Chapters.Items[I] is TGsChapter then
begin
NewDoc := TGsDocument.Create;
try
NewDoc.DocumentType := Doc.DocumentType;
NewDoc.BaseDataType := Doc.BaseDataType;
NewDoc.TypeName := Doc.TypeName;
NewDoc.Number := Doc.Number;
NewDoc.Title := Doc.Title;
Chapter := TGsChapter.Create(NewDoc);
Chapter.Assign(Doc.Chapters.Items[I]);
NewDoc.Chapters.Add(Chapter);
NewDoc.SaveToFile(ChangeFileExt(AFileName, '_' + IntToStr(I + 1) + '.xml'));
finally
NewDoc.Free;
end;
end;
end;
finally
Doc.Free;
end;
end;
procedure TFmSplitDocsByChapter.JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings);
begin
lbFiles.Items.Assign(Value);
end;
{ TSplitDocsByChapterActionHanler }
procedure TSplitDocsByChapterActionHanler.ExecuteAction(UserData: Pointer);
begin
TFmSplitDocsByChapter.Create(Application).Show;
end;
begin
ActionHandlerManager.RegisterActionHandler('Разбить документ по разделам', hkDefault, TSplitDocsByChapterActionHanler);
end.
|
////////////////////////////////////////////////////////////////////////////////
// MTBD2XXUnit.pas
// MTB communication library
// Interface to FTDI library
// (c) Petr Travnik (petr.travnik@kmz-brno.cz),
// Jan Horacek (jan.horacek@kmz-brno.cz),
// Michal Petrilak (engineercz@gmail.com)
////////////////////////////////////////////////////////////////////////////////
{
LICENSE:
Copyright 2015 Petr Travnik, Michal Petrilak, Jan Horacek
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.
}
{
DESCRIPTION:
This unit is basically just an interface to FTDI ftd2xx.dll communication
library. MTBusb.pas calls functions in this file to communicate with MTB-USB
module.
Installation of ftd2xx.dll (drivers from FTDI generally) is needed.
See http://www.ftdichip.com/Drivers/D2XX.htm .
}
unit MTBD2XXUnit;
interface
Uses Windows, Forms, Dialogs, SysUtils;
Type
FT_Result = Integer;
EFtGeneral = class(Exception);
EFtInvalidHandle = class(EFtGeneral);
EFtDeviceNotFound = class(EFtGeneral);
EFtDeviceNotOpened = class(EFtGeneral);
EFtIoError = class(EFtGeneral);
EFtInsufficientResources = class(EFtGeneral);
EFtInvalidParameter = class(EFtGeneral);
// Exported Functions
Function GetFTDeviceCount : FT_Result;
Function GetFTDeviceDescription( DeviceIndex : DWord ) : FT_Result;
Function GetFTDeviceSerialNo( DeviceIndex : DWord ) : FT_Result;
Function Open_USB_Device : FT_Result;
Function Close_USB_Device : FT_Result;
Function Write_USB_Device_Buffer( Write_Count : Integer ) : Integer;
Function Read_USB_Device_Buffer( Read_Count : Integer ) : Integer;
Function Reset_USB_Device : FT_Result;
Function Purge_USB_Device_Out : FT_Result;
Function Purge_USB_Device_In : FT_Result;
Function Set_USB_Device_RTS : FT_Result;
Function Clr_USB_Device_RTS : FT_Result;
Function Set_USB_Device_DTR : FT_Result;
Function Clr_USB_Device_DTR : FT_Result;
Function Set_USB_Device_BaudRate : FT_Result;
Function Set_USB_Device_DataCharacteristics : FT_Result;
Function Set_USB_Device_FlowControl : FT_Result;
Function Get_USB_Device_ModemStatus : FT_Result;
Function Set_USB_Device_Chars : FT_Result;
Function Set_USB_Device_TimeOuts(ReadTimeOut,WriteTimeOut:DWord) : FT_Result;
Function Get_USB_Device_QueueStatus : FT_Result;
Function Open_USB_Device_By_Serial_Number( Serial_Number : string ) : FT_Result;
Function Open_USB_Device_By_Device_Description( Device_Description : string ) : FT_Result;
Var
// Port Handle Returned by the Open Function
// Used by the Subsequent Function Calls
FT_HANDLE : DWord = 0;
// Used to handle multiple device instances in future
// versions. Must be set to 0 for now.
PV_Device : DWord = 0;
// Holding Variables for the current settings
// Can be configured visually using the CFGUnit Unit
// or manually before calling SetUp_USB_Device
FT_Current_Baud : Dword;
FT_Current_DataBits : Byte;
FT_Current_StopBits : Byte;
FT_Current_Parity : Byte;
FT_Current_FlowControl : Word;
FT_RTS_On : Boolean;
FT_DTR_On : Boolean;
FT_Event_On : Boolean;
FT_Error_On : Boolean;
FT_XON_Value : Byte = $11;
FT_XOFF_Value : Byte = $13;
FT_EVENT_Value : Byte = $0;
FT_ERROR_Value : Byte = $0;
// Used by CFGUnit to flag a bad value
FT_SetupError : Boolean;
// Used to Return the current Modem Status
FT_Modem_Status : DWord;
// Used to return the number of bytes pending
// in the Rx Buffer Queue
FT_Q_Bytes : DWord;
Const
// FT_Result Values
FT_OK = 0;
FT_INVALID_HANDLE = 1;
FT_DEVICE_NOT_FOUND = 2;
FT_DEVICE_NOT_OPENED = 3;
FT_IO_ERROR = 4;
FT_INSUFFICIENT_RESOURCES = 5;
FT_INVALID_PARAMETER = 6;
FT_SUCCESS = FT_OK;
// FT_Open_Ex Flags
FT_OPEN_BY_SERIAL_NUMBER = 1;
FT_OPEN_BY_DESCRIPTION = 2;
// FT_List_Devices Flags
FT_LIST_NUMBER_ONLY = $80000000;
FT_LIST_BY_INDEX = $40000000;
FT_LIST_ALL = $20000000;
// Baud Rate Selection
FT_BAUD_300 = 300;
FT_BAUD_600 = 600;
FT_BAUD_1200 = 1200;
FT_BAUD_2400 = 2400;
FT_BAUD_4800 = 4800;
FT_BAUD_9600 = 9600;
FT_BAUD_14400 = 14400;
FT_BAUD_19200 = 19200;
FT_BAUD_38400 = 38400;
FT_BAUD_57600 = 57600;
FT_BAUD_115200 = 115200;
FT_BAUD_230400 = 230400;
FT_BAUD_460800 = 460800;
FT_BAUD_921600 = 921600;
// Data Bits Selection
FT_DATA_BITS_7 = 7;
FT_DATA_BITS_8 = 8;
// Stop Bits Selection
FT_STOP_BITS_1 = 0;
FT_STOP_BITS_2 = 2;
// Parity Selection
FT_PARITY_NONE = 0;
FT_PARITY_ODD = 1;
FT_PARITY_EVEN = 2;
FT_PARITY_MARK = 3;
FT_PARITY_SPACE = 4;
// Flow Control Selection
FT_FLOW_NONE = $0000;
FT_FLOW_RTS_CTS = $0100;
FT_FLOW_DTR_DSR = $0200;
FT_FLOW_XON_XOFF = $0400;
// Purge Commands
FT_PURGE_RX = 1;
FT_PURGE_TX = 2;
// IO Buffer Sizes
FT_In_Buffer_Size = $8000; // 32k
FT_In_Buffer_Index = FT_In_Buffer_Size - 1;
FT_Out_Buffer_Size = $8000; // 32k
FT_Out_Buffer_Index = FT_Out_Buffer_Size - 1;
// DLL Name
FT_DLL_Name = 'ftd2xx.dll';
var
// Declare Input and Output Buffers
FT_In_Buffer : Array[0..FT_In_Buffer_Index] of byte;
FT_Out_Buffer : Array[0..FT_Out_Buffer_Index] of byte;
// A variable used to detect time-outs
// Attach a timer to the main project form
// which decrements this every 10mS if
// FT_TimeOut_Count <> 0
FT_TimeOut_Count : Integer = 0;
// Used to determine how many bytes were
// actually received by FT_Read_Device_All
// in the case of a time-out
FT_All_Bytes_Received : Integer = 0;
FT_IO_Status : Ft_Result = FT_OK;
// Used By FT_ListDevices
FT_Device_Count : DWord;
FT_Device_String_Buffer : Array [1..50] of byte;
FT_Device_String : String;
implementation
function FT_Open(PVDevice:Integer; ftHandle:Pointer ) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_Open';
function FT_Close(ftHandle:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_Close';
function FT_Read(ftHandle:Dword; FTInBuf : Pointer; BufferSize : LongInt; ResultPtr : Pointer ) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_Read';
function FT_Write(ftHandle:Dword; FTOutBuf : Pointer; BufferSize : LongInt; ResultPtr : Pointer ) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_Write';
function FT_SetBaudRate(ftHandle:Dword;BaudRate:DWord) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_SetBaudRate';
function FT_SetDataCharacteristics(ftHandle:Dword;WordLength,StopBits,Parity:Byte) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_SetDataCharacteristics';
function FT_SetFlowControl(ftHandle:Dword;FlowControl:Word;XonChar,XoffChar:Byte) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_SetFlowControl';
function FT_ResetDevice(ftHandle:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_ResetDevice';
function FT_SetDtr(ftHandle:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_SetDtr';
function FT_ClrDtr(ftHandle:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_ClrDtr';
function FT_SetRts(ftHandle:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_SetRts';
function FT_ClrRts(ftHandle:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_ClrRts';
function FT_GetModemStatus(ftHandle:Dword;ModemStatus:Pointer) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_GetModemStatus';
function FT_SetChars(ftHandle:Dword;EventChar,EventCharEnabled,ErrorChar,ErrorCharEnabled : Byte) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_SetChars';
function FT_Purge(ftHandle:Dword;Mask:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_Purge';
function FT_SetTimeouts(ftHandle:Dword;ReadTimeout,WriteTimeout:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_SetTimeouts';
function FT_GetQueueStatus(ftHandle:Dword;RxBytes:Pointer) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_GetQueueStatus';
function FT_GetNumDevices(pvArg1:Pointer;pvArg2:Pointer;dwFlags:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_ListDevices';
function FT_ListDevices(pvArg1:Dword;pvArg2:Pointer;dwFlags:Dword) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_ListDevices';
function FT_OpenEx(pvArg1:Pointer;dwFlags:Dword;ftHandle:Pointer) : FT_Result ; stdcall ; External FT_DLL_Name name 'FT_OpenEx';
Function FT_Error_To_Exception(E:FT_Result):EFtGeneral;
Begin
Case (E) of
FT_INVALID_HANDLE : Result := EFtInvalidHandle.Create('Invalid handle!');
FT_DEVICE_NOT_FOUND : Result := EFtDeviceNotFound.Create('Device not found!');
FT_DEVICE_NOT_OPENED : Result := EFtDeviceNotOpened.Create('Device not opened!');
FT_IO_ERROR : Result := EFtIoError.Create('General IO error!');
FT_INSUFFICIENT_RESOURCES : Result := EFtInsufficientResources.Create('Insufficient resources!');
FT_INVALID_PARAMETER : Result := EFtInvalidParameter.Create('Invalid parameter!');
else
Result := EFtGeneral.Create('EFtGeneral!');
End;
End;
Function GetDeviceString : String;
Var I : Integer;
Begin
Result := ''; I := 1;
FT_Device_String_Buffer[50] := 0; // Just in case !
While FT_Device_String_Buffer[I] <> 0 do
Begin
Result := Result + chr(FT_Device_String_Buffer[I]);
Inc(I);
End;
End;
Procedure SetDeviceString ( S : String );
Var I,L : Integer;
Begin
FT_Device_String_Buffer[1] := 0;
L := Length(S); If L > 49 then L := 49;
If L = 0 then Exit;
For I := 1 to L do FT_Device_String_Buffer[I] := ord(S[I]);
FT_Device_String_Buffer[L+1] := 0;
End;
Function GetFTDeviceCount : FT_Result;
Begin
Result := FT_GetNumDevices(@FT_Device_Count,Nil,FT_LIST_NUMBER_ONLY);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function GetFTDeviceSerialNo( DeviceIndex : DWord ) : FT_Result;
Begin
Result := FT_ListDevices(DeviceIndex,@FT_Device_String_Buffer,(FT_OPEN_BY_SERIAL_NUMBER or FT_LIST_BY_INDEX));
If Result = FT_OK then FT_Device_String := GetDeviceString
else raise FT_Error_To_Exception(Result);
End;
Function GetFTDeviceDescription( DeviceIndex : DWord ) : FT_Result;
Begin
Result := FT_ListDevices(DeviceIndex,@FT_Device_String_Buffer,(FT_OPEN_BY_DESCRIPTION or FT_LIST_BY_INDEX));
If Result = FT_OK then FT_Device_String := GetDeviceString;
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Open_USB_Device : FT_Result;
Begin
Result := FT_Open(PV_Device,@FT_Handle);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Open_USB_Device_By_Serial_Number( Serial_Number : string ) : FT_Result;
Begin
SetDeviceString(Serial_Number);
Result := FT_OpenEx(@FT_Device_String_Buffer,FT_OPEN_BY_SERIAL_NUMBER,@FT_Handle);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Open_USB_Device_By_Device_Description( Device_Description : string ) : FT_Result;
Begin
SetDeviceString(Device_Description);
Result := FT_OpenEx(@FT_Device_String_Buffer,FT_OPEN_BY_DESCRIPTION,@FT_Handle);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Close_USB_Device : FT_Result;
Begin
Result := FT_Close(FT_Handle);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Reset_USB_Device : FT_Result;
Begin
Result := FT_ResetDevice(FT_Handle);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Purge_USB_Device_Out : FT_Result;
Begin
Result := FT_Purge(FT_Handle,FT_PURGE_TX);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Purge_USB_Device_In : FT_Result;
Begin
Result := FT_Purge(FT_Handle,FT_PURGE_RX);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Set_USB_Device_RTS : FT_Result;
Begin
Result := FT_SetRTS(FT_Handle);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Clr_USB_Device_RTS : FT_Result;
Begin
Result := FT_ClrRTS(FT_Handle);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Set_USB_Device_DTR : FT_Result;
Begin
Result := FT_SetDTR(FT_Handle);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Clr_USB_Device_DTR : FT_Result;
Begin
Result := FT_ClrDTR(FT_Handle);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Set_USB_Device_BaudRate : FT_Result;
Begin
Result := FT_SetBaudRate(FT_Handle,FT_Current_Baud);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Set_USB_Device_DataCharacteristics : FT_Result;
Begin
Result := FT_SetDataCharacteristics(FT_Handle,FT_Current_DataBits,FT_Current_StopBits,FT_Current_Parity);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Set_USB_Device_FlowControl : FT_Result;
Begin
Result := FT_SetFlowControl(FT_Handle,FT_Current_FlowControl,FT_XON_Value,FT_XOFF_Value);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Get_USB_Device_ModemStatus : FT_Result;
Begin
Result := FT_GetModemStatus(FT_Handle,@FT_Modem_Status);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Set_USB_Device_Chars : FT_Result;
Var Events_On,Errors_On : Byte;
Begin
If FT_Event_On then Events_On := 1 else Events_On := 0;
If FT_Error_On then Errors_On := 1 else Errors_On := 0;
Result := FT_SetChars(FT_Handle,FT_EVENT_Value,Events_On,FT_ERROR_Value,Errors_On);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Set_USB_Device_TimeOuts(ReadTimeOut,WriteTimeOut:DWord) : FT_Result;
Begin
Result := FT_SetTimeouts(FT_Handle,ReadTimeout,WriteTimeout);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
Function Get_USB_Device_QueueStatus : FT_Result;
Begin
Result := FT_GetQueueStatus(FT_Handle,@FT_Q_Bytes);
If Result <> FT_OK then raise FT_Error_To_Exception(Result);
End;
function Write_USB_Device_Buffer( Write_Count : Integer ) : Integer;
// Writes Write_Count Bytes from FT_Out_Buffer to the USB device
// Function returns the number of bytes actually sent
// In this example, Write_Count should be 32k bytes max
Var Write_Result : Integer;
Begin
FT_IO_Status := FT_Write(FT_Handle,@FT_Out_Buffer,Write_Count,@Write_Result);
Result := Write_Result;
If FT_IO_Status <> FT_OK then raise FT_Error_To_Exception(Result);
End;
function Read_USB_Device_Buffer( Read_Count : Integer ) : Integer;
// Reads Read_Count Bytes ( or less ) from the USB device to the FT_In_Buffer
// Function returns the number of bytes actually received which may range from zero
// to the actual number of bytes requested, depending on how many have been received
// at the time of the request + the read timeout value.
Var Read_Result : Integer;
Begin
FT_IO_Status := FT_Read(FT_Handle,@FT_In_Buffer,Read_Count,@Read_Result);
Result := Read_Result;
If FT_IO_Status <> FT_OK then raise FT_Error_To_Exception(Result);
End;
end.
|
unit Service.Campanha;
interface
uses
System.SysUtils, System.Classes, Service.Module, 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,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,System.JSON,
System.Generics.Collections;
type
TServiceCampanha = class(TServiceModule)
private
{ Private declarations }
public
{ Public declarations }
function List(AFilter : TDictionary<String,String>): TDataset; // Retrieves all items from Produto Table
function GetByID(ID : Integer): TDataset; //Does as the name says
function Insert(JSON : TJSONObject) : Boolean;
function Update(JSON : TJSONObject) : Boolean;
function Delete : Boolean;
end;
implementation
uses Dataset.Serialize;
{$R *.dfm}
{ TServiceCampanha }
function TServiceCampanha.Delete: Boolean;
begin
qUpdate.Delete;
Result := qUpdate.ApplyUpdates(0) = 0;
end;
function TServiceCampanha.GetByID(ID: Integer): TDataset;
begin
Result:= qUpdate;
qUpdate.SQL.Add('WHERE idcampanha = :ID');
qUpdate.ParamByName('ID').AsInteger := ID;
qUpdate.Open;
end;
function TServiceCampanha.Insert(JSON: TJSONObject): Boolean;
begin
qUpdate.SQL.Add('WHERE 1<>1');
qUpdate.Open;
qUpdate.LoadFromJSON(JSON, False);
Result := qUpdate.ApplyUpdates(0) = 0;
end;
function TServiceCampanha.List(AFilter : TDictionary<String,String>): TDataset;
var
I: Integer;
begin
Result:= Query;
if(Assigned(AFilter)) then
begin
if AFilter.ContainsKey('limit') then begin
Query.FetchOptions.RecsMax := AFilter.Items['limit'].ToInt64;
end;
if AFilter.ContainsKey('offset') then begin
Query.FetchOptions.RecsSkip := AFilter.Items['offset'].ToInt64;
end;
for I := 0 to Query.ParamCount - 1 do begin
if (AFilter.ContainsKey(Query.Params[I].Name.ToLower)) then begin
Query.Params[I].AsString := AFilter.Items[Query.Params[I].Name.ToLower];
end;
end;
end;
Query.Open;
end;
function TServiceCampanha.Update(JSON: TJSONObject): Boolean;
begin
qUpdate.Open;
qUpdate.MergeFromJSONObject(JSON,False);
Result := qUpdate.ApplyUpdates(0) = 0;
end;
end.
|
unit MainForm;
interface
{$DEFINE DEMO_MODE}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, CheckLst, Spin, ExtCtrls, Grids,
uBehaviorInterfaces, uProjectData, uDataDisplay;
type
TfrmTeamCityMonitor = class(TForm)
pnlTop: TPanel;
edUrl: TEdit;
btnScan: TButton;
lblurl: TLabel;
sePort: TSpinEdit;
lblPort: TLabel;
pnlLeft: TPanel;
chklbScan: TCheckListBox;
StringGrid: TStringGrid;
Timer: TTimer;
pnlMonitorBtn: TPanel;
btnMonitor: TButton;
Splitter: TSplitter;
procedure btnScanClick(Sender: TObject);
procedure btnMonitorClick(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure chklbScanClickCheck(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SplitterMoved(Sender: TObject);
private
FProjectData: TProjectData;
FProjectDataDisplay : TSelectedProjectsDisplay;
procedure CleanUpAssignedObjects;
public
{ Public declarations }
end;
var
frmTeamCityMonitor : TfrmTeamCityMonitor;
implementation
uses
uProjectConstants;
{$R *.dfm}
procedure TfrmTeamCityMonitor.btnScanClick(Sender: TObject);
begin
CleanUpAssignedObjects;
FProjectData := TProjectData.Create(nil);
FProjectDataDisplay := TSelectedProjectsDisplay.Create(FProjectData);
with FProjectData do
begin
FCheckLBItems := chklbScan.Items;
{$IFDEF DEMO_MODE}
LoadDataFromInputXML;
{$ELSE}
HTTPURL := Format(rsProjects, [edUrl.Text, sePort.Value]);
LoadDataViaHTTP;
{$ENDIF}
SetProjectInformation;
end;
end;
procedure TfrmTeamCityMonitor.btnMonitorClick(Sender: TObject);
begin
TimerTimer(Sender);
Timer.Enabled := True;
end;
procedure TfrmTeamCityMonitor.TimerTimer(Sender: TObject);
begin
with FProjectDataDisplay do
begin
InitializeDisplayGrid;
DisplayData;
end;
end;
procedure TfrmTeamCityMonitor.FormCreate(Sender: TObject);
begin
inherited;
Timer.Interval := TIMER_INTERVAL;
pnlLeft.Constraints.MaxWidth := ClientWidth div 2;
end;
procedure TfrmTeamCityMonitor.chklbScanClickCheck(Sender: TObject);
begin
FProjectDataDisplay.DoOnProjectItemChange(chklbScan.Items.Strings[chklbScan.ItemIndex]);
end;
procedure TfrmTeamCityMonitor.FormDestroy(Sender: TObject);
begin
if Assigned(FProjectDataDisplay) then
FreeAndNil(FProjectDataDisplay);
inherited;
end;
procedure TfrmTeamCityMonitor.SplitterMoved(Sender: TObject);
begin
btnMonitor.Width := Splitter.Left-1;
end;
procedure TfrmTeamCityMonitor.CleanUpAssignedObjects;
begin
if Assigned(FProjectDataDisplay) then
FreeAndNil(FProjectDataDisplay);
if Assigned(FProjectData) then
FProjectData := nil;
end;
end.
|
unit DW.VOIP;
{*******************************************************}
{ }
{ Kastri }
{ }
{ Delphi Worlds Cross-Platform Library }
{ }
{ Copyright 2020-2021 Dave Nottage under MIT license }
{ which is located in the root folder of this library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// FMX
FMX.Graphics,
// DW
DW.PushKit;
type
TVOIPCallState = (Unknown, IncomingCall, OutgoingCall, CallAnswered, CallDeclined, CallDisconnected);
TVOIPCallInfo = record
DisplayName: string;
Ident: string;
end;
TVOIP = class;
TCustomPlatformVOIP = class(TObject)
private
FIcon: TBitmap;
FPushKit: TPushKit;
FVOIP: TVOIP;
procedure PushKitMessageReceivedHandler(Sender: TObject; const AJSON: string);
procedure PushKitTokenReceivedHandler(Sender: TObject; const AToken: string; const AIsNew: Boolean);
procedure SetIcon(const Value: TBitmap);
protected
procedure DoVOIPCallState(const ACallState: TVOIPCallState; const AIdent: string);
procedure IconUpdated; virtual;
procedure PushKitMessageReceived(const AJSON: string); virtual;
procedure ReportIncomingCall(const AIdent, ADisplayName: string); virtual;
procedure ReportOutgoingCall; virtual;
function StartCall(const AIdent, ADisplayName: string): Boolean; virtual;
property Icon: TBitmap read FIcon write SetIcon;
property PushKit: TPushKit read FPushKit;
property VOIP: TVOIP read FVOIP;
public
constructor Create(const AVOIP: TVOIP); virtual;
destructor Destroy; override;
end;
TVOIPCallStateEvent = procedure(Sender: TObject; const CallState: TVOIPCallState; const Ident: string) of object;
TVOIP = class(TObject)
private
FIdentProperty: string;
FPlatformVOIP: TCustomPlatformVOIP;
FOnPushKitMessageReceived: TPushKitMessageReceivedEvent;
FOnPushKitTokenReceived: TPushKitTokenReceivedEvent;
FOnVOIPCallState: TVOIPCallStateEvent;
function GetStoredToken: string;
function GetIcon: TBitmap;
procedure SetIcon(const Value: TBitmap);
protected
procedure DoVOIPCallState(const ACallState: TVOIPCallState; const AIdent: string);
function DoPushKitMessageReceived(const AJSON: string): Boolean;
procedure DoPushKitTokenReceived(const AToken: string; const AIsNew: Boolean);
public
constructor Create;
destructor Destroy; override;
procedure Start;
procedure ReportIncomingCall(const AIdent, ADisplayName: string);
function StartCall(const AIdent, ADisplayName: string): Boolean;
property Icon: TBitmap read GetIcon write SetIcon;
property IdentProperty: string read FIdentProperty write FIdentProperty;
property StoredToken: string read GetStoredToken;
property OnVOIPCallState: TVOIPCallStateEvent read FOnVOIPCallState write FOnVOIPCallState;
property OnPushKitMessageReceived: TPushKitMessageReceivedEvent read FOnPushKitMessageReceived write FOnPushKitMessageReceived;
property OnPushKitTokenReceived: TPushKitTokenReceivedEvent read FOnPushKitTokenReceived write FOnPushKitTokenReceived;
end;
implementation
uses
DW.OSLog,
System.JSON,
{$IF Defined(IOS)}
DW.VOIP.iOS;
{$ELSEIF Defined(ANDROID)}
DW.VOIP.Android;
{$ELSE}
DW.VOIP.Default;
{$ENDIF}
{ TCustomPlatformVOIP }
constructor TCustomPlatformVOIP.Create(const AVOIP: TVOIP);
begin
inherited Create;
FIcon := TBitmap.Create;
// PushKit handles the push notifications that signal an incoming call
FPushKit := TPushKit.Create;
FPushKit.OnTokenReceived := PushKitTokenReceivedHandler;
FPushKit.OnMessageReceived := PushKitMessageReceivedHandler;
FVOIP := AVOIP;
end;
destructor TCustomPlatformVOIP.Destroy;
begin
FIcon.Free;
inherited;
end;
procedure TCustomPlatformVOIP.DoVOIPCallState(const ACallState: TVOIPCallState; const AIdent: string);
begin
FVOIP.DoVOIPCallState(ACallState, AIdent);
end;
procedure TCustomPlatformVOIP.IconUpdated;
begin
//
end;
procedure TCustomPlatformVOIP.PushKitMessageReceived(const AJSON: string);
var
LJSON: TJSONValue;
LIdent, LDisplayName: string;
begin
// By default, expect a property that identifies the incoming call
LJSON := TJSONObject.ParseJSONValue(AJSON);
if LJSON <> nil then
try
if LJSON.TryGetValue(VOIP.IdentProperty, LIdent) then
begin
LDisplayName := 'Unknown'; // Needs localization
LJSON.TryGetValue('DisplayName', LDisplayName); // Might need a property too
ReportIncomingCall(LIdent, LDisplayName);
end;
//!!!! else perhaps have an "unhandled push" event
finally
LJSON.Free;
end;
end;
procedure TCustomPlatformVOIP.PushKitMessageReceivedHandler(Sender: TObject; const AJSON: string);
begin
if not FVOIP.DoPushKitMessageReceived(AJSON) then
PushKitMessageReceived(AJSON);
end;
procedure TCustomPlatformVOIP.PushKitTokenReceivedHandler(Sender: TObject; const AToken: string; const AIsNew: Boolean);
begin
FVOIP.DoPushKitTokenReceived(AToken, AIsNew);
end;
procedure TCustomPlatformVOIP.ReportIncomingCall(const AIdent, ADisplayName: string);
begin
//
end;
procedure TCustomPlatformVOIP.ReportOutgoingCall;
begin
//
end;
procedure TCustomPlatformVOIP.SetIcon(const Value: TBitmap);
begin
FIcon.Assign(Value);
IconUpdated;
end;
function TCustomPlatformVOIP.StartCall(const AIdent, ADisplayName: string): Boolean;
begin
Result := False;
end;
{ TVOIP }
constructor TVOIP.Create;
begin
inherited;
FIdentProperty := 'ident'; // Do not localize
FPlatformVOIP := TPlatformVOIP.Create(Self);
end;
destructor TVOIP.Destroy;
begin
FPlatformVOIP.Free;
inherited;
end;
procedure TVOIP.DoVOIPCallState(const ACallState: TVOIPCallState; const AIdent: string);
begin
if Assigned(FOnVOIPCallState) then
FOnVOIPCallState(Self, ACallState, AIdent);
end;
function TVOIP.GetIcon: TBitmap;
begin
Result := FPlatformVOIP.Icon;
end;
function TVOIP.GetStoredToken: string;
begin
Result := FPlatformVOIP.PushKit.StoredToken;
end;
function TVOIP.DoPushKitMessageReceived(const AJSON: string): Boolean;
begin
// If not handled, return False. This will cause the default handling to be invoked
Result := False;
if Assigned(FOnPushKitMessageReceived) then
begin
FOnPushKitMessageReceived(Self, AJSON);
Result := True;
end;
end;
procedure TVOIP.DoPushKitTokenReceived(const AToken: string; const AIsNew: Boolean);
begin
TOSLog.d('Token: %s', [AToken]);
if Assigned(FOnPushKitTokenReceived) then
FOnPushKitTokenReceived(Self, AToken, AIsNew);
end;
procedure TVOIP.ReportIncomingCall(const AIdent, ADisplayName: string);
begin
FPlatformVOIP.ReportIncomingCall(AIdent, ADisplayName);
end;
procedure TVOIP.SetIcon(const Value: TBitmap);
begin
FPlatformVOIP.Icon := Value;
end;
procedure TVOIP.Start;
begin
TOSLog.d('TVOIP.Start');
FPlatformVOIP.PushKit.Start;
end;
function TVOIP.StartCall(const AIdent, ADisplayName: string): Boolean;
begin
Result := FPlatformVOIP.StartCall(AIdent, ADisplayName);
end;
end.
|
program Ch1;
{$mode objfpc}
var
I:Integer;
function IsPrime(N:Integer):Boolean;
var
I:Integer;
begin
if(N <= 1) then Exit(False);
for I := 2 to Trunc(Sqrt(N)) do
if(N mod I = 0) then Exit(False);
Result := True;
end;
function ReverseNum(N:Integer):Integer;
begin
Result := 0;
while(N <> 0) do
begin
Result := (Result * 10) + (N mod 10);
N := N div 10;
end;
end;
begin
for I := 1 to 1000 do
if((I = ReverseNum(I)) and IsPrime(I)) then
Write(I, ' ');
end.
|
unit Control.Lancamentos;
interface
uses Model.Lancamentos, System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum;
type
TLancamentosControl = class
private
FLancamentos: TLancamentos;
public
constructor Create;
destructor Destroy; override;
function Gravar: Boolean;
function Localizar(aParam: array of variant): TFDQuery;
function GetId(): Integer;
function ValidaCampos(): Boolean;
function ValidaExclusao(): Boolean;
function ExtratoLancamentos(aParam: Array of variant): TFDQuery;
function ExtratoLancamentosEntregador(aParam: Array of variant): Boolean;
function EncerraLancamentos(aParam: Array of variant): Boolean;
property Lancamentos: TLancamentos read FLancamentos write FLancamentos;
end;
implementation
{ TLancamentosControl }
constructor TLancamentosControl.Create;
begin
FLancamentos := TLancamentos.Create;
end;
destructor TLancamentosControl.Destroy;
begin
FLancamentos.Free;
inherited;
end;
function TLancamentosControl.EncerraLancamentos(aParam: array of variant): Boolean;
begin
Result:= FLancamentos.EncerraLancamentos(aParam);
end;
function TLancamentosControl.ExtratoLancamentos(aParam: array of variant): TFDQuery;
begin
Result := FLancamentos.ExtratoLancamentos(aParam);
end;
function TLancamentosControl.ExtratoLancamentosEntregador(aParam: array of variant): Boolean;
begin
Result := FLancamentos.ExtratoLancamentosEntregador(aParam);
end;
function TLancamentosControl.GetId: Integer;
begin
Result := FLancamentos.GetID;
end;
function TLancamentosControl.Gravar: Boolean;
begin
Result := FLancamentos.Gravar;
end;
function TLancamentosControl.Localizar(aParam: array of variant): TFDQuery;
begin
Result := FLancamentos.Localizar(aParam);
end;
function TLancamentosControl.ValidaCampos: Boolean;
begin
Result := False;
if FLancamentos.Descricao.IsEmpty then
begin
Application.MessageBox('Informe a descrição do lançamento.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if (DateTimeToStr(FLancamentos.Data).IsEmpty) or (FLancamentos.Data = 0) then
begin
Application.MessageBox('Informe a data do Lançamento.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FLancamentos.Cadastro = 0 then
begin
Application.MessageBox('Informe o código do Entregador.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FLancamentos.Valor = 0 then
begin
Application.MessageBox('Informe o valor.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
end;
function TLancamentosControl.ValidaExclusao: Boolean;
begin
Result := False;
if FLancamentos.Desconto = 'S' then
begin
Application.MessageBox('Lançamento já fechado! Impossível excluir.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
end;
end.
|
unit MFichas.Model.Produto.Metodos.Buscar;
interface
uses
System.SysUtils,
MFichas.Model.Produto.Interfaces,
MFichas.Controller.Types,
ORMBR.Container.DataSet.Interfaces,
ORMBR.Container.DataSet,
ORMBR.DataSet.ClientDataSet,
FireDAC.Comp.Client,
FireDAC.Comp.DataSet;
type
TModelProdutoMetodosBuscar = class(TInterfacedObject, iModelProdutoMetodosBuscar)
private
[weak]
FParent : iModelProduto;
FFDMemTable: TFDMemTable;
constructor Create(AParent: iModelProduto);
procedure CopiarDataSet;
procedure Validacao;
public
destructor Destroy; override;
class function New(AParent: iModelProduto): iModelProdutoMetodosBuscar;
function FDMemTable(AFDMemTable: TFDMemTable): iModelProdutoMetodosBuscar;
function BuscarTodos : iModelProdutoMetodosBuscar;
function BuscarTodosAtivos : iModelProdutoMetodosBuscar;
function BuscarPorCodigo(ACodigo: String): iModelProdutoMetodosBuscar;
function BuscarPorGrupo(AGrupo: String) : iModelProdutoMetodosBuscar;
function &End : iModelProdutoMetodos;
end;
implementation
{ TModelProdutoMetodosBuscar }
function TModelProdutoMetodosBuscar.BuscarPorCodigo(
ACodigo: String): iModelProdutoMetodosBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
' GUUID = ' + QuotedStr(ACodigo) +
' STATUS = ' + Integer(saiAtivo).ToString
);
Validacao;
CopiarDataSet;
end;
function TModelProdutoMetodosBuscar.BuscarPorGrupo(
AGrupo: String): iModelProdutoMetodosBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
' GRUPO = ' + QuotedStr(AGrupo) + ' AND ' +
' STATUS = ' + Integer(saiAtivo).ToString
);
Validacao;
CopiarDataSet;
end;
function TModelProdutoMetodosBuscar.BuscarTodos: iModelProdutoMetodosBuscar;
begin
Result := Self;
FParent.DAODataSet.Open;
Validacao;
CopiarDataSet;
end;
function TModelProdutoMetodosBuscar.BuscarTodosAtivos: iModelProdutoMetodosBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
'STATUS = ' + Integer(saiAtivo).ToString
);
Validacao;
CopiarDataSet;
end;
function TModelProdutoMetodosBuscar.&End: iModelProdutoMetodos;
begin
//TODO: IMPLEMENTAR METODO DE BUSCAR PRODUTOS
Result := FParent.Metodos;
end;
procedure TModelProdutoMetodosBuscar.Validacao;
begin
if not Assigned(FFDMemTable) then
raise Exception.Create(
'Para prosseguir, você deve vincular um FDMemTable ao encadeamento' +
' de funcões do método de Produto.Metodo.Buscar .'
);
end;
procedure TModelProdutoMetodosBuscar.CopiarDataSet;
begin
FFDMemTable.CopyDataSet(FParent.DAODataSet.DataSet, [coStructure, coRestart, coAppend]);
FFDMemTable.IndexFieldNames := 'DESCRICAO';
end;
function TModelProdutoMetodosBuscar.FDMemTable(
AFDMemTable: TFDMemTable): iModelProdutoMetodosBuscar;
begin
Result := Self;
FFDMemTable := AFDMemTable;
end;
constructor TModelProdutoMetodosBuscar.Create(AParent: iModelProduto);
begin
FParent := AParent;
end;
destructor TModelProdutoMetodosBuscar.Destroy;
begin
inherited;
end;
class function TModelProdutoMetodosBuscar.New(AParent: iModelProduto): iModelProdutoMetodosBuscar;
begin
Result := Self.Create(AParent);
end;
end.
|
unit m3StorageHolder;
// Модуль: "w:\common\components\rtl\Garant\m3\m3StorageHolder.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tm3StorageHolder" MUID: (542E5D79018F)
{$Include w:\common\components\rtl\Garant\m3\m3Define.inc}
interface
uses
l3IntfUses
, l3CProtoObject
, m3StorageInterfaces
, m3CommonStorage
, m3RootStreamManagerPrim
, ActiveX
;
type
Tm3StorageHolder = class(Tl3CProtoObject, Im3StorageHolder)
private
f_Storage: Im3IndexedStorage;
f_StorageClass: Rm3CommonStorage;
f_RootStreamManager: Tm3RootStreamManagerPrim;
f_Access: Tm3StoreAccess;
f_FileName: WideString;
f_SharedMode: Cardinal;
protected
function ReopenStorage(anAccess: Tm3StoreAccess): Im3IndexedStorage;
function Get_Storage: Im3IndexedStorage;
function StoreToCache(const aFileName: WideString;
aSharedMode: Cardinal): Im3IndexedStorage;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure ClearFields; override;
public
constructor Create(aStorageClass: Rm3CommonStorage;
anAccess: Tm3StoreAccess;
const aStream: IStream); reintroduce;
class function Make(aStorageClass: Rm3CommonStorage;
anAccess: Tm3StoreAccess;
const aStream: IStream): Im3StorageHolder; reintroduce;
class function GetFromCache(const aFileName: WideString;
anAccess: Tm3StoreAccess;
aType: Tm3StorageType;
aSharedMode: Cardinal;
out theStorage: Im3IndexedStorage): Boolean;
public
property Access: Tm3StoreAccess
read f_Access;
property FileName: WideString
read f_FileName;
property SharedMode: Cardinal
read f_SharedMode;
end;//Tm3StorageHolder
implementation
uses
l3ImplUses
, SysUtils
, m3StorageHolderList
, Windows
//#UC START# *542E5D79018Fimpl_uses*
//#UC END# *542E5D79018Fimpl_uses*
;
constructor Tm3StorageHolder.Create(aStorageClass: Rm3CommonStorage;
anAccess: Tm3StoreAccess;
const aStream: IStream);
//#UC START# *542E5E1A037B_542E5D79018F_var*
//#UC END# *542E5E1A037B_542E5D79018F_var*
begin
//#UC START# *542E5E1A037B_542E5D79018F_impl*
Assert(f_RootStreamManager = nil);
Assert((anAccess = STGM_READ) OR (anAccess = STGM_READWRITE));
Assert(Assigned(aStorageClass));
Assert(aStream <> nil);
inherited Create;
f_Access := anAccess;
f_StorageClass := aStorageClass;
f_Storage := f_StorageClass.OpenRoot(anAccess, aStream, f_RootStreamManager);
Assert(f_Storage <> nil);
Assert(f_RootStreamManager <> nil);
//#UC END# *542E5E1A037B_542E5D79018F_impl*
end;//Tm3StorageHolder.Create
class function Tm3StorageHolder.Make(aStorageClass: Rm3CommonStorage;
anAccess: Tm3StoreAccess;
const aStream: IStream): Im3StorageHolder;
var
l_Inst : Tm3StorageHolder;
begin
l_Inst := Create(aStorageClass, anAccess, aStream);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//Tm3StorageHolder.Make
class function Tm3StorageHolder.GetFromCache(const aFileName: WideString;
anAccess: Tm3StoreAccess;
aType: Tm3StorageType;
aSharedMode: Cardinal;
out theStorage: Im3IndexedStorage): Boolean;
//#UC START# *542E6E450028_542E5D79018F_var*
var
l_List : Tm3StorageHolderList;
l_Index : Integer;
l_Item : Tm3StorageHolder;
//#UC END# *542E6E450028_542E5D79018F_var*
begin
//#UC START# *542E6E450028_542E5D79018F_impl*
Result := false;
theStorage := nil;
if not Tm3StorageHolderList.Exists then
Exit;
if (aType <> m3_stArchive) then
Exit;
l_List := Tm3StorageHolderList.Instance;
Assert(l_List <> nil);
l_List.Lock;
try
if (aSharedMode = 0) then
begin
if l_List.FindData(aFileName, l_Index) then
l_List.Delete(l_Index);
// - удаляем то, что было захвачено не монопольно
Exit;
end;//aSharedMode = 0
if l_List.FindData(aFileName, l_Index) then
begin
l_Item := l_List.Items[l_Index];
if (l_Item.SharedMode <> aSharedMode) then
begin
if (l_Item.SharedMode = FILE_SHARE_READ) then
begin
l_List.Delete(l_Index);
// - удаляем менеджер с более низкими разрешениями доступа
Exit;
end;//l_Item.Access = STGM_READ
end;//l_Item.SharedMode <> aSharedMode
if (l_Item.Access <> anAccess) then
begin
if (l_Item.Access = STGM_READ) then
begin
l_List.Delete(l_Index);
// - удаляем менеджер с более низкими разрешениями доступа
Exit;
end;//l_Item.Access = STGM_READ
end;//l_Item.Access <> anAccess
theStorage := l_Item.ReopenStorage(anAccess);
Result := (theStorage <> nil);
end;//l_List.FindData(aFileName, l_Index)
finally
l_List.Unlock;
end;//try..finally
//#UC END# *542E6E450028_542E5D79018F_impl*
end;//Tm3StorageHolder.GetFromCache
function Tm3StorageHolder.ReopenStorage(anAccess: Tm3StoreAccess): Im3IndexedStorage;
//#UC START# *542E95A901B7_542E5D79018F_var*
//#UC END# *542E95A901B7_542E5D79018F_var*
begin
//#UC START# *542E95A901B7_542E5D79018F_impl*
Assert(f_Storage = nil);
Result := f_StorageClass.OpenFromManager(anAccess, f_RootStreamManager);
//#UC END# *542E95A901B7_542E5D79018F_impl*
end;//Tm3StorageHolder.ReopenStorage
function Tm3StorageHolder.Get_Storage: Im3IndexedStorage;
//#UC START# *542E5D4E01DD_542E5D79018Fget_var*
//#UC END# *542E5D4E01DD_542E5D79018Fget_var*
begin
//#UC START# *542E5D4E01DD_542E5D79018Fget_impl*
Result := f_Storage;
//#UC END# *542E5D4E01DD_542E5D79018Fget_impl*
end;//Tm3StorageHolder.Get_Storage
function Tm3StorageHolder.StoreToCache(const aFileName: WideString;
aSharedMode: Cardinal): Im3IndexedStorage;
//#UC START# *542E736E0204_542E5D79018F_var*
var
l_List : Tm3StorageHolderList;
l_Index : Integer;
//#UC END# *542E736E0204_542E5D79018F_var*
begin
//#UC START# *542E736E0204_542E5D79018F_impl*
Assert(f_RootStreamManager <> nil);
Assert(f_Storage <> nil);
Result := f_Storage;
// - отдаём хранилище
f_Storage := nil;
// - отпускаем его
f_FileName := aFileName;
f_SharedMode := aSharedMode;
if (aFileName = '') then
// - нельзя кешировать временные хранилища
Exit;
if f_StorageClass.ForPlugin then
// - для плагина - нечего вообще заморачиваться
Exit;
if not f_StorageClass.IsPacked then
// - непакованные хранилища - это какая-то экзотика
Exit;
if (aSharedMode = 0) then
// - нельзя кешировать монопольные хранилища
Exit;
(* if (f_Access = STGM_READWRITE) then
// - давайте пока кешировать хранилища только на чтение
Exit;*)
l_List := Tm3StorageHolderList.Instance;
Assert(l_List <> nil);
l_List.Lock;
try
if not l_List.FindData(Self, l_Index) then
l_List.Add(Self)
else
begin
if (l_List.Items[l_Index] = Self) then
// - мы уже закешированы, выходим
Exit;
Assert(false, 'Для файла "' + FileName + '" уже есть другой менеджер блоков');
end;//not l_List.FindData(Self, l_Index)
finally
l_List.Unlock;
end;//try..finally
//#UC END# *542E736E0204_542E5D79018F_impl*
end;//Tm3StorageHolder.StoreToCache
procedure Tm3StorageHolder.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_542E5D79018F_var*
//#UC END# *479731C50290_542E5D79018F_var*
begin
//#UC START# *479731C50290_542E5D79018F_impl*
FreeAndNil(f_RootStreamManager);
inherited;
//#UC END# *479731C50290_542E5D79018F_impl*
end;//Tm3StorageHolder.Cleanup
procedure Tm3StorageHolder.ClearFields;
begin
f_Storage := nil;
f_FileName := '';
inherited;
end;//Tm3StorageHolder.ClearFields
end.
|
unit DamMsgEdit;
interface
uses
{$IFDEF FPC}
Forms, Buttons, StdCtrls, ExtCtrls, ColorBox, Controls,
{$ELSE}
Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Controls,
Vcl.Buttons, System.Classes,
{$ENDIF}
//
DamUnit, Vcl.DzHTMLText;
type
TFrmDamMsgEdit = class(TForm)
BtnOK: TBitBtn;
BtnCancel: TBitBtn;
EdNome: TEdit;
W5: TShape;
W6: TShape;
W4: TShape;
W2: TShape;
W3: TShape;
W1: TShape;
BtnBold: TSpeedButton;
BtnItalic: TSpeedButton;
BtnUnderline: TSpeedButton;
BtnDoFont: TSpeedButton;
BtnDoSize: TSpeedButton;
BtnDoFontColor: TSpeedButton;
BtnDoBgColor: TSpeedButton;
LbFontColor: TLabel;
LbBgColor: TLabel;
BtnCenter: TSpeedButton;
BtnRight: TSpeedButton;
BtnDoAnyColor: TSpeedButton;
EdSize: TComboBox;
Box: TScrollBox;
BtnPreview: TBitBtn;
LbMsg: TDzHTMLText;
BtnLeft: TSpeedButton;
BoxQuickButtons: TFlowPanel;
tInfo: TSpeedButton;
tQuest: TSpeedButton;
tWarn: TSpeedButton;
tError: TSpeedButton;
tRaise: TSpeedButton;
BtnDoLink: TSpeedButton;
EdFont: TComboBox;
LbAnyColor: TLabel;
EdFontColor: TColorBox;
EdBgColor: TColorBox;
EdAnyColor: TColorBox;
Label1: TLabel;
BtnHelp: TBitBtn;
BtnParameter: TSpeedButton;
BtnExceptPar: TSpeedButton;
M: TMemo;
WPreview: TShape;
procedure MChange(Sender: TObject);
procedure BtnBoldClick(Sender: TObject);
procedure BtnItalicClick(Sender: TObject);
procedure BtnUnderlineClick(Sender: TObject);
procedure BtnDoSizeClick(Sender: TObject);
procedure BtnDoFontColorClick(Sender: TObject);
procedure tInfoClick(Sender: TObject);
procedure BtnPreviewClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
procedure BtnDoBgColorClick(Sender: TObject);
procedure BtnDoAnyColorClick(Sender: TObject);
procedure BtnCenterClick(Sender: TObject);
procedure BtnRightClick(Sender: TObject);
procedure BtnDoLinkClick(Sender: TObject);
procedure BtnLeftClick(Sender: TObject);
procedure BtnDoFontClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EdFontDropDown(Sender: TObject);
procedure BtnHelpClick(Sender: TObject);
procedure BtnParameterClick(Sender: TObject);
procedure BtnExceptParClick(Sender: TObject);
public
Dam: TDam;
DamMsg: TDamMsg;
procedure StoreComp(Target: TDamMsg);
private
procedure PutSelText(TagOpen: string; TagClose: string='');
procedure SetBtn(C: TDamMsg);
end;
var
FrmDamMsgEdit: TFrmDamMsgEdit;
implementation
{$R *.dfm}
uses
{$IFDEF FPC}
Graphics, SysUtils, LCLIntf;
{$ELSE}
Vcl.Graphics, System.SysUtils,
Winapi.Windows, Winapi.Messages, Winapi.ShellAPI;
{$ENDIF}
procedure TFrmDamMsgEdit.FormCreate(Sender: TObject);
begin
LbMsg.StyleElements := []; //do not use themes in Delphi IDE
LbMsg.Text := '';
end;
procedure TFrmDamMsgEdit.FormShow(Sender: TObject);
var A: string;
V: Boolean;
begin
EdFont.Text := Dam.MessageFont.Name;
EdSize.Text := IntToStr(Dam.MessageFont.Size);
Box.Color := Dam.MessageColor;
LbMsg.Font.Assign(Dam.MessageFont);
LbMsg.Images := Dam.Images;
if DamMsg <> nil then
begin
A := DamMsg.Name;
if A[1] = '_' then Delete(A, 1, 1);
EdNome.Text := A;
M.Text := DamMsg.Message;
//MChange(nil);
V := (DamMsg.Button1 = '')
and (DamMsg.Button2 = '')
and (DamMsg.Button3 = '')
and (DamMsg.CustomTitle = '')
and (DamMsg.CustomIcon.Empty)
and (DamMsg.Title = dtByIcon);
tRaise.Down := (V)
and (DamMsg.RaiseExcept)
and (DamMsg.Icon = diError)
and (DamMsg.Buttons = dbOK);
tInfo.Down := (V)
and (not DamMsg.RaiseExcept)
and (DamMsg.Icon = diInfo)
and (DamMsg.Buttons = dbOK);
tWarn.Down := (V)
and (not DamMsg.RaiseExcept)
and (DamMsg.Icon = diWarn)
and (DamMsg.Buttons = dbOK);
tQuest.Down := (V)
and (not DamMsg.RaiseExcept)
and (DamMsg.Icon = diQuest)
and (DamMsg.Buttons = dbYesNo);
tError.Down := (V)
and (not DamMsg.RaiseExcept)
and (DamMsg.Icon = diError)
and (DamMsg.Buttons = dbOK);
end;
end;
procedure TFrmDamMsgEdit.EdFontDropDown(Sender: TObject);
begin
if EdFont.Items.Count=0 then
EdFont.Items.Assign(Screen.Fonts);
end;
procedure TFrmDamMsgEdit.MChange(Sender: TObject);
begin
LbMsg.Text := M.Text;
end;
function CorToStr(C: TColor): string;
begin
Result := ColorToString(C);
if Result.StartsWith('$00') then Delete(Result, 2, 2);
end;
procedure TFrmDamMsgEdit.PutSelText(TagOpen: string; TagClose: string='');
begin
if TagClose='' then TagClose := TagOpen;
M.SelText := '<'+TagOpen+'>'+M.SelText+'</'+TagClose+'>';
end;
procedure TFrmDamMsgEdit.BtnBoldClick(Sender: TObject);
begin
PutSelText('b');
end;
procedure TFrmDamMsgEdit.BtnItalicClick(Sender: TObject);
begin
PutSelText('i');
end;
procedure TFrmDamMsgEdit.BtnUnderlineClick(Sender: TObject);
begin
PutSelText('u');
end;
procedure TFrmDamMsgEdit.BtnLeftClick(Sender: TObject);
begin
PutSelText('l');
end;
procedure TFrmDamMsgEdit.BtnCenterClick(Sender: TObject);
begin
PutSelText('c');
end;
procedure TFrmDamMsgEdit.BtnRightClick(Sender: TObject);
begin
PutSelText('r');
end;
procedure TFrmDamMsgEdit.BtnDoFontClick(Sender: TObject);
begin
PutSelText('fn:'+EdFont.Text, 'fn');
end;
procedure TFrmDamMsgEdit.BtnDoSizeClick(Sender: TObject);
begin
PutSelText('fs:'+EdSize.Text, 'fs');
end;
procedure TFrmDamMsgEdit.BtnDoFontColorClick(Sender: TObject);
begin
PutSelText('fc:'+CorToStr(EdFontColor.Selected), 'fc');
end;
procedure TFrmDamMsgEdit.BtnDoBgColorClick(Sender: TObject);
begin
PutSelText('bc:'+CorToStr(EdBgColor.Selected), 'bc');
end;
procedure TFrmDamMsgEdit.BtnDoAnyColorClick(Sender: TObject);
begin
M.SelText := CorToStr(EdAnyColor.Selected);
end;
procedure TFrmDamMsgEdit.BtnDoLinkClick(Sender: TObject);
begin
PutSelText('a');
end;
procedure TFrmDamMsgEdit.BtnParameterClick(Sender: TObject);
begin
M.SelText := DAM_PARAM_IDENT;
end;
procedure TFrmDamMsgEdit.BtnExceptParClick(Sender: TObject);
begin
M.SelText := DAM_PARAM_EXCEPTION;
end;
procedure ClearMsg(Msg: TDamMsg);
var Def: TDamMsg;
FocoInvertido: Boolean;
AMsg: string;
begin
Def := TDamMsg.Create(nil);
try
AMsg := Msg.Message;
FocoInvertido := Msg.SwapFocus;
Msg.Assign(Def); //get default properties
Msg.Message := AMsg;
Msg.SwapFocus := FocoInvertido;
finally
Def.Free;
end;
end;
procedure TFrmDamMsgEdit.tInfoClick(Sender: TObject);
var aTipo: string;
aNome: string;
function CheckStartWith(Btn: TSpeedButton): Boolean;
var Prefix: string;
begin
Result := False;
Prefix := Btn.Caption;
if aNome.StartsWith(Prefix) then
begin
Result := True;
Delete(aNome, 1, Length(Prefix));
end;
end;
begin
aTipo := TSpeedButton(Sender).Caption;
aNome := EdNome.Text;
if not CheckStartWith(tInfo) then
if not CheckStartWith(tQuest) then
if not CheckStartWith(tWarn) then
if not CheckStartWith(tError) then
if not CheckStartWith(tRaise) then {};
EdNome.Text := aTipo+aNome;
end;
procedure TFrmDamMsgEdit.SetBtn(C: TDamMsg);
begin
if tInfo.Down then
begin
ClearMsg(C);
C.Icon := diInfo;
end else
if tWarn.Down then
begin
ClearMsg(C);
C.Icon := diWarn;
end else
if tError.Down then
begin
ClearMsg(C);
C.Icon := diError;
end else
if tQuest.Down then
begin
ClearMsg(C);
C.Icon := diQuest;
C.Buttons := dbYesNo;
end else
if tRaise.Down then
begin
ClearMsg(C);
C.Icon := diError;
C.RaiseExcept := True;
end;
end;
procedure TFrmDamMsgEdit.BtnPreviewClick(Sender: TObject);
var C: TDamMsg;
begin
C := TDamMsg.Create(nil);
try
C.Dam := Dam;
if DamMsg<>nil then C.Assign(DamMsg);
C.Message := M.Text;
SetBtn(C);
C.Preview;
finally
C.Free;
end;
end;
procedure TFrmDamMsgEdit.BtnOKClick(Sender: TObject);
var A: string;
begin
EdNome.Text := Trim(EdNome.Text);
if EdNome.Text = '' then
raise Exception.Create('Please, specify a name');
A := '_' + EdNome.Text;
if not ((DamMsg <> nil) and (DamMsg.Name = A)) then
if Dam.Owner.FindComponent(A) <> nil then
raise Exception.Create(EdNome.Text + ' already exists');
EdNome.Text := A;
ModalResult := mrOk;
end;
procedure TFrmDamMsgEdit.StoreComp(Target: TDamMsg);
begin
Target.Name := EdNome.Text;
Target.Message := M.Text;
SetBtn(Target);
end;
procedure TFrmDamMsgEdit.BtnHelpClick(Sender: TObject);
const URL = 'https://github.com/digao-dalpiaz/Dam';
begin
{$IFDEF FPC}
OpenURL(URL);
{$ELSE}
ShellExecute(0, '', URL, '', '', SW_SHOWNORMAL);
{$ENDIF}
end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_
* Implements a Quaternion class (and Quaternion operations)
***********************************************************************************************************************
}
Unit TERRA_Quaternion;
{$I terra.inc}
Interface
Uses TERRA_Math, TERRA_Vector3D, TERRA_Matrix4x4;
Type
PQuaternion = ^Quaternion;
Quaternion=Packed {$IFDEF USE_OLD_OBJECTS}Object{$ELSE}Record{$ENDIF}
X:Single;
Y:Single;
Z:Single;
W:Single;
Function Equals(Const B:Quaternion):Boolean;
// Returns a normalized Quaternion
Procedure Normalize;
{$IFDEF BENCHMARK}
Procedure TransformSSE(Const M:Matrix4x4);
Procedure NormalizeSSE;
{$ENDIF}
Procedure Transform(Const M:Matrix4x4);
Procedure Add(Const B:Quaternion);
Procedure Subtract(Const B:Quaternion);
Function Length:Single;
End;
Color4F = Quaternion;
Const
QuaternionOne:Quaternion=(X:1.0; Y:1.0; Z:1.0; W:1.0);
QuaternionZero:Quaternion=(X:0.0; Y:0.0; Z:0.0; W:1.0);
Function QuaternionCreate(Const X,Y,Z,W:Single):Quaternion;Overload;
Function QuaternionCreate(Const V:Vector3D):Quaternion;Overload;
// Creates a quaterion with specified rotation
Function QuaternionRotation(Const Rotation:Vector3D):Quaternion;
// Returns a Matrix4x4 representing the Quaternion
Function QuaternionMatrix4x4(Const Quaternion:Quaternion):Matrix4x4;
Function QuaternionFromRotationMatrix4x4(Const M:Matrix4x4):Quaternion;
Function QuaternionFromToRotation(Const Src,Dest:Vector3D):Quaternion;
// Slerps two Quaternions
Function QuaternionSlerp(A,B:Quaternion; Const T:Single):Quaternion;
{$IFDEF BENCHMARK}
Function QuaternionSlerpSSE(A,B:Quaternion; Const T:Single):Quaternion;
{$ENDIF}
// Returns the conjugate of a Quaternion
Function QuaternionConjugate(Const Q:Quaternion):Quaternion;
// Returns the norm of a Quaternion
Function QuaternionNorm(Const Q:Quaternion):Single;
// Returns the inverse of a Quaternion
Function QuaternionInverse(Const Q:Quaternion):Quaternion;
// Multiplies two Quaternions
Function QuaternionMultiply(Const Ql,Qr:Quaternion):Quaternion;
Function QuaternionAdd(Const A,B:Quaternion):Quaternion;
Function QuaternionScale(Const Q:Quaternion; Const Scale:Single):Quaternion;
Function QuaternionFromBallPoints(Const arcFrom,arcTo:Vector3D):Quaternion;
Procedure QuaternionToBallPoints(Q:Quaternion; Var arcFrom,arcTo:Vector3D);
Function QuaternionFromAxisAngle(Const Axis:Vector3D; Const Angle:Single):Quaternion;
Function QuaternionToEuler(Const Q:Quaternion):Vector3D;
Function QuaternionLookRotation(lookAt, up:Vector3D):Quaternion;
Function QuaternionTransform(Const Q:Quaternion; Const V:Vector3D):Vector3D;
// Returns the dot product between two vectors
Function QuaternionDot(Const A,B:Quaternion):Single; {$IFDEF FPC}Inline;{$ENDIF}
Implementation
Uses Math{$IFDEF SSE},TERRA_SSE{$ENDIF}{$IFDEF NEON_FPU},TERRA_NEON{$ENDIF};
Function QuaternionCreate(Const X,Y,Z,W:Single):Quaternion;
Begin
Result.X := X;
Result.Y := Y;
Result.Z := Z;
Result.W := W;
End;
Function QuaternionCreate(Const V:Vector3D):Quaternion;
Begin
Result.X := V.X;
Result.Y := V.Y;
Result.Z := V.Z;
Result.W := 1.0;
End;
Function QuaternionTransform(Const Q:Quaternion; Const V:Vector3D):Vector3D;
Var
M:Matrix4x4;
Begin
M := QuaternionMatrix4x4(Q);
Result := M.Transform(V);
End;
Function Quaternion.Length:Single;
Begin
Result := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z) + Sqr(W));
End;
Function Quaternion.Equals(Const B:Quaternion):Boolean;
Begin
Result := (Self.X=B.X) And (Self.Y=B.Y) And(Self.Z=B.Z) And(Self.W=B.W);
End;
Function QuaternionDot(Const A,B:Quaternion):Single; {$IFDEF FPC}Inline;{$ENDIF}
Begin
{$IFDEF NEON_FPU}
Result := dot4_neon_hfp(@A,@B);
{$ELSE}
Result := (A.X*B.X)+(A.Y*B.Y)+(A.Z*B.Z)+(A.W*B.W);
{$ENDIF}
End;
Function QuaternionLookRotation(lookAt, up:Vector3D):Quaternion;
Var
m00,m01, m02, m10, m11, m12, m20, m21, m22:Single;
right:Vector3D;
w4_recip:Single;
Begin
VectorOrthoNormalize(lookAt, up);
lookAt.Normalize();
right := VectorCross(up, lookAt);
m00 := right.x;
m01 := up.x;
m02 := lookAt.x;
m10 := right.y;
m11 := up.y;
m12 := lookAt.y;
m20 := right.z;
m21 := up.z;
m22 := lookAt.z;
Result.w := Sqrt(1.0 + m00 + m11 + m22) * 0.5;
w4_recip := 1.0 / (4.0 * Result.w);
Result.x := (m21 - m12) * w4_recip;
Result.y := (m02 - m20) * w4_recip;
Result.z := (m10 - m01) * w4_recip;
End;
Function QuaternionFromToRotation(Const Src,Dest:Vector3D):Quaternion;
{Var
Temp:Vector3D;
Begin
Temp := VectorCross(A, B);
Result.X := Temp.X;
Result.Y := Temp.Y;
Result.Z := Temp.Z;
Result.W := Sqrt(Sqr(A.Length) * Sqr(B.Length)) + VectorDot(A, B);
Result.Normalize();
End;}
Var
D,S,Invs:Single;
axis, v0,v1,c:Vector3D;
Begin
v0 := Src;
v1 := dest;
v0.Normalize();
v1.Normalize();
d := VectorDot(v0, v1);
// If dot == 1, vectors are the same
If (d >= 1.0) Then
Begin
Result := QuaternionZero;
Exit;
End;
If (d < (1e-6 - 1.0)) Then
Begin
// Generate an axis
axis := VectorCross(VectorCreate(1,0,0), Src);
If (axis.Length<=0) Then // pick another if colinear
axis := VectorCross(VectorCreate(0,1,0), Src);
Axis.Normalize();
Result := QuaternionFromAxisAngle(Axis, PI);
End Else
Begin
s := Sqrt( (1+d)*2 );
invs := 1 / s;
c := VectorCross(v0, v1);
Result.x := c.x * invs;
Result.y := c.y * invs;
Result.z := c.z * invs;
Result.w := s * 0.5;
Result.Normalize();
End;
End;
Function QuaternionRotation(Const Rotation:Vector3D):Quaternion;
Var
cos_z_2, cos_y_2, cos_x_2:Single;
sin_z_2, sin_y_2, sin_x_2:Single;
Begin
cos_z_2 := Cos(0.5 * Rotation.Z);
cos_y_2 := Cos(0.5 * Rotation.y);
cos_x_2 := Cos(0.5 * Rotation.x);
sin_z_2 := Sin(0.5 * Rotation.z);
sin_y_2 := Sin(0.5 * Rotation.y);
sin_x_2 := Sin(0.5 * Rotation.x);
// and now compute Quaternion
Result.W := cos_z_2*cos_y_2*cos_x_2 + sin_z_2*sin_y_2*sin_x_2;
Result.X := cos_z_2*cos_y_2*sin_x_2 - sin_z_2*sin_y_2*cos_x_2;
Result.Y := cos_z_2*sin_y_2*cos_x_2 + sin_z_2*cos_y_2*sin_x_2;
Result.Z := sin_z_2*cos_y_2*cos_x_2 - cos_z_2*sin_y_2*sin_x_2;
Result.Normalize;
End;
Function QuaternionFromRotationMatrix4x4(Const M:Matrix4x4):Quaternion;
Var
w4:Double;
Function Index(I,J:Integer):Integer;
Begin
Result := J*4 + I;
End;
Begin
Result.w := Sqrt(1.0 + M.V[0] + M.V[5] + M.V[10]) / 2.0;
w4 := (4.0 * Result.w);
Result.x := (M.V[Index(2,1)] - M.V[Index(1,2)]) / w4 ;
Result.y := (M.V[Index(0,2)] - M.V[Index(2,0)]) / w4 ;
Result.z := (M.V[Index(1,0)] - M.V[Index(0,1)]) / w4 ;
End;
Function QuaternionMatrix4x4(Const Quaternion:Quaternion):Matrix4x4;
Var
Q:TERRA_Quaternion.Quaternion;
Begin
Q := Quaternion;
Q.Normalize;
Result.V[0]:= 1.0 - 2.0*Q.Y*Q.Y -2.0 *Q.Z*Q.Z;
Result.V[1]:= 2.0 * Q.X*Q.Y + 2.0 * Q.W*Q.Z;
Result.V[2]:= 2.0 * Q.X*Q.Z - 2.0 * Q.W*Q.Y;
Result.V[3] := 0;
Result.V[4]:= 2.0 * Q.X*Q.Y - 2.0 * Q.W*Q.Z;
Result.V[5]:= 1.0 - 2.0 * Q.X*Q.X - 2.0 * Q.Z*Q.Z;
Result.V[6]:= 2.0 * Q.Y*Q.Z + 2.0 * Q.W*Q.X;
Result.V[7] := 0;
Result.V[8] := 2.0 * Q.X*Q.Z + 2.0 * Q.W*Q.Y;
Result.V[9] := 2.0 * Q.Y*Q.Z - 2.0 * Q.W*Q.X;
Result.V[10] := 1.0 - 2.0 * Q.X*Q.X - 2.0 * Q.Y*Q.Y;
Result.V[11] := 0;
Result.V[12] := 0.0;
Result.V[13] := 0.0;
Result.V[14] := 0.0;
Result.V[15] := 1.0;
End;
Function QuaternionMultiply(Const Ql,Qr:Quaternion):Quaternion;
Begin
Result.W := qL.W * qR.W - qL.X * qR.X - qL.Y * qR.Y - qL.Z * qR.Z;
Result.X := qL.W * qR.X + qL.X * qR.W + qL.Y * qR.Z - qL.Z * qR.Y;
Result.Y := qL.W * qR.Y + qL.Y * qR.W + qL.Z * qR.X - qL.X * qR.Z;
Result.Z := qL.W * qR.Z + qL.Z * qR.W + qL.X * qR.Y - qL.Y * qR.X;
End;
{$IFDEF SSE}
{$IFDEF BENCHMARK}
Procedure Quaternion.NormalizeSSE; Register;
{$ELSE}
Procedure Quaternion.Normalize; Register;
{$ENDIF}
Asm
movups xmm0, [eax]
movaps xmm2, xmm0 // store copy of the vector
mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y), sqr(z), sqr(w))
movaps xmm1, xmm0
movaps xmm3, xmm0
shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y), sqr(y), sqr(y))
addps xmm1, xmm0 // add both
shufps xmm0, xmm0, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z), sqr(z))
addps xmm0, xmm1 // sum x + y + z
shufps xmm3, xmm3, 0FFh // xmm2 = (sqr(w), sqr(w), sqr(w), sqr(w))
addps xmm0, xmm3 // sum all
shufps xmm0, xmm0, 0h // broadcast length
xorps xmm1, xmm1
ucomiss xmm0, xmm1 // check for zero length
je @@END
rsqrtps xmm0, xmm0 // get reciprocal of length of vector
mulps xmm2, xmm0 // normalize
movups [eax], xmm2 // store normalized result
@@END:
End;
{$ENDIF}
{$IFDEF BENCHMARK}{$UNDEF SSE}{$ENDIF}
{$IFNDEF SSE}
Procedure Quaternion.Normalize;
Var
Len:Single;
{$IFDEF NEON_FPU}
Temp:Quaternion;
{$ENDIF}
Begin
{$IFDEF NEON_FPU}
Temp := Self;
normalize4_neon(@Temp, @Self);
{$ELSE}
Len := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z) + Sqr(W));
If (Len<=0) Then
Exit;
Len := 1.0 / Len;
X := X * Len;
Y := Y * Len;
Z := Z * Len;
W := W * Len;
{$ENDIF}
End;
{$IFDEF BENCHMARK}
{$ENDIF}
{$ENDIF}
{$IFDEF BENCHMARK}{$DEFINE SSE}{$ENDIF}
Function QuaternionSlerp(A,B:Quaternion; Const T:Single):Quaternion;
Var
Theta, Sine, Beta, Alpha:Single;
Cosine:Single;
Begin
Cosine := a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w;
Cosine := Abs(Cosine);
If ((1-cosine)>Epsilon) Then
Begin
Theta := ArcCos(cosine);
Sine := Sin(theta);
Beta := Sin((1-t)*theta) / sine;
Alpha := Sin(t*theta) / sine;
End Else
Begin
Beta := (1.0 - T);
Alpha := T;
End;
Result.X := A.X * Beta + B.X * Alpha;
Result.Y := A.Y * Beta + B.Y * Alpha;
Result.Z := A.Z * Beta + B.Z * Alpha;
Result.W := A.W * Beta + B.W * Alpha;
End;
Procedure Quaternion.Add(Const B:Quaternion);
Begin
X := X + B.X;
Y := Y + B.Y;
Z := Z + B.Z;
End;
Procedure Quaternion.Subtract(Const B:Quaternion);
Begin
X := X - B.X;
Y := Y - B.Y;
Z := Z - B.Z;
End;
Function QuaternionAdd(Const A,B:Quaternion):Quaternion;
Begin
With Result Do
Begin
X := A.X + B.X;
Y := A.Y + B.Y;
Z := A.Z + B.Z;
End;
End;
Function QuaternionScale(Const Q:Quaternion; Const Scale:Single):Quaternion;
Begin
With Result Do
Begin
X := Q.X * Scale;
Y := Q.Y * Scale;
Z := Q.Z * Scale;
End;
End;
Function QuaternionFromBallPoints(Const arcFrom,arcTo:Vector3D):Quaternion;
Begin
Result.X := arcFrom.Y * arcTo.Z - arcFrom.Z * arcTo.Y;
Result.Y := arcFrom.Z * arcTo.X - arcFrom.X * arcTo.Z;
Result.Z := arcFrom.X * arcTo.Y - arcFrom.Y * arcTo.X;
Result.W := arcFrom.X * arcTo.X + arcFrom.Y * arcTo.Y + arcFrom.Z * arcTo.Z;
End;
Procedure QuaternionToBallPoints(Q:Quaternion; Var arcFrom,arcTo:Vector3D);
Var
S:Single;
Begin
S := Sqrt(Sqr(Q.X) + Sqr(Q.Y));
If s=0 Then
arcFrom:=VectorCreate(0.0, 1.0, 0.0)
Else
arcFrom:=VectorCreate(-Q.Y/S, Q.X/S, 0.0);
arcTo.X := (Q.W * arcFrom.X) - (Q.Z * arcFrom.Y);
arcTo.Y := (Q.W * arcFrom.Y) + (Q.Z * arcFrom.X);
arcTo.Z := (Q.X * arcFrom.Y) - (Q.Y * arcFrom.X);
If Q.W<0.0 Then
arcFrom := VectorCreate(-arcFrom.X, -arcFrom.Y, 0.0);
End;
Function QuaternionConjugate(Const Q:Quaternion):Quaternion;
Begin
Result.X := -Q.X;
Result.Y := -Q.Y;
Result.Z := -Q.Z;
Result.W := Q.W;
End;
Function QuaternionNorm(Const Q:Quaternion):Single;
Begin
Result := (Q.W*Q.W)+(Q.Z*Q.Z)+(Q.Y*Q.Y)+(Q.X*Q.X);
End;
Function QuaternionInverse(Const Q:Quaternion):Quaternion;
Var
N:Single;
Begin
Result := QuaternionConjugate(Q);
N := QuaternionNorm(Result);
Result.X := Result.X/N;
Result.Y := Result.Y/N;
Result.Z := Result.Z/N;
Result.W := Result.W/N;
End;
{$IFDEF SSE}
{$IFDEF BENCHMARK}
Procedure Quaternion.TransformSSE(Const M:Matrix4x4); Register;
{$ELSE}
Procedure Quaternion.Transform(Const M:Matrix4x4); Register;
{$ENDIF}
Asm
// copy vector, Matrix4x4 and result vector to registers
mov ecx, eax
mov edx, M
movups xmm4, [edx]
movups xmm5, [edx+$10]
movups xmm6, [edx+$20]
movups xmm7, [edx+$30]
// calc x * m_1X
movss xmm0, [ecx]
shufps xmm0, xmm0, 0
//mulps xmm0, [edx]
mulps xmm0, xmm4
// calc y * m_2X
movss xmm1, [ecx+4]
shufps xmm1, xmm1, 0
//mulps xmm1, [edx+16]
mulps xmm1, xmm5
// calc z * m_3X
movss xmm2, [ecx+8]
shufps xmm2, xmm2, 0
//mulps xmm2, [edx+32]
mulps xmm2, xmm6
// calc w * m_3X
movss xmm3, [ecx+12]
shufps xmm3, xmm3, 0
//mulps xmm3, [edx+48]
mulps xmm3, xmm7
// calc final result
addps xmm0, xmm1
addps xmm2, xmm3
addps xmm0, xmm2
// save result
movups [eax], xmm0
End;
{$ENDIF}
{$IFDEF BENCHMARK}{$UNDEF SSE}{$ENDIF}
{$IFNDEF SSE}
Procedure Quaternion.Transform(Const M:Matrix4x4); {$IFDEF FPC}Inline;{$ENDIF}
Var
QX,QY,QZ,QW:Single;
{$IFDEF NEON_FPU}
Temp:Quaternion;
{$ENDIF}
Begin
{$IFDEF NEON_FPU}
Temp := Self;
matvec4_neon(@M,@Temp,@Self);
{$ELSE}
QX := X;
QY := Y;
QZ := Z;
QW := W;
X := QX*M.V[0] + QY*M.V[4] + QZ*M.V[8] + QW*M.V[12];
Y := QX*M.V[1] + QY*M.V[5] + QZ*M.V[9] + QW*M.V[13];
Z := QX*M.V[2] + QY*M.V[6] + QZ*M.V[10] + QW*M.V[14];
W := QX*M.V[3] + QY*M.V[7] + QZ*M.V[11] + QW*M.V[15];
{$ENDIF}
End;
{$ENDIF}
//! converts from a normalized axis - angle pair rotation to a Quaternion
Function QuaternionFromAxisAngle(Const Axis:Vector3D; Const Angle:Single):Quaternion;
Var
S:Single;
Begin
S := Sin(Angle/2);
Result.X := Axis.X * S;
Result.Y := Axis.Y * S;
Result.Z := Axis.Z * S;
Result.W := Cos(angle/2);
End;
Function QuaternionToEuler(Const Q:Quaternion):Vector3D;
Var
sqx, sqy, sqz:Single;
Begin
{ Result.X := Atan2(2 * q.Y * q.W - 2 * q.X * q.Z,
1 - 2* Pow(q.Y, 2) - 2*Pow(q.Z, 2) );
Result.Y := Arcsin(2*q.X*q.Y + 2*q.Z*q.W);
Result.Z := Atan2(2*q.X*q.W-2*q.Y*q.Z,
1 - 2*Pow(q.X, 2) - 2*Pow(q.Z, 2) );
If (q.X*q.Y + q.Z*q.W = 0.5) Then
Begin
Result.X := (2 * Atan2(q.X,q.W));
Result.Z := 0;
End Else
If (q.X*q.Y + q.Z*q.W = -0.5) Then
Begin
Result.X := (-2 * Atan2(q.X, q.W));
Result.Z := 0;
End;}
sqx := Sqr(Q.X);
sqy := Sqr(Q.Y);
sqz := Sqr(Q.Z);
Result.x := atan2(2 * (Q.z*Q.y + Q.x*Q.W), 1 - 2*(sqx + sqy));
Result.y := arcsin(-2 * (Q.x*Q.z - Q.y*Q.W));
Result.z := atan2(2 * (Q.x*Q.y + Q.z*Q.W), 1 - 2*(sqy + sqz));
End;
End.
|
unit ce_miniexplorer;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, FileUtil, ListFilterEdit, Forms, Controls, Graphics,
ExtCtrls, Menus, ComCtrls, Buttons, lcltype, strutils, ce_widget,
ce_common, ce_interfaces, ce_observer, ce_writableComponent;
type
TCEMiniExplorerOptions = class(TWritableLfmTextComponent)
private
fFavoriteFolders: TStringList;
fSplitter1Position: integer;
fSplitter2Position: integer;
fLastFolder: string;
procedure setFavoriteFolders(aValue: TStringList);
published
property splitter1Position: integer read fSplitter1Position write fSplitter1Position;
property splitter2Position: integer read fSplitter2Position write fSplitter2Position;
property lastFolder: string read fLastFolder write fLastFolder;
property favoriteFolders: TStringList read fFavoriteFolders write setFavoriteFolders;
public
constructor create(aOwner: TComponent); override;
destructor destroy; override;
procedure assign(aValue: TPersistent); override;
procedure assignTo(aValue: TPersistent); override;
end;
TCEMiniExplorerWidget = class(TCEWidget)
btnAddFav: TBitBtn;
btnEdit: TBitBtn;
btnShellOpen: TBitBtn;
btnRemFav: TBitBtn;
imgList: TImageList;
lstFilter: TListFilterEdit;
lstFiles: TListView;
lstFav: TListView;
Panel1: TPanel;
Panel2: TPanel;
Splitter1: TSplitter;
Splitter2: TSplitter;
Tree: TTreeView;
procedure btnEditClick(Sender: TObject);
procedure btnShellOpenClick(Sender: TObject);
procedure btnAddFavClick(Sender: TObject);
procedure btnRemFavClick(Sender: TObject);
procedure lstFilesDblClick(Sender: TObject);
procedure Panel1Click(Sender: TObject);
private
fFavorites: TStringList;
fLastFold: string;
procedure lstFavDblClick(Sender: TObject);
procedure updateFavorites;
procedure treeSetRoots;
procedure lstFilesFromTree;
procedure treeScanSubFolders(aRoot: TTreeNode);
procedure treeClick(sender: TObject);
procedure treeChanged(Sender: TObject; Node: TTreeNode);
procedure treeExpanding(Sender: TObject; Node: TTreeNode; var allow: boolean);
procedure treeDeletion(Sender: TObject; Item: TTreeNode);
procedure treeSelectionChanged(sender: TObject);
procedure favStringsChange(sender: TObject);
procedure fillLstFiles(const aList: TStrings);
procedure lstDeletion(Sender: TObject; Item: TListItem);
procedure lstFavSelect(Sender: TObject; Item: TListItem; Selected: Boolean);
procedure shellOpenSelected;
procedure lstFilterChange(sender: TObject);
public
constructor create(aIwner: TComponent); override;
destructor destroy; override;
//
procedure expandPath(aPath: string);
end;
implementation
{$R *.lfm}
const
OptsFname = 'miniexplorer.txt';
{$REGION TCEMiniExplorerOptions ------------------------------------------------}
constructor TCEMiniExplorerOptions.create(aOwner: TComponent);
begin
inherited;
fFavoriteFolders := TStringList.Create;
end;
destructor TCEMiniExplorerOptions.destroy;
begin
fFavoriteFolders.Free;
inherited;
end;
procedure TCEMiniExplorerOptions.assign(aValue: TPersistent);
var
widg: TCEMiniExplorerWidget;
begin
if aValue is TCEMiniExplorerWidget then
begin
widg := TCEMiniExplorerWidget(aValue);
fFavoriteFolders.Assign(widg.fFavorites);
fLastFolder := widg.fLastFold;
fSplitter1Position := widg.Splitter1.GetSplitterPosition;
fSplitter2Position := widg.Splitter2.GetSplitterPosition;
end
else inherited;
end;
procedure TCEMiniExplorerOptions.assignTo(aValue: TPersistent);
var
widg: TCEMiniExplorerWidget;
begin
if aValue is TCEMiniExplorerWidget then
begin
widg := TCEMiniExplorerWidget(aValue);
widg.fFavorites.Assign(fFavoriteFolders);
widg.fLastFold:=fLastFolder;
widg.Splitter1.SetSplitterPosition(fSplitter1Position);
widg.Splitter2.SetSplitterPosition(fSplitter2Position);
widg.updateFavorites;
if DirectoryExists(widg.fLastFold) then
widg.expandPath(fLastFolder);
end
else inherited;
end;
procedure TCEMiniExplorerOptions.setFavoriteFolders(aValue: TStringList);
begin
fFavoriteFolders.Assign(aValue);
end;
{$ENDREGION}
{$REGION Standard Comp/Obj------------------------------------------------------}
constructor TCEMiniExplorerWidget.create(aIwner: TComponent);
var
png: TPortableNetworkGraphic;
fname: string;
begin
inherited;
//
png := TPortableNetworkGraphic.Create;
try
png.LoadFromLazarusResource('folder_add');
btnAddFav.Glyph.Assign(png);
png.LoadFromLazarusResource('folder_delete');
btnRemFav.Glyph.Assign(png);
png.LoadFromLazarusResource('flash');
btnShellOpen.Glyph.Assign(png);
png.LoadFromLazarusResource('pencil');
btnEdit.Glyph.Assign(png);
finally
png.Free;
end;
//
fFavorites := TStringList.Create;
fFavorites.onChange := @favStringsChange;
lstFiles.OnDeletion := @lstDeletion;
lstFav.OnDeletion := @lstDeletion;
lstFav.OnSelectItem := @lstFavSelect;
lstFav.OnDblClick := @lstFavDblClick;
//
Tree.OnClick := @treeClick;
Tree.OnChange := @treeChanged;
Tree.OnDeletion := @treeDeletion;
Tree.OnSelectionChanged := @treeSelectionChanged;
Tree.OnExpanding := @treeExpanding;
//
lstFilter.FilteredListbox := nil;
lstFilter.onChange := @lstFilterChange;
//
treeSetRoots;
//
fname := getCoeditDocPath + OptsFname;
if fileExists(fname) then with TCEMiniExplorerOptions.create(nil) do
try
loadFromFile(fname);
assignTo(self);
finally
free;
end;
end;
destructor TCEMiniExplorerWidget.destroy;
begin
with TCEMiniExplorerOptions.create(nil) do
try
assign(self);
saveToFile(getCoeditDocPath + OptsFname);
finally
free;
end;
//
fFavorites.Free;
inherited;
end;
procedure TCEMiniExplorerWidget.lstDeletion(Sender: TObject; Item: TListItem);
begin
if Item.Data <> nil then
DisposeStr(PString(Item.Data));
end;
{$ENDREGION}
{$REGION Favorites -------------------------------------------------------------}
procedure TCEMiniExplorerWidget.favStringsChange(sender: TObject);
begin
updateFavorites;
end;
procedure TCEMiniExplorerWidget.updateFavorites;
var
itm: TListItem;
fold: string;
dat: PString;
begin
lstFav.Clear;
for fold in fFavorites do
begin
itm := lstFav.Items.Add;
itm.Caption := shortenPath(fold);
dat := NewStr(fold);
itm.Data := dat;
itm.ImageIndex := 2;
end;
end;
procedure TCEMiniExplorerWidget.lstFavSelect(Sender: TObject; Item: TListItem; Selected: Boolean);
var
lst: TStringList;
begin
if not Selected then exit;
//
fLastFold := PString(Item.Data)^;
lst := TStringList.Create;
try
lstFiles.Items.Clear;
listFiles(lst, fLastFold);
fillLstFiles(lst);
finally
lst.Free;
end;
end;
procedure TCEMiniExplorerWidget.btnRemFavClick(Sender: TObject);
var
i: Integer;
begin
if lstFav.Selected = nil then exit;
i := fFavorites.IndexOf(PString(lstFav.Selected.Data)^);
if i <> -1 then fFavorites.Delete(i);
lstFiles.Clear;
end;
procedure TCEMiniExplorerWidget.btnAddFavClick(Sender: TObject);
begin
if Tree.Selected = nil then exit;
fFavorites.Add(PString(Tree.Selected.Data)^);
end;
procedure TCEMiniExplorerWidget.lstFavDblClick(Sender: TObject);
begin
if lstFav.Selected = nil then exit;
lstFiles.Items.Clear;
expandPath(lstFav.Selected.Caption);
end;
{$ENDREGION}
{$REGION Files -----------------------------------------------------------------}
procedure TCEMiniExplorerWidget.fillLstFiles(const aList: TStrings);
var
itm: TListItem;
fname, itemText: string;
dat: PString;
noFilter: boolean;
begin
noFilter := lstFilter.Filter = '';
lstFiles.Clear;
lstFiles.BeginUpdate;
for fname in aList do
begin
itemText := extractFileName(fname);
if noFilter or AnsiContainsText(itemText,lstFilter.Filter) then
begin
itm := lstFiles.Items.Add;
itm.Caption := itemText;
dat := NewStr(fname);
itm.Data := dat;
itm.ImageIndex := 0;
end;
end;
lstFiles.EndUpdate;
end;
procedure TCEMiniExplorerWidget.btnShellOpenClick(Sender: TObject);
begin
shellOpenSelected;
end;
procedure TCEMiniExplorerWidget.btnEditClick(Sender: TObject);
var
fname: string;
begin
if lstFiles.Selected = nil then exit;
if lstFiles.Selected.Data = nil then exit;
fname := PString(lstFiles.Selected.Data)^;
if not fileExists(fname) then exit;
getMultiDocHandler.openDocument(fname);
end;
procedure TCEMiniExplorerWidget.lstFilesDblClick(Sender: TObject);
begin
shellOpenSelected;
end;
procedure TCEMiniExplorerWidget.Panel1Click(Sender: TObject);
begin
end;
procedure TCEMiniExplorerWidget.shellOpenSelected;
var
fname: string;
begin
if lstFiles.Selected = nil then exit;
if lstFiles.Selected.Data = nil then exit;
fname := PString(lstFiles.Selected.Data)^;
if not fileExists(fname) then exit;
if not shellOpen(fname) then getMessageDisplay.message(
(format('the shell failed to open "%s"', [shortenPath(fname, 25)])),
nil, amcMisc, amkErr);
end;
procedure TCEMiniExplorerWidget.lstFilterChange(sender: TObject);
begin
lstFilesFromTree;
end;
{$ENDREGION}
{$REGION Tree ------------------------------------------------------------------}
procedure TCEMiniExplorerWidget.treeDeletion(Sender: TObject; Item: TTreeNode);
begin
if Item.Data <> nil then
DisposeStr(PString(Item.Data));
end;
procedure TCEMiniExplorerWidget.treeSetRoots;
var
drv: string;
itm: TTreeNode;
lst: TStringList;
begin
Tree.Items.Clear;
lst := TStringList.Create;
try
listDrives(lst);
for drv in lst do
begin
itm := Tree.Items.Add(nil, drv);
itm.Data := NewStr(drv[1..length(drv)-1]);
treeScanSubFolders(itm);
end;
finally
lst.Free;
end;
end;
procedure TCEMiniExplorerWidget.lstFilesFromTree;
var
lst: TStringList;
pth: string;
begin
if Tree.Selected = nil then exit;
//
lst := TStringList.Create;
try
pth := PString(Tree.Selected.Data)^;
fLastFold := pth;
listFiles(lst, pth);
fillLstFiles(lst);
finally
lst.Free;
end;
end;
procedure TCEMiniExplorerWidget.treeScanSubFolders(aRoot: TTreeNode);
var
lst: TStringList;
fold: string;
itm: TTreeNode;
begin
aRoot.DeleteChildren; // delete the fake item...
lst := TStringList.Create;
try
listFolders(lst, PString(aRoot.Data)^ + directorySeparator);
for fold in lst do
begin
itm := Tree.Items.AddChild(aRoot, extractFileName(fold));
itm.Data := NewStr(fold);
itm.ImageIndex := 1;
itm.SelectedIndex := 1;
//
if hasFolder(fold) then
Tree.Items.AddChild(itm, ''); //...created here to show the expander glyph
end;
finally
lst.Free;
end;
end;
procedure TCEMiniExplorerWidget.treeExpanding(Sender: TObject; Node: TTreeNode; var allow: boolean);
begin
if Node <> nil then
treeScanSubFolders(Node);
allow := true;
end;
procedure TCEMiniExplorerWidget.treeChanged(Sender: TObject; Node: TTreeNode);
begin
if Node = nil then exit;
Node.DeleteChildren;
treeScanSubFolders(Node);
lstFilesFromTree;
end;
procedure TCEMiniExplorerWidget.treeSelectionChanged(sender: TObject);
begin
lstFilesFromTree;
end;
procedure TCEMiniExplorerWidget.treeClick(sender: TObject);
begin
if Tree.Selected = nil then exit;
if Tree.Selected.Expanded then exit;
treeScanSubFolders(Tree.Selected);
end;
procedure TCEMiniExplorerWidget.expandPath(aPath: string);
var
i: NativeInt;
node : TTreeNode;
function dig(const aRoot: TTreenode): boolean;
var
i: NativeInt;
str: string;
begin
result := false;
{$IFDEF LINUX}
if (length(aPath) >= 2) and (aPath[2] <> '/') then
aPath := '/' + aPath;
{$ENDIF}
for i := 0 to aRoot.Count-1 do
begin
str := PString(aRoot.Items[i].Data)^;
if SameText(LeftStr(aPath, length(str)), str) then
begin
result := true;
Tree.Selected := aRoot.Items[i];
Tree.Selected.Expand(false);
//
if str = aPath then break;
if dig(Tree.Selected) then break;
end;
end;
end;
begin
for i := 0 to Tree.Items.Count-1 do
begin
node := Tree.Items[i];
if node.Level = 0 then
begin
node.Selected := true;
node.Expand(false);
end;
if dig(node) then break;
end;
showWidget;
end;
{$ENDREGION}
end.
|
unit uAddFieldAggregate;
interface
uses
DBClient, SysUtils;
Type
TypeFieldAggregateERROR = class(Exception);
TFieldAggregateRetorne = (ftSomar,ftMaxima,ftContar,FtMedia);
TAddFieldAggregate = class
class procedure Execute(ClientDataSet:TClientDataSet;
Const
cFieldAggregado, cFieldName:String;
Tipo:TFieldAggregateRetorne);
end;
implementation
uses
Classes,
Db;
{ TAddFieldAggregate }
class procedure TAddFieldAggregate.Execute(ClientDataSet: TClientDataSet; Const cFieldAggregado, cFieldName: String; Tipo: TFieldAggregateRetorne);
var
campos:TAggregateField;
begin
try
ClientDataSet.Active := false;
try
ClientDataSet.AggregatesActive := false;
campos := TAggregateField.Create(ClientDataSet);
Campos.FieldName := cFieldName;
Campos.Name := ClientDataSet.Name + Campos.FieldName;
Campos.Index := ClientDataSet.FieldCount;
Campos.DataSet := ClientDataSet;
Campos.Required := False;
case Tipo of
ftSomar: campos.Expression := 'Sum(' + cFieldAggregado + ')';
ftMaxima: campos.Expression := 'Max(' + cFieldAggregado + ')';
ftContar: campos.Expression := 'Count(' + cFieldAggregado + ')';
FtMedia: campos.Expression := 'Avg(' + cFieldAggregado + ')';
end;
campos.currency := true;
campos.Active := true;
ClientDataSet.AggregatesActive := true;
ClientDataSet.Active := true;
except
on E:EComponentError do
ClientDataSet.AggregatesActive := true;
on e:exception do
begin
ClientDataSet.FindField(cFieldAggregado).Free;
campos.Free;
raise TypeFieldAggregateERROR.Create('Não foi possivel a criação do campo ' + cFieldName + sLineBreak + 'mensagem Original' + sLineBreak + E.Message);
end;
end;
finally
ClientDataSet.Active:=true;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.