text stringlengths 14 6.51M |
|---|
unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.Grids,
Vcl.DBGrids, RTTIUtils, Validacoes;
type
TForm2 = class(TForm)
Edit1: TEdit;
Button1: TButton;
ListBox1: TListBox;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
Validacoes : TValidacoes;
public
{ Public declarations }
procedure ExibirResultado(aValue : String);
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
Memo1.Lines.Clear;
Validacoes.Validar(Edit1.Text);
end;
procedure TForm2.ExibirResultado(aValue: String);
begin
Memo1.Lines.Add(aValue);
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
Validacoes := TValidacoes.Create;
Validacoes
.AddValidacao('Mensagem')
.AddValidacao('ValorNulo')
.AddValidacao('CFOP')
.AddValidacao('ST')
.AddValidacao('NCM')
.ResultDisplay(ExibirResultado);
end;
procedure TForm2.FormDestroy(Sender: TObject);
begin
Validacoes.Free;
end;
end.
|
unit OptionForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TOptionFrm = class(TForm)
chkAutoRun: TCheckBox;
chkAutoPlay: TCheckBox;
procedure chkAutoRunClick(Sender: TObject);
procedure chkAutoPlayClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
OptionFrm: TOptionFrm;
implementation
{$R *.dfm}
uses Registry, MainForm, Option;
procedure TOptionFrm.chkAutoRunClick(Sender: TObject);
var Reg: TRegistry;
begin
Reg:=TRegistry.Create;
with Reg do begin
RootKey:=HKEY_LOCAL_MACHINE;
OpenKey('SOFTWARE\Microsoft\windows\CurrentVersion\Run',true);
if TCheckBox(Sender).Checked then
WriteString('MediaPlayer', '"C:\Program Files\MediaPlayer\MediaPlayer.exe"')
else DeleteValue('MediaPlayer');
CloseKey;
end;
Reg.Free;
end;
procedure TOptionFrm.chkAutoPlayClick(Sender: TObject);
begin
MainFrm.MediaPlayer1.AutoOpen:=TCheckBox(Sender).Checked;
end;
procedure TOptionFrm.FormCreate(Sender: TObject);
begin
myOption.LoadConfig(TForm(Sender));
end;
procedure TOptionFrm.FormDestroy(Sender: TObject);
begin
myOption.SaveConfig(TForm(Sender));
end;
end.
|
unit BluetoothStream;
interface
uses System.SysUtils, System.Classes;
const
kPacketLength = 512 - 1; // bytes
type
TBluetoothStreamProgressEvent = procedure(Sender: TObject; Progress: Integer; BytesProcessed: Int64) of object;
TBluetoothStreamFinishedEvent = procedure(Sender: TObject) of object;
TBluetoothStreamErrorEvent = procedure(Sender: TObject) of object;
TBluetoothStream = class
protected
FLastPosition: Int64;
FStarted: Boolean;
FStream: TStream;
FOnBluetoothStreamProgressEvent: TBluetoothStreamProgressEvent;
function CalculatePacketLength: Integer;
public
constructor Create(AStream: TStream); overload; virtual;
function GetProgress: Integer;
function GetBytesProcessed: Int64;
function GetFinished: Boolean;
procedure Reset;
property Stream: TStream read FStream;
property Finished: Boolean read GetFinished;
property Progress: Integer read GetProgress;
property BytesProcessed: Int64 read GetBytesProcessed;
property OnBluetoothStreamProgressEvent: TBluetoothStreamProgressEvent read FOnBluetoothStreamProgressEvent
write FOnBluetoothStreamProgressEvent;
end;
TBluetoothStreamSender = class(TBluetoothStream)
public
function CreatePacket: TBytes;
function CreateHeaderPacket: TBytes;
function CreateDataPacket: TBytes;
end;
TBluetoothStreamReceiver = class(TBluetoothStream)
public
procedure ProcessPacket(const Packet: TBytes);
procedure ProcessHeaderPacket(const Packet: TBytes);
procedure ProcessDataPacket(const Packet: TBytes);
end;
implementation
{ TStreamPacket }
procedure TBluetoothStreamReceiver.ProcessDataPacket(const Packet: TBytes);
begin
FStream.Write(Packet[1], CalculatePacketLength);
end;
procedure TBluetoothStreamReceiver.ProcessHeaderPacket(const Packet: TBytes);
var
Size: Int64;
begin
Move(Packet[1], Size, SizeOf(Size));
FStream.Position := 0;
FStream.Size := Size;
FStarted := True;
end;
procedure TBluetoothStreamReceiver.ProcessPacket(const Packet: TBytes);
var
PacketLength: Integer;
Buffer: TBytes;
Size: Int64;
begin
if (Packet = nil) or (Length(Packet) = 0) then
Exit;
FLastPosition := FStream.Position;
case Packet[0] of
0: ProcessHeaderPacket(Packet);
1: ProcessDataPacket(Packet);
end;
if Assigned(FOnBluetoothStreamProgressEvent) then
FOnBluetoothStreamProgressEvent(Self, Progress, BytesProcessed);
end;
{ TStreamSender }
function TBluetoothStream.CalculatePacketLength: Integer;
begin
if (FStream.Size >= (FStream.Position + kPacketLength)) then
Result := kPacketLength
else
Result := FStream.Size - FStream.Position;
end;
constructor TBluetoothStream.Create(AStream: TStream);
begin
FStream := AStream;
end;
function TBluetoothStreamSender.CreateDataPacket: TBytes;
var
PacketLength: Integer;
begin
PacketLength := CalculatePacketLength;
SetLength(Result, PacketLength + 1);
Result[0] := 1;
FStream.Read(Result[1], PacketLength);
end;
function TBluetoothStreamSender.CreateHeaderPacket: TBytes;
var
Size: Int64;
begin
FStream.Position := 0;
Size := FStream.Size;
SetLength(Result, SizeOf(Byte) + SizeOf(Int64));
Result[0] := 0;
Move(Size, Result[1], SizeOf(Int64));
FStarted := True;
end;
function TBluetoothStreamSender.CreatePacket: TBytes;
begin
FLastPosition := FStream.Position;
if not FStarted then
Result := CreateHeaderPacket
else
Result := CreateDataPacket;
if Assigned(FOnBluetoothStreamProgressEvent) then
FOnBluetoothStreamProgressEvent(Self, Progress, BytesProcessed);
end;
function TBluetoothStream.GetBytesProcessed: Int64;
begin
Result := Stream.Position;
end;
function TBluetoothStream.GetFinished: Boolean;
begin
if not FStarted then
Result := False
else
Result := FStream.Position = FStream.Size;
end;
function TBluetoothStream.GetProgress: Integer;
begin
if FStream.Size = 0 then
Result := 0
else
Result := Round((FStream.Position + 1) / FStream.Size * 100);
end;
procedure TBluetoothStream.Reset;
begin
FStarted := False;
end;
end.
|
unit viewer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ToolWin, ComCtrls, StdCtrls;
const
defaultBufferSize = 65536;
type
TfViewer = class(TForm)
CoolBar1: TCoolBar;
ToolBar1: TToolBar;
tbWordWrap: TToolButton;
pContainer: TPanel;
memText: TMemo;
sbText: TScrollBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
eFont: TEdit;
bFontSelect: TButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure ToolButton2Click(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
Stream : TStream;
Buffer : PChar;
BufferSize : integer;
FileSize : integer;
procedure setBuffer;
procedure go(offset:integer);
public
procedure initFile(const path:string);
end;
procedure ViewFile(const path:string);
implementation
{$R *.dfm}
procedure ViewFile;
var
F:TfViewer;
begin
Screen.Cursor := crHourGlass;
Application.CreateForm(TfViewer,F);
try
F.Caption := 'Viewer - '+path;
F.InitFile(path);
F.Show;
except
F.Free;
end;
Screen.Cursor := crDefault;
end;
{ TfViewer }
procedure TfViewer.FormCreate(Sender: TObject);
begin
pContainer.DoubleBuffered := true;
eFont.Text := memText.Font.Name;
end;
procedure TfViewer.setBuffer;
var
s:string;
begin
SetLength(s,bufferSize);
Move(Buffer^,s[1],BufferSize);
memText.Text := s;
end;
procedure TfViewer.go;
begin
Stream.Position := offset;
BufferSize := defaultBufferSize;
if BufferSize > FileSize-offset then BufferSize := FileSize-offset;
Stream.Read(Buffer^,BufferSize);
setBuffer;
end;
procedure TfViewer.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfViewer.FormDestroy(Sender: TObject);
begin
if Stream <> NIL then Stream.Free;
if Buffer <> NIL then FreeMem(buffer);
end;
procedure TfViewer.initFile(const path: string);
begin
Stream := TFileStream.Create(path,fmOpenRead);
GetMem(Buffer,defaultBufferSize);
FileSize := Stream.Size;
go(0);
end;
procedure TfViewer.ToolButton2Click(Sender: TObject);
begin
Close;
end;
procedure TfViewer.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then Close;
end;
end.
|
(*
* iocp 关闭线程、业务线程、推送线程等
*)
unit iocp_threads;
interface
{$I in_iocp.inc} // 模式设置
uses
{$IFDEF DELPHI_XE7UP}
Winapi.Windows, System.Classes, System.SysUtils, Winapi.ActiveX, {$ELSE}
Windows, Classes, SysUtils, ActiveX, {$ENDIF}
iocp_base, iocp_lists, iocp_objPools,
iocp_winSock2, iocp_baseObjs, iocp_sockets,
iocp_managers, iocp_msgPacks, iocp_senders;
type
// ===================== 专门关闭 Socket 的线程 =====================
TCloseSocketThread = class(TCycleThread)
private
FLock: TThreadLock; // 锁
FSockets: TInList; // 可以删首节点的列表
protected
procedure AfterWork; override;
procedure DoThreadMethod; override;
public
constructor Create;
procedure AddSocket(const Socket: TBaseSocket);
procedure WaitFor; // 覆盖
end;
// ===================== 执行业务的线程 =====================
TBusiWorkManager = class;
TBusiThread = class(TCycleThread)
private
FManager: TBusiWorkManager; // 管理器
FSender: TServerTaskSender; // 任务发送器(引用)
FSocket: TBaseSocket; // 当前套接字对象
FWorker: TBusiWorker; // 任务执行者(引用)
protected
procedure AfterWork; override;
procedure DoThreadMethod; override;
public
constructor Create(AManager: TBusiWorkManager);
end;
// ===================== 业务线程调度管理 =====================
TBusiWorkManager = class(TObject)
private
FServer: TObject; // TInIOCPServer
FSemaphore: THandle; // 线程共享的信号灯
// 线程数组
FThreads: Array of TBusiThread;
FThreadCount: Integer; // 线程数
FLock: TThreadLock; // 管理器锁
FSockets: TInList; // 可以删首节点的主列表(可能很大)
FBackSockets: TInList; // 备用列表(可能很大,增删数模时用)
FCurrentList: TInList; // 引用 FSockets/FBackSockets
FActiveCount: Integer; // 类别任务数
FActiveThreadCount: Integer; // 活动线程数
FWorkTotalCount: IOCP_LARGE_INTEGER; // 已执行的任务总数
function CreateWorker(Index: Integer): TBusiWorker;
function GetDataModuleState(Index: Integer): Boolean;
function GetWork(var Socket: TObject): Boolean;
procedure InternalAddRemove(Index: Integer; AddMode: Boolean);
procedure InternalStop;
public
constructor Create(AServer: TObject; AThreadCount: Integer);
destructor Destroy; override;
procedure AddWork(Socket: TObject; Activate: Boolean = True);
procedure AddDataModule(Index: Integer);
procedure RemoveDataModule(Index: Integer);
procedure StopThreads;
procedure WaitFor;
public
property ActiveCount: Integer read FActiveCount;
property ActiveThreadCount: Integer read FActiveThreadCount;
property DataModuleState[Index: Integer]: Boolean read GetDataModuleState;
property WorkTotalCount: IOCP_LARGE_INTEGER read FWorkTotalCount;
end;
// ===================== 推送对象/任务 =====================
TPushMessage = class(TInList)
private
FObjPool: TIOCPSocketPool; // 对象池
FBufPool: TIODataPool; // 内存池
FPushBuf: PPerIOData; // 待推送消息
FCastType: TBroadcastType; // 广播目的类型
FGroup: String; // 客户端分组
FIngoreSocket: TObject; // 忽略广播的 TIOCPSocketPool
FClientCount: Integer; // 估计广播目的数
FTickCount: Cardinal; // 加入时间毫秒
public
constructor Create(Msg: PPerIOData; BroadcastType: TBroadcastType = btUnknown); overload;
constructor Create(ASocketPool: TIOCPSocketPool; ABufferPool: TIODataPool;
BroadcastType: TBroadcastType = btUnknown; MsgSize: Cardinal = 0); overload;
constructor Create(Socket: TBaseSocket; IOKind: TIODataType; MsgSize: Cardinal); overload;
destructor Destroy; override;
public
procedure UpdateMsgId;
procedure WriteWebSocketMsg(OpCode: TWSOpCode; Buffer: PAnsiChar; Size: Integer);
public
property IngoreSocket: TObject read FIngoreSocket write FIngoreSocket;
property PushBuf: PPerIOData read FPushBuf;
property Group: String read FGroup write FGroup;
end;
// ===================== 消息推送线程 =====================
TPushMsgManager = class;
TPushThread = class(TCycleThread)
private
FBusiManager: TBusiWorkManager; // 业务管理器
FPushManager: TPushMsgManager; // 推送管理器
FMsg: TPushMessage; // 当前待推送消息
FSocket: TBaseSocket; // 当前套接字对象
procedure PushMesssage;
protected
procedure AfterWork; override;
procedure DoThreadMethod; override;
public
constructor Create(APushManager: TPushMsgManager; ABusiManager: TBusiWorkManager);
end;
// ===================== 推送消息缓冲池 =====================
// 1. 推送时在业务线程,Socket 资源被占用,如果直接投放时
// 会引起推送线程争抢不到资源,做大量无用功。
// 2. 先把消息投放到缓冲池,每隔一定时间加入推送队列。
TMsgPushPool = class(TBaseThread)
private
FLock: TThreadLock; // 消息锁
FManager: TPushMsgManager; // 管理器
FMsgList: TInList; // 推送消息池
procedure InterAdd(Msg: TPushMessage);
protected
procedure ExecuteWork; override;
public
constructor Create(AManager: TPushMsgManager);
destructor Destroy; override;
end;
// ===================== 消息推送线程管理 =====================
TPushMsgManager = class(TObject)
private
FSemaphore: THandle; // 线程信号灯
FWaitSemaphore: THandle; // 线程等待信号灯
// 线程数组
FThreads: array of TPushThread;
FThreadCount: Integer; // 线程数
FLock: TThreadLock; // 管理器锁
FPushPool: TMsgPushPool; // 推送消息池
FMsgList: TInList; // 推送消息列表
FActiveCount: Integer; // 推送列表任务数
FActiveThreadCount: Integer; // 活动的推送线程数
FPushMsgCount: Integer; // 消息总数(估算)
// 速度控制
FMaxPushCount: Integer; // 允许每秒最大推送消息数
FNowTickCount: Cardinal; // 当前毫秒时间
FTickCount: Cardinal; // 旧的毫秒时间
FPushCountPS: Integer; // 每秒加入的消息数
function GetWork(var Msg: TPushMessage): Boolean;
procedure ActivateThreads;
procedure InterAdd(Msg: TPushMessage);
public
constructor Create(ABusiManger: TBusiWorkManager; AThreadCount, AMaxPushCount: Integer);
destructor Destroy; override;
function AddWork(Msg: TPushMessage): Boolean;
procedure StopThreads;
procedure WaitFor;
public
property ActiveCount: Integer read FActiveCount;
property ActiveThreadCount: Integer read FActiveThreadCount;
property PushMsgCount: Integer read FPushMsgCount;
end;
implementation
uses
iocp_api, iocp_Server,
iocp_log, iocp_utils, http_objects;
type
TBaseSocketRef = class(TBaseSocket);
{ TCloseSocketThread }
procedure TCloseSocketThread.AddSocket(const Socket: TBaseSocket);
begin
// 加入要关闭的 Socket
FLock.Acquire;
try
FSockets.Add(Socket);
finally
FLock.Release;
end;
Activate; // 激活
end;
procedure TCloseSocketThread.AfterWork;
begin
FLock.Free;
FSockets.Free; // 释放节点空间即可, 对象由池释放
end;
constructor TCloseSocketThread.Create;
begin
inherited Create;
FLock := TThreadLock.Create;
FSockets := TInList.Create;
end;
procedure TCloseSocketThread.DoThreadMethod;
var
Socket: TBaseSocket;
begin
while (Terminated = False) do
begin
FLock.Acquire;
try
Socket := FSockets.PopFirst; // 取第一个并删除
if (Socket = nil) then
Exit;
finally
FLock.Release;
end;
try
Socket.Close; // 释放资源
finally
Socket.ObjPool.Push(Socket.LinkNode); // 压入池,下次不用新建
end;
end;
end;
procedure TCloseSocketThread.WaitFor;
begin
// 等待全部 Socket 关闭完毕
while (FSockets.Count > 0) do
Sleep(10);
end;
{ TBusiThread }
procedure TBusiThread.AfterWork;
begin
// 启用线程数 -1
InterlockedDecrement(FManager.FThreadCount);
FSender.FreeBuffers(TInIOCPServer(FManager.FServer).IODataPool); // 释放发送缓存
FSender.Free;
end;
constructor TBusiThread.Create(AManager: TBusiWorkManager);
begin
inherited Create(False); // 引用信号灯
FManager := AManager;
FSemaphore := FManager.FSemaphore; // 引用
FSender := TServerTaskSender.Create(TInIOCPServer(FManager.FServer).IODataPool);
end;
procedure TBusiThread.DoThreadMethod;
begin
// 取列表第一个 Socket,执行
while (Terminated = False) and
FManager.GetWork(TObject(FSocket)) do
case TBaseSocketRef(FSocket).Lock(False) of // 加锁,非推送模式
SOCKET_LOCK_OK: begin // 加锁成功
InterlockedIncrement(FManager.FActiveThreadCount); // 活动业务线程+
try
TBaseSocketRef(FSocket).DoWork(FWorker, FSender) // 传递 FWorker, FSender
finally
InterlockedDecrement(FManager.FActiveThreadCount); // 活动业务线程-
{$IFDEF WIN_64}
System.AtomicIncrement(FManager.FWorkTotalCount); // 执行总数+
{$ELSE}
InterlockedIncrement(FManager.FWorkTotalCount); // 执行总数+
{$ENDIF}
end;
end;
SOCKET_LOCK_FAIL: // 加锁不成功,重新加入列表,等下次!
FManager.AddWork(FSocket, False); // 不激活
else
{ 已经关闭, 放弃这个节点的 Socket } ;
end;
end;
{ TBusiWorkManager }
procedure TBusiWorkManager.AddDataModule(Index: Integer);
begin
// 新建编号为 Index 的数模(要先注册数模)
InternalAddRemove(Index, True);
end;
procedure TBusiWorkManager.AddWork(Socket: TObject; Activate: Boolean);
begin
// 工作线程调用!
// 1. 加入一个任务
FLock.Acquire;
try
FCurrentList.Add(Socket);
if (FCurrentList = FSockets) then // 未改变列表
FActiveCount := FCurrentList.Count;
finally
FLock.Release;
end;
// 2. 激活业务线程,让其取任务
if Activate and (FCurrentList = FSockets) then // 是主列表
ReleaseSemapHore(FSemaphore, 8, Nil);
end;
constructor TBusiWorkManager.Create(AServer: TObject; AThreadCount: Integer);
var
i: Integer;
Thread: TBusiThread;
begin
inherited Create;
// 每个工作线程对应一个或多个业务线程(1:n)
// 1. 共享信号灯:最大值 = MaxInt
FSemaphore := CreateSemapHore(Nil, 0, MaxInt, Nil);
// 2. 服务器、业务线程数
FServer := AServer;
FThreadCount := AThreadCount;
SetLength(FThreads, FThreadCount);
// 3. 锁、Socket 列表
FLock := TThreadLock.Create;
FSockets := TInList.Create; // 主列表
FBackSockets := TInList.Create; // 备用列表
FCurrentList := FSockets; // 引用主列表
// 4. 建业务线程、任务执行者
for i := 0 to FThreadCount - 1 do
begin
Thread := TBusiThread.Create(Self);
Thread.FWorker := CreateWorker(i);
FThreads[i] := Thread;
Thread.Resume;
end;
end;
function TBusiWorkManager.CreateWorker(Index: Integer): TBusiWorker;
begin
// 为工作线程建一个业务工作者
// 数模由 DatabaseManager 管理,在 TBusiThread.FWorker 释放
Result := TBusiWorker.Create(FServer, Index);
Result.CreateDataModules; // 建实例
end;
destructor TBusiWorkManager.Destroy;
begin
InternalStop; // 要先等待执行完毕
inherited;
end;
function TBusiWorkManager.GetDataModuleState(Index: Integer): Boolean;
begin
// 返回数模是否有实例
Result := TBusiWorker(FThreads[0].FWorker).DataModules[Index] <> nil;
end;
function TBusiWorkManager.GetWork(var Socket: TObject): Boolean;
begin
// 从主任务表弹出第一个任务
FLock.Acquire;
try
Socket := FSockets.PopFirst;
FActiveCount := FSockets.Count;
Result := (Socket <> nil);
finally
FLock.Release;
end;
end;
procedure TBusiWorkManager.InternalAddRemove(Index: Integer; AddMode: Boolean);
procedure StartBackSocketList;
begin
// 启用备用任务列表存储任务
// (AddWork 不触发业务线程)
FLock.Acquire;
try
if (FCurrentList = FSockets) then
FCurrentList := FBackSockets
else
FCurrentList := FSockets;
finally
FLock.Release;
end;
end;
procedure SetMainSocketList;
begin
// 主、备份任务列表互换
// (AddWork 触发业务线程,GetWork 从新的 FSockets 取任务)
FLock.Acquire;
try
FCurrentList := FBackSockets; // 当前引用备份
FBackSockets := FSockets; // 主 -> 备份
FSockets := FCurrentList; // 备份 -> 主
finally
FLock.Release;
end;
end;
var
i: Integer;
begin
// 删除、新建编号为 Index 的数模实例
StartBackSocketList;
try
while (FActiveThreadCount > 0) do // 等活动线程执行完毕
Sleep(10);
for i := 0 to FThreadCount - 1 do // 增/删每执行者的对应数模实例
if AddMode then
TBusiWorker(FThreads[i].FWorker).AddDataModule(Index)
else
TBusiWorker(FThreads[i].FWorker).RemoveDataModule(Index);
finally
SetMainSocketList;
end;
end;
procedure TBusiWorkManager.InternalStop;
var
i: Integer;
begin
if Assigned(FLock) then
begin
for i := 0 to FThreadCount - 1 do // 停止线程
begin
FThreads[i].FWorker.Free; // FWorker 自动释放数模
FThreads[i].Stop;
end;
while (FThreadCount > 0) do // 等待全部线程退出
begin
ReleaseSemapHore(FSemaphore, 1, Nil);
Sleep(10);
end;
SetLength(FThreads, 0);
CloseHandle(FSemaphore); // 关闭
FLock.Free;
FSockets.Free;
FBackSockets.Free;
FLock := Nil;
FSockets := nil;
FBackSockets := nil;
end;
end;
procedure TBusiWorkManager.RemoveDataModule(Index: Integer);
begin
// 删除编号为 Index 的数模实例(不改变数组 FThreads 长度)
InternalAddRemove(Index, False);
end;
procedure TBusiWorkManager.StopThreads;
begin
InternalStop;
end;
procedure TBusiWorkManager.WaitFor;
begin
// 等待活动线程结束
while (FActiveThreadCount > 0) do
Sleep(10);
end;
{ TPushMessage }
constructor TPushMessage.Create(Msg: PPerIOData; BroadcastType: TBroadcastType);
begin
inherited Create;
// 发送消息个列表的客户端,或广播
FCastType := BroadcastType;
FTickCount := GetTickCount; // 当前时间
FObjPool := TBaseSocket(Msg^.Owner).ObjPool;
FBufPool := TBaseSocket(Msg^.Owner).BufferPool;
FPushBuf := FBufPool.Pop^.Data;
FPushBuf^.IOType := ioPush; // 推送
FPushBuf^.Data.len := Msg^.Overlapped.InternalHigh; // 消息大小
FPushBuf^.Overlapped.InternalHigh := FPushBuf^.Data.len; // 消息大小
// 复制 Msg
System.Move(Msg^.Data.buf^, FPushBuf^.Data.buf^, FPushBuf^.Data.len);
end;
constructor TPushMessage.Create(ASocketPool: TIOCPSocketPool;
ABufferPool: TIODataPool; BroadcastType: TBroadcastType; MsgSize: Cardinal);
begin
inherited Create;
// 广播一条消息,在外部设置 FPushBuf 内容
FCastType := BroadcastType;
FTickCount := GetTickCount; // 当前时间
FObjPool := ASocketPool;
FBufPool := ABufferPool;
FPushBuf := FBufPool.Pop^.Data;
FPushBuf^.IOType := ioPush; // 固定 = ioPush
FPushBuf^.Data.len := MsgSize; // 内容长度
FPushBuf^.Overlapped.InternalHigh := MsgSize;
end;
constructor TPushMessage.Create(Socket: TBaseSocket; IOKind: TIODataType; MsgSize: Cardinal);
begin
inherited Create;
// 建一条给 Socket 的 IOKind 类型消息,由外部构建消息内容
FCastType := btUnknown; // 不是广播
FTickCount := GetTickCount; // 当前时间
FObjPool := Socket.ObjPool;
FBufPool := Socket.BufferPool;
FPushBuf := FBufPool.Pop^.Data;
FPushBuf^.IOType := IOKind; // 类型
FPushBuf^.Data.len := MsgSize; // 内容长度
FPushBuf^.Overlapped.InternalHigh := MsgSize;
inherited Add(Socket); // 只有一个节点
end;
destructor TPushMessage.Destroy;
begin
FBufPool.Push(FPushBuf^.Node);
inherited;
end;
procedure TPushMessage.UpdateMsgId;
var
MsgHead: PMsgHead;
begin
// 使用新的 MsgId
MsgHead := PMsgHead(FPushBuf^.Data.buf + IOCP_SOCKET_FLEN);
MsgHead^.MsgId := TSystemGlobalLock.GetMsgId;
end;
procedure TPushMessage.WriteWebSocketMsg(OpCode: TWSOpCode; Buffer: PAnsiChar; Size: Integer);
var
Data: PWsaBuf;
begin
// 写 WebSocket 协议消息
Data := @(FPushBuf^.Data);
MakeFrameHeader(Data, OpCode, Size); // 构建帧,操作:OpCode,长度:Size
System.Move(Buffer^, (Data^.buf + Data^.len)^, Size); // 加入 Buffer
Inc(Data^.len, Size);
end;
{ TPushThread }
procedure TPushThread.AfterWork;
begin
// 启用线程数 -1
InterlockedDecrement(FPushManager.FThreadCount);
end;
constructor TPushThread.Create(APushManager: TPushMsgManager; ABusiManager: TBusiWorkManager);
begin
inherited Create(False); // 引用信号灯
FBusiManager := ABusiManager;
FPushManager := APushManager;
FSemaphore := APushManager.FSemaphore; // 引用
end;
procedure TPushThread.DoThreadMethod;
var
i: Integer;
Trigger: Boolean;
begin
// 推送 TPushMessage.FPushBuf 给 TPushMessage 的列表用户
// 只要没关闭 Socket,一定要发送一次
Trigger := False;
while (Terminated = False) and FPushManager.GetWork(FMsg) do
begin
// 1. 广播,建在线客户端列表
if (FMsg.FCastType > btUnknown) then
begin
FMsg.FObjPool.GetSockets(FMsg, FMsg.FIngoreSocket,
FMsg.FCastType = btAdminOnly, FMsg.Group);
FMsg.FCastType := btUnknown; // 只取在此时间点的客户端
end;
// 2. 逐一推送
for i := 1 to FMsg.Count do
begin
FSocket := FMsg.PopFirst; // 待发目的
FMsg.FPushBuf^.Owner := FSocket;
if FSocket.Active then
PushMesssage;
end;
// 给多点机会业务线程抢 Socket 资源,等一下
WaitForSingleObject(FPushManager.FWaitSemaphore, 10);
// 3. 处理结果
if (FMsg.Count > 0) then // 未全部发出
begin
Trigger := True;
FPushManager.InterAdd(FMsg); // 再加入
Break; // 下次继续
end else
begin
Trigger := False;
FMsg.Free; // 全部发出,释放
end;
end;
if Trigger then
FPushManager.ActivateThreads;
end;
procedure TPushThread.PushMesssage;
begin
// 推送 FMsg.FPushBuf 给 FSocket
case TBaseSocketRef(FSocket).Lock(True) of
SOCKET_LOCK_OK: begin // 加锁成功
// 工作量统计到 FTotalCount
InterlockedIncrement(FPushManager.FActiveThreadCount); // 活动推送线程+
try
TBaseSocketRef(FSocket).InternalPush(FMsg.FPushBuf); // 推送
finally
InterlockedDecrement(FPushManager.FActiveThreadCount); // 活动业务线程-
{$IFDEF WIN_64}
System.AtomicIncrement(FBusiManager.FWorkTotalCount); // 执行总数+
{$ELSE}
InterlockedIncrement(FBusiManager.FWorkTotalCount); // 执行总数+
{$ENDIF}
end;
end;
SOCKET_LOCK_FAIL: // 不成功
// 可能 Socket 被关闭且再次从池取出,此时不是原来的客户端了,
// 但理论上也是一个需广播的客户端,可以接收广播消息。
FMsg.Add(FSocket); // 重新加入,等下次!
else
{ 已经关闭, 放弃这个节点的 Socket } ;
end;
end;
{ TMsgPushPool }
constructor TMsgPushPool.Create(AManager: TPushMsgManager);
begin
inherited Create(True);
FManager := AManager;
FreeOnTerminate := True;
FLock := TThreadLock.Create;
FMsgList := TInList.Create;
Resume;
end;
destructor TMsgPushPool.Destroy;
var
i: Integer;
begin
for i := 0 to FMsgList.Count - 1 do
TPushMessage(FMsgList.PopFirst).Free;
FMsgList.Free;
FLock.Free;
// FManager 的线程数计算-
InterlockedDecrement(FManager.FThreadCount);
inherited;
end;
procedure TMsgPushPool.ExecuteWork;
const
WAIT_MILLSECONDS = 50; // 毫秒数
var
i: Integer;
Trigger: Boolean;
NowTickCount: Cardinal;
Msg: TPushMessage;
function GetTickCountDiff: Boolean;
begin
if (NowTickCount >= Msg.FTickCount) then
Result := NowTickCount - Msg.FTickCount >= WAIT_MILLSECONDS // n 毫秒
else
Result := High(Cardinal) - Msg.FTickCount + NowTickCount >= WAIT_MILLSECONDS;
end;
begin
// 每 n 毫秒循环一次,
// 检查池中的消息是否要投放到推送队列。
while (Terminated = False) do
begin
Sleep(WAIT_MILLSECONDS); // 等 n 毫秒
FLock.Acquire;
try
Trigger := False;
NowTickCount := GetTickCount;
for i := 1 to FMsgList.Count do
begin
Msg := FMsgList.PopFirst;
if GetTickCountDiff then // 时差达 n 毫秒
begin
FManager.InterAdd(Msg); // 正式加入推送队列
Trigger := True;
end else
FMsgList.Add(Msg); // 重新加入
end;
if Trigger then // 激活
FManager.ActivateThreads;
finally
FLock.Release;
end;
end;
end;
procedure TMsgPushPool.InterAdd(Msg: TPushMessage);
begin
// 把消息加到缓冲列表
FLock.Acquire;
try
FMsgList.Add(Msg);
finally
FLock.Release;
end;
end;
{ TPushMsgManager }
procedure TPushMsgManager.ActivateThreads;
var
Trigger: Boolean;
begin
// 激活推送线程
FLock.Acquire;
try
Trigger := (FMsgList.Count > 0); // 有消息
finally
FLock.Release;
end;
if Trigger then
ReleaseSemapHore(FSemaphore, 8, Nil);
end;
function TPushMsgManager.AddWork(Msg: TPushMessage): Boolean;
function GetTickCountDiff: Boolean;
begin
if (FNowTickCount >= FTickCount) then
Result := FNowTickCount - FTickCount >= 1000 // 一秒
else
Result := High(Cardinal) - FTickCount + FNowTickCount >= 1000;
end;
begin
// 加入一个推送消息
// 速度控制:每秒加入的推送数超 FMaxPushCount 次,放弃!
// 出现消息堆积时,也放弃!
Result := True;
FLock.Acquire;
try
if (FMaxPushCount > 0) then
begin
if (FPushMsgCount > FMaxPushCount div 5) then // 出现消息堆积(根据设备性能调整)
Result := False
else begin
FNowTickCount := GetTickCount;
if GetTickCountDiff then // 时差 1 秒
begin
FTickCount := FNowTickCount;
Result := (FPushCountPS <= FMaxPushCount); // 没超量
FPushCountPS := 0;
end;
end;
end;
if Result then // 统计
begin
// 活动数
FActiveCount := FMsgList.Count;
// 每秒加入的消息数
Inc(FPushCountPS, Msg.FClientCount);
end;
finally
FLock.Release;
end;
if Result then
FPushPool.InterAdd(Msg) // 先加入池
else // 释放(修正)
Msg.Free;
end;
constructor TPushMsgManager.Create(ABusiManger: TBusiWorkManager; AThreadCount, AMaxPushCount: Integer);
var
i: Integer;
begin
inherited Create;
// 1. 信号灯:最大值 = MaxInt
FSemaphore := CreateSemapHore(Nil, 0, MaxInt, Nil);
FWaitSemaphore := CreateSemapHore(Nil, 0, MaxInt, Nil);
// 2. 锁、列表
FLock := TThreadLock.Create;
FPushPool := TMsgPushPool.Create(Self); // 消息池
FMsgList := TInList.Create; // 推送消息列表
// 3. 推送线程数,允许每秒最大推送数
FThreadCount := AThreadCount;
FMaxPushCount := AMaxPushCount;
SetLength(FThreads, FThreadCount);
for i := 0 to High(FThreads) do
begin
FThreads[i] := TPushThread.Create(Self, ABusiManger);
FThreads[i].Resume;
end;
// 4. 包含 FPushPool,停止时先释放 FPushPool
InterlockedIncrement(FThreadCount);
end;
destructor TPushMsgManager.Destroy;
begin
StopThreads;
inherited;
end;
function TPushMsgManager.GetWork(var Msg: TPushMessage): Boolean;
begin
// 取一个推送消息
FLock.Acquire;
try
Msg := FMsgList.PopFirst;
if (Msg = nil) then
begin
FActiveCount := 0;
Result := False;
end else
begin
FActiveCount := FMsgList.Count;
Dec(FPushMsgCount, Msg.FClientCount); // 待推送数-
Result := True;
end;
finally
FLock.Release;
end;
end;
procedure TPushMsgManager.InterAdd(Msg: TPushMessage);
begin
// 正式把消息加入推送队列
FLock.Acquire;
try
// 估算待推送数
if (Msg.FCastType > btUnknown) then
Msg.FClientCount := Msg.FObjPool.UsedCount
else
Msg.FClientCount := 1;
Inc(FPushMsgCount, Msg.FClientCount);
FMsgList.Add(Msg);
finally
FLock.Release;
end;
end;
procedure TPushMsgManager.StopThreads;
var
i: Integer;
begin
if Assigned(FLock) then
begin
// 先释放
FPushPool.Terminate;
// 停止全部推送线程
for i := 0 to High(FThreads) do
FThreads[i].Stop;
// 等待全部线程退出
while (FThreadCount > 0) do
begin
ReleaseSemapHore(FSemaphore, 1, Nil);
Sleep(10);
end;
SetLength(FThreads, 0);
CloseHandle(FSemaphore); // 关闭
CloseHandle(FWaitSemaphore); // 关闭
// 释放未发送的消息空间
for i := 0 to FMsgList.Count - 1 do
TPushMessage(FMsgList.PopFirst).Free;
FMsgList.Free;
FLock.Free;
FPushPool := nil;
FMsgList := nil;
FLock := nil;
end;
end;
procedure TPushMsgManager.WaitFor;
begin
// 等待活动线程结束
while (FActiveThreadCount > 0) do
Sleep(10);
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit frmMaterializedViewProperties;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, dxBar, ComCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
cxControls, cxGridCustomView, cxGrid, cxListView, cxSplitter, cxMemo,
cxRichEdit, cxTextEdit, cxLabel, cxContainer, cxGroupBox, cxPC, StdCtrls,
ExtCtrls;
type
TMaterializedViewPropertiesFrm = class(TForm)
Panel1: TPanel;
Image1: TImage;
Shape1: TShape;
lblDescription: TLabel;
pcMaterializedViewProperties: TcxPageControl;
tsProcedureSQLQuery: TcxTabSheet;
dxBarDockControl1: TdxBarDockControl;
cxGroupBox1: TcxGroupBox;
cxLabel1: TcxLabel;
edtName: TcxTextEdit;
cxLabel2: TcxLabel;
edtOwner: TcxTextEdit;
redtCode: TcxRichEdit;
cxSplitter1: TcxSplitter;
lviewError: TcxListView;
tsBody: TcxTabSheet;
redtBodyCode: TcxRichEdit;
cxSplitter2: TcxSplitter;
lviewBodyError: TcxListView;
tsArguments: TcxTabSheet;
cxGrid1: TcxGrid;
cxGridDBTableView1: TcxGridDBTableView;
cxGridDBColumn4: TcxGridDBColumn;
cxGridDBColumn1: TcxGridDBColumn;
cxGridDBColumn2: TcxGridDBColumn;
cxGridDBColumn3: TcxGridDBColumn;
cxGridDBColumn5: TcxGridDBColumn;
cxGridDBTableView1Column1: TcxGridDBColumn;
cxGridLevel1: TcxGridLevel;
tsProcedureGrants: TcxTabSheet;
dxBarDockControl4: TdxBarDockControl;
GridGrants: TcxGrid;
GridGrantsDBTableView1: TcxGridDBTableView;
GridGrantsDBTableView1Column1: TcxGridDBColumn;
GridGrantsDBTableView1Column2: TcxGridDBColumn;
GridGrantsDBTableView1Column3: TcxGridDBColumn;
GridGrantsDBTableView1Column4: TcxGridDBColumn;
cxGridLevel5: TcxGridLevel;
tsProcedureSynonyms: TcxTabSheet;
dxBarDockControl6: TdxBarDockControl;
GridSynonyms: TcxGrid;
GridSynonymsDBTableView1: TcxGridDBTableView;
GridSynonymsDBTableView1Column1: TcxGridDBColumn;
GridSynonymsDBTableView1Column2: TcxGridDBColumn;
cxGridLevel6: TcxGridLevel;
tsProcedureUsedBy: TcxTabSheet;
GridUsed: TcxGrid;
GridUsedDBTableView1: TcxGridDBTableView;
GridUsedDBTableView1Column1: TcxGridDBColumn;
GridUsedDBTableView1Column2: TcxGridDBColumn;
GridUsedDBTableView1Column3: TcxGridDBColumn;
GridUsedDBTableView1Column4: TcxGridDBColumn;
GridUsedDBTableView1Column5: TcxGridDBColumn;
cxGridLevel7: TcxGridLevel;
tsProcedureUses: TcxTabSheet;
GridUses: TcxGrid;
GridUsesDBTableView1: TcxGridDBTableView;
GridUsesDBTableView1Column1: TcxGridDBColumn;
GridUsesDBTableView1Column2: TcxGridDBColumn;
GridUsesDBTableView1Column3: TcxGridDBColumn;
GridUsesDBTableView1Column4: TcxGridDBColumn;
GridUsesDBTableView1Column5: TcxGridDBColumn;
cxGridLevel2: TcxGridLevel;
dxBarManager1: TdxBarManager;
btnCreateProc: TdxBarButton;
btnAlterProc: TdxBarButton;
btnDropProc: TdxBarButton;
btnCompileProc: TdxBarButton;
btnRefreshProc: TdxBarButton;
btnPrivilegesView: TdxBarButton;
bbtnGrantPrivileges: TdxBarButton;
btnRefreshGrants: TdxBarButton;
bbtnCreateSynonym: TdxBarButton;
bbtnDropSynonym: TdxBarButton;
bbtnRefreshSynonym: TdxBarButton;
bbtnExecPro: TdxBarButton;
private
{ Private declarations }
public
{ Public declarations }
end;
var
MaterializedViewPropertiesFrm: TMaterializedViewPropertiesFrm;
implementation
{$R *.dfm}
end.
|
//===============================
//
// AcceptEx 模式使用的单元
//
//===============================
unit iocp_wsExt;
interface
{$I in_iocp.inc}
uses
{$IFDEF DELPHI_XE7UP}
Winapi.Windows, System.Classes, System.SysUtils, Winapi.PsAPI, {$ELSE}
Windows, Classes, SysUtils, PsAPI, {$ELSE}
{$ENDIF} iocp_Winsock2;
const
// transmit file flag values
{$EXTERNALSYM TF_DISCONNECT}
TF_DISCONNECT = $01;
{$EXTERNALSYM TF_REUSE_SOCKET}
tf_reuse_socket = $02;
{$EXTERNALSYM TF_WRITE_BEHIND}
tf_write_behind = $04;
{$EXTERNALSYM TF_USE_DEFAULT_WORKER}
tf_use_default_worker = $00;
{$EXTERNALSYM TF_USE_SYSTEM_THREAD}
tf_use_system_thread = $10;
{$EXTERNALSYM TF_USE_KERNEL_APC}
tf_use_kernel_apc = $20;
{ Other NT-specific options. }
{$EXTERNALSYM SO_MAXDG}
SO_MAXDG = $7009;
{$EXTERNALSYM SO_MAXPATHDG}
SO_MAXPATHDG = $700A;
{$EXTERNALSYM SO_UPDATE_ACCEPT_CONTEXT}
SO_UPDATE_ACCEPT_CONTEXT = $700B;
{$EXTERNALSYM SO_CONNECT_TIME}
SO_CONNECT_TIME = $700C;
type
// TransmitFile 发送内存结构
PTransmitFileBuffers = ^TTransmitFileBuffers;
TTransmitFileBuffers = packed record
Head: Pointer; // 先发送的数据
HeadLength: DWORD;
Tail: Pointer; // 最后发送的数据
TailLength: DWORD;
end;
PTransmitBuffers = PTransmitFileBuffers;
// ============== TCP 心跳包 ==============
// TCP 心跳包结构
PTCPKeepAlive = ^TTCPKeepAlive;
TTCPKeepAlive = record
OnOff: Integer; // 是否启用
KeepAliveTime: Integer; // 心跳周期
KeepAliveInterVal: Integer; // 多长时间无心跳即探测
end;
TAcceptEx = function(sListenSocket, sAcceptSocket: TSocket;
lpOutputBuffer: Pointer; dwReceiveDataLength, dwLocalAddressLength,
dwRemoteAddressLength: LongWord; var lpdwBytesReceived: LongWord;
lpOverlapped: POverlapped): BOOL; stdcall;
TGetAcceptExSockAddrs = procedure(lpOutputBuffer: Pointer;
dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength: DWORD;
var LocalSockaddr: PSockAddr; var LocalSockaddrLength: Integer;
var RemoteSockaddr: PSockAddr; var RemoteSockaddrLength: Integer);stdcall;
TConnectEx = function(const hSocket: TSocket; const name: PSOCKADDR; const
namelen: Integer; lpSendBuffer: Pointer; dwSendDataLength : DWORD; var
lpdwBytesSent: LongWord; lpOverlapped: POverlapped): BOOL; stdcall;
TDisconnectEx = function(const hSocket: TSocket; lpOverlapped: POverlapped;
const dwFlags: LongWord; const dwReserved: LongWord) : BOOL; stdcall;
TTransmitFileProc = function(hSocket: TSocket; hFile: THandle;
nNumberOfBytesToWrite, nNumberOfBytesPerSend: DWORD; lpOverlapped: POVERLAPPED;
lpTransmitBuffers: PTransmitFileBuffers; dwFlags: DWORD): BOOL; stdcall;
var
gAcceptEx: TAcceptEx = nil;
gGetAcceptExSockAddrs: TGetAcceptExSockAddrs = nil;
gConnectEx: TConnectEx = nil;
gDisconnectEx: TDisconnectEx = nil;
gTransmitFile: TTransmitFileProc = nil;
procedure GetWSExtFuncs(Socket: TSocket);
function SetKeepAlive(Socket: TSocket; InterValue: Integer = 8000): Boolean;
implementation
uses
iocp_log, iocp_base, iocp_utils, iocp_msgPacks, iocp_Server;
const
WSAID_ACCEPTEX: System.TGuid =
(D1:$b5367df1;D2:$cbac;D3:$11cf;D4:($95,$ca,$00,$80,$5f,$48,$a1,$92));
WSAID_GETACCEPTEXSOCKADDRS: System.TGuid =
(D1:$b5367df2;D2:$cbac;D3:$11cf;D4:($95,$ca,$00,$80,$5f,$48,$a1,$92));
WSAID_CONNECTEX: System.TGuid =
(D1:$25a207b9;D2:$ddf3;D3:$4660;D4:($8e,$e9,$76,$e5,$8c,$74,$06,$3e));
WSAID_DISCONNECTEX: System.TGuid =
(D1:$7fda2e11;D2:$8630;D3:$436f;D4:($a0,$31,$f5,$36,$a6,$ee,$c1,$57));
WSAID_TRANSMITFILE: System.TGuid =
(D1:$B5367DF0;D2:$CBAC;D3:$11CF;D4:($95,$CA,$00,$80,$5F,$48,$A1,$92));
procedure GetWSExtFuncs(Socket: TSocket);
var
ByteCount: Cardinal;
begin
// 查询 Socket 扩展函数(AcceptEx 模式)
// Socket := WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, nil, 0, WSA_FLAG_OVERLAPPED);
if (WSAIoctl(Socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
@WSAID_ACCEPTEX, SizeOf(WSAID_ACCEPTEX),
@@gAcceptEx, SizeOf(Pointer),
ByteCount, nil, nil) = SOCKET_ERROR) then
begin
@gAcceptEx := nil;
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog('GetWSExtFuncs->AcceptEx Error.');
{$ENDIF}
Exit;
end;
if (WSAIoctl(Socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
@WSAID_GETACCEPTEXSOCKADDRS, SizeOf(WSAID_GETACCEPTEXSOCKADDRS),
@@gGetAcceptExSockAddrs, SizeOf(Pointer),
ByteCount, nil, nil) = SOCKET_ERROR) then
begin
@gGetAcceptExSockAddrs := nil;
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog('GetWSExtFuncs->GetAcceptExSockAddrs Error.');
{$ENDIF}
Exit;
end;
if (WSAIoctl(Socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
@WSAID_CONNECTEX, SizeOf(WSAID_CONNECTEX),
@@gConnectEx, SizeOf(Pointer),
ByteCount, nil, nil) = SOCKET_ERROR) then
begin
@gConnectEx := nil;
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog('GetWSExtFuncs->ConnectEx Error.');
{$ENDIF}
Exit;
end;
if (WSAIoctl(Socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
@WSAID_DISCONNECTEX, SizeOf(WSAID_DISCONNECTEX),
@@gDisconnectEx, SizeOf(Pointer),
ByteCount, nil, nil) = SOCKET_ERROR) then
begin
@gDisconnectEx := nil;
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog('GetWSExtFuncs->DisconnectEx Error.');
{$ENDIF}
Exit;
end;
if (WSAIoctl(Socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
@WSAID_TRANSMITFILE, SizeOf(WSAID_TRANSMITFILE),
@@gTransmitFile, SizeOf(Pointer),
ByteCount, nil, nil) = SOCKET_ERROR) then
begin
@gTransmitFile := nil;
{$IFDEF DEBUG_MODE}
iocp_log.WriteLog('GetWSExtFuncs->TransmitFile Error.');
{$ENDIF}
Exit;
end;
end;
function SetKeepAlive(Socket: TSocket; InterValue: Integer): Boolean;
var
Opt: Integer;
OutByte: DWORD;
InSize, OutSize: Integer;
KeepAliveIn, KeepAliveOut: TTCPKeepAlive;
begin
// 设置 Socket 心跳
Opt := 1;
if (iocp_Winsock2.SetSockopt(Socket, SOL_SOCKET, SO_KEEPALIVE,
@Opt, SizeOf(Integer)) <> SOCKET_ERROR) then
begin
KeepAliveIn.OnOff := 1;
KeepAliveIn.KeepAliveTime := InterValue; // 心跳周期
if (InterValue <= 8000) then
KeepAliveIn.KeepAliveInterVal := 10000 // 10 秒无心跳即探测
else
KeepAliveIn.KeepAliveInterVal := InterValue + 2000; // 超2秒无心跳即探测
InSize := SizeOf(TTCPKeepAlive);
OutSize := SizeOf(TTCPKeepAlive);
Result := (iocp_Winsock2.WSAIoctl(Socket, IOC_IN or IOC_VENDOR or 4, // = SIO_KEEPALIVE_VALS
@KeepAliveIn, InSize, @KeepAliveOut, OutSize,
OutByte, nil, nil) <> SOCKET_ERROR);
end else
Result := False;
end;
end.
|
unit csExport;
interface
uses
Classes,
dt_Types,
CsDataPipe, csProcessTask, CsTaskTypes, dt_Sab;
type
TcsExport = class(TddProcessTask)
private
f_AdditionalProcess: AnsiString;
f_AnnoTopicFileName: AnsiString;
f_DiapasonType: TDiapType;
f_DocID: TDocID;
f_DocSab: ISab;
f_DocumentFileNameMask: AnsiString;
f_ExportAnnoTopics: Boolean;
f_ExportDirectory: AnsiString;
f_ExportDocImage: Boolean;
f_ExportDocument: Boolean;
f_ExportEditions: Boolean;
f_ExportEmptyKW: Boolean;
f_ExportKW: Boolean;
f_ExportReferences: Boolean;
f_ExportRTFBody: Boolean;
f_Family: Integer;
f_FormulaAsPicture: Boolean;
f_InternalFormat: Boolean;
f_KWFileName: AnsiString;
f_MultiUser: Boolean;
f_ObjTopicFileName: AnsiString;
f_OnlyStructure: Boolean;
f_OutFileType: LongInt;
f_OutputFileSize: LongInt;
f_ReferenceFileNameMask: AnsiString;
f_SABStream: TStream;
f_SeparateFiles: LongInt;
f_ServerSide: Boolean;
f_StartNumber: Integer;
f_ToRegion: TDictID;
procedure pm_SetDocSab(Value: ISab);
procedure pm_SetExportDirectory(const Value: AnsiString);
protected
procedure Cleanup; override;
function GetDescription: AnsiString; override;
procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override;
procedure pm_SetTaskFolder(const Value: AnsiString); override;
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
procedure MakeSab;
procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override;
procedure WriteResult(aStream: TStream); overload; override;
procedure WriteResult(aPipe: TcsDataPipe); overload; override;
property AdditionalProcess: AnsiString
read f_AdditionalProcess
write f_AdditionalProcess;
property AnnoTopicFileName: AnsiString read f_AnnoTopicFileName write
f_AnnoTopicFileName;
property DiapasonType: TDiapType read f_DiapasonType write f_DiapasonType;
property DocID: TDocID read f_DocID write f_DocID;
property DocSab: ISab read f_DocSab write pm_SetDocSab;
property DocumentFileNameMask: AnsiString read f_DocumentFileNameMask write
f_DocumentFileNameMask;
property ExportAnnoTopics: Boolean read f_ExportAnnoTopics write
f_ExportAnnoTopics;
property ExportDirectory: AnsiString read f_ExportDirectory write
pm_SetExportDirectory;
property ExportDocImage: Boolean read f_ExportDocImage write
f_ExportDocImage;
property ExportDocument: Boolean read f_ExportDocument write
f_ExportDocument;
property ExportEditions: Boolean read f_ExportEditions write f_ExportEditions;
property ExportEmptyKW: Boolean read f_ExportEmptyKW write f_ExportEmptyKW;
property ExportKW: Boolean read f_ExportKW write f_ExportKW;
property ExportReferences: Boolean read f_ExportReferences write f_ExportReferences;
property ExportRTFBody: Boolean read f_ExportRTFBody write f_ExportRTFBody;
property Family: Integer read f_Family write f_Family;
property FormulaAsPicture: Boolean read f_FormulaAsPicture write
f_FormulaAsPicture;
property InternalFormat: Boolean read f_InternalFormat write
f_InternalFormat;
property KWFileName: AnsiString read f_KWFileName write f_KWFileName;
property MultiUser: Boolean read f_MultiUser write f_MultiUser;
property ObjTopicFileName: AnsiString read f_ObjTopicFileName write
f_ObjTopicFileName;
property OnlyStructure: Boolean read f_OnlyStructure write f_OnlyStructure;
property OutFileType: LongInt read f_OutFileType write f_OutFileType;
property OutputFileSize: LongInt read f_OutputFileSize write
f_OutputFileSize;
property ReferenceFileNameMask: AnsiString read f_ReferenceFileNameMask write
f_ReferenceFileNameMask;
property SABStream: TStream read f_SABStream write f_SABStream;
property SeparateFiles: LongInt read f_SeparateFiles write f_SeparateFiles;
property ServerSide: Boolean read f_ServerSide write f_ServerSide;
property StartNumber: Integer read f_StartNumber write f_StartNumber;
property ToRegion: TDictID read f_ToRegion write f_ToRegion;
end;
implementation
uses
l3TempMemoryStream,
SysUtils, ddUtils, L3FileUtils, DT_DictConst, dt_Doc, DT_Const;
{
****************************** TcsExport *******************************
}
constructor TcsExport.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType := cs_ttExport;
Version:= 4;
f_SABStream := Tl3TempMemoryStream.Create;
ServerSide:= False;
StartNumber:= 1;
f_ToRegion:= cUndefDictID;
f_FormulaAsPicture:= False;
end;
procedure TcsExport.Cleanup;
begin
f_DocSab:= nil;
FreeAndNil(f_SABStream);
inherited;
end;
function TcsExport.GetDescription: AnsiString;
var
l_SR: TSearchRec;
l_Mask, l_Descript: AnsiString;
l_Total, l_Count: Int64;
begin
Result := 'Экспорт ';
if TepDivideBy(SeparateFiles) = divTopic then
Result:= Result + 'по документам, '
else
begin
if DocumentFileNameMask <> '' then
Result := Result + SysUtils.Format('%s, ', [DocumentFileNameMask]);
if TepDivideBy(SeparateFiles) = divSize then
Result := Result + SysUtils.Format('размер части: %s, ', [Bytes2Str(OutputFileSize)]);
end;
Result := Result + SysUtils.Format('папка: %s, формат: %s',
[ExportDirectory,
SupportFileTypeNames[TepSupportFileType(OutFileType)]]);
end;
procedure TcsExport.LoadFrom(aStream: TStream; aIsPipe: Boolean);
var
l_Value: Integer;
begin
inherited;
with aStream do
begin
ReadString(aStream, F_AnnoTopicFileName);
Read(l_Value, SizeOf(Integer));
F_DiapasonType := TDiapType(l_Value);
Read(F_DOcID, SizeOf(Integer));
ReadString(aStream, F_DocumentFileNameMask);
Read(F_ExportAnnoTopics, SizeOf(Boolean));
ReadString(aStream, F_ExportDirectory);
Read(F_ExportDocImage, SizeOf(Boolean));
Read(F_ExportDocument, SizeOf(Boolean));
Read(f_ExportEmptyKW, SizeOf(Boolean));
Read(F_ExportKW, SizeOf(Boolean));
Read(F_ExportRTFBody, SizeOF(Boolean));
Read(F_Family, SizeOf(Integer));
Read(F_InternalFormat, SizeOf(Boolean));
ReadString(aStream, F_KWFileName);
Read(F_MultiUser, SizeOf(Boolean));
Read(l_Value, SizeOf(Integer));
if l_Value > 0 then
begin
f_SABStream.Seek(0, 0);
l_Value := f_SABStream.CopyFrom(aStream, l_Value);
f_SABStream.Seek(0, 0);
end;
if not aIsPipe then // Нельзя использовать HyTech в другой нити :(
begin
(*TODO: extracted code
f_DocSab:= MakeValueSet(DocumentServer(CurrentFamily).FileTbl, fID_Fld, SABStream);
f_DocSab.Sort;
*)
//MakeSab;
end; // not aIsPipe
ReadString(aStream, F_ObjTopicFileName);
Read(F_OnlyStructure, SizeOf(Boolean));
Read(F_OutFileType, SizeOf(Longint));
Read(F_OutputFileSize, SizeOf(LongInt));
ReadString(aStream, F_ReferenceFileNameMask);
Read(F_SeparateFiles, SizeOf(Longint));
Read(f_ToRegion, SizeOf(f_ToRegion));
f_ExportReferences:= F_ExportDocument;
f_ExportEditions:= False;
f_FormulaAsPicture:= False;
if Version > 1 then
Read(F_ExportReferences, SizeOf(Boolean));
if Version > 2 then
read(f_ExportEditions, SizeOf(Boolean));
if Version > 3 then
read(f_FormulaAsPicture, SizeOf(Boolean));
end; // with aStream
end;
procedure TcsExport.MakeSab;
begin
f_DocSab:= MakeValueSet(DocumentServer(CurrentFamily).FileTbl, fID_Fld, SABStream);
f_DocSab.Sort;
end;
procedure TcsExport.pm_SetDocSab(Value: ISab);
begin
f_DocSab := Value;
end;
procedure TcsExport.pm_SetExportDirectory(const Value: AnsiString);
begin
f_ExportDirectory := Value;
//if UserID
//TaskFolder := ConcatDirName(GlobalHtServer.GetHomePath(aTask.UserID), rsExport);
end;
procedure TcsExport.pm_SetTaskFolder(const Value: AnsiString);
begin
f_TaskFolder := GetUniqFileName(Value, 'Export', '');
end;
procedure TcsExport.SaveTo(aStream: TStream; aIsPipe: Boolean);
var
l_Value: Integer;
begin
inherited;
with aStream do
begin
WriteString(aStream, F_AnnoTopicFileName);
l_Value := Integer(Ord(F_DiapasonType));
Write(l_Value, SizeOf(Integer));
Write(F_DocID, SizeOf(F_DocID));
WriteString(aStream, F_DocumentFileNameMask);
Write(F_ExportAnnoTopics, SizeOf(Boolean));
WriteString(aStream, F_ExportDirectory);
Write(F_ExportDocImage, SizeOf(Boolean));
Write(F_ExportDocument, SizeOf(Boolean));
Write(f_ExportEmptyKW, SizeOf(Boolean));
Write(F_ExportKW, SizeOf(Boolean));
Write(F_ExportRTFBody, SizeOF(Boolean));
write(F_Family, SizeOf(Integer));
Write(F_InternalFormat, SizeOf(Boolean));
WriteString(aStream, F_KWFileName);
Write(F_MultiUser, SizeOf(Boolean));
//if not aIsPipe and (DocSab <> nil) and not DocSab.IsEmpty then
// dtOutSabToStream(DocSab, SABStream);
(* %<---Потом нужно удалить--->% *)
l_Value := f_SABStream.Size;
Write(l_Value, SizeOf(l_Value));
f_SABStream.Seek(0, 0);
CopyFrom(f_SABStream, l_Value);
f_SABStream.Seek(0, 0);
(*=======================*)
WriteString(aStream, F_ObjTopicFileName);
Write(F_OnlyStructure, SizeOf(Boolean));
Write(F_OutFileType, SizeOf(Longint));
Write(F_OutputFileSize, SizeOf(LongInt));
WriteString(aStream, F_ReferenceFileNameMask);
Write(F_SeparateFiles, SizeOf(Longint));
Write(f_ToRegion, SizeOf(f_ToRegion));
if Version > 1 then
Write(F_ExportReferences, SizeOf(Boolean));
if Version > 2 then
begin
Write(f_ExportEditions, SizeOf(Boolean));
end;
if Version > 3 then
begin
Write(f_FormulaAsPicture, SizeOf(Boolean));
end;
end; // with aStream
end;
procedure TcsExport.WriteResult(aStream: TStream);
begin
inherited;
// Бросить в трубу все вылитые файлы
WriteFolderTo(aStream, TaskFolder)
end;
procedure TcsExport.WriteResult(aPipe: TcsDataPipe);
begin
aPipe.WriteFolder(TaskFolder);
PureDir(TaskFolder);
RemoveDir(TaskFolder);
end;
end.
|
unit kwPopEditorPrintAcnhor;
{* *Формат:* aTopAnchor anEditorControl pop:editor:PrintAcnhor
*Описание:* Печатает текущее значение якоря, включая дочерние, позицию, PID параграф и т.п. aTopAnchor - true - верхния якорь, false - нижний якорь.
*Пример:*
[code]
true focused:control:push pop:editor:PrintAcnhor
[code]
*Результат:* В засимости от значения поля в будет напечатано значение "true" или "false" }
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwPopEditorPrintAcnhor.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "pop_editor_PrintAcnhor" MUID: (5009071C00FF)
// Имя типа: "TkwPopEditorPrintAcnhor"
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, kwEditorFromStackWord
, tfwScriptingInterfaces
, nevTools
, evCustomEditorWindow
;
type
TkwPopEditorPrintAcnhor = {final} class(TkwEditorFromStackWord)
{* *Формат:* aTopAnchor anEditorControl pop:editor:PrintAcnhor
*Описание:* Печатает текущее значение якоря, включая дочерние, позицию, PID параграф и т.п. aTopAnchor - true - верхния якорь, false - нижний якорь.
*Пример:*
[code]
true focused:control:push pop:editor:PrintAcnhor
[code]
*Результат:* В засимости от значения поля в будет напечатано значение "true" или "false" }
private
procedure SaveAnchor(const aCtx: TtfwContext;
const anAnchor: InevBasePoint;
anEditor: TevCustomEditorWindow);
function CheckBaseLine(const aCtx: TtfwContext;
const anAnchor: InevBasePoint;
anEditor: TevCustomEditorWindow): Boolean;
protected
procedure DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow); override;
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopEditorPrintAcnhor
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, SysUtils
, l3Base
, Windows
{$If NOT Defined(NoVCL)}
, Controls
{$IfEnd} // NOT Defined(NoVCL)
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
//#UC START# *5009071C00FFimpl_uses*
//#UC END# *5009071C00FFimpl_uses*
;
procedure TkwPopEditorPrintAcnhor.SaveAnchor(const aCtx: TtfwContext;
const anAnchor: InevBasePoint;
anEditor: TevCustomEditorWindow);
//#UC START# *500925030215_5009071C00FF_var*
var
l_Anchor : InevBasePoint;
//#UC END# *500925030215_5009071C00FF_var*
begin
//#UC START# *500925030215_5009071C00FF_impl*
l_Anchor := anAnchor;
while l_Anchor <> nil do
begin
aCtx.rCaller.Print(l3CStr(Format('TagName = %s PID = %d Position = %d', [l_Anchor.Obj^.AsObject.TagType.AsString, l_Anchor.Obj.PID, l_Anchor.Position])));
if l_Anchor.Obj.IsVertical then
aCtx.rCaller.Print(l3CStr(Format('VertPosition = %d', [l_Anchor.VertPosition(anEditor.View, anEditor.View.FormatInfoByPoint(l_Anchor))])));
aCtx.rCaller.Print(l3CStr(Format('AtStart = %s AtEnd = %s AfterEnd = %s', [BoolToStr(l_Anchor.AtStart, True), BoolToStr(l_Anchor.AtEnd(anEditor.View), True), BoolToStr(l_Anchor.AfterEnd, True)])));
if l_Anchor.AsLeaf <> nil then
aCtx.rCaller.Print(l3CStr(l_Anchor.Obj^.Text));
if CheckBaseLine(aCtx, l_Anchor, anEditor) then Break;
l_Anchor := l_Anchor.Inner;
end; // while l_Anchor <> nil do
//#UC END# *500925030215_5009071C00FF_impl*
end;//TkwPopEditorPrintAcnhor.SaveAnchor
function TkwPopEditorPrintAcnhor.CheckBaseLine(const aCtx: TtfwContext;
const anAnchor: InevBasePoint;
anEditor: TevCustomEditorWindow): Boolean;
//#UC START# *5009264E0377_5009071C00FF_var*
var
i : Integer;
l_Head : InevBasePoint;
l_Inner : InevBasePoint;
//#UC END# *5009264E0377_5009071C00FF_var*
begin
//#UC START# *5009264E0377_5009071C00FF_impl*
Result := anAnchor.HasBaseLine;
if Result then
begin
aCtx.rCaller.Print(l3CStr('--------------'));
for i := 0 to anAnchor.Obj^.AsObject.ChildrenCount - 1 do
begin
aCtx.rCaller.Print(l3CStr('----'));
l_Inner := anAnchor.InnerFor(anAnchor.Obj^.ToList[i], l_Head);
if l_Inner <> nil then
begin
SaveAnchor(aCtx, l_Inner, anEditor);
aCtx.rCaller.Print(l3CStr(Format('Merge Type = %d', [Ord(l_Inner.Obj^.OverlapType)])));
end; // if l_Inner <> nil then
if l_Head <> nil then
begin
SaveAnchor(aCtx, l_Head, anEditor);
aCtx.rCaller.Print(l3CStr(Format('Merge Type = %d', [Ord(l_Head.Obj^.OverlapType)])));
end; // if l_Head <> nil then
aCtx.rCaller.Print(l3CStr('----'));
end; // for i := 0 to anAnchor.Obj^.ChildrenCount - 1 do
aCtx.rCaller.Print(l3CStr('--------------'));
end; // if anAnchor.HasBaseLine then
//#UC END# *5009264E0377_5009071C00FF_impl*
end;//TkwPopEditorPrintAcnhor.CheckBaseLine
procedure TkwPopEditorPrintAcnhor.DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow);
//#UC START# *4F4CB81200CA_5009071C00FF_var*
var
l_Top: Boolean;
//#UC END# *4F4CB81200CA_5009071C00FF_var*
begin
//#UC START# *4F4CB81200CA_5009071C00FF_impl*
if aCtx.rEngine.IsTopBool then
l_Top := aCtx.rEngine.PopBool
else
Assert(False, 'Не задано, какой якорь печатать.');
if l_Top then
SaveAnchor(aCtx, anEditor.View.TopAnchor, anEditor)
else
SaveAnchor(aCtx, anEditor.View.BottomAnchor(False), anEditor);
//SaveAnchor(aCtx, anEditor.View.ExperimentalAnchor, anEditor{anEditor.View.BottomAnchor});
//#UC END# *4F4CB81200CA_5009071C00FF_impl*
end;//TkwPopEditorPrintAcnhor.DoWithEditor
class function TkwPopEditorPrintAcnhor.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:editor:PrintAcnhor';
end;//TkwPopEditorPrintAcnhor.GetWordNameForRegister
initialization
TkwPopEditorPrintAcnhor.RegisterInEngine;
{* Регистрация pop_editor_PrintAcnhor }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit l3StringFormatter;
{ Библиотека "L3 (Low Level Library)" }
{ Автор: Инишев Д.А. © }
{ Модуль: l3StringFormatter - }
{ Начат: 20.09.06 19:00 }
{ $Id: l3StringFormatter.PAS,v 1.8 2014/02/13 10:12:59 lulin Exp $ }
// $Log: l3StringFormatter.PAS,v $
// Revision 1.8 2014/02/13 10:12:59 lulin
// - рефакторим безликие списки.
//
// Revision 1.7 2013/12/25 15:10:36 lulin
// {RequestLink:509706011}
// - перетрясаем модель.
//
// Revision 1.6 2013/04/04 11:33:02 lulin
// - портируем.
//
// Revision 1.5 2007/12/24 13:25:49 lulin
// - модуль l3InternalInterfaces полностью перенесен на модель.
//
// Revision 1.4 2007/07/11 12:11:59 dinishev
// Cleanup
//
// Revision 1.3 2006/12/01 15:51:04 lulin
// - cleanup.
//
// Revision 1.2 2006/11/13 16:35:04 dinishev
// Bug fix: иногда выливали не все пробелы из-за чего ехали границы таблиц
//
// Revision 1.1 2006/09/21 12:25:41 dinishev
// new interface: Il3StringFormatter
//
{$Include l3Define.inc }
interface
uses
l3Base,
l3Types,
l3InternalInterfaces,
l3ProtoObject
;
type
Tl3StringFormatted = class(Tl3ProtoObject, Il3StringFormatter)
protected
f_String : Tl3String;
{* - Форматируемая строка. }
f_CurrSpacePos : Long;
{* - Позиция текущего найденного пробела. }
f_CurrSpaceCnt : Long;
{* - Текущее количество добавляемых пробелов. }
protected
procedure DoBeforeFormatting;
virtual;
{* - Действия перед началом форматирования строки. }
procedure DoBeforeInsertSpaces;
virtual;
{* - Действия перед вставкой пробелов. }
procedure DoAfterInsertSpaces;
virtual;
{* - Действия после вставкой пробелов. }
protected
// - interfaces methods
// Il3StringFormatter
procedure FixWidth(aString : TObject;
aDelta : Long;
var aSpacesCount : Long);
{-}
end;
implementation
uses
l3Chars,
l3String,
l3StringEx;
{ Tl3StringFormatted }
procedure Tl3StringFormatted.DoAfterInsertSpaces;
begin
end;
procedure Tl3StringFormatted.DoBeforeFormatting;
begin
end;
procedure Tl3StringFormatted.DoBeforeInsertSpaces;
begin
end;
procedure Tl3StringFormatted.FixWidth(aString : TObject;
aDelta : Long;
var aSpacesCount : Long);
{-}
var
l_WordCount : Long;
l_PCharString : PAnsiChar;
l_CharIndex : Long;
l_CurrPos : Long;
l_SpacesCount : Long;
l_Div : Integer;
l_StringLength : Long;
l_Delta : Long;
begin
f_String := aString as Tl3String;
l_StringLength := f_String.Len;
if (l_StringLength > 0) and (aSpacesCount > 0) then
begin
l_PCharString := f_String.St;
l_WordCount := l3CountOfChar(cc_HardSpace, l3PCharLen(l_PCharString, l_StringLength, f_String.CodePage));
if (l_WordCount > 0) then
begin
if (f_String.CodePage = CP_Unicode) then
l_Div := 2
else
l_Div := 1;
l_CurrPos := 0;
l_SpacesCount := aSpacesCount;
DoBeforeFormatting;
while (l_SpacesCount > 0) AND (l_WordCount > 0) do
begin
l_Delta := (l_PCharString - f_String.St) div l_Div;
l_CharIndex := ev_lpCharIndex(cc_HardSpace,
l3PCharLen(l_PCharString,
l_StringLength - l_Delta,
f_String.CodePage));
f_CurrSpaceCnt := l_SpacesCount div l_WordCount;
f_CurrSpacePos := l_CharIndex + l_Delta;
DoBeforeInsertSpaces;
f_String.Insert(cc_HardSpace, f_CurrSpacePos, f_CurrSpaceCnt);
DoAfterInsertSpaces;
Dec(l_SpacesCount, f_CurrSpaceCnt);
Dec(l_WordCount);
Inc(l_CurrPos, l_CharIndex);
Inc(l_CurrPos, f_CurrSpaceCnt);
Inc(l_CurrPos);
l_PCharString := f_String.St + l_CurrPos * l_Div;
end;//while (l_SpacesCount > 0) AND (l_WordCount > 0) do
//Не все пробелы могли быть использованы (для обычного txt это не верно, но
//для NRSC с текстом со ссылками такая ситуация возможна.
if (l_SpacesCount > 0) then
f_String.Append(cc_HardSpace, l_SpacesCount);
end//if (l_WordCount > 0) then
else
aSpacesCount := 0; //- Сигнализируем, что мы не добили пробелами
end;//if (l_StringLength > 0) and (aSpacesCount > 0) then
end;
end.
|
unit Snapshot;
interface
uses Classes, SysUtils, Windows, Graphics, Cnst, Dialogs, Forms;
type
TRange = record
From,
Too: Integer;
end;
{ Sorted selected area }
TRanges = record
XRange: TRange;
YRange: TRange;
end;
PRanges = ^TRanges;
TSnapshot = class
private
FbSnapshot,
FbPreviousSnapshot,
FbFullSnapshot: TBitmap;
procedure ScreenShot(ActiveWindow: Boolean; var DestBitmap : TBitmap);
public
constructor Create;
destructor Destroy; override;
procedure Make(ActiveWindow: Boolean);
procedure CutPoints(Oblong: TOblong);
procedure SortRanges(Oblong: TOblong; var Ranges: TRanges);
procedure Cleanup;
property Snapshot: TBitmap read FbSnapshot write FbSnapshot;
property PreviousSnapshot: TBitmap read FbPreviousSnapshot;
property FullSnapshot: TBitmap read FbFullSnapshot;
end;
implementation
constructor TSnapshot.Create;
begin
FbSnapshot:=TBitmap.Create;
FbPreviousSnapshot:=TBitmap.Create;
FbFullSnapshot:=TBitmap.Create;
end;
destructor TSnapshot.Destroy;
begin
FbSnapshot.Free;
FbPreviousSnapshot.Free;
FbFullSnapshot.Free;
end;
procedure TSnapshot.ScreenShot(ActiveWindow: Boolean; var DestBitmap : TBitmap);
var
W, H: Integer;
DC: HDC;
hWin: Cardinal;
r: TRect;
c: TCanvas;
begin
if(ActiveWindow)then begin
hWin:=GetForegroundWindow;
DC:=GetWindowDC(hWin) ;
GetWindowRect(hWin, r) ;
W:=r.Right-r.Left;
H:=r.Bottom-r.Top;
end else begin
{
rocedure ScreenShot(Bild: TBitMap);
var
c: TCanvas;
r: TRect;
begin
c := TCanvas.Create;
c.Handle := GetWindowDC(GetDesktopWindow);
try
r := Rect(0, 0, Screen.Width, Screen.Height);
Bild.Width := Screen.Width;
Bild.Height := Screen.Height;
Bild.Canvas.CopyRect(r, c, r);
finally
ReleaseDC(0, c.Handle);
c.Free;
end;
end;
}
hWin:=GetDesktopWindow;
DC:=GetDC(hWin) ;
W:=GetDeviceCaps(DC, HORZRES);
H:=GetDeviceCaps(DC, VERTRES);
end;
try
DestBitmap.Width := Screen.Width;
DestBitmap.Height := Screen.Height;
BitBlt(DestBitmap.Canvas.Handle, 0, 0, DestBitmap.Width,
DestBitmap.Height, DC, 0, 0, SRCCOPY);
finally
ReleaseDC(hWin, DC) ;
end;
end;
procedure TSnapshot.Make;
begin
FbPreviousSnapshot.Assign(FbSnapshot);
ScreenShot(ActiveWindow, FbSnapshot);
FbFullSnapshot.Assign(FbSnapshot);
end;
procedure TSnapshot.SortRanges(Oblong: TOblong; var Ranges: TRanges);
begin
with Oblong do begin
with Ranges.XRange do begin
if(A.X>B.X)then begin
From:=B.X;
Too:=A.X;
end else
if(A.X<B.X)then begin
From:=A.X;
Too:=B.X;
end else begin
From:=A.X;
Too:=A.X;
end;
end;
with Ranges.YRange do begin
if(A.Y>B.Y)then begin
From:=B.Y;
Too:=A.Y;
end else
if(A.Y<B.Y)then begin
From:=A.Y;
Too:=B.Y;
end else begin
From:=A.Y;
Too:=A.Y;
end;
end;
end;
end;
procedure TSnapshot.CutPoints;
var
Ranges: PRanges;
begin
New(Ranges);
SortRanges(Oblong, Ranges^);
FbPreviousSnapshot.Assign(FbSnapshot);
FbSnapshot.FreeImage;
with Ranges^ do begin
FbSnapshot.Width:=XRange.Too-XRange.From;
FbSnapshot.Height:=YRange.Too-YRange.From;
FbSnapshot.Canvas.CopyRect(Rect(0, 0, FbSnapshot.Width, FbSnapshot.Height),
FbPreviousSnapshot.Canvas, Rect(XRange.From, YRange.From, XRange.Too, YRange.Too));
end;
Dispose(Ranges);
end;
procedure TSnapshot.Cleanup;
begin
FbSnapshot.FreeImage;
FbPreviousSnapshot.FreeImage;
FbFullSnapshot.FreeImage;
end;
end.
|
(****************************************************************************
*
* WinLIRC plug-in for jetAudio
*
* Copyright (c) 2016 Tim De Baets
*
****************************************************************************
*
* 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.
*
****************************************************************************
*
* Main plug-in implementation
*
****************************************************************************)
unit JFLircPluginClass;
interface
uses Windows, Messages, SysUtils, Classes, JFBase, JFGeneral, JDefine, ThisCall,
ScktComp, Common2, EzdslHsh, IniFiles, CmnFunc2;
const
PluginName = 'WinLIRC plug-in for jetAudio';
PluginDesc =
'Control jetAudio with a remote controller through the WinLIRC protocol.';
type
TJFLircPlugin = class(TJFGeneral)
private
fSocket: TClientSocket;
fFields: TStringList;
fModeCommands: THashTable;
fStandardCommands: THashTable;
fMenuCommands: THashTable;
fMonitorCommands: THashTable;
fMappedCommands: THashTable;
fMappedKeys: TStringList;
fIniFile: TIniFile;
fWinLircHost: String;
fWinLircPort: Integer;
fWinLircServer: String;
fMaxRetries: Integer;
fNoConnectFailedWarning: Boolean;
fhWndMain: HWND;
fWindow: HWND;
fConnected: Boolean;
fTries: Integer;
procedure csConnect(Sender: TObject; Socket: TCustomWinSocket);
procedure csDisconnect(Sender: TObject; Socket: TCustomWinSocket);
procedure csError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure csRead(Sender: TObject; Socket: TCustomWinSocket);
procedure WndProc(var Message: TMessage);
procedure StartServer;
procedure TryConnect;
procedure FillModeCommands;
procedure FillStandardCommands;
procedure FillMenuCommands;
procedure FillMonitorCommands;
procedure CreateAndOpenIniFile;
procedure ReadWriteSettings(Write: Boolean);
procedure ResolveMappings;
procedure ClearMappedKeys;
procedure HandleException(E: Exception);
public
FakeContextMenuId: Integer;
hWndRemocon: HWND;
constructor Create;
destructor Destroy; override;
procedure CDestroy(Val: Integer); override; stdcall;
procedure GetInfo(pInfo: PJFInfo); override; stdcall;
function SetPropertyPTR(pszPropName: PAnsiChar; pVal: PAnsiChar;
iValSize: Integer): BOOL; override; stdcall;
function GetPropertyPTR(pszPropName: PAnsiChar; pVal: PAnsiChar;
iValSize: Integer): BOOL; override; stdcall;
function SetPropertyINT(pszPropName: PAnsiChar; nVal: Integer): BOOL;
override; stdcall;
function GetPropertyINT(pszPropName: PAnsiChar; pnVal: PInteger): BOOL;
override; stdcall;
procedure Config(hWnd: HWND); override; stdcall;
procedure About(hWnd: HWND); override; stdcall;
function GetErrorString(pszBuffer: PAnsiChar;
nBufferSize: Integer): JERROR_TYPE; override; stdcall;
function Open(hWnd: HWND; pszRootDir: PAnsiChar; dwReserved1: DWORD;
dwReserved2: DWORD): BOOL; override; stdcall;
function Close: BOOL; override; stdcall;
function OnTimer(nCounter: Integer): BOOL; override; stdcall;
function OnEvent(uEvent: UINT; wParam: WPARAM; lParam: LPARAM): UINT;
override; stdcall;
end;
var
JFLircPlugin: TJFLircPlugin = nil;
ApiHooked: Boolean = False;
implementation
uses JetAudio6_API, JetAudio6_Const, JetAudioUtil, PathFunc, ShFolder,
JFLircCommands;
var
// TODO: better way than keeping this in a global var?
ThisCallPatched: Boolean = False;
const
DefaultHost = 'localhost';
DefaultPort = 8765;
DefaultMaxRetries = 3;
const
IniSection = 'Settings';
KeysSection = 'Keys';
procedure DisposeCommand(pData: Pointer);
begin
if Assigned(pData) then
FreeAndNil(TObject(pData));
end;
constructor TJFLircPlugin.Create;
begin
try
inherited Create;
fHwndMain := 0;
fWindow := 0;
FakeContextMenuId := 0;
hWndRemocon := 0;
if not ThisCallPatched then begin
TThisCallThunks.Create(Self, 13);
ThisCallPatched := True;
end;
fFields := TStringList.Create;
fModeCommands := THashTable.Create(False);
// default hash function causes integer overflows
fModeCommands.HashFunction := HashELF;
fStandardCommands := THashTable.Create(False);
fStandardCommands.HashFunction := HashELF;
fMenuCommands := THashTable.Create(False);
fMenuCommands.HashFunction := HashELF;
fMonitorCommands := THashTable.Create(False);
fMonitorCommands.HashFunction := HashELF;
fMappedCommands := THashTable.Create(True);
fMappedCommands.HashFunction := HashELF;
fMappedCommands.DisposeData := DisposeCommand;
fMappedKeys := TStringList.Create;
fMappedKeys.Sorted := True;
fIniFile := nil; // gets created in Open-method
fSocket := TClientSocket.Create(nil);
with fSocket do begin
Active := False;
OnConnect := csConnect;
OnDisconnect := csDisconnect;
OnRead := csRead;
OnError := csError;
end;
JFLircPlugin := Self;
except
on E: Exception do
HandleException(E);
end;
end;
destructor TJFLircPlugin.Destroy;
begin
JFLircPlugin := nil;
FreeAndNil(fSocket);
FreeAndNil(fMonitorCommands);
FreeAndNil(fMenuCommands);
FreeAndNil(fStandardCommands);
FreeAndNil(fModeCommands);
FreeAndNil(fMappedCommands); // DisposeCommand frees mapped commands
ClearMappedKeys;
FreeAndNil(fMappedKeys);
FreeAndNil(fFields);
if Assigned(fIniFile) then
FreeAndNil(fIniFile);
inherited Destroy;
// don't free the thunks because they are shared among all object instances
{if Assigned(ThisCallThunks) then
FreeAndNil(ThisCallThunks);}
end;
procedure TJFLircPlugin.CDestroy(Val: Integer);
begin
try
Free;
except
on E: Exception do
HandleException(E);
end;
end;
procedure TJFLircPlugin.GetInfo(pInfo: PJFInfo); stdcall;
begin
try
FillChar(pInfo^, SizeOf(TJFInfo), 0);
pInfo.m_uSDKVersion := $100; // 1.00
pInfo.m_szFilterName := PluginName;
pInfo.m_szFilterDesc := PluginDesc;
pInfo.m_szFilterWriter := 'BM-productions';
pInfo.m_uInputDeviceType := JDEVICE_UNKNOWN;
pInfo.m_uOutputDeviceType := JDEVICE_UNKNOWN;
pInfo.m_uInputStreamType := JSTREAM_UNKNOWN;
pInfo.m_uOutputStreamType := JSTREAM_UNKNOWN;
pInfo.m_uCategory := JCATEGORY_GENERAL;
pInfo.m_uCaps := JCAPS_HAS_CONFIG {or JCAPS_HAS_ABOUTBOX};
pInfo.m_bUnvisible := FALSE;
except
on E: Exception do
HandleException(E);
end;
end;
function TJFLircPlugin.SetPropertyPTR(pszPropName: PAnsiChar; pVal: PAnsiChar;
iValSize: Integer): BOOL;
begin
Result := False;
end;
function TJFLircPlugin.GetPropertyPTR(pszPropName: PAnsiChar; pVal: PAnsiChar;
iValSize: Integer): BOOL;
begin
Result := False;
end;
function TJFLircPlugin.SetPropertyINT(pszPropName: PAnsiChar;
nVal: Integer): BOOL;
begin
Result := False;
end;
function TJFLircPlugin.GetPropertyINT(pszPropName: PAnsiChar;
pnVal: PInteger): BOOL;
begin
Result := False;
end;
procedure TJFLircPlugin.Config(hWnd: HWND);
var
F: TextFile;
begin
if not Assigned(fIniFile) then
CreateAndOpenIniFile;
if not NewFileExists(fIniFile.FileName) then begin
AssignFile(F, fIniFile.FileName);
Rewrite(F);
CloseFile(F);
end;
ExecuteFile(fhWndMain, fIniFile.FileName, '', '', SW_SHOWNORMAL);
end;
procedure TJFLircPlugin.About(hWnd: HWND);
begin
// not called
end;
function TJFLircPlugin.GetErrorString(pszBuffer: PAnsiChar;
nBufferSize: Integer): JERROR_TYPE;
begin
Result := JERROR_UNKNOWN;
end;
function TJFLircPlugin.Open(hWnd: HWND; pszRootDir: PAnsiChar;
dwReserved1: DWORD; dwReserved2: DWORD): BOOL;
begin
Result := True;
try
fWindow := AllocateHWND(WndProc);
fhWndMain := hWnd;
hWndRemocon := JAGetRemoconWindow;
FillModeCommands;
FillStandardCommands;
FillMenuCommands;
FillMonitorCommands;
CreateAndOpenIniFile;
ReadWriteSettings(False);
fSocket.Host := fWinLircHost;
fSocket.Port := fWinLircPort;
TryConnect;
except
on E: Exception do
HandleException(E);
end;
end;
function TJFLircPlugin.Close: BOOL;
begin
Result := True;
try
fConnected := False;
fSocket.Close;
if fWindow <> 0 then begin
DeallocateHWND(fWindow);
fWindow := 0;
end;
except
on E: Exception do
HandleException(E);
end;
end;
function TJFLircPlugin.OnTimer(nCounter: Integer): BOOL;
begin
Result := True;
end;
function TJFLircPlugin.OnEvent(uEvent: UINT; wParam: WPARAM;
lParam: LPARAM): UINT;
begin
Result := 0;
end;
procedure TJFLircPlugin.csConnect(Sender: TObject; Socket: TCustomWinSocket);
begin
{$IFDEF Debug}
OutputDebugString('Status: Connected');
{$ENDIF}
fConnected := True;
KillTimer(fWindow, 0);
end;
procedure TJFLircPlugin.csDisconnect(Sender: TObject; Socket: TCustomWinSocket);
begin
{$IFDEF Debug}
OutputDebugString('Status: Disconnected');
{$ENDIF}
if fConnected then begin
MessageBox(fhWndMain, 'Connection with the WinLIRC server lost.' + CrLf2
+ 'Please verify that the server is still running and '
+ 'restart jetAudio to reconnect.', PluginName, MB_ICONWARNING);
end;
fConnected := False;
end;
procedure TJFLircPlugin.csError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
var
ServerCfged: Boolean;
begin
if ErrorEvent = eeConnect then begin
ServerCfged := (fWinLircServer <> '');
if not ServerCfged or (fTries = fMaxRetries) then begin
if not fNoConnectFailedWarning then begin
MessageBox(fhWndMain,
'Unable to connect to the WinLIRC server. ' + CrLf2
+ 'Check if the WinLIRC plug-in is configured correctly and '
+ 'verify that the server is running. '
+ 'Restart jetAudio to try again.', PluginName, MB_ICONWARNING);
end;
fTries := 0;
end
else if ServerCfged then begin
if fTries = 0 then
StartServer
else if fTries < fMaxRetries then begin
Inc(fTries);
SetTimer(fWindow, 0, 1000, nil);
end;
end;
end
else
OutputDebugString(PChar('Status: Error ' + IntToStr(ErrorCode)));
{ don't raise an exception, because this will occur in jetAudio's message loop
-> unhandled exception -> crash }
ErrorCode := 0;
end;
procedure TJFLircPlugin.csRead(Sender: TObject; Socket: TCustomWinSocket);
var
Data: String;
Command: Pointer;
begin
fFields.Clear;
Data := Socket.ReceiveText;
Split(Data, ' ', fFields);
if fFields.Count <> 4 then
Exit;
fFields[2] := Trim(fFields[2]);
if fMappedCommands.Search(fFields[2], Command) then begin
if Assigned(Command) then
TJACommand(Command).Execute;
end
else begin
fIniFile.WriteString(KeysSection, fFields[2], '');
fMappedCommands.Insert(fFields[2], nil);
fMappedKeys.AddObject(fFields[2], nil);
end;
end;
procedure TJFLircPlugin.WndProc(var Message: TMessage);
begin
if Message.Msg = WM_TIMER then begin
TryConnect;
KillTimer(fWindow, 0);
Message.Result := 0;
end;
end;
procedure TJFLircPlugin.StartServer;
begin
if not ExecuteFile(0, fWinLircServer, '', '', SW_SHOWNORMAL) then begin
MessageBox(fhWndMain, 'Unable to start the WinLIRC server. ' + CrLf2
+ 'Review the WinLIRC plug-in settings and '
+ 'check if the server filename points to a valid executable.',
PluginName, MB_ICONWARNING);
Exit;
end;
fTries := 1;
TryConnect;
end;
procedure TJFLircPlugin.TryConnect;
begin
if fWinLircHost <> '' then
fSocket.Active := True;
end;
procedure TJFLircPlugin.FillModeCommands;
begin
fModeCommands.Insert('discmode', Pointer(jamDisc));
fModeCommands.Insert('filemode', Pointer(jamFile));
end;
const
RepeatModeNames: array[eRepeatMode] of String =
('none', 'this', 'all');
RandomModeNames: array[eRandomMode] of String =
('normal', 'random', 'program');
procedure TJFLircPlugin.FillStandardCommands;
procedure AddCommand(const Name: String; Command, Param: Word);
begin
fStandardCommands.Insert(Name, Pointer(MAKELPARAM(Command, Param)));
end;
var
RepMode: eRepeatMode;
RandMode: eRandomMode;
begin
AddCommand('stop', JRC_ID_STOP, 0);
AddCommand('play', JRC_ID_PLAY, 0);
AddCommand('playresume', JRC_ID_PLAY_RESUME, 0);
AddCommand('prevtrack', JRC_ID_PREV_TRACK, 0);
AddCommand('nexttrack', JRC_ID_NEXT_TRACK, 0);
AddCommand('cyclerepeatmode', JRC_ID_REPEATMODE, 0);
for RepMode := Low(eRepeatMode) to High(eRepeatMode) do begin
AddCommand('setrepeat' + RepeatModeNames[RepMode], JRC_ID_REPEATMODE,
Integer(RepMode) + 1);
end;
AddCommand('backward', JRC_ID_BACKWARD, 0);
AddCommand('forward', JRC_ID_FORWARD, 0);
AddCommand('cycleplaymode', JRC_ID_RANDOMMODE, 0);
for RandMode := Low(eRandomMode) to High(eRandomMode) do begin
AddCommand('setplaymode' + RandomModeNames[RandMode], JRC_ID_RANDOMMODE,
Integer(RandMode) + 1);
end;
AddCommand('playslower', JRC_ID_PLAY_SLOW, 0);
AddCommand('playfaster', JRC_ID_PLAY_FAST, 0);
AddCommand('volumedown', JRC_ID_VOL_DOWN, 0);
AddCommand('volumeup', JRC_ID_VOL_UP, 0);
AddCommand('exit', JRC_ID_EXIT, 0);
AddCommand('togglemute', JRC_ID_ATT, 0);
{AddCommand('muteon', JRC_ID_ATT, 1);
AddCommand('muteoff', JRC_ID_ATT, $FFFF);} // doesn't work
AddCommand('screen1x', JRC_ID_SCREEN_1X, 0);
AddCommand('screen2x', JRC_ID_SCREEN_2X, 0);
AddCommand('screenfull', JRC_ID_SCREEN_FULL, 0);
AddCommand('togglefullscreen', JRC_ID_CHANGE_SCREEN_SIZE, 0);
AddCommand('minimizerestore', JRC_ID_MINIMIZE, 0);
AddCommand('togglewidemode', JRC_ID_CHANGE_SFX_WIDE, 0);
AddCommand('togglexbassmode', JRC_ID_CHANGE_SFX_XBASS, 0);
AddCommand('togglebbemode', JRC_ID_CHANGE_SFX_BBE, 0);
AddCommand('togglebbevivamode', JRC_ID_CHANGE_SFX_B3D, 0);
// for some reason, JRC_ID_CHANGE_SFX_XFADE and JRC_ID_CHANGE_SFX_XSR got
// mixed up in the API
AddCommand('togglecrossfade', JRC_ID_CHANGE_SFX_XSR, 0);
AddCommand('togglexsurround', JRC_ID_CHANGE_SFX_XFADE, 0);
AddCommand('eject', JRC_ID_EJECT_DRIVE, 0);
AddCommand('toggletray', JRC_ID_GOTO_TRAY, 0);
AddCommand('refreshalbum', JRC_ID_ALBUM_REFRESH, 0);
AddCommand('sortalbum', JRC_ID_ALBUM_SORT, 0);
AddCommand('goup', JRC_ID_GOUP, 0);
AddCommand('cyclelang', JRC_ID_DVD_CHANGE_LANGUAGE, 0);
AddCommand('cyclesubtitle', JRC_ID_DVD_CHANGE_SUBTITLE, 0);
AddCommand('cycleangle', JRC_ID_DVD_CHANGE_ANGLE, 0);
AddCommand('togglesubtitle', JRC_ID_DVD_SUBTITLE_FLAG, 0);
AddCommand('titlemenu', JRC_ID_DVDMENU_TITLE, 0);
AddCommand('rootmenu', JRC_ID_DVDMENU_ROOT, 0);
AddCommand('up', JRC_ID_DVD_BUTTON, VK_UP);
AddCommand('down', JRC_ID_DVD_BUTTON, VK_DOWN);
AddCommand('left', JRC_ID_DVD_BUTTON, VK_LEFT);
AddCommand('right', JRC_ID_DVD_BUTTON, VK_RIGHT);
AddCommand('enter', JRC_ID_DVD_BUTTON, VK_RETURN);
end;
const
AspectModeCommands: array[eAspectMode] of String =
('aspectoriginal', 'aspect43', 'aspect169', 'aspect1851', 'aspect2351');
procedure TJFLircPlugin.FillMenuCommands;
var
Aspect: eAspectMode;
begin
for Aspect := Low(eAspectMode) to High(eAspectMode) do begin
fMenuCommands.Insert(AspectModeCommands[Aspect],
Pointer(AspectMenuId + Integer(Aspect)));
end;
end;
procedure TJFLircPlugin.FillMonitorCommands;
const
MaxMonitorIdx = 9;
var
i: Integer;
begin
fMonitorCommands.Insert('cyclemonitor', Pointer(-1));
for i := 1 to MaxMonitorIdx do // start from 1 (most users aren't programmers)
fMonitorCommands.Insert('setmonitor' + IntToStr(i), Pointer(i - 1));
end;
procedure TJFLircPlugin.CreateAndOpenIniFile;
var
IniDir: String;
begin
IniDir := AddBackSlash(GetShellFolderByCSIDL(CSIDL_APPDATA, True))
+ 'COWON\JetAudio';
if not CreateDirectory(PChar(IniDir), nil)
and (GetLastError <> ERROR_ALREADY_EXISTS) then
IniDir := '';
fIniFile := TIniFile.Create(AddBackSlash(IniDir) + 'JFLirc.ini');
end;
procedure TJFLircPlugin.ReadWriteSettings(Write: Boolean);
procedure ReadWriteInteger(const Ident: String; var Value: Integer;
Default: Integer);
begin
if Write then
fIniFile.WriteInteger(IniSection, Ident, Value)
else
Value := fIniFile.ReadInteger(IniSection, Ident, Default);
end;
procedure ReadWriteString(const Ident: String; var Value: String;
Default: String);
begin
if Write then
fIniFile.WriteString(IniSection, Ident, Value)
else
Value := fIniFile.ReadString(IniSection, Ident, Default);
end;
procedure ReadWriteBool(const Ident: String; var Value: Boolean;
Default: Boolean);
begin
if Write then
fIniFile.WriteBool(IniSection, Ident, Value)
else
Value := fIniFile.ReadBool(IniSection, Ident, Default);
end;
var
i: Integer;
begin
if Assigned(fIniFile) then begin
ReadWriteString('WinLircHost', fWinLircHost, DefaultHost);
ReadWriteInteger('WinLircPort', fWinLircPort, DefaultPort);
ReadWriteString('WinLircServer', fWinLircServer, '');
ReadWriteInteger('MaxRetries', fMaxRetries, DefaultMaxRetries);
ReadWriteBool('NoConnectFailedWarning', fNoConnectFailedWarning, False);
if not Write then begin
ClearMappedKeys;
fIniFile.ReadSection(KeysSection, fMappedKeys);
for i := 0 to fMappedKeys.Count - 1 do begin
fMappedKeys.Objects[i] :=
RefString(fIniFile.ReadString(KeysSection, fMappedKeys[i], ''));
end;
ResolveMappings;
end;
end
else if not Write then begin
fWinLircHost := DefaultHost;
fWinLircPort := DefaultPort;
fWinLircServer := '';
fMaxRetries := DefaultMaxRetries;
fNoConnectFailedWarning := False;
end;
end;
procedure TJFLircPlugin.ResolveMappings;
var
i: Integer;
pCommandStr: Pointer;
CommandStr: String;
Command: TJACommand;
CommandParam: Pointer;
begin
fMappedCommands.Empty;
for i := 0 to fMappedKeys.Count - 1 do begin
Command := nil;
pCommandStr := fMappedKeys.Objects[i];
if Assigned(pCommandStr) then begin
CommandStr := String(pCommandStr);
if fStandardCommands.Search(CommandStr, CommandParam) then
Command := TStandardJACommand.Create(Self, Integer(CommandParam));
if fModeCommands.Search(CommandStr, CommandParam) then
Command := TModeJACommand.Create(Self, TJAMode(CommandParam));
if fMenuCommands.Search(CommandStr, CommandParam) then
Command := TMenuJACommand.Create(Self, Integer(CommandParam));
if fMonitorCommands.Search(CommandStr, CommandParam) then
Command := TSwitchMonitorCommand.Create(Self, Integer(CommandParam));
end;
fMappedCommands.Insert(fMappedKeys[i], Command);
end;
end;
procedure TJFLircPlugin.ClearMappedKeys;
var
P: Pointer;
begin
while fMappedKeys.Count > 0 do begin
P := fMappedKeys.Objects[0];
fMappedKeys.Delete(0);
if Assigned(P) then
ReleaseString(P);
end;
end;
procedure TJFLircPlugin.HandleException(E: Exception);
var
Info: String;
begin
if Assigned(E) then
Info := CrLf + '(' + E.ClassName + ' : ' + E.Message + ')';
MessageBox(fHwndMain, PChar('An unexpected error occurred.' + Info + CrLf2
+ 'Please contact the author if the problems persists.'),
PluginName, MB_ICONERROR);
end;
end.
|
unit uChamadoQuadroViewModel;
interface
uses
System.Classes, uClienteVO, uStatusVO, uTipoVo, uUsuarioVO, System.SysUtils,
System.Generics.Collections;
type
TChamadoQuadroViewModel = class
private
FIdChamado: Integer;
FParCodigo: Integer;
FQuadro: string;
FCliente: TClienteVO;
FHoraAtendeAtual: TTime;
FUltimaData: TDate;
FDataAbertura: TDateTime;
FIdUsuarioAtendeAtual: Integer;
FStatus: TStatusVO;
FNivel: Integer;
FHoraAbertura: TTime;
FCha_Nivel: string;
FUsuario: TUsuarioVO;
FTipo: TTipoVO;
FUltimaHora: TDateTime;
procedure SetCha_Nivel(const Value: string);
procedure SetCliente(const Value: TClienteVO);
procedure SetDataAbertura(const Value: TDateTime);
procedure SetHoraAbertura(const Value: TTime);
procedure SetHoraAtendeAtual(const Value: TTime);
procedure SetIdChamado(const Value: Integer);
procedure SetIdUsuarioAtendeAtual(const Value: Integer);
procedure SetNivel(const Value: Integer);
procedure SetParCodigo(const Value: Integer);
procedure SetQuadro(const Value: string);
procedure SetStatus(const Value: TStatusVO);
procedure SetTipo(const Value: TTipoVO);
procedure SetUltimaData(const Value: TDate);
procedure SetUsuario(const Value: TUsuarioVO);
procedure SetUltimaHora(const Value: TDateTime);
public
property Quadro: string read FQuadro write SetQuadro;
property IdChamado: Integer read FIdChamado write SetIdChamado;
property DataAbertura: TDateTime read FDataAbertura write SetDataAbertura;
property HoraAbertura: TTime read FHoraAbertura write SetHoraAbertura;
property Nivel: Integer read FNivel write SetNivel;
property Cha_Nivel: string read FCha_Nivel write SetCha_Nivel;
property IdUsuarioAtendeAtual: Integer read FIdUsuarioAtendeAtual write SetIdUsuarioAtendeAtual;
property UltimaData: TDate read FUltimaData write SetUltimaData;
property HoraAtendeAtual: TTime read FHoraAtendeAtual write SetHoraAtendeAtual;
property ParCodigo: Integer read FParCodigo write SetParCodigo;
property UltimaHora: TDateTime read FUltimaHora write SetUltimaHora;
property Cliente: TClienteVO read FCliente write SetCliente;
property Status: TStatusVO read FStatus write SetStatus;
property Tipo: TTipoVO read FTipo write SetTipo;
property Usuario: TUsuarioVO read FUsuario write SetUsuario;
constructor Create(); overload;
destructor destroy; override;
end;
TListaChamadoQuadroViewModel = TObjectList<TChamadoQuadroViewModel>;
implementation
{ TChamadoQuadroViewModel }
constructor TChamadoQuadroViewModel.Create;
begin
inherited Create;
FCliente := TClienteVO.create;
FStatus := TStatusVO.Create;
FTipo := TTipoVO.Create;
FUsuario := TUsuarioVO.Create;
end;
destructor TChamadoQuadroViewModel.destroy;
begin
FreeAndNil(FCliente);
FreeAndNil(FStatus);
FreeAndNil(FTipo);
FreeAndNil(FUsuario);
inherited;
end;
procedure TChamadoQuadroViewModel.SetCha_Nivel(const Value: string);
begin
FCha_Nivel := Value;
end;
procedure TChamadoQuadroViewModel.SetCliente(const Value: TClienteVO);
begin
FCliente := Value;
end;
procedure TChamadoQuadroViewModel.SetDataAbertura(const Value: TDateTime);
begin
FDataAbertura := Value;
end;
procedure TChamadoQuadroViewModel.SetHoraAbertura(const Value: TTime);
begin
FHoraAbertura := Value;
end;
procedure TChamadoQuadroViewModel.SetHoraAtendeAtual(const Value: TTime);
begin
FHoraAtendeAtual := Value;
end;
procedure TChamadoQuadroViewModel.SetIdChamado(const Value: Integer);
begin
FIdChamado := Value;
end;
procedure TChamadoQuadroViewModel.SetIdUsuarioAtendeAtual(const Value: Integer);
begin
FIdUsuarioAtendeAtual := Value;
end;
procedure TChamadoQuadroViewModel.SetNivel(const Value: Integer);
begin
FNivel := Value;
end;
procedure TChamadoQuadroViewModel.SetParCodigo(const Value: Integer);
begin
FParCodigo := Value;
end;
procedure TChamadoQuadroViewModel.SetQuadro(const Value: string);
begin
FQuadro := Value;
end;
procedure TChamadoQuadroViewModel.SetStatus(const Value: TStatusVO);
begin
FStatus := Value;
end;
procedure TChamadoQuadroViewModel.SetTipo(const Value: TTipoVO);
begin
FTipo := Value;
end;
procedure TChamadoQuadroViewModel.SetUltimaData(const Value: TDate);
begin
FUltimaData := Value;
end;
procedure TChamadoQuadroViewModel.SetUltimaHora(const Value: TDateTime);
begin
FUltimaHora := Value;
end;
procedure TChamadoQuadroViewModel.SetUsuario(const Value: TUsuarioVO);
begin
FUsuario := Value;
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_Rasterizer
* Implements a triangle software rasterizer
***********************************************************************************************************************
}
Unit TERRA_Rasterizer;
{$I terra.inc}
{
How to use:
1 - Attach a target image to a rasterizer.Target property
2 - Add the X and Y of each of the 3 corners with
Rasterizer.SetInterpolatorValues(rasterX, X1, X2, X3);
Rasterizer.SetInterpolatorValues(rasterY, Y1, Y2, Y3);
3 - Add any other values for interpolation (optional)
4 - Call Rasterizer.Rasterize to output a triangle to the target image
}
Interface
Uses TERRA_Utils, TERRA_Image, TERRA_Color, TERRA_Vector3D;
Const
rasterX = 0;
rasterY = 1;
rasterZ = 2;
rasterU = 3;
rasterV = 4;
rasterW = 5;
rasterNX = 6;
rasterNY = 7;
rasterNZ = 8;
Type
InterpolatorValues = Array[0..2] Of Single;
Rasterizer = Class(TERRAObject)
Protected
_MinY, _MaxY:Integer;
_IL, _IR:Array Of Array Of Single;
_Target:Image;
_Value, _Add:Array Of Single;
_Interpolators:Array Of InterpolatorValues;
_InterpolatorCount:Integer;
Procedure SetColor(Values:PSingleArray; Dest:PColor); Virtual;
Procedure DoLine(Y:Integer);
Procedure DoSide(A,B:Integer);
Procedure InitBuffers;
Public
// all coordinates are in normalized space (0.0 to 1.0)
Procedure SetInterpolatorValues(Index:Integer; A,B,C:Single; Normalized:Boolean=True); Overload;
Procedure Rasterize;
Property Target:Image Read _Target Write _Target;
End;
ColorRasterizer = Class(Rasterizer)
Protected
Procedure SetColor(Values:PSingleArray; Dest:PColor); Override;
Public
FillColor:Color;
End;
Procedure FillGutter(Target, GutterMask:Image; Levels:Integer);
Implementation
Uses TERRA_Log;
Procedure Rasterizer.DoLine(Y:Integer);
Var
I,D:Integer;
O:Word;
Dest:PColor;
U,V,Ux,Vx:Single;
Count:Integer;
X1,X2:Integer;
Begin
For I:=0 To Pred(_InterpolatorCount) Do
_Value[I] := _IL[Y, I];
X1 := Trunc(_IL[Y, rasterX]);
X2 := Trunc(_IR[Y, rasterX]);
Count := (X2 - X1);
If Count<=0 Then
For I:=0 To Pred(_InterpolatorCount) Do
_Add[I] := 0
Else
For I:=0 To Pred(_InterpolatorCount) Do
_Add[I] := (_IR[Y,I] - _IL[Y,I])/Count;
Dest := _Target.GetPixelOffset(X1,Y);
While (Count>0) Do
Begin
Self.SetColor(@_Value[0], Dest);
Inc(Dest);
Dec(Count);
For I:=0 To Pred(_InterpolatorCount) Do
_Value[I] := _Value[I] + _Add[I];
End;
End;
Procedure Rasterizer.DoSide(A,B:Integer);
Var
I:Integer;
Y1,Y2:Integer;
Temp,Y:Integer;
Begin
Y1 := Trunc(_Interpolators[rasterY, A]);
Y2 := Trunc(_Interpolators[rasterY, B]);
If (Y1=Y2) Then
Exit;
If (Y1>Y2) Then
Begin
DoSide(B, A);
Exit;
End;
For I:=0 To Pred(_InterpolatorCount) Do
Begin
_Value[I] := _Interpolators[I, A];
_Add[I] := (_Interpolators[I, B] - _Interpolators[I, A]) /(Y2-Y1);
End;
For Y:=Y1 To Y2 Do
Begin
If (Y>=_Target.Height) Then
Exit;
If Y>_MaxY Then
_MaxY := Y;
If Y<_MinY Then
_MinY := Y;
If Y>=0 Then
Begin
If _Value[rasterX]<_IL[Y, rasterX] Then
Begin
For I:=0 To Pred(_InterpolatorCount) Do
_IL[Y, I] := _Value[I];
End;
If _Value[rasterX]>_IR[Y, rasterX] Then
Begin
For I:=0 To Pred(_InterpolatorCount) Do
_IR[Y, I] := _Value[I];
End;
End;
For I:=0 To Pred(_InterpolatorCount) Do
_Value[I] := _Value[I] + _Add[I];
End;
End;
Procedure Rasterizer.InitBuffers;
Var
I:Integer;
Begin
SetLength(_IL, _Target.Height, _InterpolatorCount);
SetLength(_IR, _Target.Height, _InterpolatorCount);
SetLength(_Value, _InterpolatorCount);
SetLength(_Add, _InterpolatorCount);
For I:=0 To Pred(_Target.Height) Do
Begin
_IL[I, rasterX] := _Target.Width;
_IR[I, rasterX] := 0;
End;
_MinY := _Target.Height;
_MaxY := 0;
DoSide(0, 1);
DoSide(1, 2);
DoSide(2, 0);
End;
Procedure Rasterizer.Rasterize;
Var
I:Integer;
Begin
Self.InitBuffers;
For I:=_MinY To _MaxY Do
If (I<0) Then
Continue
Else
Self.DoLine(I);
End;
Procedure Rasterizer.SetColor(Values: PSingleArray; Dest:PColor);
Begin
Dest^ := ColorBlack;
End;
Procedure Rasterizer.SetInterpolatorValues(Index:Integer; A,B,C:Single; Normalized:Boolean=True);
Begin
If (Index>Pred(_InterpolatorCount)) Then
Begin
_InterpolatorCount := Succ(Index);
SetLength(_Interpolators, _InterpolatorCount);
End;
If (Index = rasterX) And (Normalized) Then
Begin
A := A * _Target.Width;
B := B * _Target.Width;
C := C * _Target.Width;
End;
If (Index = rasterY) And (Normalized) Then
Begin
A := A * _Target.Height;
B := B * _Target.Height;
C := C * _Target.Height;
End;
_Interpolators[Index, 0] := A;
_Interpolators[Index, 1] := B;
_Interpolators[Index, 2] := C;
End;
{ ColorRasterizer }
Procedure ColorRasterizer.SetColor(Values: PSingleArray; Dest: PColor);
Begin
Dest^ := FillColor;
End;
Type
GutterTexel = Record
X,Y:Integer;
PX,PY:Integer;
End;
Procedure FillGutter(Target, GutterMask:Image; Levels:Integer);
Var
_GutterTexels:Array Of GutterTexel;
_GutterCount:Integer;
P:Color;
I,J,K:Integer;
Mask:Image;
Function FindGutter(Var Texel:GutterTexel):Boolean;
Const
GX:Array[0..7] Of Integer = (-1,1,-1,0,1,-1,0,1);
GY:Array[0..7] Of Integer = (0, 0, -1,-1,-1, 1,1 ,1);
Var
P:Color;
I,J:Integer;
PX,PY:Integer;
Begin
Result := True;
For I:=0 To 7 Do
Begin
PX := Texel.X + GX[I];
PY := Texel.Y + GY[I];
If (PX<0) Or (PY<0) Or (PX>=Mask.Width) Or (PY>=Mask.Height) Then
Continue;
P := Mask.GetPixel(PX,PY);
If (P.A<>0) Then
Begin
Texel.PX := PX;
Texel.PY := PY;
Exit;
End;
End;
Result := False;
End;
Begin
_GutterCount := 0;
If Assigned(GutterMask) Then
Mask := Image.Create(GutterMask)
Else
Mask := Image.Create(Target);
For K:=1 To Levels Do
Begin
For J:=0 To Pred(Mask.Height) Do
For I:=0 To Pred(Mask.Width) Do
Begin
If (I=18) And (J=0) Then
IntToString(2);
P := Mask.GetPixel(I,J);
If (P.A=0) Then
Begin
Inc(_GutterCount);
SetLength(_GutterTexels, _GutterCount);
_GutterTexels[Pred(_GutterCount)].X := I;
_GutterTexels[Pred(_GutterCount)].Y := J;
If Not FindGutter(_GutterTexels[Pred(_GutterCount)]) Then
Dec(_GutterCount);
End;
End;
For I:=0 To Pred(_GutterCount) Do
Mask.SetPixel(_GutterTexels[I].X, _GutterTexels[I].Y, ColorWhite);
End;
ReleaseObject(Mask);
Mask := Nil;
For I:=0 To Pred(_GutterCount) Do
Begin
P := Target.GetPixel(_GutterTexels[I].PX, _GutterTexels[I].PY);
Target.SetPixel(_GutterTexels[I].X, _GutterTexels[I].Y, P);
End;
End;
End.
|
unit MFichas.Model.Empresa.Metodos.Editar.View;
interface
uses
System.SysUtils,
System.Generics.Collections,
MFichas.Model.Empresa.Interfaces,
MFichas.Model.Entidade.EMPRESA,
ORMBR.Types.Blob;
type
TModelEmpresaMetodosEditarView = class(TInterfacedObject, iModelEmpresaMetodosEditarView)
private
[weak]
FParent : iModelEmpresa;
FEntidade : TEMPRESA;
FNomeEmpresa: String;
FLogoEmpresa: TBlob;
FListaEmpresa: TObjectList<TEMPRESA>;
constructor Create(AParent: iModelEmpresa);
procedure RecuperarObjectoNoBancoDeDados;
procedure Gravar;
public
destructor Destroy; override;
class function New(AParent: iModelEmpresa): iModelEmpresaMetodosEditarView;
function Descricao(ANomeEmpresa: String): iModelEmpresaMetodosEditarView;
function LogoTipo(ALogoEmpresa: String) : iModelEmpresaMetodosEditarView;
function &End : iModelEmpresaMetodos;
end;
implementation
{ TModelEmpresaMetodosEditarView }
function TModelEmpresaMetodosEditarView.&End: iModelEmpresaMetodos;
begin
Result := FParent.Metodos;
RecuperarObjectoNoBancoDeDados;
Gravar;
end;
procedure TModelEmpresaMetodosEditarView.Gravar;
begin
FParent.DAO.Modify(FEntidade);
FEntidade.DESCRICAO := FNomeEmpresa;
FEntidade.LOGOTIPO := FLogoEmpresa;
FParent.DAO.Update(FEntidade);
end;
constructor TModelEmpresaMetodosEditarView.Create(AParent: iModelEmpresa);
begin
FParent := AParent;
FEntidade := TEMPRESA.Create;
end;
function TModelEmpresaMetodosEditarView.Descricao(
ANomeEmpresa: String): iModelEmpresaMetodosEditarView;
begin
Result := Self;
FNomeEmpresa := ANomeEmpresa;
end;
destructor TModelEmpresaMetodosEditarView.Destroy;
begin
{$IFDEF MSWINDOWS}
FreeAndNil(FEntidade);
if Assigned(FListaEmpresa) then
FreeAndNil(FListaEmpresa);
{$ELSE}
FEntidade.Free;
FEntidade.DisposeOf;
if Assigned(FListaEmpresa) then
begin
FListaEmpresa.Free;
FListaEmpresa.DisposeOf;
end;
{$ENDIF}
inherited;
end;
function TModelEmpresaMetodosEditarView.LogoTipo(
ALogoEmpresa: String): iModelEmpresaMetodosEditarView;
begin
Result := Self;
FLogoEmpresa.LoadFromFile(ALogoEmpresa);
end;
class function TModelEmpresaMetodosEditarView.New(AParent: iModelEmpresa): iModelEmpresaMetodosEditarView;
begin
Result := Self.Create(AParent);
end;
procedure TModelEmpresaMetodosEditarView.RecuperarObjectoNoBancoDeDados;
begin
FListaEmpresa := FParent.DAO.Find;
FEntidade.GUUID := FListaEmpresa[0].GUUID;
FEntidade.DESCRICAO := FListaEmpresa[0].DESCRICAO;
FEntidade.LOGOTIPO := FListaEmpresa[0].LOGOTIPO;
FEntidade.DATACADASTRO := FListaEmpresa[0].DATACADASTRO;
FEntidade.DATAALTERACAO := FListaEmpresa[0].DATAALTERACAO;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.Data.Base
Description : Data Metrics
Author : Kike Pérez
Version : 1.0
Created : 08/04/2019
Modified : 08/04/2019
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Data.Custom;
{$i QuickLib.inc}
interface
uses
SysUtils,
Quick.Commons;
type
TOutputOptions = class
private
fUseUTCTime : Boolean;
public
property UseUTCTime : Boolean read fUseUTCTime write fUseUTCTime;
end;
IDataProvider = interface
['{D4D03D84-9BD7-49A0-8A46-0E89E0988F58}']
function Send(const aName, aValue : string): Boolean; overload;
function Send(const aName : string; aValue : Integer): Boolean; overload;
function Send(const aName : string; aValue : Extended): Boolean; overload;
function Send(const aName : string; aValue : TDateTime): Boolean; overload;
end;
TDataProvider = class(TInterfacedObject,IDataProvider)
private
fOutputOptions : TOutputOptions;
protected
fInitiated : Boolean;
public
constructor Create; virtual;
destructor Destroy; override;
property OutputOptions : TOutputOptions read fOutputOptions write fOutputOptions;
procedure Init; virtual;
procedure Stop; virtual;
procedure Restart; virtual; abstract;
function Send(const aName, aValue : string): Boolean; overload; virtual; abstract;
function Send(const aName : string; aValue : Integer): Boolean; overload; virtual; abstract;
function Send(const aName : string; aValue : Extended): Boolean; overload; virtual; abstract;
function Send(const aName : string; aValue : TDateTime): Boolean; overload; virtual; abstract;
end;
const
DEF_USER_AGENT = 'Quick.Data.Base Agent';
implementation
{ TDataProvider }
constructor TDataProvider.Create;
begin
fOutputOptions := TOutputOptions.Create;
fInitiated := False;
end;
destructor TDataProvider.Destroy;
begin
fOutputOptions.Free;
fInitiated := False;
inherited;
end;
procedure TDataProvider.Init;
begin
fInitiated := True;
end;
procedure TDataProvider.Stop;
begin
fInitiated := False;
end;
end.
|
{ Version 2.0 - Author jasc2v8 at yahoo dot com
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org> }
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
FileCtrl, EditBtn, strutils, lclintf, htmlbrowser, DebugUnit;
type
{ TfrmMain }
TfrmMain = class(TForm)
btnHelp: TButton;
btnRemove: TButton;
btnAdd: TButton;
btnDemo: TButton;
DirectoryEdit: TDirectoryEdit;
FileListBox: TFileListBox;
procedure btnHelpClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure btnDemoClick(Sender: TObject);
procedure DirectoryEditChange(Sender: TObject);
procedure FormShow(Sender: TObject);
end;
const
DS=DirectorySeparator;
LE=LineEnding;
var
frmMain: TfrmMain;
Viewer: THTMLBrowserViewer;
implementation
{$R *.lfm}
{ TfrmMain }
procedure TfrmMain.btnHelpClick(Sender: TObject);
begin
//lclintf.OpenURL('help.html');
Viewer.OpenResource('help.html');
end;
procedure TfrmMain.btnDemoClick(Sender: TObject);
begin
DebugForm.Show;
Debugln('Unformatted output up to 8 Args of any Type:');
Debugln('--------------------------------------------');
Debugln(1,2,3,4,5,6,7,8);
Debugln('binary =', %010);
Debugln('boolean =', true);
Debugln('decimal =', 10);
Debugln('general =', 3.1415927);
Debugln('hex =', $0010);
Debugln('octal =', &0010);
Debugln('scientific=', 1.9E6);
Debugln('signed =', -100, ' or ', +100);
Debugln('string =', 'the quick brown fox');
Debugln('mixed bin=',%010,',bool=',true,',dec=',10,',gen=',3.1415927);
Debugln(LE+'Unformatted output with Array of Variant:');
Debugln( '-----------------------------------------');
Debugln(['decimal', -1,true,3.1415,4,5]);
Debugln(['T1=', true,',T2=',false,',T3=',01.23]);
Debugln(LE+'Formatted output with Array of Const:');
Debugln( '-------------------------------------');
Debugln('boolean =%s or %s', [BoolToStr(true,false), BoolToStr(true,true)]);
Debugln('currency =%m', [1000000.]);
Debugln('decimal =%d', [-1]);
Debugln('float =%f', [3.1415927]);
Debugln('general =%g', [3.1415927]);
Debugln('hex =%x', [-1]);
Debugln('number =%n', [1000000.]);
Debugln('scientific=%e', [1.0e3]);
Debugln('string =%s', ['the quick brown fox']);
Debugln('unsigned =%u', [-1]);
Debugln('mixed cur =%m, dec=%d',[1000000., 10]);
Debugln('mixed float=%f, num=%n',[3.1415927, 1000000.]);
DebugForm.Memo.SelStart:=0; //scroll to top
end;
procedure TfrmMain.DirectoryEditChange(Sender: TObject);
var
i: integer;
begin
FileListBox.Sorted:=false;
FileListBox.Mask:='*.lpr;*.pas;*.pp';
FileListBox.Directory:=DirectoryEdit.Text;
for i:=0 to FileListBox.Items.Count-1 do begin
if not (FileListBox.Items[i]='debugunit.pas') then
FileListBox.Selected[i]:=true;
end;
end;
procedure TfrmMain.btnAddClick(Sender: TObject);
var
i,j: integer;
aFilename, aFilepath: string;
OldFile, NewFile: TStringList;
inUses: boolean;
aLine: string;
begin
if FileListBox.Count=0 then Exit;
OldFile:=TStringList.Create;
NewFile:=TStringList.Create;
for i:=0 to FileListBox.Count-1 do begin
if not FileListBox.Selected[i] then
Continue;
aFileName:=FileListBox.Directory+DS+FileListBox.Items[i];
Debugln('aFilename='+aFilename);
OldFile.LoadFromFile(aFilename);
if AnsiContainsText(OldFile.Text, 'DebugUnit') then begin
ShowMessage('DebugUnit already added to: '+LE+LE+aFilename);
Continue;
end;
if not AnsiContainsText(OldFile.Text, 'uses') then begin
ShowMessage('DebugUnit can''t be added, no uses section in: '+LE+LE+aFilename);
Continue;
end;
CopyFile(aFilename, aFilename+'.bak', [cffOverwriteFile]);
inUses:=false;
j:=0;
repeat
if AnsiContainsText(OldFile[j],'uses') then begin
inUses:=true;
end;
{ will not detect a missing ';' after the uses statement }
if inUses and OldFile[j].EndsWith(';') then begin
aLine:=StringReplace(OldFile[j],';',', DebugUnit;',[]);
OldFile[j]:=aLine;
inUses:=false;
end;
if AnsiContainsText(OldFile[j],'Application.Run') then
NewFile.Append(' Application.CreateForm(TDebugForm, DebugForm);');
NewFile.Append(OldFile[j]);
Inc(j);
until j=OldFile.Count;
NewFile.SaveToFile(aFilename);
ShowMessage('DebugUnit added in: '+LE+LE+aFilename);
OldFile.Clear;
NewFile.Clear;
end;
aFilepath:=ExtractFilePath(aFilename);
aFilename:='debugunit.pas';
if not FileExists(aFilePath+aFilename) then
if FileExists(aFilename) then
CopyFile(aFilename, aFilepath+aFilename)
else
ShowMessage('Error: debugunit.pas not in current directory');
aFilename:='debugunit.lfm';
if not FileExists(aFilePath+aFilename) then
if FileExists(aFilename) then
CopyFile(aFilename, aFilepath+aFilename)
else
ShowMessage('Error: debugunit.lfm not in current directory');
FileListBox.UpdateFileList;
DirectoryEditChange(nil);
OldFile.Free;
NewFile.Free;
end;
procedure TfrmMain.btnRemoveClick(Sender: TObject);
var
i,j: integer;
aFilename: string;
OldFile, NewFile: TStringList;
aLine: string;
begin
if FileListBox.Count=0 then Exit;
OldFile:=TStringList.Create;
NewFile:=TStringList.Create;
for i:=0 to FileListBox.Count-1 do begin
if not FileListBox.Selected[i] then
Continue;
aFileName:=FileListBox.Directory+DS+FileListBox.Items[i];
OldFile.LoadFromFile(aFilename);
if not AnsiContainsText(OldFile.Text, 'DebugUnit') then begin
ShowMessage('DebugUnit already removed from: '+LE+LE+aFilename);
Continue;
end;
CopyFile(aFilename, aFilename+'.bak', [cffOverwriteFile]);
j:=0;
repeat
if AnsiContainsText(OldFile[j],', DebugUnit;') then begin
aLine:=StringReplace(OldFile[j],', DebugUnit;',';',[]);
OldFile[j]:=aLine;
ShowMessage('DebugUnit removed from: '+LE+LE+aFilename);
end;
if AnsiContainsText(OldFile[j],',DebugUnit;') then begin
aLine:=StringReplace(OldFile[j],',DebugUnit;',';',[]);
OldFile[j]:=aLine;
ShowMessage('DebugUnit removed from: '+LE+LE+aFilename);
end;
if AnsiContainsText(OldFile[j],
'Application.CreateForm(TDebugForm, DebugForm);') then begin
//don't repeat ShowMessage('DebugUnit removed from: '+LE+LE+aFilename);
end
else
NewFile.Append(OldFile[j]);
Inc(j);
until j=OldFile.Count;
NewFile.SaveToFile(aFilename);
OldFile.Clear;
NewFile.Clear;
end;
aFilename:=ExtractFilePath(aFilename)+'debugunit.pas';
if FileExists(aFilename) then
DeleteFile(aFilename);
aFilename:=ExtractFilePath(aFilename)+'debugunit.lfm';
if FileExists(aFilename) then
DeleteFile(aFilename);
FileListBox.UpdateFileList;
DirectoryEditChange(nil);
OldFile.Free;
NewFile.Free;
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
//DebugForm.Show;
//Debugln('Ready');
Viewer:=THTMLBrowserViewer.Create;
Viewer.ExtractResFiles;
FileListBox.Clear;
end;
end.
|
unit atNonATQueryLogicOperationConverter;
// Модуль: "w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atNonATQueryLogicOperationConverter.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TatNonATQueryLogicOperationConverter" MUID: (503E51C002D7)
interface
uses
l3IntfUses
, SearchUnit
, SysUtils
;
type
_SecondType_ = TQueryLogicOperation;
{$Include w:\quality\test\garant6x\AdapterTest\CoreObjects\atStringConverter.imp.pas}
TatNonATQueryLogicOperationConverter = class(_atStringConverter_)
protected
procedure InitConvertMap; override;
public
class function Instance: TatNonATQueryLogicOperationConverter;
{* Метод получения экземпляра синглетона TatNonATQueryLogicOperationConverter }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
end;//TatNonATQueryLogicOperationConverter
implementation
uses
l3ImplUses
, TypInfo
, l3Base
//#UC START# *503E51C002D7impl_uses*
//#UC END# *503E51C002D7impl_uses*
;
var g_TatNonATQueryLogicOperationConverter: TatNonATQueryLogicOperationConverter = nil;
{* Экземпляр синглетона TatNonATQueryLogicOperationConverter }
procedure TatNonATQueryLogicOperationConverterFree;
{* Метод освобождения экземпляра синглетона TatNonATQueryLogicOperationConverter }
begin
l3Free(g_TatNonATQueryLogicOperationConverter);
end;//TatNonATQueryLogicOperationConverterFree
{$Include w:\quality\test\garant6x\AdapterTest\CoreObjects\atStringConverter.imp.pas}
procedure TatNonATQueryLogicOperationConverter.InitConvertMap;
//#UC START# *503E3A040395_503E51C002D7_var*
const
CONVERT_MAP : array [_SecondType_] of Synonyms = (
(First : 'LO_OR'; Second : QLO_OR),
(First : 'LO_AND'; Second : QLO_AND),
(First : 'LO_NOT'; Second : QLO_AND_NOT)
);
//#UC END# *503E3A040395_503E51C002D7_var*
begin
//#UC START# *503E3A040395_503E51C002D7_impl*
InitConvertMap(CONVERT_MAP);
//#UC END# *503E3A040395_503E51C002D7_impl*
end;//TatNonATQueryLogicOperationConverter.InitConvertMap
class function TatNonATQueryLogicOperationConverter.Instance: TatNonATQueryLogicOperationConverter;
{* Метод получения экземпляра синглетона TatNonATQueryLogicOperationConverter }
begin
if (g_TatNonATQueryLogicOperationConverter = nil) then
begin
l3System.AddExitProc(TatNonATQueryLogicOperationConverterFree);
g_TatNonATQueryLogicOperationConverter := Create;
end;
Result := g_TatNonATQueryLogicOperationConverter;
end;//TatNonATQueryLogicOperationConverter.Instance
class function TatNonATQueryLogicOperationConverter.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_TatNonATQueryLogicOperationConverter <> nil;
end;//TatNonATQueryLogicOperationConverter.Exists
initialization
{$Include w:\quality\test\garant6x\AdapterTest\CoreObjects\atStringConverter.imp.pas}
end.
|
unit UGePromocao;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UGrPadraoCadastro, ImgList, IBCustomDataSet, IBUpdateSQL, DB,
Mask, DBCtrls, StdCtrls, Buttons, ExtCtrls, Grids, DBGrids, ComCtrls,
ToolWin, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxButtons,
JvToolEdit, JvDBControls, JvExMask;
type
TfrmGePromocao = class(TfrmGrPadraoCadastro)
lblNome: TLabel;
dbNome: TDBEdit;
IbDtstTabelaCODIGO: TIntegerField;
IbDtstTabelaDESCRICAO: TIBStringField;
IbDtstTabelaDATA_INICIO: TDateField;
IbDtstTabelaDATA_FINAL: TDateField;
IbDtstTabelaPERCENTUAL_DESCONTO: TIBBCDField;
lblDataInicio: TLabel;
lblDataFinal: TLabel;
lblDescontoProm: TLabel;
dbDescontoProm: TDBEdit;
cdsProdutos: TIBDataSet;
IbUpdProdutos: TIBUpdateSQL;
DtSrcProdutos: TDataSource;
GrpBxDadosProduto: TGroupBox;
lblProduto: TLabel;
lblValorUnit: TLabel;
lblDesconto: TLabel;
lblUnidade: TLabel;
Bevel5: TBevel;
lblValorPromocao: TLabel;
dbProdutoNome: TDBEdit;
dbValorUnit: TDBEdit;
dbDesconto: TDBEdit;
dbUnidade: TDBEdit;
pnlBotoesProduto: TPanel;
btnProdutoInserir: TBitBtn;
btnProdutoEditar: TBitBtn;
btnProdutoExcluir: TBitBtn;
btnProdutoSalvar: TBitBtn;
Bevel6: TBevel;
dbgProdutos: TDBGrid;
cdsProdutosCODIGO_PROM: TIntegerField;
cdsProdutosCODIGO_PROD: TIBStringField;
cdsProdutosPRECO_VENDA: TIBBCDField;
cdsProdutosDESCONTO: TIBBCDField;
cdsProdutosPRECO_PROMOCAO: TIBBCDField;
cdsProdutosUSUARIO: TIBStringField;
cdsProdutosDESCRI: TIBStringField;
cdsProdutosUNIDADE: TIBStringField;
IbDtstTabelaATIVA: TSmallintField;
dbAtiva: TDBCheckBox;
qryProduto: TIBDataSet;
cdsProdutosSequencial: TIntegerField;
dbProduto: TJvDBComboEdit;
dbValorPromocao: TJvDBComboEdit;
dbDataInicio: TJvDBDateEdit;
dbDataFinal: TJvDBDateEdit;
procedure FormCreate(Sender: TObject);
procedure IbDtstTabelaAfterCancel(DataSet: TDataSet);
procedure btbtnExcluirClick(Sender: TObject);
procedure pgcGuiasChange(Sender: TObject);
procedure btbtnAlterarClick(Sender: TObject);
procedure DtSrcProdutosStateChange(Sender: TObject);
procedure dbProdutoButtonClick(Sender: TObject);
procedure DtSrcTabelaStateChange(Sender: TObject);
procedure cdsProdutosNewRecord(DataSet: TDataSet);
procedure IbDtstTabelaNewRecord(DataSet: TDataSet);
procedure btnProdutoInserirClick(Sender: TObject);
procedure btnProdutoEditarClick(Sender: TObject);
procedure btnProdutoExcluirClick(Sender: TObject);
procedure btnProdutoSalvarClick(Sender: TObject);
procedure ControlEditExit(Sender: TObject);
procedure dbValorPromocaoButtonClick(Sender: TObject);
procedure cdsProdutosCalcFields(DataSet: TDataSet);
procedure btbtnSalvarClick(Sender: TObject);
procedure dbgDadosDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
private
{ Private declarations }
SQL_Produtos : TStringList;
procedure AbrirTabelaProdutos(const PromocaoID : Integer);
procedure CarregarDadosProduto(const ProdutoID : Integer);
public
{ Public declarations }
end;
var
frmGePromocao: TfrmGePromocao;
procedure MostrarTabelaPromocoes(const AOwner : TComponent);
function SelecionarPromocao(const AOwner : TComponent; var Codigo : Integer; var Nome : String) : Boolean;
implementation
uses
UDMBusiness, UGeProduto, UConstantesDGE;
{$R *.dfm}
procedure MostrarTabelaPromocoes(const AOwner : TComponent);
var
frm : TfrmGePromocao;
begin
frm := TfrmGePromocao.Create(AOwner);
try
frm.ShowModal;
finally
frm.Destroy;
end;
end;
function SelecionarPromocao(const AOwner : TComponent; var Codigo : Integer; var Nome : String) : Boolean;
var
frm : TfrmGePromocao;
begin
frm := TfrmGePromocao.Create(AOwner);
try
Result := frm.SelecionarRegistro(Codigo, Nome);
finally
frm.Destroy;
end;
end;
procedure TfrmGePromocao.AbrirTabelaProdutos(const PromocaoID: Integer);
begin
cdsProdutos.Close;
with cdsProdutos, SelectSQL do
begin
Clear;
AddStrings( SQL_Produtos );
Add('where p.Codigo_prom = ' + IntToStr(PromocaoID));
end;
cdsProdutos.Open;
end;
procedure TfrmGePromocao.FormCreate(Sender: TObject);
begin
inherited;
Desativar_Promocoes;
DisplayFormatCodigo := '0000';
RotinaID := ROTINA_CAD_PROMOCAO_ID;
ControlFirstEdit := dbNome;
NomeTabela := 'TBPROMOCAO';
CampoCodigo := 'CODIGO';
CampoDescricao := 'DESCRICAO';
UpdateGenerator;
SQL_Produtos := TStringList.Create;
SQL_Produtos.AddStrings( cdsProdutos.SelectSQL );
end;
procedure TfrmGePromocao.IbDtstTabelaAfterCancel(DataSet: TDataSet);
begin
inherited;
AbrirTabelaProdutos( IbDtstTabelaCODIGO.AsInteger );
end;
procedure TfrmGePromocao.btbtnExcluirClick(Sender: TObject);
begin
inherited;
if ( not OcorreuErro ) then
AbrirTabelaProdutos( IbDtstTabelaCODIGO.AsInteger );
end;
procedure TfrmGePromocao.pgcGuiasChange(Sender: TObject);
begin
inherited;
AbrirTabelaProdutos( IbDtstTabelaCODIGO.Value );
end;
procedure TfrmGePromocao.btbtnAlterarClick(Sender: TObject);
begin
inherited;
if ( not OcorreuErro ) then
AbrirTabelaProdutos( IbDtstTabelaCODIGO.AsInteger );
end;
procedure TfrmGePromocao.DtSrcProdutosStateChange(Sender: TObject);
begin
btnProdutoInserir.Enabled := ( DtSrcProdutos.AutoEdit and (cdsProdutos.State = dsBrowse) );
btnProdutoEditar.Enabled := ( DtSrcProdutos.AutoEdit and (cdsProdutos.State = dsBrowse) and (not cdsProdutos.IsEmpty) );
btnProdutoExcluir.Enabled := ( DtSrcProdutos.AutoEdit and (cdsProdutos.State = dsBrowse) and (not cdsProdutos.IsEmpty) );
btnProdutoSalvar.Enabled := ( cdsProdutos.State in [dsEdit, dsInsert] );
if ( cdsProdutos.State in [dsEdit, dsInsert] ) then
if ( dbProduto.Visible and dbProduto.Enabled ) then
dbProduto.SetFocus;
end;
procedure TfrmGePromocao.dbProdutoButtonClick(Sender: TObject);
var
iCodigo : Integer;
sCodigoAlfa ,
sDescricao ,
sUnidade : String;
cValorVenda ,
cValorPromocao: Currency;
begin
if ( cdsProdutos.State in [dsEdit, dsInsert] ) then
if ( SelecionarProduto(Self, iCodigo, sCodigoAlfa, sDescricao, sUnidade, cValorVenda, cValorPromocao) ) then
begin
cdsProdutosCODIGO_PROD.AsString := sCodigoAlfa;
cdsProdutosDESCRI.AsString := sDescricao;
cdsProdutosUNIDADE.AsString := sUnidade;
cdsProdutosPRECO_VENDA.AsCurrency := cValorVenda;
end;
end;
procedure TfrmGePromocao.DtSrcTabelaStateChange(Sender: TObject);
begin
inherited;
dbAtiva.ReadOnly := ( IbDtstTabela.State in [dsInsert] );
DtSrcProdutos.AutoEdit := ( IbDtstTabela.State in [dsEdit, dsInsert] );
DtSrcProdutosStateChange( DtSrcProdutos );
end;
procedure TfrmGePromocao.cdsProdutosNewRecord(DataSet: TDataSet);
begin
cdsProdutosCODIGO_PROM.Value := IbDtstTabelaCODIGO.Value;
cdsProdutosDESCONTO.Value := 0.0;
end;
procedure TfrmGePromocao.IbDtstTabelaNewRecord(DataSet: TDataSet);
begin
inherited;
IbDtstTabelaATIVA.Value := 0;
IbDtstTabelaDATA_INICIO.Value := GetDateDB;
IbDtstTabelaPERCENTUAL_DESCONTO.Value := 0;
AbrirTabelaProdutos( IbDtstTabelaCODIGO.AsInteger );
end;
procedure TfrmGePromocao.btnProdutoInserirClick(Sender: TObject);
begin
if ( cdsProdutos.Active ) then
begin
cdsProdutos.Append;
cdsProdutosCODIGO_PROM.AsInteger := IbDtstTabelaCODIGO.AsInteger;
cdsProdutosDESCONTO.AsCurrency := IbDtstTabelaPERCENTUAL_DESCONTO.AsCurrency;
dbProduto.SetFocus;
end;
end;
procedure TfrmGePromocao.btnProdutoEditarClick(Sender: TObject);
begin
if ( not cdsProdutos.IsEmpty ) then
begin
cdsProdutos.Edit;
dbProduto.SetFocus;
end;
end;
procedure TfrmGePromocao.btnProdutoExcluirClick(Sender: TObject);
begin
if ( not cdsProdutos.IsEmpty ) then
if ( ShowConfirm('Deseja excluir o ítem selecionado?') ) then
cdsProdutos.Delete;
end;
procedure TfrmGePromocao.btnProdutoSalvarClick(Sender: TObject);
begin
if ( cdsProdutos.State in [dsEdit, dsInsert] ) then
begin
if ( Trim(cdsProdutosCODIGO_PROD.AsString) = EmptyStr ) then
begin
ShowWarning('Favor informar o código do produto.');
dbProduto.SetFocus;
end
else
if ( (cdsProdutosDESCONTO.AsCurrency < 0) or (cdsProdutosDESCONTO.AsCurrency > 100) ) then
begin
ShowWarning('Percentual de desconto inválido.');
dbDesconto.SetFocus;
end
else
begin
cdsProdutos.Post;
if ( btnProdutoInserir.Visible and btnProdutoInserir.Enabled ) then
btnProdutoInserir.SetFocus;
end;
end;
end;
procedure TfrmGePromocao.ControlEditExit(Sender: TObject);
begin
inherited;
if ( Sender = dbProduto ) then
if ( cdsProdutos.State in [dsEdit, dsInsert] ) then
CarregarDadosProduto( StrToIntDef(cdsProdutosCODIGO_PROD.AsString, 0) );
if ( Sender = dbDesconto ) then
if ( cdsProdutos.State in [dsEdit, dsInsert] ) then
begin
if ( cdsProdutosPRECO_VENDA.IsNull ) then
cdsProdutosPRECO_VENDA.AsCurrency := 0;
if ( cdsProdutosDESCONTO.IsNull ) then
cdsProdutosDESCONTO.AsCurrency := 0;
cdsProdutosPRECO_PROMOCAO.Value := cdsProdutosPRECO_VENDA.AsCurrency - (cdsProdutosPRECO_VENDA.AsCurrency * cdsProdutosDESCONTO.AsCurrency / 100);
end;
if ( Sender = dbValorPromocao ) then
if ( btnProdutoSalvar.Visible and btnProdutoSalvar.Enabled ) then
btnProdutoSalvar.SetFocus;
end;
procedure TfrmGePromocao.CarregarDadosProduto(const ProdutoID: Integer);
begin
if ( ProdutoID = 0 ) then
begin
ShowWarning('Favor informar o código do produto');
Exit;
end;
if ( not cdsProdutos.Active ) then
Exit
else
if ( cdsProdutos.State in [dsEdit, dsInsert] ) then
begin
with qryProduto do
begin
Close;
ParamByName('Codigo').AsInteger := ProdutoID;
Open;
if not IsEmpty then
begin
cdsProdutosCODIGO_PROD.AsString := FieldByName('Cod').AsString;
cdsProdutosDESCRI.AsString := FieldByName('Descri').AsString;
cdsProdutosPRECO_VENDA.AsCurrency := FieldByName('Preco').AsCurrency;
end
else
begin
ShowWarning('Código de produto não cadastrado');
cdsProdutosCODIGO_PROD.Clear;
if ( dbProduto.Visible and dbProduto.Enabled ) then
dbProduto.SetFocus;
end;
end;
end;
end;
procedure TfrmGePromocao.dbValorPromocaoButtonClick(Sender: TObject);
var
sValor : String;
cValor : Currency;
begin
if ( cdsProdutos.State in [dsEdit, dsInsert] ) then
begin
sValor := InputBox('VALOR PROMOÇÃO (R$)', 'Favor informar o Valor Promocional:', FormatFloat(',0.00', dbValorPromocao.Field.AsCurrency));
sValor := Trim(StringReplace(sValor, '.', '', [rfReplaceAll]));
cValor := StrToCurrDef(sValor, 0);
if ( cValor > 0 ) then
begin
cdsProdutosPRECO_PROMOCAO.AsCurrency := cValor;
cdsProdutosDESCONTO.AsCurrency := (1 - (cdsProdutosPRECO_PROMOCAO.Value / cdsProdutosPRECO_VENDA.AsCurrency)) * 100;
end;
end;
end;
procedure TfrmGePromocao.cdsProdutosCalcFields(DataSet: TDataSet);
begin
cdsProdutosSequencial.Value := cdsProdutos.RecNo;
end;
procedure TfrmGePromocao.btbtnSalvarClick(Sender: TObject);
begin
inherited;
if ( not OcorreuErro ) then
begin
if ( cdsProdutos.State in [dsEdit, dsInsert] ) then
cdsProdutos.Post;
cdsProdutos.ApplyUpdates;
CommitTransaction;
end;
end;
procedure TfrmGePromocao.dbgDadosDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
begin
inherited;
if ( Sender = dbgDados ) then
begin
if ( IbDtstTabelaATIVA.AsInteger = 0 ) then
dbgDados.Canvas.Font.Color := clRed;
dbgDados.DefaultDrawDataCell(Rect, dbgDados.Columns[DataCol].Field, State);
end;
end;
initialization
FormFunction.RegisterForm('frmGePromocao', TfrmGePromocao);
end.
|
unit frmDateSelect;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, Grids, ExtCtrls, FIBDatabase,
FIBQuery, pFIBQuery, PrjConst, System.Actions, Vcl.ActnList;
type
TfrmRequestDate = class(TFrame)
pnlGrid: TPanel;
sgCalendar: TStringGrid;
pnlInfo: TPanel;
btnNextMon: TBitBtn;
btnPrevMon: TBitBtn;
qBusyDays: TpFIBQuery;
actlst1: TActionList;
actPrevMon: TAction;
actNextMon: TAction;
procedure bbPrevClick(Sender: TObject);
procedure sgCalendarDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
procedure sgCalendarSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
procedure FrameResize(Sender: TObject);
procedure actPrevMonExecute(Sender: TObject);
procedure actNextMonExecute(Sender: TObject);
private
{ Private declarations }
FYear: Word;
FMonth: Word;
FDay: Word;
FHouse: Integer;
FType: Integer;
FDisabledDays: TStrings;
procedure ChangeMonth(const Value: Integer);
procedure UpdateCalendar;
function GetSelectedDate: TDate;
procedure SetHouse(Value: Integer);
procedure SetType(Value: Integer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property House: Integer read FHouse write SetHouse;
property RType: Integer read FType write SetType;
property SelectedDate: TDate read GetSelectedDate;
end;
implementation
{$R *.dfm}
uses DateUtils, DM, AtrStrUtils;
procedure TfrmRequestDate.SetHouse(Value: Integer);
begin
FHouse := Value;
ChangeMonth(0);
end;
procedure TfrmRequestDate.SetType(Value: Integer);
begin
FType := Value;
ChangeMonth(0);
end;
function TfrmRequestDate.GetSelectedDate: TDate;
begin
Result := EncodeDate(FYear, FMonth, FDay);
end;
constructor TfrmRequestDate.Create(AOwner: TComponent);
var
GridLines: Integer;
begin
inherited Create(AOwner);
FHouse := -1;
FDisabledDays := TStringList.Create();
with sgCalendar do begin
GridLines := 6 * GridLineWidth;
DefaultColWidth := (Width - GridLines - 1) div 7;
DefaultRowHeight := (Height - GridLines - 1) div 7;
Cells[0, 0] := rsMon;
Cells[1, 0] := rsTue;
Cells[2, 0] := rsWed;
Cells[3, 0] := rsThu;
Cells[4, 0] := rsFri;
Cells[5, 0] := rsSat;
Cells[6, 0] := rsSun;
end;
DecodeDate(Now(), FYear, FMonth, FDay);
end;
procedure TfrmRequestDate.bbPrevClick(Sender: TObject);
begin
ChangeMonth(-1);
end;
procedure TfrmRequestDate.ChangeMonth(const Value: Integer);
var
sd: TDate;
y, m, d: Word;
s: string;
st: string;
begin
IncAMonth(FYear, FMonth, FDay, Value);
sd := EncodeDate(FYear, FMonth, 1);
FDisabledDays.Clear;
if FHouse >= 0
then
with qBusyDays do begin
// qBusyDays.ParamByName('FROM_DATE').AsDate := Today();
// qBusyDays.ParamByName('TO_DATE').Clear;
// qBusyDays.ParamByName('HOUSE_ID').AsDate := FHouse;
if FType = -1
then st := 'null'
else st := IntToStr(FType);
s := 'select BUSY_DAY from GET_REQUEST_BUSY_DAYS(' + IntToStr(FHouse) + ', ' + DateTOFBdate(sd) + ', null, '
+ st + ')';
qBusyDays.Sql.Text := s;
Transaction.StartTransaction;
ExecQuery;
while not Eof do begin
if not FieldByName('BUSY_DAY').IsNull
then begin
DecodeDate(FieldByName('BUSY_DAY').AsDate, y, m, d);
FDisabledDays.Add(IntToStr(d));
end;
Next;
end;
Transaction.Commit;
Close;
end;
pnlInfo.Caption := FormatDateTime('mmmm, yyyy', EncodeDate(FYear, FMonth, 1));
UpdateCalendar;
actPrevMon.Enabled := not(EncodeDate(FYear, FMonth, 1) < Today);
end;
procedure TfrmRequestDate.UpdateCalendar;
var
j, i, vC, vR: Integer;
FirstDate: TDateTime;
MonthOffset: Integer;
SRect: TGridRect;
begin
with sgCalendar do begin
for i := 1 to RowCount - 1 do begin
Rows[i].Clear;
for j := 0 to ColCount - 1 do Cells[j, i] := '';
end;
FirstDate := EncodeDate(FYear, FMonth, 1);
i := DayOfWeek(FirstDate); { day of week for 1st of month }
if 2 < i
then MonthOffset := i - 3
else MonthOffset := 4 + i;
vR := 1;
for i := 1 to DaysInMonth(FirstDate) do begin
vC := (i + MonthOffset) mod 7;
if (vC = 0)
then inc(vR);
Cells[vC, vR] := IntToStr(i);
end;
i := -1;
j := -1;
for vR := 1 to 6 do
for vC := 0 to 7 do
if (i = -1)
then
if (Cells[vC, vR] <> '')
then
if (FDisabledDays.IndexOf(Cells[vC, vR]) = -1)
then
if (EncodeDate(FYear, FMonth, StrToInt(Cells[vC, vR])) >= Today())
then begin
i := vC;
j := vR;
end;
end;
if i > -1
then begin
sgCalendar.Row := j; { Устанавливаем Row/Col }
sgCalendar.Col := i;
SRect.Top := j; { Определяем выбранную область }
SRect.Left := i;
SRect.Bottom := j;
SRect.Right := i;
sgCalendar.Selection := SRect; { Устанавливаем выбор }
end;
end;
procedure TfrmRequestDate.sgCalendarDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
TheText: string;
OldColor: TColor;
begin
with sgCalendar do begin
OldColor := Canvas.Font.Color;
TheText := Cells[ACol, ARow];
if not(gdSelected in State)
then
if FDisabledDays.IndexOf(TheText) > -1
then Canvas.Font.Color := clGrayText
else begin
Canvas.Font.Style := [fsBold];
if ACol >= 5
then Canvas.Font.Color := clRed;
end
else begin
Canvas.Brush.Color := clHighlight;
Canvas.Font.Color := clHighlightText;
end;
with Rect, Canvas do begin
TextRect(Rect, Left + (Right - Left - TextWidth(TheText)) div 2, Top + (Bottom - Top - TextHeight(TheText))
div 2, TheText);
end;
Canvas.Font.Color := OldColor;
end;
end;
procedure TfrmRequestDate.sgCalendarSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
TheText: String;
begin
TheText := (Sender as TStringGrid).Cells[ACol, ARow];
if (TheText = '') or (FDisabledDays.IndexOf(TheText) > -1) or (EncodeDate(FYear, FMonth, StrToInt(TheText)) < Today())
then CanSelect := False
else begin
FDay := StrToInt(TheText);
CanSelect := True;
end;
end;
destructor TfrmRequestDate.Destroy;
begin
inherited Destroy;
FreeAndNil(FDisabledDays);
end;
procedure TfrmRequestDate.FrameResize(Sender: TObject);
var
GridLines: Integer;
begin
GridLines := 6 * sgCalendar.GridLineWidth;
sgCalendar.DefaultColWidth := (pnlGrid.ClientWidth - GridLines - 2) div 7;
sgCalendar.DefaultRowHeight := (pnlGrid.ClientHeight - pnlInfo.Height - GridLines) div 7;
end;
procedure TfrmRequestDate.actPrevMonExecute(Sender: TObject);
begin
ChangeMonth(-1);
end;
procedure TfrmRequestDate.actNextMonExecute(Sender: TObject);
begin
ChangeMonth(1);
end;
end.
|
unit uMessageBox;
interface
uses Forms, Windows, SysUtils;
type
MessageBox = class
public
class procedure MessageOk(const Msg: string); overload; virtual;
class procedure MessageOk(const Msg: string; const Caption: string); overload; virtual;
class procedure MessageOkFmt(const Msg: string; const Args: array of const); overload; virtual;
class procedure MessageOkFmt(const Msg: string; const Args: array of const; const Caption: string); overload; virtual;
class procedure MessageError(const Msg: string); overload; virtual;
class procedure MessageError(const Msg: string; const Caption: string); overload; virtual;
class procedure MessageErrorFmt(const Msg: string; const Args: array of const); overload; virtual;
class procedure MessageErrorFmt(const Msg: string; const Args: array of const; const Caption: string); overload; virtual;
class function MessageYesNo(const Msg: string): Boolean; overload; virtual;
class function MessageYesNo(const Msg: string; const Caption: string): Boolean; overload; virtual;
class function MessageYesNoFmt(const Msg: string; const Args: array of const): Boolean; overload; virtual;
class function MessageYesNoFmt(const Msg: string; const Caption: string; const Args: array of const): Boolean; overload; virtual;
end;
implementation
const
INFORMATION = 'Informação';
ERROR = 'Error';
{ MessageBox }
class procedure MessageBox.MessageError(const Msg, Caption: string);
begin
Application.MessageBox(PChar(Msg), PChar(Caption), MB_OK + MB_ICONERROR);
end;
class procedure MessageBox.MessageError(const Msg: string);
begin
MessageError(Msg, ERROR);
end;
class procedure MessageBox.MessageErrorFmt(const Msg: string;
const Args: array of const; const Caption: string);
begin
MessageError(Format(Msg, Args), Caption);
end;
class procedure MessageBox.MessageErrorFmt(const Msg: string;
const Args: array of const);
begin
MessageError(Format(Msg, Args));
end;
class procedure MessageBox.MessageOk(const Msg, Caption: string);
begin
Application.MessageBox(PChar(Msg), PChar(Caption), MB_OK + MB_ICONINFORMATION);
end;
class procedure MessageBox.MessageOk(const Msg: string);
begin
MessageOk(Msg, INFORMATION);
end;
class procedure MessageBox.MessageOkFmt(const Msg: string;
const Args: array of const; const Caption: string);
begin
MessageOk(Format(Msg, Args), Caption);
end;
class procedure MessageBox.MessageOkFmt(const Msg: string;
const Args: array of const);
begin
MessageOk(Format(Msg, Args));
end;
class function MessageBox.MessageYesNo(const Msg, Caption: string): Boolean;
begin
Result := (Application.MessageBox(PChar(Msg), PChar(Caption), MB_YESNO + MB_ICONQUESTION) = ID_YES);
end;
class function MessageBox.MessageYesNo(const Msg: string): Boolean;
begin
Result := MessageYesNo(Msg, INFORMATION);
end;
class function MessageBox.MessageYesNoFmt(const Msg, Caption: string;
const Args: array of const): Boolean;
begin
Result := MessageYesNo(Format(Msg, Args), Caption);
end;
class function MessageBox.MessageYesNoFmt(const Msg: string;
const Args: array of const): Boolean;
begin
Result := MessageYesNo(Format(Msg, Args));
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit OraRollbackSegment;
interface
uses Classes, SysUtils, Ora, OraStorage, DB, DBQuery, Forms, Dialogs, VirtualTable;
type
TRollbackSegment = class(TObject)
private
FSEGMENT_NAME,
FOWNER,
FTABLESPACE_NAME: string;
FINITIAL_EXTENT,
FNEXT_EXTENT,
FMIN_EXTENTS,
FMAX_EXTENTS,
FOPTSIZE : Extended;
FPCT_INCREASE,
FINSTANCE_NUM: integer;
FSTATUS: string;
FPUBLIC: Boolean;
FMode: TMode;
FOraSession: TOraSession;
//function GetStatus: string;
function GetRollbackSegmentDetail: String;
public
property SEGMENT_NAME : String read FSEGMENT_NAME write FSEGMENT_NAME;
property OWNER : String read FOWNER write FOWNER;
property TABLESPACE_NAME: String read FTABLESPACE_NAME write FTABLESPACE_NAME;
property INITIAL_EXTENT: Extended read FINITIAL_EXTENT write FINITIAL_EXTENT;
property NEXT_EXTENT: Extended read FNEXT_EXTENT write FNEXT_EXTENT;
property MIN_EXTENTS: Extended read FMIN_EXTENTS write FMIN_EXTENTS;
property MAX_EXTENTS: Extended read FMAX_EXTENTS write FMAX_EXTENTS;
property OPTSIZE: Extended read FOPTSIZE write FOPTSIZE;
property PCT_INCREASE: Integer read FPCT_INCREASE write FPCT_INCREASE;
property INSTANCE_NUM: Integer read FINSTANCE_NUM write FINSTANCE_NUM;
property STATUS: string read FSTATUS write FSTATUS;
property PUBLIC: Boolean read FPUBLIC write FPUBLIC;
property Mode: TMode read FMode write FMode;
property OraSession: TOraSession read FOraSession write FOraSession;
procedure SetDDL;
function GetDDL: string;
function GetAlterDDL: string;
function RollbackSegmentToOnline: boolean;
function RollbackSegmentToOffline: boolean;
function CreateRollbackSegment(Script: string) : boolean;
function AlterRollbackSegment(Script: string) : boolean;
function DropRollbackSegment: boolean;
constructor Create;
destructor Destroy; override;
end;
function GetRollbackSegments(): string;
implementation
uses Util, frmSchemaBrowser, OraScripts, Languages;
resourcestring
strRollbackSegmentDropped = 'Rollback Segment %s has been dropped.';
strRollbackSegmentAltered = 'Rollback Segment %s has been altered.';
strRollbackSegmentCreated = 'Rollback Segment %s has been created.';
strRollbackSegmentOnline = 'Rollback Segment %s has been Online.';
strRollbackSegmentOffline = 'Rollback Segment %s has been Offline.';
function GetRollbackSegments(): string;
begin
result := 'select * from SYS.Dba_rollback_segs '
+' order by SEGMENT_NAME ';
end;
constructor TRollbackSegment.Create;
begin
inherited;
end;
destructor TRollbackSegment.destroy;
begin
inherited;
end;
function TRollbackSegment.GetRollbackSegmentDetail: String;
begin
Result :=
'Select * '
+' from sys.Dba_rollback_segs '
+'WHERE SEGMENT_NAME = :pName ';
end;
{function TRollbackSegment.GetStatus: string;
var
q1: TOraQuery;
begin
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetObjectStatusSQL;
q1.ParamByName('pOName').AsString := ;
q1.ParamByName('pOType').AsString := '';
q1.ParamByName('pOwner').AsString := FOWNER;
q1.Open;
result := FDB_LINK+' ( Created: '+q1.FieldByName('CREATED').AsString
+' Last DDL: '+q1.FieldByName('LAST_DDL_TIME').AsString
+' Status: '+q1.FieldByName('STATUS').AsString
+' )';
q1.Close;
end; }
procedure TRollbackSegment.SetDDL;
var
q1: TOraQuery;
begin
if FSEGMENT_NAME = '' then exit;
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetRollbackSegmentDetail;
q1.ParamByName('pName').AsString := FSEGMENT_NAME;
q1.Open;
FSEGMENT_NAME := q1.FieldByName('SEGMENT_NAME').AsString;
FOWNER := q1.FieldByName('OWNER').AsString;
FPUBLIC := q1.FieldByName('OWNER').AsString = 'PUBLIC';
FTABLESPACE_NAME := q1.FieldByName('TABLESPACE_NAME').AsString;
FINITIAL_EXTENT := q1.FieldByName('INITIAL_EXTENT').AsFloat;
FNEXT_EXTENT := q1.FieldByName('NEXT_EXTENT').AsFloat;
FMIN_EXTENTS := q1.FieldByName('MIN_EXTENTS').AsFloat;
FMAX_EXTENTS := q1.FieldByName('MAX_EXTENTS').AsFloat;
FOPTSIZE := 0;
FPCT_INCREASE := q1.FieldByName('PCT_INCREASE').AsInteger;
FINSTANCE_NUM := StrToInt(isNull(q1.FieldByName('INSTANCE_NUM').AsString));
FSTATUS := q1.FieldByName('STATUS').AsString;
Q1.close;
end;
function TRollbackSegment.GetDDL: string;
var s: string;
begin
s := '';
if FPUBLIC then
result := 'CREATE PUBLIC ROLLBACK SEGMENT '+FSEGMENT_NAME+ln
else
result := 'CREATE ROLLBACK SEGMENT '+FSEGMENT_NAME+ln;
result := result +'TABLESPACE '+FTABLESPACE_NAME+ln;
if isNullorZero(FINITIAL_EXTENT,0) then
s := s + ln +' INITIAL '+FloatToStr(FINITIAL_EXTENT)+' K';
if isNullorZero(FNEXT_EXTENT,0) then
s := s + ln +' NEXT '+FloatToStr(FNEXT_EXTENT)+' K';
if isNullorZero(FMIN_EXTENTS,0) then
s := s + ln +' MINEXTENTS '+FloatToStr(FMIN_EXTENTS)+' K';
if isNullorZero(FMAX_EXTENTS,0) then
s := s + ln +' MAXEXTENTS '+FloatToStr(FMAX_EXTENTS)+' K';
if isNullorZero(FOPTSIZE,0) then
s := s + ln +' OPTIMAL '+FloatToStr(FOPTSIZE)+' K';
if length(s) > 0 then
result := result + 'STORAGE ('
+s
+')';
result := result +';';
end;
function TRollbackSegment.GetAlterDDL: string;
var s: string;
begin
s := '';
if FPUBLIC then
result := 'ALTER PUBLIC ROLLBACK SEGMENT '+FSEGMENT_NAME+ln
else
result := 'ALTER ROLLBACK SEGMENT '+FSEGMENT_NAME+ln;
if isNullorZero(FINITIAL_EXTENT,0) then
s := s + ln +' INITIAL '+FloatToStr(FINITIAL_EXTENT)+' K';
if isNullorZero(FNEXT_EXTENT,0) then
s := s + ln +' NEXT '+FloatToStr(FNEXT_EXTENT)+' K';
if isNullorZero(FMIN_EXTENTS,0) then
s := s + ln +' MINEXTENTS '+FloatToStr(FMIN_EXTENTS)+' K';
if isNullorZero(FMAX_EXTENTS,0) then
s := s + ln +' MAXEXTENTS '+FloatToStr(FMAX_EXTENTS)+' K';
if isNullorZero(FOPTSIZE,0) then
s := s + ln +' OPTIMAL '+FloatToStr(FOPTSIZE)+' K';
if length(s) > 0 then
result := result + 'STORAGE ('
+s
+')';
result := result +';';
end;
function TRollbackSegment.RollbackSegmentToOnline: boolean;
var
script: string;
begin
result := false;
script := 'ALTER ROLLBACK SEGMENT '+FSEGMENT_NAME+' ONLINE';
if FSEGMENT_NAME = '' then exit;
result := ExecSQL(Script, Format(ChangeSentence('strRollbackSegmentOnline',strRollbackSegmentOnline),[FSEGMENT_NAME]), FOraSession);
end;
function TRollbackSegment.RollbackSegmentToOffline: boolean;
var
script: string;
begin
result := false;
script := 'ALTER ROLLBACK SEGMENT '+FSEGMENT_NAME+' OFFLINE';
if FSEGMENT_NAME = '' then exit;
result := ExecSQL(Script, Format(ChangeSentence('strRollbackSegmentOffline',strRollbackSegmentOffline),[FSEGMENT_NAME]), FOraSession);
end;
function TRollbackSegment.CreateRollbackSegment(Script: string) : boolean;
begin
result := false;
if FSEGMENT_NAME = '' then exit;
result := ExecSQL(Script, Format(ChangeSentence('strRollbackSegmentCreated',strRollbackSegmentCreated),[FSEGMENT_NAME]), FOraSession);
end;
function TRollbackSegment.AlterRollbackSegment(Script: string) : boolean;
begin
result := false;
if FSEGMENT_NAME = '' then exit;
result := ExecSQL(Script, Format(ChangeSentence('strRollbackSegmentAltered',strRollbackSegmentAltered),[FSEGMENT_NAME]), FOraSession);
end;
function TRollbackSegment.DropRollbackSegment: boolean;
var
FSQL: string;
begin
result := false;
if FSEGMENT_NAME = '' then exit;
FSQL := 'DROP ROLLBACK SEGMENT '+FSEGMENT_NAME;
result := ExecSQL(FSQL, Format(ChangeSentence('strRollbackSegmentDropped',strRollbackSegmentDropped),[FSEGMENT_NAME]), FOraSession);
end;
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Decorators.Inverter;
interface
uses
Behavior3, Behavior3.Core.Decorator, Behavior3.Core.BaseNode, Behavior3.Core.Tick;
type
TB3Inverter = class(TB3Decorator)
public
constructor Create; override;
(**
* Tick method.
* @method tick
* @param {Tick} tick A tick instance.
* @return {Constant} A state constant.
**)
function Tick(Tick: TB3Tick): TB3Status; override;
end;
implementation
{ TB3Inverter }
constructor TB3Inverter.Create;
begin
inherited;
(**
* Node name. Default to `Inverter`.
* @property {String} name
* @readonly
**)
Name := 'Inverter';
end;
function TB3Inverter.Tick(Tick: TB3Tick): TB3Status;
var
Status: TB3Status;
begin
if not Assigned(Child) then
begin
Result := Behavior3.Error;
Exit;
end;
Status := Child._Execute(Tick);
if Status = Behavior3.Success then
Status := Behavior3.Failure
else
if Status = Behavior3.Failure then
Status := Behavior3.Success;
Result := Status;
end;
end.
|
unit GMKernel;
interface
const
INVALID_GAMEMASTER = 0;
INVALID_INTSERVER = 0;
const
GM_ERR_NOERROR = 0;
GM_ERR_UNEXPECTED = 1000;
GM_ERR_NOGMAVAILABLE = 1001;
GM_ERR_UNKNOWGM = 1002;
GM_ERR_UNKNOWNIS = 1003;
GM_ERR_UNKNOWMCUST = 1004;
const
GM_STATUS_ONLINE = 1;
GM_STATUS_AWAY = 2;
const
GM_NOTIFY_USERONLINE = 1;
GM_NOTIFY_USERWAITING = 2;
const
tidRDOHook_GMServer = 'GMServer';
type
TGameMasterId = integer;
TCustomerId = widestring;
TErrorCode = integer;
TIServerId = integer;
IGMCustomer =
interface['{B3B4FFC0-415B-11D4-8301-00A0CC2C3344}']
procedure GameMasterMsg( Msg : WideString; Info : integer );
procedure GMNotify( notID : integer; Info : WideString );
end;
IInterfaceServer =
interface['{B3B4FFC1-415B-11D4-8301-00A0CC2C3344}']
function ConnectToGameMaster( ClientId : TCustomerId; ClientInfo : widestring; GameMasters : widestring ) : OleVariant;
function SendGMMessage( ClientId : TCustomerId; GMId : TGameMasterId; Msg : WideString ) : OleVariant;
procedure DisconnectUser( ClientId : TCustomerId; GMId : TGameMasterId );
end;
IIServerConnection =
interface['{B3B4FFC4-415B-11D4-8301-00A0CC2C3344}']
function GameMasterMsg( ClientId : TCustomerId; Msg : WideString; Info : integer ) : OleVariant;
procedure GMNotify( ClientId : TCustomerId; notID : integer; Info : WideString );
end;
IGMServer =
interface['{B3B4FFC2-415B-11D4-8301-00A0CC2C3344}']
function RegisterInterfaceServer( IsId : TIServerId; ClientId : integer; Info : WideString) : Olevariant;
procedure UnRegisterCustomer( ISId : TIServerId; aCustomerId : TCustomerId );
procedure DisconnectUser( ISId : TIServerId; ClientId : TCustomerId; GMId : TGameMasterId );
function ConnectToGameMaster( ISId : TIServerId; ClientId : TCustomerId; ClientInfo : widestring; GameMasters : widestring ) : OleVariant;
function SendGMMessage( ISId : TIServerId; ClientId : TCustomerId; GMId : TGameMasterId; Msg : WideString ) : OleVariant;
end;
IGMServerConnection =
interface['{B3B4FFC5-415B-11D4-8301-00A0CC2C3344}']
function RegisterGameMaster( ClientId : integer; GMId : TGameMasterId; GMName : widestring; GMPassword : widestring ) : OleVariant;
procedure NotifyGMStatus( GMId : TGameMasterId; Status : integer; Customers : integer; Pending : integer );
procedure UserNotification( ISId : TIServerId; CustomerId : TCustomerId; notID : integer; Info : WideString );
function SendMessage( ISId : TIServerId; CustomerId : TCustomerId; Msg : WideString; Info : integer ) : OleVariant;
end;
IGameMaster =
interface['{B3B4FFC3-415B-11D4-8301-00A0CC2C3344}']
function AddCustomer( ISId : TIServerId; CustomerId : TCustomerId; ClientInfo : widestring) : olevariant;
procedure CustomerMsg( ISId : TIServerId; CustomerId : TCustomerId; Msg : WideString );
procedure UnRegisterCustomer( ISId : TIServerId; aCustomerId : TCustomerId );
procedure UnRegisterIServer( aIsId : TIServerId );
end;
function GMErrorToStr( error : TErrorCode ) : WideString;
function GMStatusToStr( GMStatus : integer ) : WideString;
implementation
function GMErrorToStr( error : TErrorCode ) : WideString;
begin
case error of
GM_ERR_NOERROR : result := 'No error!';
GM_ERR_UNEXPECTED : result := 'Unexpected error occurred';
GM_ERR_NOGMAVAILABLE : result := 'Sorry, No Game Master available at this time, please try again later';
GM_ERR_UNKNOWGM : result := 'No such Game Master';
GM_ERR_UNKNOWNIS : result := 'No such interface server';
GM_ERR_UNKNOWMCUST : result := 'No such customer';
else result := 'Unknown error';
end;
end;
function GMStatusToStr( GMStatus : integer ) : WideString;
begin
case GMStatus of
GM_STATUS_ONLINE : result := 'Game Master Ready';
GM_STATUS_AWAY : result := 'Game Master is Away';
else result := 'Unknown error';
end;
end;
end.
|
{
*****************************************************************************
* *
* This file is part of the iPhone Laz Extension *
* *
* See the file COPYING.modifiedLGPL.txt, 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. *
* *
*****************************************************************************
}
unit project_iphone_options;
{$mode objfpc}{$H+}
interface
uses
Classes,SysUtils,FileUtil,LResources,Forms,StdCtrls,CheckLst,Buttons, Dialogs,
Menus,IDEOptionsIntf,ProjectIntf,LazIDEIntf,iPhoneExtStr,
iPhoneExtOptions, Controls, LazFilesUtils, XcodeUtils, newXibDialog, xibfile;
type
{ TiPhoneProjectOptionsEditor }
TiPhoneProjectOptionsEditor = class(TAbstractIDEOptionsEditor)
btnShowInFinder:TButton;
btnAddXib:TButton;
btnRemoveXib:TButton;
Label5:TLabel;
mnuDump:TMenuItem;
mnuOpenIB:TMenuItem;
nibFilesBox:TCheckListBox;
chkisPhone: TCheckBox;
cmbSDKs: TComboBox;
edtResDir: TEdit;
edtExclude: TEdit;
edtAppID: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4:TLabel;
lblAppID: TLabel;
lblAppIDHint: TLabel;
lblSDKVer: TLabel;
nibsPopup:TPopupMenu;
procedure btnAddXibClick(Sender:TObject);
procedure btnRemoveXibClick(Sender:TObject);
procedure btnShowInFinderClick(Sender:TObject);
procedure Button1Click(Sender:TObject);
procedure chkisPhoneChange(Sender:TObject);
procedure cmbSDKsChange(Sender: TObject);
procedure edtExcludeChange(Sender: TObject);
procedure edtResDirChange(Sender:TObject);
procedure edtResDirExit(Sender:TObject);
procedure FrameClick(Sender: TObject);
procedure mnuDumpClick(Sender:TObject);
procedure mnuOpenIBClick(Sender:TObject);
procedure nibFilesBoxClickCheck(Sender:TObject);
procedure nibFilesBoxItemClick(Sender:TObject;Index:integer);
procedure nibFilesBoxMouseDown(Sender:TObject;Button:TMouseButton;Shift:
TShiftState;X,Y:Integer);
procedure nibFilesBoxMouseUp(Sender:TObject;Button:TMouseButton;Shift:
TShiftState;X,Y:Integer);
procedure nibsPopupPopup(Sender:TObject);
private
{ private declarations }
SelXibFile : String;
ResDirChanged : Boolean;
fOnChanged : TNotifyEvent;
procedure DoChanged;
procedure RefreshXIBList;
procedure SetControlsEnabled(AEnabled: Boolean);
procedure DumpClasses(const XibFileName: AnsiString; var PascalFileName: AnsiString);
public
{ public declarations }
class function SupportedOptionsClass: TAbstractIDEOptionsClass; override;
function GetTitle: String; override;
procedure Setup(ADialog: TAbstractOptionsEditorDialog); override;
procedure ReadSettings(AOptions: TAbstractIDEOptions); override;
procedure WriteSettings(AOptions: TAbstractIDEOptions); override;
property OnChanged: TNotifyEvent read fOnChanged write fOnChanged;
end;
implementation
{ TiPhoneProjectOptionsEditor }
procedure TiPhoneProjectOptionsEditor.cmbSDKsChange(Sender: TObject);
begin
end;
procedure TiPhoneProjectOptionsEditor.btnShowInFinderClick(Sender:TObject);
var
path: AnsiString;
tmp : AnsiString;
begin
path:=Trim(edtResDir.Text);
path:=ResolveProjectPath(path);
ForceDirectoriesUTF8(path);
while (path<>'') and (not DirectoryExistsUTF8(path)) do begin
tmp:=path;
path:=ExtractFileDir(path);
if tmp=path then Break;
end;
if DirectoryExistsUTF8(path) then ExecCmdLineNoWait('open "'+path +'"');
end;
procedure TiPhoneProjectOptionsEditor.btnAddXibClick(Sender:TObject);
var
FileName : AnsiString;
SrcXib : AnsiString;
ResDir : AnsiString;
begin
newXibForm:=TnewXibForm.Create(Self);
ScanForXibTemplates(
XibTemplateDir( IncludeTrailingPathDelimiter(EnvOptions.PlatformsBaseDir)+iPhoneOSplatform),
@newXibForm.AddTemplate);
if (newXibForm.Execute(FileName, SrcXib)) and (SrcXib<>'')then begin
ResDir:=edtResDir.Text;
ResDir := ResolveProjectPath(ResDir);
ForceDirectoriesUTF8(ResDir);
if not CopyFile(SrcXib, ChangeFileExt(IncludeTrailingPathDelimiter(ResDir)+FileName,'.xib')) then
ShowMessage('Failed to create Nib file');
RefreshXIBList;
end;
newXibForm.Free;
newXibForm:=nil;
end;
procedure TiPhoneProjectOptionsEditor.btnRemoveXibClick(Sender:TObject);
var
XibName : AnsiString;
begin
if nibFilesBox.ItemIndex<0 then Exit;
XibName:=edtResDir.Text;
XibName := ResolveProjectPath(XibName);
XibName:=ChangeFileExt(IncludeTrailingPathDelimiter(XibName)+nibFilesBox.Items[nibFilesBox.ItemIndex],'.xib');
if FileExistsUTF8(XibName) then DeleteFileUTF8(XibName);
RefreshXIBList;
end;
procedure TiPhoneProjectOptionsEditor.Button1Click(Sender:TObject);
begin
end;
procedure TiPhoneProjectOptionsEditor.chkisPhoneChange(Sender:TObject);
begin
SetControlsEnabled(chkisPhone.Checked);
end;
procedure TiPhoneProjectOptionsEditor.edtExcludeChange(Sender: TObject);
begin
end;
procedure TiPhoneProjectOptionsEditor.edtResDirChange(Sender:TObject);
begin
ResDirChanged:=True;
end;
procedure TiPhoneProjectOptionsEditor.edtResDirExit(Sender:TObject);
var
s : AnsiString;
chk : AnsiString;
i : Integer;
begin
if not ResDirChanged then Exit;
ResDirChanged:=False;
// storing checked and selected items
for i:=0 to nibFilesBox.Count-1 do
if nibFilesBox.Checked[i] then
chk:=nibFilesBox.Items[i];
if nibFilesBox.ItemIndex>=0 then
s:=nibFilesBox.Items[nibFilesBox.ItemIndex]
else
s := '';
// refreshing the list
RefreshXIBList;
// restore selection and checked item
if s<>'' then nibFilesBox.ItemIndex:=nibFilesBox.Items.IndexOf(s);
i:=nibFilesBox.Items.IndexOf(chk);
nibFilesBox.Checked[i]:=True;
end;
procedure TiPhoneProjectOptionsEditor.FrameClick(Sender: TObject);
begin
end;
procedure TiPhoneProjectOptionsEditor.mnuDumpClick(Sender:TObject);
var
s : AnsiString;
pas : AnsiString;
p : TControl;
begin
if SelXibFile ='' then Exit;
s:=ChangeFileExt(IncludeTrailingPathDelimiter (edtResDir.Text) + SelXibFile,'.xib');
s := ResolveProjectPath(s);
DumpClasses(s, pas);
p:=Parent;
while Assigned(p) and (not (p is TForm)) do
p:=p.Parent;
if Assigned(p) then TForm(p).ModalResult:=mrOK;
LazarusIDE.DoOpenEditorFile(pas, -1,-1, [ofOnlyIfExists]);
end;
procedure TiPhoneProjectOptionsEditor.mnuOpenIBClick(Sender:TObject);
var
path : AnsiString;
begin
path:=ChangeFileExt(IncludeTrailingPathDelimiter(edtResDir.Text)+SelXibFile,'.xib');
path := ResolveProjectPath(path);
ExecCmdLineNoWait('open ' + path);
end;
procedure TiPhoneProjectOptionsEditor.nibFilesBoxClickCheck(Sender:TObject);
begin
end;
procedure TiPhoneProjectOptionsEditor.nibFilesBoxItemClick(Sender:TObject;Index: integer);
var
i, j : Integer;
begin
j:=-1;
for i:=0 to nibFilesBox.Count-1 do
if nibFilesBox.Checked[i] and (Index<>i) then begin
j:=i;
end;
if j>=0 then nibFilesBox.Checked[j]:=false;
end;
procedure TiPhoneProjectOptionsEditor.nibFilesBoxMouseDown(Sender:TObject;Button
:TMouseButton;Shift:TShiftState;X,Y:Integer);
var
i: Integer;
begin
i:=nibFilesBox.ItemAtPos(Point(X,Y), True);
if i>=0 then begin
nibFilesBox.ItemIndex:=i;
SelXibFile:=nibFilesBox.Items[i];
end else
SelXibFile:='';
end;
procedure TiPhoneProjectOptionsEditor.nibFilesBoxMouseUp(Sender:TObject;Button:
TMouseButton;Shift:TShiftState;X,Y:Integer);
begin
end;
procedure TiPhoneProjectOptionsEditor.nibsPopupPopup(Sender:TObject);
begin
mnuOpenIB.Enabled:=SelXibFile<>'';
if mnuOpenIB.Enabled then
mnuOpenIB.Caption:=Format(strOpenXibAtIB, [SelXibFile])
else
mnuOpenIB.Caption:=strOpenAtIB;
mnuDump.Enabled:=SelXibFile<>''
end;
procedure TiPhoneProjectOptionsEditor.DoChanged;
begin
if Assigned(fOnChanged) then fOnChanged(Self);
end;
procedure TiPhoneProjectOptionsEditor.RefreshXIBList;
var
path : AnsiString;
st : TStringList;
i : Integer;
AProjectFile: TLazProjectFile;
begin
path := ResolveProjectPath(trim(edtResDir.Text));
st:=TStringList.Create;
try
for i := 0 to LazarusIDE.ActiveProject.FileCount-1 do
begin
AProjectFile := LazarusIDE.ActiveProject.Files[i];
if (AProjectFile.IsPartOfProject) and FileExistsUTF8(ChangeFileExt(AProjectFile.filename,'.xib')) then
st.add(AProjectFile.filename);
end;
EnumFilesAtDir(path, '*.xib', st);
nibFilesBox.Clear;
for i:=0 to st.Count-1 do
nibFilesBox.Items.Add( ChangeFileExt( ExtractFileName(st[i]), ''));
finally
st.Free;
end;
end;
procedure TiPhoneProjectOptionsEditor.SetControlsEnabled(AEnabled:Boolean);
var
i : Integer;
begin
for i:=0 to ControlCount-1 do
if not (Controls[i] is TLabel) and (Controls[i]<>chkisPhone) then
Controls[i].Enabled:=AEnabled;
end;
function MethodName(const msg: AnsiString): String;
var
i : Integer;
begin
Result:=msg;
for i:=0 to length(Result) do if Result[i]=':' then Result[i]:='_';
end;
function ActionParams(const ActionName: AnsiString): String;
var
i : integer;
c : Integer;
begin
c:=0;
for i:=1 to length(ActionName) do if ActionName[i]=':' then inc(c);
case c of
1 : Result:=('(sender: id)');
2 : Result:=('(sender: id; keyEvent: SEL)');
end;
end;
function SetMethodName(const propName: AnsiString): String;
begin
if propName<>'' then
Result:='set'+AnsiUpperCase(propName[1])+Copy(propName, 2, length(propName)-1)
else
Result:='';
end;
procedure XibClassToInterface(cls: TXibClassDescr; intf: TStrings);
var
i : Integer;
begin
if not Assigned(cls) or not Assigned(intf) then Exit;
intf.Add(' { ' +cls.Name + ' }');
intf.Add('');
intf.Add(' ' +cls.Name + '=objcclass(NSObject)');
if length(cls.Outlets)>0 then begin
intf.Add(' private');
for i:=0 to length(cls.Outlets) - 1 do
intf.Add(' f'+cls.Outlets[i].Key+' : '+ cls.Outlets[i].Value+';');
end;
intf.Add(' public');
for i:=0 to length(cls.Actions) - 1 do
with cls.Actions[i] do
intf.Add(Format(' function %s%s: %s; message ''%s'';', [MethodName(Key), ActionParams(Key), Value, Key]));
for i:=0 to length(cls.Outlets) - 1 do
with cls.Outlets[i] do begin
intf.Add(Format(' function %s: %s; message ''%s'';', [Key, Value, Key]));
intf.Add(Format(' procedure %s(a%s: %s); message ''%s'';',
[SetMethodName(Key), Key, Value, SetMethodName(Key)+':']));
end;
if length(cls.Outlets) > 0 then
intf.Add(' procedure dealloc; override;');
intf.Add(' end;');
intf.Add('');
end;
procedure XibClassToImplementation(cls: TXibClassDescr; st: TStrings);
var
i : Integer;
begin
if not Assigned(cls) or not Assigned(st) then Exit;
if (length(cls.Actions)=0) and (length(cls.Outlets)=0) then exit;
st.Add(' { ' +cls.Name + ' }');
st.Add('');
for i:=0 to length(cls.Actions)-1 do
with cls.Actions[i] do begin
st.Add(Format('function %s.%s%s: %s;', [cls.Name, MethodName(Key), ActionParams(Key), Value]));
st.Add('begin');
st.Add(' // put action''s code here');
st.Add(' Result:=nil;');
st.Add('end;');
st.Add('');
end;
for i:=0 to length(cls.Outlets) - 1 do
with cls.Outlets[i] do begin
st.Add(Format('function %s.%s: %s;', [cls.Name, Key, Value]));
st.Add( 'begin');
st.Add(Format(' Result:=f%s;', [Key]));
st.Add( 'end;');
st.Add( '');
st.Add(Format('procedure %s.%s(a%s: %s);', [cls.Name, SetMethodName(Key), Key, Value]));
st.Add( 'begin');
st.Add(Format(' f%s:=a%s;', [Key, Key]));
st.Add(Format(' f%s.retain;', [Key]));
st.Add( 'end;');
st.Add( '');
end;
if length(cls.Outlets)>0 then begin
st.Add(Format('procedure %s.dealloc; ', [cls.Name]));
st.Add( 'begin');
for i:=0 to length(cls.Outlets) - 1 do
st.Add(Format(' f%s.release;',[cls.Outlets[i].Key]));
st.Add( ' inherited;');
st.Add( 'end;');
st.Add('');
end;
end;
procedure TiPhoneProjectOptionsEditor.DumpClasses(const XibFileName: AnsiString;
var PascalFileName: AnsiString);
var
unitNm : AnsiString;
fs : TFileStream;
xibcls : TList;
i : Integer;
intfPart : TStringList;
implPart : TStringList;
cls : TXibClassDescr;
const
le : Ansistring = LineEnding;
procedure wln(const s: AnsiString);
begin
if s <>'' then
fs.Write(s[1], length(s));
fs.Write(le[1], length(le));
end;
begin
if not FileExists(XibFileName) then Exit;
intfPart:=TStringList.Create;
implPart:=TStringList.Create;
xibcls:=TList.Create;
ListClassesDescr(XibFileName, xibcls);
for i:=0 to xibcls.Count-1 do begin
cls:=TXibClassDescr(xibcls[i]);
XibClassToInterface(cls, intfPart);
XibClassToImplementation(cls, implPart);
cls.Free;
end;
xibcls.Free;
unitNm:='dump'+ChangeFileExt(ExtractFileName(XibFileName),'');
PascalFileName:=ResolveProjectPath(unitNm+'.pas');
fs:=TFileStream.Create(PascalFileName, fmCreate);
wln('unit ' + unitNm+';');
wln('');
wln('{$mode objfpc}{$h+}');
wln('{$modeswitch objectivec1}');
wln('');
wln('interface');
wln('');
if intfPart.Count>0 then begin
wln('type');
for i:=0 to intfPart.Count-1 do wln(intfPart[i]);
end;
wln('');
wln('implementation');
wln('');
if implPart.Count>0 then
for i:=0 to implPart.Count-1 do wln(implPart[i]);
wln('');
wln('end.');
intfPart.Free;
implPart.Free;
fs.Free;
end;
function TiPhoneProjectOptionsEditor.GetTitle: String;
begin
Result:=strPrjOptTitle;
end;
procedure TiPhoneProjectOptionsEditor.Setup(ADialog: TAbstractOptionsEditorDialog);
begin
chkisPhone.Caption := strPrjOptIsiPhone;
lblSDKVer.Caption := strPrjOptSDKver;
lblAppID.Caption := strPtrOptAppID;
lblAppIDHint.Caption := strPtrOptAppIDHint;
end;
procedure TiPhoneProjectOptionsEditor.ReadSettings(AOptions: TAbstractIDEOptions);
var
i : Integer;
begin
with TiPhoneProjectOptions(AOptions) do
begin
Load;
chkisPhone.Checked:=isIPhoneApp;
EnvOptions.GetSDKVersions(cmbSDKs.Items);
i:=cmbSDKs.Items.IndexOf(SDK);
if (i<0) and (cmbSDKs.Items.Count>0) then
i:=cmbSDKs.Items.IndexOf(EnvOptions.DefaultSDK);
cmbSDKs.ItemIndex:=i;
edtAppID.Text:=AppID;
edtResDir.Text:=ResourceDir;
edtExclude.Text:=ExcludeMask;
end;
RefreshXIBList;
if TiPhoneProjectOptions(AOptions).MainNib<>'' then begin
i:=nibFilesBox.Items.IndexOf(TiPhoneProjectOptions(AOptions).MainNib);
if i>=0 then nibFilesBox.Checked[i]:=True;
end;
SetControlsEnabled(chkisPhone.Checked); // is iPhone project
end;
procedure TiPhoneProjectOptionsEditor.WriteSettings(AOptions: TAbstractIDEOptions);
var
amainnib : AnsiString;
i : integer;
begin
amainnib:='';
for i:=0 to nibFilesBox.Count-1 do
if nibFilesBox.Checked[i] then begin
amainnib:=nibFilesBox.Items[i];
Break;
end;
with TiPhoneProjectOptions(AOptions) do
begin
isIPhoneApp:=chkisPhone.Checked;
SDK:=cmbSDKs.Caption;
AppID:=edtAppID.Text;
ResourceDir:=edtResDir.Text;
ExcludeMask:=edtExclude.Text;
MainNib:=amainnib;
Save;
DoChanged;
end;
end;
class function TiPhoneProjectOptionsEditor.SupportedOptionsClass: TAbstractIDEOptionsClass;
begin
Result:=TiPhoneProjectOptions;
end;
const
iPhoneOptions = 10000; //todo: get it dynamically
initialization
{$I project_iphone_options.lrs}
writeln('registering iPhone proj editor');
//RegisterIDEOptionsEditor(iPhonePrjGroup, TiPhoneProjectOptionsEditor, iPhoneOptions);
RegisterIDEOptionsEditor(GroupProject, TiPhoneProjectOptionsEditor, iPhoneOptions);
finalization
end.
|
program exProcedure;
var
a, b, c, min: integer;
procedure findMin(x, y, z: integer; var m: integer);
(* Finds the minimum of the 3 values *)
begin
if x < y then
m:= x
else
m:= y;
if z < m then
m:= z;
end; { end of procedure findMin }
begin
findMin(a, b, c, min); (* Procedure call *)
end.
|
unit GetOrdersWithSpecifiedTextUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TGetOrdersWithSpecifiedText = class(TBaseExample)
public
procedure Execute(SpecifiedText: String);
end;
implementation
uses CommonTypesUnit, OrderUnit;
procedure TGetOrdersWithSpecifiedText.Execute(SpecifiedText: String);
var
ErrorString: String;
Orders: TOrderList;
Offset, Limit: integer;
Total: integer;
begin
Limit := 10;
Offset := 0;
Orders := Route4MeManager.Order.GetOrdersWithSpecifiedText(
SpecifiedText, Limit, Offset, Total, ErrorString);
try
WriteLn('');
if (Orders.Count > 0) then
WriteLn(Format(
'GetOrdersWithSpecifiedText executed successfully, %d orders returned, %d total',
[Orders.Count, Total]))
else
WriteLn(Format('GetOrdersWithSpecifiedText error: "%s"', [ErrorString]));
finally
FreeAndNil(Orders);
end;
end;
end.
|
unit kwPopEditorSelectCellsVertical;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorSelectCellsVertical.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_SelectCellsVertical
//
// *Формат:* aStartCell aStartRow aFinshCell aFinishRow anEditorControl
// pop:editor:SelectCellsVertical
// *Описание:* Выделяет диапазон ячеек с помощью мыши начиная от начальной (aStartCell, aRowCell)
// до конечной (aFinishCell, aFinishRow). Курсор должен уже находится в таблице. Положение курсора
// в таблице не имеет значения. Параметры aStartCell aStartRow aFinshCell aFinishRow - Integer
// *Пример:*
// {code}
// 0 0 2 2 focused:control:push pop:editor:SelectCellsVertical
// {code}
// *Результат:* Выделяет диапазон ячеек в таблице от (0, 0) до (2, 2) у текущего редактора.
// *Примечание:* В каждой ячейке должен быть только один параграф, иначе выделение будет
// неправильным.
// *Примечание 2:* Текст в начальной ячейке должен быть выровнен по левому краю. Иначе появится
// сообщение об ошибке.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
evCustomEditorWindow,
tfwScriptingInterfaces,
Controls,
Classes,
nevTools
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\kwSelectCellsWord.imp.pas}
TkwPopEditorSelectCellsVertical = {final} class(_kwSelectCellsWord_)
{* *Формат:* aStartCell aStartRow aFinshCell aFinishRow anEditorControl pop:editor:SelectCellsVertical
*Описание:* Выделяет диапазон ячеек с помощью мыши начиная от начальной (aStartCell, aRowCell) до конечной (aFinishCell, aFinishRow). Курсор должен уже находится в таблице. Положение курсора в таблице не имеет значения. Параметры aStartCell aStartRow aFinshCell aFinishRow - Integer
*Пример:*
[code]
0 0 2 2 focused:control:push pop:editor:SelectCellsVertical
[code]
*Результат:* Выделяет диапазон ячеек в таблице от (0, 0) до (2, 2) у текущего редактора.
*Примечание:* В каждой ячейке должен быть только один параграф, иначе выделение будет неправильным.
*Примечание 2:* Текст в начальной ячейке должен быть выровнен по левому краю. Иначе появится сообщение об ошибке. }
protected
// realized methods
function IsVertical: Boolean; override;
{* При выделении мышь движется сверху вниз. }
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopEditorSelectCellsVertical
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
l3Base,
l3Units,
evConst,
nevGUIInterfaces,
tfwAutoregisteredDiction,
tfwScriptEngine,
Windows,
afwFacade,
Forms,
Table_Const
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwPopEditorSelectCellsVertical;
{$Include ..\ScriptEngine\kwSelectCellsWord.imp.pas}
// start class TkwPopEditorSelectCellsVertical
function TkwPopEditorSelectCellsVertical.IsVertical: Boolean;
//#UC START# *4F6042D20081_4F6044140356_var*
//#UC END# *4F6042D20081_4F6044140356_var*
begin
//#UC START# *4F6042D20081_4F6044140356_impl*
Result := True;
//#UC END# *4F6042D20081_4F6044140356_impl*
end;//TkwPopEditorSelectCellsVertical.IsVertical
class function TkwPopEditorSelectCellsVertical.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'pop:editor:SelectCellsVertical';
end;//TkwPopEditorSelectCellsVertical.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\kwSelectCellsWord.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit IntfSimple;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Buttons, IntfColSel,
ColorGrd;
type
TFormSimpleColor = class(TForm, IColorSelect)
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
ColorGrid1: TColorGrid;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
procedure SetSelColor (Col: TColor);
function GetSelColor: TColor;
public
procedure ApplyClick (Sender: TObject);
function Display (Modal: Boolean = True): Boolean;
published
property SelectedColor: TColor
read GetSelColor write SetSelColor;
end;
implementation
{$R *.DFM}
procedure TFormSimpleColor.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// used by the modeless form
Action := caFree;
end;
procedure TFormSimpleColor.ApplyClick(Sender: TObject);
begin
// set the color of the main form
Application.MainForm.Color := SelectedColor;
end;
// set and get properties
function TFormSimpleColor.GetSelColor: TColor;
begin
Result := ColorGrid1.ForegroundColor;
end;
procedure TFormSimpleColor.SetSelColor (Col: TColor);
begin
ColorGrid1.ForegroundIndex :=
ColorGrid1.ColorToIndex(Col)
end;
function TFormSimpleColor.Display(Modal: Boolean): Boolean;
begin
Result := True; // default
if Modal then
Result := (ShowModal = mrOK)
else
begin
BitBtn1.Caption := 'Apply';
BitBtn1.OnClick := ApplyClick;
BitBtn2.Kind := bkClose;
Show;
end;
end;
initialization
RegisterColorSelect (TFormSimpleColor);
end.
|
{$REGION 'Copyright (C) CMC Development Team'}
{ **************************************************************************
Copyright (C) 2015 CMC Development Team
CMC is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
CMC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CMC. If not, see <http://www.gnu.org/licenses/>.
************************************************************************** }
{ **************************************************************************
Additional Copyright (C) for this modul:
Chromaprint: Audio fingerprinting toolkit
Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com>
Lomont FFT: Fast Fourier Transformation
Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/
************************************************************************** }
{$ENDREGION}
{$REGION 'Notes'}
{ **************************************************************************
See CP.Chromaprint.pas for more information
************************************************************************** }
unit CP.Imagebuilder;
interface
uses
Classes,
CP.Def, CP.FeatureVectorConsumer, CP.Image;
type
{ TImageBuilder }
TImageBuilder = class(TFeatureVectorConsumer)
private
FImage: TImage;
public
property Image: TImage read FImage write FImage;
public
constructor Create(Image: TImage = nil);
destructor Destroy; override;
procedure Reset(Image: TImage);
procedure Consume(var features: tDoubleArray); override;
end;
implementation
{ TImageBuilder }
constructor TImageBuilder.Create(Image: TImage);
begin
FImage := Image;
end;
destructor TImageBuilder.Destroy;
begin
FImage := nil;
inherited Destroy;
end;
procedure TImageBuilder.Reset(Image: TImage);
begin
FImage := Image;
end;
procedure TImageBuilder.Consume(var features: tDoubleArray);
begin
FImage.AddRow(features);
end;
end.
|
unit versioninfo;
interface
uses
Windows, sysutils;
type
// 1: Major, 2: Minor, 3: Release, 4: Build
TFileVersion = array[1..4] of Smallint;
function GetExeVersion(FileName: string): TFileVersion;
function GetExeVersionStr(FileName: string): string;
implementation
function GetExeVersion(FileName: string): TFileVersion;
var
VerInfoSize, VerValueSize, Dummy: DWord;
VerInfo: Pointer;
VerValue: PVSFixedFileInfo;
begin
// Länge der Dateiinformationen bekommen.
VerInfoSize := GetFileVersionInfoSize(PChar(FileName), Dummy);
// Speicherplatz reservieren.
GetMem(VerInfo, VerInfoSize);
// Dateiinformationen selektieren.
GetFileVersionInfo(PChar(FileName), 0, VerInfoSize, VerInfo);
// Prüfen ob Dateiinformationen vorhanden
if VerInfo <> nil then
begin
// Dateiinformationen auslesen.
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
// Version auslesen und zurückgeben.
with VerValue^ do
begin
// Major
Result[1] := dwFileVersionMS shr 16;
// Minor
Result[2] := dwFileVersionMS and $FFFF;
// Release
Result[3] := dwFileVersionLS shr 16;
// Build
Result[4] := dwFileVersionLS and $FFFF;
end;
end;
// Speicher freigeben (Dateiinformationen).
FreeMem(VerInfo, VerInfoSize);
end;
function GetExeVersionStr(FileName: string): string;
var
ver: TFileVersion;
ver_str: string;
begin
ver := GetExeVersion(filename);
ver_str := IntToStr(ver[1]) + '.' + IntToStr(ver[2]) + '.' + IntToStr(ver[3])
+
'.' + IntToStr(ver[4]);
GetExeVersionStr := ver_str;
end;
end.
|
unit Errores;
interface
resourcestring
rsDatosIncompletos = 'Por Favor, complete datos. (%s)';
rsValorNoCero = 'Valor Debe ser mayor a 0 (%s)';
rsCuitNoValido = 'CUIT es incorrecto. Revise por favor';
rsCantMaxArtSuperada = 'Cantidad Maxima (999) de Articulos superada';
rsInformeNoEncontrado = 'Error! Informe no encontrado en modulo de informes';
rsTasaIVAIncorrecta = 'Error! Tasa de IVA Incorrecta!';
rsErrorFechaVencida = 'FECHA de comprobante (%s) ' + #13 +
'corresponde a periodo CERRADO (%s)' + #13 +
'Debe Modificar la fecha. Imposible Continuar';
rsClienteSinPedido = 'Cliente NO tiene pedidos pendientes';
rsCompleteDatos = 'Falta completar datos de Registro';
rsNoEliminar = 'No se puede eliminar (%s) ya que Hay (%s) que la referencian';
rsAsientoNoEncontrado = 'Asiento no encontrado para edicion';
rsCuentaNoEncontrada = 'Cuenta (%s) no encontrada.';
rsExisteValorReferencia = 'No se puede eliminar %s. Hay registros que requieren de el';
implementation
end.
|
unit FFSSORTTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TFFSSORTRecord = record
PRecordID: Integer;
End;
TFFSSORTBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TFFSSORTRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIFFSSORT = (FFSSORTPrimaryKey);
TFFSSORTTable = class( TDBISAMTableAU )
private
FDFRecordID: TAutoIncField;
procedure SetEnumIndex(Value: TEIFFSSORT);
function GetEnumIndex: TEIFFSSORT;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TFFSSORTRecord;
procedure StoreDataBuffer(ABuffer:TFFSSORTRecord);
property DFRecordID: TAutoIncField read FDFRecordID;
published
property Active write SetActive;
property EnumIndex: TEIFFSSORT read GetEnumIndex write SetEnumIndex;
end; { TFFSSORTTable }
procedure Register;
implementation
procedure TFFSSORTTable.CreateFields;
begin
FDFRecordID := CreateField('RecId') as TAutoIncField; //VG 260717: RecordId is a reserved name in DBISAM4 and can not be used
end; { TFFSSORTTable.CreateFields }
procedure TFFSSORTTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TFFSSORTTable.SetActive }
procedure TFFSSORTTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('RecId, AutoInc, 0, N'); //VG 260717: RecordId is a reserved name in DBISAM4 and can not be used
end;
end;
procedure TFFSSORTTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, RecId, Y, Y, N, N');
end;
end;
procedure TFFSSORTTable.SetEnumIndex(Value: TEIFFSSORT);
begin
case Value of
FFSSORTPrimaryKey : IndexName := '';
end;
end;
function TFFSSORTTable.GetDataBuffer:TFFSSORTRecord;
var buf: TFFSSORTRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PRecordID := DFRecordID.Value;
result := buf;
end;
procedure TFFSSORTTable.StoreDataBuffer(ABuffer:TFFSSORTRecord);
begin
end;
function TFFSSORTTable.GetEnumIndex: TEIFFSSORT;
var iname : string;
begin
result := FFSSORTPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := FFSSORTPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'FFS Tables', [ TFFSSORTTable, TFFSSORTBuffer ] );
end; { Register }
function TFFSSORTBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..1] of string = ('RecId');
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 1) and (flist[x] <> s) do inc(x);
if x <= 1 then result := x else result := 0;
end;
function TFFSSORTBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftAutoInc;
end;
end;
function TFFSSORTBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PRecordID;
end;
end;
end.
|
{ Subroutine SST_R_PAS_EXP_EVAL (VAL)
*
* Evaluate an EXPRESSION syntax. It must be possible to evaluate the expression
* at compile time. VAL is the returned expression value.
}
module sst_r_pas_EXP_EVAL;
define sst_r_pas_exp_eval;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_exp_eval ( {find constant value of EXPRESSION syntax}
out val: sst_var_value_t); {value of EXPRESSION}
var
tag: sys_int_machine_t; {syntax tag ID}
str_h: syo_string_t; {handle to string associated with TAG}
tag_op: sys_int_machine_t; {syntax tag for operator between items}
str_h_op: syo_string_t; {handle to string associated with TAG_OP}
val2: sst_var_value_t; {for ITEM after current operator}
label
loop, do_float, dtype_mismatch, op_mismatch;
begin
syo_level_down; {down to EXPRESSION syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0);
case tag of
1: begin {first operand is EXPRESSION}
sst_r_pas_exp_eval (val);
end;
2: begin {first operand is ITEM}
sst_r_pas_item_eval (val);
end;
otherwise
syo_error_tag_unexp (tag, str_h);
end;
{
* VAL has been initialized from the first (and mandatory) item
* in the expression. There may now be any number of operator/item pairs
* following. For each one, get the new item value, apply the operator, and
* put the result back into VAL. VAL will always be the result of all
* previous work.
}
loop: {back here each new operator/item pair}
syo_get_tag_msg (tag_op, str_h_op, 'sst_pas_read', 'constant_bad', nil, 0); {get op tag}
if tag_op = syo_tag_end_k then begin {no more tags in EXPRESSION ?}
syo_level_up; {back up from EXPRESSION syntax}
return;
end;
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); {get second ITEM tag}
case tag of
1: begin {this operand is EXPRESSION}
sst_r_pas_exp_eval (val2);
end;
2: begin {this operand is ITEM}
sst_r_pas_item_eval (val2);
end;
otherwise
syo_error_tag_unexp (tag, str_h);
end;
{
* VAL declares the value of the first operand, and VAL2 declares
* the value of the second operand. TAG_OP is set to the tag value of the
* operand in between.
}
case val.dtype of {what data type is the first operand ?}
{
****************************************
*
* First operand is INTEGER.
}
sst_dtype_int_k: begin
case val2.dtype of {what is data type of second operand ?}
sst_dtype_int_k: begin {INTEGER op INTEGER}
case tag_op of {what operand was used indicated ?}
1: begin {+}
val.int_val := val.int_val + val2.int_val;
end;
2: begin {-}
val.int_val := val.int_val - val2.int_val;
end;
3: begin {**}
val.int_val := val.int_val ** val2.int_val;
end;
4: begin {*}
val.int_val := val.int_val * val2.int_val;
end;
5: begin {/}
val.float_val := val.int_val / val2.int_val;
val.dtype := sst_dtype_float_k;
end;
6: begin {DIV}
val.int_val := val.int_val div val2.int_val;
end;
7: begin {MOD}
val.int_val := val.int_val mod val2.int_val;
end;
8: begin {&}
val.int_val := val.int_val & val2.int_val;
end;
9: begin {!}
val.int_val := val.int_val ! val2.int_val;
end;
10: begin {=}
val.bool_val := val.int_val = val2.int_val;
val.dtype := sst_dtype_bool_k;
end;
11: begin {<>}
val.bool_val := val.int_val <> val2.int_val;
val.dtype := sst_dtype_bool_k;
end;
12: begin {>=}
val.bool_val := val.int_val >= val2.int_val;
val.dtype := sst_dtype_bool_k;
end;
13: begin {>}
val.bool_val := val.int_val > val2.int_val;
val.dtype := sst_dtype_bool_k;
end;
14: begin {<=}
val.bool_val := val.int_val <= val2.int_val;
val.dtype := sst_dtype_bool_k;
end;
15: begin {<}
val.bool_val := val.int_val < val2.int_val;
val.dtype := sst_dtype_bool_k;
end;
otherwise
goto op_mismatch;
end; {end of INTEGER op INTEGER operator types}
end; {end of INTEGER op INTEGER}
sst_dtype_float_k: begin {INTEGER op FLOAT}
val.float_val := val.int_val; {convert first operand to floating point}
val.dtype := sst_dtype_float_k;
goto do_float; {process two floating point operands}
end; {end of INTEGER op FLOAT case}
otherwise
goto dtype_mismatch;
end; {done with second operand data type cases}
end; {done with first operand is INTEGER case}
{
****************************************
*
* First operand is floating point.
}
sst_dtype_float_k: begin
case val2.dtype of {what is data type of second operand ?}
sst_dtype_int_k: begin {FLOAT op INTEGER}
val2.float_val := val2.int_val; {convert second operand to floating point}
val2.dtype := sst_dtype_float_k;
goto do_float; {process as two floating point operands}
end; {end of FLOAT op INTEGER}
sst_dtype_float_k: begin {FLOAT op FLOAT}
goto do_float; {handle floating point operations}
end; {end of FLOAT op FLOAT}
otherwise
goto dtype_mismatch;
end; {done with second operand data type cases}
end; {done with first operand is FLOAT case}
{
****************************************
*
* First operand is BOOLEAN.
}
sst_dtype_bool_k: begin
case val2.dtype of {what is data type of second operand ?}
sst_dtype_bool_k: begin {BOOLEAN op BOOLEAN}
case tag_op of {what operand was used indicated ?}
10: begin {=}
val.bool_val := val.bool_val = val2.bool_val;
end;
11: begin {<>}
val.bool_val := val.bool_val <> val2.bool_val;
end;
16: begin {AND}
val.bool_val := val.bool_val AND val2.bool_val;
end;
17: begin {OR}
val.bool_val := val.bool_val OR val2.bool_val;
end;
otherwise
goto op_mismatch;
end; {end of BOOLEAN op BOOLEAN operator types}
end; {end of BOOLEAN op BOOLEAN}
otherwise
goto dtype_mismatch;
end; {done with second operand data type cases}
end; {done with first operand is BOOLEAN case}
{
****************************************
*
* Illegal or unsupported data type for first operand of diadic pair.
}
otherwise
goto op_mismatch;
end; {end of first operand data type cases}
goto loop;
do_float: {jump here after convert to FLOAT op FLOAT}
case tag_op of {what operand was used indicated ?}
1: begin {+}
val.float_val := val.float_val + val2.float_val;
end;
2: begin {-}
val.float_val := val.float_val - val2.float_val;
end;
3: begin {**}
val.float_val := val.float_val ** val2.float_val;
end;
4: begin {*}
val.float_val := val.float_val * val2.float_val;
end;
5: begin {/}
val.float_val := val.float_val / val2.float_val;
end;
10: begin {=}
val.bool_val := val.float_val = val2.float_val;
val.dtype := sst_dtype_bool_k;
end;
11: begin {<>}
val.bool_val := val.float_val <> val2.float_val;
val.dtype := sst_dtype_bool_k;
end;
12: begin {>=}
val.bool_val := val.float_val >= val2.float_val;
val.dtype := sst_dtype_bool_k;
end;
13: begin {>}
val.bool_val := val.float_val > val2.float_val;
val.dtype := sst_dtype_bool_k;
end;
14: begin {<=}
val.bool_val := val.float_val <= val2.float_val;
val.dtype := sst_dtype_bool_k;
end;
15: begin {<}
val.bool_val := val.float_val < val2.float_val;
val.dtype := sst_dtype_bool_k;
end;
otherwise
goto op_mismatch;
end; {end of FLOAT op FLOAT operator types}
goto loop; {back and handle next operator/operand pair}
dtype_mismatch: {mismatched operand data types}
syo_error (str_h, 'sst_pas_read', 'exp_dtype_mismatch', nil, 0);
op_mismatch: {operator is mismatched to operand data types}
syo_error (str_h, 'sst_pas_read', 'exp_operand_mismatch', nil, 0);
end;
|
(*---------------------------------------------------------*)
(* Swap implementation with VAR parameter and... *)
(* Neuhold Michael *)
(* 28.11.2018 *)
(*---------------------------------------------------------*)
PROGRAM Swaps;
TYPE
IntegerPointer= ^INTEGER;
{PROCEDURE Swap1(VAR x,y: INTEGER);
VAR
h: INTEGER;
BEGIN
h := x;
x := y;
y := h;
END;}
PROCEDURE Swap2(xPtr,yPtr: IntegerPointer);
VAR
h: INTEGER;
BEGIN
h := xPtr^;
xPtr^ := yPtr^;
yPtr^ := h;
END;
PROCEDURE Swap3(VAR xPtr,yPtr: IntegerPointer);
VAR
h: IntegerPointer;
BEGIN
h := xPtr;
xPtr := yPtr;
yPtr := h;
END;
VAR
x,y: IntegerPointer;
BEGIN
New(x);
New(y);
x^ := 3;
y^ := 4;
WriteLn('x: ', x^);
WriteLn('y: ', y^);
Swap2(x,y);
WriteLn('x: ', x^);
WriteLn('y: ', y^);
Swap3(x,y);
WriteLn('x: ', x^);
WriteLn('y: ', y^);
Dispose(x);
Dispose(y);
END. |
unit UDiscNumPad;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls, UDialog, FMX.Objects, FMX.Edit;
type
TDiscNumPadDialog = class(TDialogFrame)
Label1: TLabel;
resultBox: TEdit;
Line1: TLine;
Number8: TButton;
Number7: TButton;
Number4: TButton;
Number5: TButton;
Number6: TButton;
Number3: TButton;
Number2: TButton;
Number1: TButton;
Number0: TButton;
Dot: TButton;
Cancel: TButton;
ok: TButton;
Clear: TButton;
allDiscBtn: TButton;
itemDiscBtn: TButton;
dollarDiscBtn: TButton;
Number9: TButton;
DiscountTypeEdit: TEdit;
Label2: TLabel;
Label3: TLabel;
procedure Number9Click(Sender: TObject);
procedure Number8Click(Sender: TObject);
procedure Number7Click(Sender: TObject);
procedure Number4Click(Sender: TObject);
procedure Number5Click(Sender: TObject);
procedure Number6Click(Sender: TObject);
procedure Number1Click(Sender: TObject);
procedure Number2Click(Sender: TObject);
procedure Number3Click(Sender: TObject);
procedure Number0Click(Sender: TObject);
procedure ClearClick(Sender: TObject);
procedure CancelClick(Sender: TObject);
procedure okClick(Sender: TObject);
procedure DiscountBtnClick(Sender: TObject);
procedure DotClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
discountType: Integer;
constructor Create(ParentForm: TForm; ParentPanel: TPanel;
CallBackProc: IProcessDialogResult);
end;
implementation
{$R *.fmx}
var j : Integer;
procedure TDiscNumPadDialog.DiscountBtnClick(Sender: TObject);
begin
j := 1;
discountType := (Sender as TButton).Tag;
case discountType of // display discount type
1:
DiscountTypeEdit.Text := 'ALL % Discount';
2:
DiscountTypeEdit.Text := 'Item % Discount';
else
DiscountTypeEdit.Text := 'Dollar Discount';
end;
end;
procedure TDiscNumPadDialog.CancelClick(Sender: TObject);
begin
inherited;
resultBox.Text := '';
self.DialogResult := mrCancel;
FProcessDialogResult.ProcessDialogResult;
end;
procedure TDiscNumPadDialog.ClearClick(Sender: TObject);
begin
inherited;
resultBox.Text := '';
end;
constructor TDiscNumPadDialog.Create(ParentForm: TForm; ParentPanel: TPanel;
CallBackProc: IProcessDialogResult);
begin
inherited;
DiscountTypeEdit.Text := 'ALL % Discount';
end;
procedure TDiscNumPadDialog.DotClick(Sender: TObject);
var
I: Integer;
isdot: Integer;
begin
inherited;
for I := 0 to resultBox.Text.Length - 1 do
begin
if resultBox.Text[I] = '.' then
isdot := 1;
end;
if isdot <> 1 then
resultBox.Text := resultBox.Text + '.';
end;
procedure TDiscNumPadDialog.Number0Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(0);
end;
procedure TDiscNumPadDialog.Number1Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(1);
end;
procedure TDiscNumPadDialog.Number2Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(2);
end;
procedure TDiscNumPadDialog.Number3Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(3);
end;
procedure TDiscNumPadDialog.Number4Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(4);
end;
procedure TDiscNumPadDialog.Number5Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(5);
end;
procedure TDiscNumPadDialog.Number6Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(6);
end;
procedure TDiscNumPadDialog.Number7Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(7);
end;
procedure TDiscNumPadDialog.Number8Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(8);
end;
procedure TDiscNumPadDialog.Number9Click(Sender: TObject);
begin
inherited;
resultBox.Text := resultBox.Text + IntToStr(9);
end;
procedure TDiscNumPadDialog.okClick(Sender: TObject);
begin
inherited;
if j = 0 then
discountType := 1;
if Trim(resultBox.Text) = '' then
begin
FMX.Dialogs.MessageDlg('Please enter the discount value!',
TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOK], 0);
end;
if Trim(DiscountTypeEdit.Text) = '' then
begin
FMX.Dialogs.MessageDlg('Please select a discount type!',
TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOK], 0);
end;
ReturnString := resultBox.Text;
DialogResult := mrOK;
FProcessDialogResult.ProcessDialogResult;
end;
initialization
j :=0;
end.
|
{ GDAX/Coinbase-Pro client library
Copyright (c) 2018 mr-highball
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
}
unit gdax.api.fills;
{$i gdax.inc}
interface
uses
Classes, gdax.api, gdax.api.consts, gdax.api.types;
type
{ TGDAXFillsImpl }
TGDAXFillsImpl = class(TGDAXPagedApi,IGDAXFills)
private
FEntries: TFillEntryArray;
FOrderID: String;
FProductID: String;
protected
function GetCount: Cardinal;
function GetEntries: TFillEntryArray;
function GetOrderID: String;
function GetPaged: IGDAXPaged;
function GetProductID: String;
procedure SetOrderID(Const Value: String);
function BuildQueryParams:String;
function GetTotalSize(Const ASides: TOrderSides): Extended;
function GetTotalPrice(Const ASides: TOrderSides): Extended;
function GetTotalFees(Const ASides: TOrderSides): Extended;
procedure SetProductID(Const AValue: String);
protected
function DoGetSupportedOperations: TRestOperations; override;
function GetEndpoint(Const AOperation: TRestOperation): string; override;
function DoLoadFromJSON(Const AJSON: string;
out Error: string): Boolean;override;
function DoMove(Const ADirection: TGDAXPageDirection; out Error: String;
Const ALastBeforeID, ALastAfterID: Integer;
Const ALimit: TPageLimit=0): Boolean; override;
public
property Paged: IGDAXPaged read GetPaged;
property Entries: TFillEntryArray read GetEntries;
property Count: Cardinal read GetCount;
property OrderID: String read GetOrderID write SetOrderID;
property ProductID: String read GetProductID write SetProductID;
property TotalSize[Const ASides:TOrderSides]: Extended read GetTotalSize;
property TotalPrice[Const ASides:TOrderSides]: Extended read GetTotalPrice;
property TotalFees[Const ASides:TOrderSides]: Extended read GetTotalFees;
procedure ClearEntries;
constructor Create; override;
end;
implementation
uses
fpjson,
jsonparser,
SysUtils;
{ TGDAXFillsImpl }
function TGDAXFillsImpl.BuildQueryParams: String;
begin
Result:='';
//as of 8/23/18 empty call to fills is deprecated, but cb pro will report error
if (Trim(FOrderID).Length + Trim(FProductID).Length)<1 then
Exit;
Result:='?';
//if requesting a specific order id (prioritize this)
if Trim(FOrderID).Length>0 then
Result := Result + TFillEntry.PROP_ORDER + '=' + FOrderID
//append product id filter
else
Result := Result + TFillEntry.PROP_PROD +'=' + FProductID;
//only append moving parameters if we have any
if not GetMovingParameters.IsEmpty then
begin
//we have to check if we are being requested to "move" via paged
if Result.Length > 1 then
Result := Result + '&' + GetMovingParameters
else
Result := Result + GetMovingParameters;
end;
end;
constructor TGDAXFillsImpl.Create;
begin
inherited;
FOrderID:='';
FProductID:='';
end;
function TGDAXFillsImpl.DoGetSupportedOperations: TRestOperations;
begin
Result:=[roGet];
end;
function TGDAXFillsImpl.DoLoadFromJSON(Const AJSON: string; out Error: string): Boolean;
var
LJSON : TJSONArray;
I : Integer;
begin
Result := False;
try
//clear fill entries
SetLength(FEntries,0);
//determine if we can load the array
LJSON := TJSONArray(GetJSON(AJSON));
if not Assigned(LJSON) then
raise Exception.Create(E_BADJSON);
try
//deserialize fill entries
for I := 0 to Pred(LJSON.Count) do
begin
SetLength(FEntries,Succ(Length(FEntries)));
FEntries[High(FEntries)]:=TFillEntry.Create(LJSON.Items[I].AsJSON);
end;
Result := True;
finally
LJSON.Free;
end;
except on E: Exception do
Error := E.Message;
end;
end;
function TGDAXFillsImpl.DoMove(Const ADirection: TGDAXPageDirection; out
Error: String; Const ALastBeforeID, ALastAfterID: Integer;
Const ALimit: TPageLimit): Boolean;
var
LEntries:TFillEntryArray;
I,J:Integer;
begin
SetLength(LEntries,0);
if Length(FEntries)>0 then
LEntries := FEntries;
Result := inherited DoMove(ADirection, Error, ALastBeforeID, ALastAfterID,ALimit);
if not Result then
Exit;
//only if we have a local array that needs to be appended somewhere do we
//do this logic
if (Length(LEntries)>0) then
begin
//use length because we want the index "after" the highest entry
I := Length(LEntries);
SetLength(LEntries,Length(LEntries)+Length(FEntries));
if ADirection=pdBefore then
begin
if Length(FEntries)>0 then
begin
//slide old entries ahead of new entries
for J:=0 to High(LEntries) - I do
LEntries[I + J]:=LEntries[J];
//now move new entries to start
for J:=0 to High(FEntries) do
LEntries[J]:=FEntries[J];
end;
//lastly, assign our merged array to private var
FEntries := LEntries;
end
else
begin
//move new entries to end and assign to private var
if Length(FEntries)>0 then
for J:=0 to High(FEntries) do
LEntries[I + J]:=FEntries[J];
FEntries := LEntries;
end;
end;
end;
procedure TGDAXFillsImpl.ClearEntries;
begin
SetLength(FEntries,0);
end;
function TGDAXFillsImpl.GetEndpoint(Const AOperation: TRestOperation): string;
begin
Result:='';
if AOperation=roGet then
Result := GDAX_END_API_FILLS+BuildQueryParams;
end;
function TGDAXFillsImpl.GetOrderID: String;
begin
Result := FOrderID;
end;
function TGDAXFillsImpl.GetEntries: TFillEntryArray;
begin
Result := FEntries;
end;
function TGDAXFillsImpl.GetCount: Cardinal;
begin
Result := Length(FEntries);
end;
function TGDAXFillsImpl.GetPaged: IGDAXPaged;
begin
Result := Self as IGDAXPaged;
end;
function TGDAXFillsImpl.GetProductID: String;
begin
Result := FProductID;
end;
function TGDAXFillsImpl.GetTotalFees(Const ASides: TOrderSides): Extended;
var
I: Integer;
begin
Result:=0;
for I := 0 to High(FEntries) do
if FEntries[I].Side in ASides then
Result := Result + FEntries[I].Fee;
end;
procedure TGDAXFillsImpl.SetProductID(Const AValue: String);
begin
FProductID := AValue;
end;
function TGDAXFillsImpl.GetTotalPrice(Const ASides: TOrderSides): Extended;
var
I: Integer;
begin
Result:=0;
for I := 0 to High(FEntries) do
if FEntries[I].Side in ASides then
Result := Result + FEntries[I].Price;
end;
function TGDAXFillsImpl.GetTotalSize(Const ASides: TOrderSides): Extended;
var
I: Integer;
begin
Result:=0;
for I := 0 to High(FEntries) do
if FEntries[I].Side in ASides then
Result := Result + FEntries[I].Size;
end;
procedure TGDAXFillsImpl.SetOrderID(Const Value: String);
begin
FOrderID := Value;
end;
end.
|
unit StockDataTaskConsole0;
interface
uses
Classes, Windows, Messages, SysUtils,
define_dealitem,
define_datasrc,
db_dealitem,
win.process,
StockDataConsoleTask;
type
TStockTaskConsoleData = record
StockItemDB: TDBDealItem;
StockIndexDB: TDBDealItem;
TaskList: TList;
end;
TStockTaskConsole = class
protected
fStockTaskConsoleData: TStockTaskConsoleData;
public
constructor Create;
destructor Destroy; override;
function CheckOutDownloadTask(ATaskDataSrc: TDealDataSource; ATaskDealItemCode: integer): PDownloadTask;
function NewDownloadTask(ATaskDataSrc: TDealDataSource; ATaskDealItemCode: integer): PDownloadTask;
function GetDownloadTask(ATaskDataSrc: TDealDataSource; ATaskDealItemCode: integer): PDownloadTask;
function GetDownloadTaskByProcessID(AProcessId: integer): PDownloadTask;
procedure ClearTask;
function CreateProcessHostCommandWindow(AProcess: POwnedProcess): Boolean;
function Console_GetNextDownloadDealItem(ADownloadTask: PDownloadTask): PRT_DealItem; overload;
function Console_GetNextDownloadDealItem_DB(ADownloadTask: PDownloadTask; ADealItemDB: TDBDealItem): PRT_DealItem; overload;
procedure Console_NotifyDownloadData(ADownloadTask: PDownloadTask);
function Console_CheckDownloaderProcess(ADownloadTask: PDownloadTask): Boolean;
procedure Console_NotifyDownloaderShutdown(ADownloadTask: PDownloadTask);
property StockItemDB: TDBDealItem read fStockTaskConsoleData.StockItemDB write fStockTaskConsoleData.StockItemDB;
property StockIndexDB: TDBDealItem read fStockTaskConsoleData.StockIndexDB write fStockTaskConsoleData.StockIndexDB;
end;
var
G_StockTaskConsole: TStockTaskConsole = nil;
implementation
uses
windef_msg,
define_dealstore_file,
define_StockDataApp,
BaseStockFormApp;
function BusinessCommandWndProcA(ADownloadTask: PDownloadTask; AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT;
var
tmpStockCode: integer;
tmpDataSrc: integer;
tmpDownloadTask: PDownloadTask;
tmpDealItem: PRT_DealItem;
begin
Result := 0;
case AMsg of
WM_RegisterClientCommandWnd: begin
if 0 <> lParam then
begin
tmpDownloadTask := G_StockTaskConsole.GetDownloadTaskByProcessID(wParam);
if nil <> tmpDownloadTask then
begin
if IsWindow(lParam) then
begin
tmpDownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd := lParam;
end;
end;
end;
end;
WM_Console_Command_Download: begin
if nil <> GlobalBaseStockApp then
begin
//GlobalBaseStockApp.RunStart;
if nil <> G_StockTaskConsole then
begin
tmpDataSrc := lParam;
tmpStockCode := wParam;
tmpDownloadTask := G_StockTaskConsole.GetDownloadTask(GetDealDataSource(tmpDataSrc), tmpStockCode);
if nil = tmpDownloadTask then
begin
tmpDownloadTask := G_StockTaskConsole.NewDownloadTask(GetDealDataSource(tmpDataSrc), tmpStockCode);
end;
tmpDownloadTask.TaskStatus := TaskStatus_Active;
if not G_StockTaskConsole.Console_CheckDownloaderProcess(tmpDownloadTask) then
begin
PostMessage(AWnd, WM_Console_Command_Download, wParam, lParam);
exit;
end;
if not IsWindow(tmpDownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd) then
begin
PostMessage(AWnd, WM_Console_Command_Download, wParam, lParam);
exit;
end;
G_StockTaskConsole.Console_NotifyDownloadData(tmpDownloadTask);
end;
end;
exit;
end;
WM_Downloader2Console_Command_DownloadResult: begin
tmpDownloadTask := G_StockTaskConsole.GetDownloadTaskByProcessID(wParam);
if nil <> tmpDownloadTask then
begin
if 0 = lParam then
begin
// 下载成功
tmpDealItem := G_StockTaskConsole.Console_GetNextDownloadDealItem(tmpDownloadTask);
if nil <> tmpDealItem then
begin
tmpDownloadTask.DownProcessTaskArray[0].DealItem := tmpDealItem;
PostMessage(AWnd, WM_Console_Command_Download, tmpDownloadTask.TaskDealItemCode, GetDealDataSourceCode(tmpDownloadTask.TaskDataSrc));
end else
begin
// 都下载完了 ???
tmpDownloadTask.DownProcessTaskArray[0].DealItem := nil;
tmpDownloadTask.TaskStatus := TaskStatus_End;
G_StockTaskConsole.Console_NotifyDownloaderShutdown(tmpDownloadTask);
//PostMessage(AWnd, WM_AppRequestEnd, 0, 0);
end;
end else
begin
// 下载失败
PostMessage(AWnd, WM_Console_Command_Download, 0, 0);
end;
end;
end;
end;
end;
function ProcessHostCommandWndProcA(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
begin
// Result := 0;
// case AMsg of
// WM_Console_Command_Download: begin
// end;
// WM_Downloader2Console_Command_DownloadResult: begin
// end;
// end;
Result := BusinessCommandWndProcA(nil, AWnd, AMsg, wParam, lParam);
Result := DefWindowProcA(AWnd, AMsg, wParam, lParam);
end;
constructor TStockTaskConsole.Create;
begin
inherited;
FillChar(fStockTaskConsoleData, SizeOf(fStockTaskConsoleData), 0);
fStockTaskConsoleData.TaskList := TList.Create;
G_StockTaskConsole := Self;
end;
destructor TStockTaskConsole.Destroy;
begin
if Self = G_StockTaskConsole then
G_StockTaskConsole := nil;
ClearTask;
FreeAndNil(fStockTaskConsoleData.TaskList);
inherited;
end;
procedure TStockTaskConsole.ClearTask;
var
i: Integer;
tmpTask: PDownloadTask;
begin
if nil <> fStockTaskConsoleData.TaskList then
begin
for i := fStockTaskConsoleData.TaskList.Count - 1 downto 0 do
begin
tmpTask := fStockTaskConsoleData.TaskList.Items[i];
FreeMem(tmpTask);
end;
fStockTaskConsoleData.TaskList.Clear;
end;
end;
function TStockTaskConsole.GetDownloadTask(ATaskDataSrc: TDealDataSource; ATaskDealItemCode: integer): PDownloadTask;
var
i: Integer;
tmpTask: PDownloadTask;
begin
Result := nil;
if nil <> fStockTaskConsoleData.TaskList then
begin
for i := fStockTaskConsoleData.TaskList.Count - 1 downto 0 do
begin
tmpTask := fStockTaskConsoleData.TaskList.Items[i];
if (tmpTask.TaskDataSrc = ATaskDataSrc) and ((tmpTask.TaskDealItemCode = ATaskDealItemCode)) then
begin
Result := tmpTask;
Break;
end;
end;
end;
end;
function TStockTaskConsole.GetDownloadTaskByProcessID(AProcessId: integer): PDownloadTask;
var
i: Integer;
tmpTask: PDownloadTask;
begin
Result := nil;
if nil <> fStockTaskConsoleData.TaskList then
begin
for i := fStockTaskConsoleData.TaskList.Count - 1 downto 0 do
begin
tmpTask := fStockTaskConsoleData.TaskList.Items[i];
if tmpTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessId = AProcessId then
begin
Result := tmpTask;
Break;
end;
end;
end;
end;
function TStockTaskConsole.NewDownloadTask(ATaskDataSrc: TDealDataSource; ATaskDealItemCode: integer): PDownloadTask;
begin
Result := System.New(PDownloadTask);
FillChar(Result^, SizeOf(TDownloadTask), 0);
Result.TaskDataSrc := ATaskDataSrc;
Result.TaskDealItemCode := ATaskDealItemCode;
fStockTaskConsoleData.TaskList.Add(Result);
CreateProcessHostCommandWindow(@Result.DownProcessTaskArray[0].DownloadProcess);
end;
function TStockTaskConsole.CheckOutDownloadTask(ATaskDataSrc: TDealDataSource; ATaskDealItemCode: integer): PDownloadTask;
begin
Result := GetDownloadTask(ATaskDataSrc, ATaskDealItemCode);
if nil = Result then
Result := NewDownloadTask(ATaskDataSrc, ATaskDealItemCode);
end;
function TStockTaskConsole.CreateProcessHostCommandWindow(AProcess: POwnedProcess): Boolean;
var
tmpRegWinClass: TWndClassA;
tmpGetWinClass: TWndClassA;
tmpIsReged: Boolean;
tmpWndClassName: AnsiString;
tmpGuid: TGuid;
begin
//Log('StockDataConsoleApp.pas', 'CreateProcessHostCommandWindow');
Result := false;
FillChar(tmpRegWinClass, SizeOf(tmpRegWinClass), 0);
tmpRegWinClass.hInstance := HInstance;
tmpRegWinClass.lpfnWndProc := @ProcessHostCommandWndProcA;
CreateGuid(tmpGuid);
tmpWndClassName := GuidToString(tmpGuid);
tmpRegWinClass.lpszClassName := PAnsiChar(tmpWndClassName);
tmpIsReged := GetClassInfoA(HInstance, tmpRegWinClass.lpszClassName, tmpGetWinClass);
if tmpIsReged then
begin
if (tmpGetWinClass.lpfnWndProc <> tmpRegWinClass.lpfnWndProc) then
begin
UnregisterClassA(tmpRegWinClass.lpszClassName, HInstance);
tmpIsReged := false;
end;
end;
if not tmpIsReged then
begin
if 0 = RegisterClassA(tmpRegWinClass) then
exit;
end;
AProcess.HostCmdWnd.CmdWndHandle := CreateWindowExA(
WS_EX_TOOLWINDOW
//or WS_EX_APPWINDOW
//or WS_EX_TOPMOST
,
tmpRegWinClass.lpszClassName,
'', WS_POPUP {+ 0},
0, 0, 0, 0,
HWND_MESSAGE, 0, HInstance, nil);
Result := Windows.IsWindow(AProcess.HostCmdWnd.CmdWndHandle);
//Log('StockDataConsoleApp.pas', 'CreateProcessHostCommandWindow:' + IntToStr(AProcess.HostCmdWnd.CmdWndHandle));
end;
procedure TStockTaskConsole.Console_NotifyDownloadData(ADownloadTask: PDownloadTask);
begin
if nil = ADownloadTask then
exit;
if nil = ADownloadTask.DownProcessTaskArray[0].DealItem then
ADownloadTask.DownProcessTaskArray[0].DealItem := Console_GetNextDownloadDealItem(ADownloadTask);
if nil = ADownloadTask.DownProcessTaskArray[0].DealItem then
begin
PostMessage(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd, WM_AppRequestEnd, 0, 0);
exit;
end;
if Console_CheckDownloaderProcess(ADownloadTask) then
begin
PostMessage(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd, WM_Console2Downloader_Command_Download_Day,
ADownloadTask.DownProcessTaskArray[0].DealItem.iCode, GetDealDataSourceCode(ADownloadTask.TaskDataSrc));
end;
end;
function TStockTaskConsole.Console_GetNextDownloadDealItem(ADownloadTask: PDownloadTask): PRT_DealItem;
begin
Result := nil;
if 0 = ADownloadTask.TaskDataDB then
begin
if 0 = ADownloadTask.CurrentDataDB then
begin
ADownloadTask.CurrentDataDB := FilePath_DBType_Item;
ADownloadTask.DownProcessTaskArray[0].DealItemIndex := 0;
end;
end else
begin
ADownloadTask.CurrentDataDB := ADownloadTask.TaskDataDB;
end;
if FilePath_DBType_Item = ADownloadTask.CurrentDataDB then
begin
Result := Console_GetNextDownloadDealItem_DB(ADownloadTask, fStockTaskConsoleData.StockItemDB);
end;
if nil = Result then
begin
if 0 = ADownloadTask.TaskDataDB then
begin
if FilePath_DBType_Item = ADownloadTask.CurrentDataDB then
begin
ADownloadTask.CurrentDataDB := FilePath_DBType_Index;
ADownloadTask.DownProcessTaskArray[0].DealItemIndex := 0;
end;
end;
end;
if FilePath_DBType_Index = ADownloadTask.CurrentDataDB then
begin
Result := Console_GetNextDownloadDealItem_DB(ADownloadTask, fStockTaskConsoleData.StockIndexDB);
end;
end;
function TStockTaskConsole.Console_GetNextDownloadDealItem_DB(ADownloadTask: PDownloadTask; ADealItemDB: TDBDealItem): PRT_DealItem;
var
tmpDealItem: PRT_DealItem;
begin
Result := nil;
if nil = ADealItemDB then
exit;
if 1 > ADealItemDB.RecordCount then
exit;
if 0 > ADownloadTask.DownProcessTaskArray[0].DealItemIndex then
ADownloadTask.DownProcessTaskArray[0].DealItemIndex := 0;
if ADealItemDB.RecordCount <= ADownloadTask.DownProcessTaskArray[0].DealItemIndex then
exit;
if 0 <> ADownloadTask.TaskDealItemCode then
begin
if nil = ADownloadTask.DownProcessTaskArray[0].DealItem then
begin
ADownloadTask.DownProcessTaskArray[0].DealItem := ADealItemDB.FindDealItemByCode(IntToStr(ADownloadTask.TaskDealItemCode));
Result := ADownloadTask.DownProcessTaskArray[0].DealItem;
end;
if nil <> ADownloadTask.DownProcessTaskArray[0].DealItem then
begin
if ADownloadTask.DownProcessTaskArray[0].DealItem.iCode = ADownloadTask.TaskDealItemCode then
begin
end;
end;
exit;
end;
if nil = ADownloadTask.DownProcessTaskArray[0].DealItem then
begin
ADownloadTask.DownProcessTaskArray[0].DealItemIndex := 0;
end;
if nil = ADownloadTask.DownProcessTaskArray[0].DealItem then
begin
Result := ADealItemDB.Items[ADownloadTask.DownProcessTaskArray[0].DealItemIndex];
ADownloadTask.DownProcessTaskArray[0].DealItem := Result;
end else
begin
tmpDealItem := ADealItemDB.Items[ADownloadTask.DownProcessTaskArray[0].DealItemIndex];
if ADownloadTask.DownProcessTaskArray[0].DealItem.iCode = tmpDealItem.iCode then
begin
while nil = Result do
begin
Inc(ADownloadTask.DownProcessTaskArray[0].DealItemIndex);
if ADealItemDB.RecordCount > ADownloadTask.DownProcessTaskArray[0].DealItemIndex then
begin
tmpDealItem := ADealItemDB.Items[ADownloadTask.DownProcessTaskArray[0].DealItemIndex];
if 0 = tmpDealItem.EndDealDate then
begin
Result := tmpDealItem;
ADownloadTask.DownProcessTaskArray[0].DealItem := Result;
end;
end else
begin
Break;
end;
end;
end;
end;
end;
function TStockTaskConsole.Console_CheckDownloaderProcess(ADownloadTask: PDownloadTask): Boolean;
var
tmpRetCode: DWORD;
begin
// 这里主要 检查 下载进程是否有效
//Log('StockDataConsoleApp.pas', 'Console_CheckDownloaderProcess');
Result := false;
if nil = ADownloadTask then
exit;
Result := IsWindow(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd);
if not Result then
begin
if 0 <> ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle then
begin
if Windows.GetExitCodeProcess(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle, tmpRetCode) then
begin
if Windows.STILL_ACTIVE <> tmpRetCode then
ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessId := 0;
end;
end else
begin
ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessId := 0;
end;
if 0 = ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessId then
begin
//Log('StockDataConsoleApp.pas', 'Console_CheckDownloaderProcess RunProcessA begin');
RunProcessA(@ADownloadTask.DownProcessTaskArray[0].DownloadProcess, ParamStr(0));
Sleep(1);
//Log('StockDataConsoleApp.pas', 'Console_CheckDownloaderProcess RunProcessA end');
end;
if (0 = ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle) or
(INVALID_HANDLE_VALUE = ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle) then
exit;
(*//
tmpWindowName := IntToStr(ADownloadTask.DownloadProcess.Core.ProcessId);
for i := 0 to 100 do
begin
if IsWindow(ADownloadTask.DownloadProcess.Core.AppCmdWnd) then
Break;
Sleep(10);
ADownloadTask.DownloadProcess.Core.AppCmdWnd := Windows.FindWindowA(AppCmdWndClassName_StockDataDownloader, PAnsiChar(tmpWindowName));
Log('StockDataConsoleApp.pas', 'Console_CheckDownloaderProcess Command Wnd:' + IntToStr(ADownloadTask.DownloadProcess.Core.AppCmdWnd));
end;
//*)
//Result := IsWindow(ADownloadTask.DownloadProcess.Core.AppCmdWnd);
if Windows.GetExitCodeProcess(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.ProcessHandle, tmpRetCode) then
begin
Result := Windows.STILL_ACTIVE = tmpRetCode;
end;
end;
end;
procedure TStockTaskConsole.Console_NotifyDownloaderShutdown(ADownloadTask: PDownloadTask);
begin
if IsWindow(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd) then
begin
PostMessage(ADownloadTask.DownProcessTaskArray[0].DownloadProcess.Core.AppCmdWnd, WM_AppRequestEnd, 0, 0);
end;
end;
end.
|
unit SystemStr;
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\Common\SystemStr.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "SystemStr" MUID: (54F443CF018E)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3IntfUses
;
const
cMainFormPath = 'Настройки форм/utMainWindow/';
cFrmIDMainMenu = cMainFormPath + 'utNavigator/';
cFrmIDConfList = cMainFormPath + 'utConfigurationList/';
cFrmIDMyDoc = cMainFormPath + 'utFolders/';
cFrmIDRubTree = cMainFormPath + 'utRubricatorTree/';
cFrmIDFilter = cMainFormPath + 'utFilters/';
cFrmIDRedations = cMainFormPath + 'utRedaction/';
cFrmIDDocUnderControl = cMainFormPath + 'utUnderControl/';
cFrmIDTaskPanel = cMainFormPath + 'tpMain/';
cFrmIDDictionaryTerm = cMainFormPath + 'utDiction/';
casExportTitle = 'Текущее; По умолчанию; Тип; Идентификатор; Название;';
li_il_Russian = 'Русский';
li_il_English = 'Английский';
li_il_German = 'Немецкий';
li_il_French = 'Французский';
li_il_Spanish = 'Испанский';
li_il_Italian = 'Итальянский';
li_li_Document_CRType0 = 'Все документы';
li_li_Document_CRType1 = 'Документы';
li_li_Document_CRType2 = 'Комментарии, разъяснения, схемы';
li_li_Document_CRType3 = 'Формы документов';
li_li_Document_CRType4 = 'Проекты законов';
li_li_Document_CRType5 = 'Судебная практика';
li_li_Document_CRType6 = 'Международные договоры';
li_li_Document_CRType7 = 'Не найдено';
li_li_Document_CRType8 = 'Пользовательский тип';
ccakFederalLawFull = 'Федеральное законодательство и проекты федеральных законов';
ccakFederalLawShort = 'Федеральное законодательство';
ccakJudgePracticeLawFull = 'Судебная и арбитражная практика';
ccakJudgePracticeLawShort = 'Судебная практика';
ccakRegionalLaw = 'Региональное законодательство';
implementation
uses
l3ImplUses
//#UC START# *54F443CF018Eimpl_uses*
//#UC END# *54F443CF018Eimpl_uses*
;
end.
|
unit localized_string_lib;
interface
uses windows,classes,streaming_class_lib,contnrs;
//пусть именно этот модуль хранит переменную - текущий выставленный язык
//и TLocalizedName на нее опирается
type
TLangIdType = Integer;
TListWithID = class(TList)
public
ID: Integer;
end;
TLangId = class(TPersistent)
private
fStrings: TStringList;
procedure ReadData(reader: TReader);
procedure WriteData(writer: TWriter);
protected
procedure DefineProperties(filer: TFiler); override;
public
constructor Create;
destructor Destroy; override;
procedure Add(name: string; lang,sublang: Integer);
function NameToID(name:string): Integer;
function IDToName(id: integer): string;
end;
TLangPrefMatrix = class(TComponent)
private
fList: TObjectList;
procedure ReadData(reader: TReader);
procedure WriteData(writer: TWriter);
protected
procedure DefineProperties(filer: TFiler); override;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure Add(prefList: TListWithID);
function GetPrefList(ID: Integer): TListWithId;
end;
TLocalePreferences=class(TStreamingClass)
private
fLangId: TLangId;
fLangPrefMatrix: TLangPrefMatrix;
fCurLang,fResLang: Integer;
fAvailLanguageList: TList;
procedure SetLanguage(value: string);
procedure SetLanguageID(value: Integer);
function GetLanguage: string;
procedure SetResourceLang(value: string);
function GetResourceLang: string;
public
constructor Create(Owner: TComponent); override;
constructor CreateDefault;
destructor Destroy; override;
procedure Loaded; override;
function GetAppropriateLang(list: TListWithID): Integer;
function TryGetMatchingString(ID: Integer; strings: TStrings; out str: string): Boolean;
function TrySetMatchingString(ID: Integer; strings: TStrings; val: string): Boolean;
function GetLanguageList: TStringList; //string:название языка, object: его ID
function ChangeLanguageID(value: Integer): Boolean;
function ChangeLanguage(value: string): Boolean;
property languageID: Integer read fCurLang write SetLanguageID;
property ResourceLangID: Integer read fResLang;
published
property LangID: TLangId read fLangId write fLangId;
property LangPrefMatrix: TLangPrefMatrix read fLangPrefMatrix write fLangPrefMatrix;
property ResourceLang: string read GetResourceLang write SetResourceLang;
property Language: string read GetLanguage write SetLanguage;
end;
TLocalizedName = class (TComponent) //опробуем композицию вместо наследования
//можно указать это имя на любых языках и он это поймет, но возвращать будет
//язык, поставленный в настройках
//плюс, сохранение в файле и считывание из него
private
fStrings: TStringList;
procedure ReadData(reader: TReader);
procedure WriteData(writer: TWriter);
protected
procedure DefineProperties(filer: TFiler); override;
procedure SetMatchingString(lang,value: string);
function GetMatchingString(lang: string): string;
public
constructor Create(aOwner: TComponent); override;
constructor CreateEmptyNeutral(aOwner: Tcomponent=nil);
procedure MakeEmptyNeutral;
destructor Destroy; override;
procedure Assign(source: TPersistent); override;
procedure Clear;
function Caption: string;
function TryCaption(out Caption: string): Boolean;
function MatchingString(Lang: TObject): string;
function TryMatchingString(Lang: TObject; out val: string): Boolean;
function TryEnglish(out val: string): Boolean;
function InEnglish: string;
function Enabled: Boolean;
function isNeutral(index: Integer): Boolean;
procedure AddString(str, langName: string);
procedure AddInCurrentLang(str: string);
procedure LeftConcat(source: TLocalizedName; chr: string=''); overload;
procedure LeftConcat(str: string); overload;
procedure RightConcat(source: TLocalizedName; chr: string=''); overload;
procedure RightConcat(str: string); overload;
property strings: TStringList read fstrings;
property str[Lang: string]: string read GetMatchingString write SetMatchingString;
// function EqualsTo(value: string): Boolean;
end;
function GetDefaultLanguageInEnglish: string;
function LocaleCompareStr(s1,s2: string): Integer;
function LocaleCompareText(s1,s2: string): Integer;
var LocalePreferences: TLocalePreferences;
implementation
{$R LanguageSettings.txt}
uses sysutils,reinit,simple_parser_lib;
(*
General functions
*)
function GetDefaultLanguageInEnglish: string;
var size: Integer;
begin
Size:=GetLocaleInfo(LANG_USER_DEFAULT,LOCALE_SENGLANGUAGE,nil,0);
SetLength(Result,size);
GetLocaleInfo(LANG_USER_DEFAULT,LOCALE_SENGLANGUAGE,@Result[1],size);
end;
function GetDefaultLanguageID: Integer;
var loc_str: PChar;
size: Integer;
begin
Size:=GetLocaleInfo(LANG_USER_DEFAULT,LOCALE_ILANGUAGE,nil,0);
loc_Str:=AllocMem(Size);
GetLocaleInfo(LANG_USER_DEFAULT,LOCALE_ILANGUAGE,loc_str,size);
Result:=StrToInt(loc_str);
FreeMem(loc_str);
end;
function GetLanguageNameInCurLocale(Lang_ID: Integer): string;
var size: Integer;
begin
Size:=GetLocaleInfo(Lang_ID,LOCALE_SLANGUAGE,nil,0);
SetLength(Result,size);
GetLocaleInfo(Lang_ID,LOCALE_SLANGUAGE,@Result[1],size);
end;
(*
TLangID
*)
constructor TLangID.Create;
begin
inherited Create;
fStrings:=TStringList.Create;
fstrings.CaseSensitive:=false;
fStrings.Sorted:=true;
fStrings.Duplicates:=dupError;
end;
destructor TLangID.Destroy;
begin
fStrings.Free;
inherited Destroy;
end;
procedure TLangID.DefineProperties(filer: TFiler);
begin
filer.DefineProperty('data',ReadData,WriteData,fStrings.Count>0);
end;
procedure TLangId.WriteData(writer: TWriter);
var i: Integer;
begin
writer.WriteListBegin;
for i:=0 to fStrings.Count-1 do
writer.WriteString(Format('%s;%x;%x',[fStrings[i],
Integer(fStrings.Objects[i]) and $03FF,Integer(fStrings.Objects[i]) shr 10]));
writer.WriteListEnd;
end;
procedure TLangId.ReadData(reader: TReader);
var p: TSimpleParser;
nm: string;
lang,sublang: Integer;
begin
reader.ReadListBegin;
p:=TSimpleParser.Create;
while not reader.EndOfList do begin
p.AssignString(reader.ReadString);
nm:=p.getString;
lang:=p.getHex;
sublang:=p.getHex;
Add(nm,lang,sublang);
end;
p.Free;
reader.ReadListEnd;
end;
procedure TLangId.Add(name: string; lang,sublang: Integer);
begin
fstrings.AddObject(name,TObject(lang or (sublang shl 10)));
end;
function TLangID.NameToID(name: string): Integer;
var i: Integer;
begin
i:=fstrings.IndexOf(name);
if i>=0 then
Result:=Integer(fstrings.Objects[i])
else
Raise Exception.CreateFmt('Language %s not found among langID',[name]);
end;
function TLangID.IDToName(id: Integer): string;
var i: Integer;
begin
i:=fstrings.IndexOfObject(TObject(id));
if i>=0 then
Result:=fstrings[i]
else
Raise Exception.CreateFmt('Language with ID %x not found among LangID',[id]);
end;
(*
TLangPrefMatrix
*)
function LanguageListCompare (Item1, Item2: Pointer): Integer;
var i1: TListWithId absolute Item1;
i2: TListWIthId absolute Item2;
begin
if i1.id>i2.ID then Result:=1
else if i1.Id<i2.ID then Result:=-1
else Result:=0;
end;
constructor TLangPrefMatrix.Create(Owner: TComponent);
begin
inherited Create(Owner);
fList:=TObjectList.Create(true);
end;
destructor TLangPrefMatrix.Destroy;
begin
fList.Free;
inherited Destroy;
end;
procedure TLangPrefMatrix.DefineProperties(filer: TFiler);
begin
filer.DefineProperty('data',ReadData,WriteData,fList.Count>0);
end;
procedure TLangPrefMatrix.WriteData(writer: TWriter);
var i,j: Integer;
langID: TLangId;
begin
langID:=(Owner as TLocalePreferences).LangID;
writer.WriteListBegin;
for i:=0 to fList.Count-1 do
with TListWithID(fList[i]) do begin
writer.WriteIdent(langID.IDToName(ID));
writer.WriteListBegin;
for j:=0 to Count-1 do
writer.WriteIdent(langID.IDToName(Integer(Items[j])));
writer.WriteListEnd;
end;
writer.WriteListEnd;
end;
procedure TLangPrefMatrix.ReadData(reader: TReader);
var langID: TLangId;
lst: TListWithID;
begin
langID:=(Owner as TLocalePreferences).LangID;
reader.ReadListBegin;
while not reader.EndOfList do begin
lst:=TListWithID.Create;
lst.ID:=langID.NameToID(reader.ReadIdent);
reader.ReadListBegin;
while not reader.EndOfList do
lst.Add(Pointer(langID.NameToID(reader.ReadIdent)));
Add(lst);
reader.ReadListEnd;
end;
reader.ReadListEnd;
fList.Sort(LanguageListCompare);
end;
procedure TLangPrefMatrix.Add(prefList: TListWithId);
begin
fList.Add(prefList);
end;
function TLangPrefMatrix.GetPrefList(ID: Integer): TListWithId;
var i: Integer;
begin
for i:=0 to flist.Count-1 do begin
Result:=TListWithID(flist[i]);
if Result.ID=ID then Exit
else if Result.ID>ID then break;
end;
Result:=nil;
end;
(*
TLocalePreferences
*)
constructor TLocalePreferences.Create(Owner: TComponent);
begin
inherited Create(Owner);
LangId:=TLangId.Create;
LangPrefMatrix:=TLangPrefMatrix.Create(self);
LangPrefMatrix.SetSubComponent(true);
fAvailLanguageList:=TList.Create;
end;
constructor TLocalePreferences.CreateDefault;
var lst: TListWithID;
begin
Create(nil);
//англ. язык необходим
LangID.Add('English',9,1);
lst:=TListWithID.Create;
lst.ID:=1033;
lst.Add(Pointer(0)); //neutral/any на первом месте
lst.Add(Pointer(1033)); //след. - английский
LangPrefMatrix.Add(lst);
end;
destructor TLocalePreferences.Destroy;
begin
LangId.Free;
fAvailLanguageList.Free;
inherited Destroy;
end;
procedure TLocalePreferences.Loaded;
// var i: Integer;
begin
inherited Loaded;
fAvailLanguageList.Clear;
(*
for i:=0 to LangId.fStrings.Count-1 do
if (Cardinal(LangId.fStrings.Objects[i])<>0) and (LoadNewResourceModule(Cardinal(LangId.fStrings.Objects[i]))<>0) then
fAvailLanguageList.Add(LangId.fStrings.Objects[i]);
*)
if fCurLang=0 then
// LanguageID:=GetDefaultLanguageID;
Language:=GetDefaultLanguageInEnglish;
end;
procedure TLocalePreferences.SetLanguage(value: string);
begin
SetLanguageID(LangID.NameToID(value));
end;
procedure TLocalePreferences.SetLanguageID(value: Integer);
begin
ChangeLanguageID(value);
end;
function TLocalePreferences.GetResourceLang: string;
begin
Result:=LangID.IDToName(fResLang);
end;
procedure TLocalePreferences.SetResourceLang(value: string);
begin
fResLang:=LangID.NameToID(value);
end;
function TLocalePreferences.ChangeLanguage(value: string): Boolean;
begin
Result:=ChangeLanguageID(LangID.NameToID(value));
end;
function TLocalePreferences.ChangeLanguageID(value: integer): Boolean;
var i: Integer;
preflist: TListWithID;
begin
Result:=false;
if value<>fCurLang then begin
preflist:=LangPrefMatrix.GetPrefList(value);
if Assigned(preflist) then
for i:=0 to preflist.Count-1 do
if (Cardinal(preflist[i])<>0) and (LoadNewResourceModule(Cardinal(preflist[i]))<>0) then begin
fCurLang:=value;
ReinitializeForms;
Result:=true;
break;
end;
end;
end;
function TLocalePreferences.GetLanguage: string;
begin
Result:=LangID.IDToName(fCurLang);
end;
function TLocalePreferences.GetAppropriateLang(list: TListWithId): Integer;
var preflist: TListWithID;
i: Integer;
begin
//в list.ID лежит искомый язык, а в самом списке - варианты замены
preflist:=LangPrefMatrix.GetPrefList(list.ID);
if assigned(preflist) then begin
for i:=0 to preflist.Count-1 do begin
Result:=Integer(preflist[i]);
if list.IndexOf(Pointer(Result))>=0 then Exit;
end;
//если дошли до этого места, значит, списки list и preflist не пересеклись
//ну и хрен с ним - не будем гадать, лучше выругаемся
end;
raise Exception.CreateFmt('Didn''t find appropriate replacement for %s language',[LangId.IDToName(list.ID)]);
end;
function TLocalePreferences.TryGetMatchingString(ID: Integer;
strings: TStrings; out str: string): Boolean;
var preflist: TListWithID;
i,j: Integer;
begin
preflist:=LangPrefMatrix.GetPrefList(ID);
Result:=false;
if assigned(preflist) then
for i:=0 to preflist.Count-1 do begin
j:=strings.IndexOfObject(preflist[i]);
if j>=0 then begin
Result:=true;
str:=strings[j];
Exit;
end;
end;
end;
function TLocalePreferences.TrySetMatchingString(ID: Integer; strings: TStrings;
val: string): Boolean;
var preflist: TListWithID;
i,j: Integer;
begin
preflist:=LangPrefMatrix.GetPrefList(ID);
Result:=false;
if assigned(preflist) then
for i:=0 to preflist.Count-1 do begin
j:=strings.IndexOfObject(preflist[i]);
if j>=0 then begin
Result:=true;
strings[j]:=val;
Exit;
end;
end;
end;
function TLocalePreferences.GetLanguageList: TStringList;
var i: Integer;
begin
Result:=TStringList.Create;
for i:=0 to fAvailLanguageList.Count-1 do
Result.AddObject(GetLanguageNameInCurLocale(Integer(fAvailLanguageList[i])),
TObject(fAvailLanguageList[i]));
end;
(*
TLocalizedName
*)
constructor TLocalizedName.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
SetSubComponent(true);
fStrings:=TStringList.Create;
end;
constructor TLocalizedName.CreateEmptyNeutral(aOwner: TComponent=nil);
begin
Create(aOwner);
strings.AddObject('',nil);
end;
procedure TLocalizedName.MakeEmptyNeutral;
begin
strings.Clear;
strings.AddObject('',nil);
end;
destructor TLocalizedName.Destroy;
begin
fStrings.Free;
inherited Destroy;
end;
procedure TLocalizedName.DefineProperties(filer: TFiler);
begin
filer.DefineProperty('data',ReadData,WriteData,fStrings.Count>0);
end;
procedure TLocalizedName.ReadData(reader: TReader);
var p: TSimpleParser;
str: string;
begin
reader.ReadListBegin;
p:=TSimpleParser.Create;
while not reader.EndOfList do begin
p.AssignString(reader.ReadString);
str:=p.getString;
AddString(str,p.getString);
end;
p.Free;
reader.ReadListEnd;
end;
procedure TLocalizedName.WriteData(writer: TWriter);
var i: Integer;
begin
writer.WriteListBegin;
for i:=0 to fStrings.Count-1 do
writer.WriteString(Format('%s;%s',
[fStrings[i],LocalePreferences.LangID.IDToName(Integer(fstrings.Objects[i]))]));
writer.WriteListEnd;
end;
procedure TLocalizedName.AddString(str,langName: string);
begin
fStrings.AddObject(str,TObject(LocalePreferences.LangID.NameToId(langName)));
end;
procedure TLocalizedName.AddInCurrentLang(str: string);
begin
fstrings.AddObject(str,TObject(LocalePreferences.fCurLang));
end;
function TLocalizedName.TryMatchingString(Lang: TObject; out val: string): Boolean;
begin
Result:=localePreferences.TryGetMatchingString(Integer(Lang),fstrings,val);
end;
function TLocalizedName.MatchingString(Lang: TObject): string;
//var i: Integer;
begin
// i:=fstrings.IndexOfObject(Lang);
// Result:=fstrings[i];
if not TryMatchingString(Lang,Result) then
if fstrings.Count=0 then Raise Exception.Create('empty locale string') else
Raise Exception.CreateFMT('Couldn''t find string matching %s',[localePreferences.LangID.IDToName(Integer(Lang))]);
end;
function TLocalizedName.Caption: string;
begin
Result:=MatchingString(TObject(LocalePreferences.languageID));
end;
function TLocalizedName.TryCaption(out Caption: string): Boolean;
begin
Result:=TryMatchingString(TObject(LocalePreferences.languageID),Caption);
end;
function TLocalizedName.TryEnglish(out val: string): Boolean;
begin
Result:=TryMatchingString(TObject(1033),val);
end;
function TLocalizedName.InEnglish: string;
begin
Result:=MatchingString(Tobject(1033));
end;
function TLocalizedName.Enabled: Boolean;
begin
Result:=(fstrings.Count>0);
end;
function TLocalizedName.isNeutral(index: Integer): Boolean;
begin
Result:=Integer(fstrings.Objects[index])=0;
end;
procedure TLocalizedName.Assign(source: TPersistent);
var s: TLocalizedName absolute source;
begin
if source is TLocalizedName then begin
fstrings.Assign(s.fStrings);
end
else inherited Assign(source);
end;
procedure TLocalizedName.Clear;
begin
strings.Clear;
end;
procedure TLocalizedName.LeftConcat(source: TLocalizedName; chr: string='');
var i,j: Integer;
new_strings: TStringList;
begin //add source to the left of us, and we are main here
new_strings:=TStringList.Create;
for i:=0 to strings.Count-1 do
if isNeutral(i) then
for j:=0 to source.strings.Count-1 do
new_strings.AddObject(source.strings[j]+chr+strings[i],source.strings.Objects[j])
else begin
j:=source.strings.IndexOfObject(strings.Objects[i]);
if j>=0 then
new_strings.AddObject(source.strings[j]+chr+strings[i],strings.Objects[i])
else begin
j:=source.strings.IndexOfObject(nil);
if j>=0 then
new_strings.AddObject(source.strings[j]+chr+strings[i],strings.Objects[i]);
end;
end;
strings.Free;
fstrings:=new_strings;
end;
procedure TLocalizedName.RightConcat(source: TLocalizedName; chr: string='');
var i,j: Integer;
new_strings: TStringList;
begin //add source to the right of us, and we are main here
new_strings:=TStringList.Create;
for i:=0 to strings.Count-1 do
if isNeutral(i) then
for j:=0 to source.strings.Count-1 do
new_strings.AddObject(strings[i]+chr+source.strings[j],source.strings.Objects[j])
else begin
j:=source.strings.IndexOfObject(strings.Objects[i]);
if j>=0 then
new_strings.AddObject(strings[i]+chr+source.strings[j],strings.Objects[i])
else begin
j:=source.strings.IndexOfObject(nil);
if j>=0 then
new_strings.AddObject(strings[i]+chr+source.strings[j],strings.Objects[i]);
end;
end;
// if new_strings.Count=0 then
// Assert(fstrings.Count>0,'RightConcat yielded empty locale string');
// Raise Exception.CreateFmt('%s + %s yielded empty string',[strings.Text,source.strings.Text]);
strings.Free;
fstrings:=new_strings;
end;
procedure TLocalizedName.LeftConcat(str: string);
var i: Integer;
begin
for i:=0 to strings.Count-1 do
strings[i]:=str+strings[i];
end;
procedure TLocalizedName.RightConcat(str: string);
var i: Integer;
begin
for i:=0 to strings.Count-1 do
strings[i]:=strings[i]+str;
end;
procedure TLocalizedName.SetMatchingString(lang,value: string);
begin
if not localePreferences.TrySetMatchingString(localePreferences.LangID.NameToID(lang),strings,value) then
Raise Exception.CreateFMT('SetMatchingString: lang %s not found',[lang]);
end;
function TLocalizedName.GetMatchingString(lang: string): string;
begin
if not localePreferences.TryGetMatchingString(localePreferences.LangID.NameToID(lang),strings,Result) then
Raise Exception.CreateFmt('GetMatchingString: lang %s not found',[lang]);
end;
(*
General
*)
function LocaleCompareStr(s1,s2: string): Integer;
begin
Result:=CompareString(localePreferences.ResourceLangID, 0, PChar(S1), Length(S1),
PChar(S2), Length(S2)) - 2;
end;
function LocaleCompareText(s1,s2: string): Integer;
begin
Result:=CompareString(localePreferences.ResourceLangID, NORM_IGNORECASE, PChar(S1), Length(S1),
PChar(S2), Length(S2)) - 2;
end;
initialization
if FileExists(GetCurrentDir+'\data\Lang\LanguageSettings.txt') then
localePreferences:=TLocalePreferences.LoadFromFile(GetCurrentDir+'\data\Lang\LanguageSettings.txt')
else
localePreferences:=TLocalePreferences.CreateDefault;
finalization
FreeAndNil(localePreferences);
end.
|
unit FileSizeToStr_lib;
interface
function FileSizeToStr(size: Int64): string;
var WriteKiBasKB: boolean;
implementation
uses SysUtils;
const megabyteSize = 1024*1024;
gigabyteSize = 1024*1024*1024;
terabyteSize: Int64 = Int64(1024*1024*1024)*1024;
resourcestring
Bstr = 'B';
KiBstr = 'KiB';
MiBstr = 'MiB';
GiBstr = 'GiB';
TiBstr = 'TiB';
KBstr = 'KB';
MBstr = 'MB';
GBstr = 'GB';
TBstr = 'TB';
function FileSizeToStr(size: Int64): string;
begin
if size<1024 then Result:=Format('%d %s',[size,Bstr])
else if size<megabyteSize then
if WriteKiBasKB then
Result:=Format('%.3f %s',[size/1024,KBstr])
else
Result:=Format('%.3f %s',[size/1024,KiBstr])
else if size<gigabyteSize then
if WriteKiBasKB then
Result:=Format('%.3f %s',[size/megabyteSize,MBstr])
else
Result:=Format('%.3f %s',[size/megabyteSize,MiBstr])
else if size<terabyteSize then
if WriteKiBasKB then
Result:=Format('%.3f %s',[size/gigabyteSize,GBstr])
else
Result:=Format('%.3f %s',[size/gigabyteSize,GiBstr])
else
if WriteKiBasKB then
Result:=Format('%.3f %s',[size/terabyteSize,TBstr])
else
Result:=Format('%.3f %s',[size/terabyteSize,TBstr])
end;
end.
|
program Lab10_Var9;
function getdigit25(c :Char) :LongInt;
var w :LongInt;
begin
w := 0;
case c of
'0': w := 0;
'1': w := 1;
'2': w := 2;
'3': w := 3;
'4': w := 4;
'5': w := 5;
'6': w := 6;
'7': w := 7;
'8': w := 8;
'9': w := 9;
'A', 'a': w := 10;
'B', 'b': w := 11;
'C', 'c': w := 12;
'D', 'd': w := 13;
'E', 'e': w := 14;
'F', 'f': w := 15;
'G', 'g': w := 16;
'H', 'h': w := 17;
'I', 'i': w := 18;
'J', 'j': w := 19;
'K', 'k': w := 20;
'L', 'l': w := 21;
'M', 'm': w := 22;
'N', 'n': w := 23;
'O', 'o': w := 24;
else { Error }
w := -1;
end;
getdigit25 := w;
end;
function str25toint(var s :String) :LongInt;
var i, d :Integer; n :LongInt;
begin
n := 0;
for i := 1 to length(s) do
begin
d := getdigit25(s[i]);
if d < 0 then { Error }
begin
str25toint := -1;
exit;
end;
n := n*25 + d;
end;
str25toint := n;
end;
function validinput(var s :String) :Boolean;
var i, alphacount, len :Integer; d :LongInt;
begin
len := length(s);
alphacount := 0;
if (len < 4) or (len > 5) then
begin
validinput := false;
exit;
end;
for i := 1 to len do
begin
d := getdigit25(s[i]);
if d < 0 then { Error }
begin
validinput := false;
exit;
end;
if d >= 10 then
begin
alphacount := alphacount + 1;
end;
end;
validinput := (alphacount >= 2);
end;
var instr :String;
n :LongInt;
begin
write('Write your number (base of 25): ');
readln(instr);
if not validinput(instr) then
begin
writeln('Input is not valid!');
end
else
begin
n := str25toint(instr);
writeln('Decimal: ', n);
end;
end.
|
unit Ntapi.ntstatus;
{$MINENUMSIZE 4}
interface
const
NT_FACILITY_SHIFT = 16;
NT_FACILITY_MASK = $FFF;
FACILITY_NTWIN32 = $7;
ERROR_SEVERITY_SUCCESS = $00000000;
ERROR_SEVERITY_INFORMATIONAL = $40000000;
ERROR_SEVERITY_WARNING = $80000000;
ERROR_SEVERITY_ERROR = $C0000000;
// Success
STATUS_SUCCESS = $00000000;
STATUS_WAIT_0 = $00000000;
STATUS_ABANDONED = $00000080;
STATUS_TIMEOUT = $00000102;
STATUS_MORE_ENTRIES = $00000105;
STATUS_NOT_ALL_ASSIGNED = $00000106;
STATUS_SOME_NOT_MAPPED = $00000107;
// Information
STATUS_OBJECT_NAME_EXISTS = $40000000;
// Warning
STATUS_DATATYPE_MISALIGNMENT = $80000002;
STATUS_BREAKPOINT = $80000003;
STATUS_SINGLE_STEP = $80000004;
STATUS_BUFFER_OVERFLOW = $80000005;
STATUS_NO_MORE_ENTRIES = $8000001A;
// Error
STATUS_UNSUCCESSFUL = $C0000001;
STATUS_NOT_IMPLEMENTED = $C0000002;
STATUS_INVALID_INFO_CLASS = $C0000003;
STATUS_INFO_LENGTH_MISMATCH = $C0000004;
STATUS_INVALID_HANDLE = $C0000008;
STATUS_INVALID_CID = $C000000B;
STATUS_INVALID_PARAMETER = $C000000D;
STATUS_ACCESS_DENIED = $C0000022;
STATUS_BUFFER_TOO_SMALL = $C0000023;
STATUS_OBJECT_TYPE_MISMATCH = $C0000024;
STATUS_OBJECT_NAME_INVALID = $C0000033;
STATUS_OBJECT_NAME_NOT_FOUND = $C0000034;
STATUS_OBJECT_NAME_COLLISION = $C0000035;
STATUS_THREAD_IS_TERMINATING = $C000004B;
STATUS_INVALID_OWNER = $C000005A;
STATUS_INVALID_PRIMARY_GROUP = $C000005B;
STATUS_NO_IMPERSONATION_TOKEN = $C000005C;
STATUS_CANT_DISABLE_MANDATORY = $C000005D;
STATUS_NO_SUCH_LOGON_SESSION = $C000005F;
STATUS_NO_SUCH_PRIVILEGE = $C0000060;
STATUS_PRIVILEGE_NOT_HELD = $C0000061;
STATUS_NONE_MAPPED = $C0000073;
STATUS_INVALID_ACL = $C0000077;
STATUS_INVALID_SID = $C0000078;
STATUS_INVALID_SECURITY_DESCR = $C0000079;
STATUS_NO_TOKEN = $C000007C;
STATUS_BAD_IMPERSONATION_LEVEL = $C00000A5;
STATUS_BAD_TOKEN_TYPE = $C00000A8;
STATUS_NOT_SUPPORTED = $C00000BB;
STATUS_VARIABLE_NOT_FOUND = $C0000100;
STATUS_CONTROL_C_EXIT = $C000013A;
STATUS_NOT_SAME_OBJECT = $C00001AC;
STATUS_NOT_FOUND = $C0000225;
STATUS_CANT_ENABLE_DENY_ONLY = $C00002B3;
STATUS_ASSERTION_FAILURE = $C0000420;
STATUS_NOT_CAPABLE = $C0000429;
STATUS_IMPLEMENTATION_LIMIT = $C000042B;
STATUS_WOW_ASSERTION = $C0009898;
// Debug
DBG_EXCEPTION_HANDLED = $00010001;
DBG_CONTINUE = $00010002;
DBG_EXCEPTION_NOT_HANDLED = $80010001;
implementation
end.
|
unit ce_messages;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, ComCtrls,
lcltype, ce_widget, ActnList, Menus, clipbrd, AnchorDocking, TreeFilterEdit,
Buttons, ce_writableComponent, ce_common, ce_project, ce_synmemo,
ce_dlangutils, ce_interfaces, ce_observer;
type
(**
* the struct linked to a log message. allow to be filtered.
*)
PMessageData = ^TMessageData;
TMessageData = record
ctxt: TCEAppMessageCtxt;
data: Pointer;
end;
TCEMessagesOptions = class(TWritableLfmTextComponent)
private
fFastDisplay: boolean;
fMaxCount: Integer;
fAutoSelect: boolean;
fSingleClick: boolean;
fFont: TFont;
procedure setFont(aValue: TFont);
published
property fastDisplay: boolean read fFastDisplay write fFastDisplay;
property maxMessageCount: integer read fMaxCount write fMaxCount;
property autoSelect: boolean read fAutoSelect write fAutoSelect;
property singleMessageClick: boolean read fSingleClick write fSingleClick;
property font: TFont read fFont write setFont;
public
constructor Create(AOwner: TComponent); override;
destructor destroy; override;
procedure assign(Source: TPersistent); override;
procedure AssignTo(Dest: TPersistent); override;
end;
{ TCEMessagesWidget }
TCEMessagesWidget = class(TCEWidget, ICEEditableOptions, ICEMultiDocObserver, ICEProjectObserver, ICEMessagesDisplay)
btnClearCat: TBitBtn;
imgList: TImageList;
List: TTreeView;
selCtxt: TToolBar;
btnSelAll: TToolButton;
ToolButton1: TToolButton;
ToolButton10: TToolButton;
btnSelMisc: TToolButton;
ToolButton11: TToolButton;
ToolButton2: TToolButton;
btnSelEdit: TToolButton;
ToolButton4: TToolButton;
btnSelProj: TToolButton;
ToolButton8: TToolButton;
btnSelApp: TToolButton;
TreeFilterEdit1: TTreeFilterEdit;
procedure ListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
fActAutoSel: TAction;
fActClearAll: TAction;
fActClearCurCat: TAction;
fActSaveMsg: TAction;
fActCopyMsg: TAction;
fActSelAll: TAction;
fMaxMessCnt: Integer;
fProj: TCEProject;
fDoc: TCESynMemo;
fCtxt: TCEAppMessageCtxt;
fAutoSelect: boolean;
fSingleClick: boolean;
fastDisplay: boolean;
fOptions: TCEMessagesOptions;
fOptionsBackup: TCEMessagesOptions;
fBtns: array[TCEAppMessageCtxt] of TToolButton;
procedure filterMessages(aCtxt: TCEAppMessageCtxt);
procedure clearOutOfRangeMessg;
procedure actAutoSelExecute(Sender: TObject);
procedure actClearCurCatExecute(Sender: TObject);
procedure actClearAllExecute(Sender: TObject);
procedure actSaveMsgExecute(Sender: TObject);
procedure actCopyMsgExecute(Sender: TObject);
procedure actSelAllExecute(Sender: TObject);
procedure setMaxMessageCount(aValue: Integer);
procedure setAutoSelectCategory(aValue: boolean);
procedure setSingleMessageClick(aValue: boolean);
procedure listDeletion(Sender: TObject; Node: TTreeNode);
procedure selCtxtClick(Sender: TObject);
function iconIndex(aKind: TCEAppMessageKind): Integer;
procedure handleMessageClick(Sender: TObject);
//
procedure projNew(aProject: TCEProject);
procedure projClosing(aProject: TCEProject);
procedure projFocused(aProject: TCEProject);
procedure projChanged(aProject: TCEProject);
procedure projCompiling(aProject: TCEProject);
//
procedure docNew(aDoc: TCESynMemo);
procedure docClosing(aDoc: TCESynMemo);
procedure docFocused(aDoc: TCESynMemo);
procedure docChanged(aDoc: TCESynMemo);
//
function optionedWantCategory(): string;
function optionedWantEditorKind: TOptionEditorKind;
function optionedWantContainer: TPersistent;
procedure optionedEvent(anEvent: TOptionEditorEvent);
function optionedOptionsModified: boolean;
//
function singleServiceName: string;
procedure message(const aValue: string; aData: Pointer; aCtxt: TCEAppMessageCtxt; aKind: TCEAppMessageKind);
procedure clearbyContext(aCtxt: TCEAppMessageCtxt);
procedure clearbyData(aData: Pointer);
protected
procedure updateLoop; override;
//
function contextName: string; override;
function contextActionCount: integer; override;
function contextAction(index: integer): TAction; override;
//
property maxMessageCount: Integer read fMaxMessCnt write setMaxMessageCount;
property autoSelectCategory: boolean read fAutoSelect write setAutoSelectCategory;
property singleMessageClick: boolean read fSingleClick write setSingleMessageClick;
public
constructor create(aOwner: TComponent); override;
destructor destroy; override;
//
procedure scrollToBack;
end;
function guessMessageKind(const aMessg: string): TCEAppMessageKind;
function getLineFromMessage(const aMessage: string): TPoint;
function openFileFromDmdMessage(const aMessage: string): boolean;
implementation
{$R *.lfm}
const
optname = 'messages.txt';
{$REGION TCEMessagesOptions ----------------------------------------------------}
constructor TCEMessagesOptions.Create(AOwner: TComponent);
begin
inherited;
fFont := TFont.Create;
end;
destructor TCEMessagesOptions.destroy;
begin
fFont.Free;
inherited;
end;
procedure TCEMessagesOptions.setFont(aValue: TFont);
begin
fFont.Assign(aValue);
end;
procedure TCEMessagesOptions.assign(Source: TPersistent);
var
widg : TCEMessagesWidget;
opts : TCEMessagesOptions;
begin
if Source is TCEMessagesOptions then
begin
opts := TCEMessagesOptions(Source);
fFont.BeginUpdate;
fFont.Assign(opts.font);
fMaxCount := opts.fMaxCount;
fAutoSelect := opts.fAutoSelect;
fSingleClick := opts.fSingleClick;
fFastDisplay := opts.fFastDisplay;
fFont.EndUpdate;
end
else if Source is TCEMessagesWidget then
begin
widg := TCEMessagesWidget(Source);
fFont.Assign(widg.List.Font);
fMaxCount := widg.fMaxMessCnt;
fAutoSelect := widg.fAutoSelect;
fSingleClick := widg.fSingleClick;
fFastDisplay := widg.fastDisplay;
end
else inherited;
end;
procedure TCEMessagesOptions.AssignTo(Dest: TPersistent);
var
widg : TCEMessagesWidget;
begin
if Dest is TCEMessagesWidget then
begin
widg := TCEMessagesWidget(Dest);
widg.List.Font.Assign(fFont);
widg.maxMessageCount := fMaxCount;
widg.autoSelectCategory := fAutoSelect;
widg.singleMessageClick := fSingleClick;
widg.fastDisplay:= fFastDisplay;
end
else inherited;
end;
{$ENDREGION}
{$REGION Standard Comp/Obj------------------------------------------------------}
constructor TCEMessagesWidget.create(aOwner: TComponent);
var
fname: string;
png: TPortableNetworkGraphic;
begin
fMaxMessCnt := 500;
fCtxt := amcAll;
//
fActAutoSel := TAction.Create(self);
fActAutoSel.Caption := 'Auto select message category';
fActAutoSel.AutoCheck := true;
fActAutoSel.OnExecute := @actAutoSelExecute;
fActClearAll := TAction.Create(self);
fActClearAll.OnExecute := @actClearAllExecute;
fActClearAll.caption := 'Clear all messages';
fActClearCurCat := TAction.Create(self);
fActClearCurCat.OnExecute := @actClearCurCatExecute;
fActClearCurCat.caption := 'Clear filtered messages';
fActCopyMsg := TAction.Create(self);
fActCopyMsg.OnExecute := @actCopyMsgExecute;
fActCopyMsg.Caption := 'Copy message(s)';
fActSelAll := TAction.Create(self);
fActSelAll.OnExecute := @actSelAllExecute;
fActSelAll.Caption := 'Select all';
fActSaveMsg := TAction.Create(self);
fActSaveMsg.OnExecute := @actSaveMsgExecute;
fActSaveMsg.caption := 'Save selected message(s) to...';
//
inherited;
//
updaterByLoopInterval := 12;
fOptions := TCEMessagesOptions.Create(Self);
fOptions.assign(self);
fOptions.Name:= 'messageOptions';
fOptionsBackup := TCEMessagesOptions.Create(Self);
//
List.PopupMenu := contextMenu;
List.OnDeletion := @ListDeletion;
List.OnDblClick := @handleMessageClick;
//
btnSelProj.OnClick := @selCtxtClick;
btnSelMisc.OnClick := @selCtxtClick;
btnSelEdit.OnClick := @selCtxtClick;
btnSelApp.OnClick := @selCtxtClick;
btnSelAll.OnClick := @selCtxtClick;
fBtns[amcAll] := btnSelAll;
fBtns[amcApp] := btnSelApp;
fBtns[amcEdit]:= btnSelEdit;
fBtns[amcMisc]:= btnSelMisc;
fBtns[amcProj]:= btnSelProj;
//
btnClearCat.OnClick := @actClearCurCatExecute;
png:= TPortableNetworkGraphic.Create;
try
png.LoadFromLazarusResource('clean');
btnClearCat.Glyph.Assign(png);
finally
png.free;
end;
//
fname := getCoeditDocPath + optname;
if fileExists(fname) then
begin
fOptions.loadFromFile(fname);
fOptions.AssignTo(self);
end;
//
EntitiesConnector.addObserver(self);
EntitiesConnector.addSingleService(self);
end;
destructor TCEMessagesWidget.destroy;
begin
fOptions.saveToFile(getCoeditDocPath + optname);
EntitiesConnector.removeObserver(self);
Inherited;
end;
procedure TCEMessagesWidget.listDeletion(Sender: TObject; Node: TTreeNode);
begin
if node.Data <> nil then
Dispose(PMessageData(Node.Data));
end;
procedure TCEMessagesWidget.ListKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
i: Integer;
begin
case Key of
VK_BACK, VK_DELETE:
begin
if List.SelectionCount > 0 then
begin
for i := List.Items.Count-1 downto 0 do
if List.Items[i].MultiSelected then
List.Items.Delete(List.Items[i]);
end
else clearbyContext(amcAll);
end;
VK_UP, VK_DOWN:
if fOptions.singleMessageClick then handleMessageClick(nil);
VK_RETURN:
handleMessageClick(nil);
end;
end;
procedure TCEMessagesWidget.selCtxtClick(Sender: TObject);
var
btn: TToolButton;
i: Integer;
begin
if sender = nil then
exit;
//
fCtxt := amcAll;
btn := TToolButton(Sender);
for i := 0 to selCtxt.ButtonCount-1 do
selCtxt.Buttons[i].Down := selCtxt.Buttons[i] = btn;
if btn = btnSelAll then
fCtxt := amcAll
else if btn = btnSelEdit then
fCtxt := amcEdit
else if btn = btnSelProj then
fCtxt := amcProj
else if btn = btnSelApp then
fCtxt := amcApp
else if btn = btnSelMisc then
fCtxt := amcMisc;
filterMessages(fCtxt);
end;
procedure TCEMessagesWidget.setMaxMessageCount(aValue: Integer);
begin
if aValue < 5 then
aValue := 5;
if fMaxMessCnt = aValue then
exit;
fMaxMessCnt := aValue;
clearOutOfRangeMessg;
end;
procedure TCEMessagesWidget.setAutoSelectCategory(aValue: boolean);
begin
fAutoSelect := aValue;
fActAutoSel.Checked:= fAutoSelect;
end;
procedure TCEMessagesWidget.setSingleMessageClick(aValue: boolean);
begin
fSingleClick := aValue;
if fSingleClick then
begin
List.OnClick := @handleMessageClick;
List.OnDblClick:= nil;
end else begin
List.OnClick := nil;
List.OnDblClick:= @handleMessageClick;
end;
end;
{$ENDREGION}
{$REGION ICEEditableOptions ----------------------------------------------------}
function TCEMessagesWidget.optionedWantCategory(): string;
begin
exit('Messages');
end;
function TCEMessagesWidget.optionedWantEditorKind: TOptionEditorKind;
begin
exit(oekGeneric);
end;
function TCEMessagesWidget.optionedWantContainer: TPersistent;
begin
fOptions.assign(self);
fOptionsBackup.assign(self);
exit(fOptions);
end;
procedure TCEMessagesWidget.optionedEvent(anEvent: TOptionEditorEvent);
begin
case anEvent of
oeeAccept, oeeSelectCat:
fOptionsBackup.assign(fOptions);
oeeCancel:
fOptions.assign(fOptionsBackup);
end;
fOptions.AssignTo(self);
end;
function TCEMessagesWidget.optionedOptionsModified: boolean;
begin
exit(false);
end;
{$ENDREGION}
{$REGION ICEContextualActions---------------------------------------------------}
function TCEMessagesWidget.contextName: string;
begin
result := 'Messages';
end;
function TCEMessagesWidget.contextActionCount: integer;
begin
result := 6;
end;
function TCEMessagesWidget.contextAction(index: integer): TAction;
begin
case index of
0: result := fActAutoSel;
1: result := fActClearAll;
2: result := fActClearCurCat;
3: result := fActCopyMsg;
4: result := fActSelAll;
5: result := fActSaveMsg;
else result := nil;
end;
end;
procedure TCEMessagesWidget.actAutoSelExecute(Sender: TObject);
begin
fAutoSelect := fActAutoSel.Checked;
end;
procedure TCEMessagesWidget.actClearAllExecute(Sender: TObject);
begin
clearbyContext(amcAll);
end;
procedure TCEMessagesWidget.actClearCurCatExecute(Sender: TObject);
begin
case fCtxt of
amcAll, amcApp, amcMisc :
clearbyContext(fCtxt);
amcEdit: if fDoc <> nil then
clearbyData(fDoc);
amcProj: if fProj <> nil then
clearbyData(fProj);
end;
end;
procedure TCEMessagesWidget.actCopyMsgExecute(Sender: TObject);
var
i: Integer;
str: string;
begin
str := '';
for i := 0 to List.Items.Count-1 do
if List.Items[i].MultiSelected then
str += List.Items[i].Text + LineEnding;
Clipboard.AsText := str;
end;
procedure TCEMessagesWidget.actSelAllExecute(Sender: TObject);
var
i: Integer;
begin
for i := 0 to List.Items.Count-1 do
if List.Items[i].Visible then
List.Items[i].MultiSelected := true;
end;
procedure TCEMessagesWidget.actSaveMsgExecute(Sender: TObject);
var
lst: TStringList;
itm: TtreeNode;
begin
with TSaveDialog.Create(nil) do
try
if execute then
begin
lst := TStringList.Create;
try
for itm in List.Items do
lst.Add(itm.Text);
lst.SaveToFile(filename);
finally
lst.Free;
end;
end;
finally
free;
end;
end;
{$ENDREGION}
{$REGION ICEProjectObserver ----------------------------------------------------}
procedure TCEMessagesWidget.projNew(aProject: TCEProject);
begin
fProj := aProject;
filterMessages(fCtxt);
end;
procedure TCEMessagesWidget.projClosing(aProject: TCEProject);
begin
if fProj <> aProject then
exit;
//
clearbyData(aProject);
fProj := nil;
filterMessages(fCtxt);
end;
procedure TCEMessagesWidget.projFocused(aProject: TCEProject);
begin
if fProj = aProject then exit;
fProj := aProject;
filterMessages(fCtxt);
end;
procedure TCEMessagesWidget.projChanged(aProject: TCEProject);
begin
end;
procedure TCEMessagesWidget.projCompiling(aProject: TCEProject);
begin
end;
{$ENDREGION}
{$REGION ICEMultiDocObserver ---------------------------------------------------}
procedure TCEMessagesWidget.docNew(aDoc: TCESynMemo);
begin
fDoc := aDoc;
filterMessages(fCtxt);
end;
procedure TCEMessagesWidget.docClosing(aDoc: TCESynMemo);
begin
if aDoc <> fDoc then exit;
clearbyData(fDoc);
fDoc := nil;
filterMessages(fCtxt);
end;
procedure TCEMessagesWidget.docFocused(aDoc: TCESynMemo);
begin
if fDoc = aDoc then exit;
fDoc := aDoc;
filterMessages(fCtxt);
end;
procedure TCEMessagesWidget.docChanged(aDoc: TCESynMemo);
begin
fDoc := aDoc;
end;
{$ENDREGION}
{$REGION ICEMessagesDisplay ----------------------------------------------------}
function TCEMessagesWidget.singleServiceName: string;
begin
exit('ICEMessagesDisplay');
end;
procedure TCEMessagesWidget.message(const aValue: string; aData: Pointer;
aCtxt: TCEAppMessageCtxt; aKind: TCEAppMessageKind);
var
dt: PMessageData;
item: TTreeNode;
begin
showWidget;
if aKind = amkAuto then
aKind := guessMessageKind(aValue);
dt := new(PMessageData);
dt^.data := aData;
dt^.ctxt := aCtxt;
if fAutoSelect then if fCtxt <> aCtxt then
fBtns[aCtxt].Click;
if fastDisplay then
IncLoopUpdate;
item := List.Items.Add(nil, aValue);
item.Data := dt;
item.ImageIndex := iconIndex(aKind);
item.SelectedIndex := item.ImageIndex;
if not fastDisplay then
begin
//TODO-cfeature: reset horz scroll bar to the left
clearOutOfRangeMessg;
scrollToBack;
Application.ProcessMessages;
filterMessages(fCtxt);
end;
end;
procedure TCEMessagesWidget.clearByContext(aCtxt: TCEAppMessageCtxt);
var
i: Integer;
msgdt: PMessageData;
begin
list.BeginUpdate;
if aCtxt = amcAll then
List.Items.Clear
else for i := List.Items.Count-1 downto 0 do
begin
msgdt := PMessageData(List.Items[i].Data);
if msgdt^.ctxt = aCtxt then
List.Items.Delete(List.Items[i]);
end;
list.EndUpdate;
end;
procedure TCEMessagesWidget.clearByData(aData: Pointer);
var
i: Integer;
msgdt: PMessageData;
begin
if aData = nil then
exit;
list.BeginUpdate;
for i := List.Items.Count-1 downto 0 do
begin
msgdt := PMessageData(List.Items[i].Data);
if (msgdt^.data = aData) then
List.Items.Delete(List.Items[i]);
end;
list.EndUpdate;
end;
{$ENDREGION}
{$REGION Messages --------------------------------------------------------------}
procedure TCEMessagesWidget.updateLoop;
begin
clearOutOfRangeMessg;
scrollToBack;
Application.ProcessMessages;
filterMessages(fCtxt);
end;
function TCEMessagesWidget.iconIndex(aKind: TCEAppMessageKind): Integer;
begin
case aKind of
amkBub: exit(0);
amkInf: exit(1);
amkHint: exit(2);
amkWarn: exit(3);
amkErr: exit(4);
else exit(0);
end;
end;
procedure TCEMessagesWidget.clearOutOfRangeMessg;
begin
list.BeginUpdate;
while List.Items.Count > fMaxMessCnt do
List.Items.Delete(List.Items.GetFirstNode);
list.EndUpdate;
end;
procedure TCEMessagesWidget.scrollToBack;
begin
if not Visible then
exit;
if List.BottomItem <> nil then
List.BottomItem.MakeVisible;
end;
procedure TCEMessagesWidget.handleMessageClick(Sender: TObject);
var
pos: TPoint;
msg: string;
begin
if List.Selected = nil then
exit;
msg := List.Selected.Text;
if not openFileFromDmdMessage(msg) then
exit;
// from here, since a doc has the focus, List.Selected is nil
pos := getLineFromMessage(msg);
if fDoc = nil then
exit;
fDoc.CaretXY := pos;
fDoc.SelectLine;
end;
procedure TCEMessagesWidget.filterMessages(aCtxt: TCEAppMessageCtxt);
var
msgdt: PMessageData;
itm: TTreeNode;
i: Integer;
begin
if updating then
exit;
List.BeginUpdate;
for i := 0 to List.Items.Count-1 do
begin
itm := List.Items[i];
Itm.Visible := false;
Itm.Selected := false;
msgdt := PMessageData(itm.Data);
if aCtxt = amcAll then
Itm.Visible := true
else case msgdt^.ctxt of
amcEdit: itm.Visible := (fDoc = TCESynMemo(msgdt^.data)) and (aCtxt = amcEdit);
amcProj: itm.Visible := (fProj = TCEProject(msgdt^.data)) and (aCtxt = amcProj);
amcApp: itm.Visible := aCtxt = amcApp;
amcMisc: itm.Visible := aCtxt = amcMisc;
end;
end;
list.EndUpdate;
end;
function guessMessageKind(const aMessg: string): TCEAppMessageKind;
var
pos: Integer;
idt: string;
function checkIdent: TCEAppMessageKind;
begin
case idt of
'ERROR', 'error', 'Error', 'Invalid', 'invalid',
'exception', 'Exception', 'illegal', 'Illegal',
'fatal', 'Fatal', 'Critical', 'critical':
exit(amkErr);
'Warning', 'warning', 'caution', 'Caution', 'warn', 'Warn':
exit(amkWarn);
'Hint', 'hint', 'Tip', 'tip', 'advice', 'Advice',
'suggestion', 'Suggestion':
exit(amkHint);
'Information', 'information':
exit(amkInf);
else
exit(amkBub);
end;
end;
begin
idt := '';
pos := 1;
result := amkBub;
while(true) do
begin
if pos > length(aMessg) then
exit;
if aMessg[pos] in [#0..#32, ',', ':', ';'] then
begin
Inc(pos);
result := checkIdent;
if result <> amkBub then
exit;
idt := '';
continue;
end;
if not (aMessg[pos] in ['a'..'z', 'A'..'Z']) then
begin
Inc(pos);
result := checkIdent;
if result <> amkBub then exit;
idt := '';
continue;
end;
idt += aMessg[pos];
Inc(pos);
end;
end;
function getLineFromMessage(const aMessage: string): TPoint;
var
i, j: Integer;
ident: string;
begin
result.x := 0;
result.y := 0;
ident := '';
i := 1;
while (true) do
begin
if i > length(aMessage) then exit;
if aMessage[i] = '(' then
begin
inc(i);
if i > length(aMessage) then exit;
while( isNumber(aMessage[i]) or (aMessage[i] = ',') or (aMessage[i] = ':')) do
begin
ident += aMessage[i];
inc(i);
if i > length(aMessage) then exit;
end;
if aMessage[i] = ')' then
begin
j := Pos(',', ident);
if j = 0 then j := Pos(':', ident);
if j = 0 then
result.y := strToIntDef(ident, -1)
else
begin
result.y := strToIntDef(ident[1..j-1], -1);
result.x := strToIntDef(ident[j+1..length(ident)], -1);
end;
exit;
end;
end;
inc(i);
end;
end;
function openFileFromDmdMessage(const aMessage: string): boolean;
var
i: Integer;
ident: string;
ext: string;
begin
ident := '';
i := 0;
result := false;
while(true) do
begin
inc(i);
if i > length(aMessage) then
exit;
if (aMessage[i] = '(') or (aMessage[i..i+5] = '-mixin') then
begin
if not fileExists(ident) then
exit;
ext := extractFileExt(ident);
if dExtList.IndexOf(ext) = -1 then
exit;
getMultiDocHandler.openDocument(ident);
result := true;
end
else if aMessage[i] = '@' then
ident := ''
else
ident += aMessage[i];
end;
end;
{$ENDREGION}
end.
|
(**************************************************)
(* *)
(* 本单元用于歌曲列表存储操作 *)
(* *)
(* Copyright (c) 2019 *)
(* 南烛 *)
(* *)
(**************************************************)
unit Data;
interface
uses
superobject, System.SysUtils, System.Classes, Vcl.Controls, NxControls6,
NxVirtualGrid6, NxGrid6, dxmdaset, InfoFromID;
type
IO_List = class
private
const
INIT_Str = '{"customlist":[],"playlist":[]}';
public
procedure Create_Json; // 初始化创建JSON配置文件
function Open_Json: string; // 打开JSON配置文件
procedure AddSongs(ListName: string; Music_Info: array of string); // 向列表写入歌曲信息
procedure DelSongs(ListName, SongID: string); // 删除列表歌曲信息
end;
type
LD_List = class(TThread)
private
var
Filed_ID, Song_Name, Song_Album, Song_Singer, Song_Time, Song_Img, Song_Url, Song_ID, Song_From, Song_Count: string;
public
var
NG_S: TNextGrid6;
MEM_S: TdxMemData;
LM: string;
constructor Create(ListName: string; NG: TNextGrid6; MEM: TdxMemData); overload; // 构造函数
protected
procedure Add_To; // 显示歌曲到到列表
procedure Execute; override;
end;
implementation
uses
Main, List,Start;
{ IO_List }
// 向列表写入歌曲信息 <Done>
procedure IO_List.AddSongs(ListName: string; Music_Info: array of string);
var
jo: ISuperObject;
sm: TStringStream;
Add_Str: string;
begin
sm := TStringStream.Create('', tencoding.UTF8);
jo := so(Open_Json);
Add_Str := '{"from":"' + Music_Info[0] + '","name":"' + Music_Info[1] + '","album":"' + Music_Info[2] + '","singer":"' + Music_Info[3] + '","time":"' + Music_Info[4] + '","img":"' + Music_Info[5] + '","id":"' + Music_Info[6] + '","singerid":"' + Music_Info[7] + '","albumid":"' + Music_Info[8] + '","mvid":"' + Music_Info[9] + '"}';
jo.A[ListName].Add(so(Add_Str));
jo.SaveTo(sm);
sm.SaveToFile(ExtractFileDir(ParamStr(0)) + '\Data.json');
end;
// 初始化创建JSON配置文件,在文件不存在的情况下创建 <Done>
procedure IO_List.Create_Json;
var
path: string;
sm: TStringStream;
begin
path := ExtractFileDir(ParamStr(0));
sm := TStringStream.Create(INIT_Str, tencoding.UTF8);
sm.SaveToFile(path + '\Data.json');
FreeAndNil(sm);
end;
// 删除本地歌曲列表歌曲 <Done>
procedure IO_List.DelSongs(ListName, SongID: string);
var
jo, item: ISuperObject;
ja: TSuperArray;
sm: TStringStream;
FIleName: string;
no: Word;
begin
FIleName := ExtractFileDir(ParamStr(0)) + '\Data.json';
if not FileExists(FIleName) then
begin
// 提示
end
else
begin
no := 0;
sm := TStringStream.Create('', tencoding.UTF8);
jo := so(Open_Json);
ja := jo.A[ListName];
for item in jo[ListName] do
begin
if jo[ListName + '[' + inttostr(no) + '].id'].AsString = SongID then
begin
ja.Delete(no);
Break;
end;
Inc(no);
end;
jo.SaveTo(sm);
sm.SaveToFile(ExtractFileDir(ParamStr(0)) + '\Data.json');
end;
end;
// 打开JSON配置文件,在文件不存在的情况下先创建 <Done>
function IO_List.Open_Json: string;
var
sm: TStringStream;
FIleName: string;
begin
FIleName := ExtractFileDir(ParamStr(0)) + '\Data.json';
if not FileExists(FIleName) then // 如果文件不存在,那么创建一个
begin
Create_Json; // 如果不存在,那么先创建
end;
sm := TStringStream.Create('', tencoding.UTF8);
sm.LoadFromFile(ExtractFileDir(ParamStr(0)) + '\Data.json');
result := sm.DataString;
end;
{ LD_List }
// 程序启动时载入列表线程
procedure LD_List.Add_To;
begin
with MEM_S do
begin
Open;
Append;
FieldByName('S_ID').AsString := Filed_ID; // 序号
FieldByName('S_Name').AsString := Song_Name; // 歌名
FieldByName('S_Album').AsString := Song_Album; // 专辑
FieldByName('S_Singer').AsString := Song_Singer; // 歌手
FieldByName('S_Time').AsString := Song_Time; // 时长
FieldByName('S_From').AsString := Song_From; // 来源
FieldByName('S_Url').AsString := Song_Url; // 下载地址
FieldByName('S_Img').AsString := Song_Img; // 图片地址
FieldByName('S_MusicId').AsString := Song_ID; // 歌曲ID
Post;
end;
with NG_S.AddRow.Cells do
begin
item[1].AsString := Filed_ID;
item[2].AsString := Song_Name;
item[3].AsString := Song_Album;
item[4].AsString := Song_Singer;
item[5].AsString := Song_Time;
item[6].AsString := Song_From;
item[7].AsString := Song_Url;
item[8].AsString := Song_Img;
item[9].AsString := Song_ID;
// Item[10].AsString := SongList[i].ChildNodes['SingerID'].Text;
// Item[10].AsString := SongList[i].ChildNodes['AlbumID'].Text;
// Item[10].AsString := SongList[i].ChildNodes['MVID'].Text;
end;
Fm_Main.BTN_PlayList.Caption := Song_Count;
Fm_List.SB_List.Max := StrToInt(Song_Count);
end;
constructor LD_List.Create(ListName: string; NG: TNextGrid6; MEM: TdxMemData);
begin
NG_S := NG;
MEM_S := MEM;
LM := ListName;
inherited Create(True);
end;
procedure LD_List.Execute;
var
FIleName: string;
IO: IO_List;
jo, item: ISuperObject;
Num: Word;
GT: GetFromId;
begin
FreeOnTerminate := True;
OnTerminate := Fm_Main.Search_Over;
FIleName := ExtractFileDir(ParamStr(0)) + '\Data.json';
if FileExists(FIleName) then // 如果文件存在,那么执行读取
begin
Num := 0;
IO := IO_List.Create;
jo := so(IO.Open_Json);
MEM_S.Open;
MEM_S.First;
for item in jo[LM] do
begin
GT := GetFromId.Create;
GT.ID := jo[LM + '[' + inttostr(Num) + '].id'].AsString;
case StrToInt(jo[LM + '[' + inttostr(Num) + '].from'].AsString) of
1: // QQ音乐
begin
Song_Url := GT.GetFromId_QQ;
end;
2: // 网易音乐
begin
Song_Url := GT.GetFromId_WangYi;
end;
3: // 酷我音乐
begin
Song_Url := GT.GetFromId_Kuwo;
end;
4: // 酷狗音乐
begin
Song_Url := GT.GetFromId_KuGou;
end;
end;
GT.Free;
Filed_ID := inttostr(Num + 1);
Song_Name := jo[LM + '[' + inttostr(Num) + '].name'].AsString;
Song_Album := jo[LM + '[' + inttostr(Num) + '].album'].AsString;
Song_Singer := jo[LM + '[' + inttostr(Num) + '].singer'].AsString;
Song_Time := jo[LM + '[' + inttostr(Num) + '].time'].AsString;
Song_Img := jo[LM + '[' + inttostr(Num) + '].img'].AsString;
Song_ID := jo[LM + '[' + inttostr(Num) + '].id'].AsString;
Song_From := jo[LM + '[' + inttostr(Num) + '].from'].AsString;
Song_Count := inttostr(Num + 1);
Synchronize(Add_To);
Inc(Num);
Fm_Start.LB_Satate.Caption := '正在载入播放列表<'+inttostr(Num)+'>……';
end;
IO.Free;
end;
end;
end.
|
unit uibutton;
interface
uses ui, uimpl, uihandle, uicomp;
type
TWinButton=class(TWinComp)
private
protected
public
constructor Create(Owner:TWinHandle);override;
procedure CustomPaint;override;
procedure MouseMovePerform(AButtonControl:cardinal; x,y:integer);override;
procedure MouseLeavePerform;override;
procedure MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override;
procedure MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override;
end;
implementation
constructor TWinButton.Create(Owner:TWinHandle);
begin
inherited Create(Owner);
wFont:=fntBold;
wColor:=clWhite;
wBkColor:=clFaceBook1;
wBorderColor:=clFaceBook1;
wHoverColor:=clWhite;
wHoverBkColor:=clFaceBook1;
wHoverBorderColor:=clWhite;
end;
procedure TWinButton.CustomPaint;
var r:trect;
begin
r:=GetClientRect;
BeginPaint;
Polygon(ifthen(wMouseOverComponent, HoverBorderColor, BorderColor),
ifthen(wMouseOverComponent, ifthen(wMouseDown, clFaceBook2, HoverBkColor), BkColor),
r.Left, r.Top, r.Right-1, r.Bottom-1);
DrawText(r, text, font,
ifthen(wMouseOverComponent, HoverColor, Color), 0,
TRANSPARENT, DT_SINGLELINE or DT_CENTER or DT_VCENTER);
EndPaint;
end;
procedure TWinButton.MouseMovePerform(AButtonControl:cardinal; x,y:integer);
begin
inherited;
// Text:=inttostr(x)+':'+inttostr(y);
//RedrawPerform;
end;
procedure TWinButton.MouseLeavePerform;
begin
inherited;
// Text:='X';
// RedrawPerform;
end;
procedure TWinButton.MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);
begin
inherited;
RedrawPerform;
end;
procedure TWinButton.MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);
begin
inherited;
RedrawPerform;
end;
end.
|
unit nscContextFilterRes;
{* Ресурсы для TnscContextFilter }
// Модуль: "w:\common\components\gui\Garant\Nemesis\nscContextFilterRes.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "nscContextFilterRes" MUID: (4B97E1EA011F)
{$Include w:\common\components\gui\Garant\Nemesis\nscDefine.inc}
interface
{$If Defined(Nemesis)}
uses
l3IntfUses
, l3StringIDEx
;
const
{* Локализуемые строки ContextFilterMessages }
str_nsc_LabelCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_LabelCaption'; rValue : 'Контекстный фильтр');
{* 'Контекстный фильтр' }
str_nsc_ContextEmptyMessage: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_ContextEmptyMessage'; rValue : 'Введите слова для поиска и фильтрации');
{* 'Введите слова для поиска и фильтрации' }
str_nsc_ButtonActiveHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_ButtonActiveHint'; rValue : 'Выключить контекстный фильтр');
{* 'Выключить контекстный фильтр' }
str_nsc_ButtonInActiveHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_ButtonInActiveHint'; rValue : 'Включить контекстный фильтр');
{* 'Включить контекстный фильтр' }
{$IfEnd} // Defined(Nemesis)
implementation
{$If Defined(Nemesis)}
uses
l3ImplUses
//#UC START# *4B97E1EA011Fimpl_uses*
//#UC END# *4B97E1EA011Fimpl_uses*
;
initialization
str_nsc_LabelCaption.Init;
{* Инициализация str_nsc_LabelCaption }
str_nsc_ContextEmptyMessage.Init;
{* Инициализация str_nsc_ContextEmptyMessage }
str_nsc_ButtonActiveHint.Init;
{* Инициализация str_nsc_ButtonActiveHint }
str_nsc_ButtonInActiveHint.Init;
{* Инициализация str_nsc_ButtonInActiveHint }
{$IfEnd} // Defined(Nemesis)
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpAsn1OctetString;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
SysUtils,
ClpCryptoLibTypes,
ClpArrayUtils,
ClpAsn1Object,
ClpIProxiedInterface,
ClpIAsn1OctetString,
ClpIAsn1TaggedObject,
ClpAsn1Encodable,
ClpAsn1Sequence,
ClpHex,
ClpIDerOctetString,
ClpIAsn1OctetStringParser;
resourcestring
SIllegalObject = 'Illegal Object in GetInstance: %s, "obj"';
SStrNil = '"Str" Cannot be Nil';
SProcessingError = 'Error Processing Object : "%s"';
type
TAsn1OctetString = class abstract(TAsn1Object, IAsn1OctetString,
IAsn1OctetStringParser)
strict private
var
FStr: TCryptoLibByteArray;
function GetStr: TCryptoLibByteArray; inline;
function GetParser: IAsn1OctetStringParser; inline;
strict protected
function Asn1GetHashCode(): Int32; override;
function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override;
public
property Str: TCryptoLibByteArray read GetStr;
property Parser: IAsn1OctetStringParser read GetParser;
/// <summary>
/// return an Octet string from a tagged object.
/// </summary>
/// <param name="obj">
/// the tagged object holding the object we want.
/// </param>
/// <param name="isExplicit">
/// explicitly true if the object is meant to be explicitly tagged false
/// otherwise.
/// </param>
/// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException">
/// if the tagged object cannot be converted.
/// </exception>
class function GetInstance(const obj: IAsn1TaggedObject;
isExplicit: Boolean): IAsn1OctetString; overload; static;
/// <summary>
/// return an Octet string from the given object.
/// </summary>
/// <param name="obj">
/// the object we want converted.
/// </param>
/// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException">
/// if the object cannot be converted.
/// </exception>
class function GetInstance(const obj: TObject): IAsn1OctetString;
overload; static;
/// <param name="Str">
/// the octets making up the octet string.
/// </param>
constructor Create(const Str: TCryptoLibByteArray); overload;
constructor Create(const obj: IAsn1Encodable); overload;
function GetOctetStream(): TStream;
function GetOctets(): TCryptoLibByteArray; virtual;
function ToString(): String; override;
end;
implementation
uses
ClpBerOctetString; // included here to avoid circular dependency :)
{ TAsn1OctetString }
function TAsn1OctetString.GetStr: TCryptoLibByteArray;
begin
result := FStr;
end;
function TAsn1OctetString.GetParser: IAsn1OctetStringParser;
begin
result := Self as IAsn1OctetStringParser;
end;
constructor TAsn1OctetString.Create(const Str: TCryptoLibByteArray);
begin
Inherited Create();
if (Str = Nil) then
begin
raise EArgumentNilCryptoLibException.CreateRes(@SStrNil);
end;
FStr := Str;
end;
function TAsn1OctetString.Asn1Equals(const asn1Object: IAsn1Object): Boolean;
var
other: IDerOctetString;
begin
if (not Supports(asn1Object, IDerOctetString, other)) then
begin
result := false;
Exit;
end;
result := TArrayUtils.AreEqual(GetOctets(), other.GetOctets());
end;
function TAsn1OctetString.Asn1GetHashCode: Int32;
begin
result := TArrayUtils.GetArrayHashCode(GetOctets());
end;
constructor TAsn1OctetString.Create(const obj: IAsn1Encodable);
begin
Inherited Create();
try
FStr := obj.GetEncoded(TAsn1Encodable.Der);
except
on e: EIOCryptoLibException do
begin
raise EArgumentCryptoLibException.CreateResFmt(@SProcessingError,
[e.Message]);
end;
end;
end;
class function TAsn1OctetString.GetInstance(const obj: IAsn1TaggedObject;
isExplicit: Boolean): IAsn1OctetString;
var
o: IAsn1Object;
begin
o := obj.GetObject();
if ((isExplicit) or (Supports(o, IAsn1OctetString))) then
begin
result := GetInstance(o as TAsn1Object);
Exit;
end;
result := TBerOctetString.FromSequence
(TAsn1Sequence.GetInstance(o as TAsn1Object));
end;
class function TAsn1OctetString.GetInstance(const obj: TObject)
: IAsn1OctetString;
var
asn1TaggedObject: IAsn1TaggedObject;
begin
if ((obj = Nil) or (obj is TAsn1OctetString)) then
begin
result := obj as TAsn1OctetString;
Exit;
end;
// TODO: this needs to be deleted in V2
if Supports(obj, IAsn1TaggedObject, asn1TaggedObject) then
begin
result := GetInstance(asn1TaggedObject.GetObject() as TAsn1Object);
Exit;
end;
raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject,
[obj.ClassName]);
end;
function TAsn1OctetString.GetOctets: TCryptoLibByteArray;
begin
result := Str;
end;
function TAsn1OctetString.GetOctetStream: TStream;
begin
// used TBytesStream here for one pass creation and population with byte array :)
result := TBytesStream.Create(Str);
end;
function TAsn1OctetString.ToString: String;
begin
result := '#' + THex.Encode(Str);
end;
end.
|
UNIT ConstAndTypes;
INTERFACE
CONST
ValidAlphabet: SET OF CHAR = ['A' .. 'Z', 'a' .. 'z', 'Ё', 'ё', 'А' .. 'Я', 'а' .. 'я']; {Все допустимые символы}
Uppercase: SET OF CHAR = ['A' .. 'Z', 'А' .. 'Я']; {Буквы в верхнем регистре}
ASCIIStep = 32; {Рассояние между верхним и нижним регистром}
TYPE
WordString = STRING(52);
Tree = ^NodeType;
NodeType = RECORD
SomeWord: WordString;
CountWord: INTEGER;
LLink, RLink: Tree
END;
IMPLEMENTATION
BEGIN {ConstAndTypes}
END. {ConstAndTypes}
|
unit U16;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TFrm16 = class(TForm)
edt1: TEdit;
lbl1: TLabel;
lbl2: TLabel;
edt2: TEdit;
btnAdd: TButton;
bvl1: TBevel;
lstUser: TListBox;
btnDel: TButton;
btnSaveAs: TButton;
btnOpen: TButton;
lblChanged: TLabel;
dlgOpen1: TOpenDialog;
dlgSave1: TSaveDialog;
btnSave: TButton;
lblFileName: TLabel;
btnNew: TButton;
procedure btnAddClick(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure btnSaveAsClick(Sender: TObject);
procedure btnDelClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormShow(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnNewClick(Sender: TObject);
private
public
procedure OpenFFileName;
end;
implementation
uses md5, UAccessConstant;
{$R *.dfm}
procedure TFrm16.btnAddClick(Sender: TObject);
var
sLogin, sPasw: string;
begin
sLogin := AnsiLowerCase(Trim(edt1.Text));
if (sLogin <> '') and (edt2.Text <> '') then
begin
if lstUser.Items.Values[sLogin] = '' then
begin
sPasw := md5.MD5DigestToStr(MD5String(edt2.Text));
lstUser.Items.Add(sLogin + '=' + sPasw);
lblChanged.Enabled := True;
btnSave.Enabled := lblFileName.Caption <> '';
end
else
ShowMessage('Пользователь ' + sLogin + ' уже существует');
end
else
ShowMessage('Поля "логин" и "пароль" не могут быть пустыми!');
end;
procedure TFrm16.btnOpenClick(Sender: TObject);
begin
if dlgOpen1.Execute then
begin
try
lstUser.Items.LoadFromFile(dlgOpen1.FileName);
lblChanged.Enabled := False;
lblFileName.Caption := dlgOpen1.FileName;
btnSave.Enabled := lblFileName.Caption <> '';
except
ShowMessage(UAccessConstant.csOpenError + dlgOpen1.FileName);
end;
end;
end;
procedure TFrm16.btnSaveAsClick(Sender: TObject);
begin
if dlgSave1.Execute then
try
lstUser.Items.SaveToFile(dlgSave1.FileName);
lblChanged.Enabled := False;
lblFileName.Caption := dlgSave1.FileName;
btnSave.Enabled := lblFileName.Caption <> '';
except
ShowMessage('Невозможно сохранить ' + dlgSave1.FileName)
end;
end;
procedure TFrm16.btnDelClick(Sender: TObject);
begin
if lstUser.ItemIndex > -1 then
begin
lstUser.DeleteSelected;
lblChanged.Enabled := True;
btnSave.Enabled := lblFileName.Caption <> '';
end;
end;
procedure TFrm16.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if lblChanged.Enabled then
CanClose :=
Application.MessageBox('Вы уверены что хотите закрыть окно, с потерей всех не сохраненных изменений?',
'Есть не сохраненные изменения', MB_YESNOCANCEL + MB_ICONWARNING +
MB_DEFBUTTON2) = IDYES;
end;
procedure TFrm16.FormShow(Sender: TObject);
begin
OpenFFileName;
end;
procedure TFrm16.btnSaveClick(Sender: TObject);
begin
try
lstUser.Items.SaveToFile(lblFileName.Caption);
lblChanged.Enabled:=False;
btnSave.Enabled:=False;
except
ShowMessage(csSaveError+lblFileName.Caption);
end;
end;
procedure TFrm16.OpenFFileName;
begin
if lblFileName.Caption <> '' then
try
lstUser.Items.LoadFromFile(lblFileName.Caption);
except
ShowMessage(UAccessConstant.csOpenError + lblFileName.Caption);
end;
end;
procedure TFrm16.btnNewClick(Sender: TObject);
begin
lstUser.Clear;
lblFileName.Caption:='';
lblChanged.Enabled:=False;
btnSave.Enabled:=False;
end;
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals 5.00 }
{ File name: flcCertificatePEM.pas }
{ File version: 5.03 }
{ Description: PEM parsing }
{ }
{ Copyright: Copyright (c) 2010-2021, David J Butler }
{ All rights reserved. }
{ Redistribution and use in source and binary forms, with }
{ or without modification, are permitted provided that }
{ the following conditions are met: }
{ Redistributions of source code must retain the above }
{ copyright notice, this list of conditions and the }
{ following disclaimer. }
{ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND }
{ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED }
{ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED }
{ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A }
{ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL }
{ THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, }
{ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR }
{ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, }
{ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF }
{ USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) }
{ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER }
{ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING }
{ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE }
{ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE }
{ POSSIBILITY OF SUCH DAMAGE. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ {
{ Description: }
{ }
{ Privacy Enhanced Mail (PEM) is a Base64 encoded DER certificate. }
{ }
{ Revision history: }
{ }
{ 2011/10/18 0.01 Initial development. }
{ 2016/01/10 0.02 String changes. }
{ 2018/07/17 5.03 Revised for Fundamentals 5. }
{ }
{******************************************************************************}
{$INCLUDE ..\flcInclude.inc}
{$INCLUDE flcCrypto.inc}
unit flcCertificatePEM;
interface
uses
{ System }
SysUtils,
{ Fundamentals }
flcStdTypes;
{ TPEMFile }
type
TPEMFile = class
private
FCertificates : array of RawByteString;
FRSAPrivateKey : RawByteString;
procedure Clear;
procedure AddCertificate(const CertificatePEM: RawByteString);
procedure SetRSAPrivateKey(const RSAPrivateKeyPEM: RawByteString);
procedure ParsePEMContent(const Content: RawByteString);
function GetCertificateCount: Integer;
function GetCertificate(const Idx: Integer): RawByteString;
public
procedure LoadFromText(const Txt: RawByteString);
procedure LoadFromFile(const FileName: String);
property CertificateCount: Integer read GetCertificateCount;
property Certificate[const Idx: Integer]: RawByteString read GetCertificate;
property RSAPrivateKey: RawByteString read FRSAPrivateKey;
end;
EPEMFile = class(Exception);
implementation
uses
{ System }
Classes,
{ Fundamentals }
flcStrings,
flcBase64;
{ TPEMFile }
procedure TPEMFile.Clear;
begin
FCertificates := nil;
FRSAPrivateKey := '';
end;
procedure TPEMFile.AddCertificate(const CertificatePEM: RawByteString);
var
L : Integer;
C : RawByteString;
begin
C := MIMEBase64Decode(CertificatePEM);
L := Length(FCertificates);
SetLength(FCertificates, L + 1);
FCertificates[L] := C;
end;
procedure TPEMFile.SetRSAPrivateKey(const RSAPrivateKeyPEM: RawByteString);
begin
FRSAPrivateKey := MIMEBase64Decode(RSAPrivateKeyPEM);
end;
procedure TPEMFile.ParsePEMContent(const Content: RawByteString);
var
S : RawByteString;
function GetTextBetween(const Start, Stop: RawByteString; var Between: RawByteString): Boolean;
var I, J : Integer;
begin
I := PosStrB(Start, S, 1, False);
if I > 0 then
begin
J := PosStrB(Stop, S, 1, False);
if J = 0 then
J := Length(S) + 1;
Between := CopyRangeB(S, I + Length(Start), J - 1);
Delete(S, I, J + Length(Stop) - I);
Between := StrRemoveCharSetB(Between, [#0..#32]);
Result := True;
end
else
Result := False;
end;
var
Found : Boolean;
Cert : RawByteString;
RSAPriv : RawByteString;
begin
S := Content;
repeat
Found := GetTextBetween('-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----', Cert);
if Found then
AddCertificate(Cert);
until not Found;
Found := GetTextBetween('-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----', RSAPriv);
if Found then
SetRSAPrivateKey(RSAPriv);
end;
procedure TPEMFile.LoadFromText(const Txt: RawByteString);
begin
Clear;
ParsePEMContent(Txt);
end;
procedure TPEMFile.LoadFromFile(const FileName: String);
var
F : TFileStream;
B : RawByteString;
L : Int64;
N : Integer;
begin
try
F := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
L := F.Size;
if L > 16 * 1024 * 1024 then
raise EPEMFile.Create('File too large');
N := L;
if N = 0 then
B := ''
else
begin
SetLength(B, N);
F.ReadBuffer(B[1], N);
end;
finally
F.Free;
end;
except
on E : Exception do
raise EPEMFile.CreateFmt('Error loading PEM file: %s: %s', [E.ClassName, E.Message]);
end;
LoadFromText(B);
end;
function TPEMFile.GetCertificateCount: Integer;
begin
Result := Length(FCertificates);
end;
function TPEMFile.GetCertificate(const Idx: Integer): RawByteString;
begin
Result := FCertificates[Idx];
end;
end.
|
program TESTSUB ( OUTPUT ) ;
//**********************************************************************
// Testprogramm fuer Strings bzw. VARCHARs
//
// Oppolzer - 02.2018
//$A+
//**********************************************************************
type TRANSLATE_TAB = array [ 1 .. 128 ] of CHAR ;
var C1 : CHAR ;
C2 : CHAR ;
C20 : CHAR ( 20 ) ;
C20A : CHAR ( 20 ) ;
VC20 : STRING ( 20 ) ;
VC200 : STRING ( 200 ) ;
VC1 : STRING ( 1 ) ;
VC2000 : STRING ( 2000 ) ;
LIMIT : INTEGER ;
X : BOOLEAN ;
P1 : STRING ( 20 ) ;
P2 : STRING ( 200 ) ;
I : INTEGER ;
XP : -> CHAR ;
TTAB : STRING ( 256 ) ;
function SUBSTR1 ( const SOURCE : STRING ; START : INTEGER ; LEN :
INTEGER ) : STRING ;
type LENGTHF = 0 .. 32767 ;
var X : INTEGER ;
Z : STRING ( 100 ) ;
P : ANYPTR ;
Q : ANYPTR ;
PLF : -> LENGTHF ;
begin (* SUBSTR1 *)
if LEN < 0 then
begin
if START > LENGTH ( SOURCE ) then
EXIT ( 1201 ) ;
LEN := LENGTH ( SOURCE ) - START + 1 ;
end (* then *)
else
begin
X := START + LEN - 1 ;
if X > LENGTH ( SOURCE ) then
EXIT ( 1201 ) ;
end (* else *) ;
if LEN > 100 then
EXIT ( 1202 ) ;
Z := '' ;
P := ADDR ( Z ) ;
P := PTRADD ( P , 2 ) ;
PLF := P ;
P := PTRADD ( P , 2 ) ;
Q := ADDR ( SOURCE [ START ] ) ;
PLF -> := LEN ;
MEMCPY ( P , Q , LEN ) ;
SUBSTR1 := Z ;
end (* SUBSTR1 *) ;
function SUBSTR2 ( const SOURCE : STRING ; START : INTEGER ; LEN :
INTEGER ) : STRING ;
type LENGTHF = 0 .. 32767 ;
var X : INTEGER ;
P : ANYPTR ;
Q : ANYPTR ;
begin (* SUBSTR2 *)
if LEN < 0 then
begin
if START > LENGTH ( SOURCE ) then
EXIT ( 1201 ) ;
LEN := LENGTH ( SOURCE ) - START + 1 ;
end (* then *)
else
begin
X := START + LEN - 1 ;
if X > LENGTH ( SOURCE ) then
EXIT ( 1201 ) ;
end (* else *) ;
SUBSTR2 := REPEATSTR ( ' ' , LEN ) ;
P := STRRESULTP ;
Q := ADDR ( SOURCE [ START ] ) ;
MEMCPY ( P , Q , LEN ) ;
end (* SUBSTR2 *) ;
procedure TEST4 ;
begin (* TEST4 *)
P1 := 'Oppolzer' ;
WRITE ( 'Zugriff auf String ueber Index .......: ' ) ;
WRITELN ( P1 [ 1 ] ) ;
WRITE ( 'Zugriff auf String ueber Index .......: ' ) ;
WRITELN ( P1 [ 5 ] ) ;
P2 := SUBSTR1 ( P1 , 3 , 4 ) ;
WRITE ( 'p2 = Ergebnis von SUBSTR1 ............: ' ) ;
WRITELN ( '<' , P2 , '>' ) ;
P2 := SUBSTR1 ( 'Bernd ' || 'Oppolzer' , 5 , 7 ) ;
WRITE ( 'p2 = Ergebnis von SUBSTR1 ............: ' ) ;
WRITELN ( '<' , P2 , '>' ) ;
P2 := SUBSTR1 ( 'Bernd ' || 'Oppolzer' , 5 , - 1 ) ;
WRITE ( 'p2 = Ergebnis von SUBSTR1 ............: ' ) ;
WRITELN ( '<' , P2 , '>' ) ;
//*************************************************************
// test SUBSTR2 - korrekte Variante mit STRRESULTP usw.
//*************************************************************
P1 := 'Oppolzer' ;
P2 := SUBSTR2 ( P1 , 3 , 4 ) ;
WRITE ( 'p2 = Ergebnis von SUBSTR2 ............: ' ) ;
WRITELN ( '<' , P2 , '>' ) ;
P2 := SUBSTR2 ( 'Bernd ' || 'Oppolzer' , 5 , 7 ) ;
WRITE ( 'p2 = Ergebnis von SUBSTR2 ............: ' ) ;
WRITELN ( '<' , P2 , '>' ) ;
P2 := SUBSTR2 ( 'Bernd ' || 'Oppolzer' , 5 , - 1 ) ;
WRITE ( 'p2 = Ergebnis von SUBSTR2 ............: ' ) ;
WRITELN ( '<' , P2 , '>' ) ;
//*************************************************************
// test SUBSTR
//*************************************************************
P1 := 'Oppolzer' ;
P2 := SUBSTR ( P1 , 3 , 4 ) ;
WRITE ( 'p2 = Ergebnis von SUBSTR .............: ' ) ;
WRITELN ( '<' , P2 , '>' ) ;
WRITE ( 'P1 nach SUBSTR (should not change) ...: ' ) ;
WRITELN ( '<' , P1 , '>' ) ;
P2 := SUBSTR ( 'Bernd ' || 'Oppolzer' , 5 , 7 ) ;
WRITE ( 'p2 = Ergebnis von SUBSTR .............: ' ) ;
WRITELN ( '<' , P2 , '>' ) ;
P2 := SUBSTR ( 'Bernd ' || 'Oppolzer' , 5 ) ;
WRITE ( 'p2 = Ergebnis von SUBSTR .............: ' ) ;
WRITELN ( '<' , P2 , '>' ) ;
end (* TEST4 *) ;
begin (* HAUPTPROGRAMM *)
TEST4 ;
end (* HAUPTPROGRAMM *) .
|
unit UGPlacesPhoneDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Edit, FMX.Layouts, FMX.ListBox, FMX.TabControl,
FMX.TMSCloudBase, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomGoogle, FMX.TMSCloudImage,
FMX.TMSCloudGoogleFMX, FMX.TMSCloudCustomGPlaces, FMX.TMSCloudGPlaces,
FMX.Objects, System.Actions, FMX.ActnList, System.Sensors, FMX.Sensors;
type
TForm2 = class(TForm)
TabControl1: TTabControl;
tabPlaces: TTabItem;
tabDetail: TTabItem;
edSearch: TEdit;
edType: TEdit;
Label2: TLabel;
Label3: TLabel;
Button1: TButton;
btnSearchNearby: TButton;
lstPlaces: TListBox;
TMSFMXCloudGPlaces1: TTMSFMXCloudGPlaces;
lblAutocomplete: TLabel;
lblAutocompleteText: TLabel;
btnAutocomplete: TButton;
ciIcon: TTMSFMXCloudImage;
lblNameTitle: TLabel;
Label6: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label1: TLabel;
Label7: TLabel;
lstTypes: TListBox;
lblOpen: TLabel;
lblVicinity: TLabel;
lblWebsite: TLabel;
lblRating: TLabel;
lblLattitude: TLabel;
lblLongtitude: TLabel;
lblPhone: TLabel;
lblAddress: TLabel;
SpeedButton1: TSpeedButton;
btnUp: TSpeedButton;
btnDown: TSpeedButton;
btnNextPage: TButton;
LocationSensor1: TLocationSensor;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnSearchNearbyClick(Sender: TObject);
procedure btnAutocompleteClick(Sender: TObject);
procedure lstPlacesItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
procedure SpeedButton1Click(Sender: TObject);
procedure btnUpClick(Sender: TObject);
procedure btnDownClick(Sender: TObject);
procedure btnNextPageClick(Sender: TObject);
procedure LocationSensor1LocationChanged(Sender: TObject; const OldLocation,
NewLocation: TLocationCoord2D);
private
procedure ShowPlacesList;
procedure SearchNearby;
procedure ShowSuggestions;
procedure ShowPlaceInfo;
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
var
lat, long: double;
{$R *.fmx}
{$I APPIDS.INC}
procedure TForm2.btnAutocompleteClick(Sender: TObject);
begin
edSearch.Text := lblAutocompleteText.Text;
edType.Text := '';
Button1Click(Self);
end;
procedure TForm2.btnDownClick(Sender: TObject);
var
placeIndex: integer;
begin
btnUp.Enabled := true;
placeIndex := lstPlaces.ItemIndex;
if placeIndex + 1 <= lstPlaces.items.Count -1 then
begin
lstPlaces.ItemIndex := placeIndex+1;
lstPlaces.OnItemClick(lstPlaces, TListBoxItem(lstPlaces.Items[placeIndex+1]));
end
else
begin
btnDown.enabled := false;
end;
end;
procedure TForm2.btnNextPageClick(Sender: TObject);
begin
TMSFMXCloudGPlaces1.GetNextPlacesPage();
ShowPlacesList();
end;
procedure TForm2.btnSearchNearbyClick(Sender: TObject);
begin
TMSFMXCloudGPlaces1.App.Key := GAppkey;
if TMSFMXCloudGPlaces1.App.Key <> '' then
begin
SearchNearby();
if lstPlaces.Items.Count > 0 then
lstPlaces.ItemIndex := 0;
end;
end;
procedure TForm2.btnUpClick(Sender: TObject);
var
placeIndex: integer;
begin
placeIndex := lstPlaces.ItemIndex;
btnDown.Enabled := true;
if placeIndex - 1 >= 0 then
begin
lstPlaces.ItemIndex := placeIndex-1;
if placeIndex - 1 = 0 then
btnUp.Enabled := false;
lstPlaces.OnItemClick(lstPlaces, TListBoxItem(lstPlaces.Items[placeIndex-1]));
end
else
btnUp.Enabled := false;
end;
procedure TForm2.Button1Click(Sender: TObject);
var
autocomplete: string;
begin
TMSFMXCloudGPlaces1.App.Key := GAppkey;
if (edSearch.Text <> '') and (TMSFMXCloudGPlaces1.App.Key <> '') then
begin
// search & show results
TMSFMXCloudGPlaces1.SearchByText(edSearch.Text, edType.Text);
ShowPlacesList();
// look for suggestions
if lblAutocompleteText.Text <> '' then
autocomplete := TMSFMXCloudGPlaces1.Autocomplete(edSearch.Text);
lblAutocompleteText.Text := autocomplete;
// show suggestion
ShowSuggestions();
end;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
TMSFMXCloudGPlaces1.App.Key := GAppkey;
tabPlaces.Visible := true;
tabDetail.Visible := false;
TabControl1.ActiveTab := tabPlaces;
LocationSensor1.Active := true;
end;
procedure TForm2.LocationSensor1LocationChanged(Sender: TObject;
const OldLocation, NewLocation: TLocationCoord2D);
var
LDecSeparator: String;
begin
LDecSeparator := FormatSettings.DecimalSeparator;
FormatSettings.DecimalSeparator := '.';
// current location
lat := StrToFloat(Format('%2.6f', [NewLocation.Latitude]));
long := StrToFloat(Format('%2.6f', [NewLocation.Longitude]));
end;
procedure TForm2.lstPlacesItemClick(const Sender: TCustomListBox; const Item: TListBoxItem);
begin
tabPlaces.Visible := false;
tabDetail.Visible := true;
TabControl1.ActiveTab := tabDetail;
ShowPlaceInfo();
SpeedButton1.Visible := true;
if lstPlaces.ItemIndex = 0 then
btnUp.Enabled := false;
btnUp.Visible := true;
btnDown.Visible := true;
end;
procedure TForm2.SearchNearby();
begin
TMSFMXCloudGPlaces1.SearchNearby(long, lat);
ShowPlacesList();
end;
procedure TForm2.ShowSuggestions();
begin
lblAutocomplete.Visible := true;
lblAutocompleteText.Visible := true;
btnAutocomplete.Visible := true;
end;
procedure TForm2.SpeedButton1Click(Sender: TObject);
begin
tabDetail.Visible := false;
tabPlaces.Visible := true;
TabControl1.ActiveTab := tabPlaces;
SpeedButton1.Visible := false;
btnUp.Visible := false;
btnDown.Visible := false;
end;
procedure TForm2.ShowPlaceInfo();
var
typ: string;
counter, heightCounter: integer;
Itm: TListBoxItem;
PlaceItem: TGPlacesItem;
PlaceIndex: integer;
CloudImage: TTMSFMXCloudImage;
Obj: TObject;
Photo: TPhotoItem;
I: Integer;
begin
PlaceIndex := lstPlaces.ItemIndex;
if PlaceIndex >= 0 then
begin
PlaceItem := TGPlacesItem(lstPlaces.Items.Objects[PlaceIndex]);
// Get more info about this place
PlaceItem := PlaceItem.GetDetails(PlaceItem);
ciIcon.URL := PlaceItem.Icon;
lblWebsite.Text := PlaceItem.Website;
lblAddress.Text := PlaceItem.Address.FormattedAddress;
lblPhone.Text := PlaceItem.Phone;
lblNameTitle.Text := PlaceItem.Title;
lblLattitude.Text := FloatToStr(PlaceItem.Lat);
lblLongtitude.Text := FloatToStr(PlaceItem.long);
lblRating.Text := PlaceItem.Rating;
lblVicinity.Text := PlaceItem.Vicinity;
if PlaceItem.Open then
lblOpen.Text := 'Yes'
else
lblOpen.Text := 'No';
lstTypes.Items.Clear;
lstTypes.Items := PlaceItem.Types;
end;
end;
procedure TForm2.ShowPlacesList();
var
Obj: TObject;
Place: TGPlacesItem;
Itm: TListBoxItem;
begin
// clear the list
lstPlaces.Items.Clear;
if TMSFMXCloudGPlaces1.HasNextPage then
btnNextPage.Enabled := true
else
btnNextPage.Enabled := false;
// show the list
for Obj in TMSFMXCloudGPlaces1.Items do
begin
Place := TGPlacesItem(Obj);
Itm := TListBoxItem.Create(lstPlaces);
Itm.Text := Place.Title;
Itm.Data := Place;
lstPlaces.AddObject(Itm);
end;
end;
end.
|
unit vcmProfilersCollection;
{------------------------------------------------------------------------------}
{ Библиотека : vcm; }
{ Автор : Морозов М.А; }
{ Начат : 21.06.2006; }
{ Модуль : vcmProfilersCollection }
{ Описание : Модуль содержит реализации объектов для производства замеров в }
{ библиотеке vcm; }
{------------------------------------------------------------------------------}
// $Id: vcmProfilersCollection.pas,v 1.1 2016/04/18 22:32:14 lulin Exp $
// $Log: vcmProfilersCollection.pas,v $
// Revision 1.1 2016/04/18 22:32:14 lulin
// - перегенерация.
//
// Revision 1.11 2013/04/05 12:02:37 lulin
// - портируем.
//
// Revision 1.10 2012/11/01 09:42:22 lulin
// - забыл точку с запятой.
//
// Revision 1.9 2012/11/01 07:44:07 lulin
// - делаем возможность логирования процесса загрузки модулей.
//
// Revision 1.8 2011/07/08 15:33:51 vkuprovich
// {RequestLink:271192867}
// Наследуем TvcmProfiler от класса, у которого есть блок RTTI
//
// Revision 1.7 2011/05/19 12:21:15 lulin
// {RequestLink:266409354}.
//
// Revision 1.6 2009/10/01 15:08:23 lulin
// - чистка кода.
//
// Revision 1.5 2009/02/12 13:57:31 lulin
// - <K>: 135604584. Выделен новый интерфейсный модуль.
//
// Revision 1.4 2006/12/29 13:09:23 lulin
// - реализуем интерфейс расширенного списка строк.
//
// Revision 1.3 2006/06/28 12:11:09 mmorozov
// - bugfix: для хранения времени использовался неправильный тип;
//
// Revision 1.2 2006/06/23 13:15:32 mmorozov
// - new behaviour: профайлеры создаются по первому требованию, не при запуске измерений, потому что профайлер может быть нужен до начала измерений;
//
// Revision 1.1 2006/06/23 10:42:29 mmorozov
// - new: профайлеры в библиотеке VCM;
//
interface
uses
Types,
l3ProtoPersistent,
l3ProtoPersistentRefList,
vcmInterfaces,
vcmProfilerInterfaces,
vcmBase
;
type
TvcmProfiler = class(Tl3ProtoPersistent, IvcmProfiler)
private
// internal fields
f_AverageExecuteTime : Integer;
f_Id : Integer;
f_FinishCount : Integer;
f_FinishCalledCount : Integer;
f_DisplayName : AnsiString;
f_Results : TvcmLongintList;
f_StartTime : DWORD;
private
// IvcmProfiler
function pm_GetId: Integer;
{* - идентификатор профайлера. }
function pm_GetHasFinished: Boolean;
{* - определяет закончил ли профайлер работу. }
function pm_GetExecuteTime: Integer;
{* - время загрузки прецедента (в миллисекунадах). }
function pm_GetExecuteCount: Integer;
{* - количество открытий прецедента. Профайлер запоминает результаты
каждого замера. }
function pm_GetAverageExecuteTime: Integer;
{* - среднее время открытие прецедента. }
function pm_GetDisplayName: AnsiString;
{* - отображаемое название. }
procedure Init(const aDisplayName : AnsiString;
aFinishCount : Integer);
{* - инициализирует профайлер. }
procedure Start;
{* - начать замер. }
procedure Finish;
{* - закончить замер. }
private
// property methods
function pm_GetResults: TvcmLongintList;
{* - список результатов запуска профайлера, каждый элемент содержит время
ExecuteTime. }
protected
// protected methods
procedure Cleanup;
override;
{-}
protected
// protected methods
property Results: TvcmLongintList
read pm_GetResults;
{* - список результатов запуска профайлера, каждый элемент содержит время
ExecuteTime. }
public
// public methods
constructor Create(const anId : Integer;
const aDisplayName : AnsiString = '';
const aFinishCount : Integer = 0);
reintroduce;
{-}
class function Make(const anId : Integer;
const aDisplayName : AnsiString = '';
const aFinishCount : Integer = 0): IvcmProfiler;
{-}
published
// published properties
property Id: Integer
read pm_GetId;
{* - идентификатор профайлера. }
property HasFinished: Boolean
read pm_GetHasFinished;
{* - определяет закончил ли профайлер работу. }
property ExecuteTime: Integer
read pm_GetExecuteTime;
{* - время загрузки прецедента (в миллисекунадах). }
property ExecuteCount: Integer
read pm_GetExecuteCount;
{* - количество открытий прецедента. Профайлер запоминает результаты
каждого замера. }
property AverageExecuteTime: Integer
read pm_GetAverageExecuteTime;
{* - среднее время открытие прецедента. }
property DisplayName: AnsiString
read pm_GetDisplayName;
{* - отображаемое название. }
end;
TvcmProfilersCollection = class(Tl3ProtoPersistentRefList, IvcmProfilersCollection)
private
// internal methods
function FindById(anId: Integer): IvcmProfiler;
{* - это нужно пользователям профайлера, они знают только его
идентификатор. }
function CreateProfier(const anId: Integer): TvcmProfiler;
{-}
public
// public methods
class function Make: IvcmProfilersCollection;
{-}
public
// IvcmProfilersCollection
procedure StartProfile(const aDisplayName : AnsiString;
anId : Integer;
aFinishCount : Integer);
{* - aFinishCount - устанавливает количество вызовов Finish после которых
считается, что профайле отработал и его свойство
HasFinished установится в True; }
procedure FinishProfile(anId: Integer);
{* - завершить работу профайлера. }
public
// published methods
function FindProfilerById(anId: Integer): TvcmProfiler;
{-}
end;
function vcmProfilers: TvcmProfilersCollection;
implementation
uses
SysUtils,
Windows
;
var
g_Profilers: TvcmProfilersCollection;
function vcmProfilers: TvcmProfilersCollection;
begin
if not Assigned(g_Profilers) then
g_Profilers := TvcmProfilersCollection.Create;
Result := g_Profilers;
end;
{ TvcmProfiles }
procedure TvcmProfilersCollection.StartProfile(const aDisplayName : AnsiString;
anId : Integer;
aFinishCount : Integer);
{* - aFinishCount - устанавливает количество вызовов Finish после которых
считается, что профайле отработал и его свойство
HasFinished установится в True; }
var
l_Profiler: IvcmProfiler;
begin
l_Profiler := FindById(anId);
with l_Profiler do
begin
Init(aDisplayName, aFinishCount);
Start;
end;
end;
procedure TvcmProfilersCollection.FinishProfile(anId: Integer);
{* - завершить работу профайлера. }
begin
FindById(anId).Finish;
end;
function TvcmProfilersCollection.CreateProfier(const anId: Integer): TvcmProfiler;
{-}
var
l_Temp: TvcmProfiler;
begin
l_Temp := TvcmProfiler.Create(anId);
try
Add(l_Temp);
Result := l_Temp;
finally
FreeAndNil(l_Temp);
end;
end;
function TvcmProfilersCollection.FindById(anId: Integer): IvcmProfiler;
{* - это нужно пользователям профайлера, они знают только его
идентификатор. }
begin
Supports(FindProfilerById(anId), IvcmProfiler, Result);
end;
function TvcmProfilersCollection.FindProfilerById(anId: Integer): TvcmProfiler;
var
l_Index: Integer;
begin
Result := nil;
for l_Index := 0 to Pred(Count) do
if TvcmProfiler(Items[l_Index]).Id = anId then
begin
Result := TvcmProfiler(Items[l_Index]);
Break
end;
if not Assigned(Result) then
Result := CreateProfier(anId);
end;
class function TvcmProfilersCollection.Make: IvcmProfilersCollection;
var
l_Class: TvcmProfilersCollection;
begin
l_Class := Create;
try
Result := l_Class;
finally
FreeAndNil(l_Class);
end;
end;
{ TvcmProfiler }
constructor TvcmProfiler.Create(const anId : Integer;
const aDisplayName : AnsiString = '';
const aFinishCount : Integer = 0);
// reintroduce;
{-}
begin
inherited Create;
f_DisplayName := aDisplayName;
f_Id := anId;
f_FinishCount := aFinishCount;
end;
class function TvcmProfiler.Make(const anId : Integer;
const aDisplayName : AnsiString = '';
const aFinishCount : Integer = 0): IvcmProfiler;
{-}
var
l_Class: TvcmProfiler;
begin
l_Class := Create(anId, aDisplayName, aFinishCount);
try
Result := l_Class;
finally
FreeAndNil(l_Class);
end;
end;
function TvcmProfiler.pm_GetAverageExecuteTime: Integer;
{* - среднее время открытие прецедента. }
var
l_Index: Integer;
begin
// Считаем по первому требованию:
if (Results.Count > 0) and (f_AverageExecuteTime = 0) then
for l_Index := 0 to Pred(Results.Count) do
Inc(f_AverageExecuteTime, Results.Items[l_Index]);
Result := f_AverageExecuteTime;
end;
function TvcmProfiler.pm_GetResults: TvcmLongintList;
{* - список результатов запуска профайлера, каждый элемент содержит время
ExecuteTime. }
begin
if not Assigned(f_Results) then
f_Results := TvcmLongintList.Make;
Result := f_Results;
end;
procedure TvcmProfiler.Init(const aDisplayName : AnsiString;
aFinishCount : Integer);
{* - инициализирует профайлер. }
begin
f_DisplayName := aDisplayName;
f_FinishCount := aFinishCount;
end;
procedure TvcmProfiler.Start;
{* - начать замер. }
begin
f_FinishCalledCount := 0;
f_StartTime := GetTickCount;
end;
procedure TvcmProfiler.Finish;
{* - закончить замер. }
begin
// Профайлер не был запущен:
if f_StartTime = 0 then
Exit;
Inc(f_FinishCalledCount);
// Все finish вызваны можно считать:
if pm_GetHasFinished then
begin
f_AverageExecuteTime := 0;
Results.Add(GetTickCount - f_StartTime);
f_StartTime := 0;
end;
end;
function TvcmProfiler.pm_GetDisplayName: AnsiString;
{* - отображаемое название. }
begin
Result := f_DisplayName;
end;
function TvcmProfiler.pm_GetExecuteCount: Integer;
{* - количество открытий прецедента. Профайлер запоминает результаты
каждого замера; }
begin
Result := Results.Count;
end;
function TvcmProfiler.pm_GetExecuteTime: Integer;
{* - время загрузки прецедента (в миллисекунадах). }
begin
Result := 0;
if Results.Count > 0 then
Result := Results.Items[Pred(Results.Count)];
end;
function TvcmProfiler.pm_GetId: Integer;
{* - идентификатор профайлера. }
begin
Result := f_Id;
end;
function TvcmProfiler.pm_GetHasFinished: Boolean;
{* - определяет закончил ли профайлер работу. }
begin
Result := f_FinishCalledCount = f_FinishCount;
end;
procedure TvcmProfiler.Cleanup;
begin
FreeAndNil(f_Results);
inherited;
end;
initialization
{!touched!}{$IfDef LogInit} WriteLn('W:\common\components\gui\Garant\VCM\implementation\Components\vcmProfilersCollection.pas initialization enter'); {$EndIf}
{!touched!}{$IfDef LogInit} WriteLn('W:\common\components\gui\Garant\VCM\implementation\Components\vcmProfilersCollection.pas initialization leave'); {$EndIf}
finalization
FreeAndNil(g_Profilers);
end.
|
unit Model;
{
////////////////////////////////
This project aims to study the persistence of business objects in
one application FPC/Lazarus using BrookFramework and dOPF from Silvio Clecio.
This project is not intended to provide warranties of any kind for any purpose!
////////////////////////////////
}
{$mode objfpc}{$H+}
interface
//uses
// SysUtils,
// Classes;
type
TState = class
private
FId: Int64;
FName: string;
protected
public
property Id: Int64 read FId write FId;
property Name: string read FName write FName;
published
end;
TCity = class
private
FId: Int64;
FStateId: Int64;
FName: string;
protected
public
property Id: Int64 read FId write FId;
property StateId: Int64 read FStateId write FStateId;
property Name: string read FName write FName;
published
end;
TDistrict = class
private
FId: Int64;
FCityId: Int64;
FName: string;
protected
public
property Id: Int64 read FId write FId;
property CityId: Int64 read FCityId write FCityId;
property Name: string read FName write FName;
published
end;
TStreet = class
private
FId: Int64;
FDistrictId: Int64;
FName: string;
FZipCode: string;
protected
public
property Id: Int64 read FId write FId;
property DistrictId: Int64 read FDistrictId write FDistrictId;
property Name: string read FName write FName;
property ZipCode: string read FZipCode write FZipCode;
published
end;
TAddressType = class
private
FId: Int64;
FDescription: string;
protected
public
property Id: Int64 read FId write FId;
property Description: string read FDescription write FDescription;
published
end;
TAddress = class
private
FId: Int64;
FAddressTypeId: Int64;
FStreetId: Int64;
FNumber: integer;
FComplement: string;
protected
public
property Id: Int64 read FId write FId;
property AddressTypeId: Int64 read FAddressTypeId write FAddressTypeId;
property StreetId: Int64 read FStreetId write FStreetId;
property Number: integer read FNumber write FNumber;
property Complement: string read FComplement write FComplement;
published
end;
TPerson = class
FId: Int64;
FName: string;
FAddress: Int64;
protected
public
property Id: Int64 read FId write FId;
property Name: string read FName write FName;
property Address: Int64 read FAddress write FAddress;
published
end;
TIndCust = class(TPerson) // Individual Customer
private
FBirthdate: TDateTime;
FSSNumber: string; // Social security number;
protected
public
property Birthdate: TDateTime read FBirthdate write FBirthdate;
property SSNumber: string read FSSNumber write FSSNumber;
published
end;
TCompCust = class(TPerson) // Company Customer
private
FEIN: string; // Employer Identification Number;
protected
public
property EIN: string read FEIN write FEIN;
published
end;
TUnit = class
private
FId: Int64;
FName: string;
FShortName: string;
protected
public
property Id: Int64 read FId write FId;
property Name: string read FName write FName;
property ShortName: string read FShortName write FShortName;
published
end;
TProduct = class
private
FId: Int64;
FName: string;
FUnitId: Int64;
FPrice: currency;
FQty: real;
protected
public
property Id: Int64 read FId write FId;
property Name: string read FName write FName;
property UnitId: Int64 read FUnitId write FUnitId;
property Price: currency read FPrice write FPrice;
property Qty: real read FQty write FQty;
published
end;
TOrder = class
private
FId: Int64;
FPersonId: Int64; // coud be TIndividualCustomer or TCompanyCustomer
FBillingAddressId: Int64;
FDeliveryAddressId: Int64;
FDate: TDateTime;
FTotal: currency;
protected
public
property Id: Int64 read FId write FId;
property PersonId: Int64 read FPersonId write FPersonId;
property BillingAddressId: Int64 read FBillingAddressId
write FBillingAddressId;
property DeliveryAddressId: Int64 read FDeliveryAddressId
write FDeliveryAddressId;
property Date: TDateTime read FDate write FDate;
property Total: currency read FTotal write FTotal;
published
end;
TOrderItems = class
private
FId: Int64;
FOrderId: Int64;
FProductId: Int64;
FDiscount: currency;
FQty: real;
protected
public
property Id: Int64 read FId write FId;
property OrderId: Int64 read FOrderId write FOrderId;
property ProductId: Int64 read FProductId write FProductId;
property Discount: currency read FDiscount write FDiscount;
property Qty: real read FQty write FQty;
published
end;
implementation
end.
|
unit LzFindMt;
interface
uses System.SysUtils, Threads, LzmaTypes, LzFind;
const
kMtCacheLineDummy = 128;
{$Z4}
type
TCMtSync = record
wasCreated: Boolean;
needStart: Boolean;
exit: Boolean;
stopWriting: Boolean;
thread: TCThread;
canStart: TCAutoResetEvent;
wasStarted: TCAutoResetEvent;
wasStopped: TCAutoResetEvent;
freeSemaphore: TCSemaphore;
filledSemaphore: TCSemaphore;
csWasInitialized: Boolean;
csWasEntered: Boolean;
cs: TCCriticalSection;
numProcessedBlocks: UInt32;
end;
TMf_Mix_Matches = function(p: Pointer; matchMinPos: UInt32; var distances: UInt32): PCardinal; cdecl;
TMf_GetHeads = procedure(const buffer: TBytes; pos: UInt32; hash: PCardinal; hashMask: UInt32;
heads: PCardinal; numHeads: UInt32; const crc: PCardinal); cdecl;
TCMatchFinderMt = record
(* LZ *)
pointerToCurPos: PByte;
btBuf: PCardinal;
btBufPos: UInt32;
btBufPosLimit: UInt32;
lzPos: UInt32;
btNumAvailBytes: UInt32;
UInt32: PCardinal;
fixedHashSize: UInt32;
historySize: UInt32;
crc: PCardinal;
MixMatchesFunc: TMf_Mix_Matches;
(* LZ + BT *)
btSync: TCMtSync;
btDummy: array[0..kMtCacheLineDummy - 1] of Byte;
(* BT *)
hashBuf: PCardinal;
hashBufPos: UInt32;
hashBufPosLimit: UInt32;
hashNumAvail: UInt32;
son: PCLzRef;
matchMaxLen: UInt32;
numHashBytes: UInt32;
pos: UInt32;
buffer: PByte;
cyclicBufferPos: UInt32;
cyclicBufferSize: UInt32; (* it must be historySize + 1 *)
cutValue: UInt32;
(* BT + Hash *)
hashSync: TCMtSync;
(* Byte hashDummy[kMtCacheLineDummy]; *)
(* Hash *)
GetHeadsFunc: TMf_GetHeads;
MatchFinder: PCMatchFinder;
end;
procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinderMt_Construct{$else}MatchFinderMt_Construct{$endif}(var p: TCMatchFinderMt); cdecl; external;
procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinderMt_Destruct{$else}MatchFinderMt_Destruct{$endif}(var p: TCMatchFinderMt; var alloc:
TISzAlloc); cdecl; external;
function {$ifdef UNDERSCOREIMPORTNAME}_MatchFinderMt_Create{$else}MatchFinderMt_Create{$endif}(var p: TCMatchFinderMt; historySize: UInt32;
keepAddBufferBefore: UInt32; matchMaxLen: UInt32; keepAddBufferAfter:
UInt32; var alloc: TISzAlloc): TSRes; cdecl; external;
procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinderMt_CreateVTable{$else}MatchFinderMt_CreateVTable{$endif}(var p: TCMatchFinderMt; var vTable:
TIMatchFinder); cdecl; external;
procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinderMt_ReleaseStream{$else}MatchFinderMt_ReleaseStream{$endif}(var p: TCMatchFinderMt); cdecl; external;
function {$ifdef UNDERSCOREIMPORTNAME}_MatchFinderMt_InitMt{$else}MatchFinderMt_InitMt{$endif}(var p: TCMatchFinderMt): Integer; cdecl; external;
implementation
uses System.Win.Crtl, Winapi.Windows;
{$ifdef Win32}
{$L Win32\LzFindMt.obj}
{$else}
{$L Win64\LzFindMt.o}
{$endif}
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.3 2004.02.03 5:44:54 PM czhower
Name changes
Rev 1.2 2/1/2004 3:33:48 AM JPMugaas
Reenabled. Should work in DotNET.
Rev 1.1 2003.10.12 3:36:26 PM czhower
todo item
Rev 1.0 11/14/2002 02:13:44 PM JPMugaas
}
{
Implementation of the NTLM authentication as specified in
http://www.innovation.ch/java/ntlm.html with some fixes
Author: Doychin Bondzhev (doychin@dsoft-bg.com)
Copyright: (c) Chad Z. Hower and The Winshoes Working Group.
S.G. 12/7/2002: Moved the user query one step up: the domain name is required
to properly format the Type 1 message.
}
unit IdAuthenticationNTLM;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdAuthentication;
Type
TIdNTLMAuthentication = class(TIdAuthentication)
protected
FNTLMInfo: String;
FHost, FDomain, FUser: String;
function DoNext: TIdAuthWhatsNext; override;
function GetSteps: Integer; override;
procedure SetUserName(const Value: String); override;
public
constructor Create; override;
function Authentication: String; override;
function KeepAlive: Boolean; override;
end;
// RLebeau 4/17/10: this forces C++Builder to link to this unit so
// RegisterAuthenticationMethod can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdAuthenticationNTLM"'*)
implementation
uses
IdGlobal,
IdGlobalProtocols,
IdException,
IdCoderMIME,
IdResourceStringsOpenSSL,
IdSSLOpenSSLHeaders,
IdSSLOpenSSL,
IdNTLM,
SysUtils;
{ TIdNTLMAuthentication }
constructor TIdNTLMAuthentication.Create;
begin
inherited Create;
if not LoadOpenSSLLibrary then begin
raise EIdOSSLCouldNotLoadSSLLibrary.Create(RSOSSLCouldNotLoadSSLLibrary);
end;
end;
function TIdNTLMAuthentication.DoNext: TIdAuthWhatsNext;
begin
Result := wnDoRequest;
case FCurrentStep of
0:
begin
if Length(UserName) > 0 then begin
FCurrentStep := 1;
Result := wnDoRequest;
end else begin
Result := wnAskTheProgram;
end;
end;
1:
begin
FCurrentStep := 2;
Result := wnDoRequest;
end;
2:
begin
FCurrentStep := 3;
Result := wnDoRequest;
end;
3:
begin
Reset;
Result := wnFail;
end;
end;
end;
function TIdNTLMAuthentication.Authentication: String;
var
buf: TIdBytes;
Type2: type_2_message_header;
begin
Result := ''; {do not localize}
SetLength(buf, 0);
case FCurrentStep of
1:
begin
FHost := IndyComputerName;
Result := 'NTLM ' + BuildType1Message(FDomain, FHost); {do not localize}
end;
2:
begin
if Length(FNTLMInfo) = 0 then
begin
FNTLMInfo := ReadAuthInfo('NTLM'); {do not localize}
Fetch(FNTLMInfo);
end;
if Length(FNTLMInfo) = 0 then
begin
Reset;
Abort;
end;
with TIdDecoderMIME.Create do try
buf := DecodeBytes(FNTLMInfo);
finally Free; end;
BytesToRaw(buf, Type2, SizeOf(Type2));
buf := RawToBytes(Type2.Nonce, SizeOf(Type2.Nonce));
Result := 'NTLM ' + BuildType3Message(FDomain, FHost, FUser, Password, buf); {do not localize}
FCurrentStep := 2;
end;
end;
end;
function TIdNTLMAuthentication.KeepAlive: Boolean;
begin
Result := True;
end;
function TIdNTLMAuthentication.GetSteps: Integer;
begin
Result := 3;
end;
procedure TIdNTLMAuthentication.SetUserName(const Value: String);
begin
if Value <> Username then
begin
inherited SetUserName(Value);
GetDomain(Username, FUser, FDomain);
end;
end;
initialization
RegisterAuthenticationMethod('NTLM', TIdNTLMAuthentication); {do not localize}
finalization
UnregisterAuthenticationMethod('NTLM'); {do not localize}
end.
|
unit uAssets;
interface
uses
glr_scene,
glr_render,
glr_render2d;
type
{ Assets }
Assets = class
public
// Base assets
class var GuiAtlas: TglrTextureAtlas;
class var GuiMaterial: TglrMaterial;
class var GuiCamera: TglrCamera;
class var GuiSpriteBatch: TglrSpriteBatch;
class var FontMain: TglrFont;
class var FontMainBatch: TglrFontBatch;
class procedure LoadBase();
class procedure UnloadBase();
// Level specified assets
// ...
end;
const
R_GUI_ATLAS_BUTTON = 'button.png';
R_GUI_ATLAS_BUTTON_OVER = 'button_over.png';
R_GUI_ATLAS_SLIDER_BACK = 'slider_back.png';
R_GUI_ATLAS_SLIDER_FILL = 'slider_fill.png';
R_GUI_ATLAS_SLIDER_BTN = 'slider_btn.png';
R_GUI_ATLAS_CHECKBOX = 'checkbox.png';
R_GUI_ATLAS_CHECKBOX_C = 'checkbox_check.png';
implementation
uses
glr_filesystem, glr_core, glr_math;
const
R_BASE = 'data/';
R_GUI_ATLAS_IMG = R_BASE + 'gui.tga';
R_GUI_ATLAS_TXT = R_BASE + 'gui.atlas';
R_FONT_MAIN = R_BASE + 'AmazingGrotesk19.fnt';
{ Assets }
class procedure Assets.LoadBase();
begin
GuiAtlas := TglrTextureAtlas.Create(
FileSystem.ReadResource(R_GUI_ATLAS_IMG),
FileSystem.ReadResource(R_GUI_ATLAS_TXT),
extTga, aextCheetah);
GuiMaterial := TglrMaterial.Create(Default.SpriteShader);
GuiMaterial.AddTexture(GuiAtlas, 'uDiffuse');
GuiSpriteBatch := TglrSpriteBatch.Create();
GuiCamera := TglrCamera.Create();
GuiCamera.SetProjParams(0, 0, Render.Width, Render.Height, 45, 0.1, 100, pmOrtho, pTopLeft);
GuiCamera.SetViewParams(
Vec3f(0, 0, 100),
Vec3f(0, 0, 0),
Vec3f(0, 1, 0));
FontMain := TglrFont.Create(FileSystem.ReadResource(R_FONT_MAIN));
FontMainBatch := TglrFontBatch.Create(FontMain);
end;
class procedure Assets.UnloadBase();
begin
GuiMaterial.Free();
GuiAtlas.Free();
GuiSpriteBatch.Free();
GuiCamera.Free();
FontMainBatch.Free();
FontMain.Free();
end;
end.
|
unit TaskbarProgressFunc;
{
Inno Setup
Copyright (C) 1997-2010 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Wrappers for ITaskbarList3.SetProgressState & SetProgressValue
$jrsoftware: issrc/Projects/TaskbarProgressFunc.pas,v 1.1 2010/10/29 01:48:45 jr Exp $
}
interface
type
TTaskbarProgressState = (tpsNoProgress, tpsIndeterminate, tpsNormal,
tpsError, tpsPaused);
procedure SetAppTaskbarProgressState(const State: TTaskbarProgressState);
procedure SetAppTaskbarProgressValue(const Completed, Total: Cardinal);
implementation
uses
Windows, {$IFDEF VER90} OLE2 {$ELSE} ActiveX {$ENDIF}, Forms, dwTaskbarList;
var
TaskbarListInitialized: Boolean;
TaskbarListInterface: ITaskbarList3;
function InitializeTaskbarList: Boolean;
var
WinVer: Word;
Intf: ITaskbarList3;
begin
if not TaskbarListInitialized then begin
WinVer := Swap(Word(GetVersion()));
if WinVer >= $0601 then
if CoCreateInstance(CLSID_TaskbarList, nil, CLSCTX_INPROC_SERVER, IID_TaskbarList3, Intf) = S_OK then
if Intf.HrInit = S_OK then begin
{$IFNDEF VER90}
{ Safety: don't allow the instance to be destroyed at shutdown }
Intf._AddRef;
{$ENDIF}
TaskbarListInterface := Intf;
end;
TaskbarListInitialized := True;
end;
Result := Assigned(TaskbarListInterface);
end;
procedure SetAppTaskbarProgressState(const State: TTaskbarProgressState);
const
StateFlags: array[TTaskbarProgressState] of Integer = (
TBPF_NOPROGRESS, TBPF_INDETERMINATE, TBPF_NORMAL, TBPF_ERROR, TBPF_PAUSED);
begin
if InitializeTaskbarList then
TaskbarListInterface.SetProgressState(Application.Handle, StateFlags[State]);
end;
procedure SetAppTaskbarProgressValue(const Completed, Total: Cardinal);
var
Completed64, Total64: dwInteger64;
begin
if InitializeTaskbarList then begin
Completed64.Lo := Completed;
Completed64.Hi := 0;
Total64.Lo := Total;
Total64.Hi := 0;
TaskbarListInterface.SetProgressValue(Application.Handle, Completed64, Total64);
end;
end;
end.
|
Unit cdrip;
{$mode objfpc}{$H+}
Interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ComCtrls,
StdCtrls, Buttons, ExtCtrls, cddb, dos, Grids, DBCtrls, process,
debug;
resourcestring
rsEncodeToMp3 = 'Encode to mp3';
rsQuerryCDDB = 'Query CDDB';
rsLoad = 'Load';
rsEject = 'Eject';
rsStart = 'Start';
rsBack = 'Back';
rsSetID3Tag = 'Write ID3-Tags';
rsCrSubfolders = 'Create artist subfolders';
rsOutfileNamin = 'Outfile naming scheme';
Type
{ Tcdrip }
Tcdrip = Class(TForm)
bitratebox: TComboBox;
FileNameType: TComboBox;
LNameScheme: TLabel;
paranoia: TCheckBox;
startbtn: TButton;
backbtn: TButton;
querrybtn: TButton;
ejectbtn: TButton;
loadbtn: TButton;
browsedirectorybtn: TButton;
encodecheck: TCheckBox;
writetagscheck: TCheckBox;
artistedit: TEdit;
albumedit: TEdit;
subfoldercheck: TCheckBox;
drivebox: TComboBox;
outputfolderbox: TComboBox;
Label1: TLabel;
LArtist: TLabel;
LAlbum: TLabel;
SelectDirectoryDialog1: TSelectDirectoryDialog;
Trackgrid: TStringGrid;
Panel1: TPanel;
Timer1: TTimer;
Procedure Button1Click(Sender: TObject);
Procedure Button2Click(Sender: TObject);
Procedure Button4Click(Sender: TObject);
Procedure Button5Click(Sender: TObject);
procedure browsedirectorybtnClick(Sender: TObject);
Procedure CheckBox1Change(Sender: TObject);
Procedure FormClose(Sender: TObject; Var CloseAction: TCloseAction);
Procedure FormCreate(Sender: TObject);
Procedure Timer1Timer(Sender: TObject);
Procedure TrackgridHeaderClick(Sender: TObject; IsColumn: Boolean;
index: Integer);
Procedure TrackgridMouseDown(Sender: TOBject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
Procedure TrackgridSelectCell(Sender: TObject; Col, Row: Integer;
Var CanSelect: Boolean);
Procedure encodecheckChange(Sender: TObject);
Procedure startButClick(Sender: TObject);
Private
{ private declarations }
Outputstring: TStringlist;
Outputstream: TMemoryStream;
RipProcess, EncodeProcess: TProcess;
Public
{ public declarations }
ToRemove, ToRip, ToEncode: array[1..100] Of boolean;
OutFileNames: array[1..100] Of string;
RipTrack, EncodeTrack: byte;
ripping, encoding: boolean;
outfolder: string;
CDDBcon: TCddbObject;
End;
Var
cdripwin: Tcdrip;
Implementation
Uses mainform, mediacol, translations, functions, config;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{ Tcdrip }
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.Button1Click(Sender: TObject);
Begin
Button5Click(Nil);
If CDDBcon=Nil Then
CDDBcon := TCddbObject.create
Else
Begin
Timer1.Enabled := false;
CDDBcon.destroy;
CDDBcon := TCddbObject.create;
End;
If CDDBcon.ReadTOC(drivebox.Text) Then
Begin
CDDBcon.query(drivebox.Text, 'freedb.org', 8880);
Timer1.Enabled := true;
End;
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.Button2Click(Sender: TObject);
Begin
close;
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.Button4Click(Sender: TObject);
Begin
{$ifdef linux}
Exec('/usr/bin/eject',CDDBcon.CDromDrives[drivebox.ItemIndex+1]);
{$endif linux}
{$ifdef win32}
Exec('eject.exe',CDDBcon.CDromDrives[drivebox.ItemIndex+1]);
{$endif win32}
DebugOutLn('ATTENTION!! DIRTY! ejecting cdrom drive... ',0);
Trackgrid.Clean([gzNormal, gzFixedCols]);
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.Button5Click(Sender: TObject);
Var b, z: byte;
tmps, t1, t2: string;
ti1, ti2: integer;
Begin
Trackgrid.Clean([gzNormal, gzFixedCols]);
If CDDBcon.ReadTOC(drivebox.Text) Then
Begin
artistedit.Text := 'Unknown';
albumedit.Text := 'Unknown';
Trackgrid.RowCount := 1;
Trackgrid.ColWidths[0] := 20;
For b := 1 To CDDBcon.NrTracks Do
Begin
str(b, tmps);
Trackgrid.RowCount := Trackgrid.RowCount+1;
Trackgrid.Cells[0,b] := tmps;
Trackgrid.Cells[1,b] := 'Track '+tmps;
z := b;
ti1 := (CDDBcon.TOCEntries[z+1].min)-(CDDBcon.TOCEntries[z].min);
ti2 := (CDDBcon.TOCEntries[z+1].sec)-(CDDBcon.TOCEntries[z].sec);
If ti2<0 Then dec(ti1);
ti2 := abs(ti2);
str(ti1, t1);
str(ti2, t2);
If ti2<10 Then t2 := '0'+t2;
Trackgrid.Cells[3,b] := t1+':'+t2;
End;
End;
Timer1.Enabled := true;
End;
procedure Tcdrip.browsedirectorybtnClick(Sender: TObject);
begin
if DirectoryExists(outputfolderbox.Text) then SelectDirectoryDialog1.FileName := outputfolderbox.Text;
if SelectDirectoryDialog1.Execute Then
begin
if outputfolderbox.Items.IndexOf(SelectDirectoryDialog1.FileName) < 0 then outputfolderbox.Items.Insert(0, SelectDirectoryDialog1.FileName);
outputfolderbox.ItemIndex := outputfolderbox.Items.IndexOf(SelectDirectoryDialog1.FileName);
end;
end;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.CheckBox1Change(Sender: TObject);
Begin
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.FormClose(Sender: TObject; Var CloseAction: TCloseAction);
Begin
Timer1.Enabled := false;
RipProcess.free;
EncodeProcess.free;
Outputstream.free;
Outputstring.free;
Timer1.free;
CDDBcon.destroy;
main.Enabled := true;
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.FormCreate(Sender: TObject);
Var b, z: byte;
tmps, t1, t2: string;
ti1, ti2, i: integer;
Begin
TranslateUnitResourceStrings('cdrip', cactusconfig.DataPrefix+'languages/cactus.%s.po',
CactusConfig.language, copy(CactusConfig.language, 0, 2));
encodecheck.Caption := rsEncodeToMp3;
LArtist.Caption := rsArtist;
LAlbum.Caption := rsAlbum;
querrybtn.Caption := rsQuerryCDDB;
loadbtn.Caption := rsLoad;
ejectbtn.Caption := rsEject;
startbtn.Caption := rsStart;
backbtn.Caption := rsBack;
writetagscheck.Caption := rsSetID3Tag;
subfoldercheck.Caption := rsCrSubfolders;
LNameScheme.Caption := rsOutfileNamin;
ripping := false;
RipProcess := TProcess.Create(Nil);
EncodeProcess := TProcess.Create(Nil);
Outputstring := TStringList.Create;
Outputstream := TMemoryStream.Create;
For i:= 0 To MediaCollection.DirList.Count-1 Do
//
Begin
outputfolderbox.AddItem(MediaCollection.DirList[i], Nil);
End;
outputfolderbox.ItemIndex := 0;
CDDBcon := TCddbObject.create;
If (CDDBcon.DriveCount>0) Then
Begin
For b:=1 To CDDBcon.DriveCount Do
drivebox.AddItem(CDDBcon.CDromDrives[b], Nil);
drivebox.ItemIndex := 0;
If CDDBcon.ReadTOC(CDDBcon.CDromDrives[drivebox.ItemIndex+1]) Then
Begin
artistedit.Text := 'Unknown';
albumedit.Text := 'Unknown';
Trackgrid.Clean([gzNormal, gzFixedCols]);
Trackgrid.Cells[1,0] := 'Title';
Trackgrid.Cells[2,0] := 'Rip';
Trackgrid.Cells[3,0] := 'Length';
Trackgrid.RowCount := 1;
Trackgrid.ColWidths[0] := 20;
For b := 1 To CDDBcon.NrTracks Do
Begin
str(b, tmps);
Trackgrid.RowCount := Trackgrid.RowCount+1;
Trackgrid.Cells[0,b] := tmps;
Trackgrid.Cells[1,b] := 'Track '+tmps;
z := b;
ti1 := (CDDBcon.TOCEntries[z+1].min)-(CDDBcon.TOCEntries[z].min);
ti2 := (CDDBcon.TOCEntries[z+1].sec)-(CDDBcon.TOCEntries[z].sec);
If ti2<0 Then dec(ti1);
ti2 := abs(ti2);
str(ti1, t1);
str(ti2, t2);
If ti2<10 Then t2 := '0'+t2;
Trackgrid.Cells[3,b] := t1+':'+t2;
End;
End;
Timer1.Enabled := true;
End
Else
Begin
ShowMessage('No CDROM-Drive found on this computer');
End;
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{This timerevent is too confusing, big and buggy. split in 2 timer objects -> one for IP communication and one for rip/encode status }
Procedure Tcdrip.Timer1Timer(Sender: TObject);
Var
b: byte;
tmps: string;
ti1, ti2: integer;
t1,t2, EncPercent: string;
i: integer;
Begin
If (ripping=false) And (encoding=false) Then
Begin
CDDBcon.callevents;
If CDDBcon.data_ready Then
Begin
artistedit.Text := CDDBcon.artist;
albumedit.Text := CDDBcon.album;
Trackgrid.Clean([gzNormal, gzFixedCols]);
Trackgrid.RowCount := 1;
Trackgrid.ColWidths[0] := 20;
For b:= 1 To CDDBcon.NrTracks Do
Begin
str(b, tmps);
Trackgrid.RowCount := Trackgrid.RowCount+1;
Trackgrid.Cells[0,b] := tmps;
Trackgrid.Cells[1,b] := CDDBcon.title[b];
ti1 := (CDDBcon.TOCEntries[b+1].min)-(CDDBcon.TOCEntries[b].min);
ti2 := (CDDBcon.TOCEntries[b+1].sec)-(CDDBcon.TOCEntries[b].sec);
If ti2<0 Then dec(ti1);
ti2 := abs(ti2);
str(ti1, t1);
str(ti2, t2);
If ti2<10 Then t2 := '0'+t2;
Trackgrid.Cells[3,b] := t1+':'+t2;
End;
CDDBcon.data_ready := false;
End;
End;
If ripping And RipProcess.Running Then
Begin
Outputstream.Clear;
Outputstream.SetSize(2048);
i := (RipProcess.OutPut.Read(Outputstream.Memory^, 2048));
Outputstream.SetSize(i);
If i>5 Then
Begin
Outputstring.clear;
Outputstring.LoadFromStream(Outputstream);
for i:=0 to Outputstring.Count-1 do begin
tmps := copy(Outputstring.Strings[i], pos('%', Outputstring.Strings[i])-3, 3);
if tmps<>'' then EncPercent:=tmps;
end;
Trackgrid.Cells[2,RipTrack] := EncPercent+'%';
End;
End;
If (ripping) And (RipProcess.Running=false) Then
Begin
If ToEncode[RipTrack] Then
Begin
encoding := true;
EncodeTrack := RipTrack;
str(EncodeTrack, tmps);
If EncodeTrack<10 Then tmps := '0'+tmps;
If FileNameType.ItemIndex=0 Then OutFileNames[EncodeTrack] := tmps+' - '+
artistedit.Text+' - '+
Trackgrid.Cells[1,
EncodeTrack]+'.mp3';
If FileNameType.ItemIndex=1 Then OutFileNames[EncodeTrack] := artistedit.
Text+' - '+Trackgrid.Cells[1
, EncodeTrack]+'.mp3';
If FileNameType.ItemIndex=2 Then OutFileNames[EncodeTrack] := artistedit.
Text+' - '+inttostr(
EncodeTrack)+' - '+Trackgrid
.Cells[1, EncodeTrack]+
'.mp3';
OutFileNames[EncodeTrack] := StringReplace(OutFileNames[EncodeTrack], '/', '_', [rfReplaceAll]);
OutFileNames[EncodeTrack] := StringReplace(OutFileNames[EncodeTrack], '\', '_', [rfReplaceAll]);
OutFileNames[EncodeTrack] := IncludeTrailingPathDelimiter(outfolder)+OutFileNames[EncodeTrack];
OutFileNames[EncodeTrack] := StringReplace(OutFileNames[EncodeTrack], #39, '', [
rfReplaceAll]);
DebugOutLn(OutFileNames[EncodeTrack],0);
EncodeProcess.CommandLine := '/usr/bin/lame -h -b'+bitratebox.Items[bitratebox.ItemIndex]+
' --tt "'+UTF8toLatin1(Trackgrid.Cells[1, EncodeTrack])+
'" --ta "'+UTF8toLatin1(artistedit.Text)+'" --tl "'+
UTF8toLatin1(albumedit.Text)+'" --tn '+tmps+' "'+outfolder+
'/Track'+tmps+'.wav"'+' "'+OutFileNames[EncodeTrack]+'"';
DebugOutLn(EncodeProcess.CommandLine,0);
Caption := 'Encoding Track '+inttostr(EncodeTrack)+' ...';
EncodeProcess.Options := [poUsePipes, poStderrToOutPut];
EncodeProcess.Execute;
encoding := true;
ripping := false;
Timer1.Enabled := true;
End
Else
Begin
encoding := false;
i := 0;
str(Riptrack, tmps);
If RipTrack<10 Then tmps := '0'+tmps;
If ToRemove[RipTrack] Then
Begin
DeleteFile(outfolder+'/Track'+tmps+'.wav');
DeleteFile(outfolder+'/Track'+tmps+'.inf');
DebugOutLn('delete '+outfolder+'/Track'+tmps+'.wav',0);
End;
Repeat
inc(i)
Until (ToRip[i]=true) Or (i>CDDBcon.NrTracks);
If i<=CDDBcon.NrTracks Then
Begin
Trackgrid.Cells[2,i] := '0%';
ToRip[i] := false;
ToRemove[RipTrack] := false;
Trackgrid.Cells[2,RipTrack] := '100%';
RipTrack := i;
str(i, tmps);
If i<10 Then tmps := '0'+tmps;
If paranoia.Checked Then
RipProcess.CommandLine := '/usr/bin/cdda2wav -paranoia -D'+CDDBcon.Device+' -t '+
tmps+' '''+outfolder+'/Track'+tmps+'.wav'''
Else
RipProcess.CommandLine := '/usr/bin/cdda2wav -D'+CDDBcon.Device+' -t '+tmps+' '''+
outfolder+'/Track'+tmps+'.wav''';
RipProcess.Options := [poUsePipes,poStderrToOutPut, poDefaultErrorMode];
Caption := 'Ripping Track '+tmps+' ...';
DebugOutLn('Ripping Track '+tmps,0);
RipProcess.Execute;
Timer1.Enabled := true;
End
Else
Begin
DebugOutLn('Finished all tracks', 0);
Trackgrid.Cells[2,RipTrack] := '100%';
Caption := 'CD Rip... < Finished >';
Trackgrid.Options:= Trackgrid.Options + [goEditing];
Timer1.Enabled := false;
main.update_artist_view;
update_title_view;
ripping := false;
encoding := false;
ShowMessage('Ripping and encoding finished');
MediaCollection.SaveToFile;
End;
End;
End;
If encoding And EncodeProcess.Running And ToEncode[RipTrack] Then
Begin
Outputstream.Clear;
Outputstream.SetSize(1024);
i := (EncodeProcess.OutPut.Read(Outputstream.Memory^, 1024));
Outputstream.SetSize(i);
If i>0 Then
Begin
Outputstring.clear;
Outputstring.LoadFromStream(Outputstream);
for i:=0 to Outputstring.Count-1 do begin
tmps := copy(Outputstring.Strings[i], pos('%', Outputstring.Strings[i])-2, 2);
if tmps<>'' then EncPercent:=tmps;
end;
DebugOutLn(EncPercent,0);
Trackgrid.Cells[2,EncodeTrack] := EncPercent+'%';
Application.ProcessMessages;
End;
End;
If encoding And (EncodeProcess.Running=false) {and (ToEncode[RipTrack]=false)} Then
Begin
ripping := true;
encoding := false;
ToEncode[RipTrack] := false;
DebugOutLn('adding file',0);
MediaCollection.add(OutFileNames[EncodeTrack]);
End;
End;
Procedure Tcdrip.TrackgridHeaderClick(Sender: TObject; IsColumn: Boolean;
index: Integer);
Var row: integer;
Begin
If index = 2 Then
Begin
For row:=1 To Trackgrid.RowCount-1 Do
If Trackgrid.Cells[2, row]='' Then Trackgrid.Cells[2, row] := 'x'
Else Trackgrid.Cells[2, row] := '';
End;
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.TrackgridMouseDown(Sender: TOBject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
Begin
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.TrackgridSelectCell(Sender: TObject; Col, Row: Integer;
Var CanSelect: Boolean);
Begin
If col=2 Then If Trackgrid.Cells[2, row]='' Then Trackgrid.Cells[2, row] := 'x'
Else Trackgrid.Cells[2, row] := '';
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.encodecheckChange(Sender: TObject);
Begin
If EncodeCheck.Checked Then
Begin
writetagscheck.Enabled := true;
subfoldercheck.Enabled := true;
bitratebox.enabled := true;
End
Else
Begin
writetagscheck.Enabled := false;
subfoldercheck.Enabled := false;
bitratebox.enabled := false;
End;
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure Tcdrip.startButClick(Sender: TObject);
Var row, i: integer;
tmps : string;
Begin
outfolder := outputfolderbox.Items[outputfolderbox.ItemIndex];
If subfoldercheck.Checked Then outfolder := outfolder+DirectorySeparator+artistedit.Text;
If DirectoryExists(outfolder)=false Then mkdir(outfolder);
For i:= 1 To CDDBcon.NrTracks Do
Begin
If Trackgrid.Cells[2,i]='x' Then ToRip[i] := true;
End;
i := 0;
If encodecheck.Checked Then
begin
ToEncode := ToRip;
ToRemove := ToRip;
end;
Repeat
inc(i)
Until (ToRip[i]=true) Or (i>CDDBcon.NrTracks);
If i<=CDDBcon.NrTracks Then
Begin
If FileExists('/usr/bin/cdda2wav') Then
Begin {NOT PORTABLE!!!}
Trackgrid.Options:= Trackgrid.Options - [goEditing];
// Trackgrid.Enabled := false;
Trackgrid.Cells[2,i] := '0%';
ToRip[i] := false;
RipTrack := i;
str(i, tmps);
If i<10 Then tmps := '0'+tmps;
If paranoia.Checked Then
RipProcess.CommandLine := '/usr/bin/cdda2wav -paranoia -D'+CDDBcon.Device+' -t '+tmps+
' "'+outfolder+'/Track'+tmps+'.wav"'
Else
RipProcess.CommandLine := '/usr/bin/cdda2wav -D'+CDDBcon.Device+' -t '+tmps+' "'+
outfolder+'/Track'+tmps+'.wav"';
RipProcess.Options := [poUsePipes, poStderrToOutPut, poDefaultErrorMode];
DebugOutLn('Ripping Track '+tmps, 0);
Caption := 'Ripping Track '+tmps+' ...';
RipProcess.Execute;
Timer1.Enabled := true;
ripping := true;
End
Else ShowMessage(
'ERROR: cdda2wav executable not found. Please install cdda2wav package first...'
);
End
Else If MessageDlg('No tracks selected. Rip complete disc?', mtWarning, mbOKCancel, 0)=mrOK Then
Begin
For row:=1 To Trackgrid.RowCount-1 Do
If Trackgrid.Cells[2, row]='' Then Trackgrid.Cells[2, row] := 'x'
Else Trackgrid.Cells[2, row] := '';
startButClick(Nil);
End;
End;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
initialization
{$I cdrip.lrs}
End.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes;
type
TGlobalVar = class
private
username: string;
syslog: TStringList;
public
constructor Create;
procedure setUserName(Name: String);
function getUserName: String;
procedure addLog(Desc: String);
function getSystemLog: TStrings;
function closeSystemLog: integer;
end;
implementation
// Constructor
constructor TGlobalVar.Create;
begin
Self.syslog := TStringList.Create;
// Load log file
Self.syslog.LoadFromFile('log.txt');
end;
// Set Username
procedure TGlobalVar.setUserName(Name: String);
begin
Self.username := Name;
end;
// Get Username
function TGlobalVar.getUserName;
begin
Result := Self.username;
end;
// Add log
procedure TGlobalVar.addLog(Desc: String);
begin
Self.syslog.Add( DateToStr(date) + ' ' + TimeToStr(time) + ' | ' + getUserName + ' | ' +Desc);
end;
// Get system log
function TGlobalVar.getSystemLog;
begin
Result := Self.syslog;
end;
// CLose system log
function TGlobalVar.closeSystemLog;
begin
// Save log to file
Self.syslog.SaveToFile('log.txt');
Result := 1;
end;
end.
|
unit PipeProc;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
const
DAT_LIMIT = 1100;
ASU1_BUFFER_LENGTH = 1024;
ARC_BUFFER_LENGTH = 4096;
ASU_TIMER_INTERVAL = 3757;
function InitpSD : Boolean; // создание пустого дескриптора безопасности
function InitEventPipes : Boolean; // создать события для обработки труб
procedure DspToDspServerProc(Param : Pointer); stdcall; //обработка трубы Dsp-Dsp (сервер)
procedure DspToDspClientProc(Param : Pointer); stdcall; //обработка трубы Dsp-Dsp (клиент)
procedure DspToARCProc(Param:Pointer);stdcall;//обработка трубы архива на удаленной машине
function SendDspToARC(Buf:pchar;Len:SmallInt):Boolean;//в буфер архива на удаленной машине
// новые переменные
var
delta, maxdelta : Double;
LastRsv : Double;
pSD : PSECURITY_DESCRIPTOR;
sa : SECURITY_ATTRIBUTES;
nDspToDspPipe : WideString;
hDspToDspPipe : THandle;
DspToDspBreak : Boolean; // требование прекращения обслуживания канала ДСП-ДСП
DspToDspEnabled : Boolean; // требование инициализации канала ДСП-ДСП
DspToDspConnected : Boolean; // признак наличия соединения с трубой канала ДСП-ДСП
DspToDspSucces : Boolean; // готовность полученных данных по каналу ДСП-ДСП
DspToDspPending : Boolean; // блокировка записи данных на время передачи по трубе
DspToDspOverLapWrt : TOVERLAPPED;
DspToDspOverLapRd : TOVERLAPPED;
hDspToDspEventWrt : THandle;
hDspToDspEventRd : THandle;
DspToDspType : Byte; // тип окончания канала (0- сервер, 1- клиент)
DspToDspThreadID : ULONG;
DspToDspParam : Pointer;
DspToDspBufRd : array[0..8191] of Char;
DspToDspBufWrt : array[0..8191] of Char;
DspToDspInputBuf : string; // входной буфер канала ДСП-ДСП
DspToDspOutputBuf : string; // выходной буфер канала ДСП-ДСП
DspToDspThread : THandle;
DspToArcThread : THandle;
DspToArcThreadID : ULONG;
DspToArcSucces : Boolean; // готовность полученных данных по каналу ДСП-АРХИВ
DspToArcPending : Boolean; // блокировка записи данных на время передачи по трубе
DspToArcConnected : Boolean; // признак наличия соединения с трубой канала ДСП-АРХИВ
DspToArcAdresatEn : Boolean; // признак доступности другого конца трубы
DspToArcEnabled : Boolean; // требование инициализации канала ДСП-АРХИВ
DspToArcParam : Pointer;
DspToArcBufRd : array[0..ARC_BUFFER_LENGTH-1] of Char;
DspToArcBufWrt : array[0..ARC_BUFFER_LENGTH-1] of Char;
DspToArcInputBuf : array[0..ARC_BUFFER_LENGTH-1] of Char; // входной буфер канала ДСП-АРХИВ
DspToArcInputBufPtr : Word; // указатель на конец данных в буфере приема
DspToArcOutputBuf : array[0..ARC_BUFFER_LENGTH-1] of Char; // выходной буфер канала ДСП-АРХИВ
DspToArcOutputBufPtr : Word; // указатель на кон
nDspToArcPipe : WideString;
hDspToArcPipe : THandle;
DspToArcOverLapRd : TOVERLAPPED;
hDspToArcEventWrt : THandle;
hDspToArcEventRd : THandle; //--------- событие подключения клиента к трубе ДСП-Архив
DspToArcOverLapWrt : TOVERLAPPED;
DspToArcBreak : Boolean; //--- требование прекращения обслуживания канала ДСП-АРХИВ
IsBreakKanalASU : Boolean; //------------ признак завершения обслуживания каналов АСУ
MsgError : string;
implementation
function InitpSD : Boolean; // создание пустого дескриптора безопасности
begin
result := false;
pSD := PSECURITY_DESCRIPTOR(LocalAlloc(LPTR,SECURITY_DESCRIPTOR_MIN_LENGTH));
if not Assigned(pSD) then exit;
if not InitializeSecurityDescriptor(pSD,SECURITY_DESCRIPTOR_REVISION) then
begin
LocalFree(HLOCAL(pSD));
exit;
end;
if not SetSecurityDescriptorDacl(pSD,true,nil,false) then
begin
LocalFree(HLOCAL(pSD));
exit;
end;
sa.nLength := sizeof(sa);
sa.lpSecurityDescriptor := pSD;
sa.bInheritHandle := true;
result := true;
end;
function InitEventPipes : Boolean; // создать события для обработки труб
begin
result := false;
hDspToDspEventWrt := CreateEventW(nil,false,false,nil);
if hDspToDspEventWrt = INVALID_HANDLE_VALUE then exit;
FillChar(DspToDspOverLapWrt,sizeof(OVERLAPPED),0);
DspToDspOverLapWrt.hEvent := hDspToDspEventWrt;
hDspToDspEventRd := CreateEventW(nil,false,false,nil);
if hDspToDspEventWrt = INVALID_HANDLE_VALUE then
begin
CloseHandle(hDspToDspEventWrt); exit;
end;
FillChar(DspToDspOverLapRd,sizeof(OVERLAPPED),0);
DspToDspOverLapRd.hEvent := hDspToDspEventRd;
result := true;
end;
//------------------------------------------------------------------------------
// обработчик потока обмена между серверами (серверная сторона)
procedure DspToDspServerProc(Param : Pointer); stdcall;
var cErr,bytesRead,cbTransRd,bytesWrite,cbTransWrt : Cardinal; exitLoop : boolean;
s : string; i : integer;
begin
DspToDspSucces := false;
DspToDspPending := true;
DspToDspConnected := false;
// создать экземпляр трубы
hDspToDspPipe := CreateNamedPipeW(pWideChar(nDspToDspPipe),
PIPE_TYPE_BYTE or PIPE_ACCESS_DUPLEX or FILE_FLAG_OVERLAPPED,
PIPE_READMODE_BYTE or PIPE_NOWAIT,
PIPE_UNLIMITED_INSTANCES,
8192,
8192,
50,
@sa);
if hDspToDspPipe = INVALID_HANDLE_VALUE then
begin // не удалось создать трубу - выход
MsgError := 'ErrorCode='+ IntToStr(GetLastError)+ ' Hand='+IntToStr(hDspToDspPipe);
ExitThread(0);
exit;
end else
begin // труба создана - подключиться со стороны сервера
// запустить поток обслуживания канала
exitLoop := false;
end;
repeat
if DspToDspConnected then
begin // прочитать трубу если есть подключение к трубе
// прочитать трубу
if not ReadFile(hDspToDspPipe,DspToDspBufRd,512,bytesRead,@DspToDspOverLapRd) then
begin
cErr := GetLastError;
case cErr of
ERROR_PIPE_LISTENING :
begin // ожидается подключение к трубе с клиентской стороны
MsgError := 'Ожидание подключения клиента';
WaitForSingleObject(hDspToDspEventRd,100); // ожидать данные
end;
ERROR_NO_DATA :
begin
MsgError := 'Ожидание данных от клиента';
DspToDspPending := false;
WaitForSingleObject(hDspToDspEventRd,100); // ожидать данные
end;
ERROR_IO_PENDING :
begin
MsgError := 'Ожидание данных от клиента';
DspToDspPending := false;
WaitForSingleObject(hDspToDspEventRd,197); // ожидать данные
CancelIO(hDspToDspEventRd);
end;
else
MsgError := 'Read -> ErrorCode='+ IntToStr(cErr)+ ' Hand='+IntToStr(hDspToDspPipe);
exitLoop := true; // завершить обслуживание потока при поломке трубы
end;
end;
if not exitLoop then
begin
GetOverlappedResult(hDspToDspPipe,DspToDspOverLapRd,cbTransRd,false);
if cbTransRd <> 0 then
begin //-------------------------------------------------- передать готовые данные
if LastRsv > 0.00000000001 then
begin
delta := Time - LastRsv;
if delta > maxdelta then maxdelta := delta;
end;
LastRsv := Time;
// прочитать входные данные
s := '';
for i := 0 to cbTransRd-1 do s := s + DspToDspBufRd[i]; // Скопировать символы из буфера в строку
if s <> '' then
begin
DspToDspInputBuf := DspToDspInputBuf + s;
end;
cbTransRd := 0;
DspToDspSucces := true;
end;
// записать выходные данные
if DspToDspPending then
begin
DspToDspPending := not GetOverlappedResult(hDspToDspPipe,DspToDspOverLapWrt,cbTransWrt,false);
end else
if DspToDspOutputBuf <> '' then
begin
i := Length(DspToDspOutputBuf);
if i > Length(DspToDspBufWrt) then i := Length(DspToDspBufWrt);
if i > 0 then
begin
Move(DspToDspOutputBuf[1], DspToDspBufWrt, i);
MsgError := 'Write-> отправлено '+ IntToStr(i)+ ' байт';
DspToDspOutputBuf := '';
if not WriteFile( hDspToDspPipe, DspToDspBufWrt, i, bytesWrite, @DspToDspOverLapWrt) then // Записать в трубу
begin
cErr := GetLastError;
case cErr of
ERROR_IO_PENDING :
begin
MsgError := 'Write -> ERROR_IO_PENDING Hand='+IntToStr(hDspToDspPipe);
DspToDspPending := true;
end;
else
MsgError := 'Write -> ErrorCode='+ IntToStr(cErr)+ ' Hand='+IntToStr(hDspToDspPipe);
exitLoop := true; // завершить обслуживание потока при поломке трубы
end;
end;
end;
end;
end;
end else
begin // попытаться подключиться к трубе с серверной стороны
if ConnectNamedPipe(hDspToDspPipe,@DspToDspOverLapRd) then
begin // подсоединение с трубой состоялось
MsgError := 'Connect -> Выполнено подключение '+ TimeToStr(Time)+ ' Hand='+IntToStr(hDspToDspPipe);
DspToDspConnected := true;
DspToDspPending := false;
DspToDspOutputBuf := '';
end else
begin // обработать ошибку подключения к трубе
cErr := GetLastError;
case cErr of
ERROR_IO_PENDING :
begin
DspToDspConnected := true;
MsgError := 'Connect -> ErrorCode=ERROR_IO_PENDING '+ TimeToStr(Time)+ ' Hand='+IntToStr(hDspToDspPipe);
exitLoop := true;
end;
ERROR_PIPE_LISTENING :
begin // ожидается подключение к трубе с клиентской стороны
MsgError := 'Connect -> Ожидание подключения к трубе '+ TimeToStr(Time)+ ' Hand='+IntToStr(hDspToDspPipe);
DspToDspConnected := true;
end;
ERROR_PIPE_CONNECTED :
begin // подключен клиент к трубе
MsgError := 'Connect -> ErrorCode=ERROR_PIPE_CONNECTED '+ TimeToStr(Time)+ ' Hand='+IntToStr(hDspToDspPipe);
DspToDspConnected := true;
end;
ERROR_NO_DATA :
begin // клиент закрыл трубу - требуется разорвать соединение
MsgError := 'Connect -> ErrorCode=ERROR_NO_DATA '+ TimeToStr(Time)+ ' Hand='+IntToStr(hDspToDspPipe);
exitLoop := true;
end;
else
MsgError := 'Connect -> ErrorCode='+ IntToStr(cErr)+ ' '+ TimeToStr(Time)+ ' Hand='+IntToStr(hDspToDspPipe);
exitLoop := true;
end;
end;
end;
if exitLoop or DspToDspBreak then
begin
DspToDspConnected := false;
DspToDspPending := true;
exitLoop := not DisconnectNamedPipe(hDspToDspPipe);
end;
until DspToDspBreak; // прекратить обслуживание трубы по запросу программы
ExitThread(0);
end;
procedure DspToDspClientProc(Param : Pointer); stdcall; // обработка трубы по чтению Dsp - Dsp (клиент)
var cErr,bytesRead,cbTransRd,bytesWrite,cbTransWrt : Cardinal; exitLoop : boolean;
s : string; i : integer;
begin
exitLoop := false;
DspToDspPending := false;
repeat
if DspToDspConnected then
begin // прочитать трубу если есть подключение к трубе
if not ReadFile(hDspToDspPipe,DspToDspBufRd,512,bytesRead,@DspToDspOverLapRd) then
begin
cErr := GetLastError;
case cErr of
ERROR_IO_PENDING :
begin
MsgError := 'Ожидание данных от сервера';
WaitForSingleObject(hDspToDspEventRd,195); // ожидать данные
CancelIO(hDspToDspEventRd);
end;
ERROR_BROKEN_PIPE :
begin
MsgError := 'Read -> ErrorCode='+ IntToStr(cErr)+ ' Hand='+ IntToStr(hDspToDspPipe);
exitLoop := true; // завершить обслуживание потока при поломке трубы
end;
else
MsgError := 'Read -> ErrorCode='+ IntToStr(cErr)+ ' Hand='+ IntToStr(hDspToDspPipe);
exitLoop := true;
end;
end;
if not exitLoop then
begin
GetOverlappedResult(hDspToDspPipe,DspToDspOverLapRd,cbTransRd,false);
if cbTransRd <> 0 then
begin // передать сигнал готовности данных
if LastRsv > 0.00000000001 then
begin
delta := Time - LastRsv;
if delta > maxdelta then maxdelta := delta;
end;
LastRsv := Time;
// прочитать входные данные
s := '';
for i := 0 to cbTransRd-1 do s := s + DspToDspBufRd[i]; // Скопировать символы из буфера в строку
if s <> '' then
begin
DspToDspInputBuf := DspToDspInputBuf + s;
end;
cbTransRd := 0;
DspToDspSucces := true;
end;
// записать выходные данные
if DspToDspPending then
begin
DspToDspPending := not GetOverlappedResult(hDspToDspPipe,DspToDspOverLapWrt,cbTransWrt,false);
end else
// обработать буфер передачи
if DspToDspOutputBuf <> '' then
begin
i := Length(DspToDspOutputBuf);
if i > Length(DspToDspBufWrt) then i := Length(DspToDspBufWrt);
if i > 0 then
begin
Move(DspToDspOutputBuf[1], DspToDspBufWrt, i);
DspToDspOutputBuf := '';
if not WriteFile( hDspToDspPipe, DspToDspBufWrt, i, bytesWrite, @DspToDspOverLapWrt) then // Записать в трубу
begin
cErr := GetLastError;
case cErr of
ERROR_IO_PENDING :
begin
MsgError := 'Write -> ERROR_IO_PENDING Hand='+IntToStr(hDspToDspPipe);
DspToDspPending := true;
end;
else
MsgError := 'Write -> ErrorCode='+ IntToStr(cErr)+ ' Hand='+IntToStr(hDspToDspPipe);
exitLoop := true; // завершить обслуживание потока при поломке трубы
end;
end;
end;
end;
end;
end else
begin // попытаться подключиться к трубе с клиентской стороны
hDspToDspPipe := CreateFileW(PWideChar(nDspToDspPipe),
GENERIC_WRITE or GENERIC_READ,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);
if hDspToDspPipe <> INVALID_HANDLE_VALUE then
begin // соединеие с трубой состоялось
DspToDspConnected := true;
DspToDspOutputBuf := '';
exitLoop := false;
end else
begin // обработать ошибку подключения к трубе
cErr := GetLastError;
case cErr of
ERROR_FILE_NOT_FOUND :
begin
MsgError := 'Connect -> попытка подключения к несуществующей трубе '+ TimeToStr(Time)+ ' Hand='+ IntToStr(hDspToDspPipe);
exitLoop := true;
end;
ERROR_SEEK_ON_DEVICE :
begin
MsgError := 'Connect -> попытка подключения к несуществующей трубе '+ TimeToStr(Time)+ ' Hand='+ IntToStr(hDspToDspPipe);
exitLoop := true;
end;
else
MsgError := 'Connect -> ErrorCode='+ IntToStr(cErr)+ ' '+ TimeToStr(Time)+ ' Hand='+ IntToStr(hDspToDspPipe);
exitLoop := true;
end;
end;
end;
if exitLoop or DspToDspBreak then
begin
DspToDspConnected := false;
DspToDspPending := false;
CloseHandle(hDspToDspPipe);
hDspToDspPipe := INVALID_HANDLE_VALUE;
if not DspToDspBreak then
WaitForSingleObject(hDspToDspEventRd,1000); // ожидать
end;
until DspToDspBreak;
// завершить обслуживание трубы со стороны клиента
ExitThread(0);
end;
//========================================================================================
//------ обработка трубы для сохранения архива на удаленной машине (серверный конец трубы)
//-------------------------------------------- функция потока для связи АРМа ДСП с архивом
procedure DspToARCProc(Param : Pointer); stdcall;
var
cErr,bytesRead,cbTransRd,bytesWrite,cbTransWrt,i : Cardinal;
exitLoop : boolean;
begin
DspToArcSucces := false;
DspToArcPending := true;
DspToArcConnected := false;
DspToArcAdresatEn := false;
DspToArcInputBufPtr := 0;
DspToArcOutputBufPtr := 0;
//-------------------------------------------------------------- создать экземпляр трубы
hDspToArcPipe := CreateNamedPipeW(pWideChar(nDspToArcPipe),
PIPE_TYPE_BYTE or PIPE_ACCESS_DUPLEX or FILE_FLAG_OVERLAPPED,
PIPE_READMODE_BYTE or PIPE_NOWAIT,
PIPE_UNLIMITED_INSTANCES,
ARC_BUFFER_LENGTH,
ARC_BUFFER_LENGTH,
50,
@sa);
if hDspToArcPipe = INVALID_HANDLE_VALUE then //- если не удалось создать трубу, то выход
begin ExitThread(0); exit; end
//------ если труба создана,подключиться со стороны сервера,запустить поток обслуживания
else exitLoop := false;
repeat //----------------------------------------------------------- главный цикл потока
if DspToArcConnected then //--------------------------- если есть подключение к архиву
begin //---------- прочитать трубу если есть подключение к трубе, и если ошибка чтения
if not ReadFile(hDspToArcPipe,DspToArcBufRd,ARC_BUFFER_LENGTH,bytesRead,@DspToArcOverLapRd) then
begin
cErr := GetLastError;
case cErr of
ERROR_PIPE_LISTENING : //---- ожидается подключение к трубе с клиентской стороны
begin
DspToArcAdresatEn := false;
WaitForSingleObject(hDspToArcEventRd,100); //------ ожидать подключение 100 мс
end;
ERROR_NO_DATA : //----------------------------------- нет данных, труба закрыта
begin
WaitForSingleObject(hDspToArcEventRd,100); //----------- ожидать данные 100 мс
DspToArcAdresatEn := true;
end;
ERROR_IO_PENDING : //---------------------------- включена асинхронная операция
begin
WaitForSingleObject(hDspToArcEventRd,INFINITE); //------------- ожидать данные
CancelIO(hDspToArcPipe);
DspToArcAdresatEn := true;
end;
else exitLoop := true; //------ завершить обслуживание потока при поломке трубы
end;
end;
if not exitLoop then //----------------------------------------- если труба в работе
begin
//---------------------------------------- проверить процесс чтения архивной трубы
GetOverlappedResult(hDspToArcPipe,DspToArcOverLapRd,cbTransRd,false);
if cbTransRd > 0 then //----------------------------- если есть прочитанные данные
begin
DspToArcAdresatEn := true;//выставить признак доступности данных из трубы архива
i := 0;
if DspToArcInputBufPtr + cbTransRd <= High(DspToArcInputBuf) then
begin
while i < cbTransRd do //------ побайтное чтение данных из буфера трубы архива
begin
DspToArcInputBuf[DspToArcInputBufPtr] := DspToArcBufRd[i];
inc(i);
inc(DspToArcInputBufPtr);
end;
cbTransRd := 0;
DspToArcSucces := true;
end;
end;
if DspToArcPending then //--- если установлена блокировка записи на время передачи
begin
DspToArcPending := //-- установить блокировку по инверсии события записи в трубу
not GetOverlappedResult(hDspToArcPipe,DspToArcOverLapWrt,cbTransWrt,false);
end else
if DspToArcOutputBufPtr > 0 then //-------------------- если нет блокировки записи
begin
Move(DspToArcOutputBuf,DspToArcBufWrt,DspToArcOutputBufPtr);
//------------------------------------------------------------- Записать в трубу
if WriteFile(hDspToArcPipe,DspToArcBufWrt,DspToArcOutputBufPtr,bytesWrite,@DspToArcOverLapWrt)
then DspToArcOutputBufPtr := 0 //------------------ если запись выполнена удачно
else
begin
cErr := GetLastError; //---------------------- если неудачно, получить причину
case cErr of
//------------------------------------------------- если операция в ожидании
ERROR_IO_PENDING : begin DspToArcOutputBufPtr:=0;DspToArcPending:=true;end;
//--------------------------------------- если не ожидание, то поломка трубы
else exitLoop := true; //--- завершить обслуживание потока при поломке трубы
end;
end;
end;
end;
end else //-------------------------------------- если нет подключения сервера к трубе
begin //-------------------------- попытаться подключиться к трубе с серверной стороны
if ConnectNamedPipe(hDspToArcPipe,@DspToArcOverLapRd) then //---------- если успешно
begin //------------------------------------------- подсоединение к трубе состоялось
DspToArcConnected := true; DspToArcPending := false; DspToArcAdresatEn := true;
end else
begin //---------- если неудачное подключение, обработать ошибку подключения к трубе
cErr := GetLastError;
case cErr of
ERROR_IO_PENDING : begin DspToArcConnected := true; exitLoop := true; end;
ERROR_PIPE_LISTENING : DspToArcConnected:=true;//------ ждем подключение клиента
ERROR_PIPE_CONNECTED : // ------------------------------- клиент уже подключился
begin
DspToArcConnected:=true;
DspToArcAdresatEn:=true;//------------------------- подключен клиент к трубе
end;
ERROR_NO_DATA :exitLoop := true;//-- клиент закрыл трубу - разорвать соединение
else exitLoop := true;
end;
end;
end;
if exitLoop or DspToDspBreak then
begin
DspToArcOutputBufPtr := 0; DspToArcConnected := false; DspToArcAdresatEn := false;
DspToArcPending := false; DspToArcSucces := false;
exitLoop := not DisconnectNamedPipe(hDspToArcPipe);
end;
until DspToArcBreak; //------------- прекратить обслуживание трубы по запросу программы
ExitThread(100);
end;
//========================================================================================
//------------------ Поместить данные в буфер канала сохранения архива на удаленной машине
function SendDspToARC(Buf : pchar; Len : SmallInt) : Boolean;
var
lBuf : SmallInt;
begin
result := false;
if (Len = 0) or (DspToArcOutputBufPtr + Len > ARC_BUFFER_LENGTH)
then exit; //------------------------- если данных нет или мало места в буфере, то выйти
lBuf := 0;
while lBuf < Len do
begin
DspToArcOutputBuf[DspToArcOutputBufPtr] := Buf[lBuf];
inc(lBuf);
inc(DspToArcOutputBufPtr);
end;
result := true;
end;
end.
|
{
Author: Jarl K. Holta
License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html)
Runtime datatype representations
}
unit xpr.none;
{$I express.inc}
interface
{$I objh.inc}
uses
SysUtils,
xpr.express,
xpr.objbase;
type
TNoneObject = class(TEpObject)
function Release: Boolean; override;
function Copy(gcGen:Byte=0): TEpObject; override;
function DeepCopy: TEpObject; override;
function AsBool: Boolean; override;
function AsInt: epInt; override;
function AsFloat: Double; override;
function AsString: epString; override;
procedure ASGN(other:TEpObject; var dest:TEpObject); override;
procedure EQ(other:TEpObject; var dest:TEpObject); override;
procedure NE(other:TEpObject; var dest:TEpObject); override;
procedure LT(other:TEpObject; var dest:TEpObject); override;
procedure GT(other:TEpObject; var dest:TEpObject); override;
procedure GE(other:TEpObject; var dest:TEpObject); override;
procedure LE(other:TEpObject; var dest:TEpObject); override;
procedure LOGIC_AND(other:TEpObject; var dest:TEpObject); override;
procedure LOGIC_OR(other:TEpObject; var dest:TEpObject); override;
procedure LOGIC_NOT(var dest:TEpObject); override;
end;
implementation
uses
xpr.utils,
xpr.errors,
xpr.mmgr,
xpr.bool;
function TNoneObject.Release: Boolean;
begin
Result := False;
end;
function TNoneObject.Copy(gcGen:Byte=0): TEpObject;
begin
Result := self;
end;
function TNoneObject.DeepCopy: TEpObject;
begin
Result := self;
end;
function TNoneObject.AsBool: Boolean;
begin
Result := False;
end;
function TNoneObject.AsInt: epInt;
begin
Result := 0;
end;
function TNoneObject.AsFloat: Double;
begin
Result := 0;
end;
function TNoneObject.AsString: epString;
begin
Result := 'None';
end;
procedure TNoneObject.ASGN(other:TEpObject; var dest:TEpObject);
begin
if (other is TNoneObject) then
(* do nothing *)
else
inherited;
end;
procedure TNoneObject.EQ(other:TEpObject; var dest:TEpObject);
begin
if other.ClassType = TNoneObject then SetBoolDest(dest, True)
else SetBoolDest(dest, False);
end;
procedure TNoneObject.NE(other:TEpObject; var dest:TEpObject);
begin
if other.ClassType = TNoneObject then SetBoolDest(dest, False)
else SetBoolDest(dest, True);
end;
procedure TNoneObject.LT(other:TEpObject; var dest:TEpObject);
begin
if other.ClassType = TNoneObject then SetBoolDest(dest, False)
else SetBoolDest(dest, True);
end;
procedure TNoneObject.GT(other:TEpObject; var dest:TEpObject);
begin
SetBoolDest(dest, False);
end;
procedure TNoneObject.LE(other:TEpObject; var dest:TEpObject);
begin
if other.ClassType = TNoneObject then SetBoolDest(dest, True)
else SetBoolDest(dest, False);
end;
procedure TNoneObject.GE(other:TEpObject; var dest:TEpObject);
begin
if other.ClassType = TNoneObject then SetBoolDest(dest, True)
else SetBoolDest(dest, False);
end;
procedure TNoneObject.LOGIC_AND(other:TEpObject; var dest:TEpObject);
begin
SetBoolDest(dest, False and other.AsBool);
end;
procedure TNoneObject.LOGIC_OR(other:TEpObject; var dest:TEpObject);
begin
SetBoolDest(dest, False or other.AsBool);
end;
procedure TNoneObject.LOGIC_NOT(var dest:TEpObject);
begin
SetBoolDest(dest, True);
end;
end.
|
unit usha;
{$MODE objfpc}
{$H+}
{(C) Coban (alex@ritlabs.com)}
interface
uses SHA,CryptoUtils;
const
HASH_INITIAL = $100; //Initial constant
HASH_SHA1 = HASH_INITIAL + $D;
{Errors}
HASH_NOERROR = 0;
HASH_UNK_TYPE = HASH_NOERROR + $1; //Unknown hash type
HASH_NIL_CONTEXT = HASH_NOERROR + $2; //Context unallocated
HASH_INV_CONTEXT = HASH_NOERROR + $3; //Invalid hash context
HASH_FR_ERROR = HASH_NOERROR + $4; //File read error
HASH_FO_ERROR = HASH_NOERROR + $5; //File open error
HASH_TEST_FAILED = HASH_NOERROR + $6; //Hash test error
{Current ammount of hash algorithms}
HASH_MAX_TYPES = + 4 ;
type
{Hash context}
PHashContext = ^THashContext;
THashContext = record
IntData: Pointer; {Reserved for internal use}
HashType: LongWord; {Hash type}
lParam: LongWord; {First Param}
wParam: LongWord; {Second Param}
end;
{Low-level hash functions}
function HashInit(Context: PHashContext; HashType: LongWord): LongWord;
function HashUpdate(Context: PHashContext; SrcBuf: Pointer; BufLen: LongWord): LongWord;
function HashFinal(Context: PHashContext; var DestHash: String): LongWord;
{High-level hash functions}
function HashStr(HashType: LongWord; SrcStr: String; var DestHash: String): LongWord;
function HashBuf(HashType: LongWord; SrcBuf: Pointer; BufLen: LongWord; var DestHash: String): LongWord;
{Misc. functions}
function HashErrorToStr(Error: LongWord): String;
function EnumHashTypes(StoreToArr: Pointer; MaxItems: LongWord): LongWord;
implementation
function HashInit(Context: PHashContext; HashType: LongWord): LongWord;
begin
if Context = nil then
begin
Result := HASH_NIL_CONTEXT;
Exit;
end;
Context^.HashType := HashType;
Result := HASH_NOERROR;
case HashType of
HASH_SHA1:
begin
GetMem(Context^.IntData, SizeOf(TSHA256Ctx));
if HashType = HASH_SHA1 then
SHA1Init(PSHA256Ctx(Context^.IntData)^)
else
SHA256Init(PSHA256Ctx(Context^.IntData)^);
end;
else
Result := HASH_UNK_TYPE;
end;
end;
function HashUpdate(Context: PHashContext; SrcBuf: Pointer; BufLen: LongWord): LongWord;
begin
Result := HASH_NOERROR;
if Context = nil then
begin
Result := HASH_NIL_CONTEXT;
Exit;
end;
if Context^.IntData = nil then
begin
Result := HASH_INV_CONTEXT;
Exit;
end;
case Context^.HashType of
HASH_SHA1: SHA256Update(PSHA256Ctx(Context^.IntData)^, SrcBuf, BufLen, 1);
else
Result := HASH_UNK_TYPE;
end;
end;
function HashFinal(Context: PHashContext; var DestHash: String): LongWord;
begin
if Context = nil then
begin
Result := HASH_NIL_CONTEXT;
Exit;
end;
Result := HASH_NOERROR;
case Context^.HashType of
HASH_SHA1:
begin
if Context^.HashType = HASH_SHA1 then
DestHash := SHA256Final(PSHA256Ctx(Context^.IntData)^, 1)
else
DestHash := SHA256Final(PSHA256Ctx(Context^.IntData)^, 256);
FreeMem(Context^.IntData, SizeOf(TSHA256Ctx));
Context^.IntData := nil;
end;
else
Result := HASH_UNK_TYPE;
end;
end;
function HashStr(HashType: LongWord; SrcStr: String; var DestHash: String): LongWord;
var
ctx: THashContext;
begin
Result := HashInit(@ctx, HashType);
if Result = HASH_NOERROR then
Result := HashUpdate(@ctx, PChar(SrcStr), Length(SrcStr));
if Result = HASH_NOERROR then
Result := HashFinal(@ctx, DestHash);
end;
function HashBuf(HashType: LongWord; SrcBuf: Pointer; BufLen: LongWord; var DestHash: String): LongWord;
var
ctx: THashContext;
begin
Result := HashInit(@ctx, HashType);
if Result = HASH_NOERROR then
Result := HashUpdate(@ctx, SrcBuf, BufLen);
if Result = HASH_NOERROR then
Result := HashFinal(@ctx, DestHash);
end;
function EnumHashTypes(StoreToArr: Pointer; MaxItems: LongWord): LongWord;
procedure AddToEnum(Value: LongWord; var Count: LongWord);
begin
if Count >= MaxItems then Exit;
PDWordArray(StoreToArr)^[Count] := Value;
Inc(Count);
end;
begin
Result := 0;
if MaxItems = 0 then
Exit;
if MaxItems > HASH_MAX_TYPES then
MaxItems := HASH_MAX_TYPES;
AddToEnum(HASH_SHA1, Result);
end;
function HashErrorToStr(Error: LongWord): String;
begin
case Error of
HASH_NOERROR: Result := 'No error';
HASH_UNK_TYPE: Result := 'Unknown hash type';
HASH_NIL_CONTEXT: Result := 'Hash context is null';
HASH_INV_CONTEXT: Result := 'Invalid hash context';
HASH_FR_ERROR: Result := 'Could not read file';
HASH_FO_ERROR: Result := 'Could not open file';
HASH_TEST_FAILED: Result := 'Hash test failed';
else
Result := 'Unknown error';
end;
end;
end.
|
unit TestViewModelFactory;
{$mode objfpc}{$H+}
interface
uses
SyncObjs, Contnrs, ViewModels;
type
TTestViewModelFactory = class
private
FSection : TCriticalSection;
FViewModels : TObjectList;
public
constructor Create();
class function Current() : TTestViewModelFactory;
destructor Destroy(); override;
function Get() : TTestViewModel;
end;
implementation
var
FFactory : TTestViewModelFactory;
class function TTestViewModelFactory.Current() : TTestViewModelFactory;
begin
Result := FFactory;
end;
constructor TTestViewModelFactory.Create();
begin
inherited;
FSection := TCriticalSection.Create();
FViewModels := TObjectList.Create();
end;
destructor TTestViewModelFactory.Destroy();
begin
FViewModels.Free();
FSection.Free();
inherited;
end;
function TTestViewModelFactory.Get() : TTestViewModel;
var
ViewModel : TTestViewModel;
begin
FSection.Enter();
try
if (FViewModels.Count = 0) then
begin
ViewModel := TTestViewModel.Create();
FViewModels.Add(ViewModel);
end;
Result := FViewModels[0] as TTestViewModel;
finally
FSection.Release();
end;
end;
initialization
FFactory := TTestViewModelFactory.Create();
finalization
FFactory.Free();
end.
|
unit UConexaoXE8;
interface
uses FireDAC.Comp.Client, System.SysUtils, System.IniFiles, Vcl.Forms,
FireDAC.Phys.IBWrapper, Vcl.Dialogs, FireDAC.Stan.Def, FireDAC.Phys.FB,
FireDAC.Comp.UI, FireDAC.Stan.Async;
type
TConexaoXE8 = class(TObject)
private { private declarations }
FConexao : TFDConnection;
FConexaoBANCOS : TFDConnection;
vgsDataBase, vgsUsuario, vgsSenha, vgsSQLDialect,
vgsServer, vgsDataBaseBANCOS, vgsUsuarioBANCOS, vgsSenhaBANCOS, vgsSQLDialectBANCOS,
vgsServerBANCOS : String;
protected { protected declarations }
public { public declarations }
constructor Create;
Function getConnection :TFDConnection;
Function getConnectionBancos : TFDConnection;
procedure LerIniConexao;
published { published declarations }
end;
implementation
{ TConexaoXE8 }
constructor TConexaoXE8.Create;
begin
LerIniConexao;
// Conexão com o FIREBIRD COMÉRCIO
FConexao := TFDConnection.Create(Application);
vgsDataBase := Copy(vgsDataBase, Length(vgsServer) + 2, Length(vgsDataBase));
FConexao.DriverName := 'FB';
FConexao.Params.Add('Database='+vgsDataBase);
FConexao.Params.Add('User_name='+vgsUsuario);
FConexao.Params.Add('Password='+vgsSenha);
FConexao.Params.Add('Protocol=TCPIP');
FConexao.Params.Add('Server='+vgsServer);
FConexao.Params.Add('SQLDialect='+vgsSQLDialect);
FConexao.Params.Add('CharacterSet=WIN1252');
try
FConexao.Open;
except
on e : EIBNativeException do
begin
ShowMessage('Não foi possível efetuar a conexão. Erro: ' +
e.Message);
FConexao := nil;
end;
end;
// Conexão com o FIREBIRD BANCOS
FConexaoBANCOS := TFDConnection.Create(Application);
vgsDataBaseBANCOS := Copy(vgsDataBaseBANCOS, Length(vgsServerBANCOS) + 2, Length(vgsDataBaseBANCOS));
FConexaoBANCOS.DriverName := 'FB';
FConexaoBANCOS.Params.Add('Database='+vgsDataBaseBANCOS);
FConexaoBANCOS.Params.Add('User_name='+vgsUsuarioBANCOS);
FConexaoBANCOS.Params.Add('Password='+vgsSenhaBANCOS);
FConexaoBANCOS.Params.Add('Protocol=TCPIP');
FConexaoBANCOS.Params.Add('Server='+vgsServerBANCOS);
FConexaoBANCOS.Params.Add('SQLDialect='+vgsSQLDialectBANCOS);
FConexaoBANCOS.Params.Add('CharacterSet=WIN1252');
try
FConexaoBANCOS.Open;
except
on e : EIBNativeException do
begin
ShowMessage('Não foi possível efetuar a conexão. Erro: ' +
e.Message);
FConexaoBANCOS := nil;
end;
end;
end;
function TConexaoXE8.getConnection: TFDConnection;
begin
Result := FConexao;
end;
function TConexaoXE8.getConnectionBancos: TFDConnection;
begin
Result := FConexaoBANCOS;
end;
procedure TConexaoXE8.LerIniConexao;
var
vlIni : TiniFile;
I: Integer;
begin
try
//Lendo INI Conexão COMÉRCIO
if FileExists(ExtractFilePath(Application.ExeName) + 'dbxconnections.ini') then
vlIni := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'dbxconnections.ini')
else
raise Exception.Create('Não foi possível localizar o arquivo "dbxconnections.ini" na pasta: '+ExtractFilePath(Application.ExeName));
vgsDataBase := vlIni.ReadString('FACILITE', 'Database', '');
vgsUsuario := vlIni.ReadString('FACILITE', 'User_Name', '');
vgsSenha := vlIni.ReadString('FACILITE', 'Password', '');
vgsSQLDialect := vlIni.ReadString('FACILITE', 'SQLDialect', '');
//Lendo INI Conexão BANCOS
if FileExists(ExtractFilePath(Application.ExeName) + 'Bancos\dbxconnections.ini') then
vlIni := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'Bancos\dbxconnections.ini')
else
raise Exception.Create('Não foi possível localizar o arquivo "dbxconnections.ini" na pasta: '+ExtractFilePath(Application.ExeName) + 'Bancos');
vgsDataBaseBANCOS := vlIni.ReadString('FACILITEBANCOS', 'Database', '');
vgsUsuarioBANCOS := vlIni.ReadString('FACILITEBANCOS', 'User_Name', '');
vgsSenhaBANCOS := vlIni.ReadString('FACILITEBANCOS', 'Password', '');
vgsSQLDialectBANCOS := vlIni.ReadString('FACILITEBANCOS', 'SQLDialect', '');
for I := 1 to Length(vgsDataBase) do
begin
if Copy(vgsDataBase, I, 1) <> ':' then
vgsServer := vgsServer + Copy(vgsDataBase, I, 1)
else
Break;
end;
for I := 1 to Length(vgsDataBaseBANCOS) do
begin
if Copy(vgsDataBaseBANCOS, I, 1) <> ':' then
vgsServerBANCOS := vgsServerBANCOS + Copy(vgsDataBaseBANCOS, I, 1)
else
Break;
end;
finally
if Assigned(vlIni) then
FreeAndNil(vlIni);
end;
end;
end.
|
unit l3TimeEstimation;
{
Tl3TimeEstimation - предназначен для оценки оставшегося времени в секундах.
Пример использования:
l_TimeEstimation := Tl3TimeEstimation.Create(100, 5); // дожидаемся 100, используются не более 5 последних значений
try
while (l_Percentage < 100) do // крутим долгий цикл
begin
VeryLongOperation; // Оооочень продолжительная операция
l_Percentage := GetCurrentPercentage; // вычисление текущего значения
l_TimeEstimation.CurrentValue(l_Percentage); // и его ввод.
if l_TimeEstimation.LeftToFinish(l_Secs) then // вычисление (оценка) секунд до достижения 100
Info := Format('%d secs to finish', [l_Secs]); // и отображение информации (то, ради чего все и сделано)
end;
finally
l3Free(l_TimeEstimation);
end;
}
{ $Id: l3TimeEstimation.pas,v 1.9 2013/04/24 09:35:37 lulin Exp $ }
// $Log: l3TimeEstimation.pas,v $
// Revision 1.9 2013/04/24 09:35:37 lulin
// - портируем.
//
// Revision 1.8 2010/03/16 17:34:06 lulin
// {RequestLink:197494962}.
// - используем более простого предка.
//
// Revision 1.7 2008/02/22 18:26:37 lulin
// - доперевёл списки на модель.
//
// Revision 1.6 2005/10/17 11:20:26 step
// добавлен метод для отладки (Tl3TimeEstimation.DumpToLog)
//
// Revision 1.5 2005/02/01 17:33:08 step
// no message
//
// Revision 1.4 2005/01/12 14:01:43 step
// переименование TTimeEstimation --> Tl3TimeEstimation
//
// Revision 1.3 2005/01/12 10:28:26 step
// замена Integer --> Int64
//
// Revision 1.2 2005/01/12 10:03:15 step
// переименования, оформление
//
// Revision 1.1 2005/01/11 17:00:04 step
// занесено в CVS
//
interface
uses
Classes,
{Contnrs,}
l3Base,
l3DynamicArrayEx,
l3ProtoObject
;
type
// te - сокр. TimeEstimation
TteNumber = Single;
PtePoint = ^TtePoint;
TtePoint = record
X, Y, X2, XY: TteNumber;
end;
TtePoints = class(Tl3ProtoObject)
private
f_Array: Tl3DynamicArrayEx;
f_Amount: Integer;
f_Last: Integer;
protected
procedure Cleanup; override;
procedure DumpToLog(aStream: TStream); // чисто для отладки
public
constructor Create(const aMaxAmount: Integer); reintroduce;
procedure Add(const aX, aY: TteNumber);
procedure CalcSums(var aS1, aSX, aSY, aSX2, aSXY: TteNumber);
property Amount: Integer read f_Amount;
end;
TteLine = class(Tl3ProtoObject)
private
f_Points: TtePoints;
protected
procedure Cleanup; override;
public
constructor Create(const aPointsAmount: Integer); reintroduce;
procedure AddPoint(const aX, aY: TteNumber);
function IsEmpty: Boolean;
function Extrapolate(const aY: TteNumber;
var aX: TteNumber): Boolean;
end;
Tl3TimeEstimation = class(Tl3ProtoObject)
private
f_FinishValue: TteNumber;
f_StartTime: TDateTime;
f_Line: TteLine;
function TimeToNum(aTime: TDateTime): TteNumber;
function NumToTime(aNum: TteNumber): TDateTime;
function TimeToSecs(aTime: TDateTime): Int64;
protected
procedure Cleanup; override;
public
constructor Create(const aFinishValue: TteNumber; // значение, достижение которого мы дожидаемся
const aValuesAmount: Integer // в расчетах используются только последние введенные значения.
// Это - их количество. Более старые - отбрасываются.
); reintroduce;
procedure CurrentValue(const aValue: TteNumber); // ввод очередного текущего значения
function LeftToFinish(out aSeconds: Int64): Boolean; // собственно оценка "оставшихся секунд".
// Возвращает ложь при невозможности вычислить.
procedure DumpToLog(aStream: TStream); // чисто для отладки
end;
implementation
uses
SysUtils, Math;
const
c_Zero = 0.0;
c_Epsilon = 0.0001;
c_EmptyPoint: TtePoint = (X: c_Zero;
Y: c_Zero;
X2: c_Zero;
XY: c_Zero);
{ TteLine }
procedure TteLine.AddPoint(const aX, aY: TteNumber);
begin
f_Points.Add(aX, aY);
end;
function TteLine.Extrapolate(const aY: TteNumber; var aX: TteNumber): Boolean;
var
l_S1, l_SX, l_SY, l_SX2, l_SXY: TteNumber;
l_D, l_Db, l_Dc: TteNumber;
l_B, l_C: TteNumber;
begin
Result := False;
if f_Points.Amount < 2 then
Exit;
f_Points.CalcSums(l_S1, l_SX, l_SY, l_SX2, l_SXY);
l_D := l_S1 * l_SX2 - l_SX * l_SX;
if IsZero(l_D, c_Epsilon) then
Exit;
l_Db := l_S1 * l_SXY - l_SX * l_SY;
l_Dc := l_SX2 * l_SY - l_SX * l_SXY;
l_B := l_Db / l_D;
l_C := l_Dc / l_D;
if IsZero(l_B, c_Epsilon) then
Exit;
aX := (aY - l_C) / l_B;
Result := True;
end;
constructor TteLine.Create(const aPointsAmount: Integer);
begin
inherited Create;
f_Points := TtePoints.Create(aPointsAmount);
end;
procedure TteLine.Cleanup;
begin
l3Free(f_Points);
inherited;
end;
function TteLine.IsEmpty: Boolean;
begin
Result := f_Points.Amount = 0;
end;
{ TtePoints }
procedure TtePoints.Add(const aX, aY: TteNumber);
begin
f_Last := (f_Last + 1) mod f_Array.Count;
f_Amount := Max(f_Amount, f_Last + 1);
with PtePoint(f_Array[f_Last])^ do
begin
X := aX;
Y := aY;
X2 := aX * aX;
XY := aX * aY;
end;
end;
procedure TtePoints.CalcSums(var aS1, aSX, aSY, aSX2, aSXY: TteNumber);
var
I: Integer;
begin
aS1 := f_Amount;
aSX := c_Zero;
aSY := c_Zero;
aSX2 := c_Zero;
aSXY := c_Zero;
for I := 0 to f_Amount - 1 do
with PtePoint(f_Array[I])^ do
begin
aSX := aSX + X;
aSY := aSY + Y;
aSX2 := aSX2 + X2;
aSXY := aSXY + XY;
end;
end;
procedure TtePoints.Cleanup;
begin
l3Free(f_Array);
inherited;
end;
constructor TtePoints.Create(const aMaxAmount: Integer);
var
I: Integer;
begin
inherited Create;
f_Array := Tl3DynamicArrayEx.Create(SizeOf(TtePoint));
f_Array.Count := Max(aMaxAmount, 2); // точек не может быть менее двух
for I := 0 to f_Array.Count - 1 do
PtePoint(f_Array[I])^ := c_EmptyPoint;
f_Amount := 0;
f_Last := -1;
end;
procedure TtePoints.DumpToLog(aStream: TStream);
procedure Log(const aStr: string);
begin
aStream.Write(aStr[1], aStream.Size);
end;
var
I: Integer;
begin
Log(SysUtils.Format('Кол-во точек: %d'#13#10, [f_Amount]));
for I := 0 to f_Amount - 1 do
with PtePoint(f_Array[I])^ do
Log(SysUtils.Format('%f ; %f'#13#10, [X, Y]));
end;
{ Tl3TimeEstimation }
constructor Tl3TimeEstimation.Create(const aFinishValue: TteNumber;
const aValuesAmount: Integer);
begin
inherited Create;
f_FinishValue := aFinishValue;
f_Line := TteLine.Create(aValuesAmount);
end;
function Tl3TimeEstimation.LeftToFinish(out aSeconds: Int64): Boolean;
var
l_FinishTime: TteNumber;
begin
try
Result := f_Line.Extrapolate(f_FinishValue, l_FinishTime);
except
Result := False;
end;
if Result then
begin
aSeconds := TimeToSecs(f_StartTime + NumToTime(l_FinishTime) - Time);
Result := aSeconds >= 0; // остаток времени не может быть отрицательным
end;
end;
function Tl3TimeEstimation.NumToTime(aNum: TteNumber): TDateTime;
begin
Result := aNum / (24 * 60 * 60);
end;
procedure Tl3TimeEstimation.CurrentValue(const aValue: TteNumber);
begin
if f_Line.IsEmpty then
f_StartTime := Time;
f_Line.AddPoint(TimeToNum(Time - f_StartTime), aValue);
end;
function Tl3TimeEstimation.TimeToNum(aTime: TDateTime): TteNumber;
begin
Result := aTime * 24 * 60 * 60;
end;
function Tl3TimeEstimation.TimeToSecs(aTime: TDateTime): Int64;
begin
Result := Round(aTime * 24 * 60 * 60);
end;
procedure Tl3TimeEstimation.Cleanup;
begin
l3Free(f_Line);
inherited;
end;
procedure Tl3TimeEstimation.DumpToLog(aStream: TStream);
begin
f_Line.f_Points.DumpToLog(aStream);
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit DBQuery;
interface
uses Windows, Messages, Classes, Db, Ora, DBQueryThread, OraClasses, OraBarConn, OraError, Forms;
const
// Query execution mode
MQM_SYNC = 0;
MQM_ASYNC = 1;
// Query status notification mode
MQN_EVENTPROC = 0; // via event procedure with Synchronize
MQN_WINMESSAGE = 1; // via window message WM_MYSQL_THREAD_NOTIFY
// Thread notification events
MQE_INITED = 0; // initialized
MQE_STARTED = 1; // query started
MQE_FINISHED = 2; // query finished
MQE_FREED = 3; // object removed from memory
// Query result codes
MQR_NOTHING = 0; // no result yet
MQR_SUCCESS = 1; // success
MQR_CONNECT_FAIL = 2; // done with error
MQR_QUERY_FAIL = 3; // done with error
MQR_CANCEL = 4;
type
TDBQuery = class;
TDBQueryNotificationEvent = procedure (ASender : TDBQuery; AEvent : Integer) of object;
TDBQuery = class
private
FQueryResult : TThreadResult;
FDBSession : TOraSession;
FDBDataset : TDataset;
FThreadID : Integer;
FSyncMode : Integer;
FQueryThread : TDBQueryThread;
FEventName : String;
FSql : String;
FOnNotify : TDBQueryNotificationEvent;
FRowsAffected: integer;
function GetNotificationMode: Integer;
function GetSessionID: Integer;
function GetComment: String;
function GetResult: Integer;
function GetHasresultSet: Boolean;
protected
public
constructor Create (AOwner : TComponent; ADBSession : TOraSession);
destructor Destroy (); override;
procedure Query (ASql : String; AMode : Integer = MQM_SYNC; ANotifyWndHandle : THandle = 0);
procedure SetDBDataset(ADataset : TDataset);
procedure PostNotification (AQueryResult : TThreadResult; AEvent : Integer);
procedure SetThreadResult(AResult : TThreadResult);
procedure Stop;
procedure SetRowsAffected(rows: integer);
property Result : Integer read GetResult; // Query result code
property Comment : String read GetComment; // Textual information about the query result, includes error description
property SessionID : Integer read GetSessionID; // Mysql Session ID
property DBSession : TOraSession read FDBSession;
property DBDataset : TDataset read FDBDataset; // Resultset
property HasResultset : Boolean read GetHasresultSet; // Indicator of resultset availability
property ThreadID : Integer read FThreadID; // Mysql query thread ID (on the clients os)
property Sql : String read FSql; // Query string
property EventName : String read FEventName; // Operating system event name used for blocking mode
property NotificationMode : Integer read GetNotificationMode;
property OnNotify : TDBQueryNotificationEvent read FOnNotify write FOnNotify; // Event procedure used in MQN_EVENTPROC notification mode
property RowsAffected: integer read FRowsAffected write FRowsAffected;
end;
function ExecQueryAsync(ASql : String; ADBSession : TOraSession; ANotifyProc : TDBQueryNotificationEvent = nil; AWndHandle : THandle = 0) : TDBQuery;
function ExecDBStatementBlocking(ASql : String; ADBSession : TOraSession; AWndHandle : THandle) : TDBQuery;
function ExecSQL(SQL, Msg: string; FOraSession: TOraSession; AWndHandle : THandle; var FRecCount: integer): boolean; overload;
function ExecSQL(SQL, Msg: string; FOraSession: TOraSession; AWndHandle : THandle): boolean; overload;
function ExecSQL(SQL, Msg: string; FOraSession: TOraSession): boolean; overload;
function ExecSQL(SQL, Msg: string; FOraSession: TOraSession; var FRecCount: integer): boolean; overload;
function ExecQuery(SQL, Msg: string; ResultDataSet: TDataSource; FOraSession: TOraSession): boolean; overload;
function ExecQuery(SQL, Msg: string; ResultDataSet: TDataSource; FOraSession: TOraSession; AWndHandle : THandle): boolean; overload;
implementation
uses
SysUtils,
Dialogs,
frmSchemaBrowser;
{******************************************************************************}
{ ExecSQL }
{******************************************************************************}
function ExecSQL(SQL, Msg: string; FOraSession: TOraSession; var FRecCount: integer): boolean;
begin
result := ExecSQL(SQL, Msg, FOraSession, TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).Handle, FRecCount);
end;
function ExecSQL(SQL, Msg: string; FOraSession: TOraSession): boolean;
begin
if TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild) <> nil then
result := ExecSQL(SQL, Msg, FOraSession, TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).Handle)
else
result := ExecSQL(SQL, Msg, FOraSession, Application.Handle);
end;
function ExecSQL(SQL, Msg: string; FOraSession: TOraSession; AWndHandle : THandle): boolean;
var
FRecCount: integer;
begin
result := ExecSQL(SQL, Msg, FOraSession , AWndHandle, FRecCount);
end;
function ExecSQL(SQL, Msg: string; FOraSession: TOraSession; AWndHandle : THandle; var FRecCount: integer): boolean;
var
qSQL : TDBQuery;
begin
qSQL := ExecQueryAsync(SQL, FOraSession, nil, AWndHandle); //TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).Handle);
while not (qSQL.Result >= 1) do Application.ProcessMessages;
if qSQL.Result in [MQR_CONNECT_FAIL,MQR_QUERY_FAIL] then
begin
MessageDlg(qSQL.Comment, mtError, [mbOK], 0 );
if Application.MainForm.ActiveMDIChild is TSchemaBrowserFrm then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).LogSQL(qSQL.Comment);
result := false;
end else
begin
if Msg <> '' then
begin
MessageDlg(Msg, mtInformation, [mbOK], 0 );
if Application.MainForm.ActiveMDIChild is TSchemaBrowserFrm then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).LogSQL(Msg);
end;
result := true;
if (qSQL.HasResultset) and (pos('count(*)',SQL)>0) then
FRecCount := qSQL.DBDataset.Fields[0].AsInteger;
end;
end;
{******************************************************************************}
{ ExecSQL }
{******************************************************************************}
function ExecQuery(SQL, Msg: string; ResultDataSet: TDataSource; FOraSession: TOraSession): boolean;
begin
if TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild) <> nil then
result := ExecQuery(SQL, Msg, ResultDataSet, FOraSession, TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).Handle)
else
result := ExecQuery(SQL, Msg, ResultDataSet, FOraSession, Application.Handle);
end;
function ExecQuery(SQL, Msg: string; ResultDataSet: TDataSource; FOraSession: TOraSession; AWndHandle : THandle): boolean;
var
qSQL : TDBQuery;
begin
qSQL := ExecQueryAsync(SQL, FOraSession, nil, AWndHandle);
while not (qSQL.Result >= 1) do Application.ProcessMessages;
if qSQL.Result in [MQR_CONNECT_FAIL,MQR_QUERY_FAIL] then
begin
MessageDlg(qSQL.Comment, mtError, [mbOK], 0 );
if Application.MainForm.ActiveMDIChild is TSchemaBrowserFrm then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).LogSQL(Msg);
result := false;
end else
begin
if Msg <> '' then
begin
MessageDlg(Msg, mtInformation, [mbOK], 0 );
if Application.MainForm.ActiveMDIChild is TSchemaBrowserFrm then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).LogSQL(Msg);
end;
result := true;
if (qSQL.HasResultset) then
ResultDataSet.DataSet := qSQL.DBDataset;
end;
end;
function ExecQueryAsync(ASql : String; ADBSession : TOraSession; ANotifyProc : TDBQueryNotificationEvent; AWndHandle : THandle) : TDBQuery;
begin
Result := TDBQuery.Create(nil, ADBSession);
Result.OnNotify := ANotifyProc;
Result.Query(ASql,MQM_ASYNC,AWndHandle);
end;
function ExecDBStatementBlocking(ASql : String; ADBSession : TOraSession; AWndHandle : THandle) : TDBQuery;
begin
Result := TDBQuery.Create(nil, ADBSession);
Result.Query(ASql,MQM_SYNC,AWndHandle);
end;
constructor TDBQuery.Create(AOwner: TComponent; ADBSession : TOraSession);
begin
FDBSession := ADBSession;
ZeroMemory (@FQueryResult,SizeOf(FQueryResult));
FSql := '';
FDBDataset := nil;
end;
destructor TDBQuery.Destroy;
begin
//FreeAndNil (FDBDataset);
// Only free the Session object if we first created it
inherited;
end;
function TDBQuery.GetComment: String;
begin
Result := FQueryResult.Comment;
end;
function TDBQuery.GetSessionID: Integer;
begin
Result := FQueryResult.SessionID;
end;
function TDBQuery.GetHasresultSet: Boolean;
begin
Result := FDBDataset <> nil;
end;
function TDBQuery.GetNotificationMode: Integer;
begin
if Assigned(FOnNotify) then
Result := MQN_EVENTPROC
else
Result := MQN_WINMESSAGE;
end;
function TDBQuery.GetResult: Integer;
begin
Result := 0;
try
if self = nil then exit;
Result := FQueryResult.Result;
except
end;
end;
procedure TDBQuery.PostNotification(AQueryResult: TThreadResult; AEvent : Integer);
begin
SetThreadResult(AQueryResult);
if
(FSyncMode = MQM_ASYNC) and
(AEvent in [MQE_INITED,MQE_STARTED,MQE_FINISHED,MQE_FREED]) and
Assigned(FOnNotify) then begin
//debug(Format('thr: Calling notify function, event type %d occurred.', [AEvent]));
FOnNotify(Self, AEvent);
end else begin
//debug(Format('thr: Not calling notify function, event type %d occurred.', [AEvent]));
end;
end;
procedure TDBQuery.Query(ASql: String; AMode: Integer; ANotifyWndHandle : THandle);
var
EventHandle : THandle;
begin
// create thread object
FQueryThread := TDBQueryThread.Create(Self, FDBSession, ASql, AMode);
FQueryThread.NotifyWndHandle := ANotifyWndHandle;
FThreadID := FQueryThread.ThreadID;
FEventName := 'DBManager'+'_'+IntToStr(FThreadID);
FSyncMode := AMode;
FSql := ASql;
case AMode of
MQM_SYNC:
begin
// create mutex
EventHandle := CreateEvent (nil,False,False,PChar(FEventName));
// exec query
//debug(Format('thr: Starting query thread %d', [FQueryThread.ThreadID]));
FQueryThread.Resume();
//debug(Format('thr: Waiting for query thread %d', [FQueryThread.ThreadID]));
WaitForSingleObject (EventHandle, INFINITE);
//debug(Format('thr: Done waiting for query thread %d', [FQueryThread.ThreadID]));
CloseHandle (EventHandle);
// read status
// free thread
end;
MQM_ASYNC:
begin
// exec query
//debug(Format('thr: Starting query thread %d', [FQueryThread.ThreadID]));
FQueryThread.Resume();
end;
end;
end;
procedure TDBQuery.Stop;
begin
if FQueryThread = nil then exit;
FQueryThread.Terminate;
try
FreeAndNil(FQueryThread);//ak
except
//on E: Exception do ShowMessage(E.Message);
end;
end;
procedure TDBQuery.SetDBDataset(ADataset: TDataset);
begin
FDBDataset := ADataset;
end;
procedure TDBQuery.SetThreadResult(AResult: TThreadResult);
begin
FQueryResult := AResult;
end;
procedure TDBQuery.SetRowsAffected(rows: integer);
begin
FRowsAffected := rows;
end;
end.
|
{*********************************************************************}
{ TGradientLabel component }
{ for Delphi & C++Builder }
{ }
{ written by }
{ TMS Software }
{ copyright © 2001 - 2012 }
{ Email : info@tmssoftware.com }
{ Web : http://www.tmssoftware.com }
{*********************************************************************}
unit GradientLabel;
{$I TMSDEFS.INC}
interface
uses
Windows, SysUtils, Classes, Graphics, StdCtrls
{$IFDEF DELPHIXE3_LVL}
, System.UITypes
{$ENDIF}
;
const
MAJ_VER = 1; // Major version nr.
MIN_VER = 2; // Minor version nr.
REL_VER = 0; // Release nr.
BLD_VER = 0; // Build nr.
// version history
// 1.1.1.0 : New : GradientDirection property added
// 1.2.0.0 : New : gtCenterLineNoOverlap gradienttype
type
TVAlignment = (vaTop,vaCenter,vaBottom);
TEllipsType = (etNone, etEndEllips, etPathEllips);
TGradientType = (gtFullHorizontal, gtFullVertical, gtBottomLine, gtCenterLine, gtTopLine);
TGradientOrientation = (goHorizontal, goVertical);
TGradientDirection = (gdLeftToRight, gdRightToLeft);
{$IFDEF DELPHIXE2_LVL}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TGradientLabel = class(TLabel)
private
{ Private declarations }
FColorTo: TColor;
FEllipsType: TEllipsType;
FValignment: TVAlignment;
FIndent: Integer;
FGradientType: TGradientType;
FTransparentText: Boolean;
FLineWidth: Integer;
FOrientation : TGradientOrientation;
FGradientDirection: TGradientDirection;
procedure SetOrientation(const Value: TGradientOrientation);
procedure SetColor(const Value: TColor);
procedure SetEllipsType(const Value: TEllipsType);
procedure SetVAlignment(const Value: TVAlignment);
procedure SetIndent(const Value: Integer);
procedure SetGradientType(const Value: TGradientType);
procedure SetTransparentText(const Value: Boolean);
procedure SetLineWidth(const Value: Integer);
procedure SetGradientDirection(const Value: TGradientDirection);
protected
{ Protected declarations }
procedure Paint; override;
function GetVersionComp: string;
procedure SetVersion(const Value: string);
function GetVersionNr: Integer;
function GetColor: TColor;
function GetColorTo: TColor;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure Loaded; override;
published
{ Published declarations }
property ColorTo: TColor read FColorTo write SetColor default clWhite;
property EllipsType: TEllipsType read FEllipsType write SetEllipsType;
property GradientType: TGradientType read FGradientType write SetGradientType;
property GradientDirection: TGradientDirection read FGradientDirection write SetGradientDirection;
property Indent: Integer read FIndent write SetIndent;
property LineWidth: Integer read FLineWidth write SetLineWidth default 2;
property Orientation : TGradientOrientation read FOrientation write SetOrientation;
property TransparentText: Boolean read FTransparentText write SetTransparentText;
property VAlignment: TVAlignment read FValignment write SetVAlignment;
property Version: string read GetVersionComp write SetVersion;
property Transparent default False;
end;
implementation
uses
Controls;
const
ALIGNSTYLE : array[TAlignment] of DWORD = (DT_LEFT, DT_RIGHT, DT_CENTER);
WORDWRAPSTYLE : array[Boolean] of DWORD = (DT_SINGLELINE, DT_WORDBREAK);
LAYOUTSTYLE : array[TTextLayout] of DWORD = (0,DT_VCENTER,DT_BOTTOM);
ELLIPSSTYLE : array[TEllipsType] of DWORD = (0,DT_END_ELLIPSIS,DT_PATH_ELLIPSIS);
ACCELSTYLE : array[Boolean] of DWORD = (DT_NOPREFIX,0);
VALIGNSTYlE : array[TVAlignment] of DWORD = (DT_TOP,DT_VCENTER,DT_BOTTOM);
procedure DrawGradient(Canvas: TCanvas; FromColor,ToColor: TColor; Steps: Integer;R:TRect; Direction: Boolean);
var
diffr,startr,endr: Integer;
diffg,startg,endg: Integer;
diffb,startb,endb: Integer;
iend: Integer;
rstepr,rstepg,rstepb,rstepw: Real;
i,stepw: Word;
begin
if Steps = 0 then
Steps := 1;
FromColor := ColorToRGB(FromColor);
ToColor := ColorToRGB(ToColor);
startr := (FromColor and $0000FF);
startg := (FromColor and $00FF00) shr 8;
startb := (FromColor and $FF0000) shr 16;
endr := (ToColor and $0000FF);
endg := (ToColor and $00FF00) shr 8;
endb := (ToColor and $FF0000) shr 16;
diffr := endr - startr;
diffg := endg - startg;
diffb := endb - startb;
rstepr := diffr / steps;
rstepg := diffg / steps;
rstepb := diffb / steps;
if Direction then
rstepw := (R.Right - R.Left) / Steps
else
rstepw := (R.Bottom - R.Top) / Steps;
with Canvas do
begin
for i := 0 to Steps - 1 do
begin
endr := startr + Round(rstepr*i);
endg := startg + Round(rstepg*i);
endb := startb + Round(rstepb*i);
stepw := Round(i*rstepw);
Pen.Color := endr + (endg shl 8) + (endb shl 16);
Brush.Color := Pen.Color;
if Direction then
begin
iend := R.Left + stepw + Trunc(rstepw) + 1;
if iend > R.Right then
iend := R.Right;
Rectangle(R.Left + stepw,R.Top,iend,R.Bottom)
end
else
begin
iend := R.Top + stepw + Trunc(rstepw)+1;
if iend > r.Bottom then
iend := r.Bottom;
Rectangle(R.Left,R.Top + stepw,R.Right,iend);
end;
end;
end;
end;
{ TGradientLabel }
constructor TGradientLabel.Create(AOwner: TComponent);
begin
inherited;
FLineWidth := 2;
FColorTo := clWhite;
AutoSize := False;
Transparent := False;
end;
{$WARNINGS OFF}
procedure TGradientLabel.Loaded;
begin
inherited;
end;
procedure TGradientLabel.Paint;
var
R,LR: TRect;
DrawStyle: DWORD;
tw: Integer;
gsteps: Integer;
rgn1,rgn2,rgn3: THandle;
lf : TLogFont;
tf : TFont;
LeftCoord : Integer;
TopCoord : Integer;
begin
R := GetClientRect;
Canvas.Font := Font;
DrawStyle := DT_LEFT or DT_EXPANDTABS;
DrawTextEx(Canvas.Handle,PChar(Caption),Length(Caption),R, DrawStyle or DT_CALCRECT, nil);
tw := R.Right - R.Left;
R := GetClientRect;
if GradientType = gtFullVertical then
gsteps := (R.Bottom - R.Top) div 4
else
gsteps := (R.Right - R.Left) div 4;
if gsteps < 32 then
gsteps := 32;
if not Transparent and (GradientType in [gtFullHorizontal,gtFullVertical]) then
begin
if (ColorTo <> clNone) then
begin
DrawGradient(Canvas,GetColor,GetColorTo,gsteps,R,GradientType = gtFullHorizontal);
end
else
begin
Canvas.Brush.Color := Color;
Canvas.Pen.Color := Color;
Canvas.Rectangle(R.Left,R.Top,R.Right,R.Bottom);
end;
end;
if (Orientation = goHorizontal) then
begin
case GradientType of
gtBottomLine: R.Top := R.Bottom - LineWidth;
gtTopLine: R.Bottom := R.Top + LineWidth;
gtCenterLine:
begin
R.Top := R.Top + (R.Bottom - R.Top - LineWidth) div 2;
R.Bottom := R.Top + LineWidth;
end;
end;
end
else
begin
case GradientType of
gtBottomLine: R.Left := R.Right - LineWidth;
gtTopLine: R.Right := R.Left + LineWidth;
gtCenterLine:
begin
R.Left := R.Left + (R.Right - R.Left - LineWidth) div 2;
R.Right := R.Left + LineWidth;
end;
end;
end;
if GradientType in [gtBottomLine, gtTopLine, gtCenterLine] then
begin
{clip out region}
if TransparentText then
begin
LR := R;
OffsetRect(LR,Left,Top);
rgn3 := CreateRectRgn(LR.Left,LR.Top,LR.Right,LR.Bottom);
case Alignment of
taLeftJustify:
begin
rgn1 := CreateRectRgn(LR.Left,LR.Top,LR.Left + Indent,LR.Bottom);
rgn2 := CreateRectRgn(LR.Left + Indent + tw,LR.Top, LR.Right,LR.Bottom);
CombineRgn( rgn3,rgn1,rgn2, RGN_OR);
end;
taRightJustify:
begin
rgn1 := CreateRectRgn(LR.Left,LR.Top,LR.Right - tw - Indent,LR.Bottom);
rgn2 := CreateRectRgn(LR.Right - Indent,LR.Top, LR.Right,LR.Bottom);
CombineRgn( rgn3,rgn1,rgn2, RGN_OR);
end;
taCenter:
begin
rgn1 := CreateRectRgn(LR.Left,LR.Top,LR.Left + ((LR.Right - LR.Left - tw) div 2) - 2,LR.Bottom);
rgn2 := CreateRectRgn(LR.Left + tw + ((LR.Right - LR.Left -tw) div 2),LR.Top, LR.Right,LR.Bottom);
CombineRgn( rgn3,rgn1,rgn2, RGN_OR);
end;
end;
SelectClipRgn(Canvas.Handle,rgn3);
end;
if (Orientation = goHorizontal) then
DrawGradient(Canvas,GetColor,GetColorTo,gsteps,R,true)
else
DrawGradient(Canvas, GetColorTo, GetColor, gsteps, R, false);
if TransparentText then
begin
SelectClipRgn(Canvas.Handle,0);
DeleteObject(rgn1);
DeleteObject(rgn2);
DeleteObject(rgn3);
end;
end;
R := GetClientRect;
Canvas.Brush.Style := bsClear;
DrawStyle := ALIGNSTYLE[Alignment] or WORDWRAPSTYLE[WordWrap] or DT_NOCLIP or
LAYOUTSTYLE[Layout] or ELLIPSSTYLE[FEllipsType] or ACCELSTYLE[ShowAccelChar] or
VALIGNSTYLE[VAlignment];
DrawStyle := DrawTextBiDiModeFlags(DrawStyle);
DrawStyle := DrawStyle or DT_EXPANDTABS;
if (Orientation = goHorizontal) then
begin
if Alignment = taLeftJustify then
R.Left := R.Left + Indent;
if Alignment = taRightJustify then
R.Right := R.Right - Indent;
end
else
begin
// if Layout = tlBottom then
if Alignment = taLeftJustify then
R.Bottom := R.Bottom - Indent;
// if Layout = tlTop then
if (Alignment = taRightJustify) then
R.Top := R.Top + Indent;
end;
if not Enabled then
begin
OffsetRect(R, 1, 1);
Canvas.Font.Color := clBtnHighlight;
DrawTextEx(Canvas.Handle,PChar(Caption),Length(Caption),R, DrawStyle, nil);
OffsetRect(R, -1, -1);
Canvas.Font.Color := clBtnShadow;
DrawTextEx(Canvas.Handle,PChar(Caption),Length(Caption),R, DrawStyle, nil);
end
else
begin
if (Orientation = goVertical) then
begin
case Layout of
tlTop:LeftCoord := R.Left;
tlCenter: LeftCoord := ((R.Right - R.Left) div 2) - Canvas.TextHeight(PChar(Caption)) div 2;
tlBottom: LeftCoord := R.Right - Canvas.TextHeight(Pchar(Caption));
end;
case Alignment of
taRightJustify : TopCoord := R.Top + Canvas.TextWidth(PChar(Caption));
taLeftJustify : TopCoord := R.Bottom;
taCenter: TopCoord := (R.Bottom - R.Top) div 2 + Canvas.TextWidth(PChar(Caption)) div 2;
end;
{
case Alignment of
taLeftJustify:LeftCoord := R.Left;
taCenter: LeftCoord := ((R.Right - R.Left) div 2) - Canvas.TextHeight(PChar(Caption)) div 2;
taRightJustify: LeftCoord := R.Right - Canvas.TextHeight(Pchar(Caption));
end;
case Layout of
tlTop : TopCoord := R.Top + Canvas.TextWidth(PChar(Caption));
tlBottom : TopCoord := R.Bottom;
tlCenter: TopCoord := (R.Bottom - R.Top) div 2 + Canvas.TextWidth(PChar(Caption)) div 2;
end;
}
tf := TFont.Create;
try
tf.Assign(Font);
GetObject(tf.Handle, sizeof(lf),@lf);
lf.lfEscapement := 900;
lf.lfOrientation := 900;
tf.Handle := CreateFontIndirect(lf);
Canvas.Font.Assign(tf);
Canvas.TextOut(LeftCoord,TopCoord,PChar(Caption));
// OffsetRect(R,Canvas.TextHeight(PChar(Caption)), Canvas.TextWidth(PChar(Caption)));
// DrawTextEx(Canvas.Handle,PChar(Caption),Length(Caption),R, DT_CALCRECT, nil);
finally
tf.Free;
end;
end
else
DrawTextEx(Canvas.Handle,PChar(Caption),Length(Caption),R, DrawStyle, nil);
end;
end;
{$WARNINGS ON}
procedure TGradientLabel.SetColor(const Value: TColor);
begin
FColorTo := Value;
Invalidate;
end;
procedure TGradientLabel.SetEllipsType(const Value: TEllipsType);
begin
if FEllipsType <> Value then
begin
FEllipsType := Value;
Invalidate;
end;
end;
procedure TGradientLabel.SetGradientDirection(const Value: TGradientDirection);
begin
FGradientDirection := Value;
invalidate;
end;
procedure TGradientLabel.SetGradientType(const Value: TGradientType);
begin
FGradientType := Value;
Invalidate;
end;
procedure TGradientLabel.SetIndent(const Value: Integer);
begin
FIndent := Value;
Invalidate;
end;
procedure TGradientLabel.SetLineWidth(const Value: Integer);
begin
FLineWidth := Value;
Invalidate;
end;
procedure TGradientLabel.SetOrientation(const Value: TGradientOrientation);
begin
FOrientation := Value;
Invalidate;
end;
procedure TGradientLabel.SetTransparentText(const Value: Boolean);
begin
FTransparentText := Value;
Invalidate;
end;
procedure TGradientLabel.SetVAlignment(const Value: TVAlignment);
begin
FValignment := Value;
Invalidate;
end;
function TGradientLabel.GetColor: TColor;
begin
Result := Color;
case GradientDirection of
gdRightToLeft: Result := ColorTo;
end;
end;
function TGradientLabel.GetColorTo: TColor;
begin
Result := ColorTo;
case GradientDirection of
gdRightToLeft: Result := Color;
end;
end;
function TGradientLabel.GetVersionComp: string;
var
vn: Integer;
begin
vn := GetVersionNr;
Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn)));
end;
function TGradientLabel.GetVersionNr: Integer;
begin
Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER));
end;
procedure TGradientLabel.SetVersion(const Value: string);
begin
end;
end.
|
// Original Author: Piotr Likus
// Replace Components Utilities
unit GX_ReplaceCompUtils;
{$I GX_CondDefine.inc}
interface
uses
Classes, TypInfo;
type
TPropInfoList = class(TList)
private
function GetItem(Index: Integer): PPropInfo;
procedure SetItem(Index: Integer; const Value: PPropInfo);
protected
FOwner: TObject;
public
function FindProperty(const APropName: string): Integer; virtual;
property Owner: TObject read FOwner write FOwner;
property Items[Index: Integer]: PPropInfo read GetItem write SetItem; default;
end;
function GetPropertyList(ClassInfo: PTypeInfo): TPropInfoList;
procedure GetPropertyNames(const AClassName: string; Items: TStrings);
function ClassLevel(SearchForClass, TestClass: TClass): Integer;
function IsStoredProperty(Instance: TObject; APropInfo: PPropInfo): Boolean;
function IsDefaultPropertyValue(Instance: TObject; APropInfo: PPropInfo): Boolean;
function FlatLine(const AText: string): string;
function EscapeStr(const AStr: string; AEscapeChar: Char): string;
function CSVAddItem(const ALine, AItem: string; ASepChar: Char = ','; AQuoteChar: Char = '"'): string;
function ExtractToken(var VStr: string; const Delimiter: string): string;
implementation
uses
Variants, GX_GenericUtils, SysUtils;
function FlatLine(const AText: string): string;
begin
Result := CompressWhiteSpace(AText);
end;
function EscapeStr(const AStr: string; AEscapeChar: Char): string;
var
i: Integer;
begin
Result := AStr;
i := Length(AStr);
while i >= 1 do
begin
if AStr[i] = AEscapeChar then
Insert(AEscapeChar, Result, i);
Dec(i);
end;
end;
function CSVAddItem(const ALine, AItem: string; ASepChar: Char; AQuoteChar: Char): string;
var
sItem: string;
begin
if (Pos(ASepChar, AItem)>0) or (Pos(AQuoteChar, AItem)>0) then
begin
sItem := EscapeStr(AItem, AQuoteChar);
sItem := AQuoteChar+sItem+AQuoteChar;
end
else // no quotes
sItem := AItem;
if ALine = '' then
Result := sItem
else
Result := ALine+ASepChar+sItem;
end;
function ExtractToken(var VStr: string; const Delimiter: string): string;
var
Idx: Integer;
begin
Idx := Pos(Delimiter, VStr);
if Idx > 0 then
begin
Result := Copy(VStr, 1, Idx-1);
VStr := Copy(VStr, Idx + Length(Delimiter),
Length(VStr)-Idx-Length(Delimiter)+1);
end
else
begin
Result := VStr;
VStr := '';
end;
end;
function GetPropertyList(ClassInfo : PTypeInfo): TPropInfoList;
var
i, PropCount: Integer;
PropList: PPropList;
begin
Assert(ClassInfo<>nil);
Result := TPropInfoList.Create;
try
PropCount := GetTypeData(ClassInfo)^.PropCount;
if PropCount > 0 then
begin
GetMem(PropList, PropCount * SizeOf(Pointer));
try
GetPropInfos(ClassInfo, PropList);
Result.Count := PropCount;
for i := 0 to PropCount - 1 do
Result.Items[i] := PropList[i];
finally
FreeMem(PropList);
end;
end;
except
FreeAndNil(Result);
end;
end;
procedure GetPropertyNames(const AClassName: string; Items: TStrings);
var
ClassPtr: TPersistentClass;
PropertyList: TPropInfoList;
i: Integer;
begin
Items.Clear;
ClassPtr := GetClass(AClassName);
if ClassPtr = nil then Exit;
PropertyList := GetPropertyList(ClassPtr.ClassInfo);
if PropertyList = nil then
Exit;
try
for i := 0 to PropertyList.Count-1 do
Items.Add(string(PropertyList.Items[i].Name));
finally
FreeAndNil(PropertyList);
end;
end;
function ClassLevel(SearchForClass, TestClass: TClass): Integer;
var
ClassRef: TClass;
begin
if (SearchForClass = nil) or (TestClass = nil) then
begin
Result := -1;
Exit;
end;
Result := 0;
ClassRef := SearchForClass;
while (ClassRef <> nil) and (not ClassRef.ClassNameIs(TestClass.ClassName)) do
begin
Inc(Result);
ClassRef := ClassRef.ClassParent;
end;
if ClassRef = nil then
Result := -1;
end;
function IsStoredProperty(Instance: TObject; APropInfo: PPropInfo): Boolean;
begin
Result := not IsDefaultPropertyValue(Instance, APropInfo);
if Result then
Result := TypInfo.IsStoredProp(Instance, APropInfo);
end;
// Based on D7 Classes.IsDefaultPropertyValue
function IsDefaultPropertyValue(Instance: TObject; APropInfo: PPropInfo): Boolean;
function IsDefaultOrdProp: Boolean;
var
Value: Longint;
Default: LongInt;
begin
Default := PPropInfo(APropInfo)^.Default;
Value := GetOrdProp(Instance, APropInfo);
Result := (Default <> LongInt($80000000)) and (Value = Default);
end;
function IsDefaultFloatProp: Boolean;
var
Value: Extended;
begin
Value := GetFloatProp(Instance, APropInfo);
Result := (Value = 0);
end;
function IsDefaultStrProp: Boolean;
var
Value: WideString;
begin
Value := GetWideStrProp(Instance, APropInfo);
Result := (Value = '');
end;
function IsDefaultVariantProp: Boolean;
var
Value: Variant;
begin
Value := GetVariantProp(Instance, APropInfo);
Result := VarIsClear(Value);
end;
function IsDefaultInt64Prop: Boolean;
var
Value: Int64;
begin
Value := GetInt64Prop(Instance, APropInfo);
Result := (Value = 0);
end;
function IsDefaultObjectProp: Boolean;
var
Obj: TObject;
begin
Obj := GetObjectProp(Instance, APropInfo);
Result := (Obj = nil);
end;
function IsDefaultMethodProp: Boolean;
var
Met: TMethod;
begin
Met := GetMethodProp(Instance, APropInfo);
Result := (Met.Code = nil);
end;
function IsDefaultInterfaceProp: Boolean;
var
Intf: IInterface;
begin
Intf := GetInterfaceProp(Instance, APropInfo);
Result := (Intf = nil);
end;
var
PropType: PTypeInfo;
begin
Result := True;
if APropInfo^.GetProc = nil then
Exit;
PropType := PPropInfo(APropInfo)^.PropType^;
case PropType^.Kind of
tkInteger, tkChar, tkEnumeration, tkSet:
Result := IsDefaultOrdProp;
tkFloat:
Result := IsDefaultFloatProp;
tkString, tkLString, tkWString {$IFDEF GX_VER200_up}, tkUString {$ENDIF}:
Result := IsDefaultStrProp;
tkVariant:
Result := IsDefaultVariantProp;
tkInt64:
Result := IsDefaultInt64Prop;
tkClass:
Result := IsDefaultObjectProp;
tkMethod:
Result := IsDefaultMethodProp;
tkInterface:
Result := IsDefaultInterfaceProp;
end;
end;
{ TPropInfoList }
function TPropInfoList.FindProperty(const APropName: string): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to Count-1 do
if string(Items[i].Name) = APropName then
begin
Result := i;
Break;
end;
end;
function TPropInfoList.GetItem(Index: Integer): PPropInfo;
begin
Result := PPropInfo(inherited Items[Index]);
end;
procedure TPropInfoList.SetItem(Index: Integer; const Value: PPropInfo);
begin
inherited Items[Index] := Value;
end;
end.
|
unit mainform;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
StdCtrls, Grids, EditBtn, ExtCtrls, ComCtrls, fpspreadsheetchart,
fpspreadsheetgrid, TAGraph, TASeries, TypInfo,
// FPSpreadsheet and supported formats
fpspreadsheet, fpsallformats
;
type
{ Tlazfpsmainform }
Tlazfpsmainform = class(TForm)
btnLoadSpreadsheet: TButton;
buttonReadCellInfo: TButton;
editSourceFile: TFileNameEdit;
labelCurCell: TLabel;
Label2: TLabel;
memoCellData: TMemo;
pagesSheets: TPageControl;
Panel1: TPanel;
procedure btnLoadSpreadsheetClick(Sender: TObject);
procedure buttonReadCellInfoClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ private declarations }
procedure HandleSelectionChanged(Sender: TObject; aCol, aRow: Integer);
public
{ public declarations }
Worksheets: array of TsWorksheetGrid;
Workbook: TsWorkbook;
procedure DeleteAllSheets();
end;
var
lazfpsmainform: Tlazfpsmainform;
implementation
{$R *.lfm}
{ Tlazfpsmainform }
procedure Tlazfpsmainform.btnLoadSpreadsheetClick(Sender: TObject);
var
lWorksheetCount: Cardinal;
lCurPage: TTabSheet;
lCurWorksheet: TsWorksheet;
i: Integer;
begin
if editSourceFile.Text = '' then Exit;
Workbook.ReadFromFile(editSourceFile.Text);
DeleteAllSheets();
lWorksheetCount := Workbook.GetWorksheetCount();
SetLength(Worksheets, lWorksheetCount);
for i := 0 to lWorksheetCount-1 do
begin
pagesSheets.AddTabSheet();
lCurPage := pagesSheets.Pages[i];
lCurWorksheet := Workbook.GetWorksheetByIndex(i);
Worksheets[i] := TsWorksheetGrid.Create(nil);
Worksheets[i].Parent := lCurPage;
Worksheets[i].Align := alClient;
//Worksheets[i].Options = [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect, goEditing, goSmoothScroll]
Worksheets[i].LoadFromWorksheet(lCurWorksheet);
Worksheets[i].OnSelection := @HandleSelectionChanged;
lCurPage.Caption := lCurWorksheet.Name;
end;
end;
procedure Tlazfpsmainform.buttonReadCellInfoClick(Sender: TObject);
var
lX, lY, lCurTab: LongInt;
lCurWorksheet: TsWorksheet;
lCurCell: PCell;
begin
lCurTab := pagesSheets.TabIndex;
lX := Worksheets[lCurTab].Selection.Left;
lY := Worksheets[lCurTab].Selection.Top;
lCurWorksheet := Workbook.GetWorksheetByIndex(lCurTab);
lCurCell := lCurWorksheet.GetCell(lY, lX);
memoCellData.Lines.Text := '';
memoCellData.Lines.Add(Format('Row: %d Col: %d (zero-based)', [lY, lX]));
memoCellData.Lines.Add(Format('ContentType: %s', [GetEnumName(TypeInfo(TCellContentType), integer(lCurCell^.ContentType))]));
memoCellData.Lines.Add(Format('NumberValue: %f', [lCurCell^.NumberValue]));
memoCellData.Lines.Add(Format('UTF8StringValue: %s', [lCurCell^.UTF8StringValue]));
//memoCellData.Lines.Add(Format('DateTimeValue: %s', [lCurCell^.DateTimeValue]));
//memoCellData.Lines.Add(Format('UsedFormattingFields: %f', [lCurCell^.NumberValue]));
memoCellData.Lines.Add(Format('TextRotation: %s', [GetEnumName(TypeInfo(TsTextRotation), integer(lCurCell^.TextRotation))]));
//memoCellData.Lines.Add(Format('Border: %f', [lCurCell^.NumberValue]));
memoCellData.Lines.Add(Format('BackgroundColor: %s', [GetEnumName(TypeInfo(TsColor), integer(lCurCell^.BackgroundColor))]));
memoCellData.Lines.Add('');
memoCellData.Lines.Add(Format('ReadAsUTF8Text(): %s', [lCurWorksheet.ReadAsUTF8Text(lY, lX)]));
end;
procedure Tlazfpsmainform.DeleteAllSheets;
var
i: Integer;
begin
for i := 0 to Length(Worksheets)-1 do
begin
Worksheets[i].Free;
pagesSheets.Pages[i].Free;
end;
SetLength(Worksheets, 0);
end;
procedure Tlazfpsmainform.FormCreate(Sender: TObject);
begin
Workbook := TsWorkbook.Create;
editSourceFile.InitialDir := ExtractFilePath(ParamStr(0));
end;
procedure Tlazfpsmainform.FormDestroy(Sender: TObject);
begin
Workbook.Free;
end;
procedure Tlazfpsmainform.HandleSelectionChanged(Sender: TObject; aCol,
aRow: Integer);
begin
labelCurCell.Caption := Format('Current Cell: Row=%d Col=%d', [ARow, ACol]);
end;
end.
|
unit unitMinesweeper;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, Forms, Dialogs, ExtCtrls, Graphics, unitminesweeperdefines;
type
TMinesweeperTimer = class(TThread)
protected
PTime: PInteger;
FOnInc: TMinesweeperTimeProc;
procedure UpdateTime;
procedure Execute; override;
public
constructor Create(Counter: PInteger; const OnInc: TMinesweeperTimeProc);
end;
TMinesweeper = class(TObject)
private
FLeft, FTop: integer;
FCellHW: integer;
FSizeH: integer;
FSizeW: integer;
FParent: PPanel;
FHover: TPoint;
FData: TMinesweeperData;
PWin, PLose: TMinesweeperResultProc;
PIncTime: TMinesweeperTimeProc;
PFlag: TMinesweeperFlagProc;
FSprites: TMinesweeperSprites;
FMines: integer;
FOpenedMax: integer;
FTimer: TMinesweeperTimer;
private
FFlagCount: integer;
FOpenedCount: integer;
FLoseState: boolean;
FWinState: boolean;
FTimeCount: int64;
FFirstClick: boolean;
private
procedure RevealBombs;
procedure CheckValidBoard;
procedure InitVariables;
procedure InitializeData;
procedure RandomizeMines(AvoidedX, AvoidedY: integer; AvoidedRadius: byte);
procedure WriteMinesHint;
procedure DrawBoard;
procedure OpenCell(x, y: integer); //recursively open cell
procedure OnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
procedure OnMouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer);
const
cvBomb = 9;
cvFlag = 10;
cvNormal = 11;
cvWrongFlag = 12;
cvHover = 13;
SpritesDir = 'sprites';
FAvoidedRadius = 1;
public
GameRunning: boolean;
property OnWin: TMinesweeperResultProc write PWin;
property OnLose: TMinesweeperResultProc write PLose;
property OnTimeInc: TMinesweeperTimeProc write PIncTime;
property OnFlag: TMinesweeperFlagProc write PFlag;
procedure StartGame(SizeH, SizeW, Mines: integer);
procedure StopGame;
procedure AutoFit(FromDrawBoard: boolean = False);
destructor Destroy; override;
constructor Create(Parent: PPanel);
end;
implementation
procedure TMinesweeper.OnMouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer);
var
ax, ay, bx, by: integer;
CellRect: TRect;
begin
if FloseState or FWinState then
exit;
if (x < FLeft) or (x > (FLeft + FCellHW * FSizeW)) then
exit;
if (y < FTop) or (y > (FTop + FCellHW * FSizeh)) then
exit;
ax := (x - FLeft) div FCellHW;
ay := (y - FTop) div FCellHW;
if Fdata[ay, ax].opened or Fdata[ay, ax].flagged then
exit;
bx := FLeft + ax * FCellHW;
by := FTop + ay * FcellHw;
if (FHover.x <> ax) or (FHover.y <> ay) then
begin
CellRect.Top := by;
CellRect.Left := bx;
CellRect.Bottom := CellRect.Top + FCellHW;
CellRect.Right := CellRect.Left + FCellHW;
FParent^.Canvas.StretchDraw(CelLRect, FSprites[cvHover].Graphic);
if not (Fdata[fhover.y, fhover.x].opened or Fdata[fhover.y, fhover.x].flagged) then
begin
CellRect.Top := FTop + FHover.y * FcellHw;
CellRect.Left := FLeft + FHover.x * FCellHW;
CellRect.Bottom := CellRect.Top + FCellHW;
CellRect.Right := CellRect.Left + FCellHW;
FParent^.Canvas.StretchDraw(CellRect, FSprites[cvNormal].Graphic);
end;
FHover.x := ax;
FHover.y := ay;
end;
end;
procedure TMinesweeper.AutoFit(FromDrawBoard: boolean = False);
var
parentH, parentW: integer;
begin
parentH := FParent^.Canvas.Height;
parentW := FParent^.Canvas.Width;
if (Parenth div FSizeH) > (parentw div FSizeW) then
FCellHW := (ParentW div FSizeW)
else
FCellHW := (ParentH div FSizeH);
FLeft := (ParentW - FSizeW * FCellHW) div 2;
FTop := (ParentH - FSizeH * FCellHW) div 2;
if not fromdrawboard then
DrawBoard;
end;
procedure TMinesweeper.RevealBombs;
var
CellRect: TRect;
x, y: integer;
begin
for y := 0 to High(FData) do
for x := 0 to high(FData[y]) do
begin
if (FData[y, x].CellValue = cvBomb) and not (FData[y, x].Flagged) then
begin
CellRect.Top := FTop + y * FcellHw;
CellRect.Left := FLeft + x * FCellHW;
CellRect.Bottom := CellRect.Top + FCellHW;
CellRect.Right := CellRect.Left + FCellHW;
FParent^.Canvas.StretchDraw(CellRect, FSprites[cvBomb].Graphic);
end
else if (FData[y, x].CellValue <> cvBomb) and (FData[y, x].Flagged) then
begin
CellRect.Top := FTop + y * FcellHw;
CellRect.Left := FLeft + x * FCellHW;
CellRect.Bottom := CellRect.Top + FCellHW;
CellRect.Right := CellRect.Left + FCellHW;
FParent^.Canvas.StretchDraw(CellRect, FSprites[cvWrongFlag].Graphic);
end;
end;
end;
procedure TMinesweeper.InitializeData;
begin
TImage(FParent^).OnMouseUp := @OnMouseUp;
SetLength(FData, FSizeH, FSizeW);
FParent^.Canvas.Brush.Color := clBlack;
FParent^.Canvas.FillRect(0, 0, FParent^.Canvas.Width, FParent^.Canvas.Height);
end;
procedure TMinesweeper.InitVariables;
var
i, j: integer;
begin
FOpenedCount := 0;
FTimeCount := 0;
FFlagCount := 0;
FWinState := False;
FLoseState := False;
FFlagCount := 0;
FFirstClick := True;
for i := 0 to FSizeH - 1 do
for j := 0 to FSizeW - 1 do
begin
Fdata[i, j].Opened := False;
Fdata[i, j].Flagged := False;
Fdata[i, j].CellValue := 0;
end;
end;
procedure TMinesweeper.OpenCell(x, y: integer);
var
CellRect: TRect;
begin
if not (FWinState or FLoseState) then
if not ((x = -1) or (y = -1) or (x = FSizeW) or (y = FSizeH)) then
begin
CellRect.Top := FTop + y * FcellHw;
CellRect.Left := FLeft + x * FCellHW;
CellRect.Bottom := CellRect.Top + FCellHW;
CellRect.Right := CellRect.Left + FCellHW;
if FData[y, x].Flagged then
exit;
if (FData[y, x].Opened) then
exit;
Inc(FOpenedCount);
if (FData[y, x].cellValue = 0) then
begin
FParent^.Canvas.StretchDraw(CellRect, FSprites[Fdata[y, x].cellValue].Graphic);
FData[y, x].opened := True;
OPenCell(x - 1, y - 1);
OPenCell(x - 1, y);
OPenCell(x - 1, y + 1);
OPenCell(x, y - 1);
OPenCell(x, y + 1);
OPenCell(x + 1, y - 1);
OPenCell(x + 1, y);
OPenCell(x + 1, y + 1);
end
else if (FData[y, x].cellValue <> cvBomb) then
begin
FParent^.Canvas.StretchDraw(CellRect, FSprites[Fdata[y, x].cellValue].Graphic);
FData[y, x].Opened := True;
end
else
begin
FData[y, x].Opened := True;
FParent^.Canvas.StretchDraw(CellRect, FSprites[cvBomb].Graphic);
FLoseState := True;
StopGame;
end;
end;
if (FOpenedCount = FOpenedMax) and not (FWinState) then
begin
FWinState := True;
StopGame;
end;
end;
procedure TMinesweeper.StopGame;
begin
GameRunning := False;
if Assigned(FTimer) then
FTimer.Terminate;
if FLoseState then
begin
RevealBombs;
PLose(FTimeCount);
end
else if FWinState then
PWin(FTimeCount);
end;
procedure TMinesweeper.OnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
function CheckCell(x, y: integer): boolean;
begin
if (x = -1) or (y = -1) or (x = FSizeW) or (y = FSizeH) then
begin
Result := False;
exit;
end;
Result := FData[y, x].Flagged;
end;
function CheckTotal(x, y: integer): integer;
var
tmp: integer;
begin
tmp := 0;
if CheckCell(x - 1, y - 1) then
Inc(tmp);
if CheckCell(x - 1, y) then
Inc(tmp);
if CheckCell(x - 1, y + 1) then
Inc(tmp);
if CheckCell(x, y - 1) then
Inc(tmp);
if CheckCell(x, y + 1) then
Inc(tmp);
if CheckCell(x + 1, y - 1) then
Inc(tmp);
if CheckCell(x + 1, y) then
Inc(tmp);
if CheckCell(x + 1, y + 1) then
Inc(tmp);
Result := tmp;
end;
var
bx, by, ax, ay: integer;
CellRect: TRect;
begin
if (x < FLeft) or (x > (FLeft + FCellHW * FSizeW)) then
exit;
if (y < FTop) or (y > (FTop + FCellHW * FSizeh)) then
exit;
if FloseState or FWinState then
exit;
ax := (x - FLeft) div FCellHW;
ay := (y - FTop) div FCellHW;
bx := FLeft + ax * FCellHW;
by := FTop + ay * FcellHw;
if Button = mbLeft then
begin
if FData[ay, ax].Flagged then
exit;
if FData[ay, ax].opened then
if CheckTotal(ax, ay) = FData[ay, ax].CellValue then
begin
OpenCell(ax - 1, ay - 1);
OpenCell(ax - 1, ay);
OpenCell(ax - 1, ay + 1);
OpenCell(ax, ay - 1);
OpenCell(ax, ay + 1);
OpenCell(ax + 1, ay - 1);
OpenCell(ax + 1, ay);
OpenCell(ax + 1, ay + 1);
end;
if FFirstClick then
begin
RandomizeMines(ax, ay, 1);
WriteMinesHint;
FFirstClick := False;
FTimer := TMinesweeperTimer.Create(@FTimeCount, PIncTime);
end;
OpenCell(ax, ay);
end
else
begin
if not FData[ay, ax].Opened then
begin
CellRect.Top := by;
CellRect.Left := bx;
CellRect.Bottom := by + FCellHW;
CellRect.Right := bx + FCellHW;
if FData[ay, ax].flagged then
begin
FData[ay, ax].flagged := False;
FParent^.Canvas.StretchDraw(CellRect, FSprites[cvNormal].Graphic);
Dec(FFlagCount);
PFlag(FFlagCount, FMines - FFlagCount);
end
else
begin
FData[ay, ax].flagged := True;
FParent^.Canvas.StretchDraw(CellRect, FSprites[cvFlag].Graphic);
Inc(FFlagCount);
PFlag(FFlagCount, FMines - FFlagCount);
end;
end;
end;
end;
procedure TMinesweeper.DrawBoard;
var
x, y: integer;
CellRect: TRect;
begin
AutoFit(True);
for y := 0 to FSizeH - 1 do
for x := 0 to FSizeW - 1 do
begin
CellRect.Left := FLeft + (FCellHW * x);
CellRect.Top := FTop + (FCellHW * y);
CellRect.Bottom := FTop + (FCellHW * y) + FCellHW;
CellRect.Right := FLeft + (FCellHW * x) + FCellHW;
FParent^.Canvas.StretchDraw(CellRect, FSprites[cvNormal].Graphic);
end;
end;
procedure TMinesweeper.RandomizeMines(AvoidedX, AvoidedY: integer; AvoidedRadius: byte);
var
i, y, x: integer;
avzonex, avzoney: boolean;
begin
for i := 0 to FMines - 1 do
begin
randomize;
while True do
begin
avzonex := False;
avzoney := False;
x := Random(FSizeW);
y := random(FSizeH);
if (AvoidedX - AvoidedRadius <= x) and (AVoidedX + AVoidedRadius >= x) then
avzonex := True;
if (Avoidedy - AvoidedRadius <= y) and (AVoidedy + AVoidedRadius >= y) then
avzoney := True;
if avzonex and avzoney then
continue;
if FData[y, x].cellvalue = cvbomb then
continue;
FData[y, x].cellValue := cvbomb;
break;
end;
end;
end;
procedure TMinesweeper.CheckValidBoard;
begin
if not (FSizeH * FSizeW - (FAvoidedRadius * 2 + 1) * (FAvoidedRadius * 2 + 1) > FMines) then
raise Exception.Create('Mines total is more than the board size.');
end;
procedure TMinesweeper.WriteMinesHint;
function CheckCell(y, x: integer): boolean;
begin
if (x = -1) or (y = -1) or (x = FSizeW) or (y = FSizeH) then
begin
Result := False;
exit;
end;
Result := FData[y, x].cellvalue = cvbomb;
end;
var
x, y: integer;
begin
for y := 0 to FSizeH - 1 do
for x := 0 to FSizeW - 1 do
begin
if FData[y, x].cellvalue <> cvbomb then
begin
FData[y, x].CellValue := 0;
if CheckCell(y - 1, x - 1) then
Inc(FData[y, x].CellValue);
if CheckCell(y - 1, x) then
Inc(FData[y, x].CellValue);
if CheckCell(y - 1, x + 1) then
Inc(FData[y, x].CellValue);
if CheckCell(y, x - 1) then
Inc(FData[y, x].CellValue);
if CheckCell(y, x + 1) then
Inc(FData[y, x].CellValue);
if CheckCell(y + 1, x - 1) then
Inc(FData[y, x].CellValue);
if CheckCell(y + 1, x) then
Inc(FData[y, x].CellValue);
if CheckCell(y + 1, x + 1) then
Inc(FData[y, x].CellValue);
end;
end;
end;
procedure TMinesweeper.StartGame(SizeH, SizeW, Mines: integer);
begin
if GameRunning then
StopGame;
if not ((SizeH = FSizeH) and (SizeW = FSizeW) and (FMines = Mines)) then
begin
FSizeH := SizeH;
FSizeW := SizeW;
FMines := Mines;
CheckValidBoard;
FOpenedMax := (SizeH * SizeW) - Mines;
InitializeData;
Autofit;
end;
InitVariables;
DrawBoard;
GameRunning := True;
end;
constructor TMinesweeper.Create(Parent: PPanel);
const
SpritesCount = 14;
var
i: integer;
begin
inherited Create;
FParent := Parent;
SetLength(FSprites, SpritesCount);
for i := 0 to SpritesCount - 1 do
begin
FSprites[i] := TPicture.Create;
{$IFDEF Linux}
FSprites[i].LoadFromFile(ExpandFileName(SpritesDir) + '/' + IntToStr(i) + '.png');
{$ENDIF}
{$IFDEF WINDOWS}
FSprites[i].LoadFromFile(ExpandFileName(SpritesDir) + '\' + IntToStr(i) + '.png');
{$ENDIF}
end;
end;
destructor TMinesweeper.Destroy;
var
i: integer;
begin
SetLength(FData, 0);
for i := 0 to High(FSprites) do
FSprites[i].Free;
inherited Destroy;
end;
constructor TMinesweeperTimer.Create(Counter: PInteger; const OnInc: TMinesweeperTimeProc);
begin
inherited Create(True);
PTime := Counter;
FOnInc := OnInc;
Start;
end;
procedure TMinesweeperTimer.UpdateTime;
begin
if not terminated then
begin
Inc(PTime^);
FOnInc(PTime^);
end;
end;
procedure TMinesweeperTimer.Execute;
begin
FreeOnTerminate := True;
while not terminated do
begin
Sleep(1000);
Synchronize(@UpdateTime);
end;
end;
end.
|
{ VERIFICATION PROGRAM for FLIP GAME problem for NEERC'2000 }
{ (C) Roman Elizarov }
{$A+,B-,D+,E+,F-,G-,I+,L+,N+,O-,P-,Q+,R+,S+,T-,V+,X+,Y+}
program FLIP_CHECK;
uses
testlib, symbols;
var
iouf, ians: longint;
function readAns(var stream: InStream): longint;
var
s: string;
i: longint;
r: integer;
begin
s := compress(stream.readString);
if upstr(s) = 'IMPOSSIBLE' then
readAns := -1
else begin
val(s, i, r);
if r <> 0 then
stream.Quit(_PE, 'Invalid answer string: ' + s);
if i < 0 then
stream.Quit(_PE, 'Negative number in answer: ' + s);
readAns := i;
end;
end;
begin
ians:= readAns(ans);
iouf:= readAns(ouf);
if not ouf.seekeof then Quit(_PE, 'Extra data in file');
if iouf <> ians then
Quit(_WA, 'Wrong answer: ' + str(iouf,0) + ' <> ' + str(ians,0) +
' (-1 means impossible)');
Quit(_OK, 'Ok');
end.
|
unit Model.ExpedicaoExpressas;
interface
uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao, Control.Sistema, System.DateUtils, System.SysUtils;
type
TExpedicaoExpressas = class
private
FAcao: Tacao;
FContainer: Integer;
FPeso: Double;
FUnitizador: Integer;
FConferencia: TDateTime;
FNN: String;
FExecucao: TDateTime;
FExecutor: String;
FVolumes: Integer;
FID: Integer;
FEmbarcador: Integer;
FBase: Integer;
FCCEP: String;
FRecebedor: String;
FConferente: String;
FRecebimento: TDateTime;
FData: TDateTime;
FDomCCEP: Integer;
FRomaneio: Integer;
FNomeEmbarcador: String;
FRoteiro: String;
FConexao : TConexao;
function Inserir(): Boolean;
function Alterar(): Boolean;
function Excluir(): Boolean;
public
constructor Create;
property ID: Integer read FID write FID;
property Data: TDateTime read FData write FData;
property CCEP: String read FCCEP write FCCEP;
property Base: Integer read FBase write FBase;
property Container: Integer read FContainer write FContainer;
property Unitizador: Integer read FUnitizador write FUnitizador;
property NN: String read FNN write FNN;
property Embarcador: Integer read FEmbarcador write FEmbarcador;
property NomeEmbarcador: String read FNomeEmbarcador write FNomeEmbarcador;
property Volumes: Integer read FVolumes write FVolumes;
property Peso: Double read FPeso write FPeso;
property Executor: String read FExecutor write FExecutor;
property Execucao: TDateTime read FExecucao write FExecucao;
property Conferente: String read FConferente write FConferente;
property Conferencia: TDateTime read FConferencia write FConferencia;
property Recebedor: String read FRecebedor write FRecebedor;
property Recebimento: TDateTime read FRecebimento write FRecebimento;
property DomCCEP: Integer read FDomCCEP write FDomCCEP;
property Romaneio: Integer read FRomaneio write FRomaneio;
property Roteiro: String read FRoteiro write FRoteiro;
property Acao: Tacao read FAcao write FAcao;
function GetID(): Integer;
function GeraNumeroContaiter(): Integer;
function GeraNumeroRomaneio(): Integer;
function NNExiste(sNN: String): Integer;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
end;
const
TABLENAME = 'expressas_expedicao';
SQLUPDATE = 'update ' + TABLENAME + ' set ' +
'dat_expedicao = :dat_expedicao, cod_ccep = :cod_ccep, cod_base = :cod_base, num_container = :num_container, ' +
'cod_unitizador = :cod_unitizador, num_nossonumero = :num_nossonumero, cod_embarcador = :cod_embarcador, ' +
'des_embarcador = :des_embarcador, qtd_volumes = :qtd_volumes, qtd_peso = :qtd_peso, des_executor = :des_executor, '+
'dat_execucao = :dat_execucao, des_conferente = :des_conferente, dat_conferencia = :dat_conferencia, ' +
'des_recebedor = :des_recebedor, dat_recebimento = :dat_recebimento, dom_ccep = :dom_ccep, ' +
'num_romaneio = :num_romaneio, des_roteiro = :des_roteiro ' +
'where id_expedicao = :id_expedicao;';
SQLINSERT = 'insert into ' + TABLENAME +
'(id_expedicao, dat_expedicao, cod_ccep, cod_base, num_container, cod_unitizador, num_nossonumero, cod_embarcador, ' +
'des_embarcador, qtd_volumes, qtd_peso, des_executor, dat_execucao, des_conferente, dat_conferencia, des_recebedor, ' +
'dat_recebimento, dom_ccep, num_romaneio, des_roteiro) ' +
'value ' +
'(:id_expedicao, :dat_expedicao, :cod_ccep, :cod_base, :num_container, :cod_unitizador, :num_nossonumero, :cod_embarcador, ' +
':des_embarcador, :qtd_volumes, :qtd_peso, :des_executor, :dat_execucao, :des_conferente, :dat_conferencia, :des_recebedor, ' +
':dat_recebimento, :dom_ccep, :num_romaneio, :des_roteiro);';
implementation
{ TExpedicaoExpressas }
function TExpedicaoExpressas.Alterar: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL(SQLUPDATE, [Data, CCEP, Base, Container, Unitizador, NN, Embarcador, NomeEmbarcador, Volumes, Peso, Executor,
Execucao, Conferente, Conferencia, Recebedor, Recebimento, DomCCEP, Romaneio, Roteiro, ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
constructor TExpedicaoExpressas.Create;
begin
FConexao := TSistemaControl.GetInstance().Conexao;
end;
function TExpedicaoExpressas.Excluir: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_expedicao = :id_expedicao;', [ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TExpedicaoExpressas.GeraNumeroContaiter: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(num_container),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TExpedicaoExpressas.GeraNumeroRomaneio: Integer;
var
iDias: Integer;
sRomaneio: String;
begin
Result := 0;
iDias := DaysBetween(Data, StrToDateDef('01/01/2000',0));
sRomaneio := iDias.ToString + CCEP;
Result := StrToIntDef(sRomaneio, 0);
end;
function TExpedicaoExpressas.GetID: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(id_expedicao),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TExpedicaoExpressas.Gravar: Boolean;
begin
Result := False;
case FAcao of
Common.ENum.tacIncluir: Result := Inserir();
Common.ENum.tacAlterar: Result := Alterar();
Common.ENum.tacExcluir: Result := Excluir();
end;
end;
function TExpedicaoExpressas.Inserir: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
ID := GetID;
Romaneio := GeraNumeroRomaneio();
FDQuery.ExecSQL(SQLINSERT, [ID, Data, CCEP, Base, Container, Unitizador, NN, Embarcador, NomeEmbarcador, Volumes, Peso,
Executor, Execucao, Conferente, Conferencia, Recebedor, Recebimento, DomCCEP, Romaneio, Roteiro]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TExpedicaoExpressas.Localizar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('where id_expedicao = :id_expedicao');
FDQuery.ParamByName('id_expedicao').AsInteger := aParam[1];
end;
if aParam[0] = 'CCEP' then
begin
FDQuery.SQL.Add('where cod_ccep = :cod_ccep');
FDQuery.ParamByName('cod_ccep').AsString := aParam[1];
end;
if aParam[0] = 'BASE' then
begin
FDQuery.SQL.Add('where cod_base = :cod_base');
FDQuery.ParamByName('cod_base').AsInteger := aParam[1];
end;
if aParam[0] = 'DATA' then
begin
FDQuery.SQL.Add('where dat_expedicao = :dat_expedicao');
FDQuery.ParamByName('dat_expedicao').AsDateTime := aParam[1];
end;
if aParam[0] = 'CONTAINER' then
begin
FDQuery.SQL.Add('where num_container = :num_container');
FDQuery.ParamByName('num_container').AsInteger := aParam[1];
end;
if aParam[0] = 'NN' then
begin
FDQuery.SQL.Add('where num_nossonumero = :num_nossonumero');
FDQuery.ParamByName('num_nossonumero').AsString := aParam[1];
end;
if aParam[0] = 'ROMANEIO' then
begin
FDQuery.SQL.Add('where num_romaneio = :num_romaneio');
FDQuery.ParamByName('num_romaneio').AsString := aParam[1];
end;
if aParam[0] = 'EMBARCADOR' then
begin
FDQuery.SQL.Add('where cod_embarcador = :cod_embarcador');
FDQuery.ParamByName('cod_embarcador').AsInteger := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open;
Result := FDQuery;
end;
function TExpedicaoExpressas.NNExiste(sNN: String): Integer;
var
FDQuery : TFDQuery;
begin
Result := 0;
FDQuery := FConexao.ReturnQuery();
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select num_container from ' + TABLENAME + ' where num_nossonumero = ' + QuotedStr(sNN));
FDQuery.Open;
if FDQuery.IsEmpty then Result := FDQuery.FieldByName('num_container').AsInteger;
FDQuery.Connection.Close;
FDQuery.Free;
end;
end.
|
{7.Realizar un programa que lea números enteros desde teclado hasta que se ingrese el valor -1 (que
no debe procesarse) e informe:
− la cantidad de ocurrencias de cada dígito procesado.
− el dígito más leído
− los dígitos que no tuvieron ocurrencias.
Por ejemplo, si la secuencia que se lee es: 63 34 99 94 96 -1, el programa deberá informar:
Número 3: 2 veces
Número 4: 2 veces
Número 6: 2 veces
Número 9: 4 veces
El dígito más leído fue el 9.
Los dígitos que no tuvieron ocurrencias son: 0, 1, 2, 5, 7, 8
}
program ejercicio7;
type
vnumeros = array[0..9] of Integer;
procedure inicializarVector(var v:vnumeros);
var
i: Integer;
begin
for i := 0 to 9 do
begin
v[i]:=0;
end;
end;
procedure descomponer(var v:vnumeros; num:Integer);
var
resto: Integer;
begin
while num <> 0 do
begin
resto:= num mod 10;
v[resto]:=v[resto]+1;
num:= num div 10;
end;
end;
procedure informar(v:vnumeros);
var
i,max,digMax: Integer;
begin
max:=-1;
for i := 0 to 9 do
begin
if v[i] > max then
begin
max:=v[i];
digMax:= i;
end;
if v[i] = 0 then
begin
writeln('el digito ', i, ' no tuvo ocurrencia');
end
else
writeln('[',i, ' aparece ', v[i],']');
end;
writeln('El digito mas leido es: ', digMax);
end;
var
v: vnumeros;
num:Integer;
begin
inicializarVector(v);
writeln('ingere un numero');
readln(num);
while (num <> -1 ) do
begin
descomponer(v,num);
writeln('Ingrese un numero');
readln(num);
end;
informar(v);
readln();
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpDerExternalParser;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpIAsn1StreamParser,
ClpDerExternal,
ClpIProxiedInterface,
ClpIDerExternalParser,
ClpAsn1Encodable;
type
TDerExternalParser = class(TAsn1Encodable, IDerExternalParser)
strict private
var
F_parser: IAsn1StreamParser;
public
constructor Create(const parser: IAsn1StreamParser);
function ReadObject(): IAsn1Convertible; inline;
function ToAsn1Object(): IAsn1Object; override;
end;
implementation
{ TDerExternalParser }
constructor TDerExternalParser.Create(const parser: IAsn1StreamParser);
begin
Inherited Create();
F_parser := parser;
end;
function TDerExternalParser.ReadObject: IAsn1Convertible;
begin
result := F_parser.ReadObject();
end;
function TDerExternalParser.ToAsn1Object: IAsn1Object;
begin
result := TDerExternal.Create(F_parser.ReadVector());
end;
end.
|
unit TabbedFormwithNavigation;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TabControl, FMX.StdCtrls, FMX.Controls.Presentation,
FMX.Gestures, System.Actions, FMX.ActnList, FMX.ListView.Types,
FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.Ani, FMX.ListView,
FMX.Edit, FMX.Layouts;
type
TTabbedwithNavigationForm = class(TForm)
TabControl1: TTabControl;
TabItem1: TTabItem;
TabControl2: TTabControl;
TabItem5: TTabItem;
ToolBar1: TToolBar;
lblTitle1: TLabel;
btnNext: TSpeedButton;
TabItem6: TTabItem;
ToolBar2: TToolBar;
lblTitle2: TLabel;
btnBack: TSpeedButton;
TabItem2: TTabItem;
ToolBar3: TToolBar;
lblTitle3: TLabel;
TabItem3: TTabItem;
ToolBar4: TToolBar;
lblTitle4: TLabel;
TabItem4: TTabItem;
ToolBar5: TToolBar;
lblTitle5: TLabel;
GestureManager1: TGestureManager;
ActionList1: TActionList;
NextTabAction1: TNextTabAction;
PreviousTabAction1: TPreviousTabAction;
FlowLayout1: TFlowLayout;
Button1: TButton;
Edit1: TEdit;
Label1: TLabel;
ListView1: TListView;
FloatAnimation1: TFloatAnimation;
procedure GestureDone(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
TabbedwithNavigationForm: TTabbedwithNavigationForm;
implementation
{$R *.fmx}
procedure TTabbedwithNavigationForm.Button1Click(Sender: TObject);
begin
ListView1.Items.Add.Text := Edit1.Text;
Edit1.Text := '';
FloatAnimation1.Start;
end;
procedure TTabbedwithNavigationForm.FormCreate(Sender: TObject);
begin
{ This defines the default active tab at runtime }
TabControl1.ActiveTab := TabItem1;
end;
procedure TTabbedwithNavigationForm.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkHardwareBack then
begin
if (TabControl1.ActiveTab = TabItem1) and (TabControl2.ActiveTab = TabItem6) then
begin
TabControl2.Previous;
Key := 0;
end;
end;
end;
procedure TTabbedwithNavigationForm.GestureDone(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
case EventInfo.GestureID of
sgiLeft:
begin
if TabControl1.ActiveTab <> TabControl1.Tabs[TabControl1.TabCount - 1] then
TabControl1.ActiveTab := TabControl1.Tabs[TabControl1.TabIndex + 1];
Handled := True;
end;
sgiRight:
begin
if TabControl1.ActiveTab <> TabControl1.Tabs[0] then
TabControl1.ActiveTab := TabControl1.Tabs[TabControl1.TabIndex - 1];
Handled := True;
end;
end;
end;
end.
|
unit GetUserDetailsUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TGetUserDetails = class(TBaseExample)
public
procedure Execute(MemberId: integer);
end;
implementation
uses UserUnit;
procedure TGetUserDetails.Execute(MemberId: integer);
var
ErrorString: String;
User: TUser;
begin
User := Route4MeManager.User.Get(MemberId, ErrorString);
try
WriteLn('');
if (User <> nil) then
begin
WriteLn('GetUserDetails executed successfully');
WriteLn('');
end
else
WriteLn(Format('GetUserDetails error: "%s"', [ErrorString]));
finally
FreeAndNil(User);
end;
end;
end.
|
unit cDatasource;
interface
uses TypInfo, Uni, Generics.Collections, Data.Db, System.SysUtils, System.Classes;
type
// TxnDataSource = class(TDataSource)
// public
// published
// end;
TmyDataLink = class(TDataLink)
private
function NullIndex: integer;
function NullBookmark: TBookmark;
protected
procedure DataEvent(Event: TDataEvent; Info: NativeInt); override;
public
fState1: string;
fState2: string;
Strings: TStrings;
Strings2: TStrings;
fData: TList<string>;
fIndex: integer;
fBookmark: TBookmark;
constructor Create;
destructor Destroy; override;
procedure Log(aString: string);
procedure Log2(aString: string);
procedure DataLoad;
procedure DataClear;
function AsDebug: string;
end;
TmyEdit = class(TComponent)
public
Strings: TStrings;
Strings2: TStrings;
Link: TmyDataLink;
procedure Log(aString: string);
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
function BookmarkToString(aBookmark: TBookmark): string;
var
b: byte;
begin
for b in aBookmark do
begin
if Result <> '' then
Result := Result + ':';
Result := Result + IntToHex(b, 2);
end;
Result := '[' + Result + ']';
end;
function BookmarkCompare(aBookmark1, aBookmark2: TBookmark): boolean;
begin
Result := SameStr(BookmarkToString(aBookmark1), BookmarkToString(aBookmark2));
end;
function EventToString(aEvent: TDataEvent): string;
begin
Result := GetEnumName(TypeInfo(TDataEvent), integer(aEvent));
end;
function StateToString(aState: TDataSetState): string;
begin
Result := GetEnumName(TypeInfo(TDataSetState), integer(aState));
end;
{ TxnDataSource }
// procedure TxnDataSource.DataEvent(Event: TDataEvent; Info: NativeInt);
// begin
// inherited DataEvent(Event, Info);
// end;
{ TnQuery }
{ TnQuery }
// procedure TnQuery.DataEvent(Event: TDataEvent; Info: TObject);
// begin
//
// end;
{ TnQuery }
{ TxnDataSource }
{ TmyEdit }
constructor TmyEdit.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
Strings := nil;
Link := TmyDataLink.Create;
// Link.Control := Self;
// Link.OnDataChange := DataChange;
// Link.OnEditingChange := EditingChange;
// Link.OnUpdateData := UpdateData;
// Link.OnActiveChange := ActiveChange;
end;
destructor TmyEdit.Destroy;
begin
Link.Free;
inherited;
end;
procedure TmyEdit.Log(aString: string);
begin
if Strings <> nil then
Strings.Add(aString);
end;
{ TmyDataLink }
function TmyDataLink.AsDebug: string;
var
c: string;
r: string;
i: integer;
begin
// if fIndex <= 0 then
// exit('')
// else
exit(IntToStr(fIndex));
if fData.Count = 0 then
exit('');
// c := fData[fIndex];
r := '';
for i := 0 to fData.Count - 1 do
r := r + fData[i] + ',';
r := '[' + c + ']' + r;
Result := r;
end;
constructor TmyDataLink.Create;
begin
inherited Create;
fState1 := '-1';
fState2 := '-2';
fData := TList<string>.Create;
fIndex := NullIndex();
fBookmark := NullBookmark();
Strings := nil;
end;
procedure TmyDataLink.DataClear;
begin
fData.Clear;
fIndex := -1;
end;
procedure TmyDataLink.DataEvent(Event: TDataEvent; Info: NativeInt);
var
state_new: string;
state_old_1: string;
state_old_2: string;
index_new: integer;
index_old: integer;
bookmark_new: TBookmark;
bookmark_old: TBookmark;
valid_old: boolean;
procedure LLL(aAction: string; aIndex: integer; aBookmark: TBookmark);
begin
if (SameText(aAction, 'DELETE')) and (aIndex = 0) then
exit;
// if (SameText(aAction, 'INSERT')) and (SameText(BookmarkToString(aBookmark), '[]')) then
// exit;
Log('[' + aAction + ']: ' + IntToStr(aIndex) + ': ' + BookmarkToString(aBookmark))
end;
begin
inherited;
state_old_1 := fState1;
state_old_2 := fState2;
state_new := StateToString(DataSet.State);
fState1 := state_new;
fState2 := state_old_1;
index_old := fIndex;
index_new := DataSet.RecNo;
fIndex := index_new;
valid_old := DataSet.BookmarkValid(fBookmark);
bookmark_old := fBookmark;
bookmark_new := DataSet.Bookmark;
fBookmark := bookmark_new;
Log2(StateToString(DataSet.State)
// + ' : ' + IntToStr(Info)
+ ' : ' + IntToStr(fIndex)
+ ' : ' + BookmarkToString(fBookmark)
+ ' : ' + DataSet.FieldByName('nn').AsString
+ ' : ' + DataSet.FieldByName('ss').AsString
);
if SameStr('dsEdit', state_old_2)
and (SameStr('dsBrowse', state_old_1))
and (SameStr('dsBrowse', state_new)) then
begin
LLL('EDIT', index_new, bookmark_new);
end
else if SameStr('dsInsert', state_old_2)
and SameStr('dsBrowse', state_old_1)
and SameStr('dsBrowse', state_new) then
begin
LLL('INSERT', index_new, bookmark_new);
LLL('REC_NO', index_new, bookmark_new)
end
// else if SameStr('dsInsert', state_old_1)
// and SameStr('dsInsert', state_new) then
// begin
// LLL('REC_NO', index_new, bookmark_new)
// end
else if SameStr('dsBrowse', state_old_1)
and SameStr('dsBrowse', state_new) then
begin
if valid_old then
LLL('REC_NO', index_new, bookmark_new)
else
begin
LLL('DELETE', index_old, bookmark_old);
LLL('REC_NO', index_new, bookmark_new);
end;
end
else
begin
//
// Log(StateToString(DataSet.State) // + ' : ' + StateToString(DataSource.State)
// + ' : ' + IntToStr(Info)
// + ' : ' + IntToStr(fIndex)
// + ' : ' + BookmarkToString(fBookmark)
// + ' : ' + DataSet.FieldByName('nn').AsString
// + ' : ' + DataSet.FieldByName('ss').AsString
// );
end;
// ;
// else if (SameStr('dsBrowse', state_new))
// and (SameStr('dsInsert', state_old_2)) then
// begin
// Log('[' + state_old_2 + '] : ' + IntToStr(fIndex) + ' : ' + BookmarkToString(fBookmark))
// end
// else if (SameStr('dsBrowse', state_new))
// and (SameStr('dsBrowse', state_old_1))
// then
// Log('[REST' + IntToStr(fIndex) + ' : ' + BookmarkToString(fBookmark) + ' : valid ')
// // if valid_old then
// // Log('[' + state_new + '] : ' + IntToStr(fIndex) + ' : ' + BookmarkToString(fBookmark) + ' : valid ')
// // else
// // Log('[' + state_new + '] : ' + IntToStr(fIndex) + ' : ' + BookmarkToString(fBookmark) + ' : not valid ')
// else;
// if valid_old then
// Log('[valid] : ' + IntToStr(fIndex) + ' : ' + BookmarkToString(fBookmark))
// else
// Log('[invalid] : ' + IntToStr(fIndex) + ' : ' + BookmarkToString(fBookmark));
// ;
exit;
// if BookmarkToString(bookmark_old) <> BookmarkToString(bookmark_new) then
Log(StateToString(DataSet.State)
+ ' : ' + IntToStr(Info)
+ ' : ' + IntToStr(fIndex)
+ ' : ' + BookmarkToString(fBookmark)
+ ' : ' + DataSet.FieldByName('nn').AsString
+ ' : ' + DataSet.FieldByName('ss').AsString
);
exit;
case Event of
deFieldChange:
;
deRecordChange:
// log ( 'deRecordChange')
;
deDataSetChange:
begin
// if DataSet.State = dsInsert then
// if DataSet.Eof then
// Log('append ' + IntToStr(index_new))
// else
// Log('insert ' + IntToStr(index_new))
// else
//
// begin
// // Log(StateToString(DataSet.State));
// // Log('old : ' + BookmarkToString(bookmark_old));
// // Log('new : ' + BookmarkToString(bookmark_new));
// if BookmarkToString(bookmark_old) <> '' then
// begin
// // if BookmarkCompare(bookmark_new, bookmark_old) then
// // Log('edit ' + IntToStr(index_new))
// // else
// // Log('delete ' + IntToStr(index_new) + ':' + IntToStr(index_old))
//
// end;
//
// // if DataSet.State = dsEdit then
// // Log('update ' + IntToStr(index_new))
// // else
// //
// end;
end;
deDataSetScroll:
;
deLayoutChange:
;
deUpdateRecord:
;
deUpdateState:
// if DataSet.State <> dsInsert then
// Log('update ' + IntToStr(index_new))
;
deCheckBrowseMode:
;
dePropertyChange:
;
deFieldListChange:
;
deFocusControl:
;
deParentScroll:
;
deConnectChange:
;
deReconcileError:
;
deDisabledStateChange:
;
end;
end;
destructor TmyDataLink.Destroy;
begin
fData.Free;
inherited;
end;
function TmyDataLink.NullBookmark: TBookmark;
begin
SetLength(Result, 0);
end;
function TmyDataLink.NullIndex: integer;
begin
Result := -1;
end;
procedure TmyDataLink.DataLoad;
begin
DataClear;
DataSet.First;
while not DataSet.Eof do
begin
fData.Add(DataSet.FieldByName('nn').AsString);
DataSet.Next;
end;
end;
procedure TmyDataLink.Log(aString: string);
begin
if Strings <> nil then
Strings.Add(aString);
end;
procedure TmyDataLink.Log2(aString: string);
begin
if Strings2 <> nil then
Strings2.Add(aString);
end;
end.
|
unit Control.PlanilhaEntradaTFO;
interface
uses Model.PlanilhaEntradaTFO;
type
TPlanilhaEntradaTFOControl = class
private
FPlanilha: TPlanilhaEntradaTFO;
public
constructor Create();
destructor Destroy(); override;
function GetPlanilha(sFile: String): boolean;
property Planilha: TPlanilhaEntradaTFO read FPlanilha write FPlanilha;
end;
implementation
{ TPlanilhaEntradaTFOControl }
constructor TPlanilhaEntradaTFOControl.Create;
begin
FPlanilha := TPlanilhaEntradaTFO.Create;
end;
destructor TPlanilhaEntradaTFOControl.Destroy;
begin
FPlanilha.Free;
inherited;
end;
function TPlanilhaEntradaTFOControl.GetPlanilha(sFile: String): boolean;
begin
Result := FPlanilha.GetPlanilha(sFile);
end;
end.
|
unit clSerializers;
{
clSerializers
Author: Chris Lichti
Updated: 4/8/2002
First version: February 28, 2001
This unit provides simple functions for saving and loading objects to/from
an INI files and Registry trees.
These functions all support the following property kinds:
tkInteger, tkChar, tkString, tkLString, tkWString, tkEnumeration, tkSet,
tkFloat, tkClass
The support for tkClass includes support for both object reference properties
and delegate objects, including TCollection descendants and TStrings.
If you need these functions to work with an additional property type or
class, please let me know via email. (chlichti@mindspring.com)
This unit requires my RTTI Wrapper classes in clRTTI.pas
The simplest possible way to use these functions is by calling the versions
that take a pointer to any object and a string with a starting header in it.
For example:
IniSerializer.SaveObjToIniFile( MyObject, 'MyApp.ini', 'MyObject' );
-and-
IniSerializer.LoadObjFromIniFile( MyObject, 'MyApp.ini', 'MyObject' );
or
RegSerializer.SaveObjToRegistry( MyObject, 'Software\Mine\MyApp\MyObject' );
-and-
IniSerializer.LoadObjFromIniFile( MyObject, 'Software\Mine\MyApp\MyObject' );
However, should you require more power over which properties are saved/loaded,
or how the TIniFile or TRegistry is configured, you can use one of the
overloaded versions of these functions which allow you to set up your own
TIniFile or TRegistry and/or your own TrtWrapper object.
For example:
You can filter out property names and property kinds that get saved/loaded
by creating your own instance of rtWrapper, setting the StopNames or
VisibleKinds properties, and passing it to one of the overloaded versions
of the save/load functions.
These functions are object-centric. If you are save/loading a class called
TMyObject, and you later remove a property from TMyObject, these functions
will simply not try to load the removed property. If you later add a property
and try to load an older version from the ini file, LoadObjFromIniFile will
return a comma-separated list containing the missing property(ies). You are
then responsible for filling in default values for those missing properties,
if necessary. In most cases, it is easier to just fill all the properties
of MyObject with defaults before calling LoadObjFromIniFile. However, if
you need to change values depending on other conditions, you can get at the
missing properties like this:
var
slMissingProps: TStringList;
rtMyObj: TrtWrapper;
nProp: integer;
begin
slMissingProps := nil;
rtMyObj := nil;
try
slMissingProps := TStringList.Create;
slMissingProps.CommaText :=
LoadObjFromIniFile( MyObject, 'MyApp\MyObject' );
if slMissingProps.Count > 0 then
begin
rtMyObj := TrtWrapper.Create( MyObject );
for nProp := 0 to slMissingProps.Count - 1 do
begin
rtMyObj[slMissingProps[nProp]].Value := //some default value
end;
end;
finally
rtMyObj.Free;
slMissingProps.Free;
end;
end;
}
interface
uses clRTTI, classes, inifiles, registry, windows;
resourcestring
ERR_OBJISNIL = '%s: %s cannot be nil';
ERR_REGISTRY_NOOPENKEY = '%s: TRegistry object (%s) does not have an open key';
ERR_REGISTRY_OPENKEY = '%s: Error opening key (%s)';
ERR_NOVALINREGISTRY = '%s: Property value (%s) is not in the registry';
type
TclAbstractSerializer = class
protected
function GetParentSection( sSectionName: string ): string; virtual;
function FormatSubSection( sSectionName, sSubSection: string ): string; virtual;
function ExtractSubSectionName( sSectionName: string ): string; virtual;
//Abstract read/write functions to override
procedure CreateSection( sSectionName: string ); virtual; abstract;
procedure RemoveSection( sSectionName: string ); virtual; abstract;
function SectionExists( sSectionName: string ): boolean; virtual; abstract;
function ValueExists( sSectionName, sName: string ): boolean; virtual; abstract;
procedure WriteString( sSectionName: string; sName: string; sValue: string ); virtual; abstract;
procedure WriteDateTime( sSectionName: string; sName: string; fValue: double ); virtual; abstract;
procedure WriteTime( sSectionName: string; sName: string; fValue: double ); virtual; abstract;
procedure WriteDate( sSectionName: string; sName: string; fValue: double ); virtual; abstract;
procedure WriteFloat( sSectionName: string; sName: string; fValue: double ); virtual; abstract;
procedure WriteInteger( sSectionName: string; sName: string; nValue: integer ); virtual; abstract;
function ReadString( sSectionName: string; sName: string): string; virtual; abstract;
function ReadDateTime( sSectionName: string; sName: string): double; virtual; abstract;
function ReadTime( sSectionName: string; sName: string): double; virtual; abstract;
function ReadDate( sSectionName: string; sName: string): double; virtual; abstract;
function ReadFloat( sSectionName: string; sName: string): double; virtual; abstract;
function ReadInteger( sSectionName: string; sName: string): integer; virtual; abstract;
//Internal serialization methods to call
procedure DoSerializeFrom( Source: TObject; sSection: string ); overload; virtual;
procedure DoSerializeFrom( Source: TrtWrapper; sSection: string ); overload; virtual;
function DoDeserializeTo( Target: TObject; sSection: string ): string; overload; virtual;
function DoDeserializeTo( Target: TrtWrapper; sSection: string ): string; overload; virtual;
public
constructor Create; virtual;
end;
TclIniSerializer = class( TclAbstractSerializer )
protected
IniFile: TIniFile;
procedure CreateSection( sSectionName: string ); override;
procedure RemoveSection( sSectionName: string ); override;
function SectionExists( sSectionName: string ): boolean; override;
function ValueExists( sSectionName, sName: string ): boolean; override;
procedure WriteString( sSectionName: string; sName: string; sValue: string ); override;
procedure WriteDateTime( sSectionName: string; sName: string; fValue: double ); override;
procedure WriteTime( sSectionName: string; sName: string; fValue: double ); override;
procedure WriteDate( sSectionName: string; sName: string; fValue: double ); override;
procedure WriteFloat( sSectionName: string; sName: string; fValue: double ); override;
procedure WriteInteger( sSectionName: string; sName: string; nValue: integer ); override;
function ReadString( sSectionName: string; sName: string): string; override;
function ReadDateTime( sSectionName: string; sName: string): double; override;
function ReadTime( sSectionName: string; sName: string): double; override;
function ReadDate( sSectionName: string; sName: string): double; override;
function ReadFloat( sSectionName: string; sName: string): double; override;
function ReadInteger( sSectionName: string; sName: string): integer; override;
public
// Saving...
procedure SaveObjToIniFile( Source: TObject; Target: TIniFile;
IniSection: string); overload;
procedure SaveObjToIniFile( Source: TObject; IniFilename, IniSection: string); overload;
procedure SaveObjToIniFile( Source: TrtWrapper; IniFilename, IniSection: string); overload;
procedure SaveObjToIniFile( Source: TrtWrapper; Target: TIniFile;
IniSection: string); overload;
// Loading...
function LoadObjFromIniFile( Target: TObject; IniFilename,
IniSection: string ): string; overload;
function LoadObjFromIniFile( Target: TrtWrapper; IniFilename,
IniSection: string ): string; overload;
function LoadObjFromIniFile( Source: TIniFile; IniSection: string; Target: TObject ): string; overload;
function LoadObjFromIniFile( Source: TIniFile; IniSection: string; Target: TrtWrapper ): string; overload;
end;
TclRegSerializer = class( TclAbstractSerializer )
protected
//Registry Support
slRegistries: TStringList;
BaseReg: TRegistry;
function GetRegForKey( sKey: string ): TRegistry;
procedure CleanUpRegistries;
procedure ClearKey(sKey: string);
//Overrides
procedure CreateSection( sSectionName: string ); override;
procedure RemoveSection( sSectionName: string ); override;
function SectionExists( sSectionName: string ): boolean; override;
function ValueExists( sSectionName, sName: string ): boolean; override;
procedure WriteString( sSectionName: string; sName: string; sValue: string ); override;
procedure WriteDateTime( sSectionName: string; sName: string; fValue: double ); override;
procedure WriteTime( sSectionName: string; sName: string; fValue: double ); override;
procedure WriteDate( sSectionName: string; sName: string; fValue: double ); override;
procedure WriteFloat( sSectionName: string; sName: string; fValue: double ); override;
procedure WriteInteger( sSectionName: string; sName: string; nValue: integer ); override;
function ReadString( sSectionName: string; sName: string): string; override;
function ReadDateTime( sSectionName: string; sName: string): double; override;
function ReadTime( sSectionName: string; sName: string): double; override;
function ReadDate( sSectionName: string; sName: string): double; override;
function ReadFloat( sSectionName: string; sName: string): double; override;
function ReadInteger( sSectionName: string; sName: string): integer; override;
public
constructor Create; override;
destructor Destroy; override;
// Saving...
procedure SaveObjToRegistry( Source: TObject; Target: TRegistry ); overload;
procedure SaveObjToRegistry( Source: TObject; RegistryKey: string;
RootKey: HKEY = HKEY_CURRENT_USER ); overload;
procedure SaveObjToRegistry( Source: TrtWrapper; RegistryKey: string;
RootKey: HKEY = HKEY_CURRENT_USER ); overload;
procedure SaveObjToRegistry( Source: TrtWrapper; Target: TRegistry ); overload;
// Loading...
function LoadObjFromRegistry( Target: TObject; RegistryKey: string;
RootKey: HKEY = HKEY_CURRENT_USER ): string; overload;
function LoadObjFromRegistry( Source: TRegistry; Target: TObject ): string; overload;
function LoadObjFromRegistry( Source: TRegistry; Target: TrtWrapper ): string; overload;
end;
function IniSerializer: TclIniSerializer;
function RegSerializer: TclRegSerializer;
implementation
uses typinfo, sysutils;
var
FIniSerializer: TclIniSerializer;
FRegSerializer: TclRegSerializer;
function IniSerializer: TclIniSerializer;
begin
if not Assigned(FIniSerializer) then
begin
FIniSerializer := TclIniSerializer.Create;
end;
Result := FIniSerializer;
end;
function RegSerializer: TclRegSerializer;
begin
if not Assigned(FRegSerializer) then
begin
FRegSerializer := TclRegSerializer.Create;
end;
Result := FRegSerializer;
end;
{ TclAbstractSerializer }
constructor TclAbstractSerializer.Create;
begin
//stupid virtual base constructor that should be in TObject. sigh...
end;
function TclAbstractSerializer.DoDeserializeTo(Target: TrtWrapper; sSection: string ): string;
{
LoadSubObject
Loads a SubObject from the specified SubSection in the IniFile.
This method provides any special handling required for special subobjects,
such as TCollection and TStrings.
}
procedure LoadSubObject( SubSection: string; Instance: TObject );
var
SubWrapper: TrtWrapper;
Strings: TStrings;
nSLine: integer;
Collection: TCollection;
nCItem: integer;
sCSubSection: string;
begin
if not Assigned( Instance ) then exit;
SubWrapper := nil;
try
//Create a TrtWrapper and configure it with the same settings as Source
SubWrapper := TrtWrapper.Create( Instance, Target.VisiblePropKinds );
SubWrapper.StopNames := Target.StopNames;
if Instance is TStrings then
begin //Read in the Text property for TStrings
Strings := TStrings( Instance );
Strings.Clear;
nSLine := 0;
while ValueExists( SubSection, 'Line' + InttoStr(nSLine) ) do
begin
Strings.Add(ReadString( SubSection, 'Line' + InttoStr(nSLine)));
inc(nSLine);
end;
end
else //Read in the entire object for everything else
DoDeserializeTo( Instance, SubSection );
//If the SubObject is a collection, read in the collection items
if Instance is TCollection then
begin
Collection := TCollection( Instance );
Collection.Clear;
for nCItem := 0 to MaxInt do
begin
sCSubSection := 'CItem' + InttoStr( nCItem );
if SectionExists( SubSection + '\' + sCSubSection ) then
begin
LoadSubObject( SubSection + '\' + sCSubSection, Collection.Add )
end
else break;
end;
end;
finally
SubWrapper.Free;
end;
end;
var
Prop: TrtProperty;
nProp: integer;
begin
//Enforce assumptions
Assert( Assigned( Target ),
Format(ERR_OBJISNIL, ['DoDeserializeTo', 'Target'] ));
Result := '';
//Loop through the published properties of the object
for nProp := 0 to Target.Count - 1 do
begin
Prop := Target.Items[nProp];
if Prop.ReadOnly then continue;
if (not ValueExists( sSection, Prop.Name )) and
(not SectionExists( sSection + '\' + Prop.Name)) then
begin
if length(Result) > 0 then Result := Result + ',';
Result := Result + Prop.Name;
continue;
end;
//Load the property using the TIniFile method appropriate for the property kind.
case Prop.Kind of
tkInteger, tkChar: Prop.AsInteger := ReadInteger( sSection, Prop.Name );
tkString, tkLString, tkWString, tkEnumeration, tkSet:
begin
Prop.AsString := ReadString( sSection, Prop.Name );
end;
tkFloat:
begin
if SameText( Prop.TypeInfo.Name, 'TDateTime' ) then
begin
Prop.AsFloat := ReadDateTime( sSection, Prop.Name );
end
else if SameText( Prop.TypeInfo.Name, 'TTime' ) then
begin
Prop.AsFloat := ReadTime( sSection, Prop.Name );
end
else if SameText( Prop.TypeInfo.Name, 'TDate' ) then
begin
Prop.AsFloat := ReadDate( sSection, Prop.Name );
end
else
Prop.AsFloat := ReadFloat( sSection, Prop.Name );
end;
tkClass:
begin
if Prop.IsDelegate then
begin
LoadSubObject( sSection + '\' + Prop.Name, Prop.AsObject );
end
else
begin
if Prop.ObjClassType = TComponent then
begin
Prop.AsObject := rtFindGlobalComponent(
ReadString( sSection, Prop.Name ) );
end;
end;
end;
end;
end;
end;
function TclAbstractSerializer.DoDeserializeTo(Target: TObject; sSection: string ): string;
var
TargetWrapper: TrtWrapper;
begin
Assert( Assigned( Target ),
Format(ERR_OBJISNIL, ['DoDeserializeTo', 'Target'] ));
TargetWrapper := nil;
try
TargetWrapper := TrtWrapper.Create( Target );
Result := DoDeserializeTo( TargetWrapper, sSection );
finally
TargetWrapper.Free;
end;
end;
procedure TclAbstractSerializer.DoSerializeFrom(Source: TrtWrapper; sSection: string );
{
StoreSubObject
Stores a SubObject in the specified SubSection in the IniFile.
This method provides any special handling required for special subobjects,
such as TCollection and TStrings.
}
procedure StoreSubObject( SubSection: string; SubObject: TObject );
var
SubWrapper: TrtWrapper;
Strings: TStrings;
nSLine: integer;
Collection: TCollection;
nCItem: integer;
begin
if not Assigned( SubObject ) then exit;
SubWrapper := nil;
try
//Create a TrtWrapper and configure it with the same settings as Source
SubWrapper := TrtWrapper.Create( SubObject, Source.VisiblePropKinds );
SubWrapper.StopNames := Source.StopNames;
RemoveSection( SubSection );
CreateSection( SubSection );
if SubObject is TStrings then
begin //Write out the text property of a TStrings
Strings := TStrings( SubObject );
for nSLine := 0 to Strings.Count - 1 do
WriteString( SubSection, 'Line' + InttoStr(nSLine), Strings[nSLine] );
end
else //Save the SubObject
DoSerializeFrom( SubWrapper, SubSection );
//If the SubObject is a collection, write out the collection items
if SubObject is TCollection then
begin
//Create a section to indicate that the collection property's sub-
// items are stored.
WriteString( SubSection, 'rt_TCollection', '1' );
//Clear any existing collection item sections
nCItem := 0;
while SectionExists( FormatSubSection( SubSection, 'CItem' + InttoStr( nCItem ) ) ) do
begin
RemoveSection( FormatSubSection( SubSection, 'CItem' + InttoStr( nCItem ) ) );
inc( nCItem );
end;
//Store collection items
Collection := TCollection( SubObject );
for nCItem := 0 to Collection.Count - 1 do
begin
StoreSubObject( FormatSubSection( SubSection, 'CItem' + InttoStr( nCItem ) ),
Collection.Items[nCItem] );
end;
end;
finally
SubWrapper.Free;
end;
end;
var
Prop: TrtProperty;
nProp: integer;
begin
//Enforce assumptions
Assert( Assigned( Source ),
Format(ERR_OBJISNIL, ['DoSerializeFrom', 'Source'] ));
Assert( Assigned( Source.ObjInstance ),
Format(ERR_OBJISNIL, ['DoSerializeFrom', 'Source wrapper''s object'] ));
RemoveSection( sSection );
//Loop through the published properties of the object
for nProp := 0 to Source.Count - 1 do
begin
Prop := Source.Items[nProp];
if Prop.ReadOnly then continue;
//Save the property with the TIniFile method appropriate for the property kind.
case Prop.Kind of
tkInteger, tkChar: WriteInteger( sSection, Prop.Name, Prop.AsInteger );
tkString, tkLString, tkWString, tkEnumeration, tkSet:
begin
WriteString( sSection, Prop.Name, Prop.AsString );
end;
tkFloat:
begin
if SameText( Prop.TypeInfo.Name, 'TDateTime' ) then
begin
WriteDateTime( sSection, Prop.Name, Prop.AsFloat );
end
else if SameText( Prop.TypeInfo.Name, 'TTime' ) then
begin
WriteTime( sSection, Prop.Name, Prop.AsFloat );
end
else if SameText( Prop.TypeInfo.Name, 'TDate' ) then
begin
WriteDate( sSection, Prop.Name, Prop.AsFloat );
end
else
WriteFloat( sSection, Prop.Name, Prop.AsFloat );
end;
tkClass:
begin
if Prop.IsDelegate then
begin
StoreSubObject( FormatSubSection( sSection, Prop.Name), Prop.AsObject );
end
else
begin
if Prop.ObjClassType = TComponent then
begin
WriteString( sSection, Prop.Name, TComponent( Prop.AsObject ).Name );
end;
end;
end;
end;
end;
end;
procedure TclAbstractSerializer.DoSerializeFrom(Source: TObject; sSection: string );
var
SourceWrapper: TrtWrapper;
begin
Assert( Assigned( Source ), Format(ERR_OBJISNIL, ['DoSerializeFrom', 'Source'] ));
SourceWrapper := nil;
try
SourceWrapper := TrtWrapper.Create( Source );
DoSerializeFrom( SourceWrapper, sSection );
finally
SourceWrapper.Free;
end;
end;
function TclAbstractSerializer.GetParentSection(sSectionName: string): string;
begin
Result := ExtractFilePath( sSectionName );
end;
function TclAbstractSerializer.FormatSubSection(sSectionName,
sSubSection: string): string;
begin
Result := sSectionName + '\' + sSubSection;
end;
function TclAbstractSerializer.ExtractSubSectionName(
sSectionName: string): string;
begin
Result := ExtractFileName( sSectionName );
end;
{ TclIniSerializer }
procedure TclIniSerializer.CreateSection(sSectionName: string);
begin
//no need, since TIniFile will automatically create sections if we ask nicely.
end;
function TclIniSerializer.LoadObjFromIniFile(Source: TIniFile;
IniSection: string; Target: TObject): string;
begin
IniFile := Source;
DoDeserializeTo( Target, IniSection );
end;
function TclIniSerializer.LoadObjFromIniFile(Source: TIniFile;
IniSection: string; Target: TrtWrapper): string;
begin
IniFile := Source;
DoDeserializeTo( Target, IniSection );
end;
function TclIniSerializer.LoadObjFromIniFile(Target: TrtWrapper;
IniFilename, IniSection: string): string;
var
IniFile: TIniFile;
begin
Assert( Assigned(Target),
Format(ERR_OBJISNIL, ['LoadObjFromIniFile', 'Target'] ));
IniFile := nil;
try
IniFile := TIniFile.Create( IniFilename );
Result := LoadObjFromIniFile( IniFile, IniSection, Target );
finally
IniFile.Free;
end;
end;
function TclIniSerializer.LoadObjFromIniFile(Target: TObject; IniFilename,
IniSection: string): string;
var
IniFile: TIniFile;
begin
Assert( Assigned(Target),
Format(ERR_OBJISNIL, ['LoadObjFromIniFile', 'Target'] ));
IniFile := nil;
try
IniFile := TIniFile.Create( IniFilename );
Result := LoadObjFromIniFile( IniFile, IniSection, Target )
finally
IniFile.Free;
end;
end;
function TclIniSerializer.ReadDate(sSectionName, sName: string): double;
begin
Result := IniFile.ReadDate( sSectionName, sName, 0 );
end;
function TclIniSerializer.ReadDateTime(sSectionName, sName: string): double;
begin
Result := IniFile.ReadDateTime( sSectionName, sName, 0 );
end;
function TclIniSerializer.ReadFloat(sSectionName, sName: string): double;
begin
Result := IniFile.ReadFloat( sSectionName, sName, 0 );
end;
function TclIniSerializer.ReadInteger(sSectionName, sName: string): integer;
begin
Result := IniFile.ReadInteger( sSectionName, sName, 0 );
end;
function TclIniSerializer.ReadString(sSectionName, sName: string): string;
begin
Result := IniFile.ReadString( sSectionName, sName, '' );
end;
function TclIniSerializer.ReadTime(sSectionName, sName: string): double;
begin
Result := IniFile.ReadTime( sSectionName, sName, 0 );
end;
procedure TclIniSerializer.RemoveSection(sSectionName: string);
begin
IniFile.EraseSection( sSectionName );
end;
procedure TclIniSerializer.SaveObjToIniFile(Source: TrtWrapper;
Target: TIniFile; IniSection: string);
begin
IniFile := Target;
DoSerializeFrom( Source, IniSection );
end;
procedure TclIniSerializer.SaveObjToIniFile(Source: TObject;
Target: TIniFile; IniSection: string);
begin
IniFile := Target;
DoSerializeFrom( Source, IniSection );
end;
procedure TclIniSerializer.SaveObjToIniFile(Source: TObject; IniFilename,
IniSection: string);
var
RObj: TrtWrapper;
begin
Assert( Assigned( Source ), Format(ERR_OBJISNIL, ['SaveObjToIniFile', 'Source'] ));
RObj := nil;
try
RObj := TrtWrapper.Create( Source );
SaveObjToIniFile( RObj, IniFilename, IniSection )
finally
RObj.Free;
end;
end;
procedure TclIniSerializer.SaveObjToIniFile(Source: TrtWrapper;
IniFilename, IniSection: string);
var
IniFile: TIniFile;
begin
Assert( Assigned( Source ), Format(ERR_OBJISNIL, ['SaveObjToIniFile', 'Source'] ));
IniFile := nil;
try
IniFile := TIniFile.Create(IniFilename);
SaveObjToIniFile( Source, IniFile, IniSection )
finally
IniFile.Free;
end;
end;
function TclIniSerializer.SectionExists(sSectionName: string): boolean;
begin
Result := IniFile.SectionExists(sSectionName);
end;
function TclIniSerializer.ValueExists(sSectionName,
sName: string): boolean;
begin
Result := IniFile.ValueExists(sSectionName, sName);
end;
procedure TclIniSerializer.WriteDate(sSectionName, sName: string;
fValue: double);
begin
IniFile.WriteDate(sSectionName, sName, fValue);
end;
procedure TclIniSerializer.WriteDateTime(sSectionName, sName: string;
fValue: double);
begin
IniFile.WriteDateTime(sSectionName, sName, fValue);
end;
procedure TclIniSerializer.WriteFloat(sSectionName, sName: string;
fValue: double);
begin
IniFile.WriteFloat(sSectionName, sName, fValue);
end;
procedure TclIniSerializer.WriteInteger(sSectionName, sName: string;
nValue: integer);
begin
IniFile.WriteInteger(sSectionName, sName, nValue);
end;
procedure TclIniSerializer.WriteString(sSectionName, sName,
sValue: string);
begin
IniFile.WriteString(sSectionName, sName, sValue);
end;
procedure TclIniSerializer.WriteTime(sSectionName, sName: string;
fValue: double);
begin
IniFile.WriteTime(sSectionName, sName, fValue);
end;
{ TclRegSerializer }
procedure TclRegSerializer.CleanUpRegistries;
var
Reg: TRegistry;
i: integer;
begin
for i := slRegistries.Count - 1 downto 0 do
begin
Reg := TRegistry(slRegistries.Objects[i]);
Reg.CloseKey;
Reg.Free;
slRegistries.Delete(i);
end;
end;
{
ClearKey
Completely remove the specified registry key
}
procedure TclRegSerializer.ClearKey(sKey: string);
var
slKeys: TStringList;
i: integer;
Reg: TRegistry;
begin
slKeys := nil;
try
slKeys := TStringList.Create;
Reg := GetRegForKey( sKey );
if Reg.OpenKey( sKey, false ) then
begin
//Remove all sub-keys
Reg.GetKeyNames( slKeys );
for i := 0 to slKeys.Count - 1 do
ClearKey( sKey + '\' + slKeys[i] );
//Close and delete the specified key
Reg.CloseKey;
if not Reg.DeleteKey( sKey ) then
raise Exception.CreateFmt( 'Error deleting key (%s)', [sKey] );
end;
finally
slKeys.Free;
end;
end;
constructor TclRegSerializer.Create;
begin
inherited;
slRegistries := TStringList.Create;
end;
procedure TclRegSerializer.CreateSection(sSectionName: string);
begin
GetRegForKey(sSectionName);
end;
destructor TclRegSerializer.Destroy;
begin
slRegistries.Free;
inherited;
end;
function TclRegSerializer.GetRegForKey(sKey: string): TRegistry;
begin
//If one doesn't exist
if slRegistries.IndexOf( sKey ) < 0 then
begin //create it
Result := TRegistry.Create;
Result.RootKey := BaseReg.RootKey;
Result.OpenKey( sKey, true );
slRegistries.AddObject( sKey, Result );
end
else
begin
Result := TRegistry(slRegistries.Objects[slRegistries.IndexOf( sKey )]);
end;
end;
function TclRegSerializer.LoadObjFromRegistry(Target: TObject;
RegistryKey: string; RootKey: HKEY): string;
var
Reg: TRegistry;
begin
Assert( Assigned(Target),
Format(ERR_OBJISNIL, ['LoadObjFromRegistry', 'Target'] ));
Reg := nil;
try
Reg := TRegistry.Create;
Reg.RootKey := RootKey;
if Reg.OpenKey( RegistryKey, true ) then
Result := LoadObjFromRegistry( Reg, Target )
else
raise Exception.CreateFmt( 'SaveObjToRegistry: Error opening key (%s)',
[RegistryKey] );
finally
Reg.Free;
end;
end;
function TclRegSerializer.LoadObjFromRegistry(Source: TRegistry;
Target: TObject): string;
begin
BaseReg := Source;
Result := DoDeserializeTo( Target, Source.CurrentPath );
end;
function TclRegSerializer.LoadObjFromRegistry(Source: TRegistry;
Target: TrtWrapper): string;
begin
BaseReg := Source;
Result := DoDeserializeTo( Target, Source.CurrentPath );
end;
function TclRegSerializer.ReadDate(sSectionName, sName: string): double;
begin
Result := GetRegForKey( sSectionName ).ReadDate( sName );
end;
function TclRegSerializer.ReadDateTime(sSectionName,
sName: string): double;
begin
Result := GetRegForKey( sSectionName ).ReadDateTime( sName );
end;
function TclRegSerializer.ReadFloat(sSectionName, sName: string): double;
begin
Result := GetRegForKey( sSectionName ).ReadFloat( sName );
end;
function TclRegSerializer.ReadInteger(sSectionName,
sName: string): integer;
begin
Result := GetRegForKey( sSectionName ).ReadInteger( sName );
end;
function TclRegSerializer.ReadString(sSectionName, sName: string): string;
begin
Result := GetRegForKey( sSectionName ).ReadString( sName );
end;
function TclRegSerializer.ReadTime(sSectionName, sName: string): double;
begin
Result := GetRegForKey( sSectionName ).ReadTime( sName );
end;
procedure TclRegSerializer.RemoveSection(sSectionName: string);
var
Reg: TRegistry;
begin
Reg := GetRegForKey( sSectionName );
Reg.CloseKey;
ClearKey( sSectionName );
Reg.OpenKey( sSectionName, true );
end;
procedure TclRegSerializer.SaveObjToRegistry(Source: TObject;
RegistryKey: string; RootKey: HKEY);
var
RObj: TrtWrapper;
begin
Assert( Assigned( Source ), Format(ERR_OBJISNIL, ['SaveObjToRegistry', 'Source'] ));
RObj := nil;
try
RObj := TrtWrapper.Create( Source );
SaveObjToRegistry( RObj, RegistryKey, RootKey )
finally
RObj.Free;
end;
end;
procedure TclRegSerializer.SaveObjToRegistry(Source: TObject;
Target: TRegistry);
begin
BaseReg := Target;
DoSerializeFrom( Source, BaseReg.CurrentPath );
end;
procedure TclRegSerializer.SaveObjToRegistry(Source: TrtWrapper;
Target: TRegistry);
begin
BaseReg := Target;
DoSerializeFrom( Source, BaseReg.CurrentPath );
end;
procedure TclRegSerializer.SaveObjToRegistry(Source: TrtWrapper;
RegistryKey: string; RootKey: HKEY);
var
Reg: TRegistry;
begin
Assert( Assigned( Source ), Format(ERR_OBJISNIL, ['SaveObjToRegistry', 'Source'] ));
Reg := nil;
try
Reg := TRegistry.Create;
Reg.RootKey := RootKey;
if Reg.OpenKey( RegistryKey, true ) then
SaveObjToRegistry( Source, Reg )
else
raise Exception.CreateFmt( ERR_REGISTRY_OPENKEY,
['SaveObjToRegistry', RegistryKey] );
finally
Reg.Free;
end;
end;
function TclRegSerializer.SectionExists(sSectionName: string): boolean;
begin
Result := GetRegForKey( GetParentSection( sSectionName ) ).KeyExists( ExtractSubSectionName( sSectionName ) );
end;
function TclRegSerializer.ValueExists(sSectionName,
sName: string): boolean;
begin
Result := GetRegForKey( sSectionName ).ValueExists( sName );
end;
procedure TclRegSerializer.WriteDate(sSectionName, sName: string;
fValue: double);
begin
GetRegForKey( sSectionName ).WriteDate( sName, fValue );
end;
procedure TclRegSerializer.WriteDateTime(sSectionName, sName: string;
fValue: double);
begin
GetRegForKey( sSectionName ).WriteDateTime( sName, fValue );
end;
procedure TclRegSerializer.WriteFloat(sSectionName, sName: string;
fValue: double);
begin
GetRegForKey( sSectionName ).WriteFloat( sName, fValue );
end;
procedure TclRegSerializer.WriteInteger(sSectionName, sName: string;
nValue: integer);
begin
GetRegForKey( sSectionName ).WriteInteger( sName, nValue );
end;
procedure TclRegSerializer.WriteString(sSectionName, sName,
sValue: string);
begin
GetRegForKey( sSectionName ).WriteString( sName, sValue );
end;
procedure TclRegSerializer.WriteTime(sSectionName, sName: string;
fValue: double);
begin
GetRegForKey( sSectionName ).WriteTime( sName, fValue );
end;
initialization
FIniSerializer := nil;
FRegSerializer := nil;
finalization
FIniSerializer.Free;
FRegSerializer.Free;
end.
|
{
File: DrawSprocket.p
Contains: Games Sprockets: DrawSprocket interfaces
Version: Technology: Draw Sprocket 1.7
Release: Universal Interfaces 3.4.2
Copyright: © 1996-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 DrawSprocket;
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,Video,Events,Quickdraw,QDOffscreen,Displays,MacErrors;
{$ALIGN POWER}
{
********************************************************************************
** constants
********************************************************************************
}
type
DSpDepthMask = SInt32;
const
kDSpDepthMask_1 = $01;
kDSpDepthMask_2 = $02;
kDSpDepthMask_4 = $04;
kDSpDepthMask_8 = $08;
kDSpDepthMask_16 = $10;
kDSpDepthMask_32 = $20;
kDSpDepthMask_All = -1;
type
DSpColorNeeds = SInt32;
const
kDSpColorNeeds_DontCare = 0;
kDSpColorNeeds_Request = 1;
kDSpColorNeeds_Require = 2;
type
DSpContextState = SInt32;
const
kDSpContextState_Active = 0;
kDSpContextState_Paused = 1;
kDSpContextState_Inactive = 2;
{ kDSpContextOption_QD3DAccel not yet implemented }
type
DSpContextOption = SInt32;
const
{ kDSpContextOption_QD3DAccel = 1<<0, }
kDSpContextOption_PageFlip = $02;
kDSpContextOption_DontSyncVBL = $04;
kDSpContextOption_Stereoscopic = $08;
type
DSpAltBufferOption = SInt32;
const
kDSpAltBufferOption_RowBytesEqualsWidth = $01;
type
DSpBufferKind = SInt32;
const
kDSpBufferKind_Normal = 0;
type
DSpBlitMode = SInt32;
const
kDSpBlitMode_Plain = 0;
kDSpBlitMode_SrcKey = $01;
kDSpBlitMode_DstKey = $02;
kDSpBlitMode_Interpolation = $04;
{
********************************************************************************
** data types
********************************************************************************
}
type
DSpAltBufferReference = ^SInt32; { an opaque 32-bit type }
DSpAltBufferReferencePtr = ^DSpAltBufferReference; { when a var xx:DSpAltBufferReference parameter can be nil, it is changed to xx: DSpAltBufferReferencePtr }
DSpContextReference = ^SInt32; { an opaque 32-bit type }
DSpContextReferencePtr = ^DSpContextReference; { when a var xx:DSpContextReference parameter can be nil, it is changed to xx: DSpContextReferencePtr }
DSpContextReferenceConst = ^SInt32; { an opaque 32-bit type }
DSpContextReferenceConstPtr = ^DSpContextReferenceConst; { when a var xx:DSpContextReferenceConst parameter can be nil, it is changed to xx: DSpContextReferenceConstPtr }
{$ifc TYPED_FUNCTION_POINTERS}
DSpEventProcPtr = function(var inEvent: EventRecord): boolean;
{$elsec}
DSpEventProcPtr = ProcPtr;
{$endc}
{$ifc TYPED_FUNCTION_POINTERS}
DSpCallbackProcPtr = function(inContext: DSpContextReference; inRefCon: UnivPtr): boolean;
{$elsec}
DSpCallbackProcPtr = ProcPtr;
{$endc}
{$ifc OPAQUE_UPP_TYPES}
DSpEventUPP = ^SInt32; { an opaque UPP }
{$elsec}
DSpEventUPP = DSpEventProcPtr;
{$endc}
{$ifc OPAQUE_UPP_TYPES}
DSpCallbackUPP = ^SInt32; { an opaque UPP }
{$elsec}
DSpCallbackUPP = DSpCallbackProcPtr;
{$endc}
const
uppDSpEventProcInfo = $000000D1;
uppDSpCallbackProcInfo = $000003D1;
{$ifc CALL_NOT_IN_CARBON}
{
* NewDSpEventUPP()
*
* Availability:
* Non-Carbon CFM: available as macro/inline
* CarbonLib: not available
* Mac OS X: not available
}
function NewDSpEventUPP(userRoutine: DSpEventProcPtr): DSpEventUPP; external name '_NewDSpEventUPP';
{
* NewDSpCallbackUPP()
*
* Availability:
* Non-Carbon CFM: available as macro/inline
* CarbonLib: not available
* Mac OS X: not available
}
function NewDSpCallbackUPP(userRoutine: DSpCallbackProcPtr): DSpCallbackUPP; external name '_NewDSpCallbackUPP';
{
* DisposeDSpEventUPP()
*
* Availability:
* Non-Carbon CFM: available as macro/inline
* CarbonLib: not available
* Mac OS X: not available
}
procedure DisposeDSpEventUPP(userUPP: DSpEventUPP); external name '_DisposeDSpEventUPP';
{
* DisposeDSpCallbackUPP()
*
* Availability:
* Non-Carbon CFM: available as macro/inline
* CarbonLib: not available
* Mac OS X: not available
}
procedure DisposeDSpCallbackUPP(userUPP: DSpCallbackUPP); external name '_DisposeDSpCallbackUPP';
{
* InvokeDSpEventUPP()
*
* Availability:
* Non-Carbon CFM: available as macro/inline
* CarbonLib: not available
* Mac OS X: not available
}
function InvokeDSpEventUPP(var inEvent: EventRecord; userRoutine: DSpEventUPP): boolean; external name '_InvokeDSpEventUPP';
{
* InvokeDSpCallbackUPP()
*
* Availability:
* Non-Carbon CFM: available as macro/inline
* CarbonLib: not available
* Mac OS X: not available
}
function InvokeDSpCallbackUPP(inContext: DSpContextReference; inRefCon: UnivPtr; userRoutine: DSpCallbackUPP): boolean; external name '_InvokeDSpCallbackUPP';
{$endc} {CALL_NOT_IN_CARBON}
type
DSpContextAttributesPtr = ^DSpContextAttributes;
DSpContextAttributes = record
frequency: Fixed;
displayWidth: UInt32;
displayHeight: UInt32;
reserved1: UInt32;
reserved2: UInt32;
colorNeeds: UInt32;
colorTable: CTabHandle;
contextOptions: OptionBits;
backBufferDepthMask: OptionBits;
displayDepthMask: OptionBits;
backBufferBestDepth: UInt32;
displayBestDepth: UInt32;
pageCount: UInt32;
filler1,filler2,filler3: SInt8;
gameMustConfirmSwitch: boolean;
reserved3: array [0..3] of UInt32;
end;
DSpAltBufferAttributesPtr = ^DSpAltBufferAttributes;
DSpAltBufferAttributes = record
width: UInt32;
height: UInt32;
options: DSpAltBufferOption;
reserved: array [0..3] of UInt32;
end;
DSpBlitInfoPtr = ^DSpBlitInfo;
{$ifc TYPED_FUNCTION_POINTERS}
DSpBlitDoneProc = procedure(info: DSpBlitInfoPtr);
{$elsec}
DSpBlitDoneProc = ProcPtr;
{$endc}
DSpBlitInfo = record
completionFlag: boolean;
filler1, filler2, filler3: SInt8;
completionProc: DSpBlitDoneProc;
srcContext: DSpContextReference;
srcBuffer: CGrafPtr;
srcRect: Rect;
srcKey: UInt32;
dstContext: DSpContextReference;
dstBuffer: CGrafPtr;
dstRect: Rect;
dstKey: UInt32;
mode: DSpBlitMode;
reserved: array [0..3] of UInt32;
end;
{
********************************************************************************
** function prototypes
********************************************************************************
}
{
** global operations
}
{
* DSpStartup()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpStartup: OSStatus; external name '_DSpStartup';
{
* DSpShutdown()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpShutdown: OSStatus; external name '_DSpShutdown';
{
* DSpGetVersion()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.7 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpGetVersion: NumVersion; external name '_DSpGetVersion';
{
* DSpGetFirstContext()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpGetFirstContext(inDisplayID: DisplayIDType; var outContext: DSpContextReference): OSStatus; external name '_DSpGetFirstContext';
{
* DSpGetNextContext()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpGetNextContext(inCurrentContext: DSpContextReference; var outContext: DSpContextReference): OSStatus; external name '_DSpGetNextContext';
{
* DSpGetCurrentContext()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.7 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpGetCurrentContext(inDisplayID: DisplayIDType; var outContext: DSpContextReference): OSStatus; external name '_DSpGetCurrentContext';
{
* DSpFindBestContext()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpFindBestContext(inDesiredAttributes: DSpContextAttributesPtr; var outContext: DSpContextReference): OSStatus; external name '_DSpFindBestContext';
{
* DSpFindBestContextOnDisplayID()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.7 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpFindBestContextOnDisplayID(inDesiredAttributes: DSpContextAttributesPtr; var outContext: DSpContextReference; inDisplayID: DisplayIDType): OSStatus; external name '_DSpFindBestContextOnDisplayID';
{$ifc CALL_NOT_IN_CARBON}
{
* DSpCanUserSelectContext()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpCanUserSelectContext(inDesiredAttributes: DSpContextAttributesPtr; var outUserCanSelectContext: boolean): OSStatus; external name '_DSpCanUserSelectContext';
{
* DSpUserSelectContext()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpUserSelectContext(inDesiredAttributes: DSpContextAttributesPtr; inDialogDisplayLocation: DisplayIDType; inEventProc: DSpEventUPP; var outContext: DSpContextReference): OSStatus; external name '_DSpUserSelectContext';
{$endc} {CALL_NOT_IN_CARBON}
{
* DSpProcessEvent()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpProcessEvent(var inEvent: EventRecord; var outEventWasProcessed: boolean): OSStatus; external name '_DSpProcessEvent';
{
* DSpSetBlankingColor()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpSetBlankingColor(const (*var*) inRGBColor: RGBColor): OSStatus; external name '_DSpSetBlankingColor';
{
* DSpSetDebugMode()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpSetDebugMode(inDebugMode: boolean): OSStatus; external name '_DSpSetDebugMode';
{
* DSpFindContextFromPoint()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpFindContextFromPoint(inGlobalPoint: Point; var outContext: DSpContextReference): OSStatus; external name '_DSpFindContextFromPoint';
{
* DSpGetMouse()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpGetMouse(var outGlobalPoint: Point): OSStatus; external name '_DSpGetMouse';
{
** alternate buffer operations
}
{$ifc CALL_NOT_IN_CARBON}
{
* DSpAltBuffer_New()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpAltBuffer_New(inContext: DSpContextReference; inVRAMBuffer: boolean; var inAttributes: DSpAltBufferAttributes; var outAltBuffer: DSpAltBufferReference): OSStatus; external name '_DSpAltBuffer_New';
{
* DSpAltBuffer_Dispose()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpAltBuffer_Dispose(inAltBuffer: DSpAltBufferReference): OSStatus; external name '_DSpAltBuffer_Dispose';
{
* DSpAltBuffer_InvalRect()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpAltBuffer_InvalRect(inAltBuffer: DSpAltBufferReference; const (*var*) inInvalidRect: Rect): OSStatus; external name '_DSpAltBuffer_InvalRect';
{
* DSpAltBuffer_GetCGrafPtr()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpAltBuffer_GetCGrafPtr(inAltBuffer: DSpAltBufferReference; inBufferKind: DSpBufferKind; var outCGrafPtr: CGrafPtr; var outGDevice: GDHandle): OSStatus; external name '_DSpAltBuffer_GetCGrafPtr';
{
** context operations
}
{ general }
{$endc} {CALL_NOT_IN_CARBON}
{
* DSpContext_GetAttributes()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_GetAttributes(inContext: DSpContextReferenceConst; outAttributes: DSpContextAttributesPtr): OSStatus; external name '_DSpContext_GetAttributes';
{
* DSpContext_Reserve()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_Reserve(inContext: DSpContextReference; inDesiredAttributes: DSpContextAttributesPtr): OSStatus; external name '_DSpContext_Reserve';
{
* DSpContext_Queue()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.7 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_Queue(inParentContext: DSpContextReference; inChildContext: DSpContextReference; inDesiredAttributes: DSpContextAttributesPtr): OSStatus; external name '_DSpContext_Queue';
{
* DSpContext_Switch()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.7 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_Switch(inOldContext: DSpContextReference; inNewContext: DSpContextReference): OSStatus; external name '_DSpContext_Switch';
{
* DSpContext_Release()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_Release(inContext: DSpContextReference): OSStatus; external name '_DSpContext_Release';
{
* DSpContext_Dispose()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_Dispose(inContext: DSpContextReference): OSStatus; external name '_DSpContext_Dispose';
{
* DSpContext_GetDisplayID()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_GetDisplayID(inContext: DSpContextReferenceConst; var outDisplayID: DisplayIDType): OSStatus; external name '_DSpContext_GetDisplayID';
{
* DSpContext_GlobalToLocal()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_GlobalToLocal(inContext: DSpContextReferenceConst; var ioPoint: Point): OSStatus; external name '_DSpContext_GlobalToLocal';
{
* DSpContext_LocalToGlobal()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_LocalToGlobal(inContext: DSpContextReferenceConst; var ioPoint: Point): OSStatus; external name '_DSpContext_LocalToGlobal';
{$ifc CALL_NOT_IN_CARBON}
{
* DSpContext_SetVBLProc()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_SetVBLProc(inContext: DSpContextReference; inProcPtr: DSpCallbackUPP; inRefCon: UnivPtr): OSStatus; external name '_DSpContext_SetVBLProc';
{
* DSpContext_GetFlattenedSize()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_GetFlattenedSize(inContext: DSpContextReference; var outFlatContextSize: UInt32): OSStatus; external name '_DSpContext_GetFlattenedSize';
{
* DSpContext_Flatten()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_Flatten(inContext: DSpContextReference; outFlatContext: UnivPtr): OSStatus; external name '_DSpContext_Flatten';
{
* DSpContext_Restore()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_Restore(inFlatContext: UnivPtr; var outRestoredContext: DSpContextReference): OSStatus; external name '_DSpContext_Restore';
{$endc} {CALL_NOT_IN_CARBON}
{
* DSpContext_GetMonitorFrequency()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_GetMonitorFrequency(inContext: DSpContextReferenceConst; var outFrequency: Fixed): OSStatus; external name '_DSpContext_GetMonitorFrequency';
{$ifc CALL_NOT_IN_CARBON}
{
* DSpContext_SetMaxFrameRate()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_SetMaxFrameRate(inContext: DSpContextReference; inMaxFPS: UInt32): OSStatus; external name '_DSpContext_SetMaxFrameRate';
{
* DSpContext_GetMaxFrameRate()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_GetMaxFrameRate(inContext: DSpContextReferenceConst; var outMaxFPS: UInt32): OSStatus; external name '_DSpContext_GetMaxFrameRate';
{$endc} {CALL_NOT_IN_CARBON}
{
* DSpContext_SetState()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_SetState(inContext: DSpContextReference; inState: DSpContextState): OSStatus; external name '_DSpContext_SetState';
{
* DSpContext_GetState()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_GetState(inContext: DSpContextReferenceConst; var outState: DSpContextState): OSStatus; external name '_DSpContext_GetState';
{
* DSpContext_IsBusy()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_IsBusy(inContext: DSpContextReferenceConst; var outBusyFlag: boolean): OSStatus; external name '_DSpContext_IsBusy';
{ dirty rectangles }
{$ifc CALL_NOT_IN_CARBON}
{
* DSpContext_SetDirtyRectGridSize()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_SetDirtyRectGridSize(inContext: DSpContextReference; inCellPixelWidth: UInt32; inCellPixelHeight: UInt32): OSStatus; external name '_DSpContext_SetDirtyRectGridSize';
{
* DSpContext_GetDirtyRectGridSize()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_GetDirtyRectGridSize(inContext: DSpContextReferenceConst; var outCellPixelWidth: UInt32; var outCellPixelHeight: UInt32): OSStatus; external name '_DSpContext_GetDirtyRectGridSize';
{
* DSpContext_GetDirtyRectGridUnits()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_GetDirtyRectGridUnits(inContext: DSpContextReferenceConst; var outCellPixelWidth: UInt32; var outCellPixelHeight: UInt32): OSStatus; external name '_DSpContext_GetDirtyRectGridUnits';
{
* DSpContext_InvalBackBufferRect()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_InvalBackBufferRect(inContext: DSpContextReference; const (*var*) inRect: Rect): OSStatus; external name '_DSpContext_InvalBackBufferRect';
{ underlays }
{
* DSpContext_SetUnderlayAltBuffer()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_SetUnderlayAltBuffer(inContext: DSpContextReference; inNewUnderlay: DSpAltBufferReference): OSStatus; external name '_DSpContext_SetUnderlayAltBuffer';
{
* DSpContext_GetUnderlayAltBuffer()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpContext_GetUnderlayAltBuffer(inContext: DSpContextReferenceConst; var outUnderlay: DSpAltBufferReference): OSStatus; external name '_DSpContext_GetUnderlayAltBuffer';
{ gamma }
{$endc} {CALL_NOT_IN_CARBON}
{
* DSpContext_FadeGammaOut()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_FadeGammaOut(inContext: DSpContextReference; var inZeroIntensityColor: RGBColor): OSStatus; external name '_DSpContext_FadeGammaOut';
{
* DSpContext_FadeGammaIn()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_FadeGammaIn(inContext: DSpContextReference; var inZeroIntensityColor: RGBColor): OSStatus; external name '_DSpContext_FadeGammaIn';
{
* DSpContext_FadeGamma()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_FadeGamma(inContext: DSpContextReference; inPercentOfOriginalIntensity: SInt32; var inZeroIntensityColor: RGBColor): OSStatus; external name '_DSpContext_FadeGamma';
{ buffering }
{
* DSpContext_SwapBuffers()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_SwapBuffers(inContext: DSpContextReference; inBusyProc: DSpCallbackUPP; inUserRefCon: UnivPtr): OSStatus; external name '_DSpContext_SwapBuffers';
{
* DSpContext_GetBackBuffer()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_GetBackBuffer(inContext: DSpContextReference; inBufferKind: DSpBufferKind; var outBackBuffer: CGrafPtr): OSStatus; external name '_DSpContext_GetBackBuffer';
{
* DSpContext_GetFrontBuffer()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.1 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_GetFrontBuffer(inContext: DSpContextReferenceConst; var outFrontBuffer: CGrafPtr): OSStatus; external name '_DSpContext_GetFrontBuffer';
{ clut operations }
{
* DSpContext_SetCLUTEntries()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_SetCLUTEntries(inContext: DSpContextReference; const (*var*) inEntries: ColorSpec; inStartingEntry: UInt16; inLastEntry: UInt16): OSStatus; external name '_DSpContext_SetCLUTEntries';
{
* DSpContext_GetCLUTEntries()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.0 and later
* CarbonLib: not available
* Mac OS X: in version 10.0 and later
}
function DSpContext_GetCLUTEntries(inContext: DSpContextReferenceConst; var outEntries: ColorSpec; inStartingEntry: UInt16; inLastEntry: UInt16): OSStatus; external name '_DSpContext_GetCLUTEntries';
{ blit operations }
{$ifc CALL_NOT_IN_CARBON}
{
* DSpBlit_Faster()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.1 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpBlit_Faster(inBlitInfo: DSpBlitInfoPtr; inAsyncFlag: boolean): OSStatus; external name '_DSpBlit_Faster';
{
* DSpBlit_Fastest()
*
* Availability:
* Non-Carbon CFM: in DrawSprocketLib 1.1 and later
* CarbonLib: not available
* Mac OS X: not available
}
function DSpBlit_Fastest(inBlitInfo: DSpBlitInfoPtr; inAsyncFlag: boolean): OSStatus; external name '_DSpBlit_Fastest';
{$endc} {CALL_NOT_IN_CARBON}
{$ALIGN MAC68K}
end.
|
unit MakeProfitTask;
interface
uses
Tasks, Kernel, Accounts, CacheAgent, BackupInterfaces, MathUtils;
type
TMetaMakeProfitTask =
class(TMetaTask)
private
fAccountId : TAccountId;
fGoal : TMoney;
public
property AccountId : TAccountId read fAccountId write fAccountId;
property Goal : TMoney read fGoal write fGoal;
end;
TMakeProfitTask =
class(TAtomicTask)
public
function Execute : TTaskResult; override;
private
fProfit : TMoney;
fLastProfit : TMoney;
public
procedure LoadFromBackup(Reader : IBackupReader); override;
procedure StoreToBackup (Writer : IBackupWriter); override;
procedure StoreToCache(Prefix : string; Cache : TObjectCache); override;
end;
procedure RegisterBackup;
implementation
// TMakeProfitTask
function TMakeProfitTask.Execute : TTaskResult;
var
Tycoon : TTycoon;
Account : TAccount;
begin
Tycoon := TTycoon(Context.getContext(tcIdx_Tycoon));
if Tycoon <> nil
then Account := Tycoon.Accounts.AccountArray[TMetaMakeProfitTask(MetaTask).AccountId]
else Account := nil;
if Account <> nil
then
begin
if Account.Value - fLastProfit > 0
then fProfit := fProfit + Account.Value - fLastProfit;
fLastProfit := Account.Value;
if fProfit > TMetaMakeProfitTask(MetaTask).Goal
then result := trFinished
else result := trContinue;
end
else result := trFinished
end;
procedure TMakeProfitTask.LoadFromBackup(Reader : IBackupReader);
begin
inherited;
fProfit := Reader.ReadCurrency('Profit', 0);
fLastProfit := Reader.ReadCurrency('LstProfit', 0);
end;
procedure TMakeProfitTask.StoreToBackup (Writer : IBackupWriter);
begin
inherited;
Writer.WriteCurrency('Profit', fProfit);
Writer.WriteCurrency('LstProfit', fLastProfit);
end;
procedure TMakeProfitTask.StoreToCache(Prefix : string; Cache : TObjectCache);
var
Tycoon : TTycoon;
Account : TAccount;
begin
inherited;
Tycoon := TTycoon(Context.getContext(tcIdx_Tycoon));
Cache.WriteString(Prefix + 'Goal', FormatMoney(TMetaMakeProfitTask(MetaTask).fGoal));
Cache.WriteInteger(Prefix + 'AccountId', TMetaMakeProfitTask(MetaTask).fAccountId);
if Tycoon <> nil
then Account := Tycoon.Accounts.AccountArray[TMetaMakeProfitTask(MetaTask).AccountId]
else Account := nil;
if Account <> nil
then Cache.WriteString(Prefix + 'Profit', FormatMoney(Account.Value));
end;
procedure RegisterBackup;
begin
RegisterClass(TMakeProfitTask);
end;
end.
|
{$include lem_directives.inc}
unit LemDosStructures;
interface
uses
Classes, SysUtils, Types,
GR32,
LemTypes;
{-------------------------------------------------------------------------------
LVL raw level file structure as used by dos en winlemmings.
-------------------------------------------------------------------------------}
const
LVL_MAXOBJECTCOUNT = 32;
LVL_MAXTERRAINCOUNT = 400;
LVL_MAXSTEELCOUNT = 32;
type
TLVLObject = packed record
case Byte of
0: ( AsInt64: Int64 );
1: ( D0, D1: DWord);
2: ( W0, W1, W2, W3: Word);
3: ( B0, B1, B2, B3, B4, B5, B6, B7: Byte);
4: (
XPos : Word; // swap lo and hi
YPos : Word; // swap lo and hi
ObjectID : Word;
Modifier : Byte;
DisplayMode : Byte; // $8F = invert; $0F = normal
);
end;
{
bits 0..3 = modifier
bits 4..7 shl 8 for xpos
bits 8..15 add to xpos
bits 16..24 9 bits number YPos
}
TLVLTerrain = packed record
case Byte of
0: ( D0: DWord );
1: ( W0, W1: Word );
2: ( B0, B1, B2, B3: Byte );
3: (
XPos : Word;
YPos : Byte; // 9 bits
TerrainID : Byte;
);
end;
TLVLSteel = packed record
case Byte of
0: ( D0: DWord );
1: ( W0, W1: Word);
2: ( B0, B1, B2, B3: Byte);
3: (
XPos : Byte; // 9 bits
YPos : Byte; // 7 bits bits 1..7
Area : Byte; // bits 0..3 is height in 4 pixel units (then add 4)
// bit 4..7 is width in 4 pixel units (then add 4)
b : Byte; // always zero
);
end;
TLVLObjects = array[0..LVL_MAXOBJECTCOUNT - 1] of TLVLObject;
TLVLTerrains = array[0..LVL_MAXTERRAINCOUNT - 1] of TLVLTerrain;
TLVLSteels = array[0..LVL_MAXSTEELCOUNT - 1] of TLVLSteel;
// TChars32 = array[0..31] of Char;
// the main record 2048 bytes
TLVLRec = packed record
{0000} ReleaseRate : Word; // big endian, swap!
{ } LemmingsCount : Word; // big endian, swap!
{ } RescueCount : Word; // big endian, swap!
{ } TimeLimit : Word; // big endian, swap!
{0008} ClimberCount : Word; // big endian, swap!
{ } FloaterCount : Word; // big endian, swap!
{ } BomberCount : Word; // big endian, swap!
{ } BlockerCount : Word; // big endian, swap!
{ } BuilderCount : Word; // big endian, swap!
{ } BasherCount : Word; // big endian, swap!
{ } MinerCount : Word; // big endian, swap!
{ } DiggerCount : Word; // big endian, swap!
{0018} ScreenPosition : Word; // big endian, swap!
{001A} GraphicSet : Word; // big endian, swap!
{ } GraphicSetEx : Word; // big endian, swap!
{001E} Reserved : Word; // big endian, swap! $FFFF if SuperLemming else $0000
{0020} Objects : TLVLObjects;
{0120} Terrain : TLVLTerrains;
{0760} Steel : TLVLSteels;
{07E0} LevelName : array[0..31] of Char;
end;
const
LVL_SIZE = SizeOf(TLVLRec);
type
{SYSTEM.DAT for Flexi player}
TSysDatRec = packed record
{0000} PackName : array[0..31] of Char;
SecondLine : array[0..31] of Char;
RankNames : array[0..14] of array[0..15] of Char;
RankCount : Byte;
SecretLevelCounts : array[0..14] of Byte;
TrackCount : Byte;
CodeSeed : Byte;
CheatCode : array[0..9] of Char;
Options : Byte;
Options2 : Byte;
Options3 : Byte;
Options4 : Byte;
KResult : array[0..2] of array[0..1] of array[0..35] of Char;
SResult : array[0..8] of array[0..1] of array[0..35] of Char;
Congrats : array[0..17] of array[0..35] of Char;
ScrollerTexts : array[0..15] of array[0..35] of Char;
StyleNames : array[0..255] of array[0..15] of Char;
VgaspecNames : array[0..255] of array[0..15] of Char;
end;
const
SYSDAT_SIZE = SizeOf(TSysDatRec);
{-------------------------------------------------------------------------------
GROUNDXX.DAT files (1056 bytes) (16 objects, 64 terrain, color palette)
o See documentation for details
o Little Endian words, so we can just load them from disk halleluyah!
-------------------------------------------------------------------------------}
type
PDosMetaObject = ^TDosMetaObject;
TDosMetaObject = packed record
oAnimation_flags : Word; // 2
oStart_animation_frame_index : Byte; // 3
oAnimation_frame_count : Byte; // 4
oWidth : Byte; // 5
oHeight : Byte; // 6
oAnimation_frame_data_size : Word; // 8 size in bytes of each animation frame
oMask_offset_from_image : Word; // 10
oUnknown1 : Word; // 12
oUnknown2 : Word; // 14
oTrigger_left : Word; // 16
oTrigger_top : Word; // 18
oTrigger_width : Byte; // 19
oTrigger_height : Byte; // 20
oTrigger_effect_id : Byte; // 21
oAnimation_frames_base_loc : Word; // 23
oPreview_image_location : Word; // 25
oUnknown3 : Word; // 27
oSound_effect_id : Byte; // 28
end;
TDosMetaObjectArray = packed array[0..15] of TDOSMetaObject;
PDosMetaTerrain = ^TDosMetaTerrain;
TDosMetaTerrain = packed record
tWidth : Byte;
tHeight : Byte;
tImage_loc : Word;
tMask_loc : Word;
tUnknown1 : Word
end;
TDosMetaTerrainArray = packed array[0..63] of TDosMetaTerrain;
TDosEGAPalette8 = packed array[0..7] of Byte;
PDosVgaColorRec = ^TDosVgaColorRec;
TDosVgaColorRec = packed record
R, G, B: Byte;
end;
TDosVGAPalette8 = packed array[0..7] of TDosVGAColorRec;
// this is the total structure of a dos ground?.dat
TDosGroundRec = packed record
ObjectInfoArray : TDosMetaObjectArray;
TerrainInfoArray : TDosMetaTerrainArray;
EGA_PaletteCustom : TDosEGAPalette8;
EGA_PaletteStandard : TDOSEGAPalette8;
EGA_PalettePreview : TDOSEGAPalette8;
VGA_PaletteCustom : TDOSVGAPalette8;
VGA_PaletteStandard : TDOSVGAPalette8;
VGA_PalettePreview : TDOSVGAPalette8;
end;
TDosVGAPalette16 = packed array[0..15] of TDosVGAColorRec;
TDosVgaSpecPaletteHeader = packed record
VgaPal: TDosVGAPalette8; // 24
EgaPal: TDosEGAPalette8; // 8
UnknownPal: array[0..7] of Byte; // maybe even less colors
end;
// big endian words, swap!
TDosOddTableRec = packed record
ReleaseRate : Word;
LemmingsCount : Word;
RescueCount : Word;
TimeLimit : Word;
ClimberCount : Word;
FloaterCount : Word;
BomberCount : Word;
BlockerCount : Word;
BuilderCount : Word;
BasherCount : Word;
MinerCount : Word;
DiggerCount : Word;
LevelName : array[0..31] of Char;
end;
type
{-------------------------------------------------------------------------------
So this is a very non-oop class to easily load the oddtable in records
-------------------------------------------------------------------------------}
TDosOddTable = class
public
Recs: array of TDosOddTableRec;
procedure LoadFromFile(const aFilename: string);
procedure LoadFromStream(S: TStream);
end;
const
DosInLevelPalette: TDosVGAPalette8 =
{$ifndef christmaspalette}
(
(R: 000; G: 000; B: 000), // black
(R: 016; G: 016; B: 056), // blue
(R: 000; G: 044; B: 000), // green
(R: 060; G: 052; B: 052), // white
(R: 044; G: 044; B: 000), // yellow
(R: 060; G: 008; B: 008), // red
(R: 032; G: 032; B: 032), // gray
(R: 000; G: 000; B: 000) // not used: probably this color is replaced with the standard palette entry in ground??.dat
);
{$else}
(
(R: 000; G: 000; B: 000), // black
(R: 052; G: 008; B: 008), // red
(R: 000; G: 044; B: 000), // green
(R: 060; G: 052; B: 052), // white
(R: 060; G: 060; B: 000), // yellow
(R: 016; G: 016; B: 060), // blue
(R: 032; G: 032; B: 032), // gray
(R: 000; G: 000; B: 000) // not used: probably this color is replaced with the standard palette entry in ground??.dat
);
{$endif}
//const
//LemmingBlue: TColor32 =
//LemmixInLevelPallette =
const
{ TODO : do not mix original rgb and converted rgb }
DosMainMenuPalette: TDosVGAPalette16 = (
(R: 000; G: 000; B: 000), // black
(R: 128; G: 064; B: 032), // browns
(R: 096; G: 048; B: 032),
{$ifndef christmaspalette}
(R: 048; G: 000; B: 016),
{$else}
(R: 000; G: 000; B: 000),
{$endif}
(R: 032; G: 008; B: 124), // purples
(R: 064; G: 044; B: 144),
(R: 104; G: 088; B: 164),
(R: 152; G: 140; B: 188),
(R: 000; G: 080; B: 000), // greens
(R: 000; G: 096; B: 016),
(R: 000; G: 112; B: 032),
(R: 000; G: 128; B: 064),
(R: 208; G: 208; B: 208), // white
(R: 176; G: 176; B: 000), // yellow
{$ifndef christmaspalette}
(R: 064; G: 080; B: 176), // blue
{$else}
(R: 200; G: 16; B: 16), // red
{$endif}
(R: 224; G: 128; B: 144) // pink
);
function DosVgaColorToColor32(const ColorRec: TDosVgaColorRec): TColor32;
function GetDosMainMenuPaletteColors32(UseXmas: Boolean = false): TArrayOfColor32;
implementation
function GetDosMainMenuPaletteColors32(UseXmas: Boolean = false): TArrayOfColor32;
var
i: Integer;
P: PColor32;
begin
SetLength(Result, 16);
{ TODO : move this conversion somewhere else }
for i := 0 to 15 do // bad code
begin
P := @Result[i];
TColor32Entry(P^).A := 0;
TColor32Entry(P^).R := DosMainMenuPalette[i].R;
TColor32Entry(P^).G := DosMainMenuPalette[i].G;
TColor32Entry(P^).B := DosMainMenuPalette[i].B;
end;
{$ifdef flexi}
if UseXmas then
begin
P := @Result[3];
TColor32Entry(P^).A := 0;
TColor32Entry(P^).R := 0;
TColor32Entry(P^).G := 0;
TColor32Entry(P^).B := 0;
P := @Result[14];
TColor32Entry(P^).A := 0;
TColor32Entry(P^).R := 240;
TColor32Entry(P^).G := 32;
TColor32Entry(P^).B := 32;
end;
{$endif}
end;
function DosVgaColorToColor32(const ColorRec: TDosVgaColorRec): TColor32;
begin
with TColor32Entry(Result) do
begin
R := ColorRec.R * 4;
G := ColorRec.G * 4;
B := ColorRec.B * 4;
end;
end;
procedure TDosOddTable.LoadFromFile(const aFilename: string);
var
F: TStream;//TFileStream;
//i: Integer;
// s: string;
begin
{
F := TFileStream.Create(aFileName, fmOpenRead);
try
LoadFromStream(F);
finally
F.Free;
end; }
F := CreateDataStream(aFileName, ldtLemmings);
try
LoadFromStream(F);
finally
F.Free;
end;
end;
procedure TDosOddTable.LoadFromStream(S: TStream);
var
i: Integer;
begin
SetLength(Recs, S.Size div SizeOf(TDosOddTableRec));
for i := 0 to Length(Recs) - 1 do
S.ReadBuffer(Recs[i], Sizeof(TDosOddTableRec));
end;
end.
|
unit tmnt_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,m68000,main_engine,controls_engine,gfx_engine,rom_engine,
pal_engine,sound_engine,upd7759,ym_2151,k052109,k051960,
misc_functions,samples,k053244_k053245,k053260,k053251,eepromser,k007232;
function iniciar_tmnt:boolean;
implementation
const
//TMNT
tmnt_rom:array[0..3] of tipo_roms=(
(n:'963-u23.j17';l:$20000;p:0;crc:$58bec748),(n:'963-u24.k17';l:$20000;p:$1;crc:$dce87c8d),
(n:'963-u21.j15';l:$10000;p:$40000;crc:$abce5ead),(n:'963-u22.k15';l:$10000;p:$40001;crc:$4ecc8d6b));
tmnt_sound:tipo_roms=(n:'963e20.g13';l:$8000;p:0;crc:$1692a6d6);
tmnt_char:array[0..1] of tipo_roms=(
(n:'963a28.h27';l:$80000;p:0;crc:$db4769a8),(n:'963a29.k27';l:$80000;p:$2;crc:$8069cd2e));
tmnt_sprites:array[0..3] of tipo_roms=(
(n:'963a17.h4';l:$80000;p:0;crc:$b5239a44),(n:'963a15.k4';l:$80000;p:$2;crc:$1f324eed),
(n:'963a18.h6';l:$80000;p:$100000;crc:$dd51adef),(n:'963a16.k6';l:$80000;p:$100002;crc:$d4bd9984));
tmnt_prom:array[0..1] of tipo_roms=(
(n:'963a30.g7';l:$100;p:0;crc:$abd82680),(n:'963a31.g19';l:$100;p:$100;crc:$f8004a1c));
tmnt_upd:tipo_roms=(n:'963a27.d18';l:$20000;p:0;crc:$2dfd674b);
tmnt_title:tipo_roms=(n:'963a25.d5';l:$80000;p:0;crc:$fca078c7);
tmnt_k007232:tipo_roms=(n:'963a26.c13';l:$20000;p:0;crc:$e2ac3063);
//Sunset Riders
ssriders_rom:array[0..3] of tipo_roms=(
(n:'064ebd02.8e';l:$40000;p:0;crc:$8deef9ac),(n:'064ebd03.8g';l:$40000;p:$1;crc:$2370c107),
(n:'064eab04.10e';l:$20000;p:$80000;crc:$ef2315bd),(n:'064eab05.10g';l:$20000;p:$80001;crc:$51d6fbc4));
ssriders_sound:tipo_roms=(n:'064e01.2f';l:$10000;p:0;crc:$44b9bc52);
ssriders_char:array[0..1] of tipo_roms=(
(n:'064e12.16k';l:$80000;p:0;crc:$e2bdc619),(n:'064e11.12k';l:$80000;p:$2;crc:$2d8ca8b0));
ssriders_sprites:array[0..1] of tipo_roms=(
(n:'064e09.7l';l:$100000;p:0;crc:$4160c372),(n:'064e07.3l';l:$100000;p:$2;crc:$64dd673c));
ssriders_eeprom:tipo_roms=(n:'ssriders_ebd.nv';l:$80;p:0;crc:$cbc903f6);
ssriders_k053260:tipo_roms=(n:'064e06.1d';l:$100000;p:0;crc:$59810df9);
//DIP
tmnt_dip_a:array [0..1] of def_dip=(
(mask:$f;name:'Coinage';number:16;dip:((dip_val:$0;dip_name:'5C 1C'),(dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'2C 3C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'))),());
tmnt_dip_b:array [0..3] of def_dip=(
(mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'1'),(dip_val:$2;dip_name:'2'),(dip_val:$1;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Normal'),(dip_val:$20;dip_name:'Difficult'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
tmnt_dip_c:array [0..1] of def_dip=(
(mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
rom:array[0..$5ffff] of word;
ram:array[0..$1fff] of word;
ram2:array[0..$3f] of word;
sprite_ram:array[0..$1fff] of word;
char_rom,sprite_rom,k007232_rom,k053260_rom:pbyte;
sound_latch,sound_latch2,sprite_colorbase,last_snd,toggle:byte;
layer_colorbase,layerpri:array[0..2] of byte;
irq5_mask,sprites_pri:boolean;
procedure tmnt_cb(layer,bank:word;var code:dword;var color:word;var flags:word;var priority:word);
begin
code:=code or ((color and $03) shl 8) or ((color and $10) shl 6) or ((color and $0c) shl 9) or (bank shl 13);
color:=layer_colorbase[layer]+((color and $e0) shr 5);
end;
procedure tmnt_sprite_cb(var code:word;var color:word;var pri:word;var shadow:word);
begin
code:=code or ((color and $10) shl 9);
color:=sprite_colorbase+(color and $0f);
end;
procedure tmnt_k007232_cb(valor:byte);
begin
k007232_0.set_volume(0,(valor shr 4)*$11,0);
k007232_0.set_volume(1,0,(valor and $0f)*$11);
end;
procedure update_video_tmnt;
begin
k052109_0.draw_tiles;
k051960_0.update_sprites;
fill_full_screen(4,0);
k052109_0.draw_layer(2,4);
if sprites_pri then begin
k051960_0.draw_sprites(0,0);
k052109_0.draw_layer(1,4);
end else begin
k052109_0.draw_layer(1,4);
k051960_0.draw_sprites(0,0);
end;
k052109_0.draw_layer(0,4);
actualiza_trozo_final(96,16,320,224,4);
end;
procedure eventos_tmnt;
begin
if event.arcade then begin
//P1
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $Fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $F7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40);
if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80);
//P2
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $Fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $F7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20);
if arcade_input.but2[1] then marcade.in2:=(marcade.in2 and $bf) else marcade.in2:=(marcade.in2 or $40);
if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $7f) else marcade.in2:=(marcade.in2 or $80);
//COIN
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2);
end;
end;
procedure tmnt_principal;
var
frame_m,frame_s:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//main
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//sound
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
if f=239 then begin
update_video_tmnt;
if irq5_mask then m68000_0.irq[5]:=HOLD_LINE;
end;
end;
eventos_tmnt;
video_sync;
end;
end;
function tmnt_getword(direccion:dword):word;
begin
case direccion of
0..$05ffff:tmnt_getword:=rom[direccion shr 1];
$060000..$063fff:tmnt_getword:=ram[(direccion and $3fff) shr 1];
$080000..$080fff:tmnt_getword:=buffer_paleta[(direccion and $fff) shr 1];
$0a0000:tmnt_getword:=marcade.in0; //coin
$0a0002:tmnt_getword:=marcade.in1; //p1
$0a0004:tmnt_getword:=marcade.in2; //p2
$0a0006:tmnt_getword:=$ff; //p3
$0a0010:tmnt_getword:=marcade.dswa;
$0a0012:tmnt_getword:=marcade.dswb;
$0a0014:tmnt_getword:=$ff; //p4
$0a0018:tmnt_getword:=marcade.dswc;
$100000..$107fff:begin
direccion:=direccion shr 1;
if m68000_0.read_8bits_hi_dir then tmnt_getword:=k052109_0.read_msb(((direccion and $3000) shr 1) or (direccion and $07ff))
else tmnt_getword:=k052109_0.read_lsb(((direccion and $3000) shr 1) or (direccion and $07ff)) shl 8;
end;
$140000..$140007:tmnt_getword:=k051960_0.k051937_read(direccion and 7);
$140400..$1407ff:if m68000_0.read_8bits_hi_dir then tmnt_getword:=k051960_0.read((direccion and $3ff)+1)
else tmnt_getword:=k051960_0.read(direccion and $3ff) shl 8;
end;
end;
procedure tmnt_putword(direccion:dword;valor:word);
procedure cambiar_color_tmnt(pos:word);
var
color:tcolor;
data:word;
begin
data:=(buffer_paleta[pos and $7fe] shl 8) or (buffer_paleta[(pos and $7fe)+1] shl 0);
color.b:=pal5bit(data shr 10);
color.g:=pal5bit(data shr 5);
color.r:=pal5bit(data);
set_pal_color_alpha(color,pos shr 1);
k052109_0.clean_video_buffer;
end;
begin
case direccion of
0..$5ffff:;
$60000..$63fff:ram[(direccion and $3fff) shr 1]:=valor;
$80000..$80fff:if buffer_paleta[(direccion and $fff) shr 1]<>(valor and $ff) then begin
buffer_paleta[(direccion and $fff) shr 1]:=valor and $ff;
cambiar_color_tmnt((direccion and $fff) shr 1);
end;
$a0000:begin
if ((last_snd=8) and ((valor and 8)=0)) then z80_0.change_irq(HOLD_LINE);
last_snd:=valor and 8;
// bit 5 = irq enable
irq5_mask:=(valor and $20)<>0;
// bit 7 = enable char ROM reading through the video RAM */
if (valor and $80)<>0 then k052109_0.rmrd_line:=ASSERT_LINE
else k052109_0.rmrd_line:=CLEAR_LINE;
end;
$a0008:sound_latch:=valor and $ff;
$c0000:sprites_pri:=((valor and $0c) shr 2)<>0; //prioridad
$100000..$107fff:begin
direccion:=direccion shr 1;
if m68000_0.write_8bits_hi_dir then k052109_0.write_msb(((direccion and $3000) shr 1) or (direccion and $07ff),valor)
else k052109_0.write_lsb(((direccion and $3000) shr 1) or (direccion and $07ff),valor shr 8)
end;
$140000..$140007:k051960_0.k051937_write((direccion and $7),valor);
$140400..$1407ff:if m68000_0.write_8bits_hi_dir then k051960_0.write((direccion and $3ff)+1,valor and $ff)
else k051960_0.write(direccion and $3ff,valor shr 8)
end;
end;
function tmnt_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$87ff:tmnt_snd_getbyte:=mem_snd[direccion];
$9000:tmnt_snd_getbyte:=sound_latch2;
$a000:tmnt_snd_getbyte:=sound_latch;
$b000..$b00d:tmnt_snd_getbyte:=k007232_0.read(direccion and $f);
$c001:tmnt_snd_getbyte:=ym2151_0.status;
$f000:tmnt_snd_getbyte:=upd7759_0.busy_r;
end;
end;
procedure tmnt_snd_putbyte(direccion:word;valor:byte);
begin
if direccion<$8000 then exit;
case direccion of
$8000..$87ff:mem_snd[direccion]:=valor;
$9000:begin
upd7759_0.reset_w(valor and 2);
// bit 2 plays the title music
if (((valor and 4)<>0) and not(sample_status(0))) then start_sample(0)
else stop_sample(0);
sound_latch2:=valor;
end;
$b000..$b00d:k007232_0.write(direccion and $f,valor);
$c000:ym2151_0.reg(valor);
$c001:ym2151_0.write(valor);
$d000:upd7759_0.port_w(valor);
$e000:upd7759_0.start_w(valor and 1);
end;
end;
procedure tmnt_sound_update;
begin
ym2151_0.update;
upd7759_0.update;
k007232_0.update;
samples_update;
end;
//Sunset riders
procedure ssriders_sprite_cb(var code:word;var color:word;var priority:word);
var
pri:word;
begin
pri:=$20 or ((color and $60) shr 2);
if (pri<=layerpri[2]) then priority:=0
else if ((pri>layerpri[2]) and (pri<=layerpri[1])) then priority:=1
else if ((pri>layerpri[1]) and (pri<=layerpri[0])) then priority:=2
else priority:=3;
color:=sprite_colorbase+(color and $1f);
end;
procedure update_video_ssriders;
var
bg_colorbase:byte;
sorted_layer:array[0..2] of byte;
begin
//Ordenar
sorted_layer[0]:=0;
layerpri[0]:=k053251_0.get_priority(K053251_CI2);
sorted_layer[1]:=1;
layerpri[1]:=k053251_0.get_priority(K053251_CI4);
sorted_layer[2]:=2;
layerpri[2]:=k053251_0.get_priority(K053251_CI3);
konami_sortlayers3(@sorted_layer,@layerpri);
bg_colorbase:=k053251_0.get_palette_index(K053251_CI0);
sprite_colorbase:=k053251_0.get_palette_index(K053251_CI1);
layer_colorbase[0]:=k053251_0.get_palette_index(K053251_CI2);
if k053251_0.dirty_tmap[K053251_CI2] then begin
k052109_0.clean_video_buffer_layer(0);
k053251_0.dirty_tmap[K053251_CI2]:=false;
end;
layer_colorbase[1]:=k053251_0.get_palette_index(K053251_CI4);
if k053251_0.dirty_tmap[K053251_CI4] then begin
k052109_0.clean_video_buffer_layer(1);
k053251_0.dirty_tmap[K053251_CI4]:=false;
end;
layer_colorbase[2]:=k053251_0.get_palette_index(K053251_CI3);
if k053251_0.dirty_tmap[K053251_CI3] then begin
k052109_0.clean_video_buffer_layer(2);
k053251_0.dirty_tmap[K053251_CI3]:=false;
end;
k052109_0.draw_tiles;
k05324x_update_sprites;
fill_full_screen(4,bg_colorbase*16);
k05324x_sprites_draw(3);
k052109_0.draw_layer(sorted_layer[0],4);
k05324x_sprites_draw(2);
k052109_0.draw_layer(sorted_layer[1],4);
k05324x_sprites_draw(1);
k052109_0.draw_layer(sorted_layer[2],4);
k05324x_sprites_draw(0);
actualiza_trozo_final(112,16,288,224,4);
end;
procedure ssriders_principal;
var
frame_m,frame_s:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//main
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//sound
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
case f of
21:update_video_ssriders;
239:if k052109_0.is_irq_enabled then m68000_0.irq[4]:=HOLD_LINE;
end;
end;
eventos_tmnt;
video_sync;
end;
end;
function ssriders_protection_r:word;
var
data:integer;
cmd:word;
begin
data:=ram[$1a0a shr 1];
cmd:=ram[$18fc shr 1];
case cmd of
$100b:begin
// read twice in a row, first result discarded?
// data is always == 0x75c
ssriders_protection_r:=$0064;
end;
$6003:ssriders_protection_r:=data and $000f; // start of level
$6004:ssriders_protection_r:=data and $001f;
$6000:ssriders_protection_r:=data and $0001;
$0000:ssriders_protection_r:=data and $00ff;
$6007:ssriders_protection_r:=data and $00ff;
$8abc:begin
// collision table
data:=-ram[$1818 shr 1];
data:=(((data div 8)-4) and $1f)*$40;
//0x1040c8 is the x scroll buffer, avoids stutter on slopes + scrolling (and it's actually more logical as HW pov)
data:=data+((((ram[$1cb0 shr 1]+ram[$00c8 shr 1])-6) div 8+12) and $3f);
ssriders_protection_r:=data;
end;
else ssriders_protection_r:=$ffff;
end;
end;
function ssriders_getword(direccion:dword):word;
var
res:byte;
begin
case direccion of
0..$0bffff:ssriders_getword:=rom[direccion shr 1];
$104000..$107fff:ssriders_getword:=ram[(direccion and $3fff) shr 1];
$140000..$140fff:ssriders_getword:=buffer_paleta[(direccion and $fff) shr 1];
$180000..$183fff:begin //k053245
direccion:=(direccion and $3fff) shr 1;
if (direccion and $0031)<>0 then ssriders_getword:=sprite_ram[direccion]
else begin
direccion:=((direccion and $000e) shr 1) or ((direccion and $1fc0) shr 3);
ssriders_getword:=k053245_word_r(direccion);
end;
end;
$1c0000:ssriders_getword:=marcade.in1; //p1
$1c0002:ssriders_getword:=marcade.in2; //p2
$1c0004:ssriders_getword:=$ff; //p3
$1c0006:ssriders_getword:=$ff; //p4
$1c0100:ssriders_getword:=marcade.in0; //coin
$1c0102:begin
res:=(byte(not(main_vars.service1)) shl 7)+$78+er5911_do_read+(er5911_ready_read shl 1); //eeprom
//falta vblank en bit 8
toggle:=toggle xor $04;
ssriders_getword:=res xor toggle;
end;
$1c0400:ssriders_getword:=0; //watchdog
$1c0500..$1c057f:ssriders_getword:=ram2[(direccion and $7f) shr 1];
$1c0800:ssriders_getword:=ssriders_protection_r; //proteccion
$5a0000..$5a001f:begin //k053244
direccion:=((direccion and $1f) shr 1) and $fe; ///* handle mirror address
ssriders_getword:=k053244_read(direccion+1)+(k053244_read(direccion) shl 8);
end;
$5c0600..$5c0603:ssriders_getword:=k053260_0.main_read((direccion and 3) shr 1); //k053260
$600000..$603fff:if m68000_0.read_8bits_hi_dir then ssriders_getword:=k052109_0.read_msb((direccion and $3fff) shr 1)
else ssriders_getword:=k052109_0.read_lsb((direccion and $3fff) shr 1) shl 8;
end;
end;
procedure ssriders_protection_w(direccion:word);
var
logical_pri,hardware_pri:word;
i,f:byte;
begin
if (direccion=1) then begin
//create sprite priority attributes
hardware_pri:=1;
logical_pri:=1;
for f:=1 to 8 do begin//; logical_pri < 0x100; logical_pri <<= 1)
for i:=0 to 127 do begin
if (sprite_ram[(6+128*i) shr 1] shr 8)=logical_pri then begin
k053245_lsb_w(8*i,hardware_pri);
hardware_pri:=hardware_pri+1;
end;
end;
logical_pri:=logical_pri shl 1;
end;
end;
end;
procedure ssriders_putword(direccion:dword;valor:word);
procedure cambiar_color_ssriders(pos,valor:word);
var
color:tcolor;
begin
color.b:=pal5bit(valor shr 10);
color.g:=pal5bit(valor shr 5);
color.r:=pal5bit(valor);
set_pal_color_alpha(color,pos);
k052109_0.clean_video_buffer;
end;
begin
case direccion of
0..$bffff:;
$104000..$107fff:ram[(direccion and $3fff) shr 1]:=valor;
$140000..$140fff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin
buffer_paleta[(direccion and $fff) shr 1]:=valor;
cambiar_color_ssriders((direccion and $fff) shr 1,valor);
end;
$180000..$183fff:begin //k053245
direccion:=(direccion and $3fff) shr 1;
sprite_ram[direccion]:=valor;
if (direccion and $0031)=0 then begin
direccion:=((direccion and $000e) shr 1) or ((direccion and $1fc0) shr 3);
k053245_word_w(direccion,valor);
end;
end;
$1c0200:begin// eeprom
er5911_di_write(valor and 1);
er5911_cs_write((valor shr 1) and 1);
er5911_clk_write((valor shr 2) and 1);
k053245_bankselect(((valor and $20) shr 5) shl 2);
end;
$1c0300:begin
// bit 3 = enable char ROM reading through the video RAM */
if (valor and 8)<>0 then k052109_0.rmrd_line:=ASSERT_LINE
else k052109_0.rmrd_line:=CLEAR_LINE;
// bits 4-6 control palette dimming (DIM0-DIM2) */
//m_dim_v = (data & 0x70) >> 4;
end;
$1c0500..$1c057f:ram2[(direccion and $7f) shr 1]:=valor;
$1c0800..$1c0803:ssriders_protection_w((direccion and $3) shr 1); //proteccion
$5a0000..$5a001f:begin //k053244
direccion:=((direccion and $1f) shr 1) and $fe; // handle mirror address
if m68000_0.write_8bits_hi_dir then k053244_write(direccion+1,valor and $ff)
else k053244_write(direccion,valor shr 8);
end;
$5c0600..$5c0603:k053260_0.main_write((direccion and 3) shr 1,valor); //k053260
$5c0604:z80_0.change_irq(HOLD_LINE); //sound
$5c0700..$5c071f:k053251_0.lsb_w((direccion and $1f) shr 1,valor); //k053251
$600000..$603fff:if m68000_0.write_8bits_hi_dir then k052109_0.write_msb((direccion and $3fff) shr 1,valor)
else k052109_0.write_lsb((direccion and $3fff) shr 1,valor shr 8);
end;
end;
function ssriders_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$f7ff:ssriders_snd_getbyte:=mem_snd[direccion];
$f801:ssriders_snd_getbyte:=ym2151_0.status;
$fa00..$fa2f:ssriders_snd_getbyte:=k053260_0.read(direccion and $3f); //k053260
end;
end;
procedure ssriders_snd_putbyte(direccion:word;valor:byte);
begin
if direccion<$f000 then exit;
case direccion of
$f000..$f7ff:mem_snd[direccion]:=valor;
$f800:ym2151_0.reg(valor);
$f801:ym2151_0.write(valor);
$fa00..$fa2f:k053260_0.write(direccion and $3f,valor); //k053260
$fc00:z80_0.change_nmi(HOLD_LINE);
end;
end;
procedure ssriders_sound_update;
begin
ym2151_0.update;
k053260_0.update;
end;
//Main
procedure reset_tmnt;
begin
m68000_0.reset;
z80_0.reset;
k052109_0.reset;
ym2151_0.reset;
case main_vars.tipo_maquina of
214:begin
k051960_0.reset;
upd7759_0.reset;
upd7759_0.start_w(0);
upd7759_0.reset_w(1);
reset_samples;
end;
215:begin
k053245_reset;
k053251_0.reset;
k053260_0.reset;
eepromser_reset;
end;
end;
reset_audio;
marcade.in0:=$FF;
marcade.in1:=$FF;
marcade.in2:=$FF;
sound_latch:=0;
sound_latch2:=0;
irq5_mask:=false;
last_snd:=0;
sprites_pri:=false;
toggle:=0;
end;
procedure cerrar_tmnt;
begin
case main_vars.tipo_maquina of
214:if k007232_rom<>nil then freemem(k007232_rom);
215:begin
//k053245_0.free;
if k053260_rom<>nil then freemem(k053260_rom);
//eeprom free
end;
end;
if char_rom<>nil then freemem(char_rom);
if sprite_rom<>nil then freemem(sprite_rom);
char_rom:=nil;
sprite_rom:=nil;
k053260_rom:=nil;
k007232_rom:=nil;
end;
function iniciar_tmnt:boolean;
var
f,tempdw:dword;
mem_temp:array[0..$1ff] of byte;
ptemp:pbyte;
ptempw:pword;
procedure desencriptar_sprites;
var
len,a,b:dword;
entry,i:byte;
bits:array[0..31] of byte;
temp:pbyte;
const
CA0=0;
CA1=1;
CA2=2;
CA3=3;
CA4=4;
CA5=5;
CA6=6;
CA7=7;
CA8=8;
CA9=9;
// following table derived from the schematics. It indicates, for each of the */
// 9 low bits of the sprite line address, which bit to pick it from. */
// For example, when the PROM contains 4, which applies to 4x2 sprites, */
// bit OA1 comes from CA5, OA2 from CA0, and so on. */
bit_pick_table:array[0..9,0..7] of byte=(
//0(1x1) 1(2x1) 2(1x2) 3(2x2) 4(4x2) 5(2x4) 6(4x4) 7(8x8) */
( CA3, CA3, CA3, CA3, CA3, CA3, CA3, CA3 ), // CA3 */
( CA0, CA0, CA5, CA5, CA5, CA5, CA5, CA5 ), // OA1 */
( CA1, CA1, CA0, CA0, CA0, CA7, CA7, CA7 ), // OA2 */
( CA2, CA2, CA1, CA1, CA1, CA0, CA0, CA9 ), // OA3 */
( CA4, CA4, CA2, CA2, CA2, CA1, CA1, CA0 ), // OA4 */
( CA5, CA6, CA4, CA4, CA4, CA2, CA2, CA1 ), // OA5 */
( CA6, CA5, CA6, CA6, CA6, CA4, CA4, CA2 ), // OA6 */
( CA7, CA7, CA7, CA7, CA8, CA6, CA6, CA4 ), // OA7 */
( CA8, CA8, CA8, CA8, CA7, CA8, CA8, CA6 ), // OA8 */
( CA9, CA9, CA9, CA9, CA9, CA9, CA9, CA8 )); // OA9 */
begin
// unscramble the sprite ROM address lines
len:=$200000 div 4;
getmem(temp,$200000);
copymemory(temp,sprite_rom,$200000);
for a:=0 to (len-1) do begin
// pick the correct entry in the PROM (top 8 bits of the address) */
entry:=mem_temp[(A and $7f800) shr 11] and 7;
// the bits to scramble are the low 10 ones */
for i:=0 to 9 do bits[i]:=(A shr i) and $1;
B:=A and $7fc00;
for i:=0 to 9 do B:=b or (bits[bit_pick_table[i][entry]] shl i);
sprite_rom[a*4]:=temp[b*4];
sprite_rom[(a*4)+1]:=temp[(b*4)+1];
sprite_rom[(a*4)+2]:=temp[(b*4)+2];
sprite_rom[(a*4)+3]:=temp[(b*4)+3];
end;
freemem(temp);
end;
function decode_sample(orig:pbyte;dest:pword):dword;
var
i,pos:dword;
val:word;
expo,cont1,cont2:byte;
ptemp:pword;
begin
// Sound sample for TMNT.D05 is stored in the following mode (ym3012 format):
// Bit 15-13: Exponent (2 ^ x)
// Bit 12-3 : Sound data (10 bit)
// (Sound info courtesy of Dave <dave@finalburn.com>)
//El original viene a 20Khz, lo convierto a 44Khz
pos:=0;
cont2:=0;
for i:=0 to $3ffff do begin
val:=orig[2*i]+orig[2*i+1]*256;
expo:=val shr 13;
val:=(val shr 3) and $3ff; // 10 bit, Max Amplitude 0x400
val:=val-$200; // Centralize value
val:=val shl (expo-3);
for cont1:=0 to 1 do begin
ptemp:=dest;
inc(ptemp,pos);
ptemp^:=val;
pos:=pos+1;
end;
cont2:=cont2+1;
if cont2=5 then begin
cont2:=0;
ptemp:=dest;
inc(ptemp,pos);
ptemp^:=val;
pos:=pos+1;
end;
end;
decode_sample:=pos;
end;
begin
llamadas_maquina.close:=cerrar_tmnt;
llamadas_maquina.reset:=reset_tmnt;
iniciar_tmnt:=false;
//Pantallas para el K052109
screen_init(1,512,256,true);
screen_init(2,512,256,true);
screen_mod_scroll(2,512,512,511,256,256,255);
screen_init(3,512,256,true);
screen_mod_scroll(3,512,512,511,256,256,255);
screen_init(4,1024,1024,false,true);
case main_vars.tipo_maquina of
214:begin //TMNT
llamadas_maquina.bucle_general:=tmnt_principal;
iniciar_video(320,224,true);
iniciar_audio(false); //Sonido mono
//Main CPU
m68000_0:=cpu_m68000.create(8000000,256);
m68000_0.change_ram16_calls(tmnt_getword,tmnt_putword);
//Sound CPU
z80_0:=cpu_z80.create(3579545,256);
z80_0.change_ram_calls(tmnt_snd_getbyte,tmnt_snd_putbyte);
z80_0.init_sound(tmnt_sound_update);
//cargar roms
if not(roms_load16w(@rom,tmnt_rom)) then exit;
//cargar sonido
if not(roms_load(@mem_snd,tmnt_sound)) then exit;
//Sound Chips
ym2151_0:=ym2151_chip.create(3579545);
upd7759_0:=upd7759_chip.create(0.6);
getmem(k007232_rom,$20000);
if not(roms_load(k007232_rom,tmnt_k007232)) then exit;
k007232_0:=k007232_chip.create(3579545,k007232_rom,$20000,0.20,tmnt_k007232_cb);
if not(roms_load(upd7759_0.get_rom_addr,tmnt_upd)) then exit;
getmem(ptemp,$80000);
getmem(ptempw,$80000*3);
if not(roms_load(ptemp,tmnt_title)) then exit;
load_samples_raw(ptempw,decode_sample(ptemp,ptempw),false,false);
freemem(ptemp);
freemem(ptempw);
//Iniciar video
getmem(char_rom,$100000);
if not(roms_load32b(char_rom,tmnt_char)) then exit;
//Ordenar
for f:=0 to $3ffff do begin
tempdw:=char_rom[(f*4)+0];
tempdw:=tempdw or (char_rom[(f*4)+1] shl 8);
tempdw:=tempdw or (char_rom[(f*4)+2] shl 16);
tempdw:=tempdw or (char_rom[(f*4)+3] shl 24);
tempdw:=BITSWAP32(tempdw,31,27,23,19,15,11,7,3,30,26,22,18,14,10,6,2,29,25,21,17,13,9,5,1,28,24,20,16,12,8,4,0);
char_rom[(f*4)+0]:=tempdw and $ff;
char_rom[(f*4)+1]:=(tempdw shr 8) and $ff;
char_rom[(f*4)+2]:=(tempdw shr 16) and $ff;
char_rom[(f*4)+3]:=(tempdw shr 24) and $ff;
end;
k052109_0:=k052109_chip.create(1,2,3,0,tmnt_cb,char_rom,$100000);
//Init sprites
getmem(sprite_rom,$200000);
if not(roms_load32b(sprite_rom,tmnt_sprites)) then exit;
if not(roms_load(@mem_temp,tmnt_prom)) then exit;
//Ordenar
for f:=0 to $7ffff do begin
tempdw:=sprite_rom[(f*4)+0];
tempdw:=tempdw or (sprite_rom[(f*4)+1] shl 8);
tempdw:=tempdw or (sprite_rom[(f*4)+2] shl 16);
tempdw:=tempdw or (sprite_rom[(f*4)+3] shl 24);
tempdw:=BITSWAP32(tempdw,31,27,23,19,15,11,7,3,30,26,22,18,14,10,6,2,29,25,21,17,13,9,5,1,28,24,20,16,12,8,4,0);
sprite_rom[(f*4)+0]:=tempdw and $ff;
sprite_rom[(f*4)+1]:=(tempdw shr 8) and $ff;
sprite_rom[(f*4)+2]:=(tempdw shr 16) and $ff;
sprite_rom[(f*4)+3]:=(tempdw shr 24) and $ff;
end;
desencriptar_sprites;
k051960_0:=k051960_chip.create(4,1,sprite_rom,$200000,tmnt_sprite_cb);
layer_colorbase[0]:=0;
layer_colorbase[1]:=32;
layer_colorbase[2]:=40;
sprite_colorbase:=16;
//DIP
marcade.dswa:=$ff;
marcade.dswa_val:=@tmnt_dip_a;
marcade.dswb:=$5e;
marcade.dswb_val:=@tmnt_dip_b;
marcade.dswc:=$ff;
marcade.dswc_val:=@tmnt_dip_c;
end;
215:begin //Sunset Riders
llamadas_maquina.bucle_general:=ssriders_principal;
iniciar_video(288,224,true);
iniciar_audio(true); //Sonido stereo
//Main CPU
m68000_0:=cpu_m68000.create(16000000,256);
m68000_0.change_ram16_calls(ssriders_getword,ssriders_putword);
//Sound CPU
z80_0:=cpu_z80.create(8000000,256);
z80_0.change_ram_calls(ssriders_snd_getbyte,ssriders_snd_putbyte);
z80_0.init_sound(ssriders_sound_update);
//cargar roms
if not(roms_load16w(@rom,ssriders_rom)) then exit;
//cargar sonido
if not(roms_load(@mem_snd,ssriders_sound)) then exit;
//Sound Chips
ym2151_0:=ym2151_chip.create(3579545);
getmem(k053260_rom,$100000);
if not(roms_load(k053260_rom,ssriders_k053260)) then exit;
k053260_0:=tk053260_chip.create(3579545,k053260_rom,$100000,0.70);
//Iniciar video
getmem(char_rom,$100000);
if not(roms_load32b(char_rom,ssriders_char)) then exit;
k052109_0:=k052109_chip.create(1,2,3,0,tmnt_cb,char_rom,$100000);
//Init sprites
getmem(sprite_rom,$200000);
if not(roms_load32b(sprite_rom,ssriders_sprites)) then exit;
k053245_init(sprite_rom,$200000,ssriders_sprite_cb);
//Prioridades
k053251_0:=k053251_chip.create;
//eeprom
eepromser_init(ER5911,8);
if not(roms_load(@mem_temp,ssriders_eeprom)) then exit;
eepromser_load_data(@mem_temp[0],$80);
end;
end;
//final
reset_tmnt;
iniciar_tmnt:=true;
end;
end.
|
unit atLoginFromListOperation;
// Модуль: "w:\quality\test\garant6x\AdapterTest\Operations\atLoginFromListOperation.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TatLoginFromListOperation" MUID: (4FF30FEB005D)
interface
uses
l3IntfUses
, atOperationBase
, atLockFile
;
type
TatLoginFromListOperation = class(TatOperationBase)
private
f_LockFile: TatLockFile;
f_IsLoop: Boolean;
f_UsedFN: AnsiString;
f_FreeFN: AnsiString;
f_LPStr: AnsiString;
protected
procedure ExecuteSelf; override;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure InitParamList; override;
public
procedure AfterFillingParamList; override;
{* Вызывается генератором сценария после заполнения значений параметров.
Если операции надо что-то инициализировать, и для этого нужны значения параметров из сценария. }
end;//TatLoginFromListOperation
implementation
uses
l3ImplUses
, Classes
, SysUtils
, atLogger
, atLoginOperation
, XMLDoc
, XMLIntf
//#UC START# *4FF30FEB005Dimpl_uses*
//#UC END# *4FF30FEB005Dimpl_uses*
;
procedure TatLoginFromListOperation.ExecuteSelf;
//#UC START# *48089F460352_4FF30FEB005D_var*
const
WAIT_TIME = 5000;
LP_DELIM : Char = #01;
var
l_LoginsFN : String;
l_LP : TStringList;
l_Login, l_Password : String;
l_IsWait : Boolean;
// заполняем f_LP из текстового файла, где построчно записаны логины и пароли, разделенные пробелами
procedure FillLPFromTextFile;
var
i : Integer;
l_Str : String;
begin
with TStringList.Create do
try
CaseSensitive := true;
Duplicates := dupError;
//
try
LoadFromFile(l_LoginsFN);
except
on ex : EStringListError do
begin
Logger.Error('Ошибка при чтении файла с логинами-паролями: %s', [ex.Message]);
Raise;
end;
end;
for i:= 0 to Count-1 do
begin
l_Str := StringReplace(TrimLeft(Strings[i]), ' ', LP_DELIM, []);
if l_Str <> '' then
begin
if Pos(LP_DELIM, l_Str) = 0 then
l_Str := l_Str + LP_DELIM;
l_LP.Append(l_Str);
end;
end;
finally
Free;
end;
end;
procedure FillLPFromXML;
var
i : Integer;
begin
with TXMLDocument.Create(l_LoginsFN) as IXMLDocument do
with ChildNodes.Nodes['profiles'].ChildNodes do
for i := 0 to Count-1 do
with Nodes[i] do
if (NodeName = 'user') and NOT AnsiSameText(Attributes['login'], 'ADMIN') then
l_LP.Append(Attributes['login'] + LP_DELIM + Attributes['password']);
end;
//#UC END# *48089F460352_4FF30FEB005D_var*
begin
//#UC START# *48089F460352_4FF30FEB005D_impl*
l_LoginsFN := Parameters['logins_file'].AsStr;
if NOT FileExists(l_LoginsFN) then
begin
Logger.Error('Не найден файл с логинами-паролями %s', [l_LoginsFN]);
Exit;
end;
// файлы данных будем располагать там же где и файл синхронизации
f_FreeFN := f_LockFile.FileName + '.free.data';
f_UsedFN := f_LockFile.FileName + '.used.data';
l_LP := TStringList.Create;
l_LP.Duplicates := dupError;
l_LP.CaseSensitive := true;
try
l_IsWait := false;
// получаем строку с парой логин-пароль
while (f_LPStr = '') do
begin
if l_IsWait then
Sleep(WAIT_TIME);
//
if f_LockFile.Acquire then
try
// пробуем загрузить свободные логины-пароли из файла свободных
if FileExists(f_FreeFN) then
begin
l_LP.LoadFromFile(f_FreeFN);
if l_LP.Count = 0 then // кончились свободные логины
if f_IsLoop then
begin // крутимся в цикле пока не появятся свободные
Logger.Info('Свободных логинов пока нет, ждем когда освободятся...');
l_IsWait := true;
continue;
end
else
begin
Logger.Info('Свободные логины закончились, завершаем работу');
Abort;
end;
end
else // файла нет, заполняем из исходного
begin
if AnsiSameText(ExtractFileExt(l_LoginsFN), '.xml') then
FillLPFromXML
else
FillLPFromTextFile;
if l_LP.Count = 0 then
begin
Logger.Error('Не получилось найти в файле "%s" ни одного логина', [l_LoginsFN]);
Abort;
end;
end;
// к этой строке есть кем логиниться
// извлекаем первую строку с логином-паролем
f_LPStr := l_LP.Strings[0];
l_LP.Delete(0);
// обновляем список свободных обратно
l_LP.SaveToFile(f_FreeFN);
// добавляем пару в список уже использованных
if FileExists(f_UsedFN) then
l_LP.LoadFromFile(f_UsedFN)
else
l_LP.Clear;
l_LP.Append(f_LPStr);
l_LP.SaveToFile(f_UsedFN);
finally
f_LockFile.Release;
end;
end;
finally
FreeAndNil(l_LP);
end;
// разбиваем пару логин-пароль на логин и пароль
with TStringList.Create do
try
NameValueSeparator := LP_DELIM;
Text := f_LPStr;
l_Login := Names[0];
l_Password := Values[l_Login];
finally
Free;
end;
// Логинимся
Logger.Info('Логинимся пользователем %s', [l_Login]);
//
with ExecutionContext.F_LoginData do
begin
Login := l_Login;
Password := l_Password;
end;
//
with TatLoginOperation.Create() do
try
Execute(ExecutionContext);
finally
Free;
end;
//#UC END# *48089F460352_4FF30FEB005D_impl*
end;//TatLoginFromListOperation.ExecuteSelf
procedure TatLoginFromListOperation.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4FF30FEB005D_var*
//#UC END# *479731C50290_4FF30FEB005D_var*
begin
//#UC START# *479731C50290_4FF30FEB005D_impl*
if f_IsLoop AND (f_LPStr <> '') AND f_LockFile.Acquire then
try
// перекладываем логин из использованных в свободные
with TStringList.Create do
try
LoadFromFile(f_UsedFN);
Delete(IndexOf(f_LPStr));
SaveToFile(f_UsedFN);
LoadFromFile(f_FreeFN);
Append(f_LPStr);
SaveToFile(f_FreeFN);
finally
Free;
end;
finally
f_LockFile.Release;
end;
//
FreeAndNil(f_LockFile);
inherited;
//#UC END# *479731C50290_4FF30FEB005D_impl*
end;//TatLoginFromListOperation.Cleanup
procedure TatLoginFromListOperation.InitParamList;
//#UC START# *48089F3701B4_4FF30FEB005D_var*
//#UC END# *48089F3701B4_4FF30FEB005D_var*
begin
//#UC START# *48089F3701B4_4FF30FEB005D_impl*
inherited;
with f_ParamList do
begin
Add( ParamType.Create('logins_file', 'Файл с логинами/паролями') );
Add( ParamType.Create('sync_file', 'Файл синхронизации') );
Add( ParamType.Create('is_loop', 'Логинится в цикле', 'false') );
end;
//#UC END# *48089F3701B4_4FF30FEB005D_impl*
end;//TatLoginFromListOperation.InitParamList
procedure TatLoginFromListOperation.AfterFillingParamList;
{* Вызывается генератором сценария после заполнения значений параметров.
Если операции надо что-то инициализировать, и для этого нужны значения параметров из сценария. }
//#UC START# *492188F70140_4FF30FEB005D_var*
//#UC END# *492188F70140_4FF30FEB005D_var*
begin
//#UC START# *492188F70140_4FF30FEB005D_impl*
inherited;
f_LockFile := TatLockFile.Create( Parameters['sync_file'].AsStr );
f_IsLoop := Parameters['is_loop'].AsBool;
//#UC END# *492188F70140_4FF30FEB005D_impl*
end;//TatLoginFromListOperation.AfterFillingParamList
end.
|
{
Double Commander
-------------------------------------------------------------------------
Structures describing drives.
Copyright (C) 2006-2010 Koblov Alexander (Alexx2000@mail.ru)
Copyright (C) 2010 Przemyslaw Nagay (cobines@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
unit uDrive;
{$mode objfpc}{$H+}
interface
uses
Classes;
type
TDriveType = (dtUnknown,
dtFlash, // Flash drive
dtFloppy, // 3.5'', ZIP drive, etc.
dtHardDisk, // Hard disk drive
dtNetwork, // Network share
dtOptical, // CD, DVD, Blu-Ray, etc.
dtRamDisk, // Ram-disk
dtRemovable, // Drive with removable media
dtRemovableUsb, // Drive connected via USB
dtVirtual, // Virtual drive
dtSpecial); // Special drive
{ TDrive }
// On Linux we also put here mount points other than drives.
TDrive = record
DisplayName, //<en Name displayed to the user.
Path, //<en Where this drive is or should be mounted (by /etc/fstab).
DriveLabel, //<en Drive label if filesystem on the drive supports it.
DeviceId: String; //<en Device ID that can be used for mounting, ejecting, etc.
DriveType : TDriveType;
FileSystem: String; //<en Filesystem on the drive
IsMediaAvailable: Boolean; //<en Is media available in a drive with removable media.
IsMediaEjectable: Boolean; //<en Can eject media by a command.
IsMediaRemovable: Boolean; //<en If the drive has removable media.
IsMounted: Boolean; //<en Is the drive mounted.
AutoMount: Boolean; //<en Should the drive be automounted
end;
PDrive = ^TDrive;
{ TDrivesList }
TDrivesList = class
private
FList: TFPList;
protected
function Get(Index: Integer): PDrive;
function GetCount: Integer;
public
constructor Create;
destructor Destroy; override;
function Add(ADrive: PDrive): Integer;
procedure Remove(Index: Integer);
procedure RemoveAll;
procedure Sort(Compare: TListSortCompare);
property Items[Index: Integer]: PDrive read Get; default;
property Count: Integer read GetCount;
end;
{en
Returns drive label or status description.
}
function GetDriveLabelOrStatus(Drive: PDrive): String;
implementation
uses
SysUtils, uLng;
function GetDriveLabelOrStatus(Drive: PDrive): String;
begin
if Drive^.DriveLabel <> EmptyStr then
Result := Drive^.DriveLabel
else if not Drive^.IsMediaAvailable then
Result := rsDriveNoMedia
else
Result := rsDriveNoLabel;
end;
{ TDrivesList }
constructor TDrivesList.Create;
begin
FList := TFPList.Create;
end;
destructor TDrivesList.Destroy;
begin
inherited Destroy;
RemoveAll;
FList.Free;
end;
function TDrivesList.Add(ADrive: PDrive): Integer;
begin
Result := FList.Add(ADrive);
end;
procedure TDrivesList.Remove(Index: Integer);
begin
if (Index >= 0) and (Index < FList.Count) then
begin
Dispose(PDrive(FList[Index]));
FList.Delete(Index);
end
else
raise ERangeError.Create('Invalid index');
end;
procedure TDrivesList.RemoveAll;
begin
while FList.Count > 0 do
Remove(0);
end;
procedure TDrivesList.Sort(Compare: TListSortCompare);
begin
FList.Sort(Compare);
end;
function TDrivesList.Get(Index: Integer): PDrive;
begin
if (Index >= 0) and (Index < FList.Count) then
begin
Result := PDrive(FList.Items[Index]);
end
else
raise ERangeError.Create('Invalid index');
end;
function TDrivesList.GetCount: Integer;
begin
Result := FList.Count;
end;
end.
|
program swap(input, output);
var
a, b : integer;
procedure swap(var a, b : integer);
var
temp : integer;
begin
temp := a;
a := b;
b := temp
end;
{}
begin
write('a: ');
read(a);
write('b: ');
read(b);
swap(a, b);
writeln('a, b: ', a, ' ', b)
{}
end.
|
unit caResultSet;
// Модуль: "w:\common\components\rtl\Garant\ComboAccess\caResultSet.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TcaResultSet" MUID: (56DFD1470338)
{$Include w:\common\components\rtl\Garant\ComboAccess\caDefine.inc}
interface
{$If Defined(UsePostgres) AND Defined(TestComboAccess)}
uses
l3IntfUses
, l3ProtoObject
, daInterfaces
, daFieldList
, daSelectFieldList
;
type
TcaResultSet = class(Tl3ProtoObject, IdaResultSet, IdaResultBuffer)
private
f_HTResultSet: IdaResultSet;
f_PGResultSet: IdaResultSet;
f_Fields: TdaFieldList;
f_FieldsDescription: TdaSelectFieldList;
protected
procedure Next;
function EOF: Boolean;
function IsEmpty: Boolean;
function Get_Field(const anAlias: AnsiString): IdaField;
procedure RegisterField(const aField: IdaField);
procedure UnregisterField(const aField: IdaField);
function FieldBufferPtr(FieldIndex: Integer): Pointer;
function CalcRecordCount: Integer;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aFieldsDescription: TdaSelectFieldList;
const aHTResultSet: IdaResultSet;
const aPGResultSet: IdaResultSet); reintroduce;
class function Make(aFieldsDescription: TdaSelectFieldList;
const aHTResultSet: IdaResultSet;
const aPGResultSet: IdaResultSet): IdaResultSet; reintroduce;
end;//TcaResultSet
{$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess)
implementation
{$If Defined(UsePostgres) AND Defined(TestComboAccess)}
uses
l3ImplUses
, SysUtils
, l3Types
, caField
//#UC START# *56DFD1470338impl_uses*
//#UC END# *56DFD1470338impl_uses*
;
constructor TcaResultSet.Create(aFieldsDescription: TdaSelectFieldList;
const aHTResultSet: IdaResultSet;
const aPGResultSet: IdaResultSet);
//#UC START# *56DFDC4B0032_56DFD1470338_var*
//#UC END# *56DFDC4B0032_56DFD1470338_var*
begin
//#UC START# *56DFDC4B0032_56DFD1470338_impl*
inherited Create;
f_HTResultSet := aHTResultSet;
f_PGResultSet := aPGResultSet;
f_Fields := TdaFieldList.Make;
aFieldsDescription.SetRefTo(f_FieldsDescription);
//#UC END# *56DFDC4B0032_56DFD1470338_impl*
end;//TcaResultSet.Create
class function TcaResultSet.Make(aFieldsDescription: TdaSelectFieldList;
const aHTResultSet: IdaResultSet;
const aPGResultSet: IdaResultSet): IdaResultSet;
var
l_Inst : TcaResultSet;
begin
l_Inst := Create(aFieldsDescription, aHTResultSet, aPGResultSet);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TcaResultSet.Make
procedure TcaResultSet.Next;
//#UC START# *5549C44C037A_56DFD1470338_var*
//#UC END# *5549C44C037A_56DFD1470338_var*
begin
//#UC START# *5549C44C037A_56DFD1470338_impl*
f_HTResultSet.Next;
f_PGResultSet.Next;
//#UC END# *5549C44C037A_56DFD1470338_impl*
end;//TcaResultSet.Next
function TcaResultSet.EOF: Boolean;
//#UC START# *5549C45A025C_56DFD1470338_var*
//#UC END# *5549C45A025C_56DFD1470338_var*
begin
//#UC START# *5549C45A025C_56DFD1470338_impl*
Result := f_HTResultSet.EOF;
Assert(Result = f_PGResultSet.EOF);
//#UC END# *5549C45A025C_56DFD1470338_impl*
end;//TcaResultSet.EOF
function TcaResultSet.IsEmpty: Boolean;
//#UC START# *558BF63203D7_56DFD1470338_var*
//#UC END# *558BF63203D7_56DFD1470338_var*
begin
//#UC START# *558BF63203D7_56DFD1470338_impl*
Result := f_HTResultSet.IsEmpty;
Assert(Result = f_PGResultSet.IsEmpty);
//#UC END# *558BF63203D7_56DFD1470338_impl*
end;//TcaResultSet.IsEmpty
function TcaResultSet.Get_Field(const anAlias: AnsiString): IdaField;
//#UC START# *5590FD57027D_56DFD1470338get_var*
var
l_IDX: Integer;
//#UC END# *5590FD57027D_56DFD1470338get_var*
begin
//#UC START# *5590FD57027D_56DFD1470338get_impl*
if f_Fields.FindData(anAlias, l_IDX, l3_siUnsorted) then
Result := f_Fields[l_IDX]
else
if f_FieldsDescription.FindData(anAlias, l_IDX) then
Result := TcaField.Make(Self, f_HTResultSet.Field[anAlias], f_PGResultSet.Field[anAlias])
else
Result := nil;
//#UC END# *5590FD57027D_56DFD1470338get_impl*
end;//TcaResultSet.Get_Field
procedure TcaResultSet.RegisterField(const aField: IdaField);
//#UC START# *55A63E22019B_56DFD1470338_var*
var
l_Dummy: Integer;
//#UC END# *55A63E22019B_56DFD1470338_var*
begin
//#UC START# *55A63E22019B_56DFD1470338_impl*
Assert(f_Fields.FindData(aField, l_Dummy) = False);
f_Fields.Add(aField);
//#UC END# *55A63E22019B_56DFD1470338_impl*
end;//TcaResultSet.RegisterField
procedure TcaResultSet.UnregisterField(const aField: IdaField);
//#UC START# *55A63E3D0122_56DFD1470338_var*
//#UC END# *55A63E3D0122_56DFD1470338_var*
begin
//#UC START# *55A63E3D0122_56DFD1470338_impl*
f_Fields.Remove(aField);
//#UC END# *55A63E3D0122_56DFD1470338_impl*
end;//TcaResultSet.UnregisterField
function TcaResultSet.FieldBufferPtr(FieldIndex: Integer): Pointer;
//#UC START# *55C8996702B1_56DFD1470338_var*
//#UC END# *55C8996702B1_56DFD1470338_var*
begin
//#UC START# *55C8996702B1_56DFD1470338_impl*
Result := nil;
Assert(False, 'Никогда не должны попасть сюда');
//#UC END# *55C8996702B1_56DFD1470338_impl*
end;//TcaResultSet.FieldBufferPtr
function TcaResultSet.CalcRecordCount: Integer;
//#UC START# *576278A800EA_56DFD1470338_var*
//#UC END# *576278A800EA_56DFD1470338_var*
begin
//#UC START# *576278A800EA_56DFD1470338_impl*
Result := f_HTResultSet.CalcRecordCount;
Assert(Result = f_PGResultSet.CalcRecordCount);
//#UC END# *576278A800EA_56DFD1470338_impl*
end;//TcaResultSet.CalcRecordCount
procedure TcaResultSet.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_56DFD1470338_var*
//#UC END# *479731C50290_56DFD1470338_var*
begin
//#UC START# *479731C50290_56DFD1470338_impl*
f_HTResultSet := nil;
f_PGResultSet := nil;
FreeAndNil(f_Fields);
FreeAndNil(f_FieldsDescription);
inherited;
//#UC END# *479731C50290_56DFD1470338_impl*
end;//TcaResultSet.Cleanup
{$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess)
end.
|
unit uAtualizacaoTablelaMSSQL;
interface
uses
System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, ZAbstractConnection,
ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset, System.SysUtils,
uAtualizacaobancoDeDados;
type
TAtualizacaoTabelaMSSQL = class(TAtualizabancoDeDados)
private
function tabelaExiste(aNomeTabela: string): Boolean;
procedure Clientes;
procedure UsuariosAcaoAcesso;
procedure AcaoAcesso;
procedure Acesso;
procedure Despesa;
procedure Receita;
procedure TipoDespesaREceita;
procedure Empresa;
procedure Venda;
procedure VendaItens;
procedure Fornecedor;
protected
public
constructor Create(vConecao: TZConnection);
destructor Destroy; override;
end;
implementation
{ TAtualizacaoTabelaMSSQL }
constructor TAtualizacaoTabelaMSSQL.Create(vConecao: TZConnection);
begin
ConexaoDB := vConecao;
Clientes;
Acesso;
AcaoAcesso;
UsuariosAcaoAcesso;
TipoDespesaREceita;
Despesa;
Receita;
Venda;
VendaItens;
AcaoAcesso;
Empresa;
Fornecedor;
end;
destructor TAtualizacaoTabelaMSSQL.Destroy;
begin
inherited;
end;
procedure TAtualizacaoTabelaMSSQL.Empresa;
begin
if not TabelaExiste('Empresa') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE Empresa ( ' +
'Emp_Cod int identity not null,' +
'EMP_CNPJ varchar(20) Null,'+
'EMP_RAZAOSOCIAL varchar(100) Null,' +
'EMP_FANTASIA varchar(50) Null,' +
'EMP_ENDERECO Varchar(50) Null,' +
'Emp_Numero int Null,' +
'Emp_Cep Varchar(9) Null,' +
'EMP_Bairro Varchar(20) Null,' +
'Emp_UF Varchar(2) Null,' +
'EMP_Cidade varchar(20) Null,' +
'Emp_Telefone1 Varchar(15) Null,' +
'Emp_Telefone2 Varchar(15) Null,' +
'EMP_IE Varchar(20) Null,' +
'EMP_IM Varchar(20) Null,' +
'EMP_Email Varchar(50) Null,' +
'PRIMARY KEY (Emp_Cod)' +
')');
end;
end;
procedure TAtualizacaoTabelaMSSQL.Fornecedor;
begin
if not TabelaExiste('Fornecedor') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE Fornecedor ( ' +
'Forn_Cod int identity not null,' +
'Forn_RAZAOSOCIAL varchar(100) Null,' +
'Forn_FANTASIA varchar(50) Null,' +
'Forn_ENDERECO Varchar(50) Null,' +
'Forn_Numero int Null,' +
'Forn_Cep Varchar(9) Null,' +
'Forn_Bairro Varchar(20) Null,' +
'Forn_UF Varchar(2) Null,' +
'Forn_Cidade varchar(20) Null,' +
'Forn_Telefone1 Varchar(15) Null,' +
'Forn_Telefone2 Varchar(15) Null,' +
'Forn_Nome Varchar(20) Null,' +
'Forn_Email Varchar(50) Null,' +
'Forn_Cnpj varchar(20) Null,'+
'PRIMARY KEY (Forn_Cod)' +
')');
end;
end;
function TAtualizacaoTabelaMSSQL.TabelaExiste(aNomeTabela: string): Boolean;
var
Qry: TZQuery;
begin
try
Result := False;
Qry := TZQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add(' SELECT OBJECT_ID (:NomeTabela) As ID ');
Qry.ParamByName('NomeTabela').AsString := aNomeTabela;
Qry.Open;
if Qry.FieldByName('ID').AsInteger > 0 then
Result := True;
if Qry.FieldByName('ID').AsInteger > 0 then
Result := True;
finally
Qry.Close;
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
procedure TAtualizacaoTabelaMSSQL.Clientes;
begin
if not TabelaExiste('Clientes') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE Clientes ( ' +
'Cli_Cod int identity not null,' +
'Cli_ID_Veiculo Int,' +
'Cli_Nome varchar(50),' +
'Cli_Razao Varchar(50),' +
'Cli_Fantasia varchar(50),' +
'Cli_CNPJ_CPF Varchar(14),' +
'Cli_RG Varchar(11),' +
'Cli_Logradouro Varchar(50),' +
'Cli_Numero int,' +
'Cli_Cep Varchar(9),' +
'Cli_Bairro Varchar(20),' +
'Cli_UF Varchar(2),' +
'Cli_Cidade varchar(20),' +
'Cli_Telefone1 Varchar(15),' +
'Cli_Telefone2 Varchar(15),' +
'Cli_TipoVeiculo Varchar(10),' +
'Cli_AnoVeiculo Varchar(4),' +
'Cli_CodVeiculi int, ' +
'Cli_Email Varchar(50),' +
'Cli_DataNascimento datetime,' +
'PRIMARY KEY (Cli_Cod)' +
')');
end;
end;
procedure TAtualizacaoTabelaMSSQL.AcaoAcesso;
begin
if not TabelaExiste('acaoAcesso') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE acaoAcesso ( ' +
' acaoAcessoId int identity(1,1) not null, ' +
' descricao varchar(100) not null, ' +
' chave varchar(60) not null unique, ' +
' PRIMARY KEY (acaoAcessoId) ' +
' ) ');
end;
end;
procedure TAtualizacaoTabelaMSSQL.Acesso;
begin
if not TabelaExiste('Acesso') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE Acesso'+
'('+
'Acesso_id int identity not null ,'+
'Login Varchar(10) not null ,'+
'Senha varchar(8) not null ,'+
'Nome varchar(20) null,'+
'Tipo varchar (10) null,'+
'setor varchar (10) null,'+
'constraint PK_ID_Senha PRIMARY KEY (Acesso_id))');
end;
end;
procedure TAtualizacaoTabelaMSSQL.UsuariosAcaoAcesso;
begin
if not TabelaExiste('usuariosAcaoAcesso') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE usuariosAcaoAcesso( ' +
' usuarioId int NOT NULL, ' +
' acaoAcessoId int NOT NULL, ' +
' ativo bit not null default 1, ' +
' PRIMARY KEY (usuarioId, acaoAcessoId), ' +
' CONSTRAINT FK_UsuarioAcaoAcessoUsuario ' +
' FOREIGN KEY (usuarioId) references login (login), ' +
' CONSTRAINT FK_UsuarioAcaoAcessoAcaoAcesso ' +
' FOREIGN KEY (acaoAcessoId) references acaoAcesso(acaoAcessoId), ' +
' ) ');
end;
end;
procedure TAtualizacaoTabelaMSSQL.TipoDespesaREceita;
begin
if not TabelaExiste('TIPO_DESPESA_RECEITA') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE TIPO_DESPESA_RECEITA(' +
'TIPODR_Cod int identity not null,' +
'TIPODR_Tipo varchar (10),' +
'TIPODR_Desc varchar (20),' +
'PRIMARY KEY (TIPODR_COD))');
end;
end;
procedure TAtualizacaoTabelaMSSQL.Despesa;
begin
if not TabelaExiste('DESPESA') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE DESPESA(' +
'Desc_Cod int identity not null,' +
'Desc_Tipo integer,' +
'Desc_Descricao varchar(100),' +
'Desc_dataVencimento dateTime,' +
'Desc_Valor numeric(15,3),' +
'Desc_Status varchar(10),' +
'primary key (Desc_Cod),' +
'constraint FkDesc_Tipo foreign key (Desc_Tipo)' +
'references TIPO_DESPESA_RECEITA (TIPODR_Cod))');
end;
end;
procedure TAtualizacaoTabelaMSSQL.Receita;
begin
if not TabelaExiste('RECEITA') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE RECEITA(' +
'Rec_Cod int identity not null,' +
'Rec_Tipo integer,' +
'Rec_Descricao varchar(100),' +
'Rec_dataRecebimento dateTime,' +
'Rec_Valor numeric(15,3),' +
'Rec_Status varchar(10),' +
'primary key (Rec_Cod),' +
'constraint FkRec_Tipo foreign key (Rec_Tipo)' +
'references TIPO_DESPESA_RECEITA (TIPODR_Cod))');
end;
end;
procedure TAtualizacaoTabelaMSSQL.Venda;
begin
if not TabelaExiste('VENDA') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE VENDA'+
'('+
'Vend_Id int identity not null ,'+
'Vend_CodCli INT NOT NULL,'+
'Vend_DataVenda DATEtime,'+
'Vend_TotalVenda Numeric(15,3),'+
//'Vend_Qtde int,'+
'Vend_obs varchar(255) NULL,'+
'Vend_Veiculo varchar(20) NULL,'+
'Vend_Status varchar(10) NULL,'+
'Vend_FormaPagto varchar(20) NULL,'+
'Vend_CodOrcamento int NULL,'+
'PRIMARY KEY (Vend_Id),'+
'constraint FK_VENDACLIENTE FOREIGN KEY (Vend_CODCLI) references CLIENTES (Cli_Cod))');
end;
end;
procedure TAtualizacaoTabelaMSSQL.VendaItens;
begin
if not TabelaExiste('VENDAITENS') then
begin
ExecutaDiretoBancoDeDados('CREATE TABLE VendaItens'+
'('+
'VendItens_Id int identity not null ,'+
'VendItens_Operacao varchar(20),'+
'VendItens_prodId int,'+
'VendItens_ValorUnitario Numeric(15,3),'+
'VendItens_Quantidade int,'+
'VendItens_Desc numeric(15,3) null,'+
'VendItens_Hora Numeric(15,3) null,'+
'VendItens_Pintura Numeric(15,3) null,'+
'VendItens_TotalProduto Numeric(15,3) not null,' +
'VendItens_TipoPeca varchar(20) null,'+
'VendItens_IdVenda int ,'+
'PRIMARY KEY (VendItens_Id),'+
'CONSTRAINT FK_VendItens_idVenda Foreign Key (VendItens_IdVenda) references Venda (Vend_Id),'+
'CONSTRAINT FK_VendItens_prodId Foreign Key (VendItens_prodId) references Produtos (Prod_Cod))');
end;
end;
end.
|
unit StarVoice;
interface
uses
Windows, SysUtils,
DirectSound,
CompressIntf, FIFOIntf,
VoiceTx, VoiceRx;
type
EVoiceChat = class(Exception);
TVoiceChat = class;
TOnDSoundRequest = procedure(Sender : TVoiceChat; Request : boolean) of object;
TVoiceChat =
class
public
constructor Create(const aDSound : IDirectSound);
destructor Destroy; override;
private
fTxObject : TVoiceTx;
fRxObject : TVoiceRx;
fCompressor : ICompressor;
fDecompressor : IDecompressor;
private
fTransmit : boolean;
fReceive : boolean;
fOnAir : boolean;
procedure SetTransmit(aTransmit : boolean);
procedure SetReceive(aReceive : boolean);
procedure SetOnAir(aOnAir : boolean);
function GetDirectSound : IDirectSound;
procedure SetDirectSound(const aDSound : IDirectSound);
function GetSendFIFO : IFIFO;
function GetRecvFIFO : IFIFO;
public
property DirectSound : IDirectSound read GetDirectSound write SetDirectSound;
public
property SendFIFO : IFIFO read GetSendFIFO;
property RecvFIFO : IFIFO read GetRecvFIFO;
public
property Transmit : boolean read fTransmit write SetTransmit;
property Receive : boolean read fReceive write SetReceive;
property OnAir : boolean read fOnAir write SetOnAir;
public
function VUMeter : single;
procedure ResetCompressor;
procedure ResetDecompressor;
private
fOnDSoundRequest : TOnDSoundRequest;
public
property OnDSoundRequest : TOnDSoundRequest read fOnDSoundRequest write fOnDSoundRequest;
end;
implementation
uses
mmSystem,
Forms,
FIFOUtils, CodecIntf;
constructor TVoiceChat.Create(const aDSound : IDirectSound);
begin
inherited Create;
if aDSound <> nil
then
begin
Codecs.Initialize(ExtractFilePath(paramstr(0)));
if Codecs.Count <= 0
then raise EVoiceChat.Create('No codecs were found.');
fCompressor := Codecs.OpenCompressor(0);
fCompressor.SetOutputFIFO(CreateFIFO);
fDecompressor := Codecs.OpenDecompressor(0);
fDecompressor.SetInputFIFO(CreateFIFO);
fTxObject := TVoiceTx.Create;
fTxObject.Compressor := fCompressor;
fRxObject := TVoiceRx.Create;
fRxObject.Decompressor := fDecompressor;
end
else raise Exception.Create( 'Multimedia system is busy.' );
end;
destructor TVoiceChat.Destroy;
begin
fTxObject.Free;
fRxObject.Free;
fCompressor := nil;
fDecompressor := nil;
inherited;
end;
procedure TVoiceChat.SetTransmit(aTransmit : boolean);
begin
if aTransmit <> fTransmit
then
begin
if aTransmit
then fTxObject.Start
else fTxObject.Stop;
fTransmit := aTransmit;
end;
end;
procedure TVoiceChat.SetReceive(aReceive : boolean);
begin
if aReceive <> fReceive
then
begin
if aReceive
then fRxObject.Start
else fRxObject.Stop;
fReceive := aReceive;
end;
end;
procedure TVoiceChat.SetOnAir(aOnAir : boolean);
begin
if aOnAir
then
begin
{$IFNDEF HALFDUPLEX} // this is just for test purposes
try
Transmit := true;
except
{$ENDIF}
// Try half duplex, Stop & kill DSound first
Receive := false;
DirectSound := nil;
if assigned(fOnDsoundRequest)
then fOnDsoundRequest(Self, false);
Transmit := true;
{$IFNDEF HALFDUPLEX}
end;
{$ENDIF}
end
else
begin
// Stop recording & play if stopped
Transmit := false;
if assigned(fOnDsoundRequest) and not Receive
then fOnDsoundRequest(Self, true);
Receive := true;
end;
fOnAir := aOnAir;
end;
function TVoiceChat.GetDirectSound : IDirectSound;
begin
Result := fRxObject.DirectSound;
end;
procedure TVoiceChat.SetDirectSound(const aDSound : IDirectSound);
begin
fRxObject.DirectSound := aDSound;
end;
function TVoiceChat.GetSendFIFO : IFIFO;
begin
fCompressor.GetOutputFIFO(Result);
end;
function TVoiceChat.GetRecvFIFO : IFIFO;
begin
fDecompressor.GetInputFIFO(Result);
end;
function TVoiceChat.VUMeter : single;
begin
if fTransmit
then Result := fTxObject.Peak
else Result := 0;
end;
procedure TVoiceChat.ResetCompressor;
begin
fCompressor.Reset;
end;
procedure TVoiceChat.ResetDecompressor;
begin
fDecompressor.Reset;
end;
end.
|
{
Copyright (c) 2017-18 Pascal Riekenberg
LazProfiler: IDE Addon - Result Window
See the file COPYING.modifiedLGPL.txt, included in this distribution,
for details about the license.
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.
**********************************************************************}
unit LazProfilerWindow;
{$mode objfpc}{$H+}
interface
uses
Classes,
ComCtrls,
Controls,
Dialogs,
FileUtil,
Forms,
Generics.Collections,
Generics.Defaults,
Graphics, StdCtrls,
LazProfilerCore,
ProjectIntf,
SysUtils,
Laz.VirtualTrees,
vtvObject;
type
{ TLazProfilerForm }
TLazProfilerForm = class(TForm)
CBActive: TCheckBox;
Icons: TImageList;
PageControl: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
VST: TLazVirtualStringTree;
procedure CBActiveChange(Sender: TObject);
procedure VSTBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect);
procedure VSTChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure VSTCollapsedExpanded(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure VSTCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
procedure VSTDblClick(Sender: TObject);
procedure VSTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer);
procedure VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String);
procedure VSTHeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo);
procedure VSTInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal);
procedure VSTInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure VSTResize(Sender: TObject);
procedure VSTStructureChange(Sender: TBaseVirtualTree; Node: PVirtualNode; Reason: TChangeReason);
private
fData: TLPPasProcList;
fTreeData: TvtvObjList;
fDataChanged: Boolean;
fMaxColSize: array[0..cColumnCount - 1] of Integer;
fProcList,
fClassList,
fUnitList,
fPackageList: TvtvObjList;
procedure SetData(pData: TLPPasProcList);
procedure PrepareData;
procedure RebuildTree;
procedure RebuildLines;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
property Data: TLPPasProcList read fData write SetData;
property DataChanged: Boolean read fDataChanged write fDataChanged;
end;
{ TLPProcClassComparer }
TLPProcClassComparer = class(specialize TComparer<TLPPasProc>)
function Compare(constref Left, Right: TLPPasProc): Integer; override; overload;
end;
{ TLPProcUnitComparer }
TLPProcUnitComparer = class(specialize TComparer<TLPPasProc>)
function Compare(constref Left, Right: TLPPasProc): Integer; override; overload;
end;
{ TLPProcPackageComparer }
TLPProcPackageComparer = class(specialize TComparer<TLPPasProc>)
function Compare(constref Left, Right: TLPPasProc): Integer; override; overload;
end;
implementation
uses
LazIDEIntf,
LazLogger,
LazProfilerAddon,
SrcEditorIntf;
var
ProcClassComparer: TLPProcClassComparer;
ProcUnitComparer: TLPProcUnitComparer;
ProcPackageComparer: TLPProcPackageComparer;
{$R *.lfm}
{ TLPProcPackageComparer }
function TLPProcPackageComparer.Compare(constref Left, Right: TLPPasProc): Integer;
begin
if Left.PackageIsProject
and not Right.PackageIsProject then
Result := -1
else if Right.PackageIsProject
and not Left.PackageIsProject then
Result := 1
else
Result := strcomp(PChar(Left.PackageNameUp), PChar(Right.PackageNameUp));
if Result = 0 then Result := strcomp(PChar(Left.UnitNameUp), PChar(Right.UnitNameUp));
if Result = 0 then Result := strcomp(PChar(Left.NameOfClassUp), PChar(Right.NameOfClassUp));
if Result = 0 then Result := strcomp(PChar(Left.NameUp), PChar(Right.NameUp));
end;
{ TLPProcUnitComparer }
function TLPProcUnitComparer.Compare(constref Left, Right: TLPPasProc): Integer;
begin
Result := strcomp(PChar(Left.UnitNameUp), PChar(Right.UnitNameUp));
if Result = 0 then Result := strcomp(PChar(Left.NameOfClassUp), PChar(Right.NameOfClassUp));
if Result = 0 then Result := strcomp(PChar(Left.NameUp), PChar(Right.NameUp));
end;
{ TLPProcClassComparer }
function TLPProcClassComparer.Compare(constref Left, Right: TLPPasProc): Integer;
begin
Result := strcomp(PChar(Left.NameOfClassUp), PChar(Right.NameOfClassUp));
if Result = 0 then Result := strcomp(PChar(Left.NameUp), PChar(Right.NameUp));
end;
{ TLazProfilerForm }
procedure TLazProfilerForm.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String);
var
lData: PvtvObj;
begin
lData := VST.GetNodeData(Node);
CellText := lData^.CellText(Column, TextType);
end;
procedure TLazProfilerForm.VSTHeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo);
var
lFullRebuild: Boolean;
begin
//DebugLn('*** LazProfiler: HeaderClick');
lFullRebuild := False;
Screen.Cursor := crHourGlass;
try
if VST.Header.SortColumn = HitInfo.Column then begin
// swap current sort order
if VST.Header.SortDirection = sdAscending then
VST.Header.SortDirection := sdDescending
else
VST.Header.SortDirection := sdAscending;
end else begin
// different column clicked
// default sort direction
if HitInfo.Column in [cCountCol, cPerNetCol, cSumNetCol, cPerGrossCol, cSumGrossCol, cAvgNetCol, cAvgGrossCol] then
VST.Header.SortDirection := sdDescending
else
VST.Header.SortDirection := sdAscending;
// rebuild of layout needed?
lFullRebuild := (
(VST.Header.SortColumn in [cNameCol, cCountCol, cPerNetCol, cSumNetCol, cPerGrossCol, cSumGrossCol, cAvgNetCol, cAvgGrossCol])
and (HitInfo.Column in [cClassCol, cUnitCol, cPackageCol])
) or (
(VST.Header.SortColumn in [cClassCol, cUnitCol, cPackageCol])
and (HitInfo.Column <> VST.Header.SortColumn)
);
VST.Header.SortColumn := HitInfo.Column;
end;
if lFullRebuild then begin
RebuildTree;
end else begin
if fTreeData.Count > 0 then begin
VST.SortTree(VST.Header.SortColumn, VST.Header.SortDirection);
RebuildLines;
VST.Invalidate;
end;
end;
Addon.SortColumn := VST.Header.SortColumn;
Addon.SortDirection := Integer(VST.Header.SortDirection);
fDataChanged := True;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TLazProfilerForm.VSTInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal);
var
lData: PvtvObj;
begin
lData := VST.GetNodeData(Node);
ChildCount := lData^.InitChildren;
end;
procedure TLazProfilerForm.VSTChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
var
lData: TvtvObj;
begin
lData := PvtvObj(VST.GetNodeData(Node))^;
lData.CheckState := Node^.CheckState;
fDataChanged := True;
end;
procedure TLazProfilerForm.VSTBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect);
var
BG: TColor;
lData: TvtvObj;
begin
if (CellPaintMode = cpmGetContentMargin) then
Exit;
BG := TargetCanvas.Brush.Color;
lData := PvtvObj(Sender.GetNodeData(Node))^;
if lData.Line mod 2 = 0 then
BG := clBtnFace;
TargetCanvas.Brush.Color := BG;
TargetCanvas.FillRect(CellRect);
end;
procedure TLazProfilerForm.CBActiveChange(Sender: TObject);
begin
Addon.Active := CBActive.Checked;
end;
procedure TLazProfilerForm.VSTCollapsedExpanded(Sender: TBaseVirtualTree; Node: PVirtualNode);
var
lData: TvtvObj;
begin
lData := PvtvObj(Sender.GetNodeData(Node))^;
lData.UpdateExpanded;
VSTStructureChange(Sender, Node, crIgnore);
fDataChanged := True;
end;
procedure TLazProfilerForm.VSTCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
var
lP1, lP2: TLPPasProc;
function Compare(pV1, pV2: QWord): Integer;
begin
if pV1 > pV2 then
Result := 1
else if pV1 < pV2 then
Result := -1
else
Result := 0;
end;
begin
lP1 := PLPvtvProc(VST.GetNodeData(Node1))^.PasProc;
lP2 := PLPvtvProc(VST.GetNodeData(Node2))^.PasProc;
case Column of
cNameCol:
Result := strcomp(PChar(lP1.NameUp), PChar(lP2.NameUp));
cClassCol: begin
Result := strcomp(PChar(lP1.NameOfClassUp), PChar(lP2.NameOfClassUp));
if Result = 0 then Result := strcomp(PChar(lP1.NameUp), PChar(lP2.NameUp))
end;
cUnitCol: begin
Result := strcomp(PChar(lP1.UnitNameUp), PChar(lP2.UnitNameUp));
if Result = 0 then Result := strcomp(PChar(lP1.NameOfClassUp), PChar(lP2.NameOfClassUp));
if Result = 0 then Result := strcomp(PChar(lP1.NameUp), PChar(lP2.NameUp))
end;
cPackageCol: begin
// Project immer oben
if lP1.PackageIsProject
and not lP2.PackageIsProject then begin
if VST.Header.SortDirection = sdAscending then
Result := -1
else
Result := 1;
end else if lP2.PackageIsProject
and not lP1.PackageIsProject then begin
if VST.Header.SortDirection = sdAscending then
Result := 1
else
Result := -1;
end else
Result := strcomp(PChar(lP1.PackageNameUp), PChar(lP2.PackageNameUp));
if Result = 0 then Result := strcomp(PChar(lP1.UnitNameUp), PChar(lP2.UnitNameUp));
if Result = 0 then Result := strcomp(PChar(lP1.NameOfClassUp), PChar(lP2.NameOfClassUp));
if Result = 0 then Result := strcomp(PChar(lP1.NameUp), PChar(lP2.NameUp))
end;
cCountCol:
Result := lP1.Count - lP2.Count;
cPerNetCol,
cSumNetCol:
Result := Compare(lP1.Net, lP2.Net);
cPerGrossCol,
cSumGrossCol:
Result := Compare(lP1.Gross, lP2.Gross);
cAvgNetCol:
Result := Compare(lP1.AvgNet, lP2.AvgNet);
cAvgGrossCol:
Result := Compare(lP1.AvgGross, lP2.AvgGross);
end;
//Debugln('compare '+lp1.Name+' - '+lp2.Name+' Col='+IntToStr(Column)+' Result='+IntToStr(Result));
end;
procedure TLazProfilerForm.VSTDblClick(Sender: TObject);
var
lData: TLPPasProc;
lNode: PVirtualNode;
lFile: TLazProjectFile;
lSrcIntf: TSourceEditorInterface;
begin
lNode := VST.FocusedNode;
if vsHasChildren in lNode^.States then
Exit;
lData := PLPvtvProc(VST.GetNodeData(lNode))^.PasProc;
if not (lData is TLPPasProc) then
Exit;
if LazarusIDE.DoOpenEditorFile(lData.FileName, -1, -1, [ofAddToRecent]) <> mrOK then
exit;
lSrcIntf := SourceEditorManagerIntf.SourceEditorIntfWithFilename(lData.FileName);
if not Assigned(lSrcIntf) then
exit;
lSrcIntf.CursorTextXY := Classes.Point(1, lData.Row + 1);
end;
procedure TLazProfilerForm.VSTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer);
var
lData: PvtvObj;
begin
lData := VST.GetNodeData(Node);
ImageIndex := lData^.ImageIndex(Column);
end;
procedure TLazProfilerForm.VSTInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var
lData, lParentData: PvtvObj;
begin
lData := VST.GetNodeData(Node);
if not Assigned(ParentNode) then begin
// Root nodes
lData^ := fTreeData[Node^.Index];
end else begin
// Child nodes
lParentData := VST.GetNodeData(ParentNode);
lData^ := lParentData^.Childs[Node^.Index];
end;
lData^.InitNode(Sender, Node);
InitialStates := lData^.Initialstates;
end;
procedure TLazProfilerForm.VSTResize(Sender: TObject);
var
i, lSize, lMaxSize, lMinSize, lCalcSize: Integer;
begin
with Sender as TVirtualStringTree do begin
UpdateVerticalScrollBar(False);
lSize := ClientRect.Right - ClientRect.Left;
lMaxSize := 0;
for i := 0 to cColumnCount - 1 do
lMaxSize := lMaxSize + fMaxColSize[i];
if lMaxSize <= lSize then begin
// width is enough
for i := cColumnCount - 1 downto 1 do begin
Header.Columns[i].Width := fMaxColSize[i];
lSize := lSize - fMaxColSize[i];
end;
Header.Columns[0].Width := lSize;
end else begin
// width is to small
for i := cColumnCount - 1 downto cCountCol do begin
Header.Columns[i].Width := fMaxColSize[i];
lSize := lSize - fMaxColSize[i];
lMaxSize := lMaxSize - fMaxColSize[i];
end;
lMinSize := 0;
for i := 0 to cPackageCol do begin
lMinSize := lMinSize + Header.Columns[i].MinWidth;
end;
if lMinSize <= lSize then begin
// min width is enough -> split space (relative to min width)
for i := cPackageCol downto 0 do begin
lCalcSize := round(lSize * Header.Columns[i].MinWidth / lMinSize);
if (lCalcSize > fMaxColSize[i])
and (i <> 0) then begin
Header.Columns[i].Width := fMaxColSize[i];
end else begin
Header.Columns[i].Width := lCalcSize;
end;
lSize := lSize - Header.Columns[i].Width;
lMinSize := lMinSize - Header.Columns[i].MinWidth;
end;
end else begin
for i := 0 to cPackageCol do
Header.Columns[i].Width := Header.Columns[i].MinWidth;
end;
end;
end;
end;
procedure TLazProfilerForm.VSTStructureChange(Sender: TBaseVirtualTree; Node: PVirtualNode; Reason: TChangeReason);
var
i, lNewColSize: Integer;
begin
with Sender as TVirtualStringTree do begin
for i := 0 to cColumnCount - 1 do begin
lNewColSize := GetMaxColumnWidth(i);
if lNewColSize < Header.Columns[i].MinWidth then
lNewColSize := Header.Columns[i].MinWidth;
if fMaxColSize[i] <> lNewColSize then begin
fMaxColSize[i] := lNewColSize;
end;
end;
end;
VSTResize(Sender);
RebuildLines;
end;
procedure TLazProfilerForm.SetData(pData: TLPPasProcList);
begin
fData := pData;
VST.RootNodeCount := 0;
if not Assigned(pData) then
Exit;
//DebugLn('fData.Count=%d', [fData.Count]);
PrepareData;
RebuildTree;
fDataChanged := False;
end;
procedure TLazProfilerForm.PrepareData;
var
i: Integer;
lPasProc: TLPPasProc;
lList: TLPPasProcList;
lPasClass: TLPvtvPasClass;
lPasUnit: TLPvtvPasUnit;
lPasPackage: TLPvtvPasPackage;
begin
fProcList.Clear;
fClassList.Clear;
fUnitList.Clear;
fPackageList.Clear;
lList := TLPPasProcList.Create(False);
try
for i := 0 to fData.Count - 1 do begin
lPasProc := fData[i];
// default
fProcList.Add(TLPvtvPasProc.Create(lPasProc));
// temp list
lList.Add(lPasProc);
end;
// class
lPasClass := Nil;
lList.Sort(ProcClassComparer);
for i := 0 to lList.Count - 1 do begin
lPasProc := lList[i];
if not Assigned(lPasClass)
or (lPasClass.PasProc.NameOfClassUp <> lPasProc.NameOfClassUp) then begin
if Assigned(lPasClass)
and (lPasClass.PasProc.NameOfClass = '') then
lPasClass.Free;
lPasClass := TLPvtvPasClass.Create(lPasProc.NameOfClass, lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName);
if lPasClass.PasProc.NameOfClass <> '' then begin
lPasClass.PasClass := lPasProc.PasClass;
fClassList.Add(lPasClass);
end;
end;
if lPasClass.PasProc.NameOfClass = '' then begin
fClassList.Add(TLPvtvPasProc.Create(lPasProc));
lPasClass.PasClass := lPasProc.PasClass;
end else
lPasClass.Add(TLPvtvPasProc.Create(lPasProc));
end;
if Assigned(lPasClass)
and (lPasClass.PasProc.NameOfClass = '') then
lPasClass.Free;
// unit
lPasUnit := Nil;
lPasClass := Nil;
lList.Sort(ProcUnitComparer);
for i := 0 to lList.Count - 1 do begin
lPasProc := lList[i];
if not Assigned(lPasUnit)
or (lPasUnit.PasProc.UnitName <> lPasProc.UnitName) then begin
lPasUnit := TLPvtvPasUnit.Create(lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName);
lPasUnit.PasUnit := lPasProc.PasUnit;
fUnitList.Add(lPasUnit);
end;
if not Assigned(lPasClass)
or (lPasClass.PasProc.NameOfClassUp <> lPasProc.NameOfClassUp) then begin
if Assigned(lPasClass)
and (lPasClass.PasProc.NameOfClass = '') then
lPasClass.Free;
lPasClass := TLPvtvPasClass.Create(lPasProc.NameOfClass, lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName);
if lPasClass.PasProc.NameOfClass <> '' then begin
lPasClass.PasClass := lPasProc.PasClass;
lPasUnit.Add(lPasClass);
end;
end;
if lPasClass.PasProc.NameOfClass = '' then
lPasUnit.Add(TLPvtvPasProc.Create(lPasProc))
else
lPasClass.Add(TLPvtvPasProc.Create(lPasProc));
end;
if Assigned(lPasClass)
and (lPasClass.PasProc.NameOfClass = '') then
lPasClass.Free;
// package
lPasPackage := Nil;
lPasUnit := Nil;
lPasClass := Nil;
lList.Sort(ProcPackageComparer);
for i := 0 to lList.Count - 1 do begin
lPasProc := lList[i];
if not Assigned(lPasPackage)
or (lPasPackage.PasProc.PackageNameUp <> lPasProc.PackageNameUp) then begin
lPasPackage := TLPvtvPasPackage.Create(lPasProc.PackageName);
lPasPackage.PasPackage := lPasProc.PasPackage;
fPackageList.Add(lPasPackage);
end;
if not Assigned(lPasUnit)
or (lPasUnit.PasProc.UnitName <> lPasProc.UnitName) then begin
lPasUnit := TLPvtvPasUnit.Create(lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName);
lPasUnit.PasUnit := lPasProc.PasUnit;
lPasPackage.add(lPasUnit);
end;
if not Assigned(lPasClass)
or (lPasClass.PasProc.NameOfClassUp <> lPasProc.NameOfClassUp) then begin
if Assigned(lPasClass)
and (lPasClass.PasProc.NameOfClass = '') then
lPasClass.Free;
lPasClass := TLPvtvPasClass.Create(lPasProc.NameOfClass, lPasProc.UnitName, lPasProc.FileName, lPasProc.PackageName);
if lPasClass.PasProc.NameOfClass <> '' then begin
lPasClass.PasClass := lPasProc.PasClass;
lPasUnit.Add(lPasClass);
end;
end;
if lPasClass.PasProc.NameOfClass = '' then
lPasUnit.Add(TLPvtvPasProc.Create(lPasProc))
else
lPasClass.Add(TLPvtvPasProc.Create(lPasProc));
end;
if Assigned(lPasClass)
and (lPasClass.PasProc.NameOfClass = '') then
lPasClass.Free;
finally
lList.Free;
end;
end;
procedure TLazProfilerForm.RebuildTree;
begin
VST.RootNodeCount := 0;
case VST.Header.SortColumn of
cClassCol:
fTreeData := fClassList;
cUnitCol:
fTreeData := fUnitList;
cPackageCol:
fTreeData := fPackageList;
else
fTreeData := fProcList;
end;
if fTreeData.Count > 0 then begin
VST.RootNodeCount := fTreeData.Count;
VST.SortTree(VST.Header.SortColumn, VST.Header.SortDirection);
VSTStructureChange(VST, nil, crIgnore);
end;
end;
procedure TLazProfilerForm.RebuildLines;
var
lNode: PVirtualNode;
lData: TvtvObj;
lLine: Integer;
begin
lLine := 1;
lNode := VST.GetFirstVisible;
while Assigned(lNode) do begin
lData := PvtvObj(VST.GetNodeData(lNode))^;
lData.Line := lLine;
inc(lLine);
lNode := VST.GetNextVisible(lNode);
end;
end;
constructor TLazProfilerForm.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
fProcList := TvtvObjList.Create(True);
fClassList := TvtvObjList.Create(True);
fUnitList := TvtvObjList.Create(True);
fPackageList := TvtvObjList.Create(True);
VST.NodeDataSize := SizeOf(PLPPasProc);
end;
destructor TLazProfilerForm.Destroy;
begin
fProcList.Free;
fClassList.Free;
fUnitList.Free;
fPackageList.Free;
inherited Destroy;
end;
initialization
ProcClassComparer := TLPProcClassComparer.Create;
ProcUnitComparer := TLPProcUnitComparer.Create;
ProcPackageComparer := TLPProcPackageComparer.Create;
finalization;
ProcClassComparer.Free;
ProcUnitComparer.Free;
ProcPackageComparer.Free;
end.
|
unit uQuadroController;
interface
uses
System.SysUtils, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms,
Data.DBXJSON, Data.DBXJSONReflect;
type
TQuadroController = class
private
function VerificarChamadoEmAberto(AIdUsuario: Integer): Boolean;
function VerificarAtividadeEmAberto(AIdUsuario: Integer): Boolean;
function VerificarSolicitacaoEmAberto(AIdUsuario: Integer): Boolean;
public
procedure VerificarTarefaEmAberto(AIdUsuario, APrograma: Integer);
end;
implementation
{ TQuadroController }
function TQuadroController.VerificarAtividadeEmAberto(AIdUsuario: Integer): Boolean;
var
Negocio: TServerMethods1Client;
begin
Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection);
try
try
Result := Negocio.VerificarQuadroTarefasEmAberto(AIdUsuario, CAtividadePrograma);
except
On E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
finally
FreeAndNil(Negocio);
end;
end;
function TQuadroController.VerificarChamadoEmAberto(AIdUsuario: Integer): Boolean;
var
Negocio: TServerMethods1Client;
begin
Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection);
try
try
Result := Negocio.VerificarQuadroTarefasEmAberto(AIdUsuario, CChamadoPrograma);
except
On E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
finally
FreeAndNil(Negocio);
end;
end;
function TQuadroController.VerificarSolicitacaoEmAberto(AIdUsuario: Integer): Boolean;
var
Negocio: TServerMethods1Client;
begin
Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection);
try
try
Result := Negocio.VerificarQuadroTarefasEmAberto(AIdUsuario, CSolicitacaoPrograma);
except
On E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
finally
FreeAndNil(Negocio);
end;
end;
procedure TQuadroController.VerificarTarefaEmAberto(AIdUsuario,
APrograma: Integer);
begin
// Em desenvolvimento = 12 id=14
// Em Teste Desenvolvimento = 14 id=16
// Em Teste Final = 16 id=18
try
if APrograma = CChamadoPrograma then // chamado
begin
if VerificarChamadoEmAberto(AIdUsuario) then
raise Exception.Create('Usuário com Atividades ou Solicitações em Aberto!');
end;
if APrograma = CAtividadePrograma then // atividade
begin
if VerificarAtividadeEmAberto(AIdUsuario) then
raise Exception.Create('Usuário com Chamados ou Solicitações em Aberto!');
end;
if APrograma = CSolicitacaoPrograma then // Solicitacao
begin
if VerificarSolicitacaoEmAberto(AIdUsuario) then
raise Exception.Create('Usuário com Chamado ou Atividade em Aberto!');
end;
except
on E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Androidapi.JNI.JavaUtil;
interface
uses
Androidapi.JNIBridge,
Androidapi.JNI.JavaTypes;
type
// ===== Forward declarations =====
JAbstractCollection = interface;//java.util.AbstractCollection
JAbstractList = interface;//java.util.AbstractList
JAbstractMap = interface;//java.util.AbstractMap
JAbstractSet = interface;//java.util.AbstractSet
JArrayList = interface;//java.util.ArrayList
JBitSet = interface;//java.util.BitSet
JCalendar = interface;//java.util.Calendar
JCollection = interface;//java.util.Collection
JComparator = interface;//java.util.Comparator
JDate = interface;//java.util.Date
JDictionary = interface;//java.util.Dictionary
JEnumSet = interface;//java.util.EnumSet
JEnumeration = interface;//java.util.Enumeration
JGregorianCalendar = interface;//java.util.GregorianCalendar
JHashMap = interface;//java.util.HashMap
JHashSet = interface;//java.util.HashSet
JHashtable = interface;//java.util.Hashtable
JIterator = interface;//java.util.Iterator
JList = interface;//java.util.List
JListIterator = interface;//java.util.ListIterator
JLocale = interface;//java.util.Locale
JMap = interface;//java.util.Map
Jutil_Observable = interface;//java.util.Observable
JObserver = interface;//java.util.Observer
JProperties = interface;//java.util.Properties
JQueue = interface;//java.util.Queue
JRandom = interface;//java.util.Random
JSet = interface;//java.util.Set
JSortedMap = interface;//java.util.SortedMap
JTimeZone = interface;//java.util.TimeZone
JTimer = interface;//java.util.Timer
JTimerTask = interface;//java.util.TimerTask
JUUID = interface;//java.util.UUID
JAbstractExecutorService = interface;//java.util.concurrent.AbstractExecutorService
JBlockingQueue = interface;//java.util.concurrent.BlockingQueue
JCallable = interface;//java.util.concurrent.Callable
JCountDownLatch = interface;//java.util.concurrent.CountDownLatch
JDelayed = interface;//java.util.concurrent.Delayed
JExecutor = interface;//java.util.concurrent.Executor
JExecutorService = interface;//java.util.concurrent.ExecutorService
JFuture = interface;//java.util.concurrent.Future
JRejectedExecutionHandler = interface;//java.util.concurrent.RejectedExecutionHandler
JScheduledFuture = interface;//java.util.concurrent.ScheduledFuture
JThreadPoolExecutor = interface;//java.util.concurrent.ThreadPoolExecutor
JScheduledThreadPoolExecutor = interface;//java.util.concurrent.ScheduledThreadPoolExecutor
JThreadFactory = interface;//java.util.concurrent.ThreadFactory
JTimeUnit = interface;//java.util.concurrent.TimeUnit
// ===== Interface declarations =====
JAbstractCollectionClass = interface(JObjectClass)
['{27541496-F538-45DB-BFC7-9ED05E5680C3}']
end;
[JavaSignature('java/util/AbstractCollection')]
JAbstractCollection = interface(JObject)
['{4A5BA15A-2B07-4768-AA91-4BA9C93882C1}']
function add(object_: JObject): Boolean; cdecl;
function addAll(collection: JCollection): Boolean; cdecl;
procedure clear; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function containsAll(collection: JCollection): Boolean; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function remove(object_: JObject): Boolean; cdecl;
function removeAll(collection: JCollection): Boolean; cdecl;
function retainAll(collection: JCollection): Boolean; cdecl;
function size: Integer; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(contents: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
function toString: JString; cdecl;
end;
TJAbstractCollection = class(TJavaGenericImport<JAbstractCollectionClass, JAbstractCollection>) end;
JAbstractListClass = interface(JAbstractCollectionClass)
['{4495F751-BABA-4349-8D4B-997761ED3876}']
end;
[JavaSignature('java/util/AbstractList')]
JAbstractList = interface(JAbstractCollection)
['{2E98325B-7293-4E06-A775-240FDD287E27}']
procedure add(location: Integer; object_: JObject); cdecl; overload;
function add(object_: JObject): Boolean; cdecl; overload;
function addAll(location: Integer; collection: JCollection): Boolean; cdecl;
procedure clear; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(location: Integer): JObject; cdecl;
function hashCode: Integer; cdecl;
function indexOf(object_: JObject): Integer; cdecl;
function iterator: JIterator; cdecl;
function lastIndexOf(object_: JObject): Integer; cdecl;
function listIterator: JListIterator; cdecl; overload;
function listIterator(location: Integer): JListIterator; cdecl; overload;
function remove(location: Integer): JObject; cdecl;
function &set(location: Integer; object_: JObject): JObject; cdecl;
function subList(start: Integer; end_: Integer): JList; cdecl;
end;
TJAbstractList = class(TJavaGenericImport<JAbstractListClass, JAbstractList>) end;
JAbstractMapClass = interface(JObjectClass)
['{05119E45-9501-4270-B2BB-EE7E314695CB}']
end;
[JavaSignature('java/util/AbstractMap')]
JAbstractMap = interface(JObject)
['{63FD2094-7BFB-41B4-AED8-F781B97F6EB6}']
procedure clear; cdecl;
function containsKey(key: JObject): Boolean; cdecl;
function containsValue(value: JObject): Boolean; cdecl;
function entrySet: JSet; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(key: JObject): JObject; cdecl;
function hashCode: Integer; cdecl;
function isEmpty: Boolean; cdecl;
function keySet: JSet; cdecl;
function put(key: JObject; value: JObject): JObject; cdecl;
procedure putAll(map: JMap); cdecl;
function remove(key: JObject): JObject; cdecl;
function size: Integer; cdecl;
function toString: JString; cdecl;
function values: JCollection; cdecl;
end;
TJAbstractMap = class(TJavaGenericImport<JAbstractMapClass, JAbstractMap>) end;
JAbstractSetClass = interface(JAbstractCollectionClass)
['{C8EA147C-D0DB-4E27-B8B5-77A04711A2F3}']
end;
[JavaSignature('java/util/AbstractSet')]
JAbstractSet = interface(JAbstractCollection)
['{A520B68E-843E-46B8-BBB3-1A40DE9E92CE}']
function equals(object_: JObject): Boolean; cdecl;
function hashCode: Integer; cdecl;
function removeAll(collection: JCollection): Boolean; cdecl;
end;
TJAbstractSet = class(TJavaGenericImport<JAbstractSetClass, JAbstractSet>) end;
JArrayListClass = interface(JAbstractListClass)
['{0CC7FC88-8B13-4F0A-9635-26FEEED49F94}']
{class} function init(capacity: Integer): JArrayList; cdecl; overload;
{class} function init: JArrayList; cdecl; overload;
{class} function init(collection: JCollection): JArrayList; cdecl; overload;
end;
[JavaSignature('java/util/ArrayList')]
JArrayList = interface(JAbstractList)
['{B1D54E97-F848-4301-BA5B-F32921164AFA}']
function add(object_: JObject): Boolean; cdecl; overload;
procedure add(index: Integer; object_: JObject); cdecl; overload;
function addAll(collection: JCollection): Boolean; cdecl; overload;
function addAll(index: Integer; collection: JCollection): Boolean; cdecl; overload;
procedure clear; cdecl;
function clone: JObject; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
procedure ensureCapacity(minimumCapacity: Integer); cdecl;
function equals(o: JObject): Boolean; cdecl;
function &get(index: Integer): JObject; cdecl;
function hashCode: Integer; cdecl;
function indexOf(object_: JObject): Integer; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function lastIndexOf(object_: JObject): Integer; cdecl;
function remove(index: Integer): JObject; cdecl; overload;
function remove(object_: JObject): Boolean; cdecl; overload;
function &set(index: Integer; object_: JObject): JObject; cdecl;
function size: Integer; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(contents: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
procedure trimToSize; cdecl;
end;
TJArrayList = class(TJavaGenericImport<JArrayListClass, JArrayList>) end;
JBitSetClass = interface(JObjectClass)
['{1CB74061-9B52-4CCA-AB29-D87B5EE10BCB}']
{class} function init: JBitSet; cdecl; overload;
{class} function init(bitCount: Integer): JBitSet; cdecl; overload;
{class} function valueOf(longs: TJavaArray<Int64>): JBitSet; cdecl; overload;
{class} function valueOf(longBuffer: JLongBuffer): JBitSet; cdecl; overload;
{class} function valueOf(bytes: TJavaArray<Byte>): JBitSet; cdecl; overload;
{class} function valueOf(byteBuffer: JByteBuffer): JBitSet; cdecl; overload;
end;
[JavaSignature('java/util/BitSet')]
JBitSet = interface(JObject)
['{2FBDF9C9-FEEE-4377-B2A2-D557CF0BEC31}']
procedure &and(bs: JBitSet); cdecl;
procedure andNot(bs: JBitSet); cdecl;
function cardinality: Integer; cdecl;
procedure clear(index: Integer); cdecl; overload;
procedure clear; cdecl; overload;
procedure clear(fromIndex: Integer; toIndex: Integer); cdecl; overload;
function clone: JObject; cdecl;
function equals(o: JObject): Boolean; cdecl;
procedure flip(index: Integer); cdecl; overload;
procedure flip(fromIndex: Integer; toIndex: Integer); cdecl; overload;
function &get(index: Integer): Boolean; cdecl; overload;
function &get(fromIndex: Integer; toIndex: Integer): JBitSet; cdecl; overload;
function hashCode: Integer; cdecl;
function intersects(bs: JBitSet): Boolean; cdecl;
function isEmpty: Boolean; cdecl;
function length: Integer; cdecl;
function nextClearBit(index: Integer): Integer; cdecl;
function nextSetBit(index: Integer): Integer; cdecl;
procedure &or(bs: JBitSet); cdecl;
function previousClearBit(index: Integer): Integer; cdecl;
function previousSetBit(index: Integer): Integer; cdecl;
procedure &set(index: Integer); cdecl; overload;
procedure &set(index: Integer; state: Boolean); cdecl; overload;
procedure &set(fromIndex: Integer; toIndex: Integer; state: Boolean); cdecl; overload;
procedure &set(fromIndex: Integer; toIndex: Integer); cdecl; overload;
function size: Integer; cdecl;
function toByteArray: TJavaArray<Byte>; cdecl;
function toLongArray: TJavaArray<Int64>; cdecl;
function toString: JString; cdecl;
procedure &xor(bs: JBitSet); cdecl;
end;
TJBitSet = class(TJavaGenericImport<JBitSetClass, JBitSet>) end;
JCalendarClass = interface(JObjectClass)
['{51237FAA-7CDF-4E7E-9AE8-282DC2A930A1}']
{class} function _GetALL_STYLES: Integer; cdecl;
{class} function _GetAM: Integer; cdecl;
{class} function _GetAM_PM: Integer; cdecl;
{class} function _GetAPRIL: Integer; cdecl;
{class} function _GetAUGUST: Integer; cdecl;
{class} function _GetDATE: Integer; cdecl;
{class} function _GetDAY_OF_MONTH: Integer; cdecl;
{class} function _GetDAY_OF_WEEK: Integer; cdecl;
{class} function _GetDAY_OF_WEEK_IN_MONTH: Integer; cdecl;
{class} function _GetDAY_OF_YEAR: Integer; cdecl;
{class} function _GetDECEMBER: Integer; cdecl;
{class} function _GetDST_OFFSET: Integer; cdecl;
{class} function _GetERA: Integer; cdecl;
{class} function _GetFEBRUARY: Integer; cdecl;
{class} function _GetFIELD_COUNT: Integer; cdecl;
{class} function _GetFRIDAY: Integer; cdecl;
{class} function _GetHOUR: Integer; cdecl;
{class} function _GetHOUR_OF_DAY: Integer; cdecl;
{class} function _GetJANUARY: Integer; cdecl;
{class} function _GetJULY: Integer; cdecl;
{class} function _GetJUNE: Integer; cdecl;
{class} function _GetLONG: Integer; cdecl;
{class} function _GetMARCH: Integer; cdecl;
{class} function _GetMAY: Integer; cdecl;
{class} function _GetMILLISECOND: Integer; cdecl;
{class} function _GetMINUTE: Integer; cdecl;
{class} function _GetMONDAY: Integer; cdecl;
{class} function _GetMONTH: Integer; cdecl;
{class} function _GetNOVEMBER: Integer; cdecl;
{class} function _GetOCTOBER: Integer; cdecl;
{class} function _GetPM: Integer; cdecl;
{class} function _GetSATURDAY: Integer; cdecl;
{class} function _GetSECOND: Integer; cdecl;
{class} function _GetSEPTEMBER: Integer; cdecl;
{class} function _GetSHORT: Integer; cdecl;
{class} function _GetSUNDAY: Integer; cdecl;
{class} function _GetTHURSDAY: Integer; cdecl;
{class} function _GetTUESDAY: Integer; cdecl;
{class} function _GetUNDECIMBER: Integer; cdecl;
{class} function _GetWEDNESDAY: Integer; cdecl;
{class} function _GetWEEK_OF_MONTH: Integer; cdecl;
{class} function _GetWEEK_OF_YEAR: Integer; cdecl;
{class} function _GetYEAR: Integer; cdecl;
{class} function _GetZONE_OFFSET: Integer; cdecl;
{class} function getAvailableLocales: TJavaObjectArray<JLocale>; cdecl;
{class} function getInstance: JCalendar; cdecl; overload;
{class} function getInstance(locale: JLocale): JCalendar; cdecl; overload;
{class} function getInstance(timezone: JTimeZone): JCalendar; cdecl; overload;
{class} function getInstance(timezone: JTimeZone; locale: JLocale): JCalendar; cdecl; overload;
{class} property ALL_STYLES: Integer read _GetALL_STYLES;
{class} property AM: Integer read _GetAM;
{class} property AM_PM: Integer read _GetAM_PM;
{class} property APRIL: Integer read _GetAPRIL;
{class} property AUGUST: Integer read _GetAUGUST;
{class} property DATE: Integer read _GetDATE;
{class} property DAY_OF_MONTH: Integer read _GetDAY_OF_MONTH;
{class} property DAY_OF_WEEK: Integer read _GetDAY_OF_WEEK;
{class} property DAY_OF_WEEK_IN_MONTH: Integer read _GetDAY_OF_WEEK_IN_MONTH;
{class} property DAY_OF_YEAR: Integer read _GetDAY_OF_YEAR;
{class} property DECEMBER: Integer read _GetDECEMBER;
{class} property DST_OFFSET: Integer read _GetDST_OFFSET;
{class} property ERA: Integer read _GetERA;
{class} property FEBRUARY: Integer read _GetFEBRUARY;
{class} property FIELD_COUNT: Integer read _GetFIELD_COUNT;
{class} property FRIDAY: Integer read _GetFRIDAY;
{class} property HOUR: Integer read _GetHOUR;
{class} property HOUR_OF_DAY: Integer read _GetHOUR_OF_DAY;
{class} property JANUARY: Integer read _GetJANUARY;
{class} property JULY: Integer read _GetJULY;
{class} property JUNE: Integer read _GetJUNE;
{class} property LONG: Integer read _GetLONG;
{class} property MARCH: Integer read _GetMARCH;
{class} property MAY: Integer read _GetMAY;
{class} property MILLISECOND: Integer read _GetMILLISECOND;
{class} property MINUTE: Integer read _GetMINUTE;
{class} property MONDAY: Integer read _GetMONDAY;
{class} property MONTH: Integer read _GetMONTH;
{class} property NOVEMBER: Integer read _GetNOVEMBER;
{class} property OCTOBER: Integer read _GetOCTOBER;
{class} property PM: Integer read _GetPM;
{class} property SATURDAY: Integer read _GetSATURDAY;
{class} property SECOND: Integer read _GetSECOND;
{class} property SEPTEMBER: Integer read _GetSEPTEMBER;
{class} property SHORT: Integer read _GetSHORT;
{class} property SUNDAY: Integer read _GetSUNDAY;
{class} property THURSDAY: Integer read _GetTHURSDAY;
{class} property TUESDAY: Integer read _GetTUESDAY;
{class} property UNDECIMBER: Integer read _GetUNDECIMBER;
{class} property WEDNESDAY: Integer read _GetWEDNESDAY;
{class} property WEEK_OF_MONTH: Integer read _GetWEEK_OF_MONTH;
{class} property WEEK_OF_YEAR: Integer read _GetWEEK_OF_YEAR;
{class} property YEAR: Integer read _GetYEAR;
{class} property ZONE_OFFSET: Integer read _GetZONE_OFFSET;
end;
[JavaSignature('java/util/Calendar')]
JCalendar = interface(JObject)
['{2C0409E5-97A4-47CA-9E75-6ACB1CA4515E}']
procedure add(field: Integer; value: Integer); cdecl;
function after(calendar: JObject): Boolean; cdecl;
function before(calendar: JObject): Boolean; cdecl;
procedure clear; cdecl; overload;
procedure clear(field: Integer); cdecl; overload;
function clone: JObject; cdecl;
function compareTo(anotherCalendar: JCalendar): Integer; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(field: Integer): Integer; cdecl;
function getActualMaximum(field: Integer): Integer; cdecl;
function getActualMinimum(field: Integer): Integer; cdecl;
function getDisplayName(field: Integer; style: Integer; locale: JLocale): JString; cdecl;
function getDisplayNames(field: Integer; style: Integer; locale: JLocale): JMap; cdecl;
function getFirstDayOfWeek: Integer; cdecl;
function getGreatestMinimum(field: Integer): Integer; cdecl;
function getLeastMaximum(field: Integer): Integer; cdecl;
function getMaximum(field: Integer): Integer; cdecl;
function getMinimalDaysInFirstWeek: Integer; cdecl;
function getMinimum(field: Integer): Integer; cdecl;
function getTime: JDate; cdecl;
function getTimeInMillis: Int64; cdecl;
function getTimeZone: JTimeZone; cdecl;
function hashCode: Integer; cdecl;
function isLenient: Boolean; cdecl;
function isSet(field: Integer): Boolean; cdecl;
procedure roll(field: Integer; value: Integer); cdecl; overload;
procedure roll(field: Integer; increment: Boolean); cdecl; overload;
procedure &set(field: Integer; value: Integer); cdecl; overload;
procedure &set(year: Integer; month: Integer; day: Integer); cdecl; overload;
procedure &set(year: Integer; month: Integer; day: Integer; hourOfDay: Integer; minute: Integer); cdecl; overload;
procedure &set(year: Integer; month: Integer; day: Integer; hourOfDay: Integer; minute: Integer; second: Integer); cdecl; overload;
procedure setFirstDayOfWeek(value: Integer); cdecl;
procedure setLenient(value: Boolean); cdecl;
procedure setMinimalDaysInFirstWeek(value: Integer); cdecl;
procedure setTime(date: JDate); cdecl;
procedure setTimeInMillis(milliseconds: Int64); cdecl;
procedure setTimeZone(timezone: JTimeZone); cdecl;
function toString: JString; cdecl;
end;
TJCalendar = class(TJavaGenericImport<JCalendarClass, JCalendar>) end;
JCollectionClass = interface(JIterableClass)
['{2737AA1B-2E7C-406D-AF35-8B012C7D5803}']
end;
[JavaSignature('java/util/Collection')]
JCollection = interface(JIterable)
['{9E58EE70-C0A7-4660-BF62-945FAE9F5EC3}']
function add(object_: JObject): Boolean; cdecl;
function addAll(collection: JCollection): Boolean; cdecl;
procedure clear; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function containsAll(collection: JCollection): Boolean; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function hashCode: Integer; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function remove(object_: JObject): Boolean; cdecl;
function removeAll(collection: JCollection): Boolean; cdecl;
function retainAll(collection: JCollection): Boolean; cdecl;
function size: Integer; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(array_: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
end;
TJCollection = class(TJavaGenericImport<JCollectionClass, JCollection>) end;
JComparatorClass = interface(IJavaClass)
['{BFB6395F-2694-4292-A1B5-87CC1138FB77}']
end;
[JavaSignature('java/util/Comparator')]
JComparator = interface(IJavaInstance)
['{0754C41C-92B8-483B-88F0-B48BFE216D46}']
function compare(lhs: JObject; rhs: JObject): Integer; cdecl;
function equals(object_: JObject): Boolean; cdecl;
end;
TJComparator = class(TJavaGenericImport<JComparatorClass, JComparator>) end;
JDateClass = interface(JObjectClass)
['{37EABF6D-C7EE-4AB5-BE8B-5E439112E116}']
{class} function init: JDate; cdecl; overload;
{class} function init(year: Integer; month: Integer; day: Integer): JDate; cdecl; overload;//Deprecated
{class} function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer): JDate; cdecl; overload;//Deprecated
{class} function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer; second: Integer): JDate; cdecl; overload;//Deprecated
{class} function init(milliseconds: Int64): JDate; cdecl; overload;
{class} function init(string_: JString): JDate; cdecl; overload;//Deprecated
{class} function UTC(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer; second: Integer): Int64; cdecl;//Deprecated
{class} function parse(string_: JString): Int64; cdecl;//Deprecated
end;
[JavaSignature('java/util/Date')]
JDate = interface(JObject)
['{282E2836-B390-44E4-A14F-EF481460BDF7}']
function after(date: JDate): Boolean; cdecl;
function before(date: JDate): Boolean; cdecl;
function clone: JObject; cdecl;
function compareTo(date: JDate): Integer; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function getDate: Integer; cdecl;//Deprecated
function getDay: Integer; cdecl;//Deprecated
function getHours: Integer; cdecl;//Deprecated
function getMinutes: Integer; cdecl;//Deprecated
function getMonth: Integer; cdecl;//Deprecated
function getSeconds: Integer; cdecl;//Deprecated
function getTime: Int64; cdecl;
function getTimezoneOffset: Integer; cdecl;//Deprecated
function getYear: Integer; cdecl;//Deprecated
function hashCode: Integer; cdecl;
procedure setDate(day: Integer); cdecl;//Deprecated
procedure setHours(hour: Integer); cdecl;//Deprecated
procedure setMinutes(minute: Integer); cdecl;//Deprecated
procedure setMonth(month: Integer); cdecl;//Deprecated
procedure setSeconds(second: Integer); cdecl;//Deprecated
procedure setTime(milliseconds: Int64); cdecl;
procedure setYear(year: Integer); cdecl;//Deprecated
function toGMTString: JString; cdecl;//Deprecated
function toLocaleString: JString; cdecl;//Deprecated
function toString: JString; cdecl;
end;
TJDate = class(TJavaGenericImport<JDateClass, JDate>) end;
JDictionaryClass = interface(JObjectClass)
['{33D1971B-B4C5-4FA5-9DE3-BD76F2FCBD29}']
{class} function init: JDictionary; cdecl;
end;
[JavaSignature('java/util/Dictionary')]
JDictionary = interface(JObject)
['{C52483EE-5BB5-4F8A-B6ED-411F1920D533}']
function elements: JEnumeration; cdecl;
function &get(key: JObject): JObject; cdecl;
function isEmpty: Boolean; cdecl;
function keys: JEnumeration; cdecl;
function put(key: JObject; value: JObject): JObject; cdecl;
function remove(key: JObject): JObject; cdecl;
function size: Integer; cdecl;
end;
TJDictionary = class(TJavaGenericImport<JDictionaryClass, JDictionary>) end;
JEnumSetClass = interface(JAbstractSetClass)
['{67EF0287-D91B-44E0-9574-4CA9974FBC38}']
{class} function allOf(elementType: Jlang_Class): JEnumSet; cdecl;
{class} function complementOf(s: JEnumSet): JEnumSet; cdecl;
{class} function copyOf(s: JEnumSet): JEnumSet; cdecl; overload;
{class} function copyOf(c: JCollection): JEnumSet; cdecl; overload;
{class} function noneOf(elementType: Jlang_Class): JEnumSet; cdecl;
{class} function &of(e: JEnum): JEnumSet; cdecl; overload;
{class} function &of(e1: JEnum; e2: JEnum): JEnumSet; cdecl; overload;
{class} function &of(e1: JEnum; e2: JEnum; e3: JEnum): JEnumSet; cdecl; overload;
{class} function &of(e1: JEnum; e2: JEnum; e3: JEnum; e4: JEnum): JEnumSet; cdecl; overload;
{class} function &of(e1: JEnum; e2: JEnum; e3: JEnum; e4: JEnum; e5: JEnum): JEnumSet; cdecl; overload;
{class} function range(start: JEnum; end_: JEnum): JEnumSet; cdecl;
end;
[JavaSignature('java/util/EnumSet')]
JEnumSet = interface(JAbstractSet)
['{C8A6B028-B797-406A-9EE4-B65671555D97}']
function clone: JEnumSet; cdecl;
end;
TJEnumSet = class(TJavaGenericImport<JEnumSetClass, JEnumSet>) end;
JEnumerationClass = interface(IJavaClass)
['{5E393BCD-3EF2-4764-A59C-37B4D44C289A}']
end;
[JavaSignature('java/util/Enumeration')]
JEnumeration = interface(IJavaInstance)
['{8F9F8780-E6BE-4B67-A4F5-8EC28E1AE2EE}']
function hasMoreElements: Boolean; cdecl;
function nextElement: JObject; cdecl;
end;
TJEnumeration = class(TJavaGenericImport<JEnumerationClass, JEnumeration>) end;
JGregorianCalendarClass = interface(JCalendarClass)
['{69F4EF00-93DA-4249-8A30-3A3E4A71DA03}']
{class} function _GetAD: Integer; cdecl;
{class} function _GetBC: Integer; cdecl;
{class} function init: JGregorianCalendar; cdecl; overload;
{class} function init(year: Integer; month: Integer; day: Integer): JGregorianCalendar; cdecl; overload;
{class} function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer): JGregorianCalendar; cdecl; overload;
{class} function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer; second: Integer): JGregorianCalendar; cdecl; overload;
{class} function init(locale: JLocale): JGregorianCalendar; cdecl; overload;
{class} function init(timezone: JTimeZone): JGregorianCalendar; cdecl; overload;
{class} function init(timezone: JTimeZone; locale: JLocale): JGregorianCalendar; cdecl; overload;
{class} property AD: Integer read _GetAD;
{class} property BC: Integer read _GetBC;
end;
[JavaSignature('java/util/GregorianCalendar')]
JGregorianCalendar = interface(JCalendar)
['{CB851885-16EA-49E7-8AAF-DBFE900DA328}']
procedure add(field: Integer; value: Integer); cdecl;
function equals(object_: JObject): Boolean; cdecl;
function getActualMaximum(field: Integer): Integer; cdecl;
function getActualMinimum(field: Integer): Integer; cdecl;
function getGreatestMinimum(field: Integer): Integer; cdecl;
function getGregorianChange: JDate; cdecl;
function getLeastMaximum(field: Integer): Integer; cdecl;
function getMaximum(field: Integer): Integer; cdecl;
function getMinimum(field: Integer): Integer; cdecl;
function hashCode: Integer; cdecl;
function isLeapYear(year: Integer): Boolean; cdecl;
procedure roll(field: Integer; value: Integer); cdecl; overload;
procedure roll(field: Integer; increment: Boolean); cdecl; overload;
procedure setGregorianChange(date: JDate); cdecl;
end;
TJGregorianCalendar = class(TJavaGenericImport<JGregorianCalendarClass, JGregorianCalendar>) end;
JHashMapClass = interface(JAbstractMapClass)
['{AC953BC1-405B-4CDD-93D2-FBA77D171B56}']
{class} function init: JHashMap; cdecl; overload;
{class} function init(capacity: Integer): JHashMap; cdecl; overload;
{class} function init(capacity: Integer; loadFactor: Single): JHashMap; cdecl; overload;
{class} function init(map: JMap): JHashMap; cdecl; overload;
end;
[JavaSignature('java/util/HashMap')]
JHashMap = interface(JAbstractMap)
['{FD560211-A7FE-4AB5-B510-BB43A31AA75D}']
procedure clear; cdecl;
function clone: JObject; cdecl;
function containsKey(key: JObject): Boolean; cdecl;
function containsValue(value: JObject): Boolean; cdecl;
function entrySet: JSet; cdecl;
function &get(key: JObject): JObject; cdecl;
function isEmpty: Boolean; cdecl;
function keySet: JSet; cdecl;
function put(key: JObject; value: JObject): JObject; cdecl;
procedure putAll(map: JMap); cdecl;
function remove(key: JObject): JObject; cdecl;
function size: Integer; cdecl;
function values: JCollection; cdecl;
end;
TJHashMap = class(TJavaGenericImport<JHashMapClass, JHashMap>) end;
JHashSetClass = interface(JAbstractSetClass)
['{7828E4D4-4F9F-493D-869E-92BE600444D5}']
{class} function init: JHashSet; cdecl; overload;
{class} function init(capacity: Integer): JHashSet; cdecl; overload;
{class} function init(capacity: Integer; loadFactor: Single): JHashSet; cdecl; overload;
{class} function init(collection: JCollection): JHashSet; cdecl; overload;
end;
[JavaSignature('java/util/HashSet')]
JHashSet = interface(JAbstractSet)
['{A57B696D-8331-4C96-8759-7F2009371640}']
function add(object_: JObject): Boolean; cdecl;
procedure clear; cdecl;
function clone: JObject; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function remove(object_: JObject): Boolean; cdecl;
function size: Integer; cdecl;
end;
TJHashSet = class(TJavaGenericImport<JHashSetClass, JHashSet>) end;
JHashtableClass = interface(JDictionaryClass)
['{0459EE5F-44DF-406D-B0F4-6D2F19D2222F}']
{class} function init: JHashtable; cdecl; overload;
{class} function init(capacity: Integer): JHashtable; cdecl; overload;
{class} function init(capacity: Integer; loadFactor: Single): JHashtable; cdecl; overload;
{class} function init(map: JMap): JHashtable; cdecl; overload;
end;
[JavaSignature('java/util/Hashtable')]
JHashtable = interface(JDictionary)
['{7A995299-3381-4179-A8A2-21C4F0E2E755}']
procedure clear; cdecl;
function clone: JObject; cdecl;
function &contains(value: JObject): Boolean; cdecl;
function containsKey(key: JObject): Boolean; cdecl;
function containsValue(value: JObject): Boolean; cdecl;
function elements: JEnumeration; cdecl;
function entrySet: JSet; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(key: JObject): JObject; cdecl;
function hashCode: Integer; cdecl;
function isEmpty: Boolean; cdecl;
function keySet: JSet; cdecl;
function keys: JEnumeration; cdecl;
function put(key: JObject; value: JObject): JObject; cdecl;
procedure putAll(map: JMap); cdecl;
function remove(key: JObject): JObject; cdecl;
function size: Integer; cdecl;
function toString: JString; cdecl;
function values: JCollection; cdecl;
end;
TJHashtable = class(TJavaGenericImport<JHashtableClass, JHashtable>) end;
JIteratorClass = interface(IJavaClass)
['{2E525F5D-C766-4F79-B800-BA5FFA909E90}']
end;
[JavaSignature('java/util/Iterator')]
JIterator = interface(IJavaInstance)
['{435EBC1F-CFE0-437C-B49B-45B5257B6953}']
function hasNext: Boolean; cdecl;
function next: JObject; cdecl;
procedure remove; cdecl;
end;
TJIterator = class(TJavaGenericImport<JIteratorClass, JIterator>) end;
JListClass = interface(JCollectionClass)
['{8EA06296-143F-4381-9369-A77209B622F0}']
end;
[JavaSignature('java/util/List')]
JList = interface(JCollection)
['{3F85C565-F3F4-42D8-87EE-F724F72113C7}']
procedure add(location: Integer; object_: JObject); cdecl; overload;
function add(object_: JObject): Boolean; cdecl; overload;
function addAll(location: Integer; collection: JCollection): Boolean; cdecl; overload;
function addAll(collection: JCollection): Boolean; cdecl; overload;
procedure clear; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function containsAll(collection: JCollection): Boolean; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(location: Integer): JObject; cdecl;
function hashCode: Integer; cdecl;
function indexOf(object_: JObject): Integer; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function lastIndexOf(object_: JObject): Integer; cdecl;
function listIterator: JListIterator; cdecl; overload;
function listIterator(location: Integer): JListIterator; cdecl; overload;
function remove(location: Integer): JObject; cdecl; overload;
function remove(object_: JObject): Boolean; cdecl; overload;
function removeAll(collection: JCollection): Boolean; cdecl;
function retainAll(collection: JCollection): Boolean; cdecl;
function &set(location: Integer; object_: JObject): JObject; cdecl;
function size: Integer; cdecl;
function subList(start: Integer; end_: Integer): JList; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(array_: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
end;
TJList = class(TJavaGenericImport<JListClass, JList>) end;
JListIteratorClass = interface(JIteratorClass)
['{7541F5DD-8E71-44AE-ACD9-142ED2D42810}']
end;
[JavaSignature('java/util/ListIterator')]
JListIterator = interface(JIterator)
['{B66BDA33-5CDD-43B1-B320-7353AE09C418}']
procedure add(object_: JObject); cdecl;
function hasNext: Boolean; cdecl;
function hasPrevious: Boolean; cdecl;
function next: JObject; cdecl;
function nextIndex: Integer; cdecl;
function previous: JObject; cdecl;
function previousIndex: Integer; cdecl;
procedure remove; cdecl;
procedure &set(object_: JObject); cdecl;
end;
TJListIterator = class(TJavaGenericImport<JListIteratorClass, JListIterator>) end;
JLocaleClass = interface(JObjectClass)
['{0A5D70AA-C01B-437F-97C8-FEE25C595AE7}']
{class} function _GetCANADA: JLocale; cdecl;
{class} function _GetCANADA_FRENCH: JLocale; cdecl;
{class} function _GetCHINA: JLocale; cdecl;
{class} function _GetCHINESE: JLocale; cdecl;
{class} function _GetENGLISH: JLocale; cdecl;
{class} function _GetFRANCE: JLocale; cdecl;
{class} function _GetFRENCH: JLocale; cdecl;
{class} function _GetGERMAN: JLocale; cdecl;
{class} function _GetGERMANY: JLocale; cdecl;
{class} function _GetITALIAN: JLocale; cdecl;
{class} function _GetITALY: JLocale; cdecl;
{class} function _GetJAPAN: JLocale; cdecl;
{class} function _GetJAPANESE: JLocale; cdecl;
{class} function _GetKOREA: JLocale; cdecl;
{class} function _GetKOREAN: JLocale; cdecl;
{class} function _GetPRC: JLocale; cdecl;
{class} function _GetPRIVATE_USE_EXTENSION: Char; cdecl;
{class} function _GetROOT: JLocale; cdecl;
{class} function _GetSIMPLIFIED_CHINESE: JLocale; cdecl;
{class} function _GetTAIWAN: JLocale; cdecl;
{class} function _GetTRADITIONAL_CHINESE: JLocale; cdecl;
{class} function _GetUK: JLocale; cdecl;
{class} function _GetUNICODE_LOCALE_EXTENSION: Char; cdecl;
{class} function _GetUS: JLocale; cdecl;
{class} function init(language: JString): JLocale; cdecl; overload;
{class} function init(language: JString; country: JString): JLocale; cdecl; overload;
{class} function init(language: JString; country: JString; variant: JString): JLocale; cdecl; overload;
{class} function forLanguageTag(languageTag: JString): JLocale; cdecl;
{class} function getAvailableLocales: TJavaObjectArray<JLocale>; cdecl;
{class} function getDefault: JLocale; cdecl;
{class} function getISOCountries: TJavaObjectArray<JString>; cdecl;
{class} function getISOLanguages: TJavaObjectArray<JString>; cdecl;
{class} procedure setDefault(locale: JLocale); cdecl;
{class} property CANADA: JLocale read _GetCANADA;
{class} property CANADA_FRENCH: JLocale read _GetCANADA_FRENCH;
{class} property CHINA: JLocale read _GetCHINA;
{class} property CHINESE: JLocale read _GetCHINESE;
{class} property ENGLISH: JLocale read _GetENGLISH;
{class} property FRANCE: JLocale read _GetFRANCE;
{class} property FRENCH: JLocale read _GetFRENCH;
{class} property GERMAN: JLocale read _GetGERMAN;
{class} property GERMANY: JLocale read _GetGERMANY;
{class} property ITALIAN: JLocale read _GetITALIAN;
{class} property ITALY: JLocale read _GetITALY;
{class} property JAPAN: JLocale read _GetJAPAN;
{class} property JAPANESE: JLocale read _GetJAPANESE;
{class} property KOREA: JLocale read _GetKOREA;
{class} property KOREAN: JLocale read _GetKOREAN;
{class} property PRC: JLocale read _GetPRC;
{class} property PRIVATE_USE_EXTENSION: Char read _GetPRIVATE_USE_EXTENSION;
{class} property ROOT: JLocale read _GetROOT;
{class} property SIMPLIFIED_CHINESE: JLocale read _GetSIMPLIFIED_CHINESE;
{class} property TAIWAN: JLocale read _GetTAIWAN;
{class} property TRADITIONAL_CHINESE: JLocale read _GetTRADITIONAL_CHINESE;
{class} property UK: JLocale read _GetUK;
{class} property UNICODE_LOCALE_EXTENSION: Char read _GetUNICODE_LOCALE_EXTENSION;
{class} property US: JLocale read _GetUS;
end;
[JavaSignature('java/util/Locale')]
JLocale = interface(JObject)
['{877ADE25-1D13-4963-9A17-17EE17B3A0A8}']
function clone: JObject; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function getCountry: JString; cdecl;
function getDisplayCountry: JString; cdecl; overload;
function getDisplayCountry(locale: JLocale): JString; cdecl; overload;
function getDisplayLanguage: JString; cdecl; overload;
function getDisplayLanguage(locale: JLocale): JString; cdecl; overload;
function getDisplayName: JString; cdecl; overload;
function getDisplayName(locale: JLocale): JString; cdecl; overload;
function getDisplayScript: JString; cdecl; overload;
function getDisplayScript(locale: JLocale): JString; cdecl; overload;
function getDisplayVariant: JString; cdecl; overload;
function getDisplayVariant(locale: JLocale): JString; cdecl; overload;
function getExtension(extensionKey: Char): JString; cdecl;
function getExtensionKeys: JSet; cdecl;
function getISO3Country: JString; cdecl;
function getISO3Language: JString; cdecl;
function getLanguage: JString; cdecl;
function getScript: JString; cdecl;
function getUnicodeLocaleAttributes: JSet; cdecl;
function getUnicodeLocaleKeys: JSet; cdecl;
function getUnicodeLocaleType(keyWord: JString): JString; cdecl;
function getVariant: JString; cdecl;
function hashCode: Integer; cdecl;
function toLanguageTag: JString; cdecl;
function toString: JString; cdecl;
end;
TJLocale = class(TJavaGenericImport<JLocaleClass, JLocale>) end;
JMapClass = interface(IJavaClass)
['{2A7CE403-063B-45CA-9F4D-EA1E64304F1C}']
end;
[JavaSignature('java/util/Map')]
JMap = interface(IJavaInstance)
['{BE6A5DBF-B121-4BF2-BC18-EB64729C7811}']
procedure clear; cdecl;
function containsKey(key: JObject): Boolean; cdecl;
function containsValue(value: JObject): Boolean; cdecl;
function entrySet: JSet; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(key: JObject): JObject; cdecl;
function hashCode: Integer; cdecl;
function isEmpty: Boolean; cdecl;
function keySet: JSet; cdecl;
function put(key: JObject; value: JObject): JObject; cdecl;
procedure putAll(map: JMap); cdecl;
function remove(key: JObject): JObject; cdecl;
function size: Integer; cdecl;
function values: JCollection; cdecl;
end;
TJMap = class(TJavaGenericImport<JMapClass, JMap>) end;
Jutil_ObservableClass = interface(JObjectClass)
['{2BD8C696-02FF-4378-A514-ACD431BEE106}']
{class} function init: Jutil_Observable; cdecl;
end;
[JavaSignature('java/util/Observable')]
Jutil_Observable = interface(JObject)
['{B8443F0E-B41C-4475-934B-1C917FCF617B}']
procedure addObserver(observer: JObserver); cdecl;
function countObservers: Integer; cdecl;
procedure deleteObserver(observer: JObserver); cdecl;
procedure deleteObservers; cdecl;
function hasChanged: Boolean; cdecl;
procedure notifyObservers; cdecl; overload;
procedure notifyObservers(data: JObject); cdecl; overload;
end;
TJutil_Observable = class(TJavaGenericImport<Jutil_ObservableClass, Jutil_Observable>) end;
JObserverClass = interface(IJavaClass)
['{8582EA20-ECD9-4C10-95BD-2C89B4D5BA6E}']
end;
[JavaSignature('java/util/Observer')]
JObserver = interface(IJavaInstance)
['{452A1BDA-4B4E-406E-B455-BC56F012C1B7}']
procedure update(observable: Jutil_Observable; data: JObject); cdecl;
end;
TJObserver = class(TJavaGenericImport<JObserverClass, JObserver>) end;
JPropertiesClass = interface(JHashtableClass)
['{CA354A9C-C42E-41BD-B104-6058143813A5}']
{class} function init: JProperties; cdecl; overload;
{class} function init(properties: JProperties): JProperties; cdecl; overload;
end;
[JavaSignature('java/util/Properties')]
JProperties = interface(JHashtable)
['{5F7AA87B-4EF0-4D76-923C-D7586F38760F}']
function getProperty(name: JString): JString; cdecl; overload;
function getProperty(name: JString; defaultValue: JString): JString; cdecl; overload;
procedure list(out_: JPrintStream); cdecl; overload;
procedure list(out_: JPrintWriter); cdecl; overload;
procedure load(in_: JInputStream); cdecl; overload;
procedure load(in_: JReader); cdecl; overload;
procedure loadFromXML(in_: JInputStream); cdecl;
function propertyNames: JEnumeration; cdecl;
procedure save(out_: JOutputStream; comment: JString); cdecl;//Deprecated
function setProperty(name: JString; value: JString): JObject; cdecl;
procedure store(out_: JOutputStream; comment: JString); cdecl; overload;
procedure store(writer: JWriter; comment: JString); cdecl; overload;
procedure storeToXML(os: JOutputStream; comment: JString); cdecl; overload;
procedure storeToXML(os: JOutputStream; comment: JString; encoding: JString); cdecl; overload;
function stringPropertyNames: JSet; cdecl;
end;
TJProperties = class(TJavaGenericImport<JPropertiesClass, JProperties>) end;
JQueueClass = interface(JCollectionClass)
['{3A0B6ECD-D788-4FFA-9C17-6F7A761FE1DC}']
end;
[JavaSignature('java/util/Queue')]
JQueue = interface(JCollection)
['{1F7FBC68-484A-4622-AE37-764E1EC7AF04}']
function add(e: JObject): Boolean; cdecl;
function element: JObject; cdecl;
function offer(e: JObject): Boolean; cdecl;
function peek: JObject; cdecl;
function poll: JObject; cdecl;
function remove: JObject; cdecl;
end;
TJQueue = class(TJavaGenericImport<JQueueClass, JQueue>) end;
JRandomClass = interface(JObjectClass)
['{C50FE36A-6283-4523-BF77-15BB7A7B0F92}']
{class} function init: JRandom; cdecl; overload;
{class} function init(seed: Int64): JRandom; cdecl; overload;
end;
[JavaSignature('java/util/Random')]
JRandom = interface(JObject)
['{F1C05381-73F2-4991-853B-B22575DB43D2}']
function nextBoolean: Boolean; cdecl;
procedure nextBytes(buf: TJavaArray<Byte>); cdecl;
function nextDouble: Double; cdecl;
function nextFloat: Single; cdecl;
function nextGaussian: Double; cdecl;
function nextInt: Integer; cdecl; overload;
function nextInt(n: Integer): Integer; cdecl; overload;
function nextLong: Int64; cdecl;
procedure setSeed(seed: Int64); cdecl;
end;
TJRandom = class(TJavaGenericImport<JRandomClass, JRandom>) end;
JSetClass = interface(JCollectionClass)
['{A3E290FD-FD46-4DA8-B728-07B04920F5DE}']
end;
[JavaSignature('java/util/Set')]
JSet = interface(JCollection)
['{07BF19A2-0C1C-4ABF-9028-1F99DD0E0A79}']
function add(object_: JObject): Boolean; cdecl;
function addAll(collection: JCollection): Boolean; cdecl;
procedure clear; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function containsAll(collection: JCollection): Boolean; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function hashCode: Integer; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function remove(object_: JObject): Boolean; cdecl;
function removeAll(collection: JCollection): Boolean; cdecl;
function retainAll(collection: JCollection): Boolean; cdecl;
function size: Integer; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(array_: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
end;
TJSet = class(TJavaGenericImport<JSetClass, JSet>) end;
JSortedMapClass = interface(JMapClass)
['{7665A1A5-0EE6-483D-A256-B13FA7E65230}']
end;
[JavaSignature('java/util/SortedMap')]
JSortedMap = interface(JMap)
['{3FD4011C-7238-42A1-8E25-D7B3F130E88F}']
function comparator: JComparator; cdecl;
function firstKey: JObject; cdecl;
function headMap(endKey: JObject): JSortedMap; cdecl;
function lastKey: JObject; cdecl;
function subMap(startKey: JObject; endKey: JObject): JSortedMap; cdecl;
function tailMap(startKey: JObject): JSortedMap; cdecl;
end;
TJSortedMap = class(TJavaGenericImport<JSortedMapClass, JSortedMap>) end;
JTimeZoneClass = interface(JObjectClass)
['{8F823620-CE10-44D5-82BA-24BFD63DCF80}']
{class} function _GetLONG: Integer; cdecl;
{class} function _GetSHORT: Integer; cdecl;
{class} function init: JTimeZone; cdecl;
{class} function getAvailableIDs: TJavaObjectArray<JString>; cdecl; overload;
{class} function getAvailableIDs(offsetMillis: Integer): TJavaObjectArray<JString>; cdecl; overload;
{class} function getDefault: JTimeZone; cdecl;
{class} function getTimeZone(id: JString): JTimeZone; cdecl;
{class} procedure setDefault(timeZone: JTimeZone); cdecl;
{class} property LONG: Integer read _GetLONG;
{class} property SHORT: Integer read _GetSHORT;
end;
[JavaSignature('java/util/TimeZone')]
JTimeZone = interface(JObject)
['{9D5215F4-A1B5-4B24-8B0B-EB3B88A0328D}']
function clone: JObject; cdecl;
function getDSTSavings: Integer; cdecl;
function getDisplayName: JString; cdecl; overload;
function getDisplayName(locale: JLocale): JString; cdecl; overload;
function getDisplayName(daylightTime: Boolean; style: Integer): JString; cdecl; overload;
function getDisplayName(daylightTime: Boolean; style: Integer; locale: JLocale): JString; cdecl; overload;
function getID: JString; cdecl;
function getOffset(time: Int64): Integer; cdecl; overload;
function getOffset(era: Integer; year: Integer; month: Integer; day: Integer; dayOfWeek: Integer; timeOfDayMillis: Integer): Integer; cdecl; overload;
function getRawOffset: Integer; cdecl;
function hasSameRules(timeZone: JTimeZone): Boolean; cdecl;
function inDaylightTime(time: JDate): Boolean; cdecl;
procedure setID(id: JString); cdecl;
procedure setRawOffset(offsetMillis: Integer); cdecl;
function useDaylightTime: Boolean; cdecl;
end;
TJTimeZone = class(TJavaGenericImport<JTimeZoneClass, JTimeZone>) end;
JTimerClass = interface(JObjectClass)
['{52E301A5-4F00-4743-94D1-BA38347CC59F}']
{class} function init(name: JString; isDaemon: Boolean): JTimer; cdecl; overload;
{class} function init(name: JString): JTimer; cdecl; overload;
{class} function init(isDaemon: Boolean): JTimer; cdecl; overload;
{class} function init: JTimer; cdecl; overload;
end;
[JavaSignature('java/util/Timer')]
JTimer = interface(JObject)
['{131F841C-9357-49F0-A688-9AC5506F4C5A}']
procedure cancel; cdecl;
function purge: Integer; cdecl;
procedure schedule(task: JTimerTask; when: JDate); cdecl; overload;
procedure schedule(task: JTimerTask; delay: Int64); cdecl; overload;
procedure schedule(task: JTimerTask; delay: Int64; period: Int64); cdecl; overload;
procedure schedule(task: JTimerTask; when: JDate; period: Int64); cdecl; overload;
procedure scheduleAtFixedRate(task: JTimerTask; delay: Int64; period: Int64); cdecl; overload;
procedure scheduleAtFixedRate(task: JTimerTask; when: JDate; period: Int64); cdecl; overload;
end;
TJTimer = class(TJavaGenericImport<JTimerClass, JTimer>) end;
JTimerTaskClass = interface(JObjectClass)
['{DC15DA86-BDCC-42A9-8B9D-7348D4AE0F13}']
end;
[JavaSignature('java/util/TimerTask')]
JTimerTask = interface(JObject)
['{B01AA454-6E9B-4A26-A31E-8D9A32E59816}']
function cancel: Boolean; cdecl;
procedure run; cdecl;
function scheduledExecutionTime: Int64; cdecl;
end;
TJTimerTask = class(TJavaGenericImport<JTimerTaskClass, JTimerTask>) end;
JUUIDClass = interface(JObjectClass)
['{F254C874-67C8-4832-9619-9F686CB8E466}']
{class} function init(mostSigBits: Int64; leastSigBits: Int64): JUUID; cdecl;
{class} function fromString(uuid: JString): JUUID; cdecl;
{class} function nameUUIDFromBytes(name: TJavaArray<Byte>): JUUID; cdecl;
{class} function randomUUID: JUUID; cdecl;
end;
[JavaSignature('java/util/UUID')]
JUUID = interface(JObject)
['{B280C48F-E064-4030-BFD0-FB5970A78101}']
function clockSequence: Integer; cdecl;
function compareTo(uuid: JUUID): Integer; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function getLeastSignificantBits: Int64; cdecl;
function getMostSignificantBits: Int64; cdecl;
function hashCode: Integer; cdecl;
function node: Int64; cdecl;
function timestamp: Int64; cdecl;
function toString: JString; cdecl;
function variant: Integer; cdecl;
function version: Integer; cdecl;
end;
TJUUID = class(TJavaGenericImport<JUUIDClass, JUUID>) end;
JAbstractExecutorServiceClass = interface(JObjectClass)
['{3896A98A-B273-4500-B0D5-F7D69CD7D49E}']
{class} function init: JAbstractExecutorService; cdecl;
end;
[JavaSignature('java/util/concurrent/AbstractExecutorService')]
JAbstractExecutorService = interface(JObject)
['{7A846346-CB8B-442D-A705-40CB673B7A84}']
function invokeAll(tasks: JCollection): JList; cdecl; overload;
function invokeAll(tasks: JCollection; timeout: Int64; unit_: JTimeUnit): JList; cdecl; overload;
function invokeAny(tasks: JCollection): JObject; cdecl; overload;
function invokeAny(tasks: JCollection; timeout: Int64; unit_: JTimeUnit): JObject; cdecl; overload;
function submit(task: JRunnable): JFuture; cdecl; overload;
function submit(task: JRunnable; result: JObject): JFuture; cdecl; overload;
function submit(task: JCallable): JFuture; cdecl; overload;
end;
TJAbstractExecutorService = class(TJavaGenericImport<JAbstractExecutorServiceClass, JAbstractExecutorService>) end;
JBlockingQueueClass = interface(JQueueClass)
['{FEAC4030-F87A-4E78-9454-A48238AC00D8}']
end;
[JavaSignature('java/util/concurrent/BlockingQueue')]
JBlockingQueue = interface(JQueue)
['{4F92390A-DED1-405E-894E-656C3AD20695}']
function add(e: JObject): Boolean; cdecl;
function &contains(o: JObject): Boolean; cdecl;
function drainTo(c: JCollection): Integer; cdecl; overload;
function drainTo(c: JCollection; maxElements: Integer): Integer; cdecl; overload;
function offer(e: JObject): Boolean; cdecl; overload;
function offer(e: JObject; timeout: Int64; unit_: JTimeUnit): Boolean; cdecl; overload;
function poll(timeout: Int64; unit_: JTimeUnit): JObject; cdecl;
procedure put(e: JObject); cdecl;
function remainingCapacity: Integer; cdecl;
function remove(o: JObject): Boolean; cdecl;
function take: JObject; cdecl;
end;
TJBlockingQueue = class(TJavaGenericImport<JBlockingQueueClass, JBlockingQueue>) end;
JCallableClass = interface(IJavaClass)
['{F12DB2A8-1E01-44A9-BFBE-C6F3E32F7A65}']
end;
[JavaSignature('java/util/concurrent/Callable')]
JCallable = interface(IJavaInstance)
['{071A2E40-747B-4702-8DDB-D1749FB9B8FD}']
function call: JObject; cdecl;
end;
TJCallable = class(TJavaGenericImport<JCallableClass, JCallable>) end;
JCountDownLatchClass = interface(JObjectClass)
['{8BB952D3-8BF8-4704-BC03-DCE2997C03AC}']
{class} function init(count: Integer): JCountDownLatch; cdecl;
end;
[JavaSignature('java/util/concurrent/CountDownLatch')]
JCountDownLatch = interface(JObject)
['{302AA7D1-4CD0-45CB-868F-C1CF1209D276}']
procedure await; cdecl; overload;
function await(timeout: Int64; unit_: JTimeUnit): Boolean; cdecl; overload;
procedure countDown; cdecl;
function getCount: Int64; cdecl;
function toString: JString; cdecl;
end;
TJCountDownLatch = class(TJavaGenericImport<JCountDownLatchClass, JCountDownLatch>) end;
JDelayedClass = interface(JComparableClass)
['{67CD6011-1F40-4BCA-9E24-EDA55F6A4EA1}']
end;
[JavaSignature('java/util/concurrent/Delayed')]
JDelayed = interface(JComparable)
['{2BE364E4-9B4A-4A34-BDED-D1D9773530BF}']
function getDelay(unit_: JTimeUnit): Int64; cdecl;
end;
TJDelayed = class(TJavaGenericImport<JDelayedClass, JDelayed>) end;
JExecutorClass = interface(IJavaClass)
['{0606DEEF-30E1-4E40-82A3-20FF3E89BD61}']
end;
[JavaSignature('java/util/concurrent/Executor')]
JExecutor = interface(IJavaInstance)
['{B846ECEE-83CF-40BB-A4C5-FFC949DCEF15}']
procedure execute(command: JRunnable); cdecl;
end;
TJExecutor = class(TJavaGenericImport<JExecutorClass, JExecutor>) end;
JExecutorServiceClass = interface(JExecutorClass)
['{4CF14DA3-BA41-4F67-A2DE-F62C8B02177F}']
end;
[JavaSignature('java/util/concurrent/ExecutorService')]
JExecutorService = interface(JExecutor)
['{37810DA0-1254-423D-B181-C62455CB5AE4}']
function awaitTermination(timeout: Int64; unit_: JTimeUnit): Boolean; cdecl;
function invokeAll(tasks: JCollection): JList; cdecl; overload;
function invokeAll(tasks: JCollection; timeout: Int64; unit_: JTimeUnit): JList; cdecl; overload;
function invokeAny(tasks: JCollection): JObject; cdecl; overload;
function invokeAny(tasks: JCollection; timeout: Int64; unit_: JTimeUnit): JObject; cdecl; overload;
function isShutdown: Boolean; cdecl;
function isTerminated: Boolean; cdecl;
procedure shutdown; cdecl;
function shutdownNow: JList; cdecl;
function submit(task: JCallable): JFuture; cdecl; overload;
function submit(task: JRunnable; result: JObject): JFuture; cdecl; overload;
function submit(task: JRunnable): JFuture; cdecl; overload;
end;
TJExecutorService = class(TJavaGenericImport<JExecutorServiceClass, JExecutorService>) end;
JFutureClass = interface(IJavaClass)
['{1716BCA6-301F-4D84-956C-AC25D1787B40}']
end;
[JavaSignature('java/util/concurrent/Future')]
JFuture = interface(IJavaInstance)
['{EFD52756-9DF1-45BD-9E0D-A36E3CDE3DB9}']
function cancel(mayInterruptIfRunning: Boolean): Boolean; cdecl;
function &get: JObject; cdecl; overload;
function &get(timeout: Int64; unit_: JTimeUnit): JObject; cdecl; overload;
function isCancelled: Boolean; cdecl;
function isDone: Boolean; cdecl;
end;
TJFuture = class(TJavaGenericImport<JFutureClass, JFuture>) end;
JRejectedExecutionHandlerClass = interface(IJavaClass)
['{59CBB7C6-368F-446D-92CB-DB8638AE3BBD}']
end;
[JavaSignature('java/util/concurrent/RejectedExecutionHandler')]
JRejectedExecutionHandler = interface(IJavaInstance)
['{F75637CF-D111-4DE1-9820-CA00A2AA17C7}']
procedure rejectedExecution(r: JRunnable; executor: JThreadPoolExecutor); cdecl;
end;
TJRejectedExecutionHandler = class(TJavaGenericImport<JRejectedExecutionHandlerClass, JRejectedExecutionHandler>) end;
JScheduledFutureClass = interface(JDelayedClass)
['{6AEAD91E-6D96-4057-BD8D-8B28E3833E7E}']
end;
[JavaSignature('java/util/concurrent/ScheduledFuture')]
JScheduledFuture = interface(JDelayed)
['{0D2AEB43-60E8-4488-9260-15E693B853DD}']
end;
TJScheduledFuture = class(TJavaGenericImport<JScheduledFutureClass, JScheduledFuture>) end;
JThreadPoolExecutorClass = interface(JAbstractExecutorServiceClass)
['{DDC3110F-84AA-41F1-9D0F-9800A406A8A8}']
{class} function init(corePoolSize: Integer; maximumPoolSize: Integer; keepAliveTime: Int64; unit_: JTimeUnit; workQueue: JBlockingQueue): JThreadPoolExecutor; cdecl; overload;
{class} function init(corePoolSize: Integer; maximumPoolSize: Integer; keepAliveTime: Int64; unit_: JTimeUnit; workQueue: JBlockingQueue; threadFactory: JThreadFactory): JThreadPoolExecutor; cdecl; overload;
{class} function init(corePoolSize: Integer; maximumPoolSize: Integer; keepAliveTime: Int64; unit_: JTimeUnit; workQueue: JBlockingQueue; handler: JRejectedExecutionHandler): JThreadPoolExecutor; cdecl; overload;
{class} function init(corePoolSize: Integer; maximumPoolSize: Integer; keepAliveTime: Int64; unit_: JTimeUnit; workQueue: JBlockingQueue; threadFactory: JThreadFactory; handler: JRejectedExecutionHandler): JThreadPoolExecutor; cdecl; overload;
end;
[JavaSignature('java/util/concurrent/ThreadPoolExecutor')]
JThreadPoolExecutor = interface(JAbstractExecutorService)
['{866B2F57-7E31-4566-876F-4A35D526D76C}']
procedure allowCoreThreadTimeOut(value: Boolean); cdecl;
function allowsCoreThreadTimeOut: Boolean; cdecl;
function awaitTermination(timeout: Int64; unit_: JTimeUnit): Boolean; cdecl;
procedure execute(command: JRunnable); cdecl;
function getActiveCount: Integer; cdecl;
function getCompletedTaskCount: Int64; cdecl;
function getCorePoolSize: Integer; cdecl;
function getKeepAliveTime(unit_: JTimeUnit): Int64; cdecl;
function getLargestPoolSize: Integer; cdecl;
function getMaximumPoolSize: Integer; cdecl;
function getPoolSize: Integer; cdecl;
function getQueue: JBlockingQueue; cdecl;
function getRejectedExecutionHandler: JRejectedExecutionHandler; cdecl;
function getTaskCount: Int64; cdecl;
function getThreadFactory: JThreadFactory; cdecl;
function isShutdown: Boolean; cdecl;
function isTerminated: Boolean; cdecl;
function isTerminating: Boolean; cdecl;
function prestartAllCoreThreads: Integer; cdecl;
function prestartCoreThread: Boolean; cdecl;
procedure purge; cdecl;
function remove(task: JRunnable): Boolean; cdecl;
procedure setCorePoolSize(corePoolSize: Integer); cdecl;
procedure setKeepAliveTime(time: Int64; unit_: JTimeUnit); cdecl;
procedure setMaximumPoolSize(maximumPoolSize: Integer); cdecl;
procedure setRejectedExecutionHandler(handler: JRejectedExecutionHandler); cdecl;
procedure setThreadFactory(threadFactory: JThreadFactory); cdecl;
procedure shutdown; cdecl;
function shutdownNow: JList; cdecl;
function toString: JString; cdecl;
end;
TJThreadPoolExecutor = class(TJavaGenericImport<JThreadPoolExecutorClass, JThreadPoolExecutor>) end;
JScheduledThreadPoolExecutorClass = interface(JThreadPoolExecutorClass)
['{E97835A3-4211-4A02-AC53-E0951A70BFCE}']
{class} function init(corePoolSize: Integer): JScheduledThreadPoolExecutor; cdecl; overload;
{class} function init(corePoolSize: Integer; threadFactory: JThreadFactory): JScheduledThreadPoolExecutor; cdecl; overload;
{class} function init(corePoolSize: Integer; handler: JRejectedExecutionHandler): JScheduledThreadPoolExecutor; cdecl; overload;
{class} function init(corePoolSize: Integer; threadFactory: JThreadFactory; handler: JRejectedExecutionHandler): JScheduledThreadPoolExecutor; cdecl; overload;
end;
[JavaSignature('java/util/concurrent/ScheduledThreadPoolExecutor')]
JScheduledThreadPoolExecutor = interface(JThreadPoolExecutor)
['{7E9D716D-A52D-440A-B55A-21B9832960C6}']
procedure execute(command: JRunnable); cdecl;
function getContinueExistingPeriodicTasksAfterShutdownPolicy: Boolean; cdecl;
function getExecuteExistingDelayedTasksAfterShutdownPolicy: Boolean; cdecl;
function getQueue: JBlockingQueue; cdecl;
function getRemoveOnCancelPolicy: Boolean; cdecl;
function schedule(command: JRunnable; delay: Int64; unit_: JTimeUnit): JScheduledFuture; cdecl; overload;
function schedule(callable: JCallable; delay: Int64; unit_: JTimeUnit): JScheduledFuture; cdecl; overload;
function scheduleAtFixedRate(command: JRunnable; initialDelay: Int64; period: Int64; unit_: JTimeUnit): JScheduledFuture; cdecl;
function scheduleWithFixedDelay(command: JRunnable; initialDelay: Int64; delay: Int64; unit_: JTimeUnit): JScheduledFuture; cdecl;
procedure setContinueExistingPeriodicTasksAfterShutdownPolicy(value: Boolean); cdecl;
procedure setExecuteExistingDelayedTasksAfterShutdownPolicy(value: Boolean); cdecl;
procedure setRemoveOnCancelPolicy(value: Boolean); cdecl;
procedure shutdown; cdecl;
function shutdownNow: JList; cdecl;
function submit(task: JRunnable): JFuture; cdecl; overload;
function submit(task: JRunnable; result: JObject): JFuture; cdecl; overload;
function submit(task: JCallable): JFuture; cdecl; overload;
end;
TJScheduledThreadPoolExecutor = class(TJavaGenericImport<JScheduledThreadPoolExecutorClass, JScheduledThreadPoolExecutor>) end;
JThreadFactoryClass = interface(IJavaClass)
['{CD4277E8-4960-409B-B76C-70D202901E27}']
end;
[JavaSignature('java/util/concurrent/ThreadFactory')]
JThreadFactory = interface(IJavaInstance)
['{D96A16B3-CE4E-4293-9BB0-FE84575F7E19}']
function newThread(r: JRunnable): JThread; cdecl;
end;
TJThreadFactory = class(TJavaGenericImport<JThreadFactoryClass, JThreadFactory>) end;
JTimeUnitClass = interface(JEnumClass)
['{005AE9B1-228D-48C4-BFD2-41DCEE712F3B}']
{class} function _GetDAYS: JTimeUnit; cdecl;
{class} function _GetHOURS: JTimeUnit; cdecl;
{class} function _GetMICROSECONDS: JTimeUnit; cdecl;
{class} function _GetMILLISECONDS: JTimeUnit; cdecl;
{class} function _GetMINUTES: JTimeUnit; cdecl;
{class} function _GetNANOSECONDS: JTimeUnit; cdecl;
{class} function _GetSECONDS: JTimeUnit; cdecl;
{class} function valueOf(name: JString): JTimeUnit; cdecl;
{class} function values: TJavaObjectArray<JTimeUnit>; cdecl;
{class} property DAYS: JTimeUnit read _GetDAYS;
{class} property HOURS: JTimeUnit read _GetHOURS;
{class} property MICROSECONDS: JTimeUnit read _GetMICROSECONDS;
{class} property MILLISECONDS: JTimeUnit read _GetMILLISECONDS;
{class} property MINUTES: JTimeUnit read _GetMINUTES;
{class} property NANOSECONDS: JTimeUnit read _GetNANOSECONDS;
{class} property SECONDS: JTimeUnit read _GetSECONDS;
end;
[JavaSignature('java/util/concurrent/TimeUnit')]
JTimeUnit = interface(JEnum)
['{97B8E3BD-6430-4597-B01D-CD2AD51ECB2C}']
function convert(sourceDuration: Int64; sourceUnit: JTimeUnit): Int64; cdecl;
procedure sleep(timeout: Int64); cdecl;
procedure timedJoin(thread: JThread; timeout: Int64); cdecl;
procedure timedWait(obj: JObject; timeout: Int64); cdecl;
function toDays(duration: Int64): Int64; cdecl;
function toHours(duration: Int64): Int64; cdecl;
function toMicros(duration: Int64): Int64; cdecl;
function toMillis(duration: Int64): Int64; cdecl;
function toMinutes(duration: Int64): Int64; cdecl;
function toNanos(duration: Int64): Int64; cdecl;
function toSeconds(duration: Int64): Int64; cdecl;
end;
TJTimeUnit = class(TJavaGenericImport<JTimeUnitClass, JTimeUnit>) end;
implementation
procedure RegisterTypes;
begin
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JAbstractCollection', TypeInfo(Androidapi.JNI.JavaUtil.JAbstractCollection));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JAbstractList', TypeInfo(Androidapi.JNI.JavaUtil.JAbstractList));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JAbstractMap', TypeInfo(Androidapi.JNI.JavaUtil.JAbstractMap));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JAbstractSet', TypeInfo(Androidapi.JNI.JavaUtil.JAbstractSet));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JArrayList', TypeInfo(Androidapi.JNI.JavaUtil.JArrayList));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JBitSet', TypeInfo(Androidapi.JNI.JavaUtil.JBitSet));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JCalendar', TypeInfo(Androidapi.JNI.JavaUtil.JCalendar));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JCollection', TypeInfo(Androidapi.JNI.JavaUtil.JCollection));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JComparator', TypeInfo(Androidapi.JNI.JavaUtil.JComparator));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JDate', TypeInfo(Androidapi.JNI.JavaUtil.JDate));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JDictionary', TypeInfo(Androidapi.JNI.JavaUtil.JDictionary));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JEnumSet', TypeInfo(Androidapi.JNI.JavaUtil.JEnumSet));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JEnumeration', TypeInfo(Androidapi.JNI.JavaUtil.JEnumeration));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JGregorianCalendar', TypeInfo(Androidapi.JNI.JavaUtil.JGregorianCalendar));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JHashMap', TypeInfo(Androidapi.JNI.JavaUtil.JHashMap));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JHashSet', TypeInfo(Androidapi.JNI.JavaUtil.JHashSet));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JHashtable', TypeInfo(Androidapi.JNI.JavaUtil.JHashtable));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JIterator', TypeInfo(Androidapi.JNI.JavaUtil.JIterator));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JList', TypeInfo(Androidapi.JNI.JavaUtil.JList));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JListIterator', TypeInfo(Androidapi.JNI.JavaUtil.JListIterator));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JLocale', TypeInfo(Androidapi.JNI.JavaUtil.JLocale));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JMap', TypeInfo(Androidapi.JNI.JavaUtil.JMap));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.Jutil_Observable', TypeInfo(Androidapi.JNI.JavaUtil.Jutil_Observable));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JObserver', TypeInfo(Androidapi.JNI.JavaUtil.JObserver));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JProperties', TypeInfo(Androidapi.JNI.JavaUtil.JProperties));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JQueue', TypeInfo(Androidapi.JNI.JavaUtil.JQueue));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JRandom', TypeInfo(Androidapi.JNI.JavaUtil.JRandom));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JSet', TypeInfo(Androidapi.JNI.JavaUtil.JSet));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JSortedMap', TypeInfo(Androidapi.JNI.JavaUtil.JSortedMap));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JTimeZone', TypeInfo(Androidapi.JNI.JavaUtil.JTimeZone));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JTimer', TypeInfo(Androidapi.JNI.JavaUtil.JTimer));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JTimerTask', TypeInfo(Androidapi.JNI.JavaUtil.JTimerTask));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JUUID', TypeInfo(Androidapi.JNI.JavaUtil.JUUID));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JAbstractExecutorService', TypeInfo(Androidapi.JNI.JavaUtil.JAbstractExecutorService));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JBlockingQueue', TypeInfo(Androidapi.JNI.JavaUtil.JBlockingQueue));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JCallable', TypeInfo(Androidapi.JNI.JavaUtil.JCallable));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JCountDownLatch', TypeInfo(Androidapi.JNI.JavaUtil.JCountDownLatch));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JDelayed', TypeInfo(Androidapi.JNI.JavaUtil.JDelayed));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JExecutor', TypeInfo(Androidapi.JNI.JavaUtil.JExecutor));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JExecutorService', TypeInfo(Androidapi.JNI.JavaUtil.JExecutorService));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JFuture', TypeInfo(Androidapi.JNI.JavaUtil.JFuture));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JRejectedExecutionHandler', TypeInfo(Androidapi.JNI.JavaUtil.JRejectedExecutionHandler));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JScheduledFuture', TypeInfo(Androidapi.JNI.JavaUtil.JScheduledFuture));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JThreadPoolExecutor', TypeInfo(Androidapi.JNI.JavaUtil.JThreadPoolExecutor));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JScheduledThreadPoolExecutor', TypeInfo(Androidapi.JNI.JavaUtil.JScheduledThreadPoolExecutor));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JThreadFactory', TypeInfo(Androidapi.JNI.JavaUtil.JThreadFactory));
TRegTypes.RegisterType('Androidapi.JNI.JavaUtil.JTimeUnit', TypeInfo(Androidapi.JNI.JavaUtil.JTimeUnit));
end;
initialization
RegisterTypes;
end.
|
unit nsQueryAttribute;
(*-----------------------------------------------------------------------------
Unit Name: nsQueryAttribute
Author: Инишев Дмитрий & Михаил Морозов
Purpose: Модуль содержит классы для работы "Поиска по реквизитам"
History:
$Id: nsQueryAttribute.pas,v 1.363 2013/04/24 09:35:56 lulin Exp $
$Log: nsQueryAttribute.pas,v $
Revision 1.363 2013/04/24 09:35:56 lulin
- портируем.
Revision 1.362 2012/08/16 16:16:49 kostitsin
[$381878311]
Revision 1.361 2012/03/21 11:16:46 lulin
{RequestLink:349114873}
Revision 1.360 2012/01/19 14:09:29 lulin
{RequestLink:327825257}
Revision 1.359 2012/01/17 14:05:53 gensnet
http://mdp.garant.ru/pages/viewpage.action?pageId=326773154
Revision 1.358 2011/12/15 16:24:19 lulin
{RequestLink:320734796}
Revision 1.357 2011/09/06 15:06:59 lulin
{RequestLink:271758153}.
Revision 1.356 2011/06/23 15:30:13 lulin
{RequestLink:254944102}.
Revision 1.355 2011/05/19 12:18:14 lulin
{RequestLink:266409354}.
Revision 1.354 2011/04/13 14:34:01 lulin
{RequestLink:258607641}.
Revision 1.353 2011/03/30 13:46:41 lulin
{RequestLink:259180243}.
Revision 1.352 2011/03/22 13:21:40 lulin
{RequestLink:255964947}.
Revision 1.351 2010/12/22 18:25:00 lulin
{RequestLink:242845936}.
Revision 1.350 2010/11/22 13:39:10 lulin
[$242845500].
Revision 1.349 2010/11/02 15:19:14 lulin
{RequestLink:237994238}.
Revision 1.348 2010/11/01 17:20:09 lulin
{RequestLink:237994238}.
- передаём ссылку на "модель".
- делаем, чтобы собирались другие проекты.
Revision 1.347 2010/11/01 13:20:45 lulin
{RequestLink:237994238}.
Revision 1.346 2010/10/25 09:55:14 lulin
{RequestLink:237502802}.
Шаг №3.
Revision 1.345 2010/07/21 05:58:39 lulin
{RequestLink:227478809}.
[$227967127].
Revision 1.344 2010/07/05 11:33:05 lulin
{RequestLink:207389954}.
- bug fix: не собирался Admin.
Revision 1.343 2010/05/27 05:30:00 oman
- new: {RequestLink:197493008}
Revision 1.342 2010/05/26 12:09:58 oman
- new: {RequestLink:197493008}
Revision 1.341 2010/05/07 12:55:56 oman
- new: {RequestLink:210043512}
Revision 1.340 2010/03/16 15:50:30 lulin
{RequestLink:197496426}.
Revision 1.339 2009/12/03 14:33:01 lulin
{RequestLink:172986031}.
Revision 1.338 2009/11/16 18:59:27 lulin
{ReqestLink:159360578}. №58.
Revision 1.337 2009/10/29 14:35:47 lulin
- вторая волна компании по борьбе со старыми внутренними операциями.
Revision 1.336 2009/10/26 09:23:55 oman
- fix: {RequestLink:121160631}
Revision 1.335 2009/10/16 13:26:54 oman
- new: Переносим на модель {RequestLink:164596503}
Revision 1.334 2009/10/15 08:50:43 oman
- new: Чистим устаревшие методы доступа {RequestLink:122652464}
Revision 1.333 2009/10/12 11:27:29 lulin
- коммитим после падения CVS.
Revision 1.333 2009/10/08 12:26:08 lulin
- добавляем ссылку на поиск "СМИ по налогам и бухучёту".
Revision 1.332 2009/09/18 12:21:37 lulin
- невоплощённое убиваем, ошмётки переносим на модель.
Revision 1.331 2009/09/15 10:09:09 lulin
- избавляемся от операций модуля и ссылок на класс форм.
Revision 1.330 2009/09/03 18:49:13 lulin
- реструктуризируем поиски и удаляем ненужное.
Revision 1.329 2009/09/03 13:26:17 lulin
- делаем прецеденты более изолированными друг от друга.
Revision 1.328 2009/08/14 14:57:53 lulin
{RequestLink:129240934}. №42.
Revision 1.327 2009/08/14 11:31:30 oman
- fix: {RequestLink:159356254}
Revision 1.326 2009/08/14 11:14:38 oman
- fix: {RequestLink:159356254}
Revision 1.325 2009/07/31 17:30:07 lulin
- убираем мусор.
Revision 1.324 2009/04/01 06:43:30 oman
- fix: Недоубили использование
Revision 1.323 2009/02/20 10:12:57 lulin
- чистка комментариев.
Revision 1.322 2009/02/10 19:04:03 lulin
- <K>: 133891247. Вычищаем морально устаревший модуль.
Revision 1.321 2009/02/09 19:17:30 lulin
- <K>: 133891247. Выделяем интерфейсы поиска.
Revision 1.320 2009/01/12 15:58:38 lulin
- <K>: 133138664. № 22.
Revision 1.319 2009/01/11 10:44:22 lulin
- <K>: 134709278. Пытаемся выживать в сложных условиях.
Revision 1.318 2008/12/29 16:41:04 lulin
- <K>: 134316705.
Revision 1.317 2008/12/25 12:20:19 lulin
- <K>: 121153186.
Revision 1.316 2008/12/08 09:33:27 lulin
- <K>: 128292941.
Revision 1.315 2008/11/07 09:38:54 oman
- fix: Недоизжили IvcmDataReset (К-121157455)
Revision 1.314 2008/11/06 09:56:31 lulin
- <K>: 121167188.
Revision 1.313 2008/10/30 15:09:22 lulin
- <K>: 121159648.
Revision 1.312 2008/10/24 17:29:57 lulin
- чистка кода.
Revision 1.311 2008/09/19 14:55:22 lulin
- удалён ненужный модуль.
Revision 1.310 2008/09/19 10:55:06 oman
- fix: Неверно сравнивали контекст с ошибками (К-118394016)
Revision 1.309 2008/09/16 07:05:40 oman
- fix: Выясненяем неисправимый контекст другим макаром (К-117604398)
Revision 1.308 2008/08/20 11:33:26 lulin
- <K>: 96483355.
Revision 1.307 2008/08/14 11:00:46 oman
- fix: Мягче зачищаем фильтр (K-108627041)
Revision 1.306 2008/08/11 08:57:02 lulin
- <K>: 96483518.
Revision 1.305 2008/08/01 07:16:03 oman
- fix: Нельзя вставлять в свернутую группу (K-105251120)
Revision 1.304 2008/07/24 12:55:38 oman
К-104432064
Revision 1.303 2008/07/22 11:22:15 oman
- new: Отключение пищалки - КЗ (К-103940886)
Revision 1.302 2008/07/16 12:43:05 oman
- new: Фильтр на инфоблоки (К-97846369)
Revision 1.301 2008/07/07 14:27:14 lulin
- подготавливаемся к переименованию.
Revision 1.300 2008/07/04 05:39:14 oman
- new: Отключаем подсказки для инфарма (К-96484656)
Revision 1.299 2008/07/03 07:50:15 oman
- new: Заготовочные изменения интерфейсов (К-96484656)
Revision 1.298 2008/06/25 10:37:36 lulin
- <K>: 95487937.
Revision 1.297 2008/06/20 14:48:44 lulin
- используем префиксы элементов.
Revision 1.296 2008/06/20 13:55:34 lulin
- используем префиксы элементов.
Revision 1.295 2008/06/19 13:46:13 oman
- fix: Контекст проверяем только в контекстных полях (cq29412)
Revision 1.294 2008/06/19 13:25:41 oman
- fix: Бросали исключение в неправильном месте (cq29406)
Revision 1.293 2008/06/18 13:27:53 oman
- fix: Пытаемся сбрасывать успешно найденную опечатку (cq29204)
Revision 1.292 2008/06/18 13:09:05 oman
- fix: Проверяем морфологию по всем атрибутам (cq29204)
Revision 1.291 2008/06/18 11:20:12 oman
- fix: Пользуем более правильное исключение (cq29204)
Revision 1.290 2008/06/18 10:43:10 oman
- new: Переделка исправления опечаток (cq29204)
Revision 1.289 2008/06/17 13:26:27 oman
- new: Для информа корректируем контекст по особому (cq29273)
Revision 1.288 2008/06/09 11:39:50 demon
- new: функция ISearch.CorrectContext получила дополнительный параметр - для Инфарм или нет
Revision 1.287 2008/05/27 09:04:26 lulin
- удалена старая проверка валидности контекста.
Revision 1.286 2008/05/27 08:54:06 lulin
- <CQ>: 29024.
Revision 1.285 2008/05/16 10:57:21 lulin
- переименованы константы.
Revision 1.284 2008/05/08 16:11:09 lulin
- изменения в рамках <K>: 90442475.
Revision 1.283 2008/05/08 06:13:32 oman
- Не собирались
Revision 1.282 2008/04/14 13:43:54 lulin
- <K>: 89096854.
Revision 1.281 2008/03/19 12:45:37 oman
- fix: Не падаем в случае отсутствия значений
Revision 1.280 2008/03/04 19:54:50 lulin
- <K>: 86114496.
Revision 1.279 2008/02/14 17:08:49 lulin
- cleanup.
Revision 1.278 2008/02/12 14:39:57 lulin
- методы для чтения списка переехали на примесь.
Revision 1.277 2008/01/31 13:29:57 oman
- new: Поддержка _TrimLeafFilter (cq14053)
Revision 1.276 2008/01/22 13:59:55 oman
- new: TrimFilter для ОИЗ (cq14053)
Revision 1.275 2008/01/10 07:23:08 oman
Переход на новый адаптер
Revision 1.273.2.3 2007/12/21 09:45:43 mmorozov
- MERGE WITH HEAD;
Revision 1.273.2.2 2007/11/26 09:04:10 oman
Перепиливаем на новый адаптер
Revision 1.273.2.1 2007/11/21 15:07:46 oman
Перепиливаем на новый адаптер
Revision 1.274 2007/12/21 07:12:12 mmorozov
- new: подписка на уведомление об обновлении данных (CQ: OIT5-27823);
Revision 1.273 2007/11/01 13:15:51 oman
- fix: Более корректно очищаем для мониторингов - излишне
зачищалась название
Revision 1.272 2007/10/19 09:23:39 oman
- fix: При разборе контекста выдаем сообщение - более
структурный вариант (К-57051004)
Revision 1.271 2007/10/08 07:54:14 oman
- fix: При выборе из карточки атрибута переполучаем его. Т.к. на
переключнии баз он становиться невалиндным (cq26951)
- fix: При выборе из карточки атрибута ставим в него фокус. Т.к. на
переключнии баз он теряется.
Revision 1.270 2007/09/19 13:27:13 lulin
- bug fix: зачем-то ставили фокус в очищаемый атрибут - в результате КЗ открывалась с курсором на строчке "Да".
Revision 1.269 2007/09/11 16:43:23 lulin
- bug fix: не запускался Прайм (CQ OIT5-26654).
Revision 1.268 2007/09/10 14:19:59 lulin
- bug fix: падала КЗ ППР при переключении баз (CQ OIT5-26548).
Revision 1.267 2007/08/22 11:17:25 oman
- fix: Убираем AT_TEXT_OPT (cq25394)
Revision 1.266 2007/08/14 14:29:57 lulin
- оптимизируем перемещение блоков памяти.
Revision 1.265 2007/08/01 10:38:34 oman
- new: Выделяем процедуру проверки контекста на распознаваемость
Revision 1.264 2007/07/18 15:07:04 lulin
- выпрямляем зависимости. Схема документа, теперь не зависит от Эвереста.
Revision 1.263 2007/06/28 12:57:27 lulin
- cleanup.
Revision 1.262 2007/06/20 14:58:24 lulin
- переделана загрузка значения по умолчанию (<K>-13240526).
Revision 1.261 2007/06/20 12:45:29 lulin
- удалены ненужные параметры (<K>-20219481).
Revision 1.260 2007/06/20 12:06:10 lulin
- вычищены ненужные методы (<K>-20219395).
Revision 1.259 2007/06/19 12:01:48 lulin
- удалены ненужные параметры (<K>-20218355).
Revision 1.258 2007/06/19 10:32:01 lulin
- удален ненужный метод (<K>-18677829).
Revision 1.257 2007/06/19 08:42:29 lulin
- заполненность поля с датой проверяем особенным образом (<K>-20218207).
Revision 1.256 2007/06/19 08:10:24 lulin
- выделен метод проверки заполненности хотя бы одного из полей атрибута. В рамках <K>-18677820.
Revision 1.255 2007/06/19 08:00:03 lulin
- переносим получение списка доступных операция с утилитного класса на класс-параграф над нодой (<K>-20218184).
Revision 1.254 2007/06/18 15:01:55 lulin
- удален ненужный метод (<K>-20218066).
Revision 1.253 2007/06/18 13:32:45 lulin
- удален ненужный и крайне непрозрачный метод (<K>-20217991).
Revision 1.252 2007/06/18 12:48:16 lulin
- удален ненужный метод (<K>-20217944).
Revision 1.251 2007/06/18 10:43:04 lulin
- обобщаем код (<K>-20217891).
Revision 1.250 2007/06/18 10:28:26 lulin
- обобщаем код (<K>-20217886).
Revision 1.249 2007/06/18 10:21:23 lulin
- обобщаем код (<K>-18677820).
Revision 1.248 2007/06/18 09:28:07 lulin
- обобщаем код (<K>-19759427).
Revision 1.247 2007/06/15 12:44:18 lulin
- переименован метод - для читабельности (<K>-19759257).
Revision 1.246 2007/06/15 11:15:22 lulin
- метод обработки ESC переехал на более подходящий интерфейс (<K>-14516868).
Revision 1.245 2007/06/14 16:50:04 lulin
- cleanup.
Revision 1.244 2007/06/14 16:46:11 lulin
- избавляемся от лишней рекурсии (<K>-15368270).
Revision 1.243 2007/06/14 09:18:52 lulin
- убрана ненужная проверка (<K>-18677938).
Revision 1.242 2007/06/14 08:56:31 lulin
- убрано ненужное свойство (<K>-18677883).
Revision 1.241 2007/06/14 07:40:18 lulin
- теперь в метод проверки того заполнено поле или нет подается базовый контрол (<K>-18677854).
Revision 1.240 2007/06/13 17:59:20 lulin
- cleanup.
Revision 1.239 2007/06/13 17:40:58 lulin
- унифицируем код (<K>-18677824).
Revision 1.238 2007/06/13 17:18:22 lulin
- метод переехал в общую библиотеку (<K>-18677805).
Revision 1.237 2007/06/13 16:55:46 lulin
- переименовываем метод (<K>-18677801).
Revision 1.236 2007/06/13 16:39:21 lulin
- удален ненужный метод (<K>-18677793).
Revision 1.235 2007/06/13 15:44:28 lulin
- cleanup.
Revision 1.234 2007/06/13 15:13:57 lulin
- метод переименован в соответствии с тем, что он делает (<K>-18219651).
Revision 1.233 2007/06/13 14:12:12 lulin
- удален ненужный интерфейс (<K>-18219558).
Revision 1.232 2007/06/13 13:51:04 lulin
- метод переехал с интерфейса в глобальную область (<K>-18219517).
Revision 1.231 2007/06/13 13:32:13 lulin
- cleanup.
Revision 1.230 2007/06/09 12:30:46 lulin
- восстановлена загрузка нод по умолчанию (<K>-14516759).
Revision 1.229 2007/06/08 15:01:11 lulin
- реквизит теперь сам загружает значение ноды по-умолчанию, а не через утилитный класс. Контролу текст и нода пока не передаются. В рамках <K>-14516759.
Revision 1.228 2007/06/07 12:47:10 lulin
- убраны ненужные локальные переменные, в рамках <K>-17334761.
Revision 1.227 2007/06/06 14:23:33 lulin
- получаем дерево напрямую, а не через реквизит.
Revision 1.226 2007/06/06 14:02:34 lulin
- cleanup.
Revision 1.225 2007/06/06 13:44:02 lulin
- перенес получение дерева на более подходящий объект (<K>-16352466).
Revision 1.224 2007/06/06 13:25:29 lulin
- выделяем метод определения фильтра. В рамках <K>-16352466.
Revision 1.223 2007/06/06 13:07:33 lulin
- избавился от полиморфности метода получения дерева (<K>-16352476).
Revision 1.222 2007/06/06 12:19:02 lulin
- перенес историю контекста на более подходящий объект (<K>-14516869).
Revision 1.221 2007/06/06 11:57:43 lulin
- (!) Коментарий неверен, см. комментарий выше (!) избавляемся от вредоносного параметра по-умолчанию (<K>-16352239).
Revision 1.220 2007/06/06 10:46:20 lulin
- убрал сброс флажка модифицированности из метода загрузки реквизита (<K>-16352110).
Revision 1.219 2007/06/05 08:05:22 lulin
- bug fix: в поле даты не вбивался текст (CQ OIT5-25529, <K>-15958376).
Revision 1.218 2007/06/04 08:23:15 lulin
- вычищен ненужный метод (<K>-15663181).
Revision 1.217 2007/06/04 08:12:53 lulin
- вычищен ненужный тег (<K>-15663142).
Revision 1.216 2007/06/01 10:38:02 lulin
- восстановил загрузку текста атрибута по-умолчанию (<K>-14516770).
Revision 1.215 2007/06/01 07:35:10 lulin
- в нулевом приближении восстановил закгрузку текста атрибута по-умолчанию (<K>-14516770).
Revision 1.214 2007/06/01 06:38:27 lulin
- вычищено ненужное свойство (<K>-13239053).
Revision 1.213 2007/06/01 06:32:18 lulin
- cleanup.
Revision 1.212 2007/06/01 06:25:26 lulin
- cleanup.
Revision 1.211 2007/05/31 13:09:01 lulin
- cleanup.
Revision 1.210 2007/05/31 13:01:46 lulin
- вычистил ненужный метод (<K>-14516874).
Revision 1.209 2007/05/31 12:18:39 lulin
- вычистил ненужный метод (<K>-14516876).
Revision 1.208 2007/05/31 06:39:58 lulin
- вычищены ненужные методы (<K>-14516757).
Revision 1.207 2007/05/31 06:13:28 lulin
- убран вызов метода, который приводил к бесконечной рекурсии (для восстановления см. <K>-14516759).
Revision 1.206 2007/05/31 06:06:13 lulin
- cleanup.
Revision 1.205 2007/05/30 18:01:23 lulin
- вчерне выкинуто хранение реквизитов в списке (<K>-14516571).
Revision 1.204 2007/05/30 16:21:52 lulin
- добавлен метод итерирования атрибутов без их хранения с списке - пока не использется (<K>-14516706).
Revision 1.203 2007/05/30 15:33:41 lulin
- правим форматирование.
Revision 1.202 2007/05/30 15:30:57 lulin
- сосредотачиваем логику на менеджере поиска (<K)-14516571).
Revision 1.201 2007/05/30 14:18:45 lulin
- с менеджера поиска вычищено ненужное свойство (<K>-14516583).
Revision 1.200 2007/05/30 13:19:00 lulin
- убрал из реквизита хранение ссылки на объект модели (<K>-14516447).
Revision 1.199 2007/05/30 11:41:14 lulin
- вычищено поле, мешающее классы стать утилитным (<K>-14516416).
Revision 1.198 2007/05/30 10:49:06 lulin
- вычищаем признак модифицированности атрибута из утилитного класса, перекладываем его в тег (<K>-13239999).
Revision 1.197 2007/05/30 10:28:02 lulin
- вычищен ненужный параметр (<K>-14516397).
Revision 1.196 2007/05/30 10:09:45 lulin
- ненужный код убран под директивы компиляции.
Revision 1.195 2007/05/30 09:51:12 lulin
- optimization: получаем список операций только если его не получали.
Revision 1.194 2007/05/30 09:41:59 lulin
- вычищено хранение списка доступных операций с утилитного класса, теперь операции хранятся в теге (<K>-13239724).
Revision 1.193 2007/05/30 09:18:00 lulin
- избавляемся от хранения полей, из которых формируется поле "Тема" (<K>-14516317).
- избавляемся от ссылки на поле "Тема" (<K>-13240375).
Revision 1.192 2007/05/30 08:16:24 lulin
- избавился от хранения вычисляемого атрибута (<K>-14516310).
Revision 1.191 2007/05/30 07:39:20 lulin
- теперь при изменении признака модифицированности атрибута меняется признак модифицированности карточки (<K>-14516282).
Revision 1.190 2007/05/30 07:07:53 lulin
- со списка реквизитов вычищен признак модифицированности (<K>-13239064).
- переупорядочен код.
Revision 1.189 2007/05/30 06:29:28 lulin
- определение типа создаваемого класса атрибута перенесено в фабричную функцию (<K>-14516258).
Revision 1.188 2007/05/29 12:09:19 lulin
- прячем неиспользуемое поле.
Revision 1.187 2007/05/29 12:01:25 lulin
- вычищено хранение признака модифицированности с утилитного класса (<K>-13795407).
Revision 1.186 2007/05/29 09:50:12 lulin
- убран ненужный метод интерфейса (<K>-13795334).
Revision 1.185 2007/05/29 09:34:57 lulin
- удалено хранение вычисляемого атрибута (<K>-13239062).
Revision 1.184 2007/05/29 08:10:14 lulin
- вычистил ненужный метод интерфейса (<K>-13240506).
- вычищено ненужное поле "атрибута" (<K>-13240502).
Revision 1.183 2007/05/29 07:32:32 lulin
- вычистил ненужный параметр (<K>-13240520).
Revision 1.182 2007/05/29 07:11:29 lulin
- переименовал методы - чтобы не путаться (<K>-13239997).
Revision 1.181 2007/05/29 05:44:30 lulin
- правильнее выделяем защищенный код.
Revision 1.180 2007/05/28 15:33:04 lulin
- спрятан ненужный метод.
Revision 1.179 2007/05/28 14:33:01 lulin
- вычищен невостребованный метод (<K>-13239036).
Revision 1.178 2007/05/28 14:00:45 lulin
- с интерфейса вычищен ненужный метод (<K>-13240402).
Revision 1.177 2007/05/28 12:58:28 lulin
- вычищена возможность чтения свойства (<K>-13240379).
Revision 1.176 2007/05/28 11:44:41 lulin
- вычистил с интерфейса ненужный метод (<K>-13240319).
Revision 1.175 2007/05/28 10:51:36 lulin
- bug fix: неправильно вычислялся список доступных операций (CQ OIT5-25435).
Revision 1.174 2007/05/25 14:59:40 lulin
- не вычисляем фильтр, если он не нужен.
Revision 1.173 2007/05/25 12:54:00 lulin
- передаем не имя атрибута, а сам атрибут - чтобы лишний раз не искать его.
Revision 1.172 2007/05/25 10:48:16 lulin
- cleanup.
Revision 1.171 2007/05/25 07:38:46 lulin
- вычистил ненужное хранимое значение (<K>-13239753).
Revision 1.170 2007/05/24 14:06:47 lulin
- избавляемся от ненужной локальной переменной.
Revision 1.169 2007/05/24 14:01:37 lulin
- не получаем операцию два раза.
Revision 1.168 2007/05/24 13:40:56 lulin
- cleanup.
Revision 1.167 2007/05/23 15:46:40 lulin
- переименовываем метод прятанья выпавшего контрола в соответствии с тем, что он делает (<K>-13239271).
Revision 1.166 2007/05/23 12:45:45 lulin
- вычистил кеширование вычисляемого значения (K-13239075).
Revision 1.165 2007/05/23 10:28:52 lulin
- вычищено кеширование вычисляемого значения.
Revision 1.164 2007/05/23 06:56:49 lulin
- cleanup.
Revision 1.163 2007/05/23 06:44:16 lulin
- вычищено ненужное свойство атрибута _NumList_.
Revision 1.162 2007/05/22 12:44:58 lulin
- вычищено дублированное хранение множественности атрибута.
Revision 1.161 2007/05/22 12:00:41 lulin
- вычищено дублированное хранение имени атрибута.
Revision 1.160 2007/05/22 11:11:52 lulin
- изменен тип имени контрола.
Revision 1.159 2007/05/22 08:15:27 lulin
- вычищен мусор.
Revision 1.158 2007/05/22 07:36:02 lulin
- убрано лишнее хранение текста атрибута.
Revision 1.157 2007/05/22 07:24:50 lulin
- неиспользуемый код убран под директиву условной компиляции.
Revision 1.156 2007/05/22 07:14:13 lulin
- изменен тип заголовка контрола.
Revision 1.155 2007/05/22 07:02:53 lulin
- cleanup.
Revision 1.154 2007/05/21 14:25:37 lulin
- сразу инициализируем реквизит необходимым значением, а не устанавливаем его потом.
Revision 1.153 2007/05/21 14:11:05 lulin
- удалено ненужное свойство интерфейса.
Revision 1.152 2007/05/18 15:45:26 lulin
- забыли модификатор константности.
Revision 1.151 2007/05/18 13:55:11 lulin
- убрано сложное приведение к интерфейсу.
Revision 1.150 2007/05/17 14:04:25 lulin
- избавляем список атрибутов от знаний о менеджере.
Revision 1.149 2007/05/17 12:29:53 lulin
- вычищаем код, до которого не доходило дело.
Revision 1.148 2007/05/17 11:08:36 oman
cleanup
Revision 1.147 2007/05/16 15:32:43 lulin
- вычищаем ненужную функциональность.
Revision 1.146 2007/05/16 14:36:08 oman
Читаем историю контекста из единого места
Revision 1.145 2007/05/16 14:04:08 oman
Cleanup
Revision 1.144 2007/05/16 13:54:32 oman
Cleanup
Revision 1.143 2007/05/16 13:25:36 oman
- fix: История контекстов сохраняется в одни ворота (InsContextFindNotifier) (cq25145)
Revision 1.142 2007/05/16 11:40:02 oman
- new: Логика сохранения истории запросов (cq25145)
Revision 1.141 2007/04/09 10:53:49 lulin
- cleanup.
Revision 1.140 2007/04/05 14:57:50 oman
- fix: Не собирались мониторинги
Revision 1.139 2007/04/05 14:10:23 lulin
- избавляемся от лишних преобразований строк.
Revision 1.138 2007/04/05 13:42:52 lulin
- избавляемся от лишних преобразований строк.
Revision 1.137 2007/04/05 12:20:56 lulin
- cleanup.
Revision 1.136 2007/04/05 11:16:50 lulin
- cleanup.
Revision 1.135 2007/04/05 07:58:27 lulin
- избавляемся от лишних преобразований строк при записи в настройки.
Revision 1.134 2007/04/05 06:39:23 lulin
- избавляемся от лишних преобразований строк.
Revision 1.133 2007/03/30 09:12:11 oman
- fix: Устанавливаем дополнительные фильтры и на выпадающий
список, а не только на карточку атрибутов (cq24456)
Revision 1.132 2007/03/29 13:18:58 oman
Вычитываем таки параметры контекстного фильтра для атрибутов
Revision 1.131 2007/03/28 14:51:21 oman
- new: Избавляемся от ContextParams в КЗ (cq24456)
Revision 1.130 2007/03/28 08:39:45 oman
cleanup
Revision 1.129 2007/03/27 12:43:17 oman
Пользуем родные деревья для атрибутов
Revision 1.128 2007/03/27 11:59:34 oman
Переводим тэг атрибутов на константную строку
Revision 1.127 2007/03/19 12:08:52 lulin
- используем свою функцию форматирования.
Revision 1.126 2007/03/19 11:35:29 lulin
- разделяем приведение к строке для форматирования и для исключения.
Revision 1.125 2007/03/16 16:57:16 lulin
- избавляемся от излишнего копирования и преобразования строк.
Revision 1.124 2007/03/14 16:41:47 lulin
- cleanup.
Revision 1.123 2007/03/14 16:28:08 lulin
- cleanup.
Revision 1.122 2007/03/14 15:51:20 lulin
- cleanup.
Revision 1.121 2007/03/14 15:46:06 lulin
- cleanup.
Revision 1.120 2007/03/14 15:36:48 lulin
- cleanup.
Revision 1.119 2007/03/06 10:13:48 oman
Cleanup - убран мусорный параметр
Revision 1.118 2007/03/06 08:17:59 oman
Cleanup
Revision 1.117 2007/03/06 08:14:19 oman
Cleanup - убрано мусорное свойство ContextFilterType
Revision 1.116 2007/03/05 14:22:20 oman
- fix: Неверно определяли поле для удаления (cq24549)
Revision 1.115 2007/02/27 13:39:11 lulin
- cleanup.
Revision 1.114 2007/02/16 18:06:14 lulin
- избавляемся от стандартного строкового типа.
Revision 1.113 2007/02/16 15:16:53 lulin
- cleanup.
Revision 1.112 2007/02/16 14:53:09 lulin
- избавляемся от использования стандартных строк.
Revision 1.111 2007/02/14 17:49:30 lulin
- избавляемся от использования стандартных строк.
Revision 1.110 2007/02/14 17:04:59 lulin
- избавляемся от использования стандартных строк.
Revision 1.109 2007/02/14 16:51:00 lulin
- избавляемся от использования стандартных строк.
Revision 1.108 2007/02/14 16:13:54 lulin
- переводим на строки с кодировкой.
Revision 1.107 2007/02/14 14:24:20 lulin
- переводим на строки с кодировкой.
Revision 1.106 2007/02/13 14:33:32 lulin
- cleanup.
Revision 1.105 2007/02/13 09:33:52 lulin
- переводим на строки с кодировкой.
Revision 1.104 2007/02/12 19:35:56 lulin
- переводим на строки с кодировкой.
Revision 1.103 2007/02/12 17:15:54 lulin
- переводим на строки с кодировкой.
Revision 1.102 2007/02/12 09:58:51 lulin
- bug fix: искажались входные строковые параметры адаптера.
Revision 1.101 2007/02/09 12:58:29 lulin
- выделена функция преобразования к входной строке адаптера.
Revision 1.100 2007/02/07 17:48:54 lulin
- избавляемся от копирования строк при чтении из настроек.
Revision 1.99 2007/02/07 14:47:35 lulin
- переводим на строки с кодировкой.
Revision 1.98 2007/02/07 12:45:11 lulin
- переводим на строки с кодировкой.
Revision 1.97 2007/02/05 09:40:13 lulin
- две функции объединены в одну.
Revision 1.96 2007/02/05 09:07:26 lulin
- bug fix: не собирались мониторинги.
Revision 1.95 2007/02/02 13:23:58 lulin
- упрощаем преобразование строк.
Revision 1.94 2007/02/02 12:25:44 lulin
- переводим на строки с кодировкой.
Revision 1.93 2007/02/02 09:10:50 lulin
- упрощаем преобразование строк.
Revision 1.92 2007/02/02 08:39:25 lulin
- переводим на строки с кодировкой.
Revision 1.91 2007/01/26 14:34:23 lulin
- поправил обращение к неправильному параметру.
Revision 1.90 2007/01/20 15:30:33 lulin
- разделяем параметры операции для выполнения и для тестирования.
Revision 1.89 2006/12/01 15:20:35 mmorozov
- new: информация о локали выделана в отдельный интерфейс;
Revision 1.88 2006/11/28 15:35:29 mmorozov
- опубликован идентификатор языка приложения IafwApplication.LocateId: LCID;
- существовавшее свойство LocateId переименовано в DetailedLanguageId;
- после чтения строкового идентфикатора языка приложения проверяем его на допустимость;
- формируем идентфикаторы языков приложения по первому требованию;
- при определении языка прилоежния используем идентфикаторы опубликованные в afwInterfaces;
Revision 1.87 2006/11/20 12:12:10 oman
Merge from B_NEMESIS_6_4
Revision 1.86 2006/11/10 16:00:02 oman
Merge from B_NEMESIS_6_4
Revision 1.85 2006/11/07 14:28:30 oman
Merge from B_NEMESIS_6_4
Revision 1.84 2006/11/03 09:46:21 oman
Merge with B_NEMESIS_6_4_0
Revision 1.83.2.4.2.3 2006/11/20 12:06:11 oman
- fix: В сообщении не выводилось значение поля (cq23690)
Revision 1.83.2.4.2.2 2006/11/10 10:05:55 oman
Убран ненужный метод
Revision 1.83.2.4.2.1 2006/11/07 14:23:19 oman
- fix: При укладке в кэш не чистились атрибуты (cq23452)
Revision 1.83.2.4 2006/10/25 07:29:39 oman
Продолжаем избавлятся от StdStr
Revision 1.83.2.3 2006/10/25 06:49:57 oman
- fix: Более гуманная зачистка перед поиском (cq23205, 23114)
Revision 1.83.2.2 2006/10/24 09:46:54 oman
- fix: В КЗ при возврате по истории оставались мусорные поля
- теперь пустые поля удаляются _перед_ сохранением (cq23114)
Revision 1.83.2.1 2006/10/24 09:43:54 oman
no message
Revision 1.83 2006/10/04 11:01:43 oman
- fix: При выборе из карточки атрибутов не сбрасывалось выделение
Revision 1.82 2006/09/28 15:03:31 oman
- new: Выделена функция починяющая контекст при вставке
из клипборда (cq22776)
Revision 1.81 2006/09/27 13:42:15 mmorozov
В рамках работы над CQ: OIT500022679.
- remove: TTagSearch, TTagSearchList, TAvailableTags. В списки были не работоспособны, в единственном месте где списки использовались, можно было обойтись _IAttributeInfo;
- remove: неиспользуемые операции в enSelectedAttributesForm (enSelectedList: opAdd, opDelete, opChangeOperation);
- new: TnsTaggedTreeInfo наделен логикой;
Revision 1.80 2006/09/18 11:33:40 oman
-new: для КЗ ПП сохраняем ФИО и телефон послу успешной посылки
в настройки и восстанавливаем их при открытии (cq22612)
Revision 1.79 2006/09/18 09:08:41 oman
- fix: Корректная проверка правильности ввода
- fix: Корректное ограничение на длину полей
cleanup (ненужные операции/сообщения/проверки)
Revision 1.78 2006/09/14 14:16:27 oman
- new: Изменения в КЗ ПП (cq22535)
Revision 1.77 2006/09/11 14:02:16 oman
- new: Схлопывание подсказки в ППР (cq21474)
- fix: Более корректная работа с гиперссылками в КЗ.
Revision 1.76 2006/07/18 09:59:24 oman
- fix: При работе с карточкой атрибута неверно обновлялось
название в мониторингах (cq21909)
Revision 1.75 2006/07/12 15:03:08 oman
- new beh: Формирование заголовка для новостной ленты другим макаром (cq21699)
Revision 1.74 2006/07/10 08:04:40 oman
- new beh: В карточке выбора даты подставляем заголовок от
редактируемого атрибута (cq21733)
Revision 1.73 2006/07/05 10:00:12 oman
- new beh: При вставке в контекст из клипборда убираем нераспознаваемые символы (cq21628)
Revision 1.72 2006/06/29 11:56:13 mmorozov
- change: изменения в связи с поялением типа GblAdapter.TDateTime;
Revision 1.71 2006/06/29 10:29:36 mmorozov
- new behaviour: перед вставкой элемента в список анализируем его на предмет сортированности (CQ: OIT500021526);
Revision 1.70 2006/06/21 09:09:44 dinishev
Дополнительная проверка дат перед вызовом диалога
Revision 1.69 2006/06/16 09:23:48 oman
- fix: Отсутствовал признак посланности консультации для истории -
не все учел... (cq21330)
Revision 1.68 2006/06/16 07:45:41 oman
- fix: В карточку выбора дат отдавался реквизит, который после
переключения баз становился дохлым => имели AV (cq21336)
Revision 1.67 2006/06/15 08:35:48 oman
- fix: Отсутствовал признак посланности консультации для истории (cq21330)
Revision 1.66 2006/06/09 12:24:09 dinishev
Bug fix: не компилировались мониторинги
Revision 1.65 2006/06/09 08:44:38 dinishev
Использование одной операции для кнопок видимости кнопок и добавления текста
Revision 1.64 2006/06/08 14:41:49 dinishev
Bug fix: сохранялись данные для откакти при заполнении КЗ значениями по умолчнанию или загруженными значениями
Revision 1.63 2006/05/23 16:09:06 dinishev
Cleanup
Revision 1.62 2006/05/19 11:06:04 dinishev
Cleanup
Revision 1.61 2006/04/24 08:58:11 dinishev
Отъехало очищение логического значения для реквизита
Revision 1.60 2006/04/21 12:44:32 dinishev
new constansts
Revision 1.59 2006/04/21 12:12:15 dinishev
Bug fix: была возможность сохранить запрос в утилите заказа рассылки с пустым именем
Revision 1.58 2006/04/20 08:53:53 oman
- new beh: перекладываем StdStr в _StdRes
Revision 1.57 2006/04/19 13:34:22 oman
- new beh: перекладываем StdStr в _StdRes
Revision 1.56 2006/04/19 09:08:03 dinishev
Cleanup
Revision 1.55 2006/04/18 14:06:55 oman
- new beh: перекладываем StdStr в _StdRes
Revision 1.54 2006/04/17 14:42:38 oman
- new beh: перекладываем StdStr в _StdRes
Revision 1.53 2006/04/14 13:23:08 dinishev
Cleanup
Revision 1.52 2006/04/13 17:07:21 lulin
- падали при неприсвоенной карточке.
Revision 1.51 2006/04/11 14:16:05 dinishev
Более правильная установка курсора после ошибки
Revision 1.50 2006/04/10 14:38:53 dinishev
Bug fix: отъехала выдача сообщений о пустых полях в тулзе заказа рассылки
Revision 1.49 2006/04/07 08:46:21 mmorozov
- add: _NeedSettings для запроса на консультацию не нужен;
Revision 1.48 2006/04/07 08:25:24 mmorozov
- приведение к общему знаменателю Поиска с правовой поддержкой, Запроса на консультацию, Консультации;
Revision 1.47 2006/04/03 16:26:18 dinishev
Не компилировалось
Revision 1.46 2006/04/03 15:56:14 dinishev
_CleanUp
Revision 1.45 2006/03/31 07:42:34 lulin
- изменен тип параметров, подаваемый в Execte операции.
Revision 1.44 2006/03/27 13:35:35 lulin
- cleanup.
Revision 1.43 2006/03/22 08:41:54 oman
- new beh: Перекладываем все текстовые константы в три места (StdStr, DebugStr и SystemStr)
Revision 1.42 2006/03/20 15:11:00 dinishev
Bug fix: не сохранялся запрос в историю
Revision 1.41 2006/03/20 09:27:50 oman
- new beh: Перекладываем все текстовые константы в три места (StdStr, DebugStr и SystemStr)
Revision 1.40 2006/03/17 14:31:51 dinishev
Bug fix: List Index out of bounds при возврате по истории при символах разделителя в контексте.
Revision 1.39 2006/03/16 15:24:31 dinishev
Bug fix: при повторном вызове новой КЗ появлялось пустое окно
Revision 1.38 2006/03/15 15:06:18 dinishev
Корректная очиста многострочного поля
Revision 1.37 2006/03/10 13:37:53 dinishev
Подключение новой КЗ
Revision 1.36 2006/03/07 10:35:03 mmorozov
- warnings fix;
Revision 1.35 2006/03/04 13:15:11 dinishev
Более корректная установка курсора после очистки КЗ
Revision 1.34 2006/03/02 14:45:34 dinishev
Comment
Revision 1.33 2006/03/02 14:15:20 dinishev
Bug fix: в результате откатки не сбрасывался выбранный узел.
Revision 1.32 2006/02/16 12:52:01 mmorozov
- bugfix: после обновления при сбросе дерева не выключался контекстный фильтр (CQ: 17586) + интерфейс InscContextParams переехал в правильное место;
Revision 1.31 2006/02/13 15:01:32 dinishev
Коррекция поведения кнопки "Добавить"
Revision 1.30 2006/02/07 11:07:11 dinishev
Cleanup
Revision 1.29 2006/02/06 17:02:19 dinishev
Bug fix: при вызове операции "Удалить все" курсор ставился не в нужное место (CQ19357)
Revision 1.28 2006/01/30 07:58:16 mmorozov
bugfix: при открытии формы выбора атрибутов не передавались параметры контекстной фильтрации;
Revision 1.27 2006/01/17 15:37:57 dinishev
Bug fix: валились на обработке значения вида "1, ,2" в буфере.
Revision 1.26 2006/01/16 17:32:09 dinishev
Убрал сбрасываемость выделения красным неправильного значения
Revision 1.25 2005/12/29 11:54:07 dinishev
К сожалению, заплатка все еще нужна. Вернул вчерашнее изменения.
Revision 1.24 2005/12/28 18:20:13 dinishev
Bug fix: после обновления при возврате по истории приходила некорректная КЗ
Revision 1.23 2005/12/27 11:36:43 dinishev
Bug fix: не записываем дублирующие значения в историю ввода контекста
Revision 1.22 2005/12/26 15:52:37 dinishev
Выключена некорректно работающая проверка на дублирующие значения для полей конекста
Revision 1.21 2005/12/23 15:45:45 dinishev
Bug fix: в утилите заказа рассылки была возможность закрыть дерево, без подстановки значения и поле "Название" на это не среагирует
Revision 1.20 2005/12/22 17:33:12 lulin
- убрано предупреждение.
Revision 1.19 2005/12/22 16:44:48 dinishev
Bug fix: не очищалась КЗ после выбора из истории запросов
Revision 1.18 2005/12/19 13:55:48 dinishev
Bug fix: утечка памяти
Revision 1.17 2005/12/14 15:56:26 dinishev
Cleanup
Revision 1.16 2005/12/13 16:20:48 dinishev
Bug fix: не всегда корректно перерисовывалась КЗ после загрузке/возврате по истории
Revision 1.15 2005/12/12 17:15:54 dinishev
Bug fix: считывалась не вся история ввода контекста
Revision 1.14 2005/12/08 18:13:45 dinishev
Cleanup
Revision 1.13 2005/12/07 18:08:54 dinishev
Cleanup
Revision 1.12 2005/12/06 06:56:48 dinishev
no message
Revision 1.11 2005/11/28 17:59:44 dinishev
Bug fix: портилось поведение контекстных полей при возврате по истории
Revision 1.10 2005/11/24 18:03:15 dinishev
Bug fix: не всегда обновляли метку в первом поле
Revision 1.9 2005/11/24 15:12:58 dinishev
Cleanup
Revision 1.8 2005/11/24 09:45:22 dinishev
_CleanUp
Revision 1.7 2005/11/23 17:08:56 dinishev
Cleanup
Revision 1.6 2005/11/23 08:59:17 dinishev
Bug fix: корректное поведение кнопки "Добавить"
Revision 1.5 2005/11/22 18:54:31 lulin
- продолжаем пилить дерево на разные функциональные части.
Revision 1.4 2005/11/21 09:06:23 dinishev
Bug fix: текст в поле ввода мог выделяться красным, даже если было выбрано правильное значение.
Revision 1.3 2005/11/18 16:40:10 dinishev
Cleanup
Revision 1.2 2005/11/17 13:22:39 dinishev
Избавляемся от заплаток
Revision 1.1 2005/11/17 05:46:17 dinishev
_Move to directory 'Search'
Revision 1.105 2005/11/15 12:41:10 dinishev
Bug fix: неправильно выставлялся признак полей с номерами
Revision 1.104 2005/11/14 14:24:36 dinishev
Bug fix: корректная реакция на символ '*' в полях номера
Revision 1.103 2005/11/11 20:23:17 dinishev
Подсветка красным дублирующих значений в контекстных полях
Revision 1.102 2005/11/10 15:54:18 dinishev
Bug fix: после обновления загруженный запрос очищался.
Revision 1.101 2005/11/09 18:45:26 dinishev
Подправлено обновление
Revision 1.100 2005/11/08 15:11:15 mmorozov
bugfix: избавляемся от неосвобожденных объектов;
Revision 1.99 2005/11/08 13:17:13 mmorozov
bugfix: освобождаем память;
Revision 1.98 2005/11/04 16:50:10 dinishev
Нажатия Enter приводит к открытию окна выбора или запуску поиска (в зависимости от реквизита)
Revision 1.97 2005/11/01 18:24:27 dinishev
AV при попытке очистить КЗ при открытом дереве
Revision 1.96 2005/10/31 17:25:25 dinishev
no message
Revision 1.95 2005/10/28 13:43:58 dinishev
Bug fix: теперь вычищаем историю Undo после очистки КЗ
Revision 1.94 2005/10/27 13:30:30 dinishev
Bug fix: не обновлялось дерево, реквизита, для которого было открыто окно выбора.
Revision 1.93 2005/10/27 11:11:06 dinishev
Метод ChangeValues перенесен в другой класс
Revision 1.92 2005/10/24 15:38:20 dinishev
_CleanUp
Revision 1.91 2005/10/22 11:41:55 dinishev
Bug fix: могли быть не переинициализированы деревья при обновлении
Revision 1.90 2005/10/21 16:35:22 dinishev
Bug fix: не компилировались мониторинги
Revision 1.89 2005/10/21 16:23:39 dinishev
Clenup
Revision 1.88 2005/10/21 14:54:24 dinishev
Bug fix: сообщение об ошибке в дате
Revision 1.87 2005/10/20 16:38:22 dinishev
Обработка запятой и точки с запятой в контестных полях (вставка из буфера с добавлением полей)
Revision 1.86 2005/10/20 15:03:56 dinishev
добавлена возможность проверки для поля "Слова в названии"
Revision 1.85 2005/10/19 16:50:24 dinishev
Bug fix: не показывались хинты для кнопок
Revision 1.84 2005/10/19 14:25:39 dinishev
Bug fix: раскрытие панелей при загрузке
Revision 1.83 2005/10/18 07:33:29 dinishev
_CleanUp
Revision 1.82 2005/10/14 13:32:29 dinishev
_CleanUp
Revision 1.81 2005/10/13 17:25:08 dinishev
Попытка отвязать модель от редактора и привязать её к DocumentContainer
Revision 1.80 2005/10/12 16:43:22 dinishev
Предварительные изменения для корректной обработки события обновления
Revision 1.79 2005/10/11 11:46:09 dinishev
Bug fix: правильное выставление признака _Modified
Revision 1.78 2005/10/11 09:39:29 dinishev
Bug fix: кнопка "Удалить" у поля "Название" в F1Prime при загрузке была видима.
Revision 1.77 2005/10/11 09:31:15 dinishev
Bug fix: кнопка у поля "Название" в F1Prime просто очищала поле, не подставляя значение по умолчанию
Revision 1.76 2005/10/06 17:48:52 dinishev
Не копировалась история ввода во вторичные поля + не всегда срабатывало заполнение истрии
Revision 1.75 2005/10/05 17:37:10 dinishev
Контекстные меню
Revision 1.74 2005/10/03 17:00:30 dinishev
Bug fix: корректная загрузка операций по умолчанию
Revision 1.73 2005/09/29 15:06:53 dinishev
Подстветка красным дублирующих значений
Revision 1.72 2005/09/29 11:26:22 dinishev
Доработки работы с доступными операциями
Revision 1.71 2005/09/29 08:17:51 dinishev
Bug fix: не показывалась история запросов
Revision 1.70 2005/09/27 16:25:16 dinishev
Bug fix: при нажатии кнопки "добавить" не устанавливался фокус во вновь добавленное окно.
Revision 1.69 2005/09/27 16:12:56 dinishev
_CleanUp
Revision 1.68 2005/09/27 15:09:32 dinishev
Bug fix: попытка проверки морфологии при выходе без выполнения
Revision 1.67 2005/09/26 11:01:12 dinishev
Bug fix: используем Trim-фильтр для "Обзора законодательства"
Revision 1.66 2005/09/23 16:22:42 dinishev
Поддержка нового типа фильтра
Revision 1.65 2005/09/23 13:39:13 dinishev
Bug fix: можно свернуть группу, даже если в ней есть отмеченные значения
Revision 1.64 2005/09/23 12:12:36 dinishev
Bug fix: пункты "где искать контекст" и "Искать в недействующих редакциях"
снабжены кнопкой логич. условия слева от поля
Revision 1.63 2005/09/22 15:02:34 dinishev
Проверка морфологического контекста
Revision 1.62 2005/09/22 10:20:17 dinishev
Comments
Revision 1.61 2005/09/21 14:28:56 dinishev
Bug fix: неправильная загрузка дат в запрос
Revision 1.60 2005/09/21 14:04:53 dinishev
Bug fix: не компилировался Nemesis
Revision 1.59 2005/09/21 13:54:29 dinishev
Для утилиты мониторингов установка фокуса в поле "Название" (как в старой КЗ)
Revision 1.58 2005/09/20 11:26:39 dinishev
Bug fix: не сохранялось значение реквизита при открытом дереве и начале выполнения запроса
Revision 1.57 2005/09/19 15:00:47 dinishev
AV при удалении поля + перемещение дерева при изменении размеров поля ввода + подстановка значений по умолчанию
Revision 1.56 2005/09/16 15:03:25 dinishev
Первое приближение обработки гиперссылок + автоматическое формирование значений + проверка E-mail
Revision 1.55 2005/09/15 14:11:06 dinishev
Загрузка значений по умолчанию + Bug fix: AV при вводе символов с клавиатуры
Revision 1.54 2005/09/14 13:50:38 dinishev
Передача флага для фильтрации полей
Revision 1.53 2005/09/12 16:05:38 dinishev
Bug fix: не запоминалась история ввода контекста в поля.
Revision 1.52 2005/09/12 14:39:47 dinishev
Bug fix: висла оболочка
Revision 1.51 2005/09/09 13:20:24 dinishev
Bug fix: контекстные поля не определялись
Revision 1.50 2005/09/09 12:02:57 dinishev
Hints к кнопкам.
Revision 1.49 2005/09/08 16:16:49 dinishev
Small changes
Revision 1.48 2005/09/08 14:56:45 dinishev
Загрузка и сохранение истории ввода для контекста
Revision 1.47 2005/09/07 14:27:01 dinishev
New function NeedHistory
Revision 1.46 2005/09/07 09:08:29 dinishev
Remove interface InevInputListner
Revision 1.45 2005/09/05 10:53:52 dinishev
Поддержка запрета множественного выбора реквизита
Revision 1.44 2005/09/03 13:07:11 migel
- fix: не компилировалось.
Revision 1.43 2005/09/02 14:52:05 dinishev
Загрузка и сохранение КЗ (в частности запроса) из истории
Revision 1.42 2005/09/02 10:16:14 dinishev
Bug fix: AV при старте КЗ
Revision 1.41 2005/09/02 09:44:00 dinishev
Bug fix: не компилировалось
Revision 1.40 2005/09/02 09:21:17 dinishev
Поддержка истории ввода
Revision 1.39 2005/09/01 15:06:28 dinishev
Ошибка загрузки логических значений
Revision 1.38 2005/09/01 14:42:52 dinishev
Remove class TqaReqDict
Revision 1.37 2005/09/01 12:15:02 dinishev
Корректная загрузка дат
Revision 1.36 2005/08/31 17:40:58 dinishev
Не сохраняем значение AT_TEXT_OPT, если не выставлено AT_TEXT
Revision 1.35 2005/08/31 17:30:03 dinishev
Очистка всех видов реквизитов + _CleanUp
Revision 1.34 2005/08/30 09:50:26 dinishev
Bug fix: утечки памяти в утилите
Revision 1.33 2005/08/29 09:28:15 dinishev
Борьба с утечками памяти.
Revision 1.32 2005/08/25 15:23:43 dinishev
Bug fix: более правильное подставление логического значения
Revision 1.31 2005/08/25 14:20:59 dinishev
Bug fix: из прослойки получались неправильные логические значения.
Revision 1.30 2005/08/25 11:08:52 dinishev
Доработка передачи данных из окна выбора реквизитов и обратно.
Revision 1.29 2005/08/24 16:41:55 dinishev
Расширение интерфейсов для поддержки обработки дат.
Revision 1.28 2005/08/24 08:04:30 dinishev
AV при попытке поиска.
Revision 1.27 2005/08/23 14:07:44 dinishev
Не компилировалось
Revision 1.26 2005/08/23 13:43:55 dinishev
Нотификация об изменении текста в поле редактора
Revision 1.25 2005/08/19 07:38:39 dinishev
Bug fix: некомпилировалось
Revision 1.24 2005/08/19 07:01:40 dinishev
Сleanup
Revision 1.23 2005/08/19 06:42:32 dinishev
Bug fix: незаполнялся список атрибутов, формирующих название рассылки.
Revision 1.22 2005/08/18 14:13:56 dinishev
Не компилировалиь мониторинги
Revision 1.21 2005/08/18 13:54:15 dinishev
Подправлены названия тегов
Revision 1.20 2005/08/18 08:10:56 dinishev
Восстановление логики формирования автоматического значения в утилите
Revision 1.19 2005/08/18 06:59:13 dinishev
Bug fix: Значение по умолчанию не передавалось в запрос.
Revision 1.18 2005/08/16 15:03:24 dinishev
no message
Revision 1.17 2005/08/16 13:08:07 dinishev
Убран лишний код при создании КЗ
Revision 1.16 2005/08/16 07:31:13 dinishev
Rename evScriptModel -> evDropControls
Revision 1.15 2005/08/15 13:28:54 dinishev
Получение реквизита по имени + директива LOAD_FROM_CARD - для загрузки данных запросов из КЗ
Revision 1.14 2005/08/15 12:04:43 dinishev
Bug fix: не компилировалось.
Revision 1.13 2005/08/15 10:49:20 dinishev
Поддержка DefaultValue
Revision 1.12 2005/08/15 08:27:32 dinishev
Отказ от _Events в интерфейсах Починка отъехавших иконок в деревьях.
Revision 1.11 2005/08/12 16:36:03 dinishev
Новые интерфейсы с обработчиками - подготовка к переходу на листнеры
Revision 1.10 2005/08/12 15:47:51 dinishev
Некоторые классы переехали в другие модули
Revision 1.9 2005/08/11 16:42:04 dinishev
no message
Revision 1.8 2005/08/11 16:29:06 dinishev
no message
Revision 1.7 2005/08/11 15:30:51 dinishev
_CleanUp
Revision 1.6 2005/08/11 14:42:07 dinishev
Bug fix: зависание при выборе дерева контекста
Revision 1.5 2005/08/11 14:15:42 dinishev
Получение картинок для некоторых атрибутов
Revision 1.4 2005/08/11 12:51:32 dinishev
Нормальная инициализация бизнес-логики
Revision 1.3 2005/08/08 14:06:32 dinishev
Change: вернул код, вырезанный Мишей Морозовым. Код пока отключен, так что AV не будет.
Revision 1.2 2005/07/26 12:55:47 mmorozov
bugfix: AV при открытии карточки (удалены рудиментные методы);
Revision 1.1 2005/07/22 15:48:40 dinishev
Новая EVD
-----------------------------------------------------------------------------*)
{$Include nsDefine.inc}
interface
//{$DEFINE NEW_TREE}
uses
ImgList,
Classes,
l3Interfaces,
l3Types,
l3Base,
l3TreeInterfaces,
l3CacheableBase,
l3CObjectRefList,
afwInterfaces,
vcmBase,
vcmEntities,
vcmExternalInterfaces,
nevBase,
nevTools,
evQueryCardInt,
nsTypes,
nscInterfaces,
{$IfNDef Admin}
nsSearchClasses,
{$EndIf Admin}
nsQueryInterfaces,
BaseTreeSupportUnit,
DynamicTreeUnit,
SearchUnit,
lgTypes,
SearchDomainInterfaces
{$If not Defined(Admin) AND not Defined(Monitorings)}
,
BaseSearchInterfaces
{$IfEnd}
;
type
TqaMgrSearch = class;
TqaReq = class(Tl3CacheableBase, IqaReqPrim, IqaReq)
private
// internal fields
f_MgrSearch : IqaMgrSearch;
{-}
f_EditorReq : IevReq;
{* - Интерфейс реквизита из редактора. }
protected
{$IFDEF Monitorings}
procedure MakeChangedReq;
{-}
{$ENDIF Monitorings}
function Get_EditorReq: IevReq;
{-}
function Get_Multy: Boolean;
virtual;
{-}
function Get_TagCaption: Il3Cstring;
{-}
function Get_TagName: Il3CString;
{-}
function CanAdd: Boolean;
virtual;
{* - Проверяет можно ли добавить еще одно поле к реквизиту. }
function CanOpenTree: Boolean;
virtual;
{* - Проверяет можно ли добавить еще одно поле к реквизиту. }
function IsAttrValid: Boolean;
{ Проверяет втрибут на правильность ввода }
procedure DoOperateChanged;
virtual;
{* - Обработчик изменения поля. }
function Get_Modified: Boolean;
procedure Set_Modified(Value: Boolean);
{-}
function GetReqAsString(const aSeparator: Il3CString): Il3CString;
virtual;
{* - Формирует строку всех полей реквизита, определенных пользователем
и разделенных разделителем aSeparator. }
{$IFDEF Monitorings}
procedure MakeFieldValue;
virtual;
{-}
{$EndIF Monitorings}
function BeforeGroupCollapse : Boolean;
virtual;
{-}
procedure SaveReq;
virtual;
abstract;
{-}
procedure Cleanup;
override;
{-}
function IsEditEmpty: Boolean;
{* - Проверяет есть ли значения в поле ввода. Имеет смысл только для
одиночных полей. }
procedure Load;
virtual;
{-}
procedure DeleteEmptyValues;
{-}
public
// public methods
constructor Create(const aMgrSearch : IqaMgrSearch;
const aEditorReq : IevReq);
reintroduce;
virtual;
{-}
class function Make(const aMgrSearch : IqaMgrSearch;
const aEditorReq : IevReq): IqaReq;
{-}
procedure Clear;
virtual;
{-}
procedure OpenSelectWindow;
virtual;
{-}
function IsSet(aElseDefaultValue : Boolean = False): Boolean;
{* - Если True, то в компоненте установлено значение. }
procedure CheckAttr;
virtual;
{-}
function CheckFromControl(out aExceptionClass : EaqExceptionClass;
out aMessage : String;
out aControl : IevEditorControlField): Boolean;
virtual;
{-}
procedure Save;
{-}
procedure ReqClear;
virtual;
{* - Очистка реквизита с удалением всех полей, кроме одного. }
public
// public properties
property Multy: Boolean
read Get_Multy;
{-}
property TagName: Il3CString
read Get_TagName;
{-}
property TagCaption: Il3Cstring
read Get_TagCaption;
{-}
property EditorReq: IevReq
read Get_EditorReq;
{* - Ссылка на внутренний атрибут. }
property Modified: Boolean
read Get_Modified
write Set_Modified;
{* - Атрибут модифицирова пользователем со времени последнего сохранения. }
end;//TqaReq
TqaAttrInfo = class(Tl3CObjectRefList)
{* - Предназначен для сохранения IDictNode и типа операции. }
private
// private fields
f_Mask : Il3CString;
{-}
f_Oper : TLogicOperation;
{-}
f_Node : INodeBase;
{-}
protected
// protected methods
procedure Cleanup;
override;
{-}
public
// public methods
constructor Create(const aOper : TLogicOperation = loNone;
const aNode : INodeBase = nil;
const aMask : Il3CString = nil);
reintroduce;
virtual;
{* - Создает класс и инициализирует значениями. }
public
// public properties
property Mask: Il3CString
read f_Mask
write f_Mask;
{* - Пользователь установил маску в поле ввода. }
property Oper: TLogicOperation
read f_Oper
write f_Oper;
{-}
property NodeBase : INodeBase
read f_Node;
{-}
end;//TqaAttrInfo
TqaAttrInfoList = class(Tl3CObjectRefList)
end;//TqaAttrInfoList
TqaEventReq = class(TqaReq, IevModelListner)
//Класс создан исключительно ради поддержки интерфейса IevModelListner.
protected
function GetHint4Button(const aValue: IevEditorControlButton): Il3CString;
virtual;
{* - Возвращает текст к кнопке для конкретных реквизитов. }
function StateIndex2LogicState(aValue: Integer): TLogicOperation;
{* - Переводит логическое состояние в TLogicOperation. }
//interface IevModelListner
function CheckValue(const aField : IevEditorControlField): Boolean;
{* - Проверка значения поля. }
function GetImage(Index: Longint;
var aImages: InevImageList) : Integer;
{-}
procedure EnterPressed;
virtual;
{* - Обработчик нажатия на "Enter". }
procedure TextChange;
virtual;
{-}
procedure AfterSetText(const aField: IevEditorControlField);
virtual;
{-}
function AnalysString(const aValue : Il3CString;
out aRslt : Il3CString): Boolean;
virtual;
{-}
procedure HyperLinkClick;
virtual;
{-}
function GetHint(const aValue: IevEditorControl): Il3CString;
{-}
function pm_GetAdditionalFilter: TnsFilterType;
{-}
protected
// internal properties
property AdditionalFilter: TnsFilterType
read pm_GetAdditionalFilter;
{-}
end;//TqaEventReq
TqaReqComboField = class(TqaEventReq)
public
function CheckFromControl(out aExceptionClass : EaqExceptionClass;
out aMessage : String;
out aControl : IevEditorControlField): Boolean;
override;
{-}
procedure CheckAttr;
override;
{-}
procedure ReqClear;
override;
{* - Очистка реквизита с удалением всех полей, кроме одного. }
end;//TqaReqComboField
TqaCustomReqContext = class(TqaReqComboField)
protected
function AnalysString(const aValue : Il3CString;
out aRslt : Il3CString): Boolean;
override;
{-}
function GetReqAsString(const aSeparator: Il3CString): Il3CString;
override;
{* - Формирует строку контекста из всех строк определенных пользователем
и разделенную разделителем aSeparator. }
procedure FillReqListAsString(const aList: Il3StringsEx);
{-}
procedure EnterPressed;
override;
{* - Обработчик нажатия на "Enter". }
function CanAdd: Boolean;
override;
{* - Проверяет можно ли добавить еще одно поле к реквизиту. }
procedure Load;
override;
{-}
public
constructor Create(const aMgrSearch : IqaMgrSearch;
const aEditorReq : IevReq);
override;
{-}
procedure SaveReq;
override;
{-}
end;//TqaCustomReqContext
TqaReqContext = class(TqaCustomReqContext, IqaMorphoReq)
procedure CheckAttr;
override;
{-}
end;//TqaReqContext
TqaCommonStrReq = class(TqaCustomReqContext)
protected
procedure TextChange;
override;
{-}
procedure Load;
override;
{-}
public
procedure SaveReq;
override;
{-}
procedure ReqClear;
override;
{* - Очистка реквизита с удалением всех полей, кроме одного. }
end;//TqaCommonStrReq
TqaReqMemo = class(TqaCommonStrReq)
end;//TqaReqMemo
TqaReqStr = class(TqaCommonStrReq)
protected
function Get_Multy: Boolean;
override;
{-}
{$IFDEF Monitorings}
procedure MakeFieldValue;
override;
{* - Функция, устанавливающая значение поля при изменении. }
procedure ReqClear;
override;
{-}
{$EndIF Monitorings}
procedure Load;
override;
{-}
end;//TqaReqStr
TqaReqEMail = class(TqaReqStr)
procedure CheckAttr;
override;
{-}
function CheckFromControl(out aExceptionClass : EaqExceptionClass;
out aMessage : String;
out aControl : IevEditorControlField): Boolean;
override;
{-}
end;//TqaReqEMail
TqaReqAttribute = class(TqaReqComboField, IqaReqAttribute)
private
// internal methods
function Root : INodeBase;
{* - Полученное view. Создаётся один раз и раздаётся полям ввода. }
procedure SetAttributesToView;
{* - Устанавливаем флаги операций нода в дереве. }
procedure GetAttributesFromView(const aRoot : INodeBase);
{* - Вычитываем флаги операций из дерева (создаёт поля ввода). }
protected
// protected methods
procedure EnterPressed;
override;
{* - Обработчик нажатия на "Enter". }
procedure AfterSetText(const aField: IevEditorControlField);
override;
{-}
function GetReqAsString(const aSeparator: Il3CString): Il3CString;
override;
{-}
procedure SaveFieldToQuery(const aValue: IevEditorControlField);
{* - Замена TasField.SaveToQuery. }
procedure DoOperateChanged;
override;
{* - Обработчик изменения поля. }
function FieldLogicOperation(const aValue: IevEditorFieldWithTree): TLogicOperation;
{* - Возващает логическую операцию для поля. }
procedure LoadField(const aValue: IevEditorFieldWithTree;
aLogicOper: TLogicOperation;
const aNode: INodeBase);
{* - Загрузить данные в поле. }
function CanAdd: Boolean;
override;
{* - Проверяет можно ли добавить еще одно поле к реквизиту. }
function CanOpenTree: Boolean;
override;
{* - Проверяет можно ли открыть окно выбора реквизитов для реквизита. }
public
// public methods
procedure OpenSelectWindow;
override;
{-}
procedure Load;
override;
{-}
procedure SaveReq;
override;
{-}
end;//TqaReqAttribute
TqaReqNum = class(TqaReqAttribute)
protected
procedure InitFields;
override;
{-}
end;//TqaReqNum
TqaReqDate = class(TqaEventReq, IqaDateReq)
protected
// protected methods
function Get_Multy: Boolean;
override;
{-}
function GetHint4Button(const aValue: IevEditorControlButton): Il3CString;
override;
{* - Возвращает текст к кнопке для конкретных реквизитов. }
function Get_EndDate: System.TDateTime;
{-}
function Get_StartDate: System.TDateTime;
{-}
procedure Set_EndDate(const Value: System.TDateTime);
{-}
procedure Set_StartDate(const Value: System.TDateTime);
{-}
function BeforeGroupCollapse : Boolean;
override;
{-}
procedure InitFields;
override;
{-}
procedure SaveReq;
override;
{-}
procedure HyperLinkClick;
override;
{-}
procedure EnterPressed;
override;
{* - Обработчик нажатия на "Enter". }
function CanOpenTree: Boolean;
override;
{* - Проверяет можно ли добавить еще одно поле к реквизиту. }
public
// public methods
procedure OpenSelectWindow;
override;
{-}
procedure Load;
override;
{-}
procedure ReqClear;
override;
{-}
procedure CheckAttr;
override;
{-}
function CheckFromControl(out aExceptionClass : EaqExceptionClass;
out aMessage : String;
out aControl : IevEditorControlField): Boolean;
override;
{-}
property StartDate: System.TDateTime
read Get_StartDate
write Set_StartDate;
{-}
property EndDate: System.TDateTime
read Get_EndDate
write Set_EndDate;
{-}
end;//TqaReqDate
TqaDateReqDataHolder = class(TvcmBase, IqaDateReqDataHolder)
private
f_StartDate: System.TDateTime;
{-}
f_EndDate: System.TDateTime;
{-}
f_IsOk: Boolean;
{-}
f_ReqCaption: Il3CString;
{-}
function Get_EndDate: System.TDateTime;
{-}
function Get_StartDate: System.TDateTime;
{-}
procedure Set_EndDate(const Value: System.TDateTime);
{-}
procedure Set_StartDate(const Value: System.TDateTime);
{-}
function Get_IsOk: Boolean;
{-}
procedure Set_IsOk(const Value: Boolean);
{-}
function Get_ReqCaption: Il3CString;
{-}
function IsStartDateEmpty: Boolean;
{-}
function IsEndDateEmpty: Boolean;
{-}
protected
// internal methods
procedure Cleanup;
override;
{-}
public
constructor Create(const aReq: IqaDateReq);
reintroduce;
{-}
class function Make(const aReq: IqaDateReq): IqaDateReqDataHolder;
reintroduce;
{-}
property StartDate: System.TDateTime
read Get_StartDate
write Set_StartDate;
{-}
property EndDate: System.TDateTime
read Get_EndDate
write Set_EndDate;
{-}
property IsOk: Boolean
read Get_IsOk
write Set_IsOk;
{-}
property ReqCaption: Il3CString
read Get_ReqCaption;
end;//TqaDateReqDataHolder
TqaReqPhone = class(TqaEventReq, IqaPhoneReq)
protected
// protected methods
function Get_Multy: Boolean;
override;
{-}
function Get_Number: Il3CString;
procedure Set_Number(const Value: Il3CString);
{-}
function Get_Code: Il3CString;
procedure Set_Code(const Value: Il3CString);
{-}
procedure SaveReq;
override;
{-}
function CanOpenTree: Boolean;
override;
{* - Проверяет можно ли добавить еще одно поле к реквизиту. }
public
// public methods
procedure Load;
override;
{-}
procedure ReqClear;
override;
{-}
public
property Code: Il3CString
read Get_Code
write Set_Code;
property Number: Il3CString
read Get_Number
write Set_Number;
end;//TqaReqPhone
TqaMgrSearch = class(TvcmBase, IqaMgrSearch, IevAdapterModel
{$If not Defined(Admin) AND not Defined(Monitorings)}
,
InsMistakesCorrector
{$IfEnd}
)
{* - Предназначен для загрузки из IQuery и выгрузки из IQuery, управление
элементами поиска. }
private
f_FormName : Il3CString;
{-}
f_Query : IQuery;
{-}
f_IsQueryNew : Boolean;
{-}
f_QueryType : TlgQueryType;
{-}
f_QueryCard : IevQueryCard;
{-}
f_OnDateQuery : TOnDateQuery;
{-}
f_OnNeedExecQuery : TNotifyEvent;
{-}
f_OnModifiedChanged : TNotifyEvent;
{-}
f_InModifiedChanged : Integer;
{-}
f_FromHistory : Boolean;
{-}
{$If not Defined(Admin) AND not Defined(Monitorings)}
f_ContextHistory : InsContextSearchHistory;
{-}
{$IfEnd}
f_Modified : Integer;
f_GettingAttributesFromView : Integer;
f_FirstErrorContextReq: IevEditorControlField;
private
// private methods
function NeedSettings: Boolean;
{-}
procedure FinishEntering;
{-}
// property methods
function Get_Modified: Boolean;
{-}
procedure Set_Modified(Value: Boolean);
{-}
function Get_IsNew: Boolean;
{-}
function Get_QueryType: TlgQueryType;
{-}
function MakeGroupsSettingId: Il3CString;
{-}
function MakeDescriptionsSettingId: Il3CString;
{-}
protected
{$If not Defined(Admin) AND not Defined(Monitorings)}
// InsMistakesCorrector
procedure Correct(const aCorrectedContext: Il3StringsEx;
const aMistakesList: Il3StringsEx);
{$IfEnd}
// IAdapterModel
procedure FocusStartField;
{-}
procedure LimitCharsReached(const aControl: IevEditorControl);
{* - Обработчик достижания максимального количества символов в контроле. }
function ModelListner(const aReq: IevReq): IevModelListner;
{-}
// protected methods
{$If not Defined(Admin) AND not Defined(Monitorings)}
function Get_HistoryList: IvcmStrings;
{-}
{$IfEnd}
function Get_QueryCard: IevQueryCard;
{-}
{$IFDEF Monitorings}
function GetName4Query: Il3CString;
{* - Возвращают имя для запроса. }
{$ENDIF Monitorings}
procedure FinishOpenTree(const aRoot : INodeBase;
const aReq : IqaReq);
{-}
function GetCurrentReq: IqaReq;
{* - Возвращает текущий реквизит для контрола. }
function GetCurrentEditorReq: IevReq;
{* - Возвращает текущий реквизит для контрола. }
function GetCurrentField: IevEditorControlField;
{* - Возвращает текущий контрол для реквизита. }
function Get_FromHistory: Boolean;
{-}
procedure Set_FromHistory(const Value: Boolean);
{-}
function Get_Query: IQuery;
{-}
procedure Set_Query(const Value: IQuery);
{-}
procedure IterateAttrsF(anAction : Tl3FreeAction);
{-}
procedure DeleteValue(const aView: InevView);
{-}
procedure DeleteAll;
{-}
procedure AddValue(const aView: InevView);
{-}
procedure DateQuery(const aValue: IqaDateReq);
{-}
procedure CallModifiedChanged;
{-}
procedure ModifiedChanged(aValue: Boolean);
{-}
procedure ExecQuery;
{* - Запустить запрос на выполнение. }
procedure OpenSelectWindow;
{* - Открыть окно выбора реквизита. }
function FindAttr(const aTagName : Il3CString): IqaReq;
{* - Возвращает атрибут по имени. }
procedure ClearAttrs;
{-}
function GettingFromView: Boolean;
{-}
procedure StartGettingFromView;
{-}
procedure FinishGettingFromView;
{-}
function GetTreeFromAdapter(const aReq: Il3CString): Il3SimpleTree;
{* - Получает дерево с адаптера. }
function GetPromptTreeFromAdapter: Il3SimpleTree;
{* - Получает дерево с адаптера. }
procedure NotifyContextWrong;
{-}
procedure Cleanup;
override;
{-}
public
// public methods
constructor Create(const aQuery : IQuery;
aQueryType : TlgQueryType;
const aFormName : Il3CString;
const OnDateQuery : TOnDateQuery;
const OnNeedExecQuery : TNotifyEvent;
const OnModifiedChanged : TNotifyEvent
{$If not Defined(Admin) AND not Defined(Monitorings)}
;
const aContextHistory : InsContextSearchHistory
{$ifEnd}
);
reintroduce;
virtual;
{* - Парамтры:
- aQueryType (тип запроса);
- aFormName (имя формы для сохранения в настройки); }
class function Make(const aQuery : IQuery;
aQueryType : TlgQueryType;
const aFormName : Il3CString;
const OnDateQuery : TOnDateQuery;
const OnNeedExecQuery : TNotifyEvent;
const OnModifiedChanged : TNotifyEvent
{$If not Defined(Admin) AND not Defined(Monitorings)}
;
const aContextHistory : InsContextSearchHistory
{$IfEnd}
): IqaMgrSearch;
{-}
procedure InitUpdate;
{-}
procedure CheckAttrs;
{-}
{$If not (defined(Monitorings) or defined(Admin))}
procedure CheckMorpho;
{-}
{$IfEnd}
function Save(aIgnoreError: Boolean = False): Boolean;
{-}
function IsSomeFieldFilled(aElseDefaultValue: Boolean = False): Boolean;
{-}
procedure Load;
{-}
procedure ReadSettings;
{-}
procedure WriteSettings;
{-}
{$IFDEF Monitorings}
procedure Check;
{-}
{$EndIF Monitorings}
procedure Clear;
reintroduce;
{-}
procedure ClearContextMistakes;
{-}
procedure CreateTree(const aQueryCard: IevQueryCard);
{-}
procedure InitFocus;
{* - Устанавливает фокус первой панели. }
procedure EscPressed(const aField: IevEditorFieldWithTree);
{-}
{$IFDEF Monitorings}
function ChangableReq: IqaReq;
{* - Изменяющаеся значение при изменении реквизита. }
{$ENDIF Monitorings}
public
// public property
procedure ChangeStateAll(const aExpand: Boolean);
{-}
property Query: IQuery
read Get_Query
write Set_Query;
{-}
property QueryType: TlgQueryType
read Get_QueryType;
{-}
property IsQueryNew: Boolean
read Get_IsNew;
{* - Является ли запрос новым, т.е. не загруженным из базы. }
property Modified: Boolean
read Get_Modified
write Set_Modified;
{* - Атрибут модифицирова пользователем со времени последнего сохранения. }
property QueryCard: IevQueryCard
read Get_QueryCard
write f_QueryCard;
{* - Вход в прослойку со стороны редактора. }
property FromHistory: Boolean
read Get_FromHistory
write Set_FromHistory;
{-}
{$If not Defined(Admin) AND not Defined(Monitorings)}
property HistoryValues: IvcmStrings
read Get_HistoryList;
{-}
{$ifEnd}
end;//TqaMgrSearch
_afwApplicationDataUpdate_Parent_ = TvcmCacheableBase;
{$Include afwApplicationDataUpdate.imp.pas}
TqaHistory = class(_afwApplicationDataUpdate_,
IvcmBase,
IqaHistory)
{* - реализует интерфейс IqaHistory. }
private
f_Filter : INode;
f_Query : IQuery;
f_DataReset : Boolean;
f_ConsultationSened : Boolean;
private
// property methods
function GetFilter: INode;
{-}
procedure SetFilter(const aNode: INode);
{-}
function GetQuery: IQuery;
{-}
procedure pm_SetQuery(const aValue: IQuery);
{-}
function GetDataReset : Boolean;
{-}
procedure SetConsultationSended(const aValue : Boolean);
{-}
function GetConsultationSended: Boolean;
{-}
protected
procedure FinishDataUpdate;
override;
{* вызывает по окончании обновления }
protected
// protected methods
procedure Cleanup;
override;
{-}
end;//TqaHistory
TqaReqClass = class of TqaReq;
{$If not defined(Admin)}
procedure LoadDateNew(const aQuery : IQuery;
const aTagName : Il3CString;
var aStartDate : System.TDateTime;
var aEndDate : System.TDateTime);
{* - Загрузить диапазон дат из IQuery. }
{$IfEnd}
procedure LoadPhone(const aQuery : IQuery;
const aTagName : Tl3WString;
out aCode : Il3CString;
out aNumber : Il3CString);
{* - Загрузить номер телефона из IQuery. }
{$IfNDef Admin}
procedure LoadDictionaryNew(aList : TqaAttrInfoList;
const aQuery : IQuery;
const aTagName : Il3CString);
{* - Загрузить значение реквизита. }
{$EndIf Admin}
implementation
uses
SysUtils,
Math,
Controls,
Dialogs,
Forms,
StdRes,
SystemStr,
DebugStr,
{$IfNDef Admin}
SearchRes,
{$EndIf Admin}
l3Const,
l3Chars,
l3Date,
l3String,
l3Bits,
l3ImageList,
k2Tags,
afwFacade,
evdTypes,
evControlParaConst,
evControlParaTools,
evParaTools,
evSearch,
evdStyles,
evTypes,
evSegLst,
vcmForm,
vcmSettings,
vcmStringList,
vcmInterfaces,
bsUtils,
{$If not defined(Admin)}
nsQuery,
{$IfEnd}
nsConst,
nsTreeUtils,
nsQueryUtils,
nsDataResetTreeStruct,
nsVerifyValue,
{$If not defined(Admin)}
nsbQueryUtils,
{$IfEnd}
nsContextUtils,
nsINodeWrap,
nsLogicOperationToFlags,
nsAttributeTreeCacheNew,
nsUtils,
nsAttributeTreeStruct,
// nsBaseSearchPromptTree, // К-104432064
IOUnit,
DataAdapter,
bsInterfaces
{$If not Defined(Admin) AND not Defined(Monitorings)}
,
nsContextHistory
{$IfEnd}
,
vcmMessagesSupport
;
{$Include afwApplicationDataUpdate.imp.pas}
{$IfNDef Admin}
const
c_InpharmSearches = [lg_qtInpharmSearch];
procedure LoadDictionaryNew(aList : TqaAttrInfoList;
const aQuery : IQuery;
const aTagName : Il3CString);
var
l_List : IQueryAttributeList;
l_Index : Integer;
l_Context : IQueryContextAttribute;
l_Node : IQueryNodeAttribute;
l_ContextList : IContextValueList;
l_I : Integer;
l_NodeList : INodeValueList;
l_AttrInfo : TqaAttrInfo;
l_Count : Integer;
l_ContCount : Integer;
l_NodeCount : Integer;
l_Attribute : IQueryAttribute;
l_ContextValue: TContextValue;
l_NodeValue : TQueryNodeValue;
begin
aQuery.AttributesByTag(nsAStr(aTagName).S, l_List);
if Assigned(l_List) then
try
l_Count := l_List.Count - 1;
for l_Index := 0 to l_Count do
begin
l_List.pm_GetItem(l_Index, l_Attribute);
case l_Attribute.GetType of
// Маска для номеров
QTT_CONTEXT:
if Supports(l_Attribute, IQueryContextAttribute, l_Context) then
try
l_Context.GetValues(l_ContextList);
l_ContCount := l_ContextList.Count - 1;
for l_I := 0 to l_ContCount do
begin
l_ContextList.pm_GetItem(l_I, l_ContextValue);
with l_ContextValue do
begin
l_AttrInfo := TqaAttrInfo.Create(LQOperationToLSelection(rOperation),
nil,
nsCStr(rContext));
try
aList.Add(l_AttrInfo);
finally
vcmFree(l_AttrInfo);
end;
end;
end;
finally
l_Context := nil;
end;
// Древовидное значение
QTT_NODE:
if Supports(l_Attribute, IQueryNodeAttribute, l_Node) then
try
l_Node.GetValues(l_NodeList);
l_NodeCount := l_NodeList.Count - 1;
for l_I := 0 to l_NodeCount do
begin
l_NodeList.pm_GetItem(l_I, l_NodeValue);
with l_NodeValue do
begin
l_AttrInfo := TqaAttrInfo.Create(LQOperationToLSelection(rOperation),
rNode);
try
aList.Add(l_AttrInfo);
finally
vcmFree(l_AttrInfo);
end;
end;
end;
finally
l_Node := nil;
end;
end;
end;
finally
l_List := nil;
end;
end;
{$EndIf Admin}
{$If not defined(Admin)}
procedure LoadDateNew(const aQuery : IQuery;
const aTagName : Il3CString;
var aStartDate : System.TDateTime;
var aEndDate : System.TDateTime);
{* - Загрузить диапазон дат из IQuery. }
var
l_Node : IQueryDateAttribute;
l_List : IQueryAttributeList;
l_ValueList : IDateValueList;
l_Attribute : IQueryAttribute;
l_DateValue : TDateValue;
begin
aStartDate := NullDate;
aEndDate := NullDate;
aQuery.AttributesByTag(nsAStr(aTagName).S, l_List);
if Assigned(l_List) and (l_List.Count > 0) then
begin
// Для одного тега может быть только одно значение
l_List.pm_GetItem(0, l_Attribute);
if (l_Attribute.GetType = QTT_DATE) and Supports(l_Attribute,
IQueryDateAttribute, l_Node) then
try
// Список значений
l_Node.GetValues(l_ValueList);
if l_ValueList.Count > 0 then
begin
l_ValueList.pm_GetItem(0, l_DateValue);
with l_DateValue do
begin
// Начало
if not IsNullDate(rFrom) then
aStartDate := GblAdapterDateToDateTime(rFrom);
// Конец
if not IsNullDate(rTo) then
aEndDate := GblAdapterDateToDateTime(rTo);
end;//with l_ValueList.GetDataPtr(0)^
end;
finally
l_Node := nil;
end;//try..finally
end;//l_List.GetCount > 0
end;
{$IfEnd}
procedure LoadPhone(const aQuery : IQuery;
const aTagName : Tl3WString;
out aCode : Il3CString;
out aNumber : Il3CString);
{* - Загрузить номер телефона из IQuery. }
var
l_Node : IQueryPhoneNumberAttribute;
l_Str : IString;
begin
aQuery.GetPhoneNumberAttribute(nsAStr(aTagName).S, l_Node);
l_Node.GetCityCode(l_Str);
aCode := nsCStr(l_Str);
l_Node.GetPhoneNumber(l_Str);
aNumber := nsCStr(l_Str);
end;
function DoShowTree(const aTagName : Il3CString;
const anAdditionalFilter : TnsFilterType) : Boolean;
var
l_Cursor : TCursor;
begin
Result := False;
l_Cursor := Screen.Cursor;
try
Screen.Cursor := crHourGlass;
Result := TdmStdRes.OpenTreeSelection(aTagName, anAdditionalFilter, nil) = mrOk;
finally
Screen.Cursor := l_Cursor;
end;//try..finally
end;
// start class TqaMgrSearch
function TqaMgrSearch.Get_Query: IQuery;
begin
Result := f_Query;
end;
function TqaMgrSearch.Get_QueryType: TlgQueryType;
begin
Result := f_QueryType;
end;
class function TqaMgrSearch.Make(const aQuery : IQuery;
aQueryType : TlgQueryType;
const aFormName : Il3CString;
const OnDateQuery : TOnDateQuery;
const OnNeedExecQuery : TNotifyEvent;
const OnModifiedChanged : TNotifyEvent
{$If not Defined(Admin) AND not Defined(Monitorings)}
;
const aContextHistory: InsContextSearchHistory
{$IfEnd}
): IqaMgrSearch;
var
l_MsgSearch: TqaMgrSearch;
begin
l_MsgSearch := Create(aQuery, aQueryType, aFormName, OnDateQuery, OnNeedExecQuery,
OnModifiedChanged
{$If not Defined(Admin) AND not Defined(Monitorings)}
, aContextHistory
{$IfEnd}
);
try
Result := l_MsgSearch;
finally
l3Free(l_MsgSearch);
end;
end;
procedure TqaMgrSearch.ChangeStateAll(const aExpand: Boolean);
var
l_Index: Integer;
l_Group: IevQueryGroup;
begin
for l_Index := 0 to f_QueryCard.GroupCount - 1 do
begin
l_Group := f_QueryCard.QueryGroup[l_Index];
try
l_Group.Expanded := aExpand;
finally
l_Group := nil;
end;
end;
end;
{$IFDEF Monitorings}
procedure TqaMgrSearch.Check;
begin
try
CheckAttrs;
except
on E: EqaException do
begin
with E.ErrorControl do
begin
with Req.Group do
if not Expanded then
Expanded := True;
Req.SetFocus(E.ErrorControl, True);
end;
raise;
end;
end;
end;
{$EndIF Monitorings}
procedure TqaMgrSearch.Cleanup;
begin
f_FirstErrorContextReq := nil;
f_FormName := nil;
{$If not Defined(Admin) AND not Defined(Monitorings)}
f_ContextHistory := nil;
{$IfEnd}
if (f_QueryCard <> nil) then
f_QueryCard.ReleaseListners;
f_QueryCard := nil;
f_Query := nil;
inherited;
end;
procedure TqaMgrSearch.Clear;
begin
if (f_QueryCard <> nil) then
begin
(f_QueryCard As InevControlListner).HideDroppedControl(True);
ClearAttrs;
Self.QueryCard.CardClear
end;//f_QueryCard <> nil
{$IFDEF Monitorings}
f_Query := nil;
nsQuery.CreateQuery(f_Query, BusinessQueryToAdapterQuery(f_QueryType));
{$ELSE Monitorings}
f_Query.Clear;
{$ENDIF Monitorings}
end;
constructor TqaMgrSearch.Create(const aQuery : IQuery;
aQueryType : TlgQueryType;
const aFormName : Il3CString;
const OnDateQuery : TOnDateQuery;
const OnNeedExecQuery : TNotifyEvent;
const OnModifiedChanged : TNotifyEvent
{$If not Defined(Admin) AND not Defined(Monitorings)}
;
const aContextHistory : InsContextSearchHistory
{$IfEnd}
);
begin
f_FormName := aFormName;
f_QueryType := aQueryType;
f_IsQueryNew := True;
f_OnDateQuery := OnDateQuery;
f_OnNeedExecQuery := OnNeedExecQuery;
f_OnModifiedChanged := OnModifiedChanged;
{$If not Defined(Admin) AND not Defined(Monitorings)}
f_ContextHistory := aContextHistory;
{$IfEnd}
// Загрузим IQuery
if (aQuery = nil) then
{$If not defined(Admin)}
nsQuery.CreateQuery(f_Query, BusinessQueryToAdapterQuery(aQueryType))
{$Else}
Assert(false)
{$IfEnd}
else
begin
f_Query := aQuery;
f_IsQueryNew := False;
end;//aQuery = nil
end;
procedure TqaMgrSearch.CreateTree(const aQueryCard: IevQueryCard);
{$IFDEF Monitorings}
var
CR : IqaReq;
{$EndIF Monitorings}
begin
if (aQueryCard <> f_QueryCard) then
begin
if (f_QueryCard <> nil) then
f_QueryCard.LinkListner(nil);
f_QueryCard := aQueryCard;
f_QueryCard.LinkListner(Self);
end;//aQueryCard <> f_QueryCard
// Загрузим значения
if not f_IsQueryNew then
Load;
{$IFDEF Monitorings}
CR := ChangableReq;
if (CR <> nil) then //Значение по умолчанию для поля "Тема"
CR.MakeFieldValue;
{$ENDIF Monitorings}
InitFocus;
if (QueryCard <> nil) then
QueryCard.CardClear;
end;
function TqaMgrSearch.FindAttr(const aTagName : Il3CString): IqaReq;
{* - Возвращает атрибут по имени. }
function DoReq(const aReq: IqaReq): Boolean;
begin
Result := not l3Same(aReq.TagName, aTagName, true);
if not Result then
FindAttr := aReq;
end;
begin
Result := nil;
IterateAttrsF(l3L2FA(@DoReq));
end;
procedure TqaMgrSearch.ClearAttrs;
{-}
function DoReq(const aReq: IqaReq): Boolean;
begin
Result := true;
aReq.ReqClear;
end;
{$IfDef Monitorings}
var
l_CR : IqaReq;
{$EndIf Monitorings}
begin
IterateAttrsF(l3L2FA(@DoReq));
{$IfDef Monitorings}
l_CR := ChangableReq;
if (l_CR <> nil) then
l_CR.MakeFieldValue;
{$EndIf Monitorings}
end;
function TqaMgrSearch.GettingFromView: Boolean;
{-}
begin
Result := (f_GettingAttributesFromView > 0);
end;
procedure TqaMgrSearch.StartGettingFromView;
{-}
begin
Inc(f_GettingAttributesFromView);
QueryCard.StartLongOperation;
end;
procedure TqaMgrSearch.FinishGettingFromView;
{-}
begin
QueryCard.EndLongOperation;
Dec(f_GettingAttributesFromView);
end;
function GetAdditionalFilter(const aTagName : Il3CString;
const aQueryType : TlgQueryType): TnsFilterType;
begin
Case aQueryType of
lg_qtLegislationReview:
begin
if l3Same(aTagName, AT_CLASS) or
l3Same(aTagName, AT_CLASS_REVIEW) then
Result := ns_ftTrim
else
if (l3Same(aTagName, AT_SOURCE) or
l3Same(aTagName, AT_SOURCE_REVIEW) OR
l3Same(aTagName, AT_PREFIX_REVIEW)) then
Result := ns_ftTrimLeaf
else
Result := ns_ftNone;
end;//lg_qtLegislationReview
lg_qtAttribute:
begin
if l3Same(aTagName, AT_PREFIX) then
Result := ns_ftTrimLeaf
else
Result := ns_ftNone;
end;//lg_qtAttribute
else
Result := ns_ftNone;
end;//Case aQueryType
if l3Same(aTagName, AT_BASES) then
Result := ns_ftBlocks;
end;
function TqaMgrSearch.GetTreeFromAdapter(const aReq: Il3CString): Il3SimpleTree;
{* - Получает дерево с адаптера. }
var
l_Filters : InsAttributeTreeFilters;
l_Tree : Il3FilterableTree;
l_Index : Integer;
l_AF : TnsFilterType;
begin
Result := TnsAttributeTreeStruct.Make(aReq, False);
if Supports(Result, Il3FilterableTree, l_Tree) and
Supports(l_Tree.CloneFilters, InsAttributeTreeFilters, l_Filters) then
begin
l_AF := GetAdditionalFilter(aReq, QueryType);
if (l_Filters.FilterType <> l_AF) then
Result := l_Tree.MakeFiltered(l_Filters.SetFilterType(l_AF).
SetContext(nil),
nil,
l_Index,
True,
true);
end;//Supports(Result, Il3FilterableTree, l_Tree)..
end;
procedure TqaMgrSearch.IterateAttrsF(anAction : Tl3FreeAction);
{-}
var
I, J : Integer;
l_QueryGroup : IevQueryGroup;
l_Req : IqaReq;
begin
if Assigned(anAction) then
try
if (f_QueryCard <> nil) then
begin
for I := 0 to f_QueryCard.GroupCount - 1 do
begin
l_QueryGroup := f_QueryCard.QueryGroup[I];
try
for J := 0 to l_QueryGroup.ReqCount - 1 do
begin
l_Req := TqaReq.Make(Self, l_QueryGroup.Req[J]);
try
if not anAction(Pointer(l_Req)) then
Exit;
finally
l_Req := nil;
end;//try..finally
end;//for J
finally
l_QueryGroup := nil;
end;//try..finally
end;//for I
end;//f_QueryCard <> nil
finally
l3FreeFA(anAction);
end;//try..finally
end;
procedure TqaMgrSearch.InitFocus;
begin
if NeedSettings then
f_QueryCard.StartSetFocus;
end;
{$IFDEF Monitorings}
const
cSrc : array [0..1] of string = (AT_ANNO_KIND, AT_ANNO_USER);
{$ENDIF Monitorings}
procedure TqaMgrSearch.EscPressed(const aField: IevEditorFieldWithTree);
{-}
{$IFDEF Monitorings}
var
l_CR : IqaReq;
{$ENDIF Monitorings}
begin
{$IFDEF Monitorings}
if l3SomeOf(aField.Req.ReqName, cSrc) then
begin
l_CR := ChangableReq;
if (l_CR <> nil) then
l_CR.MakeFieldValue;
end;//l3Same(aField.Req.ReqName, cSrc[l_Index])
{$ENDIF Monitorings}
end;
{$IFDEF Monitorings}
function TqaMgrSearch.ChangableReq: IqaReq;
{* - Изменяющаеся значение при изменении реквизита. }
begin
Result := FindAttr(nsCStr(cChangableReqName));
end;
{$ENDIF Monitorings}
function TqaMgrSearch.IsSomeFieldFilled(aElseDefaultValue: Boolean): Boolean;
function DoReq(const aReq: IqaReq): Boolean;
begin
Result := not aReq.IsSet(aElseDefaultValue);
if not Result then
IsSomeFieldFilled := true;
end;
begin
Result := false;
IterateAttrsF(l3L2FA(@DoReq));
end;
procedure TqaMgrSearch.Load;
function DoReq(const aReq: IqaReq): Boolean;
begin
Result := true;
aReq.Load;
end;
{$IFDEF Monitorings}
var
CR : IqaReq;
{$EndIF Monitorings}
begin
QueryCard.StartLongOperation;
try
IterateAttrsF(l3L2FA(@DoReq));
{$IFDEF Monitorings}
CR := ChangableReq;
if (CR <> nil) then //Значение по умолчанию для поля "Тема"
CR.MakeFieldValue;
{$ENDIF Monitorings}
Modified := False;
finally
QueryCard.EndLongOperation;
end;// asLockedPaint;
end;
function TqaMgrSearch.Get_IsNew: Boolean;
begin
Result := f_IsQueryNew;
end;
function TqaMgrSearch.Get_Modified: Boolean;
begin
Result := (f_Modified > 0);
end;
procedure TqaMgrSearch.Set_Modified(Value: Boolean);
function DoReq(const aReq: IqaReq): Boolean;
begin
Result := true;
aReq.Modified := Value;
end;
begin
if (Get_Modified <> Value) then
begin
Inc(f_InModifiedChanged);
try
IterateAttrsF(l3L2FA(@DoReq));
finally
Dec(f_InModifiedChanged);
end;//try..finally
CallModifiedChanged;
end;//Get_Modified <> Value
end;
procedure TqaMgrSearch.CallModifiedChanged;
{-}
begin
if (f_InModifiedChanged <= 0) then
begin
Inc(f_InModifiedChanged);
try
if Assigned(f_OnModifiedChanged) then
f_OnModifiedChanged(Self);
finally
Dec(f_InModifiedChanged);
end;//try..finally
end;//f_InModifiedChanged <= 0
end;
procedure TqaMgrSearch.ModifiedChanged(aValue: Boolean);
{-}
begin
if aValue then
Inc(f_Modified)
else
Dec(f_Modified);
CallModifiedChanged;
end;
function TqaMgrSearch.MakeDescriptionsSettingId: Il3CString;
begin
Result := l3Fmt('%s/%s', [pi_CollapsedDescriptions, f_FormName]);
end;
procedure TqaMgrSearch.Set_Query(const Value: IQuery);
{$IFDEF Monitorings}
var
CR : IqaReq;
{$EndIF Monitorings}
begin
if (Value <> nil) then
begin
if f_Query <> nil then
f_Query.Clear;
if not f_FromHistory then
begin
ClearAttrs;
Self.QueryCard.CardClear;
end;//not f_FromHistory
f_Query := nil;
f_Query := Value;
Load;
f_IsQueryNew := False; //Формирование значения поля для загруженного запроса
{$IFDEF Monitorings}
CR := ChangableReq;
if (CR <> nil) then
begin
CR.MakeFieldValue;
InitFocus;
end;//CR <> nil
{$ENDIF Monitorings}
end//Value <> nil
else
begin
f_IsQueryNew := True; //Чистая КЗ
f_Query := nil;
end;//Value <> nil
end;
procedure TqaMgrSearch.CheckAttrs;
{-}
function DoCheckReq(const aReq: IqaReq): Boolean;
begin
Result := true;
aReq.CheckAttr;
end;
begin
IterateAttrsF(l3L2FA(@DoCheckReq));
end;
function TqaMgrSearch.Save(aIgnoreError: Boolean): Boolean;
function DoReq(const aReq: IqaReq): Boolean;
begin
Result := true;
aReq.Save;
end;
begin
FinishEntering;
Result := True;
try
CheckAttrs;
{$If not (defined(Monitorings) or defined(Admin))}
if not aIgnoreError then
CheckMorpho;
{$IfEnd}
except
on E: EqaException do
begin
Result := False;
if not aIgnoreError then
begin
with E.ErrorControl do
begin
with Req.Group do
if not Expanded then
Expanded := True;
Req.SetFocus(E.ErrorControl, True);
end;//with E.ErrorControl
raise;
end;//not aIgnoreError
end;//on E: EqaException
end;//try..except
// При переключении конфигурации запрос мог достаться от карточки 5.х с типом
// QT_OLD_ATTRIBUTE, поэтому создаем новый запрос
(* if f_Query.GetType = QT_OLD_ATTRIBUTE then
{$If not defined(Admin)}
nsQuery.CreateQuery(f_Query, BusinessQueryToAdapterQuery(f_QueryType));
{$Else}
Assert(false);
{$IfEnd}*)
f_Query.Clear;
IterateAttrsF(l3L2FA(@DoReq));
end;//Save
procedure TqaMgrSearch.FinishEntering;
begin
(f_QueryCard As InevControlListner).HideDroppedControl(True);
end;//FinishEntering
procedure TqaMgrSearch.ReadSettings;
const
FuckMagic = 'NOT DEFINED';
var
l_Groups : Il3CString;
l_Index : Integer;
l_DIdx : Integer;
l_GroupCount : Integer;
l_Descriptions : Il3CString;
begin
if NeedSettings then
begin
g_Dispatcher.FormDispatcher.Lock;
try
l_GroupCount := f_QueryCard.GroupCount - 1;
l_Descriptions := afw.Settings.LoadString(nsAStr(MakeDescriptionsSettingId).S,'');
for l_Index := 0 to l_GroupCount do
with f_QueryCard.QueryGroup[l_Index] do
for l_DIdx := 0 to DescriptionReqCount-1 do
with DescriptionReq[l_DIdx] do
Collapsed := (l3Pos(l_Descriptions,
l3Cat([nsCStr(' '),
l3Upper(ReqName),
nsCStr(' ')])) >= 0);
l_Groups := afw.Settings.LoadString(nsAStr(MakeGroupsSettingId).S, FuckMagic);
// читаем из настроек
if (l_GroupCount = 0) then
f_QueryCard.QueryGroup[0].Expanded := True
else
if (f_QueryType = lg_qtPostingOrder) then
f_QueryCard.ChangeStateAll(True)
else
if not l3Same(l_Groups, FuckMagic) then
for l_Index := 0 to l_GroupCount do
with f_QueryCard.QueryGroup[l_Index] do
Expanded := (l3Pos(l_Groups, GroupName) >= 0)
// при первой загрузке "Расширенные реквизиты свернуты"
else
if (l_GroupCount >= 0) then
begin
// свернём все
f_QueryCard.ChangeStateAll(False);
// развернём только первую
f_QueryCard.QueryGroup[0].Expanded := True;
end;//l_GroupCount >= 0
finally
g_Dispatcher.FormDispatcher.UnLock;
end;// g_Dispatcher.FormDispatcher.Lock;
end;//NeedSettings
end;//ReadSettings
procedure TqaMgrSearch.WriteSettings;
var
l_Index : Integer;
l_DIdx : Integer;
l_Groups : Il3CString;
l_Descriptions : Il3CString;
l_Group : IevQueryGroup;
begin
if NeedSettings AND (f_QueryCard <> nil) then
begin
l_Descriptions := nil;
l_Groups := nil;
// Запишем группы, которые развернуты
for l_Index := 0 to f_QueryCard.GroupCount - 1 do
begin
l_Group := f_QueryCard.QueryGroup[l_Index];
try
for l_DIdx := 0 to l_Group.DescriptionReqCount-1 do
with l_Group.DescriptionReq[l_DIdx] do
if Collapsed then
l_Descriptions := l3Cat([l_Descriptions,
nsCStr(' '),
l3Upper(ReqName),
nsCStr(' ')]);
if l_Group.Expanded then
l_Groups := l3Cat([l_Groups, l_Group.GroupName]);
finally
l_Group := nil;
end;//try..finally
end;//for l_Index
// Запомним закрытые группы в настройках
afw.Settings.SaveString(nsAStr(MakeGroupsSettingId).S, l_Groups);
afw.Settings.SaveString(nsAStr(MakeDescriptionsSettingId).S, l_Descriptions);
end;//NeedSettings
end;
function TqaMgrSearch.MakeGroupsSettingId: Il3CString;
begin
Result := l3Fmt('%s/%s', [pi_ClosedGroups, f_FormName]);
end;
function TqaMgrSearch.Get_FromHistory: Boolean;
begin
Result := f_FromHistory;
end;
procedure TqaMgrSearch.Set_FromHistory(const Value: Boolean);
begin
f_FromHistory := Value;
end;
procedure TqaMgrSearch.FocusStartField;
{$IFNDEF Monitorings}
function DoReq(const aReq: IqaReq): Boolean;
begin
Result := false;
// - прекращаем на первом реквизите
aReq.EditorReq.FirstField.SetFocus;
end;
{$EndIF Monitorings}
{$IFDEF Monitorings}
var
l_Req : IqaReq;
{$EndIF Monitorings}
begin
{$IFDEF Monitorings}
l_Req := FindAttr(nsCStr(cChangableReqName));
if (l_Req <> nil) then
l_Req.EditorReq.FirstField.SetFocus;
{$ELSE}
IterateAttrsF(l3L2FA(@DoReq));
{$ENDIF Monitorings}
end;
procedure TqaMgrSearch.DeleteValue(const aView: InevView);
var
l_Field: IevEditorControlField;
l_Req : IevReq;
begin
l_Field := GetCurrentField;
if Assigned(l_Field) then
begin
l_Req := GetCurrentEditorReq;
if Assigned(l_Req) then
l_Req.DeleteField(aView, l_Field, True);
end;
end;
procedure TqaMgrSearch.AddValue(const aView: InevView);
var
l_Req : IevReq;
begin
l_Req := GetCurrentEditorReq;
if l_Req <> nil then
l_Req.AddField(aView, True);
end;
procedure TqaMgrSearch.DeleteAll;
var
l_Req : IqaReq;
begin
l_Req := GetCurrentReq;
if l_Req <> nil then
l_Req.ReqClear;
end;
procedure TqaMgrSearch.OpenSelectWindow;
var
l_Req : IqaReq;
begin
l_Req := GetCurrentReq;
if l_Req <> nil then
l_Req.OpenSelectWindow;
end;
function TqaMgrSearch.GetCurrentReq: IqaReq;
var
l_CustCtrl : IevCustomEditorControl;
l_Control : IevEditorControl;
begin
l_CustCtrl := QueryCard.GetStateControl;
if (l_CustCtrl <> nil) and l_CustCtrl.Visible then
begin
if Supports(l_CustCtrl, IevEditorControl, l_Control) then
Result := TqaReq.Make(Self, l_Control.Req)
else
Result := nil;
end//(l_CustCtrl <> nil) and l_CustCtrl.Visible
else
Result := nil;
end;
function TqaMgrSearch.GetCurrentEditorReq: IevReq;
var
l_CustCtrl : IevCustomEditorControl;
l_Control : IevEditorControl;
begin
l_CustCtrl := QueryCard.GetStateControl;
if (l_CustCtrl <> nil) and l_CustCtrl.Visible then
begin
if Supports(l_CustCtrl, IevEditorControl, l_Control) then
Result := l_Control.Req
else
Result := nil;
end
else
Result := nil;
end;
function TqaMgrSearch.GetCurrentField: IevEditorControlField;
var
l_CustCtrl : IevCustomEditorControl;
l_Control : IevEditorControl;
begin
l_CustCtrl := QueryCard.GetStateControl;
if (l_CustCtrl <> nil) and l_CustCtrl.Visible then
begin
if Supports(l_CustCtrl, IevEditorControl, l_Control) then
if l_Control.Field = nil then
l_Control.QueryInterface(IevEditorControlField, Result)
else
Result := l_Control.Field
end
else
Result := nil;
end;
function TqaMgrSearch.Get_QueryCard: IevQueryCard;
begin
Result := f_QueryCard;
end;
procedure TqaMgrSearch.FinishOpenTree(const aRoot : INodeBase;
const aReq : IqaReq);
var
l_ReqAttr : IqaReqAttribute;
begin
QueryCard.Editor.Selection.Unselect;
if (aReq <> nil) and Supports(FindAttr(aReq.TagName), IqaReqAttribute, l_ReqAttr) then //Его может и не быть после обновления.
try
l_ReqAttr.GetAttributesFromView(aRoot);
finally
l_ReqAttr := nil;
end;//aReq <> nil
end;
procedure TqaMgrSearch.DateQuery(const aValue: IqaDateReq);
var
l_Req : IqaReq;
l_DateField : IevEditorCalendarField;
l_TagName : Il3CString;
l_DateReq : IqaDateReq;
l_Holder : IqaDateReqDataHolder;
begin
if Assigned(f_OnDateQuery) and Supports(aValue, IqaReq, l_Req) then
begin
l_TagName := l_Req.TagName;
//Заплатка: после откатки поле может содержать старую дату.
l_Req.EditorReq.FirstField.CheckDataText;
if Supports(l_Req.EditorReq.FirstField, IevEditorCalendarField, l_DateField) then
l_DateField.GetOtherField.CheckDataText;
//--Заплатка
l_Req := nil;
l_Holder := TqaDateReqDataHolder.Make(aValue);
f_OnDateQuery(l_Holder);
if l_Holder.IsOk then
begin
l_Req := FindAttr(l_TagName);
if Supports(l_Req, IqaDateReq, l_DateReq) then
begin
l_DateReq.StartDate := l_Holder.StartDate;
l_DateReq.EndDate := l_Holder.EndDate;
with l_Req.EditorReq do
if l_Holder.IsStartDateEmpty and Supports(FirstField, IevEditorCalendarField, l_DateField) then
SetFocus(l_DateField.GetOtherField)
else
SetFocus(l_DateField);
end;
end;
end;
end;
procedure TqaMgrSearch.ExecQuery;
begin
if Assigned(f_OnNeedExecQuery) then
f_OnNeedExecQuery(Self);
end;
procedure TqaMgrSearch.InitUpdate;
begin
f_QueryCard := nil;
end;
{$If not Defined(Admin) AND not Defined(Monitorings)}
function TqaMgrSearch.Get_HistoryList: IvcmStrings;
begin
Assert(Assigned(f_ContextHistory));
Result := f_ContextHistory.History;
end;
{$IfEnd}
procedure TqaMgrSearch.LimitCharsReached(const aControl: IevEditorControl);
begin
vcmSay(err_LimitCharsReached,[aControl.MaxLength]);
end;
function TqaMgrSearch.ModelListner(const aReq: IevReq): IevModelListner;
{-}
begin
if (aReq = nil) then
Result := nil
else
Supports(TqaReq.Make(Self, aReq), IevModelListner, Result);
end;
function TqaMgrSearch.NeedSettings: Boolean;
begin
Result := not (f_QueryType in [lg_qtSendConsultation]);
end;
{$IFDEF Monitorings}
function TqaMgrSearch.GetName4Query: Il3CString;
var
l_Field : IevEditorControlField;
CR : IqaReq;
begin
CR := ChangableReq;
Assert(CR <> nil);
l_Field := CR.EditorReq.FirstField;
if l_Field.IsFieldEmpty then
CR.MakeFieldValue;
Result := l_Field.Text;
end;
{$ENDIF Monitorings}
// start class TqaReq
function TqaReq.BeforeGroupCollapse: Boolean;
begin
Result := True;
end;
procedure TqaReq.CheckAttr;
begin
if f_EditorReq.IsRequired and not IsSet(False) then
raise EqaRequiredValue.CreateFmt(EditorReq.FirstField,
vcmConstString(str_RequiredValue),
[nsEStr(EditorReq.ReqCaption)]);
end;
procedure TqaReq.Cleanup;
begin
f_EditorReq := nil;
f_MgrSearch := nil;
inherited;
end;
procedure TqaReq.Clear;
begin
ReqClear;
Modified := True;
inherited;
end;
constructor TqaReq.Create(const aMgrSearch : IqaMgrSearch;
const aEditorReq : IevReq);
begin
inherited Create;
f_MgrSearch := aMgrSearch;
f_EditorReq := aEditorReq;
end;
procedure TqaReq.DoOperateChanged;
begin
{$IFDEF Monitorings}
if Modified then
MakeChangedReq;
{$ENDIF Monitorings}
end;
function TqaReq.GetReqAsString(const aSeparator: Il3CString): Il3CString;
begin
Result := nil;
end;
function TqaReq.IsEditEmpty: Boolean;
{-}
begin
Result := not IsSet(True);
end;
function TqaReq.IsSet(aElseDefaultValue: Boolean): Boolean;
{-}
begin
Result := evIsSomeFieldFilled(f_EditorReq, aElseDefaultValue);
end;
procedure TqaReq.Load;
begin
end;
{$IFDEF Monitorings}
procedure TqaReq.MakeFieldValue;
begin
end;
{$EndIF Monitorings}
procedure TqaReq.OpenSelectWindow;
begin
end;
function TqaReq.Get_Modified: Boolean;
begin
Result := f_EditorReq.Para.BoolA[k2_tiModified];
end;
procedure TqaReq.Set_Modified(Value: Boolean);
begin
with f_EditorReq.Para do
if (BoolA[k2_tiModified] <> Value) then
begin
BoolA[k2_tiModified] := Value;
if Assigned(f_MgrSearch) then
f_MgrSearch.ModifiedChanged(Value);
end;//BoolA[k2_tiModified] <> Value
end;
procedure TqaReq.ReqClear;
begin
end;
procedure TqaReq.DeleteEmptyValues;
var
l_Index : Integer;
l_ComboField : IevEditorFieldWithTree;
begin
if f_EditorReq.FieldsCount > 0 then
for l_Index := f_EditorReq.FieldsCount - 1 downto 0 do
if Supports(f_EditorReq.Fields[l_Index], IevEditorFieldWithTree, l_ComboField) and
l_ComboField.IsFieldEmpty then
f_EditorReq.DeleteField(nil, f_EditorReq.Fields[l_Index]);
end;
procedure TqaReq.Save;
begin
DeleteEmptyValues;
if IsSet then
SaveReq;
Modified := false;
end;
class function TqaReq.Make(const aMgrSearch : IqaMgrSearch;
const aEditorReq : IevReq): IqaReq;
var
l_Req : TqaReq;
l_CType : TevControlType;
l_ReqClass : TqaReqClass;
l_EdReq : IevComboReq;
begin
if (aEditorReq <> nil) then
l_CType := aEditorReq.FirstField.ControlType
else
l_CType := ev_ctCombo;
case l_CType of
ev_ctEdit:
l_ReqClass := TqaReqStr;
ev_ctEmailEdit:
l_ReqClass := TqaReqEMail;
ev_ctMemoEdit:
l_ReqClass := TqaReqMemo;
ev_ctCombo:
begin
if Supports(aEditorReq, IevComboReq, l_EdReq) then
begin
if l_EdReq.IsContext then
l_ReqClass := TqaReqContext
else
if aEditorReq.Para.BoolA[k2_tiNumList] then
l_ReqClass := TqaReqNum
else
l_ReqClass := TqaReqAttribute;
end//Supports(aEditorReq, IevComboReq, l_EdReq)
else
l_ReqClass := TqaReqAttribute;
end;//ev_ctCombo
ev_ctCalEdit:
l_ReqClass := TqaReqDate;
ev_ctPhoneEdit:
l_ReqClass := TqaReqPhone;
else
l_ReqClass := nil;
end;//case l_CType
Assert(Assigned(l_ReqClass), caUnsuppotedAttributeType);
l_Req := l_ReqClass.Create(aMgrSearch, aEditorReq);
try
Result := l_Req;
finally
l3Free(l_Req);
end;//try..finally
end;
function TqaReq.Get_EditorReq: IevReq;
begin
Result := f_EditorReq;
end;
function TqaReq.Get_TagCaption: Il3Cstring;
begin
Result := f_EditorReq.ReqCaption;
end;
function TqaReq.Get_TagName: Il3CString;
begin
Result := f_EditorReq.ReqName;
end;
{$IFDEF Monitorings}
procedure TqaReq.MakeChangedReq;
{-}
var
l_CR : IqaReq;
begin
if l3SomeOf(TagName, cSrc) then
begin
l_CR := f_MgrSearch.ChangableReq;
if (l_CR <> nil) then
l_CR.MakeFieldValue;
end;//l3Same(TagName, cSrc[l_Index])
end;
{$ENDIF Monitorings}
function TqaReq.Get_Multy: Boolean;
{-}
var
l_EdComboReq : IevComboReq;
begin
if not Supports(f_EditorReq, IevComboReq, l_EdComboReq) then
Assert(false);
Result := l_EdComboReq.IsMulty;
end;
function TqaReq.CanAdd: Boolean;
begin
Result := False;
end;
function TqaReq.CanOpenTree: Boolean;
begin
Result := False;
end;
function TqaReq.IsAttrValid: Boolean;
var
l_Exception: EaqExceptionClass;
l_Message: String;
l_Control: IevEditorControlField;
begin
Result := CheckFromControl(l_Exception, l_Message, l_Control);
end;
function TqaReq.CheckFromControl(out aExceptionClass : EaqExceptionClass;
out aMessage : String;
out aControl : IevEditorControlField): Boolean;
begin
aExceptionClass := nil;
aMessage := '';
aControl := nil;
Result := True;
end;
{ TqaCustomReqContext }
function TqaCustomReqContext.GetReqAsString(const aSeparator: Il3CString): Il3CString;
var
l_Index : Integer;
l_Count : Integer;
l_Field : IevEditorControlField;
begin
l_Count := f_EditorReq.FieldsCount - 1;
// Сформируем строку контекста из всех строк определенных пользователем
for l_Index := 0 to l_Count do
begin
l_Field := f_EditorReq.Fields[l_Index];
try
l_Field.Text := nsContextUtils.CheckContext(l_Field.Text);
Result := nsContextUtils.AddPhrase(Result, l_Field.Text);
if (l_Index < l_Count) then
Result := l3Cat([Result, aSeparator]);
finally
l_Field := nil;
end;//try..finally
end;//for l_Index
end;
procedure TqaCustomReqContext.Load;
var
l_Context : Il3CString;
l_Index : Integer;
l_Count : Integer;
l_ED : IevEditorControlField;
l_Phrases : IvcmStrings;
l_FieldCount : Integer;
begin
if LoadContextNew(f_MgrSearch.Query, Get_TagName, l_Context) then
begin
l_Phrases := nsContextUtils.ContextToPhrases(l_Context);
l_FieldCount := f_EditorReq.FieldsCount;
try
// Загрузим фразы
l_Count := l_Phrases.Count - 1;
for l_Index := 0 to l_Count do
begin
if (l_Index = 0) or (l_FieldCount > l_Index) then
with f_EditorReq do
begin
if (l_Index = 0) then
l_ED := FirstField
else
l_ED := Fields[l_Index];
try
l_ED.Text := l_Phrases.ItemC[l_Index];
finally
l_ED := nil;
end;//try..finally
end//with f_EditorReq
else
with f_EditorReq do
begin
AddField(nil);
l_ED := LastField;
try
l_ED.Text := l_Phrases.ItemC[l_Index];
finally
l_ED := nil;
end;//try..finally
end;//with f_EditorReq
end;//for l_Index
finally
l_Phrases := nil;
end;//try..finally
EditorReq.Group.Expanded := True;
end;//LoadContextNew
inherited;
end;
procedure TqaCustomReqContext.SaveReq;
begin
{$If not defined(Admin)}
SaveContextNew(f_MgrSearch.Query, Get_TagName, GetReqAsString(nil));
{$Else}
Assert(false);
{$IfEnd}
end;
procedure TqaReqAttribute.Load;
var
l_List : TqaAttrInfoList;
l_Index : Integer;
l_Node : INodeBase;
l_Count : Integer;
l_FieldCount : Integer;
l_FieldTree : IevEditorFieldWithTree;
l_ED : IevEditorControlField;
l_Tree : Il3SimpleTree;
begin
l_List := TqaAttrInfoList.Make;
try
{$IfNDef Admin}
LoadDictionaryNew(l_List, f_MgrSearch.Query, Get_TagName);
{$Else Admin}
Assert(false);
{$EndIf Admin}
l_Count := l_List.Count - 1;
l_FieldCount := f_EditorReq.FieldsCount;
Assert((l_FieldCount = 1) OR (l_Count >= l_FieldCount - 1));
// - http://mdp.garant.ru/pages/viewpage.action?pageId=227478809&focusedCommentId=227967127#comment-227967127
for l_Index := 0 to l_Count do
begin
{ Новый TasField }
if (l_Index = 0) then
l_ED := f_EditorReq.FirstField
else
if (l_FieldCount > l_Index) then
l_ED := f_EditorReq.Fields[l_Index]
else
begin
f_EditorReq.AddField(nil);
l_ED := f_EditorReq.LastField;
end;//l_FieldCount > l_Index
try
{ Введена маска }
if not l3IsNil(TqaAttrInfo(l_List[l_Index]).Mask) then
l_ED.Text := TqaAttrInfo(l_List[l_Index]).Mask
{ Выбран конкретный элемент }
else
with TqaAttrInfo(l_List[l_Index]) do
begin
if Supports(l_ED, IevEditorFieldWithTree, l_FieldTree) then
try
l_Tree := l_FieldTree.SourceTree;
if Supports(l_Tree, Il3ExpandedSimpleTree) then
begin
// преобразуем ноду в IQuery в ноду в дереве
// l_Node := GetTwinNode(l_Mgr.ComboBox.TreeStruct, NodeBase);
// !! обход бага в дереве, связанного с тем, что ноды в View и IQuery - разные
// поправить после правки бага в дереве
{$IFDEF NEW_TREE}
LoadField(l_FieldTree, Oper, NodeBase);
{$ELSE}
l_Node := GetTwinNode(TnsAttributeTreeStruct.Make(TagName, l_Tree.ShowRoot), NodeBase);
try
LoadField(l_FieldTree, Oper, l_Node);
finally
l_Node := nil;
end;//try..finally
{$ENDIF NEW_TREE}
end;//Supports(l_Tree, Il3ExpandedSimpleTree)
finally
l_FieldTree := nil;
end;//try..finally
end;//with TqaAttrInfo(l_List[l_Index])
finally
l_ED := nil;
end;//try..finally
end;//for l_Index
if (EditorReq.FieldsCount > 0) and IsSet(True) then
begin
EditorReq.Group.Expanded := True;
//EditorReq.Valid := True; //Проверяем загруженные данные
end;//EditorReq.FieldsCount > 0..
finally
vcmFree(l_List);
end;//try..finally
isAttrValid;
inherited;
end;
function TqaCustomReqContext.CanAdd: Boolean;
begin
Result := True;
end;
procedure TqaCustomReqContext.EnterPressed;
begin
f_MgrSearch.ExecQuery;
end;
function TqaCustomReqContext.AnalysString(const aValue : Il3CString;
out aRslt : Il3CString): Boolean;
var
l_ControlListner: InevControlListner;
begin
if Supports(EditorReq.QueryCard, InevControlListner, l_ControlListner)
and l_ControlListner.IsPasting then
begin
{$If not defined(Admin)}
aRslt := RepairContext6x(aValue);
{$Else}
Assert(false);
{$IfEnd}
Result := not l3Same(aRslt, aValue);
end//Supports(EditorReq.QueryCard, InevControlListner, l_ControlListner)
else
Result := inherited AnalysString(aValue, aRslt);
end;
constructor TqaCustomReqContext.Create(const aMgrSearch : IqaMgrSearch;
const aEditorReq : IevReq);
var
i : Integer;
l_FieldTree : IevEditorFieldWithTree;
begin
inherited;
for i := 0 to f_EditorReq.FieldsCount - 1 do
if Supports(f_EditorReq.Fields[i], IevEditorFieldWithTree, l_FieldTree) then
try
l_FieldTree.ComboStyle := ev_cbDropDown;
finally
l_FieldTree := nil;
end;//try..finally
end;
// start class TqaAttrInfo
constructor TqaAttrInfo.Create(const aOper : TLogicOperation = loNone;
const aNode : INodeBase = nil;
const aMask : Il3CString = nil);
{* - Создает класс и инициализирует значениями. }
begin
inherited Create;
f_Oper := aOper;
f_Mask := aMask;
f_Node := aNode;
end;
procedure TqaAttrInfo.Cleanup;
// override;
{-}
begin
f_Mask := nil;
f_Node := nil;
inherited;
end;
procedure TqaCustomReqContext.FillReqListAsString(
const aList: Il3StringsEx);
var
l_Index : Integer;
l_Count : Integer;
l_Field : IevEditorControlField;
begin
l_Count := f_EditorReq.FieldsCount - 1;
// Сформируем строку контекста из всех строк определенных пользователем
for l_Index := 0 to l_Count do
begin
l_Field := f_EditorReq.Fields[l_Index];
try
l_Field.Text := nsContextUtils.CheckContext(l_Field.Text);
if not l_Field.IsFieldEmpty then
aList.Add(l_Field.Text);
finally
l_Field := nil;
end;//try..finally
end;//for l_Index
end;
{ TqaReqAttribute }
function TqaReqAttribute.FieldLogicOperation(
const aValue: IevEditorFieldWithTree): TLogicOperation;
begin
Result := StateIndex2LogicState(aValue.LogicalState);
end;
procedure TqaReqAttribute.GetAttributesFromView(const aRoot : INodeBase);
var
l_Index : TLogicOperation;
l_Iterator : INodeIterator;
l_NodeBase : INodeBase;
l_Cursor : TCursor;
l_FieldCount : Integer;
//* - Количество выбранных элементов. Для удаления лишних полей.
l_Count : Integer;
l_EdFieldCount : Integer;
procedure AddField(const aNodeBase : INodeBase;
const aOperation : TLogicOperation);
var
l_Field : IevEditorFieldWithTree;
l_EdField : IevEditorControlField;
begin
// счетчик загруженных полей
Inc(l_FieldCount);
// используем существующее поле
if (l_FieldCount <= f_EditorReq.FieldsCount) then
f_EditorReq.Fields[l_FieldCount - 1].QueryInterface(IevEditorFieldWithTree, l_Field)
// новое поле
else
begin
l_EdField := f_EditorReq.AddField(nil);
Assert(Assigned(l_EdField), caFieldNotAdded);
try
l_EdField.QueryInterface(IevEditorFieldWithTree, l_Field);
finally
l_EdField := nil;
end;
end;
try
Assert(Assigned(l_Field), caFieldNotInitialized);
// покажем значение
LoadField(l_Field, aOperation, aNodeBase);
f_EditorReq.SetFocus(l_Field, True);
f_EditorReq.UpdateState(l_Field, nil);
finally
l_Field := nil;
end;
end;
begin
l_EdFieldCount := f_EditorReq.FieldsCount - 1;
l_FieldCount := 0;
// не удаляем значения, используем существующие поля ввода
l_Cursor := Screen.Cursor;
Screen.Cursor := crHourGlass;
try
f_MgrSearch.StartGettingFromView;
try
// первая операция
l_Index := Low(TLogicOperation);
// пройдем по списку итераторов
while True do
begin
if l_Index <> loNone then
begin
// итератор
l_Iterator := GetOperationIterator(Root, l_Index);
try
// узлы
l_Iterator.GetNext(l_NodeBase);
while Assigned(l_NodeBase) do
begin
try
// создадим поле ввода
AddField(l_NodeBase, l_Index);
finally
l_NodeBase := nil;
end;
l_Iterator.GetNext(l_NodeBase);
end;//while Assigned(l_NodeBase) do
finally
l_Iterator := nil;
end;//try..finally
end;
if l_Index < High(TLogicOperation) then
Inc(l_Index)
else
Break;
end;//while l_Index < Pred(aParams.Count) do
// удалим "лишние поля"
if l_FieldCount > 0 then
for l_Count := l_EdFieldCount downto l_FieldCount do
f_EditorReq.DeleteField(nil)
else
ReqClear;
EditorReq.UpdateState(EditorReq.FirstField, nil);
EditorReq.UpdateState(EditorReq.LastField, nil);
finally
f_MgrSearch.FinishGettingFromView;
end;//try..finally
DoOperateChanged;
// установим фокус в последнем элементе
f_EditorReq.SetFocus(f_EditorReq.LastField);
finally
Screen.Cursor := l_Cursor;
end;//Screen.Cursor := crHourGlass;
end;
procedure TqaReqAttribute.LoadField(const aValue: IevEditorFieldWithTree;
aLogicOper: TLogicOperation; const aNode: INodeBase);
var
l_State : Integer;
l_Node : Il3SimpleNode;
begin
l_State := Ord(aLogicOper) - 1; //loNone - не учитываем
l_Node := TnsINodeWrap.Make(aNode);
try
aValue.ShowNode(l_Node);
aValue.LogicalState := l_State;
finally
l_Node := nil;
end;
end;
procedure TqaReqAttribute.OpenSelectWindow;
begin
SetAttributesToView;
if DoShowTree(TagName, AdditionalFilter) then
f_MgrSearch.FinishOpenTree(Root, Self);
end;
function TqaReqAttribute.Root: INodeBase;
begin
Result := TnsAttributeTreeCacheNew.Instance.AttributeRoot[TagName];
end;
procedure TqaReqAttribute.SaveFieldToQuery(const aValue: IevEditorControlField);
var
l_DictNode : INodeBase;
l_Node : INodeBase;
l_ComboField : IevEditorFieldWithTree;
begin
if Supports(aValue, IevEditorFieldWithTree, l_ComboField) then
try
if l_ComboField.IsFieldEmpty then
l_ComboField.ClearText //Заточка для новой реакции на откатку, т.к. теперь
//ядро не ждет никакой нотификации, то может получиться так, что текст
//удален при нажатии "Ctrl + Z", а выбранный узел остался.
else
if evIsFieldSet(l_ComboField, false) then
begin
// Введено значение со звездочкой
if l_ComboField.IsAsterisk then
{$If not defined(Admin)}
SaveContextNew(f_MgrSearch.Query, Get_TagName, aValue.Text)
{$Else}
Assert(false)
{$IfEnd}
// Выбрано конкретное значение
else
if aValue.Valid and Supports(l_ComboField.Value, INodeBase, l_DictNode) then
begin
try
// !! обход бага в дереве, связанного с IQuery
// убрать после правки.
{$IFDEF NEW_TREE}
SaveAttributeNew(f_MgrSearch.Query, Get_TagName, FieldLogicOperation(l_ComboField), l_DictNode);
{$ELSE}
l_Node := GetTwinNode(TnsAttributeTreeStruct.Make(Get_TagName, False), l_DictNode);
if not Assigned(l_Node) then
l_Node := l_DictNode;
{$If not defined(Admin)}
SaveAttributeNew(f_MgrSearch.Query, Get_TagName, FieldLogicOperation(l_ComboField), l_Node);
{$Else}
Assert(false);
{$IfEnd}
{$ENDIF NEW_TREE}
finally
l_DictNode := nil;
end;//try..finally
end;//if (aValue.IsValid) and ...
end;//if evIsFieldSet(aValue) then
finally
l_ComboField := nil;
end;//try..finally
end;
procedure TqaReqAttribute.SaveReq;
var
l_Index : Integer;
begin
for l_Index := 0 to f_EditorReq.FieldsCount - 1 do
SaveFieldToQuery(f_EditorReq.Fields[l_Index]);
end;
procedure TqaReqAttribute.SetAttributesToView;
var
l_Index : Integer;
l_NodeBase : INodeBase;
l_Count : Integer;
l_Field : IevEditorFieldWithTree;
begin
// Сбросим флаги
DropAllOperations(Root);
Root.SetAllFlag(FM_SELECTION, False);
l_Count := f_EditorReq.FieldsCount - 1;
// Установим флаги
for l_Index := 0 to l_Count do
begin
if Supports(f_EditorReq.Fields[l_Index], IevEditorFieldWithTree, l_Field) then
try
if l_Field.IsFieldEmpty then
l_Field.ClearText;
if Supports(l_Field.Value, INodeBase, l_NodeBase) then
try
nsLogicOperationToFlags.SetLogicOperation(l_NodeBase,
FieldLogicOperation(l_Field));
finally
l_NodeBase := nil;
end;//try..finally
finally
l_Field := nil;
end;//try..finally
end;//for l_Index
end;
procedure TqaReqAttribute.AfterSetText(const aField: IevEditorControlField);
begin
Modified := True;
DoOperateChanged;
end;
function TqaReqAttribute.GetReqAsString(const aSeparator: Il3CString): Il3CString;
var
i, l_Count : Integer;
l_Field : IevEditorFieldWithTree;
l_Str : Il3CString;
l_SpetialWasAdded : Boolean;
l_SpetailLanguage : Boolean;
begin
Result := nil;
l_Count := f_EditorReq.FieldsCount - 1;
l_SpetialWasAdded := False;
l_SpetailLanguage := afw.Application.LocaleInfo.Language = afw_lngRussian;
if (l_Count >= 0) then
for i := 0 to l_Count do
begin
if Supports(f_EditorReq.Fields[i], IevEditorFieldWithTree, l_Field) then
try
if evIsFieldSet(l_Field, false) then
begin
if l_SpetailLanguage and
(l3Same(TagName, AT_ANNO_KIND)) then //Для более короткого названия в мониторингах.
begin
l_Str := nsConvertAnnoKind(l_Field.Text);
if not ((l3Same(l_Str, ccakRegionalLaw)) and
l_SpetialWasAdded) then
begin
if not l3IsNil(Result) then
Result := l3Cat([Result, aSeparator]);
Result := l3Cat([Result, l_Str]);
end;//not ((l3Same(l_Str.AsWStr, ccakRegionalLaw)) and
if (l3Same(l_Str, ccakRegionalLaw)) then
l_SpetialWasAdded := true;
end//l_SpetailLanguage..
else
begin
if not l3IsNil(Result) then
Result := l3Cat([Result, aSeparator]);
Result := l3Cat([Result, l_Field.Text]);
end;//l_SpetailLanguage..
end;//evIsFieldSet(l_Field)
finally
l_Field := nil;
end;//try..finally
end; //for i := 0 to ...*)
end;
function TqaReqAttribute.CanAdd: Boolean;
begin
Result := IsAttrValid;
end;
function TqaReqAttribute.CanOpenTree: Boolean;
begin
Result := True;
end;
procedure TqaReqAttribute.EnterPressed;
begin
if not Multy then
f_MgrSearch.ExecQuery
else
OpenSelectWindow;
end;
procedure TqaReqAttribute.DoOperateChanged;
begin
if not f_MgrSearch.GettingFromView then
inherited DoOperateChanged;
end;
// start class TqaReqStr
function TqaReqStr.Get_Multy: Boolean;
begin
Result := False;
end;
procedure TqaReqStr.Load;
var
l_Context : Il3CString;
begin
if LoadContextNew(f_MgrSearch.Query, Get_TagName, l_Context) then
f_EditorReq.FirstField.Text := l_Context;
end;
{$IFDEF Monitorings}
procedure TqaReqStr.MakeFieldValue;
function GetFieldValue: Il3CString;
var
i : Integer;
l_Req : IqaReq;
begin
for i := Low(cSrc) to High(cSrc) do
begin
l_Req := f_MgrSearch.FindAttr(nsCStr(cSrc[i]));
try
if (l_Req <> nil) then
begin
if (i > 0) and not l3IsNil(Result) then
Result := l3Cat([l3Cat(Result, '. '), l_Req.GetReqAsString(nsCStr('. '))])
else
Result := l_Req.GetReqAsString(nsCStr('. '));
end;//l_Req <> nil
finally
l_Req := nil;
end;//try..finally
end;//for i := 0 to ...
end;
var
l_Field : IevEditorControlField;
l_Value : Tl3PCharLen;
begin
if l3Same(TagName, cChangableReqName) then
begin
l_Field := f_EditorReq.FirstField;
try
l_Value := Tl3PCharLen(nsWStr(GetFieldValue));
if not l3IsNil(l_Value) then
begin
with l_Field.Para do
begin
if l3Same(PCharLenA[k2_tiText], f_EditorReq.Para.PCharLenA[k2_tiDefaultText]) then
begin
PCharLenA[k2_tiText] := l_Value;
Invalidate([nev_spExtent]);
l_Field.Req.UpdateState(l_Field, nil);
end;//l3Same..
end;//with l_Field.Para
f_EditorReq.Para.PCharLenA[k2_tiDefaultText] := l_Value;
end;//not l3IsNil(l_Value)
finally
l_Field := nil;
end;//try..finally
end;//l3Same(TagName, cChangableReqName)
end;
procedure TqaReqStr.ReqClear;
begin
if l3Same(TagName, cChangableReqName) then
f_EditorReq.Para.PCharLenA[k2_tiDefaultText] := Tl3PCharLen(nsWStr(''));
inherited ReqClear;
end;
{$ENDIF Monitorings}
// start class TqaReqDate
function TqaReqDate.BeforeGroupCollapse: Boolean;
begin
Result := IsAttrValid;
end;
function TqaReqDate.CanOpenTree: Boolean;
begin
Result := False;
end;
procedure TqaReqDate.CheckAttr;
var
l_DateField: IevEditorCalendarField;
l_Exception: EaqExceptionClass;
l_Message: String;
l_Control: IevEditorControlField;
begin
inherited;
if not CheckFromControl(l_Exception, l_Message, l_Control) then
begin
(l_Control as IevEditorCalendarField).ClearField;
raise l_Exception.Create(l_Control, l_Message);
end;
if Supports(EditorReq.FirstField, IevEditorCalendarField, l_DateField) then
begin
// Удалим если введена не верная дата
if not l_DateField.IsFieldEmpty and not l_DateField.GetOtherField.IsFieldEmpty then
if Floor(l_DateField.aDate) > Floor(l_DateField.GetOtherField.aDate) then
raise EqaInvalidValue.CreateFmt(l_DateField, vcmConstString(str_StartDateMoreEnd),
[DateToStr(l_DateField.aDate), DateToStr(l_DateField.GetOtherField.aDate)]);
end;
end;
function TqaReqDate.CheckFromControl(out aExceptionClass : EaqExceptionClass;
out aMessage : String;
out aControl : IevEditorControlField): Boolean;
procedure CheckDate(const aDateField: IevEditorCalendarField);
{* - проверяет правильность даты и выводит сообщение. }
begin
if not aDateField.IsBlank and not aDateField.Valid then
begin
Result := False;
aExceptionClass := EqaInvalidValue;
aMessage := Format(vcmConstString(str_InvalidDate), [nsEStr(aDateField.text)]);
aControl := aDateField;
end;
end;
var
l_DateField: IevEditorCalendarField;
begin
Result := inherited CheckFromControl(aExceptionClass, aMessage, aControl);
if Result and Supports(EditorReq.FirstField, IevEditorCalendarField, l_DateField) then
begin
CheckDate(l_DateField);
if Result then
CheckDate(l_DateField.GetOtherField);
end;
end;
procedure TqaReqDate.EnterPressed;
begin
HyperLinkClick;
end;
function TqaReqDate.GetHint4Button(
const aValue: IevEditorControlButton): Il3CString;
begin
Result := inherited GetHint4Button(aValue);
if (aValue.GetButtonType = ev_btDelete) then
Result := vcmCStr(str_HintBtnDeleteDate);
end;
function TqaReqDate.Get_EndDate: System.TDateTime;
var
l_CalReq: IevDatesReq;
begin
if Supports(f_EditorReq, IevDatesReq, l_CalReq) then
try
Result := l_CalReq.EndDate;
finally
l_CalReq := nil;
end
else
Result := NullDate;
end;
function TqaReqDate.Get_Multy: Boolean;
begin
Result := True;
end;
function TqaReqDate.Get_StartDate: System.TDateTime;
var
l_CalReq: IevDatesReq;
begin
if Supports(f_EditorReq, IevDatesReq, l_CalReq) then
try
Result := l_CalReq.StartDate;
finally
l_CalReq := nil;
end
else
Result := NullDate;
end;
procedure TqaReqDate.HyperLinkClick;
begin
f_MgrSearch.DateQuery(Self);
end;
procedure TqaReqDate.InitFields;
var
l_Field : IevEditorControlField;
l_CT : Tl3PCharLen;
l_Cal: IevEditorCalendarField;
procedure lp_Init(const aField: IevEditorControlField);
begin
if (aField <> nil) then
begin
if l3IsNil(aField.Para.PCharLenA[k2_tiText]) then
aField.Para.PCharLenA[k2_tiText] := l_CT
else
if not l3IsNil(l_CT) then
aField.Para.PCharLenA[k2_tiText] := l_CT;
end;//l_Field <> nil
end;
begin
inherited;
if not f_EditorReq.Para.HasSubAtom(k2_tiDefaultText) then
//Обновление масок текста (могут не соотвествовать региональным настройкам).
begin
l_CT := Tl3PCharLen(nsWStr(evMakeDateMaskText));
l_Field := f_EditorReq.FirstField;
if (l_Field <> nil) then
begin
lp_Init(l_Field);
if Supports(l_Field, IevEditorCalendarField, l_Cal) then
lp_Init(l_Cal.GetOtherField);
end;//l_Field <> nil
f_EditorReq.Para.PCharLenA[k2_tiDefaultText] := l_CT;
end;//not f_EditorReq.Para.HasSubAtom(k2_tiDefaultText)
end;
procedure TqaReqDate.Load;
var
l_StartDate : System.TDateTime;
l_EndDate : System.TDateTime;
begin
{$If not defined(Admin)}
LoadDateNew(f_MgrSearch.Query, Get_TagName, l_StartDate, l_EndDate);
{$Else}
Assert(false);
{$IfEnd}
if (l_StartDate <> NullDate) or (l_EndDate <> NullDate) then
begin
f_EditorReq.Group.Expanded := True;
EndDate := l_EndDate;
StartDate := l_StartDate;
end;
inherited;
end;
procedure TqaReqDate.OpenSelectWindow;
begin
HyperLinkClick;
end;
procedure TqaReqDate.ReqClear;
begin
f_EditorReq.FirstField.ClearText;
end;
procedure TqaReqDate.SaveReq;
begin
{$If not defined(Admin)}
Assert(f_EditorReq.FirstField.Enabled = f_EditorReq.LastField.Enabled);
if f_EditorReq.FirstField.Enabled AND f_EditorReq.LastField.Enabled then
SaveDateNewEx(f_MgrSearch.Query, Get_TagName, StartDate, EndDate);
{$Else}
Assert(false);
{$IfEnd}
end;
procedure TqaReqDate.Set_EndDate(const Value: System.TDateTime);
var
l_CalReq: IevDatesReq;
begin
if Supports(f_EditorReq, IevDatesReq, l_CalReq) then
try
l_CalReq.EndDate := Value;
finally
l_CalReq := nil;
end;
end;
procedure TqaReqDate.Set_StartDate(const Value: System.TDateTime);
var
l_CalReq: IevDatesReq;
begin
if Supports(f_EditorReq, IevDatesReq, l_CalReq) then
try
l_CalReq.StartDate := Value;
finally
l_CalReq := nil;
end;
end;
{ TqaEventReq }
procedure TqaEventReq.AfterSetText(const aField: IevEditorControlField);
begin
end;
function TqaEventReq.AnalysString(const aValue : Il3CString;
out aRslt : Il3CString): Boolean;
{-}
begin
Result := false;
end;
function TqaEventReq.CheckValue(const aField: IevEditorControlField): Boolean;
begin
Result := IsAttrValid;
end;
procedure TqaEventReq.EnterPressed;
begin
end;
function TqaEventReq.GetHint(const aValue: IevEditorControl): Il3CString;
var
l_Button : IevEditorControlButton;
begin
if Supports(aValue, IevEditorControlButton, l_Button) then
try
Result := GetHint4Button(l_Button);
finally
l_Button := nil;
end
else
Result := nil;
end;
function TqaEventReq.pm_GetAdditionalFilter: TnsFilterType;
begin
Result := GetAdditionalFilter(TagName, f_MgrSearch.QueryType);
end;
function TqaEventReq.GetHint4Button(const aValue: IevEditorControlButton): Il3CString;
var
l_PictBTN : IevEditorStateButton;
begin
case aValue.GetButtonType of
ev_btLogical:
begin
if (l3BitCountF(EditorReq.Para.IntA[k2_tiOperations]) = 1) then
Result := vcmCStr(str_HintNotChangedOperation)
else
if Supports(aValue, IevEditorStateButton, l_PictBTN) then
try
case StateIndex2LogicState(l_PictBTN.GetStateIndex) of
loOr :
Result := vcmCStr(str_HintOrOperation);
loAnd :
Result := vcmCStr(str_HintAndOperation);
loNot :
Result := vcmCStr(str_HintNotOperation);
else
Result := vcmCStr(str_HintChangeOperation);
end;//case StateIndex2LogicState(l_PictBTN.GetStateIndex)
finally
l_PictBTN := nil;
end;//try..finally
end;//l3BitCountF(EditorReq.Para.IntA[k2_tiOperations]) = 1
ev_btAdd :
Result := vcmCStr(str_HintBtnCreateAttr);
ev_btDelete :
Result := vcmCStr(str_HintBtnDeleteAttr);
end;//case aValue.GetButtonType
end;
function TqaEventReq.GetImage(Index: Integer;
var aImages: InevImageList): Integer;
{$IfNDef Admin}
var
l_Node: Il3SimpleNode;
l_ComboReq: IevComboReq;
{$EndIf Admin}
begin
Result := -1;
{$IfNDef Admin}
aImages := Tl3ImageList.Make(nsSearchRes.SearchItemsImageList);
if Supports(f_EditorReq, IevComboReq, l_ComboReq) then
try
l_Node := l_ComboReq.GetNode(Index);
if l_Node <> nil then
begin
try
// Папка
if l_Node.HasChild then
Result := siilFolderStart
// Элемент
else
Result := siilSelectedElement;
finally
l_Node := nil;
end;//try..finally
end;//l_Node <> nil
finally
l_ComboReq := nil;
end;//try..finally
{$EndIf Admin}
end;
procedure TqaEventReq.HyperLinkClick;
begin
OpenSelectWindow;
end;
function TqaEventReq.StateIndex2LogicState(aValue: Integer): TLogicOperation;
{-}
begin
if aValue < 0 then
Result := loNone
else
Result := TLogicOperation(aValue + 1)
end;
procedure TqaEventReq.TextChange;
{-}
begin
Modified := True;
end;
{ TqaReqNum }
procedure TqaReqNum.InitFields;
var
l_Combo: IevEditorFieldWithTree;
begin
inherited;
if Supports(f_EditorReq.FirstField, IevEditorFieldWithTree, l_Combo) then
try
// Установим символ звездочки
l_Combo.Asterisk := '*';
finally
l_Combo := nil;
end;//try..finally
end;
{ TqaHistory }
procedure TqaHistory.Cleanup;
begin
f_Filter := nil;
f_Query := nil;
f_DataReset := False;
f_ConsultationSened := False;
inherited;
end;
procedure TqaHistory.FinishDataUpdate;
begin
inherited FinishDataUpdate;
f_DataReset := True;
end;
function TqaHistory.GetConsultationSended: Boolean;
begin
Result := f_ConsultationSened;
end;
function TqaHistory.GetDataReset: Boolean;
begin
Result := f_DataReset;
end;
function TqaHistory.GetFilter: INode;
begin
Result := f_Filter;
end;
function TqaHistory.GetQuery: IQuery;
begin
Result := f_Query;
end;
procedure TqaHistory.pm_SetQuery(const aValue: IQuery);
begin
if f_Query <> nil then
f_Query := nil;
f_Query := aValue;
end;
procedure TqaHistory.SetConsultationSended(const aValue: Boolean);
begin
f_ConsultationSened := aValue;
end;
procedure TqaHistory.SetFilter(const aNode: INode);
begin
f_Filter := aNode;
end;
{ TqaReqComboField }
procedure TqaReqComboField.CheckAttr;
var
l_FirstDuplicate : IevEditorControlField;
l_Exception : EaqExceptionClass;
l_Message : string;
begin
inherited;
if not CheckFromControl(l_Exception, l_Message, l_FirstDuplicate) then
raise l_Exception.Create(l_FirstDuplicate, l_Message);
end;
function TqaReqComboField.CheckFromControl(out aExceptionClass : EaqExceptionClass;
out aMessage : String;
out aControl : IevEditorControlField): Boolean;
var
l_Index : Integer;
l_SList : IvcmStrings;
l_CheckEditor: IevEditorControlField;
l_CheckValue: Il3CString;
begin
Result := inherited CheckFromControl(aExceptionClass, aMessage, aControl);
if Result then
begin
// Проверим уникальность значений
l_SList := TvcmStringList.Make;
try
for l_Index := 0 to f_EditorReq.FieldsCount - 1 do
begin
l_CheckEditor := f_EditorReq.Fields[l_Index];
l_CheckValue := l_CheckEditor.Text;
l_CheckEditor.ErrorColor := not l3IsNil(l_CheckValue) and (l_SList.IndexOf(l_CheckValue) <> -1);
if l_CheckEditor.ErrorColor then
begin
if aControl = nil then
aControl := l_CheckEditor;
end
else
l_SList.Add(l_CheckValue);
end;//for l_Index := 0
finally
l_SList := nil;
end;//try..finally
if Assigned(aControl) then
begin
Result := False;
aExceptionClass := EqaDuplicateValue;
aMessage := Format(vcmConstString(str_DuplicateValue), [nsEStr(aControl.Text)]);
end;//Assigned(aControl)
end;//Result
end;
procedure TqaReqComboField.ReqClear;
var
l_ComboReq : IevComboReq;
l_Req : IevReq;
l_TreeField : IevEditorFieldWithTree;
begin
l_Req := f_EditorReq;
try
while l_Req.FieldsCount > 1 do
l_Req.DeleteField(nil, nil, true);
// ^ http://mdp.garant.ru/pages/viewpage.action?pageId=96483355&focusedCommentId=109511365#comment-109511365
if Supports(l_Req.LastField, IevEditorFieldWithTree, l_TreeField) then
try
if evIsFieldSet(l_TreeField, True) then
begin
l_TreeField.ClearText;
//l_Req.SetFocus(l_TreeField);
end;//evIsFieldSet(l_TreeField, True)
finally
l_TreeField := nil;
end;
if Supports(l_Req, IevComboReq, l_ComboReq) then
try
l_ComboReq.ClearLogicValue;
finally
l_ComboReq := nil;
end;
finally
l_Req := nil;
end;
end;
// start class TqaCommonStrReq
procedure TqaCommonStrReq.TextChange;
begin
Modified := True;
end;
procedure TqaCommonStrReq.ReqClear;
begin
EditorReq.FirstField.ClearText;
end;
procedure TqaCommonStrReq.SaveReq;
var
l_Value : Il3CString;
begin
l_Value := nsContextUtils.CheckContext(f_EditorReq.FirstField.Text);
{$If not defined(Admin)}
SaveContextNew(f_MgrSearch.Query, Get_TagName, l_Value);
{$ELse}
Assert(false);
{$IfEnd}
end;
procedure TqaCommonStrReq.Load;
var
l_Context : Il3CString;
begin
if LoadContextNew(f_MgrSearch.Query, Get_TagName, l_Context) then
f_EditorReq.FirstField.Text := l_Context;
end;
{ TqaDateReqDataHolder }
constructor TqaDateReqDataHolder.Create(const aReq: IqaDateReq);
var
l_Req: IqaReq;
begin
inherited Create;
StartDate := aReq.StartDate;
EndDate := aReq.EndDate;
IsOk := False;
if Supports(aReq, IqaReq, l_Req) then
f_ReqCaption := l_Req.TagCaption;
end;
procedure TqaDateReqDataHolder.Cleanup;
//override;
{-}
begin
f_ReqCaption := nil;
inherited;
end;
function TqaDateReqDataHolder.Get_EndDate: System.TDateTime;
begin
Result := f_EndDate;
end;
function TqaDateReqDataHolder.Get_IsOk: Boolean;
begin
Result := f_IsOk;
end;
function TqaDateReqDataHolder.Get_ReqCaption: Il3CString;
begin
Result := f_ReqCaption;
end;
function TqaDateReqDataHolder.Get_StartDate: System.TDateTime;
begin
Result := f_StartDate;
end;
function TqaDateReqDataHolder.IsStartDateEmpty: Boolean;
begin
Result := StartDate = NullDate;
end;
function TqaDateReqDataHolder.IsEndDateEmpty: Boolean;
begin
Result := EndDate = NullDate;
end;
class function TqaDateReqDataHolder.Make(const aReq: IqaDateReq): IqaDateReqDataHolder;
var
l_Inst: TqaDateReqDataHolder;
begin
if Assigned(aReq) then
begin
l_Inst := Create(aReq);
try
Result := l_Inst;
finally
vcmFree(l_Inst)
end;
end
else
Result := nil;
end;
procedure TqaDateReqDataHolder.Set_EndDate(const Value: System.TDateTime);
begin
F_EndDate := Value;
end;
procedure TqaDateReqDataHolder.Set_IsOk(const Value: Boolean);
begin
f_IsOk := Value;
end;
procedure TqaDateReqDataHolder.Set_StartDate(const Value: System.TDateTime);
begin
f_StartDate := Value;
end;
{ TqaReqPhone }
function TqaReqPhone.CanOpenTree: Boolean;
begin
Result := False;
end;
function TqaReqPhone.Get_Code: Il3CString;
var
l_PhoneReq: IevPhoneReq;
begin
if Supports(f_EditorReq, IevPhoneReq, l_PhoneReq) then
try
Result := l_PhoneReq.Code;
finally
l_PhoneReq := nil;
end//try..finally
else
Result := nil;
end;
function TqaReqPhone.Get_Multy: Boolean;
begin
Result := True;
end;
function TqaReqPhone.Get_Number: Il3CString;
var
l_PhoneReq: IevPhoneReq;
begin
if Supports(f_EditorReq, IevPhoneReq, l_PhoneReq) then
try
Result := l_PhoneReq.Number;
finally
l_PhoneReq := nil;
end//try..finally
else
Result := nil;
end;
procedure TqaReqPhone.Load;
var
l_Code : Il3CString;
l_Number : Il3CString;
begin
LoadPhone(f_MgrSearch.Query, nsWStr(Get_TagName), l_Code, l_Number);
Code := l_Code;
Number := l_Number;
if not l3IsNil(l_Code) or not l3IsNil(l_Number) then
f_EditorReq.Group.Expanded := True;
inherited;
end;
procedure TqaReqPhone.ReqClear;
begin
Code := nil;
Number := nil;
end;
procedure TqaReqPhone.SaveReq;
begin
{$If not defined(Admin)}
SavePhone(f_MgrSearch.Query, Get_TagName, Code, Number);
{$Else}
Assert(false);
{$IfEnd}
end;
procedure TqaReqPhone.Set_Code(const Value: Il3CString);
var
l_PhoneReq: IevPhoneReq;
begin
if Supports(f_EditorReq, IevPhoneReq, l_PhoneReq) then
try
l_PhoneReq.Code := Value;
finally
l_PhoneReq := nil;
end;//try..finally
end;
procedure TqaReqPhone.Set_Number(const Value: Il3CString);
var
l_PhoneReq: IevPhoneReq;
begin
if Supports(f_EditorReq, IevPhoneReq, l_PhoneReq) then
try
l_PhoneReq.Number := Value;
finally
l_PhoneReq := nil;
end;//try..finally
end;
{ TqaReqEMail }
procedure TqaReqEMail.CheckAttr;
var
l_Exception : EaqExceptionClass;
l_Message : String;
l_Control : IevEditorControlField;
begin
inherited;
if not CheckFromControl(l_Exception, l_Message, l_Control) then
raise l_Exception.Create(l_COntrol, l_Message);
end;
function TqaReqEMail.CheckFromControl(out aExceptionClass : EaqExceptionClass;
out aMessage : String;
out aControl : IevEditorControlField): Boolean;
var
l_Emails: Tl3CStringArray;
l_Correct: Boolean;
I: Integer;
begin
Result := inherited CheckFromControl(aExceptionClass, aMessage, aControl);
l_Correct := False;
l_Emails := l3Split(f_EditorReq.FirstField.Text, ',');
for I := 0 to Length(l_Emails) - 1 do
begin
l_Correct := nsEmailVerify.Verify(l3Trim(l_Emails[I]));
if not l_Correct then
Break;
end;
if Result and IsSet(False) and not l_Correct then
begin
Result := False;
aExceptionClass := EqaInvalidValue;
aMessage := vcmConstString(str_WrongEMail);
aControl := f_EditorReq.FirstField;
end;
end;
{$If not Defined(Admin) AND not Defined(Monitorings)}
procedure TqaMgrSearch.Correct(const aCorrectedContext: Il3StringsEx;
const aMistakesList: Il3StringsEx);
var
l_ContextsIdx: Integer;
function DoCorrectContext(const aReq: IqaReq): Boolean;
function lp_HasErrorWords(const aContext: Il3CString): Boolean;
var
l_IDX: Integer;
begin//lp_HasErrorWords
Result := False;
if Assigned(aMistakesList) then
for l_IDX := 0 to aMistakesList.Count - 1 do
if l3Pos(l3Upper(aContext), l3Upper(aMistakesList.ItemC[l_IDX])) > l3NotFound then
begin
Result := True;
Exit;
end;//l3Pos..
end;//lp_HasErrorWords
var
l_Idx: Integer;
l_Text : Il3CString;
l_Index : Integer;
l_Para : InevPara;
l_DummyText : Il3CString;
const
l_Opt = [ev_soGlobal, ev_soUseInternalCursor, ev_soReplaceAll, ev_soNoProgress];
begin//DoCorrectContext
Result := true;
if Supports(aReq, IqaMorphoReq) then
begin
for l_IDX := 0 to aReq.EditorReq.FieldsCount - 1 do
if not aReq.EditorReq.Fields[l_IDX].IsFieldEmpty then
begin
if (l_ContextsIdx < aCorrectedContext.Count) then // http://mdp.garant.ru/pages/viewpage.action?pageId=326773154
begin
if not l3Same(aReq.EditorReq.Fields[l_IDX].Text, aCorrectedContext[l_ContextsIdx]) then
aReq.EditorReq.Fields[l_IDX].Text := aCorrectedContext[l_ContextsIdx];
end
else
aReq.EditorReq.Fields[l_IDX].Text := l3CStr(''); // http://mdp.garant.ru/pages/viewpage.action?pageId=326773154
if (f_FirstErrorContextReq = nil) then
begin
if lp_HasErrorWords(aReq.EditorReq.Fields[l_IDX].Text) then
f_FirstErrorContextReq := aReq.EditorReq.Fields[l_IDX];
end;//f_FirstErrorContextReq = nil
l_Para := aReq.EditorReq.Fields[l_IDX].Para;
with l_Para.Attr[k2_tiSegments] do
if IsValid then
begin
if rAtomEx([k2_tiChildren, k2_tiHandle, ev_slMistakes], @l_Index).IsValid then
DeleteChild(l_Index);
end;//IsValid
if Assigned(aMistakesList) then
begin
for l_Index := 0 to Pred(aMistakesList.Count) do
begin
evReplaceInPara(l_Para,
TevStrictWordSearcher.Make(l3Str(aMistakesList[l_Index]), l_Opt),
TevStyleReplacer.MakeForStyleID(ev_saMistake, l_Opt));
end;//for l_Index
end;//l_Words <> nil
Inc(l_ContextsIdx);
if (l_ContextsIdx >= aCorrectedContext.Count) then
Result := false;
end;//not aReq.EditorReq.Fields[l_IDX].IsFieldEmpty
end;//Supports(aReq, IqaMorphoReq)
end;//DoCorrectContext
begin
l_ContextsIdx := 0;
IterateAttrsF(l3L2FA(@DoCorrectContext));
end;
{$IfEnd}
{$If not (defined(Monitorings) or defined(Admin))}
procedure TqaMgrSearch.CheckMorpho;
{-}
var
l_TotalContext: Il3StringsEx;
function DoCollectContext(const aReq: IqaReq): Boolean;
var
l_Req: IqaMorphoReq;
l_Context: Il3CString;
begin
Result := true;
if Supports(aReq, IqaMorphoReq, l_Req) then
l_Req.FillReqListAsString(l_TotalContext);
end;
begin
l_TotalContext := TvcmStringList.Make;
IterateAttrsF(l3L2FA(@DoCollectContext));
f_FirstErrorContextReq := nil;
try
{$If not (defined(Monitorings) or defined(Admin))}
if bsUtils.bsCorrectMistakes(l_TotalContext, QueryType in c_InpharmSearches, Self) and Assigned(f_FirstErrorContextReq) then
raise EqaSilentAbort.Create(f_FirstErrorContextReq,'');
{$Else}
Assert(false);
{$IfEnd}
finally
f_FirstErrorContextReq := nil;
end;
end;
{$IfEnd}
procedure TqaMgrSearch.ClearContextMistakes;
function DoClearMistakes(const aReq: IqaReq): Boolean;
var
l_Idx: Integer;
l_Index : Integer;
l_Para : InevPara;
begin
Result := true;
if Supports(aReq, IqaMorphoReq) then
begin
for l_IDX := 0 to aReq.EditorReq.FieldsCount - 1 do
begin
l_Para := aReq.EditorReq.Fields[l_IDX].Para;
with l_Para.Attr[k2_tiSegments] do
if IsValid then
begin
if rAtomEx([k2_tiChildren, k2_tiHandle, ev_slMistakes], @l_Index).IsValid then
begin
DeleteChild(l_Index);
evSegments_ClearSuper(l_Para, nil);
// - по-хорошему это надо в ChildDeleted, но туда пока достучаться не можем
end;//rAtomEx([k2_tiChildren, k2_tiHandle, ev_slMistakes], @l_Index).IsValid
end;//IsValid
end;
end;
end;
begin
IterateAttrsF(l3L2FA(@DoClearMistakes));
end;
{ TqaReqContext }
procedure TqaReqContext.CheckAttr;
procedure CheckContext(const aComboBox : IevEditorControlField);
var
l_Pos : Integer;
l_ErrMessage : Il3CString;
begin//CheckContext
aComboBox.Text := nsContextUtils.CheckContext(aComboBox.Text);
if not l3IsNil(aComboBox.Text) then
begin
{$If not defined(Admin)}
l_Pos := CheckContext6x(aComboBox.Text, l_ErrMessage);
{$Else}
Assert(false);
{$IfEnd}
if (l_Pos >= 0) then
raise EqaInvalidValue.Create(aComboBox, nsEStr(l_ErrMessage));
end;//not l3IsNil(aComboBox.Text)
end;//CheckContext
var
l_Index : Integer;
l_Req : IevComboReq;
begin
inherited;
if Supports(f_EditorReq, IevComboReq, l_Req) and l_Req.IsContext then
begin
(* Проверим значения в полях контекста. *)
for l_Index := 0 to f_EditorReq.FieldsCount - 1 do
CheckContext(f_EditorReq.Fields[l_Index]);
end;//Supports(f_EditorReq, IevComboReq, l_Req) and l_Req.IsContext
end;
function TqaMgrSearch.GetPromptTreeFromAdapter: Il3SimpleTree;
begin
{ if QueryType in c_InpharmSearches then
Result := nil
else
Result := BaseSearchPromptTree;}
Result := nil; // К-104432064
end;
procedure TqaMgrSearch.NotifyContextWrong;
begin
nsBeepWrongContext;
end;
end.
|
unit RootUnit;
interface
uses
Pkg.Json.DTO, System.Generics.Collections, REST.Json.Types;
{$M+}
type
TOutputs = class(TJsonDTO)
private
[JSONName('addresses')]
FAddressesArray: TArray<string>;
[JSONMarshalled(False)]
FAddresses: TList<string>;
FScript: string;
[JSONName('script_type')]
FScriptType: string;
[JSONName('spent_by')]
FSpentBy: string;
FValue: Int64;
function GetAddresses: TList<string>;
protected
function GetAsJson: string; override;
published
property Addresses: TList<string> read GetAddresses;
property Script: string read FScript write FScript;
property ScriptType: string read FScriptType write FScriptType;
property SpentBy: string read FSpentBy write FSpentBy;
property Value: Int64 read FValue write FValue;
public
destructor Destroy; override;
end;
TInputs = class(TJsonDTO)
private
[JSONName('addresses')]
FAddressesArray: TArray<string>;
[JSONMarshalled(False)]
FAddresses: TList<string>;
FAge: Integer;
[JSONName('output_index')]
FOutputIndex: Integer;
[JSONName('output_value')]
FOutputValue: Integer;
[JSONName('prev_hash')]
FPrevHash: string;
FScript: string;
[JSONName('script_type')]
FScriptType: string;
FSequence: Int64;
function GetAddresses: TList<string>;
protected
function GetAsJson: string; override;
published
property Addresses: TList<string> read GetAddresses;
property Age: Integer read FAge write FAge;
property OutputIndex: Integer read FOutputIndex write FOutputIndex;
property OutputValue: Integer read FOutputValue write FOutputValue;
property PrevHash: string read FPrevHash write FPrevHash;
property Script: string read FScript write FScript;
property ScriptType: string read FScriptType write FScriptType;
property Sequence: Int64 read FSequence write FSequence;
public
destructor Destroy; override;
end;
TRoot = class(TJsonDTO)
private
[JSONName('addresses')]
FAddressesArray: TArray<string>;
[JSONMarshalled(False)]
FAddresses: TList<string>;
[JSONName('block_hash')]
FBlockHash: string;
[JSONName('block_height')]
FBlockHeight: Integer;
[JSONName('block_index')]
FBlockIndex: Integer;
FConfidence: Integer;
FConfirmations: Integer;
FConfirmed: TDateTime;
[JSONName('double_spend')]
FDoubleSpend: Boolean;
FFees: Integer;
FHash: string;
[JSONName('inputs'), JSONMarshalled(False)]
FInputsArray: TArray<TInputs>;
[GenericListReflect]
FInputs: TObjectList<TInputs>;
[JSONName('outputs'), JSONMarshalled(False)]
FOutputsArray: TArray<TOutputs>;
[GenericListReflect]
FOutputs: TObjectList<TOutputs>;
FPreference: string;
FReceived: TDateTime;
FSize: Integer;
FTotal: Int64;
FVer: Integer;
[JSONName('vin_sz')]
FVinSz: Integer;
[JSONName('vout_sz')]
FVoutSz: Integer;
FVsize: Integer;
function GetAddresses: TList<string>;
function GetInputs: TObjectList<TInputs>;
function GetOutputs: TObjectList<TOutputs>;
protected
function GetAsJson: string; override;
published
property Addresses: TList<string> read GetAddresses;
property BlockHash: string read FBlockHash write FBlockHash;
property BlockHeight: Integer read FBlockHeight write FBlockHeight;
property BlockIndex: Integer read FBlockIndex write FBlockIndex;
property Confidence: Integer read FConfidence write FConfidence;
property Confirmations: Integer read FConfirmations write FConfirmations;
property Confirmed: TDateTime read FConfirmed write FConfirmed;
property DoubleSpend: Boolean read FDoubleSpend write FDoubleSpend;
property Fees: Integer read FFees write FFees;
property Hash: string read FHash write FHash;
property Inputs: TObjectList<TInputs> read GetInputs;
property Outputs: TObjectList<TOutputs> read GetOutputs;
property Preference: string read FPreference write FPreference;
property Received: TDateTime read FReceived write FReceived;
property Size: Integer read FSize write FSize;
property Total: Int64 read FTotal write FTotal;
property Ver: Integer read FVer write FVer;
property VinSz: Integer read FVinSz write FVinSz;
property VoutSz: Integer read FVoutSz write FVoutSz;
property Vsize: Integer read FVsize write FVsize;
public
destructor Destroy; override;
end;
implementation
{ TOutputs }
destructor TOutputs.Destroy;
begin
GetAddresses.Free;
inherited;
end;
function TOutputs.GetAddresses: TList<string>;
begin
Result := List<string>(FAddresses, FAddressesArray);
end;
function TOutputs.GetAsJson: string;
begin
RefreshArray<string>(FAddresses, FAddressesArray);
Result := inherited;
end;
{ TInputs }
destructor TInputs.Destroy;
begin
GetAddresses.Free;
inherited;
end;
function TInputs.GetAddresses: TList<string>;
begin
Result := List<string>(FAddresses, FAddressesArray);
end;
function TInputs.GetAsJson: string;
begin
RefreshArray<string>(FAddresses, FAddressesArray);
Result := inherited;
end;
{ TRoot }
destructor TRoot.Destroy;
begin
GetAddresses.Free;
GetInputs.Free;
GetOutputs.Free;
inherited;
end;
function TRoot.GetAddresses: TList<string>;
begin
Result := List<string>(FAddresses, FAddressesArray);
end;
function TRoot.GetInputs: TObjectList<TInputs>;
begin
Result := ObjectList<TInputs>(FInputs, FInputsArray);
end;
function TRoot.GetOutputs: TObjectList<TOutputs>;
begin
Result := ObjectList<TOutputs>(FOutputs, FOutputsArray);
end;
function TRoot.GetAsJson: string;
begin
RefreshArray<string>(FAddresses, FAddressesArray);
RefreshArray<TInputs>(FInputs, FInputsArray);
RefreshArray<TOutputs>(FOutputs, FOutputsArray);
Result := inherited;
end;
end.
|
{$MODE OBJFPC}
program Assignment;
const
InputFile = 'ASSIGN.INP';
OutputFile = 'ASSIGN.OUT';
maxN = 10000;
maxM = 100000;
maxW = 100000;
infty = maxN * maxW;
type
TEdge = record
x, y, w: Integer;
end;
THeap = record
nItems: Integer;
items: array[1..maxN] of Integer;
pos: array[1..maxN] of Integer;
end;
var
n, m: Integer;
e: array[1..maxM] of TEdge;
link: array[1..maxM] of Integer;
head: array[1..maxN] of Integer;
f, g: array[1..maxN] of Integer;
d: array[1..maxN] of Integer;
match: array[1..maxN] of Integer;
trace: array[1..maxN] of Integer;
z: array[1..maxN] of Integer;
nz: Integer;
list: array[1..maxN] of Integer;
nlist: Integer;
Heap: THeap;
cost: Integer;
procedure Enter;
var
f: TextFile;
i: Integer;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, n, m);
for i := 1 to m do
with e[i] do ReadLn(f, x, y, w);
finally
CloseFile(f);
end;
end;
function wp(const e: TEdge): Integer;
begin
with e do
Result := w - f[x] - g[y];
end;
procedure Init;
var
i, j, k: Integer;
begin
FillDWord(head[1], n, 0);
for k := m downto 1 do
with e[k] do
begin
link[k] := head[x];
head[x] := k;
end;
FillDWord(f[1], n, infty);
for k := 1 to m do
with e[k] do
if f[x] > w then f[x] := w;
FillDWord(g[1], n, infty);
for k := 1 to m do
with e[k] do
if g[y] > w - f[x] then g[y] := w - f[x];
//Greedy
FillDWord(match[1], n, 0);
nlist := 0;
for i := 1 to n do
begin
j := 0;
k := head[i];
while k <> 0 do
begin
if (wp(e[k]) = 0) and (match[e[k].y] = 0) then
begin
j := e[k].y;
Break;
end;
k := link[k];
end;
if j <> 0 then match[j] := i
else
begin
Inc(nlist);
list[nlist] := i;
end;
end;
end;
function HeapExtract: Integer;
var
p, c: Integer;
y: Integer;
begin
with Heap do
begin
Result := items[1];
y := items[nItems]; Dec(nItems);
p := 1;
repeat
c := p * 2;
if (c < nItems) and (d[items[c + 1]] < d[items[c]]) then Inc(c);
if (c > nItems) or (d[items[c]] >= d[y]) then Break;
items[p] := items[c]; pos[items[p]] := p;
p := c;
until False;
items[p] := y; pos[y] := p;
end;
end;
function HeapUpdate(y: Integer; dy: Integer): Boolean;
var
p, c: Integer;
begin
if d[y] <= dy then Exit(False);
d[y] := dy;
Result := True;
with Heap do
begin
c := pos[y];
if c = 0 then
begin
Inc(nItems);c := nItems;
end;
repeat
p := c div 2;
if (p = 0) or (d[items[p]] <= dy) then Break;
items[c] := items[p]; pos[items[c]] := c;
c := p;
until False;
items[c] := y; pos[y] := c;
end;
end;
procedure DijkstraInit(s: Integer);
var
j, k: Integer;
begin
FillDWord(d[1], n, infty);
FillDWord(trace[1], n, 0);
with heap do
begin
FillDWord(pos[1], n, 0);
nItems := 0;
end;
k := head[s];
while k <> 0 do
begin
j := e[k].y;
HeapUpdate(j, wp(e[k]));
k := link[k];
end;
nz := 0;
end;
function Dijkstra(s: Integer): Integer;
var
i, j, jmin: Integer;
k: Integer;
begin;
DijkstraInit(s);
while Heap.nItems > 0 do
begin
jmin := HeapExtract; i := match[jmin];
if i = 0 then Exit(jmin);
Inc(nz); z[nz] := jmin;
k := head[i];
while k <> 0 do
begin
j := e[k].y;
if HeapUpdate(j, d[jmin] + wp(e[k])) then
trace[j] := jmin;
k := link[k];
end;
end;
Result := 0;
end;
procedure UpdatePotentials(s, t: Integer);
var
i, j, k: Integer;
begin
for k := 1 to nz do
begin
j := z[k]; i := match[j];
Inc(f[i], d[t] - d[j]);
Dec(g[j], d[t] - d[j]);
end;
Inc(f[s], d[t]);
end;
procedure Enlarge(s, t: Integer);
var
y: Integer;
begin
repeat
y := trace[t];
if y = 0 then Break;
match[t] := match[y];
t := y;
until False;
match[t] := s;
end;
procedure SuccessiveShortestPaths;
var
s, t: Integer;
p: Integer;
begin
for p := 1 to nlist do
begin
s := list[p];
t := Dijkstra(s);
UpdatePotentials(s, t);
Enlarge(s, t);
end;
end;
procedure PrintResult;
var
fo: TextFile;
i, j: Integer;
begin
cost := 0;
for j := 1 to n do
begin
i := match[j];
Inc(cost, f[i] + g[j]);
end;
AssignFile(fo, OutputFile); Rewrite(fo);
try
WriteLn(fo, cost);
for j := 1 to n do Write(fo, match[j], ' ');
finally
CloseFile(fo);
end;
end;
begin
Enter;
Init;
SuccessiveShortestPaths;
PrintResult;
end.
3 6
1 1 1
1 3 3
2 1 3
2 2 2
3 2 3
3 3 7
1 1 0
1 2 0
2 1 0
2 4 2
3 2 1
3 3 0
4 3 0
4 4 9
|
unit mnSynHighlighterCpp;
//deprecated 'Buggy fix it first';
{$mode objfpc}{$H+}
{**
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
{
}
interface
uses
Classes, SysUtils,
SynEdit, SynEditTypes,
SynEditHighlighter, SynHighlighterHashEntries, mnSynHighlighterMultiProc;
type
{ TCppProcessor }
TCppProcessor = class(TCommonSynProcessor)
protected
function GetIdentChars: TSynIdentChars; override;
function GetEndOfLineAttribute: TSynHighlighterAttributes; override;
public
procedure QuestionProc;
procedure DirectiveProc;
procedure SlashProc;
procedure GreaterProc;
procedure LowerProc;
procedure Next; override;
procedure Prepare; override;
procedure MakeProcTable; override;
end;
{ TmnSynCppSyn }
TmnSynCppSyn = class(TSynMultiProcSyn)
private
protected
function GetSampleSource: string; override;
public
class function GetLanguageName: string; override;
public
constructor Create(AOwner: TComponent); override;
procedure InitProcessors; override;
published
end;
const
SYNS_LangCpp = 'Cpp';
SYNS_FilterCpp = 'Cpp Lang Files (*.c;*.cpp;*.h;*.ino)|*.c;*.cpp;*.h;*.ino';
cCppSample =
'import std.stdio;'#13#10+
'// Computes average line length for standard input.'#13#10+
''#13#10+
'void main()'#13#10+
'{'#13#10+
' ulong lines = 0;'#13#10+
' double sumLength = 0;'#13#10+
' foreach (line; stdin.byLine())'#13#10+
' {'#13#10+
' ++lines;'#13#10+
' sumLength += line.length;'#13#10+
' }'#13#10+
' writeln("Average line length: ",'#13#10+
' lines ? sumLength / lines : 0);'#13#10+
'}'#13#10;
{$INCLUDE 'CppKeywords.inc'}
implementation
uses
mnUtils;
procedure TCppProcessor.GreaterProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] in ['=', '>'] then
Inc(Parent.Run);
end;
procedure TCppProcessor.LowerProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'=': Inc(Parent.Run);
'<':
begin
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = '=' then
Inc(Parent.Run);
end;
end;
end;
procedure TCppProcessor.SlashProc;
begin
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'/':
begin
CommentSLProc;
end;
'*':
begin
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = '*' then
DocumentMLProc
else
CommentMLProc;
end;
else
Parent.FTokenID := tkSymbol;
end;
end;
procedure TCppProcessor.MakeProcTable;
var
I: Char;
begin
inherited;
for I := #0 to #255 do
case I of
'?': ProcTable[I] := @QuestionProc;
'''': ProcTable[I] := @StringSQProc;
'"': ProcTable[I] := @StringDQProc;
'`': ProcTable[I] := @StringBQProc;
'#': ProcTable[I] := @DirectiveProc;
'/': ProcTable[I] := @SlashProc;
'>': ProcTable[I] := @GreaterProc;
'<': ProcTable[I] := @LowerProc;
'A'..'Z', 'a'..'z', '_':
ProcTable[I] := @IdentProc;
'0'..'9':
ProcTable[I] := @NumberProc;
end;
end;
procedure TCppProcessor.QuestionProc;
begin
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'>':
begin
Parent.Processors.Switch(Parent.Processors.MainProcessor);
Inc(Parent.Run);
Parent.FTokenID := tkProcessor;
end
else
Parent.FTokenID := tkSymbol;
end;
end;
procedure TCppProcessor.DirectiveProc;
begin
Parent.FTokenID := tkProcessor;
WordProc;
end;
procedure TCppProcessor.Next;
begin
Parent.FTokenPos := Parent.Run;
if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then
ProcTable[Parent.FLine[Parent.Run]]
else case Range of
rscComment:
begin
CommentMLProc;
end;
rscSpecialComment:
begin
SpecialCommentMLProc;
end;
rscDocument:
begin
DocumentMLProc;
end;
rscStringSQ, rscStringDQ, rscStringBQ:
StringProc;
else
if ProcTable[Parent.FLine[Parent.Run]] = nil then
UnknownProc
else
ProcTable[Parent.FLine[Parent.Run]];
end;
end;
procedure TCppProcessor.Prepare;
begin
inherited;
EnumerateKeywords(Ord(tkKeyword), sCppKeywords, TSynValidStringChars, @DoAddKeyword);
EnumerateKeywords(Ord(tkFunction), sCppFunctions, TSynValidStringChars, @DoAddKeyword);
SetRange(rscUnknown);
end;
function TCppProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes;
begin
if (Range = rscDocument) or (LastRange = rscDocument) then
Result := Parent.DocumentAttri
else
Result := inherited GetEndOfLineAttribute;
end;
function TCppProcessor.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars + ['$'];
end;
constructor TmnSynCppSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDefaultFilter := SYNS_FilterCpp;
end;
procedure TmnSynCppSyn.InitProcessors;
begin
inherited;
Processors.Add(TCppProcessor.Create(Self, 'Cpp'));
Processors.MainProcessor := 'Cpp';
Processors.DefaultProcessor := 'Cpp';
end;
class function TmnSynCppSyn.GetLanguageName: string;
begin
Result := SYNS_LangCpp;
end;
function TmnSynCppSyn.GetSampleSource: string;
begin
Result := cCppSample;
end;
end.
|
unit FMXComponentsDemoMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms,
FMX.Objects, FMX.Layouts,
FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollableList, FMX.RatingBar,
FMX.Ani, FMX.CircleScoreIndicator, FMX.TabControl, FMX.ImageSlider,
FMX.ScrollBox, FMX.Memo, FMX.SimpleBBCodeText, ONE.Objects, Data.Bind.EngExt,
Fmx.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors,
Data.Bind.Components, FMX.GesturePassword, FMX.CalendarControl,
qcndate, CnCalendar, FMX.Seg7Shape, FMX.Toast, FMX.Colors, FMX.Edit,
FMX.QRCode, FMX.EditBox, FMX.NumberBox;
type
TFMXComponentsDemoForm = class(TForm)
Layout16: TLayout;
Layout3: TLayout;
Line1: TLine;
Line4: TLine;
FMXScrollableList2: TFMXScrollableList;
Label1: TLabel;
LayoutYears: TLayout;
Layout2: TLayout;
Line2: TLine;
Line3: TLine;
FMXScrollableList1: TFMXScrollableList;
Label2: TLabel;
FMXRatingBar1: TFMXRatingBar;
btnAnimation: TButton;
FloatAnimation1: TFloatAnimation;
FMXCircleScoreIndicator1: TFMXCircleScoreIndicator;
FloatAnimation2: TFloatAnimation;
Layout4: TLayout;
Layout5: TLayout;
Line5: TLine;
Line6: TLine;
FMXScrollableList3: TFMXScrollableList;
Label3: TLabel;
TabControl1: TTabControl;
tabBasic: TTabItem;
tabSlider: TTabItem;
Image1: TImage;
Image2: TImage;
Image3: TImage;
Image4: TImage;
FMXImageSlider1: TFMXImageSlider;
FloatAnimation3: TFloatAnimation;
tabBBCode: TTabItem;
Memo1: TMemo;
Layout1: TLayout;
FMXSimpleBBCodeText1: TFMXSimpleBBCodeText;
tabGesturePassword: TTabItem;
Layout6: TLayout;
FMXGesturePassword1: TFMXGesturePassword;
lbl1: TLabel;
lblPassword: TLabel;
tabCalendarControl: TTabItem;
FMXCalendarControl1: TFMXCalendarControl;
Layout7: TLayout;
chkShowLunarDate: TCheckBox;
rbCnMonths: TRadioButton;
rbEnMonths: TRadioButton;
Rectangle1: TRectangle;
Rectangle2: TRectangle;
txtCnDate1: TText;
txtCnDate2: TText;
tabSeg7Shape: TTabItem;
Button1: TButton;
tmr1: TTimer;
Seg7Shape1: TFMXSeg7Shape;
Seg7Shape2: TFMXSeg7Shape;
FMXRatingBar2: TFMXRatingBar;
FloatAnimation4: TFloatAnimation;
txtScore: TLabel;
tabToast: TTabItem;
Label4: TLabel;
FMXToast1: TFMXToast;
btnShowToast: TButton;
chkToastIsBlock: TCheckBox;
edtToastMessage: TEdit;
Label7: TLabel;
GroupBox1: TGroupBox;
rbToastTop: TRadioButton;
rbToastCenter: TRadioButton;
rbToastBottom: TRadioButton;
cpFontColor: TColorPanel;
Label5: TLabel;
cpBackColor: TColorPanel;
Label6: TLabel;
tabQRCode: TTabItem;
FMXQRCode1: TFMXQRCode;
Label8: TLabel;
Memo2: TMemo;
BindingsList1: TBindingsList;
cpQRCodeForeColor: TColorPanel;
Label10: TLabel;
cpQRCodeBackColor: TColorPanel;
Label9: TLabel;
Label11: TLabel;
nbQuiteZone: TNumberBox;
Label12: TLabel;
nbQRCodeSize: TNumberBox;
Rectangle3: TRectangle;
Label13: TLabel;
procedure FMXScrollableList2Change(Sender: TObject);
procedure FMXScrollableList1Change(Sender: TObject);
procedure btnAnimationClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FMXScrollableList3Change(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FMXSimpleBBCodeText1Click(Sender: TObject);
procedure Memo1Change(Sender: TObject);
procedure FMXGesturePassword1EnterCompleteEvent(Sender: TObject;
const APassword: string);
procedure chkShowLunarDateChange(Sender: TObject);
procedure rbCnMonthsChange(Sender: TObject);
procedure FMXCalendarControl1SelectedItem(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure tmr1Timer(Sender: TObject);
procedure FloatAnimation2Process(Sender: TObject);
procedure btnShowToastClick(Sender: TObject);
procedure chkToastIsBlockChange(Sender: TObject);
procedure rbToastTopChange(Sender: TObject);
procedure cpFontColorChange(Sender: TObject);
procedure cpBackColorChange(Sender: TObject);
procedure Memo2Change(Sender: TObject);
procedure cpQRCodeForeColorChange(Sender: TObject);
procedure cpQRCodeBackColorChange(Sender: TObject);
procedure nbQuiteZoneChange(Sender: TObject);
procedure nbQRCodeSizeChange(Sender: TObject);
private
{ Private declarations }
FSelection1: TOneSelection;
ShuffleCount : Byte;
FToastCount: Integer;
procedure RollSegment(Sender: TObject ; Data : Byte );
procedure RollSegmentSet( Count : Byte);
public
{ Public declarations }
end;
var
FMXComponentsDemoForm: TFMXComponentsDemoForm;
implementation
{$R *.fmx}
procedure TFMXComponentsDemoForm.btnAnimationClick(Sender: TObject);
begin
FloatAnimation1.Start;
FloatAnimation2.Start;
FloatAnimation4.Start;
end;
procedure TFMXComponentsDemoForm.btnShowToastClick(Sender: TObject);
begin
FMXToast1.ToastMessage := edtToastMessage.Text + FToastCount.ToString;
Inc(FToastCount);
FMXToast1.Show(Self);
end;
procedure TFMXComponentsDemoForm.Button1Click(Sender: TObject);
begin
tmr1.Enabled := TRUE;
Button1.Enabled := False;
ShuffleCount := 17;
Seg7Shape1.Num := $ff;
Seg7Shape2.Num := $ff;
Randomize;
Seg7Shape1.Fill.Color := Seg7Shape1.Fill.Color + Random($ffffffff);
Seg7Shape2.Fill.Color := Seg7Shape1.Fill.Color + Random($ffffffff);
RollSegmentSet( ShuffleCount );
end;
procedure TFMXComponentsDemoForm.chkShowLunarDateChange(Sender: TObject);
begin
FMXCalendarControl1.IsShowLunarDate := chkShowLunarDate.IsChecked;
end;
procedure TFMXComponentsDemoForm.chkToastIsBlockChange(Sender: TObject);
begin
FMXToast1.IsBlock := chkToastIsBlock.IsChecked;
end;
procedure TFMXComponentsDemoForm.cpBackColorChange(Sender: TObject);
begin
FMXToast1.BackColor := cpBackColor.Color;
end;
procedure TFMXComponentsDemoForm.cpFontColorChange(Sender: TObject);
begin
FMXToast1.FontColor := cpFontColor.Color;
end;
procedure TFMXComponentsDemoForm.cpQRCodeBackColorChange(Sender: TObject);
begin
FMXQRCode1.BackGround := cpQRCodeBackColor.Color;
end;
procedure TFMXComponentsDemoForm.cpQRCodeForeColorChange(Sender: TObject);
begin
FMXQRCode1.ForeGround := cpQRCodeForeColor.Color;
end;
procedure TFMXComponentsDemoForm.FloatAnimation2Process(Sender: TObject);
begin
txtScore.Text := IntToStr(Round(FMXCircleScoreIndicator1.Value));
end;
procedure TFMXComponentsDemoForm.FMXCalendarControl1SelectedItem(
Sender: TObject);
var
D: TCnDate;
Year, Month, Day: Word;
begin
DecodeDate(FMXCalendarControl1.SelectedDate, Year, Month, Day);
D := ToCnDate(FMXCalendarControl1.SelectedDate);
txtCnDate1.Text := Format('农历%s%s', [CnMonthName(D), CnDayName(D)]);
txtCnDate2.Text :=
GetGanZhiFromNumber(GetGanZhiFromYear(Year)) +
GetShengXiaoFromNumber(D.Year) + '年 ' +
GetGanZhiFromNumber(GetGanZhiFromMonth(Year, Month, Day)) + '月 ' +
GetGanZhiFromNumber(GetGanZhiFromDay(Year, Month, Day)) + '日';
end;
procedure TFMXComponentsDemoForm.FMXGesturePassword1EnterCompleteEvent(
Sender: TObject; const APassword: string);
begin
lblPassword.Text := self.FMXGesturePassword1.Password;
end;
procedure TFMXComponentsDemoForm.FMXScrollableList1Change(Sender: TObject);
begin
Label1.Text := FMXScrollableList1.GetSelected;
end;
procedure TFMXComponentsDemoForm.FMXScrollableList2Change(Sender: TObject);
begin
Label2.Text := FMXScrollableList2.GetSelected;
end;
procedure TFMXComponentsDemoForm.FMXScrollableList3Change(Sender: TObject);
begin
Label3.Text := FMXScrollableList3.GetSelected;
end;
procedure TFMXComponentsDemoForm.FMXSimpleBBCodeText1Click(Sender: TObject);
var
c: TControl;
begin
if FSelection1.ChildrenCount > 0 then
begin
c := TControl(FSelection1.Children[0]);
c.HitTest := True;
c.Align := TAlignLayout.None;
c.Parent := Layout1;
c.BoundsRect := FSelection1.BoundsRect;
c.Position.Point := FSelection1.Position.Point;
end;
FSelection1.BoundsRect := TControl(Sender).BoundsRect;
FSelection1.Position.Point := TControl(Sender).Position.Point;
FSelection1.Visible := True;
FSelection1.BringToFront;
TControl(Sender).Parent := FSelection1;
TControl(Sender).Align := TAlignLayout.Client;
TControl(Sender).HitTest := False;
end;
procedure TFMXComponentsDemoForm.FormCreate(Sender: TObject);
begin
Label1.Text := FMXScrollableList1.GetSelected;
Label2.Text := FMXScrollableList2.GetSelected;
Label3.Text := FMXScrollableList3.GetSelected;
FMXImageSlider1.SetPage(0, Image1);
FMXImageSlider1.SetPage(1, Image2);
FMXImageSlider1.SetPage(2, Image3);
FMXImageSlider1.SetPage(3, Image4);
FSelection1 := TOneSelection.Create(Self);
FSelection1.GripSize := 8;
FSelection1.Proportional := False;
Layout1.AddObject(FSelection1);
FMXSimpleBBCodeText1Click(FMXSimpleBBCodeText1);
txtCnDate1.Text := '';
txtCnDate2.Text := '';
FToastCount := 1;
end;
procedure TFMXComponentsDemoForm.FormResize(Sender: TObject);
begin
FMXImageSlider1.Height := ClientWidth * 200 / 320;
end;
procedure TFMXComponentsDemoForm.Memo1Change(Sender: TObject);
begin
self.FMXSimpleBBCodeText1.Lines.Assign(Memo1.Lines);
end;
procedure TFMXComponentsDemoForm.Memo2Change(Sender: TObject);
begin
FMXQRCode1.Lines := Memo2.Lines;
end;
procedure TFMXComponentsDemoForm.nbQRCodeSizeChange(Sender: TObject);
begin
FMXQRCode1.IconSize.Size := TSizeF.Create(nbQRCodeSize.Value, nbQRCodeSize.Value);
end;
procedure TFMXComponentsDemoForm.nbQuiteZoneChange(Sender: TObject);
begin
FMXQRCode1.QuiteZone := Round(nbQuiteZone.Value);
end;
procedure TFMXComponentsDemoForm.rbCnMonthsChange(Sender: TObject);
begin
if (Sender as TControl).Tag = 0 then
Self.FMXCalendarControl1.SetMonthNames(TCnMonths)
else
Self.FMXCalendarControl1.SetMonthNames(TEnMonths);
end;
procedure TFMXComponentsDemoForm.rbToastTopChange(Sender: TObject);
begin
if rbToastTop.IsChecked then
FMXToast1.Align := TTextAlign.Leading
else if rbToastCenter.IsChecked then
FMXToast1.Align := TTextAlign.Center
else
FMXToast1.Align := TTextAlign.Trailing
end;
procedure TFMXComponentsDemoForm.RollSegment(Sender: TObject; Data: Byte);
begin
(Sender as TFMXSeg7Shape).Data := Data;
end;
procedure TFMXComponentsDemoForm.RollSegmentSet(Count: Byte);
begin
case Count of
17,9,1 : begin RollSegment(Seg7Shape1 , $01 ); RollSegment(Seg7Shape2 , $01 ); end;
16,8 : begin RollSegment(Seg7Shape1 , $00 ); RollSegment(Seg7Shape2 , $03 ); end;
15,7 : begin RollSegment(Seg7Shape1 , $00 ); RollSegment(Seg7Shape2 , $06 ); end;
14,6 : begin RollSegment(Seg7Shape1 , $00 ); RollSegment(Seg7Shape2 , $0C ); end;
13,5 : begin RollSegment(Seg7Shape1 , $08 ); RollSegment(Seg7Shape2 , $08 ); end;
12,4 : begin RollSegment(Seg7Shape1 , $18 ); RollSegment(Seg7Shape2 , $00 ); end;
11,3 : begin RollSegment(Seg7Shape1 , $30 ); RollSegment(Seg7Shape2 , $00 ); end;
10,2 : begin RollSegment(Seg7Shape1 , $21 ); RollSegment(Seg7Shape2 , $00 ); end;
end;
end;
procedure TFMXComponentsDemoForm.tmr1Timer(Sender: TObject);
var
RandData: Byte;
begin
if (ShuffleCount = 0) then
begin
RandData := Random(100);
Seg7Shape1.Num := RandData mod 10;
Seg7Shape2.Num := RandData div 10;
tmr1.Enabled := False;
Button1.Enabled := TRUE;
Seg7Shape1.Fill.Color := TAlphaColorRec.Blue;
Seg7Shape2.Fill.Color := TAlphaColorRec.Blue;
end
else
begin
Seg7Shape1.Fill.Color := Seg7Shape1.Fill.Color + Random($FFFFFFFF);
Seg7Shape2.Fill.Color := Seg7Shape1.Fill.Color + Random($FFFFFFFF);
Dec(ShuffleCount);
RollSegmentSet(ShuffleCount);
end;
end;
end.
|
unit ВFSUnit;
interface
uses AlgorithmUnit;
type
BFSCell = class
public
coords : Point;
distance : integer;
from : Point;
end;
BFS = class(Algorithm)
private
_bfsGrid : Dictionary<(integer, integer), BFSCell>;
_openSet : Queue<BFSCell>;
_closedSet : List<BFSCell>;
_path : List<BFSCell>;
function GetNeighbours(cell : BFSCell) : List<BFSCell>;
public
constructor Create(gridSize : integer; start, finish : Point);
begin
Inherited Create(gridSize, start, finish);
_bfsGrid := new Dictionary<(integer, integer), BFSCell>;
_openSet := new Queue<BFSCell>;
_closedSet := new List<BFSCell>;
_path := new List<BFSCell>;
for var x := 0 to _gridSize - 1 do
for var y := 0 to _gridSize - 1 do
begin
var tempCell := new BFSCell;
tempCell.coords.x := x;
tempCell.coords.y := y;
tempCell.distance := MaxInt;
_bfsGrid.Add((x,y), tempCell);
end;
_bfsGrid[(start.x, start.y)].distance := 0;
_openSet.Enqueue(_bfsGrid[(start.x, start.y)]);
end;
procedure Step(); override;
function GetGridLayout() : Grid; override;
function GetPathLength() : integer; override;
end;
implementation
procedure BFS.Step();
var found : boolean;
begin
if(_openSet <> nil) and (_openSet.Count > 0) then
begin
var cell := _openSet.Dequeue();
_closedSet.Add(cell);
if(cell = _bfsGrid[(_end.x, _end.y)]) then
found := true;
var neighbours := GetNeighbours(cell);
foreach var neighbour in neighbours do
if not(_closedSet.Contains(neighbour)) then begin
var newDist := cell.distance + Distance(cell.coords.x, cell.coords.y,
neighbour.coords.x, neighbour.coords.y);
if (neighbour.distance > newDist) then
begin
neighbour.distance := newDist;
neighbour.from := cell.coords;
_openSet.Enqueue(neighbour); //Добавка
end;
end;
end else
if(_onFinish <> nil) and not(found) then begin
_onFinish();
exit;
end;
if(found)then begin
var tempCell := _bfsGrid[(_end.x, _end.y)];
_path.Add(tempCell);
while(tempCell <> _bfsGrid[(_start.x, _start.y)])do
begin
tempCell := _bfsGrid[(tempCell.from.x, tempCell.from.y)];
_path.Add(tempCell);
end;
end;
if(_onStep <> nil)then
_onStep();
if(found and (_onFinish <> nil))then
_onFinish();
end;
function BFS.GetGridLayout() : Grid;
begin
var temp := new intArray[_gridSize];
for var i := 0 to _gridSize-1 do
temp[i] := new integer[_gridSize];
foreach var cell in _openSet do
temp[cell.coords.x][cell.coords.y] := 3;
foreach var cell in _closedSet do
temp[cell.coords.x][cell.coords.y] := 2;
foreach var cell in _path do
temp[cell.coords.x][cell.coords.y] := 4;
GetGridLayout := temp;
end;
function BFS.GetNeighbours(cell : BFSCell) : List<BFSCell>;
var neighbours : List<BFSCell>;
neighbour : BFSCell;
begin
neighbours := new List<BFSCell>;
for var x := -1 to 1 do
for var y := -1 to 1 do
if(x <> 0) or (y <> 0) then
if(_bfsGrid.TryGetValue((cell.coords.x + x, cell.coords.y + y), neighbour)
and IsWalkable(cell.coords.x + x, cell.coords.y + y)) then
neighbours.Add(neighbour);
GetNeighbours := neighbours;
end;
function BFS.GetPathLength() : integer;
begin
var length := 0;
for var i := 0 to _path.Count-2 do
length += Distance(_path[i].coords.x, _path[i].coords.y,
_path[i+1].coords.x, _path[i+1].coords.y);
GetPathLength := length;
end;
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.