text stringlengths 14 6.51M |
|---|
unit atCommandLineParameter;
// Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atCommandLineParameter.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TatCommandLineParameter" MUID: (4808938A0159)
interface
uses
l3IntfUses
, atNamedParameter
, atParameter
;
type
TCLPType = (
{* тип параметра командной строки }
clptKey
, clptString
, clptNumber
);//TCLPType
TatCommandLineParameter = class(TatNamedParameter)
private
f_ParamType: TCLPType;
protected
function pm_GetIsRequired: Boolean;
public
constructor Create(parType: TCLPType;
const name: AnsiString;
const description: AnsiString = '';
const defaultValue: AnsiString = atParameter.INVALID_DEFAULT_VALUE); reintroduce;
public
property ParamType: TCLPType
read f_ParamType;
property IsRequired: Boolean
read pm_GetIsRequired;
end;//TatCommandLineParameter
implementation
uses
l3ImplUses
//#UC START# *4808938A0159impl_uses*
//#UC END# *4808938A0159impl_uses*
;
function TatCommandLineParameter.pm_GetIsRequired: Boolean;
//#UC START# *480893F80392_4808938A0159get_var*
//#UC END# *480893F80392_4808938A0159get_var*
begin
//#UC START# *480893F80392_4808938A0159get_impl*
Result := NOT IsDefaultSet;
//#UC END# *480893F80392_4808938A0159get_impl*
end;//TatCommandLineParameter.pm_GetIsRequired
constructor TatCommandLineParameter.Create(parType: TCLPType;
const name: AnsiString;
const description: AnsiString = '';
const defaultValue: AnsiString = atParameter.INVALID_DEFAULT_VALUE);
//#UC START# *4808941B0073_4808938A0159_var*
//#UC END# *4808941B0073_4808938A0159_var*
begin
//#UC START# *4808941B0073_4808938A0159_impl*
inherited Create(name, description, defaultValue);
//
f_ParamType := parType;
//#UC END# *4808941B0073_4808938A0159_impl*
end;//TatCommandLineParameter.Create
end.
|
unit m2TMPLib;
{* Функции для работы с временными файлами. }
(*
//
//
// .Author: Mickael P. Golovin.
// .Copyright: 1997-2001 by Archivarius Team, free for non commercial use.
//
//
*)
// $Id: m2tmplib.pas,v 1.1 2008/02/22 17:10:08 lulin Exp $
// $Log: m2tmplib.pas,v $
// Revision 1.1 2008/02/22 17:10:08 lulin
// - библиотека переехала.
//
// Revision 1.2 2007/12/10 15:33:04 lulin
// - cleanup.
//
// Revision 1.1 2007/12/07 11:51:05 lulin
// - переезд.
//
// Revision 1.4 2006/05/05 07:41:48 lulin
// - cleanup.
//
// Revision 1.3 2001/10/18 12:18:06 law
// - comments: исправлены комментарии.
//
// Revision 1.2 2001/10/18 12:10:32 law
// - comments: xHelpGen.
//
{$I m2Define.inc}
interface
uses
Windows,
SysUtils,
m2AddRdr,
m2AddPrc;
function m2TMPGetFilePath: WideString;
{* - возвращает путь для временных файлов. }
function m2TMPGetFileName(const APath: WideString;
const AExt: WideString): WideString;
{* - создает имя временного файла. }
implementation
var
GFilePath : WideString;
function m2TMPGetFilePath: WideString;
begin
Result := GFilePath;
end;
function m2TMPGetFileName(const APath : WideString;
const AExt : WideString): WideString;
function __CreateFile(const AName: WideString;
const AAccess: DWORD;
const ASharedMode: DWORD;
const ADistribution: DWORD;
const AFlags: DWORD;
var AHandle: THandle): BOOL;
var
LString : AnsiString;
begin
if (Win32Platform = VER_PLATFORM_WIN32_NT) then
AHandle:=CreateFileW(PWideChar(AName),AAccess,ASharedMode,nil,ADistribution,AFlags,0)
else
AHandle:=CreateFileA(m2MakeAnsiString(LString,AName),AAccess,ASharedMode,nil,ADistribution,AFlags,0);
Result:=(AHandle <> INVALID_HANDLE_VALUE);
end;
const
CAccess= 0;
CSharedMode= 0;
CDistribution= CREATE_NEW;
CFlags= FILE_ATTRIBUTE_HIDDEN;
var
LExt: WideString;
LHandle: THandle;
LPath: WideString;
begin
if (APath = WideString('')) then
LPath:=GFilePath
else
LPath:=APath;
if (AExt = WideString('')) then
LExt:=WideString('tmp')
else
LExt:=AExt;
repeat
Result:=WideString(Format('%s~%.3x%.4x.%s',[AnsiString(LPath),Random($1000),Random($FFFF),AnsiString(LExt)]));
if __CreateFile(Result,CAccess,CSharedMode,CDistribution,CFlags,LHandle) then
begin
Win32Check(CloseHandle(LHandle));
Break;
end;
until False;
end;
{$I *.inc}
end.
|
{*******************************************************************************
作者: dmzn@163.com 2009-6-25
描述: 处理窗体背景
*******************************************************************************}
unit UImageControl;
interface
uses
Windows, Classes, Controls, Graphics, SysUtils;
type
TImageControlPosition = (cpTop, cpLeft, cpRight, cpBottom, cpClient, cpForm);
//背景位置
TImageItemStyle = (isTile, isRTile, isStretch);
//放置风格
PImageItemData = ^TImageItemData;
TImageItemData = record
FSize: Integer; //宽 or 高
FRect: TRect; //绘制区域
FCtrlRect: TRect; //控件区域
FAlign: TAlign; //布局样式
FPicture: TPicture; //图片对象
FStyle: TImageItemStyle; //放置风格
end;
TImageControl = class(TGraphicControl)
private
FImages: TList;
{*图片*}
FFormName: string;
{*所在窗体*}
FPosition: TImageControlPosition;
{*位置*}
FClientBmp: TBitmap;
{*客户区*}
protected
procedure ClearImageList(const nFree: Boolean);
{*清理资源*}
procedure SetPosition(AValue: TImageControlPosition);
{*设置位置*}
procedure AdjustImageRect;
procedure PaintToCanvas(const nCanvas: TCanvas);
procedure Paint; override;
{*绘制内容*}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{*创建释放*}
function GetItemData(const nIdx: Integer): PImageItemData;
{*获取数据*}
property FormName: string read FFormName write FFormName;
property Position: TImageControlPosition read FPosition write SetPosition;
{*属性相关*}
end;
implementation
uses
IniFiles, ULibFun, USysConst;
ResourceString
sConfigFile = 'BeautyConfig.Ini'; //配置文件
sClientWidth = 'Image_Width'; //区域宽
sClientHeight = 'Image_Height'; //区域高
sImageNumber = 'Image_Number'; //图片个数
sImageFile = 'Image_File_'; //图片文件
sImageWidth = 'Image_Width_'; //图片宽
sImageHeight = 'Image_Height_'; //图片高
sImageStyle = 'Image_Style_'; //放置风格
sImageTile = 'Tile'; //平铺
sImageRTile = 'RTile'; //右平铺
sImageStretch = 'Stretch'; //拉伸
sImageAlphaColor = 'Image_Alpha_Color'; //透明色
sImageAlphaFile = 'Image_Alpha_File'; //透明文件
sImageAlign = 'Image_Align_'; //布局
sImageLeft = 'Left'; //居左
sImageRight = 'Right'; //居右
sImageTop = 'Top'; //居上
sImageBottom = 'Bottom'; //居下
sImageClient = 'Client'; //客户区
sBgTop = 'BgTop'; //上
sBgBottom = 'BgBottom'; //下
sBgLeft = 'BgLeft'; //左
sBgRight = 'BgRight'; //右
sBgClient = 'BgClient'; //中间
sBgForm = 'BgForm'; //窗体
sValidRect = 'RectValid'; //有效区域
//------------------------------------------------------------------------------
constructor TImageControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClientBmp := nil;
FImages := TList.Create;
FFormName := AOwner.Name;
end;
destructor TImageControl.Destroy;
begin
if Assigned(FClientBmp) then
FClientBmp.Free;
ClearImageList(True);
inherited;
end;
//Desc: 清理图片列表
procedure TImageControl.ClearImageList(const nFree: Boolean);
var nIdx: integer;
nP: PImageItemData;
begin
for nIdx:=FImages.Count - 1 downto 0 do
begin
nP := FImages[nIdx];
if Assigned(nP.FPicture) then FreeAndNil(nP.FPicture);
Dispose(nP);
FImages.Delete(nIdx);
end;
if nFree then FreeAndNil(FImages);
end;
//Desc: 获取索引为nIdx的图片数据
function TImageControl.GetItemData(const nIdx: Integer): PImageItemData;
begin
if (nIdx > -1) and (nIdx < FImages.Count) then
Result := FImages[nIdx]
else if (FImages.Count > 0) then
Result := FImages[0]
else Result := nil;
end;
//Desc: 字符转布局
function StrToAlign(const nStr: string): TAlign;
begin
if CompareText(nStr, sImageLeft) = 0 then
Result := alLeft
else if CompareText(nStr, sImageRight) = 0 then
Result := alRight
else if CompareText(nStr, sImageTop) = 0 then
Result := alTop
else if CompareText(nStr, sImageBottom) = 0 then
Result := alBottom
else if CompareText(nStr, sImageClient) = 0 then
Result := alClient
else Result := alLeft;
end;
//Desc: 图片方式风格
function Str2ImageStyle(const nStyle: string): TImageItemStyle;
begin
if CompareText(nStyle, sImageTile) = 0 then
Result := isTile else
if CompareText(nStyle, sImageRTile) = 0 then
Result := isRTile
else Result := isStretch;
end;
//Desc: 载入背景配置
procedure TImageControl.SetPosition(AValue: TImageControlPosition);
var nIni: TIniFile;
nP: PImageItemData;
nIdx,nCount: Integer;
nStr,nTmp,nSection: string;
begin
FPosition := AValue;
nIni := nil;
try
ClearImageList(False);
FreeAndNil(FClientBmp);
nIni := TIniFile.Create(gPath + sConfigFile);
case AValue of
cpTop,cpBottom: //上,下
begin
if AValue = cpTop then
nSection := sBgTop
else nSection := sBgBottom;
nStr := nSection + '_' + FFormName;
if nIni.ReadString(nStr, sImageStyle + '1', '') <> '' then
nSection := nStr;
//xxxxx
Height := nIni.ReadInteger(nSection, sClientHeight, 20);
nCount := nIni.ReadInteger(nSection, sImageNumber, 0);
for nIdx:=1 to nCount do
begin
New(nP);
FImages.Add(nP);
FillChar(nP^, SizeOf(TImageItemData), #0);
nP.FSize := nIni.ReadInteger(nSection, sImageWidth + IntToStr(nIdx), 0);
nStr := nIni.ReadString(nSection, sImageAlign + IntToStr(nIdx), '');
nP.FAlign := StrToAlign(nStr);
nStr := nIni.ReadString(nSection, sImageStyle + IntToStr(nIdx), '');
nP.FStyle := Str2ImageStyle(nStr);
nStr := nIni.ReadString(nSection, sImageFile + IntToStr(nIdx), '');
nStr := StringReplace(nStr, '$Path\', gPath, [rfIgnoreCase]);
if FileExists(nStr) then
begin
nP.FPicture := TPicture.Create;
nP.FPicture.LoadFromFile(nStr);
end else nP.FPicture := nil;
end;
end;
cpLeft,cpRight: //左,右
begin
if AValue = cpLeft then
nSection := sBgLeft
else nSection := sBgRight;
nStr := nSection + '_' + FFormName;
if nIni.ReadString(nStr, sImageStyle + '1', '') <> '' then
nSection := nStr;
//xxxxx
Width := nIni.ReadInteger(nSection, sClientWidth, 20);
nCount := nIni.ReadInteger(nSection, sImageNumber, 0);
for nIdx:=1 to nCount do
begin
New(nP);
FImages.Add(nP);
FillChar(nP^, SizeOf(TImageItemData), #0);
nP.FSize := nIni.ReadInteger(nSection, sImageHeight + IntToStr(nIdx), 0);
nStr := nIni.ReadString(nSection, sImageAlign + IntToStr(nIdx), '');
nP.FAlign := StrToAlign(nStr);
nStr := nIni.ReadString(nSection, sImageStyle + IntToStr(nIdx), '');
nP.FStyle := Str2ImageStyle(nStr);
nStr := nIni.ReadString(nSection, sImageFile + IntToStr(nIdx), '');
nStr := StringReplace(nStr, '$Path\', gPath, [rfIgnoreCase]);
if FileExists(nStr) then
begin
nP.FPicture := TPicture.Create;
nP.FPicture.LoadFromFile(nStr);
end else nP.FPicture := nil;
end;
end;
cpClient,cpForm: //客户区,窗体
begin
if AValue = cpForm then
begin
if nIni.ReadString(FFormName, sImageStyle + '1', '') = '' then
nSection := sBgForm
else nSection := FFormName;
end else
begin
nSection := sBgClient;
nStr := nSection + '_' + FFormName;
if nIni.ReadString(nStr, sImageStyle + '1', '') <> '' then
nSection := nStr;
//xxxxx
end;
New(nP);
FImages.Add(nP);
FillChar(nP^, SizeOf(TImageItemData), #0);
nStr := nIni.ReadString(nSection, sImageStyle + '1', '');
if nStr = sImageStretch then
nP.FStyle := isStretch
else nP.FStyle := isTile;
nStr := nIni.ReadString(nSection, sImageFile + '1', '');
nStr := StringReplace(nStr, '$Path\', gPath, [rfIgnoreCase]);
if FileExists(nStr) then
begin
nP.FPicture := TPicture.Create;
nP.FPicture.LoadFromFile(nStr);
end else nP.FPicture := nil;
nCount := 0;
nStr := nIni.ReadString(nSection, sValidRect, '') + ',';
nIdx := Pos(',', nStr);
while nIdx > 1 do
begin
nTmp := Copy(nStr, 1, nIdx - 1);
if not IsNumber(nTmp, False) then Break;
case nCount of
0: nP.FCtrlRect.Left := StrToInt(nTmp);
1: nP.FCtrlRect.Top := StrToInt(nTmp);
2: nP.FCtrlRect.Right := StrToInt(nTmp);
3: nP.FCtrlRect.Bottom := StrToInt(nTmp);
end;
Inc(nCount);
System.Delete(nStr, 1, nIdx);
nIdx := Pos(',', nStr);
end;
nStr := nIni.ReadString(nSection, sImageAlphaFile, '');
nStr := StringReplace(nStr, '$Path\', gPath, [rfIgnoreCase]);
if FileExists(nStr) then
begin
New(nP);
FImages.Add(nP);
FillChar(nP^, SizeOf(TImageItemData), #0);
nP.FPicture := TPicture.Create;
nP.FPicture.LoadFromFile(nStr);
nStr := nIni.ReadString(nSection, sImageAlphaColor, '');
if IsNumber(nStr, False) then nP.FSize := TColor(StrToInt(nStr));
end;
end;
end;
FreeAndNil(nIni);
except
FreeAndNil(nIni);
end;
end;
//Date: 2009-7-26
//Parm: 底图;图片;透明色
//Desc: 在nBg的中间位置,绘制一个nAlpha透明的nImage图片
procedure CombineAlphaImage(nBg: TBitmap; nImage: TPicture; nAlpha: Integer);
var nBmp: TBitmap;
nX,nY: integer;
begin
nBmp := TBitmap.Create;
try
nBmp.Width := nImage.Width;
nBmp.Height := nImage.Height;
nBmp.PixelFormat := nBg.PixelFormat;
nBmp.Canvas.Draw(0, 0, nImage.Graphic);
nBmp.TransparentColor := nAlpha;
nBmp.TransparentMode := tmFixed;
nBmp.Transparent := True;
nX := Round((nBg.Width - nBmp.Width) / 2);
nY := Round((nBg.Height - nBmp.Height) / 2);
nBg.Canvas.Draw(nX, nY, nBmp);
finally
nBmp.Free;
end;
end;
//Desc: 调整各个图片可绘制的区域
procedure TImageControl.AdjustImageRect;
var nP: PImageItemData;
nIdx,nCount,nValueA,nValueB: Integer;
begin
case FPosition of
cpTop,cpBottom: //上,下
begin
nValueA := 0;
nCount := FImages.Count - 1;
for nIdx:=0 to nCount do
begin
nP := FImages[nIdx];
if nP.FAlign <> alLeft then Continue;
nP.FRect := Rect(nValueA, 0, nValueA + nP.FSize, Height);
Inc(nValueA, nP.FSize);
end;
//处理居左
nValueB := Width;
for nIdx:=0 to nCount do
begin
nP := FImages[nIdx];
if nP.FAlign <> alRight then Continue;
nP.FRect := Rect(nValueB - nP.FSize, 0, nValueB, Height);
Dec(nValueB, nP.FSize);
end;
//处理居右
for nIdx:=0 to nCount do
begin
nP := FImages[nIdx];
if nP.FAlign <> alClient then Continue;
nP.FRect := Rect(nValueA, 0, nValueB, Height);
Break;
end;
//客户区
end;
cpLeft,cpRight: //左,右
begin
nValueA := 0;
nCount := FImages.Count - 1;
for nIdx:=0 to nCount do
begin
nP := FImages[nIdx];
if nP.FAlign <> alTop then Continue;
nP.FRect := Rect(0, nValueA, Width, nValueA + nP.FSize);
Inc(nValueA, nP.FSize);
end;
//处理居上
nValueB := Height;
for nIdx:=0 to nCount do
begin
nP := FImages[nIdx];
if nP.FAlign <> alBottom then Continue;
nP.FRect := Rect(0, nValueB - nP.FSize, Width, nValueB);
Dec(nValueB, nP.FSize);
end;
//处理居下
for nIdx:=0 to nCount do
begin
nP := FImages[nIdx];
if nP.FAlign <> alClient then Continue;
nP.FRect := Rect(0, nValueA, Width, nValueB);
Break;
end;
//客户区
end;
cpClient,cpForm: //客户区,窗体
begin
if FImages.Count > 0 then
begin
nP := FImages[0];
nP.FRect := ClientRect;
end;
if FImages.Count = 2 then
begin
if not Assigned(FClientBmp) then
FClientBmp := TBitmap.Create;
//xxxxx
if (FClientBmp.Width <> Width) or (FClientBmp.Height <> Height) then
begin
FClientBmp.Width := Width;
FClientBmp.Height := Height;
PaintToCanvas(FClientBmp.Canvas);
nP := FImages[1];
CombineAlphaImage(FClientBmp, nP.FPicture, nP.FSize);
end;
end; //带Alpha层
end;
end;
end;
//Desc: 将图片绘制到nCanvas上
procedure TImageControl.PaintToCanvas(const nCanvas: TCanvas);
var nP: PImageItemData;
nIdx,nCount,nValueA,nValueB: Integer;
begin
nCount := FImages.Count - 1;
for nIdx:=0 to nCount do
begin
nP := FImages[nIdx];
if not (Assigned(nP.FPicture) and Assigned(nP.FPicture.Graphic)) then Continue;
if nIdx > 0 then
if (FPosition = cpClient) or (FPosition = cpForm) then Break;
//这两种风格只有一张有效底图,余下的为Alpha图
if nP.FStyle = isTile then
begin
nValueA := nP.FRect.Left;
while nValueA < nP.FRect.Right do
begin
nValueB := nP.FRect.Top;
while nValueB < nP.FRect.Bottom do
begin
nCanvas.Draw(nValueA, nValueB, nP.FPicture.Graphic);
Inc(nValueB, nP.FPicture.Height);
end;
Inc(nValueA, nP.FPicture.Width);
end;
end else //左平铺
if nP.FStyle = isRTile then
begin
nValueA := nP.FRect.Right;
Dec(nValueA, nP.FPicture.Width);
while nValueA > -nP.FPicture.Width do
begin
nValueB := nP.FRect.Top;
while nValueB < nP.FRect.Bottom do
begin
nCanvas.Draw(nValueA, nValueB, nP.FPicture.Graphic);
Inc(nValueB, nP.FPicture.Height);
end;
Dec(nValueA, nP.FPicture.Width);
end;
end else //右平铺
if nP.FStyle = isStretch then
begin
nCanvas.StretchDraw(nP.FRect, nP.FPicture.Graphic);
end; //绘制拉伸
end;
end;
//Desc: 绘制
procedure TImageControl.Paint;
begin
AdjustImageRect;
if Assigned(FClientBmp) then
Canvas.StretchDraw(ClientRect, FClientBmp)
else PaintToCanvas(Canvas);
end;
end.
|
{ RxDBTimeEdit unit
Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team
original conception from rx library for Delphi (c)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your 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 Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit RxDBTimeEdit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
RxTimeEdit, DB, DbCtrls, LMessages, LCLType;
type
{ TCustomRxDBTimeEdit }
TCustomRxDBTimeEdit = class(TCustomRxTimeEdit)
private
FDataLink: TFieldDataLink;
procedure DataChange(Sender: TObject);
function GetDataField: string;
function GetDataSource: TDataSource;
function GetField: TField;
procedure SetDataField(const AValue: string);
procedure SetDataSource(const AValue: TDataSource);
procedure UpdateData(Sender: TObject);
procedure FocusRequest(Sender: TObject);
procedure ActiveChange(Sender: TObject);
procedure LayoutChange(Sender: TObject);
procedure CMGetDataLink(var Message: TLMessage); message CM_GETDATALINK;
function IsReadOnly: boolean;
procedure WMSetFocus(var Message: TLMSetFocus); message LM_SETFOCUS;
procedure WMKillFocus(var Message: TLMKillFocus); message LM_KILLFOCUS;
protected
function GetReadOnly: Boolean;override;
procedure SetReadOnly(AValue: Boolean);override;
property DataField: string read GetDataField write SetDataField;
property DataSource: TDataSource read GetDataSource write SetDataSource;
//property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Change; override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Field: TField read GetField;
end;
TRxDBTimeEdit = class(TCustomRxDBTimeEdit)
published
property DataField;
property DataSource;
property ReadOnly;
property AutoSize;
property AutoSelect;
property Align;
property Anchors;
property BorderSpacing;
property ButtonOnlyWhenFocused;
property ButtonHint;
property CharCase;
property Color;
// property DirectInput;
property DragCursor;
property DragMode;
property EchoMode;
property Enabled;
// property Flat;
property Font;
// property Glyph;
property MaxLength;
// property NumGlyphs;
property OnButtonClick;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEditingDone;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnStartDrag;
property OnUTF8KeyPress;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
end;
implementation
uses dbutils, LCLVersion;
type
TFieldDataLinkHack = class(TFieldDataLink)
end;
{ TCustomRxDBTimeEdit }
procedure TCustomRxDBTimeEdit.DataChange(Sender: TObject);
begin
if Assigned(FDataLink.Field) and (FDataLink.Field.DataType in DataTimeTypes) then
Self.Time:=FDatalink.Field.AsDateTime
else
Text := '';
end;
function TCustomRxDBTimeEdit.GetDataField: string;
begin
Result := FDataLink.FieldName;
end;
function TCustomRxDBTimeEdit.GetDataSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
function TCustomRxDBTimeEdit.GetField: TField;
begin
Result := FDataLink.Field;
end;
function TCustomRxDBTimeEdit.GetReadOnly: Boolean;
begin
Result := FDataLink.ReadOnly;
end;
procedure TCustomRxDBTimeEdit.SetDataField(const AValue: string);
begin
FDataLink.FieldName := AValue;
end;
procedure TCustomRxDBTimeEdit.SetDataSource(const AValue: TDataSource);
begin
ChangeDataSource(Self,FDataLink,AValue);
end;
procedure TCustomRxDBTimeEdit.SetReadOnly(AValue: Boolean);
begin
inherited SetReadOnly(AValue);
FDataLink.ReadOnly := AValue;
end;
procedure TCustomRxDBTimeEdit.UpdateData(Sender: TObject);
begin
if Assigned(FDataLink.Field) and (FDataLink.Field.DataType in DataTimeTypes) then
begin
FDataLink.Field.AsDateTime := Self.Time;
end;
end;
procedure TCustomRxDBTimeEdit.FocusRequest(Sender: TObject);
begin
SetFocus;
end;
procedure TCustomRxDBTimeEdit.ActiveChange(Sender: TObject);
begin
if FDatalink.Active then
DataChange(Sender)
else
begin
Text := '';
FDataLink.Reset;
end;
end;
procedure TCustomRxDBTimeEdit.LayoutChange(Sender: TObject);
begin
DataChange(Sender);
end;
procedure TCustomRxDBTimeEdit.CMGetDataLink(var Message: TLMessage);
begin
Message.Result := PtrUInt(FDataLink);
end;
function TCustomRxDBTimeEdit.IsReadOnly: boolean;
begin
result := true;
if FDatalink.Active and not Self.ReadOnly then
result := (Field=nil) or Field.ReadOnly;
end;
procedure TCustomRxDBTimeEdit.WMSetFocus(var Message: TLMSetFocus);
begin
inherited WMSetFocus(Message);
if not FDatalink.Editing then
FDatalink.Reset;
end;
procedure TCustomRxDBTimeEdit.WMKillFocus(var Message: TLMKillFocus);
begin
inherited WMKillFocus(Message);
if not FDatalink.Editing then
FDatalink.Reset
else
TFieldDataLinkHack(FDatalink).UpdateData;
end;
procedure TCustomRxDBTimeEdit.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
if Key=VK_ESCAPE then
begin
//cancel out of editing by reset on esc
FDataLink.Reset;
SelectAll;
Key := VK_UNKNOWN;
end
else
if Key=VK_DELETE then
begin
if not IsReadOnly then
FDatalink.Edit;
end
else
if Key=VK_TAB then
begin
if FDataLink.CanModify and FDatalink.Editing then
FDataLink.UpdateRecord;
end;
end;
procedure TCustomRxDBTimeEdit.Change;
begin
if Assigned(FDatalink) then
begin
FDatalink.Edit;
FDataLink.Modified;
end;
inherited Change;
end;
procedure TCustomRxDBTimeEdit.Loaded;
begin
inherited Loaded;
if (csDesigning in ComponentState) then
DataChange(Self);
end;
procedure TCustomRxDBTimeEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation=opRemove) then
begin
if (FDataLink<>nil) and (AComponent=DataSource) then
DataSource:=nil;
end;
end;
constructor TCustomRxDBTimeEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataLink := TFieldDataLink.Create;
FDataLink.Control := Self;
FDataLink.OnDataChange := @DataChange;
FDataLink.OnUpdateData := @UpdateData;
FDataLink.OnActiveChange := @ActiveChange;
{$if (lcl_major = 0) and (lcl_release <= 30)}
FDataLink.OnLayoutChange := @LayoutChange;
{$endif}
end;
destructor TCustomRxDBTimeEdit.Destroy;
begin
FreeAndNil(FDataLink);
inherited Destroy;
end;
end.
|
unit kwWordAliasByRef;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwWordAliasByRef.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::WordAliasByRef
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
l3Interfaces,
tfwScriptingInterfaces,
kwCompiledWord,
l3ParserInterfaces
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\tfwConstLike.imp.pas}
TkwWordAliasByRef = {final} class(_tfwConstLike_)
protected
// overridden protected methods
procedure FinishDefinitionOfNewWord(aWordToFinish: TtfwKeyWord;
aCompiled: TkwCompiledWord;
const aContext: TtfwContext); override;
{* Завершает определение вновь созданного слова }
function SupressNextImmediate: Boolean; override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwWordAliasByRef
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
SysUtils,
l3String,
l3Parser,
kwInteger,
kwString,
TypInfo,
l3Base,
kwIntegerFactory,
kwStringFactory,
l3Chars,
tfwAutoregisteredDiction,
tfwScriptEngine
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwWordAliasByRef;
{$Include ..\ScriptEngine\tfwConstLike.imp.pas}
// start class TkwWordAliasByRef
class function TkwWordAliasByRef.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'WordAliasByRef';
end;//TkwWordAliasByRef.GetWordNameForRegister
procedure TkwWordAliasByRef.FinishDefinitionOfNewWord(aWordToFinish: TtfwKeyWord;
aCompiled: TkwCompiledWord;
const aContext: TtfwContext);
//#UC START# *4F219629036A_4F4008E501E9_var*
var
l_W : TtfwWord;
l_Key : TtfwKeyWord;
l_VC : Integer;
l_VC1 : Integer;
//#UC END# *4F219629036A_4F4008E501E9_var*
begin
//#UC START# *4F219629036A_4F4008E501E9_impl*
CompilerAssert((aCompiled.Code <> nil) AND (aCompiled.Code.Count = 1),
'Неверное число парамеров для слова WordAlias',
aContext
);
l_W := aCompiled.Code[0];
l_VC := aContext.rEngine.ValuesCount;
l_W.DoIt(aContext);
l_VC1 := aContext.rEngine.ValuesCount;
CompilerAssert(l_VC1 > l_VC,
Format('Слово %s для WordAliasByRef %s не повысило уровень стека',
[
l_W.Key.AsString,
aCompiled.Key.AsString
]),
aContext);
CompilerAssert(l_VC1 <= l_VC + 1,
Format('Слово %s для WordAliasByRef %s повысило уровень стека более чем на одно значение',
[
l_W.Key.AsString,
aCompiled.Key.AsString
]),
aContext);
l_W := aContext.rEngine.PopObj As TtfwWord;
l_Key := TtfwKeyWord(l_W.Key);
try
aWordToFinish.Word := l_W;
finally
l_W.Key := l_Key;
end;//try..finally
//#UC END# *4F219629036A_4F4008E501E9_impl*
end;//TkwWordAliasByRef.FinishDefinitionOfNewWord
function TkwWordAliasByRef.SupressNextImmediate: Boolean;
//#UC START# *4F3AB3B101FC_4F4008E501E9_var*
//#UC END# *4F3AB3B101FC_4F4008E501E9_var*
begin
//#UC START# *4F3AB3B101FC_4F4008E501E9_impl*
Result := true;
//#UC END# *4F3AB3B101FC_4F4008E501E9_impl*
end;//TkwWordAliasByRef.SupressNextImmediate
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\tfwConstLike.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit CommCtrl4;
interface
uses
Windows, Messages, CommCtrl, Classes;
const
cctrl = 'comctl32.dll';
type
PInitCommonControlsEx = ^TInitCommonControlsEx;
TInitCommonControlsEx =
packed record
dwSize : longint;
dwICC : longint;
end;
const
ICC_LISTVIEW_CLASSES = $00000001; // listview, header
ICC_TREEVIEW_CLASSES = $00000002; // treeview, tooltips
ICC_BAR_CLASSES = $00000004; // toolbar, statusbar, trackbar, tooltips
ICC_TAB_CLASSES = $00000008; // tab, tooltips
ICC_UPDOWN_CLASS = $00000010; // updown
ICC_PROGRESS_CLASS = $00000020; // progress
ICC_HOTKEY_CLASS = $00000040; // hotkey
ICC_ANIMATE_CLASS = $00000080; // animate
ICC_WIN95_CLASSES = $0000000F;
ICC_DATE_CLASSES = $00000100; // month picker, date picker, time picker, updown
ICC_USEREX_CLASSES = $00000200; // comboex
ICC_COOL_CLASSES = $00000400; // rebar ( coolbar ) control
function InitCommonControlsEx( icc : PINITCOMMONCONTROLSEX ) : BOOL; stdcall;
//====== Generic WM_NOTIFY notification codes =================================
const
NM_CUSTOMDRAW = ( NM_FIRST - 12 );
NM_HOVER = ( NM_FIRST - 13 );
//====== WM_NOTIFY codes ( NMHDR.code values ) ==================================
const
MCN_FIRST = 0 - 750; // monthcal
MCN_LAST = 0 - 759;
DTN_FIRST = 0 - 760; // datetimepick
DTN_LAST = 0 - 799;
CBEN_FIRST = 0 - 800; // combo box ex
CBEN_LAST = 0 - 830;
RBN_FIRST = 0 - 831; // rebar
RBN_LAST = 0 - 859;
//==================== CUSTOM DRAW ==========================================
// custom draw return flags
// values under 0x00010000 are reserved for global custom draw values.
// above that are for specific controls
const
CDRF_DODEFAULT = $00000000;
CDRF_NEWFONT = $00000002;
CDRF_SKIPDEFAULT = $00000004;
CDRF_NOTIFYPOSTPAINT = $00000010;
CDRF_NOTIFYITEMDRAW = $00000020;
CDRF_NOTIFYPOSTERASE = $00000040;
CDRF_NOTIFYITEMERASE = $00000080;
// drawstage flags
// values under 0x00010000 are reserved for global custom draw values.
// above that are for specific controls
const
CDDS_PREPAINT = $00000001;
CDDS_POSTPAINT = $00000002;
CDDS_PREERASE = $00000003;
CDDS_POSTERASE = $00000004;
// the 0x000010000 bit means it's individual item specific
const
CDDS_ITEM = $00010000;
CDDS_ITEMPREPAINT = CDDS_ITEM or CDDS_PREPAINT;
CDDS_ITEMPOSTPAINT = CDDS_ITEM or CDDS_POSTPAINT;
CDDS_ITEMPREERASE = CDDS_ITEM or CDDS_PREERASE;
CDDS_ITEMPOSTERASE = CDDS_ITEM or CDDS_POSTERASE;
// itemState flags
const
CDIS_SELECTED = $0001;
CDIS_GRAYED = $0002;
CDIS_DISABLED = $0004;
CDIS_CHECKED = $0008;
CDIS_FOCUS = $0010;
CDIS_DEFAULT = $0020;
CDIS_HOT = $0040;
type
PNMCustomDraw = ^TNMCustomDraw;
TNMCustomDraw =
packed record
hdr : TNMHDR;
dwDrawStage : longint;
hdc : HDC;
rc : TRect;
dwItemSpec : longint;
uItemState : word;
lItemlParam : longint;
end;
// for tooltips
type
PNMTTCustomDraw = ^TNMTTCustomDraw;
TNMTTCustomDraw =
packed record
nmcd : TNMCustomDraw;
uDrawFlags : word;
end;
//====== IMAGE APIS ===========================================================
type
PImageListDrawParams = ^TImageListDrawParams;
TImageListDrawParams =
packed record
cbSize : longint;
himl : HIMAGELIST;
i : integer;
hdcDst : HDC;
x : integer;
y : integer;
cx : integer;
cy : integer;
xBitmap : integer;
yBitmap : integer;
rgbBk : TColorRef;
rgbFg : TColorRef;
fStyle : word;
dwRop : longint;
end;
function ImageList_SetImageCount( himl : HIMAGELIST;
uNewCount : word ) : BOOL; stdcall;
function ImageList_DrawIndirect( pimldp : PIMAGELISTDRAWPARAMS ) : BOOL; stdcall;
const
ILD_ROP = $0040;
const
ILCF_MOVE = $00000000;
ILCF_SWAP = $00000001;
function ImageList_Copy( himlDst : HIMAGELIST; iDst : integer; himlSrc : HIMAGELIST; iSrc : integer;
uFlags : word ) : BOOL; stdcall;
type
PImageInfo = ^TImageInfo;
TImageInfo =
packed record
hbmImage : HBITMAP;
hbmMask : HBITMAP;
Unused1 : integer;
Unused2 : integer;
rcImage : TRect;
end;
//====== TOOLBAR CONTROL ======================================================
const
TBSTATE_ELLIPSES = $40;
const
TBSTYLE_DROPDOWN = $08;
TBSTYLE_FLAT = $0800;
TBSTYLE_LIST = $1000;
TBSTYLE_CUSTOMERASE = $2000;
const
IDB_HIST_SMALL_COLOR = 8;
IDB_HIST_LARGE_COLOR = 9;
// icon indexes for standard view bitmap
const
HIST_BACK = 0;
HIST_FORWARD = 1;
HIST_FAVORITES = 2;
HIST_ADDTOFAVORITES = 3;
HIST_VIEWTREE = 4;
type
PTBSaveParamsA = ^TTBSaveParamsA;
TTBSaveParamsA =
packed record
hkr : HKEY;
pszSubKey : pchar;
pszValueName : pchar;
end;
type
TBSaveParams = TTBSaveParamsA;
const
TB_SETIMAGELIST = WM_USER + 48;
TB_GETIMAGELIST = WM_USER + 49;
TB_LOADIMAGES = WM_USER + 50;
TB_GETRECT = WM_USER + 51; // wParam is the Cmd instead of index
TB_SETHOTIMAGELIST = WM_USER + 52;
TB_GETHOTIMAGELIST = WM_USER + 53;
TB_SETDISABLEDIMAGELIST = WM_USER + 54;
TB_GETDISABLEDIMAGELIST = WM_USER + 55;
TB_SETSTYLE = WM_USER + 56;
TB_GETSTYLE = WM_USER + 57;
TB_GETBUTTONSIZE = WM_USER + 58;
TB_SETBUTTONWIDTH = WM_USER + 59;
TB_SETMAXTEXTROWS = WM_USER + 60;
TB_GETTEXTROWS = WM_USER + 61;
TB_GETBUTTONTEXT = TB_GETBUTTONTEXTA;
TB_SAVERESTORE = TB_SAVERESTOREA;
TB_ADDSTRING = TB_ADDSTRINGA;
const
TBN_DROPDOWN = TBN_FIRST - 10;
TBN_CLOSEUP = TBN_FIRST - 11;
type
PNMToolbarA = ^TNMToolbarA;
TNMToolbarA =
packed record
hdr : TNMHDR;
iItem : integer;
tbButton : TTBButton;
cchText : integer;
pszText : pchar;
end;
type
TNMTOOLBAR = TNMTOOLBARA;
type
TBNOTIFYA = TNMTOOLBARA;
TBNOTIFY = TNMTOOLBAR;
function Toolbar_AddBitmap( Toolbar : HWND; ButtonCount : integer; Data : PTBAddBitmap ) : BOOL;
function Toolbar_AddButtons( Toolbar : HWND; ButtonCount : integer; var Buttons ) : BOOL;
function Toolbar_AddString( Toolbar : HWND; hInst, idString : integer ) : integer;
function Toolbar_AutoSize( Toolbar : HWND ) : BOOL;
function Toolbar_ButtonCount( Toolbar : HWND ) : integer;
function Toolbar_ButtonStructSize( Toolbar : HWND; StructSize : integer ) : BOOL;
function Toolbar_ChangeBitmap( Toolbar : HWND; idButton, idxBitmap : integer ) : BOOL;
function Toolbar_CheckButton( Toolbar : HWND; idButton : integer; Checked : BOOL ) : BOOL;
function Toolbar_CommandToIndex( Toolbar : HWND; idButton : integer ) : integer;
function Toolbar_Customize( Toolbar : HWND ) : BOOL;
function Toolbar_DeleteButton( Toolbar : HWND; idButton : integer ) : BOOL;
function Toolbar_EnableButton( Toolbar : HWND; idButton : integer; Enabled : BOOL ) : BOOL;
function Toolbar_GetBitmap( Toolbar : HWND; idButton : integer ) : integer;
function Toolbar_GetBitmapFlags( Toolbar : HWND ) : BOOL;
function Toolbar_GetButton( Toolbar : HWND; idButton : integer; var ButtonData : TTBButton ) : BOOL;
function Toolbar_GetButtonSize( Toolbar : HWND ) : TPoint;
function Toolbar_GetButtonState( Toolbar : HWND; idButton : integer ) : integer;
function Toolbar_GetButtonText( Toolbar : HWND; idButton : integer ) : string;
function Toolbar_GetDisabledImageList( Toolbar : HWND ) : HIMAGELIST;
function Toolbar_GetHotImageList( Toolbar : HWND ) : HIMAGELIST;
function Toolbar_GetImageList( Toolbar : HWND ) : HIMAGELIST;
function Toolbar_GetItemRect( Toolbar : HWND; idButton : integer; var Rect : TRect ) : BOOL;
function Toolbar_GetRect( Toolbar : HWND; idButton : integer; var Rect : TRect ) : BOOL;
function Toolbar_GetRows( Toolbar : HWND ) : integer;
function Toolbar_GetStyle( Toolbar : HWND ) : integer;
function Toolbar_GetTextRows( Toolbar : HWND ) : integer;
function Toolbar_GetToolTips( Toolbar : HWND ) : HWND;
function Toolbar_HideButton( Toolbar : HWND; idButton : integer; Shown : BOOL ) : BOOL;
function Toolbar_IndeterminateButton ( Toolbar : HWND; idButton : integer; Indeterminate : BOOL ) : BOOL;
function Toolbar_InsertButton( Toolbar : HWND; idButton : integer; ButtonData : PTBButton ) : BOOL;
function Toolbar_IsButtonChecked( Toolbar : HWND; idButton : integer ) : BOOL;
function Toolbar_IsButtonEnabled( Toolbar : HWND; idButton : integer ) : BOOL;
function Toolbar_IsButtonHidden( Toolbar : HWND; idButton : integer ) : BOOL;
function Toolbar_IsButtonIndeterminate( Toolbar : HWND; idButton : integer ) : BOOL;
function Toolbar_IsButtonPressed( Toolbar : HWND; idButton : integer ) : BOOL;
function Toolbar_LoadImages( Toolbar : HWND; hInst, idBitmap : integer ) : BOOL;
function Toolbar_PressButton( Toolbar : HWND; idButton : integer; Pressed : BOOL ) : BOOL;
function Toolbar_SaveRestore( Toolbar : HWND; Save : BOOL; Params : TTBSaveParams ) : BOOL;
function Toolbar_SetBitmapSize( Toolbar : HWND; Width, Height : word ) : BOOL;
function Toolbar_SetButtonSize( Toolbar : HWND; Width, Height : word ) : BOOL;
function Toolbar_SetButtonState( Toolbar : HWND; idButton, State : integer ) : BOOL;
function Toolbar_SetButtonWidth( Toolbar : HWND; idButton : integer; MinWidth, MaxWidth : word ) : BOOL;
function Toolbar_SetCmdId( Toolbar : HWND; idxButton, idButton : integer ) : BOOL;
function Toolbar_SetDisabledImageList( Toolbar : HWND ) : HIMAGELIST;
function Toolbar_SetHotImageList( Toolbar : HWND; ImageList : HIMAGELIST ) : HIMAGELIST;
function Toolbar_SetImageList( Toolbar : HWND; ImageList : HIMAGELIST ) : BOOL;
function Toolbar_SetMaxTextRows( Toolbar : HWND; MaxTextRows : integer ) : BOOL;
function Toolbar_SetParent( Toolbar : HWND; Parent : HWND ) : BOOL;
function Toolbar_SetRows( Toolbar : HWND; Larger : wordbool; RowCount : integer; var Rect : TRect ) : BOOL;
function Toolbar_SetStyle( Toolbar : HWND; NewStyle : integer ) : BOOL;
function Toolbar_SetToolTips( Toolbar : HWND; ToolTips : HWND ) : BOOL;
//====== REBAR CONTROL ========================================================
const
REBARCLASSNAMEA = 'ReBarWindow32';
const
REBARCLASSNAME = REBARCLASSNAMEA;
const
RBIM_IMAGELIST = $00000001;
const
RBS_TOOLTIPS = $00000100;
RBS_VARHEIGHT = $00000200;
RBS_BANDBORDERS = $00000400;
RBS_FIXEDORDER = $00000800;
type
TRebarInfo =
packed record
cbSize : word;
fMask : word;
himl : HIMAGELIST;
end;
const
RBBS_BREAK = $00000001; // break to new line
RBBS_FIXEDSIZE = $00000002; // band can't be sized
RBBS_CHILDEDGE = $00000004; // edge around top & bottom of child window
RBBS_HIDDEN = $00000008; // don't show
RBBS_NOVERT = $00000010; // don't show when vertical
RBBS_FIXEDBMP = $00000020; // bitmap doesn't move during band resize
const
RBBIM_STYLE = $00000001;
RBBIM_COLORS = $00000002;
RBBIM_TEXT = $00000004;
RBBIM_IMAGE = $00000008;
RBBIM_CHILD = $00000010;
RBBIM_CHILDSIZE = $00000020;
RBBIM_SIZE = $00000040;
RBBIM_BACKGROUND = $00000080;
RBBIM_ID = $00000100;
type
TRebarBandInfoA =
packed record
cbSize : word;
fMask : word;
fStyle : word;
clrFore : TColorRef;
clrBack : TColorRef;
lpText : pchar;
cch : word;
iImage : integer;
hwndChild : HWND;
cxMinChild : word;
cyMinChild : word;
cx : word;
hbmBack : HBITMAP;
wID : word;
end;
type
TRebarBandInfo = TRebarBandInfoA;
const
RB_INSERTBANDA = WM_USER + 1;
RB_DELETEBAND = WM_USER + 2;
RB_GETBARINFO = WM_USER + 3;
RB_SETBARINFO = WM_USER + 4;
RB_GETBANDINFO = WM_USER + 5;
RB_SETBANDINFOA = WM_USER + 6;
RB_SETPARENT = WM_USER + 7;
RB_INSERTBANDW = WM_USER + 10;
RB_SETBANDINFOW = WM_USER + 11;
RB_GETBANDCOUNT = WM_USER + 12;
RB_GETROWCOUNT = WM_USER + 13;
RB_GETROWHEIGHT = WM_USER + 14;
RB_INSERTBAND = RB_INSERTBANDA;
RB_SETBANDINFO = RB_SETBANDINFOA;
const
RBN_HEIGHTCHANGE = RBN_FIRST - 0;
//====== COMMON CONTROL STYLES ================================================
const
CCS_VERT = $00000080;
CCS_LEFT = CCS_VERT or CCS_TOP;
CCS_RIGHT = CCS_VERT or CCS_BOTTOM;
CCS_NOMOVEX = CCS_VERT or CCS_NOMOVEY;
//====== TrackMouseEvent =====================================================
const
WM_MOUSEHOVER = $02A1;
WM_MOUSELEAVE = $02A3;
const
TME_HOVER = $00000001;
TME_LEAVE = $00000002;
TME_QUERY = $40000000;
TME_CANCEL = $80000000;
const
HOVER_DEFAULT = $FFFFFFF;
type
PTrackMouseEvent = ^TTrackMouseEvent;
TTrackMouseEvent =
packed record
cbSize : longint;
dwFlags : longint;
hwndTrack : HWND;
dwHoverTime : longint;
end;
// Declare _TrackMouseEvent. This API tries to use the window manager's
// implementation of TrackMouseEvent if it is present, otherwise it emulates.
function _TrackMouseEvent( lpEventTrack : PTRACKMOUSEEVENT ) : BOOL; stdcall;
implementation
function InitCommonControlsEx( icc : PINITCOMMONCONTROLSEX ) : BOOL;
external cctrl name 'InitCommonControlsEx';
function ImageList_SetImageCount( himl : HIMAGELIST;
uNewCount : word ) : BOOL;
external cctrl name 'ImageList_SetImageCount';
function ImageList_DrawIndirect( pimldp : PIMAGELISTDRAWPARAMS ) : BOOL;
external cctrl name 'ImageList_DrawIndirect';
function ImageList_Copy( himlDst : HIMAGELIST; iDst : integer; himlSrc : HIMAGELIST; iSrc : integer; uFlags : word ) : BOOL;
external cctrl name 'ImageList_Copy';
function _TrackMouseEvent( lpEventTrack : PTRACKMOUSEEVENT ) : BOOL;
external cctrl name '_TrackMouseEvent';
function Toolbar_EnableButton( Toolbar : HWND; idButton : integer; Enabled : BOOL ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_ENABLEBUTTON, idButton, longint(Enabled) ) );
end;
function Toolbar_CheckButton( Toolbar : HWND; idButton : integer; Checked : BOOL ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_CHECKBUTTON, idButton, longint(Checked) ) );
end;
function Toolbar_PressButton( Toolbar : HWND; idButton : integer; Pressed : BOOL ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_PRESSBUTTON, idButton, longint(Pressed) ) );
end;
function Toolbar_HideButton( Toolbar : HWND; idButton : integer; Shown : BOOL ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_HIDEBUTTON, idButton, longint(Shown) ) );
end;
function Toolbar_IndeterminateButton ( Toolbar : HWND; idButton : integer; Indeterminate : BOOL ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_INDETERMINATE, idButton, longint(Indeterminate) ) );
end;
function Toolbar_IsButtonEnabled( Toolbar : HWND; idButton : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_ISBUTTONENABLED, idButton, 0 ) );
end;
function Toolbar_IsButtonChecked( Toolbar : HWND; idButton : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_ISBUTTONCHECKED, idButton, 0 ) );
end;
function Toolbar_IsButtonPressed( Toolbar : HWND; idButton : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_ISBUTTONPRESSED, idButton, 0 ) );
end;
function Toolbar_IsButtonHidden( Toolbar : HWND; idButton : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_ISBUTTONHIDDEN, idButton, 0 ) );
end;
function Toolbar_IsButtonIndeterminate( Toolbar : HWND; idButton : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_ISBUTTONINDETERMINATE, idButton, 0 ) );
end;
function Toolbar_SetButtonState( Toolbar : HWND; idButton, State : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETSTATE, idButton, State ) );
end;
function Toolbar_GetButtonState( Toolbar : HWND; idButton : integer ) : integer;
begin
Result := integer( SendMessage( Toolbar, TB_GETSTATE, idButton, 0 ) );
end;
function Toolbar_AddBitmap( Toolbar : HWND; ButtonCount : integer; Data : PTBAddBitmap ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_ADDBITMAP, ButtonCount, longint(Data) ) );
end;
function Toolbar_SetImageList( Toolbar : HWND; ImageList : HIMAGELIST ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETIMAGELIST, 0, ImageList ) );
end;
function Toolbar_GetImageList( Toolbar : HWND ) : HIMAGELIST;
begin
Result := HIMAGELIST( SendMessage( Toolbar, TB_GETIMAGELIST, 0, 0 ) );
end;
function Toolbar_LoadImages( Toolbar : HWND; hInst, idBitmap : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_LOADIMAGES, idBitmap, hInst ) );
end;
function Toolbar_GetRect( Toolbar : HWND; idButton : integer; var Rect : TRect ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_GETRECT, idButton, longint(@Rect) ) );
end;
function Toolbar_SetHotImageList( Toolbar : HWND; ImageList : HIMAGELIST ) : HIMAGELIST;
begin
Result := HIMAGELIST( SendMessage( Toolbar, TB_SETHOTIMAGELIST, 0, ImageList ) );
end;
function Toolbar_GetHotImageList( Toolbar : HWND ) : HIMAGELIST;
begin
Result := HIMAGELIST( SendMessage( Toolbar, TB_GETHOTIMAGELIST, 0, 0 ) );
end;
function Toolbar_SetDisabledImageList( Toolbar : HWND ) : HIMAGELIST;
begin
Result := HIMAGELIST( SendMessage( Toolbar, TB_SETDISABLEDIMAGELIST, 0, 0 ) );
end;
function Toolbar_GetDisabledImageList( Toolbar : HWND ) : HIMAGELIST;
begin
Result := HIMAGELIST( SendMessage( Toolbar, TB_GETDISABLEDIMAGELIST, 0, 0 ) );
end;
function Toolbar_SetStyle( Toolbar : HWND; NewStyle : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETSTYLE, 0, NewStyle ) );
end;
function Toolbar_GetStyle( Toolbar : HWND ) : integer;
begin
Result := integer( SendMessage( Toolbar, TB_GETSTYLE, 0, 0 ) );
end;
function Toolbar_GetButtonSize( Toolbar : HWND ) : TPoint;
var
Size : integer;
begin
Size := integer( SendMessage( Toolbar, TB_GETBUTTONSIZE, 0, 0 ) );
Result := Point( word( Size ), Size shr 16 );
end;
function Toolbar_SetButtonWidth( Toolbar : HWND; idButton : integer; MinWidth, MaxWidth : word ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETBUTTONWIDTH, 0, MaxWidth shl 16 or MinWidth ) );
end;
function Toolbar_SetMaxTextRows( Toolbar : HWND; MaxTextRows : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETMAXTEXTROWS, MaxTextRows, 0 ) );
end;
function Toolbar_GetTextRows( Toolbar : HWND ) : integer;
begin
Result := integer( SendMessage( Toolbar, TB_GETTEXTROWS, 0, 0 ) );
end;
function Toolbar_GetButtonText( Toolbar : HWND; idButton : integer ) : string;
var
Length : integer;
begin
SetLength( Result, MAX_PATH );
Length := SendMessage( Toolbar, TB_GETBUTTONTEXT, idButton, longint( pchar(Result) ) );
SetLength( Result, Length );
end;
function Toolbar_SaveRestore( Toolbar : HWND; Save : BOOL; Params : TTBSaveParams ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SAVERESTORE, longint( Save ), longint( @Params ) ) );
end;
function Toolbar_AddString( Toolbar : HWND; hInst, idString : integer ) : integer;
begin
Result := integer( SendMessage( Toolbar, TB_ADDSTRING, hInst, idString ) );
end;
function Toolbar_AddButtons( Toolbar : HWND; ButtonCount : integer; var Buttons ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_ADDBUTTONS, ButtonCount, longint( @Buttons ) ) );
end;
function Toolbar_InsertButton( Toolbar : HWND; idButton : integer; ButtonData : PTBButton ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_INSERTBUTTON, idButton, longint( ButtonData ) ) );
end;
function Toolbar_DeleteButton( Toolbar : HWND; idButton : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_DELETEBUTTON, idButton, 0 ) );
end;
function Toolbar_GetButton( Toolbar : HWND; idButton : integer; var ButtonData : TTBButton ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_GETBUTTON, idButton, longint( @ButtonData ) ) );
end;
function Toolbar_ButtonCount( Toolbar : HWND ) : integer;
begin
Result := integer( SendMessage( Toolbar, TB_BUTTONCOUNT, 0, 0 ) );
end;
function Toolbar_CommandToIndex( Toolbar : HWND; idButton : integer ) : integer;
begin
Result := integer( SendMessage( Toolbar, TB_COMMANDTOINDEX, idButton, 0 ) );
end;
function Toolbar_Customize( Toolbar : HWND ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_CUSTOMIZE, 0, 0 ) );
end;
function Toolbar_GetItemRect( Toolbar : HWND; idButton : integer; var Rect : TRect ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_GETITEMRECT, idButton, longint( @Rect ) ) );
end;
function Toolbar_ButtonStructSize( Toolbar : HWND; StructSize : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_BUTTONSTRUCTSIZE, StructSize, 0 ) );
end;
function Toolbar_SetButtonSize( Toolbar : HWND; Width, Height : word ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETBUTTONSIZE, 0, (Height shl 16) or Width ) );
end;
function Toolbar_SetBitmapSize( Toolbar : HWND; Width, Height : word ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETBITMAPSIZE, 0, (Height shl 16) or Width ) );
end;
function Toolbar_AutoSize( Toolbar : HWND ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_AUTOSIZE, 0, 0 ) );
end;
(*
function Toolbar_SetButtonType( Toolbar : HWND ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETBUTTONTYPE
end;
*)
function Toolbar_GetToolTips( Toolbar : HWND ) : HWND;
begin
Result := HWND( SendMessage( Toolbar, TB_GETTOOLTIPS, 0, 0 ) );
end;
function Toolbar_SetToolTips( Toolbar : HWND; ToolTips : HWND ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETTOOLTIPS, ToolTips, 0 ) );
end;
function Toolbar_SetParent( Toolbar : HWND; Parent : HWND ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETPARENT, Parent, 0 ) );
end;
function Toolbar_SetRows( Toolbar : HWND; Larger : wordbool; RowCount : integer; var Rect : TRect ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETROWS, (word(Larger) shl 16) or RowCount, longint( @Rect ) ) );
end;
function Toolbar_GetRows( Toolbar : HWND ) : integer;
begin
Result := integer( SendMessage( Toolbar, TB_GETROWS, 0, 0 ) );
end;
function Toolbar_SetCmdId( Toolbar : HWND; idxButton, idButton : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_SETCMDID, idxButton, idButton ) );
end;
function Toolbar_ChangeBitmap( Toolbar : HWND; idButton, idxBitmap : integer ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_CHANGEBITMAP, idButton, idxBitmap ) );
end;
function Toolbar_GetBitmap( Toolbar : HWND; idButton : integer ) : integer;
begin
Result := integer( SendMessage( Toolbar, TB_GETBITMAP, idButton, 0 ) );
end;
function Toolbar_GetBitmapFlags( Toolbar : HWND ) : BOOL;
begin
Result := BOOL( SendMessage( Toolbar, TB_GETBITMAPFLAGS, 0, 0 ) );
end;
end.
(*
MenuHelp
ShowHideMenuCtl
GetEffectiveClientRect
DrawStatusTextA
CreateStatusWindowA
CreateToolbar
CreateMappedBitmap
Cctl1632_ThunkData32
CreatePropertySheetPage
CreatePropertySheetPageA
CreatePropertySheetPageW
MakeDragList
LBItemFromPt
DrawInsert
CreateUpDownControl
InitCommonControls
CreateStatusWindow
CreateStatusWindowW
CreateToolbarEx
DestroyPropertySheetPage
DllGetVersion
DrawStatusText
DrawStatusTextW
ImageList_Add
ImageList_AddIcon
ImageList_AddMasked
ImageList_BeginDrag
ImageList_Copy
ImageList_Create
ImageList_Destroy
ImageList_DragEnter
ImageList_DragLeave
ImageList_DragMove
ImageList_DragShowNolock
ImageList_Draw
ImageList_DrawEx
ImageList_EndDrag
ImageList_GetBkColor
ImageList_GetDragImage
ImageList_GetIcon
ImageList_GetIconSize
ImageList_GetImageCount
ImageList_GetImageInfo
ImageList_GetImageRect
ImageList_LoadImage
ImageList_LoadImageA
ImageList_LoadImageW
ImageList_Merge
ImageList_Read
ImageList_Remove
ImageList_Replace
ImageList_ReplaceIcon
ImageList_SetBkColor
ImageList_SetDragCursorImage
ImageList_SetFilter
ImageList_SetIconSize
ImageList_SetImageCount
ImageList_SetOverlayImage
ImageList_Write
InitCommonControlsEx
PropertySheet
PropertySheetA
PropertySheetW
_TrackMouseEvent
*)
|
{ *************************************************************************** }
{ }
{ }
{ Copyright (C) Amarildo Lacerda }
{ }
{ https://github.com/amarildolacerda }
{ }
{ }
{ *************************************************************************** }
{ }
{ 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. }
{ }
{ *************************************************************************** }
{
Objetivo: é um gerenciador de componentes de configura a serem persistindo
localmente pro INI ou JSON
Alterações:
02/04/2017 - por: amarildo lacerda
+ Adicionado suporte a JsonFile para a gravação dos dados
+ Adicionado interface para IniFile e JSONFile
}
unit MVCBr.ObjectConfigList;
interface
uses System.Classes, System.SysUtils, System.RTTI,
System.JsonFiles, System.IniFiles,
{$IFDEF LINUX} {$ELSE}VCL.StdCtrls, VCL.Controls, {$ENDIF} MVCBr.Model,
System.Generics.Collections;
type
{$IFDEF LINUX}
TButton = TComponent;
TGroupBox = TComponent;
TComboBox = class(TComponent)
public
text: string;
end;
TLabel = class(TComponent)
public
Caption: string;
end;
TCheckBox = class(TComponent)
public
checked: boolean;
end;
TEdit = class(TComponent)
public
text: string;
end;
{$ENDIF}
TObjectConfigContentType = (ctIniFile, ctJsonFile);
IObjectConfigListItem = interface;
IObjectConfigList = interface
['{302562A0-2A11-43F6-A249-4BD42E1133F2}']
function This: TObject;
procedure ReadConfig;
procedure WriteConfig;
procedure RegisterControl(ASection: string; AText: string; AControl:
{$IFDEF LINUX} TComponent {$ELSE} TControl{$ENDIF}); overload;
procedure Add(AControl: {$IFDEF LINUX} TComponent
{$ELSE} TControl{$ENDIF}); overload;
procedure SetFileName(const Value: string);
function GetFileName: string;
property FileName: string read GetFileName write SetFileName;
function Count: integer;
function GetItems(idx: integer): IObjectConfigListItem;
procedure SetItems(idx: integer; const Value: IObjectConfigListItem);
property Items[idx: integer]: IObjectConfigListItem read GetItems
write SetItems;
end;
TObjectConfigListItem = class;
IObjectConfigListItem = interface
['{AD786625-5C1A-4486-B000-2F61BB0C0A27}']
function This: TObjectConfigListItem;
procedure SetSection(const Value: string);
procedure SetItem(const Value: string);
procedure SetValue(const Value: TValue);
function GetValue: TValue;
function GetItem: string;
function GetSection: string;
property Section: string read GetSection write SetSection;
property Item: string read GetItem write SetItem;
property Value: TValue read GetValue write SetValue;
end;
IConfigFile = interface
['{136C5B69-9402-4B25-A772-A6425DBF16DD}']
function ReadString(const Section, Ident, Default: string): string;
procedure WriteString(const Section, Ident, Value: String);
procedure WriteDateTime(const Section, Ident: string; Value: TDateTime);
procedure WriteBool(const Section, Ident: string; Value: boolean);
procedure WriteInteger(const Section, Ident: string; Value: integer);
function ReadInteger(const Section, Ident: string;
Default: integer): integer;
function ReadBool(const Section, Ident: string; Default: boolean): boolean;
function ReadDatetime(const Section, Ident: string; Default: TDateTime)
: TDateTime;
function ConfigFile: TObject;
end;
TObjectConfigListItem = class(TInterfacedObject, IObjectConfigListItem)
private
FControl: {$IFDEF LINUX} TComponent {$ELSE} TControl{$ENDIF};
FSection: string;
FItem: string;
procedure SetSection(const Value: string);
procedure SetItem(const Value: string);
procedure SetValue(const Value: TValue);
function GetValue: TValue;
function GetItem: string;
function GetSection: string;
public
class function new(ASection, AItem: string; AControl:
{$IFDEF LINUX} TComponent
{$ELSE} TControl{$ENDIF}): IObjectConfigListItem;
property Section: string read GetSection write SetSection;
property Item: string read GetItem write SetItem;
property Value: TValue read GetValue write SetValue;
function This: TObjectConfigListItem;
end;
TConfigIniFile = class(TInterfacedObject, IConfigFile)
private
FIniFile: TIniFile;
public
constructor create(AFileName: string);
destructor destroy; override;
function ReadString(const Section, Ident, Default: string): string;
procedure WriteString(const Section, Ident, Value: String);
procedure WriteDateTime(const Section, Ident: string; Value: TDateTime);
procedure WriteBool(const Section, Ident: string; Value: boolean);
procedure WriteInteger(const Section, Ident: string; Value: integer);
function ReadInteger(const Section, Ident: string;
Default: integer): integer;
function ReadBool(const Section, Ident: string; Default: boolean): boolean;
function ReadDatetime(const Section, Ident: string; Default: TDateTime)
: TDateTime;
function ConfigFile: TObject;
end;
TConfigJsonFile = class(TInterfacedObject, IConfigFile)
private
FJsonFile: TJsonFile;
public
constructor create(AFileName: string);
destructor destroy; override;
function ReadString(const Section, Ident, Default: string): string;
procedure WriteString(const Section, Ident, Value: String);
procedure WriteDateTime(const Section, Ident: string; Value: TDateTime);
procedure WriteBool(const Section, Ident: string; Value: boolean);
procedure WriteInteger(const Section, Ident: string; Value: integer);
function ReadInteger(const Section, Ident: string;
Default: integer): integer;
function ReadBool(const Section, Ident: string; Default: boolean): boolean;
function ReadDatetime(const Section, Ident: string; Default: TDateTime)
: TDateTime;
function ConfigFile: TObject;
end;
TObjectConfigModel = class(TModelFactory, IObjectConfigList)
private
FList: TInterfaceList;
FFileName: string;
FProcRead: TProc<IObjectConfigListItem>;
FProcWrite: TProc<IObjectConfigListItem>;
FContentFile: IConfigFile;
FContentType: TObjectConfigContentType;
FComponentFullPath: boolean;
function GetItems(idx: integer): IObjectConfigListItem;
procedure SetItems(idx: integer; const Value: IObjectConfigListItem);
Function GetContentFile: IConfigFile;
procedure SetFileName(const Value: string);
function GetFileName: string;
procedure SetContentType(const Value: TObjectConfigContentType);
procedure SetComponentFullPath(const Value: boolean);
public
constructor create;
destructor destroy; override;
function This: TObject;
class function new: IObjectConfigList;
property ContentType: TObjectConfigContentType read FContentType
write SetContentType;
procedure ReadConfig; virtual;
procedure WriteConfig; virtual;
function Count: integer;
property Items[idx: integer]: IObjectConfigListItem read GetItems
write SetItems;
procedure RegisterControl(ASection: string; AText: string; AControl:
{$IFDEF LINUX} TComponent {$ELSE} TControl{$ENDIF}); overload; virtual;
procedure Add(AControl: {$IFDEF LINUX} TComponent
{$ELSE} TControl{$ENDIF}); overload; virtual;
property FileName: string read GetFileName write SetFileName;
procedure WriteItem(ASection, AItem: string; AValue: TValue); virtual;
procedure ReadItem(ASection, AItem: string; out AValue: TValue); virtual;
property ComponentFullPath: boolean read FComponentFullPath
write SetComponentFullPath;
function ToString:String;
end;
implementation
type
TValueHelper = record helper for TValue
function isBoolean: boolean;
function isDatetime: boolean;
end;
{ TObjectConfig }
function TObjectConfigModel.Count: integer;
begin
result := FList.Count;
end;
constructor TObjectConfigModel.create;
begin
FComponentFullPath := false;
FContentType := ctJsonFile;
FList := TInterfaceList.create;
FFileName := paramStr(0) + '.config';
FProcRead := procedure(sender: IObjectConfigListItem)
var
FOut: TValue;
begin
FOut := sender.Value;
ReadItem(sender.Section, sender.Item, FOut);
sender.Value := FOut;
end;
FProcWrite := procedure(sender: IObjectConfigListItem)
begin
WriteItem(sender.Section, sender.Item, sender.Value);
end;
end;
destructor TObjectConfigModel.destroy;
begin
FList.DisposeOf;
inherited;
end;
function TObjectConfigModel.GetFileName: string;
begin
result := FFileName;
end;
{$D+}
Function TObjectConfigModel.GetContentFile: IConfigFile;
begin
if not assigned(FContentFile) then
case ContentType of
ctIniFile:
FContentFile := TConfigIniFile.create(FFileName);
ctJsonFile:
FContentFile := TConfigJsonFile.create(FFileName);
end;
result := FContentFile;
end;
{$D-}
function TObjectConfigModel.GetItems(idx: integer): IObjectConfigListItem;
begin
result := FList.Items[idx] as IObjectConfigListItem;
end;
class function TObjectConfigModel.new: IObjectConfigList;
begin
result := TObjectConfigModel.create;
end;
procedure TObjectConfigModel.ReadConfig;
var
i: integer;
begin
if FContentType = ctJsonFile then
TJsonFile(GetContentFile.ConfigFile).LoadValues;
if assigned(FProcRead) then
for i := 0 to FList.Count - 1 do
FProcRead(FList.Items[i] as IObjectConfigListItem);
end;
procedure TObjectConfigModel.ReadItem(ASection, AItem: string;
out AValue: TValue);
begin
with GetContentFile do
if AValue.isBoolean then
AValue := ReadBool(ASection, AItem, AValue.AsBoolean)
else if AValue.isDatetime then
AValue := ReadDatetime(ASection, AItem, AValue.AsExtended)
else
AValue := ReadString(ASection, AItem, AValue.AsString);
end;
procedure TObjectConfigModel.Add(AControl: {$IFDEF LINUX} TComponent
{$ELSE} TControl{$ENDIF});
var
LItem: string;
begin
if FComponentFullPath then
LItem := AControl.className + '.' + AControl.name
else
LItem := AControl.name;
RegisterControl('Config', LItem, AControl);
end;
procedure TObjectConfigModel.RegisterControl(ASection: string; AText: string;
AControl: {$IFDEF LINUX} TComponent
{$ELSE} TControl{$ENDIF});
var
obj: TObjectConfigListItem;
begin
obj := TObjectConfigListItem.create;
obj.Section := ASection;
obj.Item := AText;
obj.FControl := AControl;
FList.Add(obj);
end;
procedure TObjectConfigModel.SetComponentFullPath(const Value: boolean);
begin
FComponentFullPath := Value;
end;
procedure TObjectConfigModel.SetContentType(const Value
: TObjectConfigContentType);
begin
FContentFile := nil;
FContentType := Value;
end;
procedure TObjectConfigModel.SetFileName(const Value: string);
begin
FFileName := Value;
end;
procedure TObjectConfigModel.SetItems(idx: integer;
const Value: IObjectConfigListItem);
begin
FList.Items[idx] := Value;
end;
function TObjectConfigModel.This: TObject;
begin
result := self;
end;
function TObjectConfigModel.ToString: String;
begin
case ContentType of
ctIniFile: result := TConfigIniFile(FContentFile.ConfigFile).FIniFile.ToString ; { TODO: ??? }
ctJsonFile: result := TConfigJsonFile(FContentFile.ConfigFile).FJsonFile.ToJson ;
end;
end;
procedure TObjectConfigModel.WriteConfig;
var
i: integer;
begin
if assigned(FProcRead) then
for i := 0 to FList.Count - 1 do
FProcWrite(FList.Items[i] as IObjectConfigListItem);
if ContentType = ctJsonFile then
with TJsonFile(GetContentFile.ConfigFile) do
begin
FileName := self.FFileName;
UpdateFile;
end
else
with TIniFile(GetContentFile.ConfigFile) do
begin
//FileName := self.FFileName;
UpdateFile;
end;
end;
procedure TObjectConfigModel.WriteItem(ASection, AItem: string; AValue: TValue);
begin
with GetContentFile do
if AValue.isBoolean then
WriteBool(ASection, AItem, AValue.AsBoolean)
else if AValue.isDatetime then
WriteDateTime(ASection, AItem, AValue.AsExtended)
else
WriteString(ASection, AItem, AValue.AsString);
end;
{ TObjectConfigItem }
function TObjectConfigListItem.GetItem: string;
begin
result := FItem;
end;
function TObjectConfigListItem.GetSection: string;
begin
result := FSection;
end;
function TObjectConfigListItem.GetValue: TValue;
begin
result := nil;
if not assigned(FControl) then
exit;
if FControl.InheritsFrom(TEdit) then
result := TEdit(FControl).text
else if FControl.InheritsFrom(TCheckBox) then
result := TCheckBox(FControl).checked
else if FControl.InheritsFrom(TComboBox) then
result := TComboBox(FControl).text;
end;
class function TObjectConfigListItem.new(ASection, AItem: string; AControl:
{$IFDEF LINUX} TComponent
{$ELSE} TControl{$ENDIF}): IObjectConfigListItem;
var
obj: TObjectConfigListItem;
begin
obj := TObjectConfigListItem.create;
obj.FControl := AControl;
obj.FSection := ASection;
obj.FItem := AItem;
result := obj;
end;
procedure TObjectConfigListItem.SetItem(const Value: string);
begin
FItem := Value;
end;
procedure TObjectConfigListItem.SetSection(const Value: string);
begin
FSection := Value;
end;
procedure TObjectConfigListItem.SetValue(const Value: TValue);
begin
if FControl.InheritsFrom(TEdit) then
TEdit(FControl).text := Value.AsString
else if FControl.InheritsFrom(TCheckBox) then
TCheckBox(FControl).checked := Value.AsBoolean
else if FControl.InheritsFrom(TComboBox) then
TComboBox(FControl).text := Value.AsString;
end;
function TObjectConfigListItem.This: TObjectConfigListItem;
begin
result := self;
end;
function TValueHelper.isBoolean: boolean;
begin
result := TypeInfo = System.TypeInfo(boolean);
end;
function TValueHelper.isDatetime: boolean;
begin
result := TypeInfo = System.TypeInfo(TDateTime);
end;
{ TConfigIniFile }
constructor TConfigIniFile.create(AFileName: string);
begin
inherited create;
FIniFile := TIniFile.create(AFileName);
end;
destructor TConfigIniFile.destroy;
begin
FIniFile.free;
inherited;
end;
function TConfigIniFile.ReadBool(const Section, Ident: string;
Default: boolean): boolean;
begin
result := FIniFile.ReadBool(Section, Ident, Default);
end;
function TConfigIniFile.ReadDatetime(const Section, Ident: string;
Default: TDateTime): TDateTime;
begin
result := FIniFile.ReadDatetime(Section, Ident, Default);
end;
function TConfigIniFile.ReadInteger(const Section, Ident: string;
Default: integer): integer;
begin
result := FIniFile.ReadInteger(Section, Ident, Default);
end;
function TConfigIniFile.ReadString(const Section, Ident,
Default: string): string;
begin
result := FIniFile.ReadString(Section, Ident, Default);
end;
function TConfigIniFile.ConfigFile: TObject;
begin
result := FIniFile;
end;
procedure TConfigIniFile.WriteBool(const Section, Ident: string;
Value: boolean);
begin
FIniFile.WriteBool(Section, Ident, Value);
end;
procedure TConfigIniFile.WriteDateTime(const Section, Ident: string;
Value: TDateTime);
begin
FIniFile.WriteDateTime(Section, Ident, Value);
end;
procedure TConfigIniFile.WriteInteger(const Section, Ident: string;
Value: integer);
begin
FIniFile.WriteInteger(Section, Ident, Value);
end;
procedure TConfigIniFile.WriteString(const Section, Ident, Value: String);
begin
FIniFile.WriteString(Section, Ident, Value);
end;
{ TConfigJsonFile }
constructor TConfigJsonFile.create(AFileName: string);
begin
inherited create;
FJsonFile := TJsonFile.create(AFileName);
end;
destructor TConfigJsonFile.destroy;
begin
FJsonFile.free;
inherited;
end;
function TConfigJsonFile.ReadBool(const Section, Ident: string;
Default: boolean): boolean;
begin
result := FJsonFile.ReadBool(Section, Ident, Default);
end;
function TConfigJsonFile.ReadDatetime(const Section, Ident: string;
Default: TDateTime): TDateTime;
begin
result := FJsonFile.ReadDatetime(Section, Ident, Default);
end;
function TConfigJsonFile.ReadInteger(const Section, Ident: string;
Default: integer): integer;
begin
result := FJsonFile.ReadInteger(Section, Ident, Default);
end;
function TConfigJsonFile.ReadString(const Section, Ident,
Default: string): string;
begin
result := FJsonFile.ReadString(Section, Ident, Default);
end;
function TConfigJsonFile.ConfigFile: TObject;
begin
result := FJsonFile;
end;
procedure TConfigJsonFile.WriteBool(const Section, Ident: string;
Value: boolean);
begin
FJsonFile.WriteBool(Section, Ident, Value);
end;
procedure TConfigJsonFile.WriteDateTime(const Section, Ident: string;
Value: TDateTime);
begin
FJsonFile.WriteDateTime(Section, Ident, Value);
end;
procedure TConfigJsonFile.WriteInteger(const Section, Ident: string;
Value: integer);
begin
FJsonFile.WriteInteger(Section, Ident, Value);
end;
procedure TConfigJsonFile.WriteString(const Section, Ident, Value: String);
begin
FJsonFile.WriteString(Section, Ident, Value);
end;
end.
|
unit Model.FaixaPeso;
interface
type
TFaixaPeso = class
private
var
FID: System.Integer;
FPesoInicial: System.Double;
FPesoFinal: System.Double;
FLog: System.string;
public
property ID: System.Integer read FID write FID;
property PesoInicial: System.Double read FPesoInicial write FPesoInicial;
property PesoFinal: System.Double read FPesoFinal write FPesoFinal;
property Log: System.string read FLog write FLog;
constructor Create; overload;
constructor Create(pFID: System.Integer; pFPesoInicial: System.Double; pFPesoFinal: System.Double; pFLog: System.string);
overload;
end;
implementation
constructor TFaixaPeso.Create;
begin
inherited Create;
end;
constructor TFaixaPeso.Create(pFID: Integer; pFPesoInicial: Double; pFPesoFinal: Double; pFLog: string);
begin
FID := pFID;
FPesoInicial := pFPesoInicial;
FPesoFinal := pFPesoFinal;
FLog := pFLog;
end;
end.
|
UNIT playcmfu;
{
********************************************************************
*Unité pour controler les cartes Sound Blaster en Turbo-Pascal 6.0*
* en utilisant le Driver SBFMDRV.COM. *
********************************************************************
* (C) 1992 MICRO APPLICATION *
* Auteur : Axel Stolz *
********************************************************************
}
INTERFACE
USES Dos;
TYPE
CMFFileTyp = FILE;
CMFDataTyp = Pointer;
CMFHeader = RECORD { Structure d'un CMF-File-Headers }
CMFFileID : ARRAY[0..3] OF CHAR; { CMF file ID = 'CTMF' }
CMFVersion : WORD; { Numéro de version }
CMFInstrBlockOfs : WORD; { Offset pour Instrument }
CMFMusicBlockOfs : WORD; { Offset Titre musical }
CMFTickPerBeat : WORD; { "Ticks" pro Beat }
CMFClockTicksPS : WORD; { Timer-Clock-Rate }
CMFFileTitleOfs : WORD; { Offset Titre musical }
CMFComposerOfs : WORD; { Offset Music composer }
CMFMusicRemarkOfs : WORD; { Offset Remarques musicales}
CMFChannelsUsed : ARRAY[0..15] OF CHAR; { Nombre de canaux utilisés }
CMFInstrNumber : WORD; { Nombre d'instruments }
CMFBasicTempo : WORD; { Tempo musical de base }
END;
CONST
CMFToolVersion = 'v1.0';
VAR
CMFStatusByte : BYTE; { Variable pour CMF-Status }
CMFErrStat : WORD; { Variable pour CMF-Numéro d'erreur }
CMFDriverInstalled : BOOLEAN; { Flag, driver install, }
CMFDriverIRQ : WORD; { Numéros d'interruptions utilisés }
CMFSongPaused : BOOLEAN; { Flag, son stop, }
OldExitProc : Pointer; { Pointeur sur l'ancienne ExitProc }
PROCEDURE PrintCMFErrMessage;
FUNCTION CMFGetSongBuffer(VAR CMFBuffer : Pointer; CMFFile : STRING):BOOLEAN;
FUNCTION CMFFreeSongBuffer (VAR CMFBuffer : Pointer):BOOLEAN;
FUNCTION CMFInitDriver : BOOLEAN;
FUNCTION CMFGetVersion : WORD;
PROCEDURE CMFSetStatusByte;
FUNCTION CMFSetInstruments(VAR CMFBuffer : Pointer):BOOLEAN;
FUNCTION CMFSetSingleInstruments(VAR CMFInstrument:Pointer; No:WORD):BOOLEAN;
PROCEDURE CMFSetSysClock(Frequency : WORD);
PROCEDURE CMFSetDriverClock(Frequency : WORD);
PROCEDURE CMFSetTransposeOfs (Offset : INTEGER);
FUNCTION CMFPlaySong(VAR CMFBuffer : Pointer) : BOOLEAN;
FUNCTION CMFStopSong : BOOLEAN;
FUNCTION CMFResetDriver:BOOLEAN;
FUNCTION CMFPauseSong : BOOLEAN;
FUNCTION CMFContinueSong : BOOLEAN;
IMPLEMENTATION
TYPE
TypeCastTyp = ARRAY [0..6000] of Char;
VAR
Regs : Registers;
CMFIntern : ^CMFHeader; { Pointeur interne sur la structure CMF }
PROCEDURE PrintCMFErrMessage;
{
* ENTREE : aucune
* SORTIE : aucune
* FONCTION : Affiche ů l'écran sous forme texte, l'erreur SB venant
* de se produire sans modifier la valeur du Status.
}
BEGIN
CASE CMFErrStat OF
100 : Write(' Driver son SBFMDRV non trouvé ');
110 : Write(' Driver Reset sans succŐs ');
200 : Write(' FichierCMF non trouvé ');
210 : Write(' Espace mémoire insuffisant pour le fichier CMF ');
220 : Write(' Le fichier n''est pas au format CMF ');
300 : Write(' Erreur d''implémentation en mémoire ');
400 : Write(' Trop d''instruments définis ');
500 : Write(' Les données CMF ne peuvent pas łtre diffusées');
510 : Write(' Les données CMF ne peuvent pas łtre stoppées ');
520 : Write(' Les données CMF ne peuvent pas łtre interrompues ');
530 : Write(' Les données CMF ne peuvent pas łtre reprises ');
END;
END;
FUNCTION Exists (Filename : STRING):BOOLEAN;
{
* ENTRÉE : Nom de fichier sous forme chaîne de caractŐres
* SORTIE : TRUE si le fichier est présent, FALSE si non.
* FONCTION : Vérifie qu'un fichier est présent et retourne la valeur
booléenne correspondante.
}
VAR
F : File;
BEGIN
Assign(F,Filename);
{$I-}
Reset(F);
Close(F);
{$I+}
Exists := (IoResult = 0) AND (Filename <> '');
END;
PROCEDURE AllocateMem (VAR Pt : Pointer; Size : LongInt);
{
* ENTRÉE : Pointeur sur le buffer,taille du buffer sous forme entier
long.
* SORTIE : Pointeur sur le buffer, ou NIL.
* FONCTION : Réserve autant d'octets qu'indiqué dans la taille, et
positionne le pointeur sur le buffer ainsi constitué.
S'il n'y a pas suffisamment de mémoire, positionne le
pointeur sur NIL.
}
VAR
SizeIntern : WORD; { Taille du buffer pour calcul interne}
BEGIN
Inc(Size,15); { Augmenter la taille du buffer de 15 }
SizeIntern := (Size shr 4); { et diviser ensuite par 16 }
Regs.AH := $48; { Charger la fonction MSDOS $48 dans AH}
Regs.BX := SizeIntern; { Charger la taille interne dans BX }
MsDos(Regs); { Réserver la mémoire }
IF (Regs.BX <> SizeIntern) THEN Pt := NIL
ELSE Pt := Ptr(Regs.AX,0);
END;
FUNCTION CheckFreeMem (VAR CMFBuffer : Pointer; CMFSize : LongInt):BOOLEAN;
{
* ENTRÉE : Pointeur sur le buffer, longueur désirée sous forme d'entier
long.
* SORTIE : Pointeur sur le buffer, TRUE/FALSE suivant AllocateMem.
* FONCTION : Vérifie qu'il y a suffisamment de mémoire pour un fichier
CMF.
}
BEGIN
AllocateMem(CMFBuffer,CMFSize);
CheckFreeMem := CMFBuffer <> NIL;
END;
FUNCTION CMFGetSongBuffer(VAR CMFBuffer : Pointer; CMFFile : STRING):BOOLEAN;
{
* ENTRÉE : Pointeur sur le buffer, nom de fichier sous forme chaîne de
caractŐres.
* SORTIE : Pointeur sur le buffer contenant des données CMF, TRUE/FALSE
* FONCTION : Charge un fichier en mémoire et retourne le valeur TRUE en
cas de succŐs, ou sinon FALSE.
}
CONST
FileCheck : STRING[4] = 'CTMF';
VAR
CMFFileSize : LongInt;
FPresent : BOOLEAN;
VFile : CMFFileTyp;
Segs : WORD;
Read : WORD;
Checkcount : BYTE;
BEGIN
FPresent := Exists(CMFFile);
{ Le fichier CMF n'a pas été trouvé }
IF Not(FPresent) THEN BEGIN
CMFGetSongBuffer := FALSE;
CMFErrStat := 200;
EXIT
END;
Assign(VFile,CMFFile);
Reset(VFile,1);
CMFFileSize := Filesize(VFile);
AllocateMem(CMFBuffer,CMFFileSize);
{ Espace mémoire insuffisant pour le fichier CMF }
IF (CMFBuffer = NIL) THEN BEGIN
Close(VFile);
CMFGetSongBuffer := FALSE;
CMFErrStat := 210;
EXIT;
END;
Segs := 0;
REPEAT
Blockread(VFile,Ptr(seg(CMFBuffer^)+4096*Segs,Ofs(CMFBuffer^))^,$FFFF,Read);
Inc(Segs);
UNTIL Read = 0;
Close(VFile);
{ Le fichier n'est pas au format CMF }
CMFIntern := CMFBuffer;
CheckCount := 1;
REPEAT
IF FileCheck[CheckCount] = CMFIntern^.CMFFileID[CheckCount-1]
THEN Inc(CheckCount)
ELSE CheckCount := $FF;
UNTIL CheckCount >= 3;
IF NOT(CheckCount = 3) THEN BEGIN
CMFGetSongBuffer := FALSE;
CMFErrStat := 220;
EXIT;
END;
{ Le chargement a été correctement effectué }
CMFGetSongBuffer := TRUE;
CMFErrStat := 0;
END;
FUNCTION CMFFreeSongBuffer (VAR CMFBuffer : Pointer):BOOLEAN;
{
* ENTRÉE : Pointeur sur le buffer
* SORTIE : aucune
* FONCTION : LibŐre ů nouveau la mémoire occupée par les données CMF.
}
BEGIN
Regs.AH := $49; { MS-DOS Fonction $49 chargé dans AH }
Regs.ES := seg(CMFBuffer^); { Charger le segment dans ES }
MsDos(Regs); { Libérer la mémoire }
CMFFreeSongBuffer := TRUE;
IF (Regs.AX = 7) OR (Regs.AX = 9) THEN BEGIN
CMFFreeSongBuffer := FALSE;
CMFErrStat := 300 { Lors de la libération, est apparue }
END; { une erreur DOS }
END;
FUNCTION CMFInitDriver : BOOLEAN;
{
* ENTRÉE : aucune
* SORTIE : TRUE, si le driver a été trouvé et installé, FALSE sinon
* FONCTION : Vérifie que, SBFMDRV.COM est en mémoire, et effectue un Reset
* du driver
}
CONST
DriverCheck :STRING[5] = 'FMDRV'; { chaîne de caractŐre cherchée dans SBFMDRV }
VAR
ScanIRQ,
CheckCount : BYTE;
IRQPtr,
DummyPtr : Pointer;
BEGIN
{ Les interruptions possibles pour SBFMDRV vont de $80 ů $BF }
FOR ScanIRQ := $80 TO $BF DO BEGIN
GetIntVec(ScanIRQ, IRQPtr);
DummyPtr := Ptr(Seg(IRQPtr^), $102);
{ Vérifie que la chaîne FMDRV est présente dans le programme d'interruption }
{ Il s'agit alors de SBFMDRV }
CheckCount := 1;
REPEAT
IF DriverCheck[CheckCount] = TypeCastTyp(DummyPtr^)[CheckCount]
THEN Inc(CheckCount)
ELSE CheckCount := $FF;
UNTIL CheckCount >= 5;
IF (CheckCount = 5) THEN BEGIN
{ La chaîne de caractŐres a été trouvée, maintenant Reset sera effectué }
Regs.BX := 08;
CMFDriverIRQ := ScanIRQ;
Intr(CMFDriverIRQ, Regs);
IF Regs.AX = 0 THEN
CMFInitDriver := TRUE
ELSE BEGIN
CMFInitDriver := FALSE;
CMFErrStat := 110;
END;
Exit;
END
ELSE BEGIN
{ La chaîne de caractŐres n'a pas été trouvée }
CMFInitDriver := FALSE;
CMFErrStat := 100;
END;
END;
END;
FUNCTION CMFGetVersion : WORD;
{
* ENTRÉE : aucune
* SORTIE : Premier numéro de version dans l'octet de poids fort, second numéro
* l'octet de poids faible.
* FONCTION : Lit le numéro de version du driver SBFMDRV.
}
BEGIN
Regs.BX := 0;
Intr(CMFDriverIRQ,Regs);
CMFGetVersion := Regs.AX;
END;
PROCEDURE CMFSetStatusByte;
{
* ENTRÉE : aucune
* SORTIE : aucune
* FONCTION : Copie la valeur du Status du driver dans la variable
* CMFStatusByte. .
}
BEGIN
Regs.BX:= 1;
Regs.DX:= Seg(CMFStatusByte);
Regs.AX:= Ofs(CMFStatusByte);
Intr(CMFDriverIRQ, Regs);
END;
FUNCTION CMFSetInstruments(VAR CMFBuffer : Pointer):BOOLEAN;
{
* ENTRÉE : Pointeur sur le buffer de données CMF
* SORTIE : TRUE/FALSE, suivant que les instruments ont été positionnés
* correctement ou non
* FONCTION : Positionne les registres FM de la carte SB, sur les valeurs
d'instruments se trouvant dans le fichier CMF chargé.
}
BEGIN
CMFIntern := CMFBuffer;
IF CMFIntern^.CMFInstrNumber > 128 THEN BEGIN
CMFErrStat := 400;
CMFSetInstruments := FALSE;
Exit;
END;
Regs.BX := 02;
Regs.CX := CMFIntern^.CMFInstrNumber;
Regs.DX := Seg(CMFBuffer^);
Regs.AX := Ofs(CMFBuffer^)+CMFIntern^.CMFInstrBlockOfs;
Intr(CMFDriverIRQ, Regs);
CMFSetInstruments := TRUE;
END;
FUNCTION CMFSetSingleInstruments(VAR CMFInstrument:Pointer; No:WORD):BOOLEAN;
{
* ENTRÉE : Pointeur sur le buffer des données CMFInstrument,
nombre d'instruments sous forme WORD
* SORTIE : TRUE/FALSE, suivant que les instruments aient été positionnés
* correctement ou non
* FONCTION : Positionne les registres FM de la carte Sound Blaster sur les
valeurs d'instruments, suivant la structure de donnée repérée
par le pointeur CMFInstrument.
}
BEGIN
IF No > 128 THEN BEGIN
CMFErrStat := 400;
CMFSetSingleInstruments := FALSE;
Exit;
END;
Regs.BX := 02;
Regs.CX := No;
Regs.DX := Seg(CMFInstrument^);
Regs.AX := Ofs(CMFInstrument^);
Intr(CMFDriverIRQ, Regs);
CMFSetSingleInstruments := TRUE;
END;
PROCEDURE CMFSetSysClock(Frequency : WORD);
{
* ENTRÉE : System-Timer-Clock-Rate sous forme WORD
* SORTIE : aucune
* FONCTION : Positionne la valeur standard du Timer 0 ů une nouvelle
* valeur.
}
BEGIN
Regs.BX := 03;
Regs.AX := (1193180 DIV Frequency);
Intr(CMFDriverIRQ, Regs);
END;
PROCEDURE CMFSetDriverClock(Frequency : WORD);
{
* ENTRÉE : Timer-Clock-Rate sous forme WORD
* SORTIE : aucune
* FONCTION : Positionne la fréquence du Timer pour le driver ů une
* nouvelle valeur.
}
BEGIN
Regs.BX := 04;
Regs.AX := (1193180 DIV Frequency);
Intr(CMFDriverIRQ, Regs);
END;
PROCEDURE CMFSetTransposeOfs (Offset : INTEGER);
{
* ENTRÉE : Offset sous forme WORD. La valeur indique, de combien de
* demi-tons doivent łtre transposées les notes
* SORTIE : aucune
* FONCTION : Transpose toutes les notes d'une valeur égale ů "Offset",
* qui doivent łtre jouées.
}
BEGIN
Regs.BX := 05;
Regs.AX := Offset;
Intr(CMFDriverIRQ, Regs);
END;
FUNCTION CMFPlaySong(VAR CMFBuffer : Pointer) : BOOLEAN;
{
* ENTRÉE : Pointeur sur les données du morceau (Song)
* SORTIE : TRUE, lorsque cela a bien démarré, FALSE sinon
* FONCTION : Initialise tous les paramŐtres importants, et démarre la
* diffusion du morceau (Song).
}
VAR
Check : BOOLEAN;
BEGIN
CMFIntern := CMFBuffer;
{ Positionnement de la fréquence d'horloge du driver }
CMFSetDriverClock(CMFIntern^.CMFClockTicksPS);
{ Instrument }
Check := CMFSetInstruments(CMFBuffer);
IF Not(Check) THEN Exit;
Regs.BX := 06;
Regs.DX := Seg(CMFIntern^);
Regs.AX := Ofs(CMFIntern^)+CMFIntern^.CMFMusicBlockOfs;
Intr(CMFDriverIRQ, Regs);
IF Regs.AX = 0 THEN BEGIN
CMFPlaySong := TRUE;
CMFSongPaused := FALSE;
END
ELSE BEGIN
CMFPlaySong := FALSE;
CMFErrStat := 500;
END;
END;
FUNCTION CMFStopSong : BOOLEAN;
{
* ENTRÉE : Aucune
* SORTIE : TRUE/FALSE, suivant que le morceau ait été bien stoppé ou non
* FONCTION : Essaye de stopper un morceau (Song).
}
BEGIN
Regs.BX := 07;
Intr(CMFDriverIRQ, Regs);
IF Regs.AX = 0 THEN
CMFStopSong := TRUE
ELSE BEGIN
CMFStopSong := FALSE;
CMFErrStat := 510;
END;
END;
FUNCTION CMFResetDriver:BOOLEAN;
{
* ENTRÉE : aucune
* SORTIE : aucune
* FONCTION : Repositionne le driver dans l'état de départ.
}
BEGIN
Regs.BX := 08;
Intr(CMFDriverIRQ, Regs);
IF Regs.AX = 0 THEN
CMFResetDriver := TRUE
ELSE BEGIN
CMFResetDriver := FALSE;
CMFErrStat := 110;
END;
END;
FUNCTION CMFPauseSong : BOOLEAN;
{
* ENTRÉE : Aucune
* SORTIE : TRUE/FALSE, suivant que le morceau ait été bien interrompu ou
non
* FONCTION : Essaye d'interrompre un morceau, si cela est possible, la
variable globale CMFSongPaused sera positionnée sur TRUE.
}
BEGIN
Regs.BX := 09;
Intr(CMFDriverIRQ, Regs);
IF Regs.AX = 0 THEN BEGIN
CMFPauseSong := TRUE;
CMFSongPaused := TRUE;
END
ELSE BEGIN
CMFPauseSong := FALSE;
CMFErrStat := 520;
END;
END;
FUNCTION CMFContinueSong : BOOLEAN;
{
* ENTRÉE : Aucune
* SORTIE : TRUE/FALSE, suivant que la reprise du morceau a été correcte
ou non.
* FONCTION : Essaye de reprendre un morceau, quand cela est possible, la
variable CMFSongPaused sera positionnée sur FALSE.
}
BEGIN
Regs.BX := 10;
Intr(CMFDriverIRQ, Regs);
IF Regs.AX = 0 THEN BEGIN
CMFContinueSong := TRUE;
CMFSongPaused := FALSE;
END
ELSE BEGIN
CMFContinueSong := FALSE;
CMFErrStat := 530;
END;
END;
{$F+}
PROCEDURE CMFToolsExitProc;
{$F-}
{
* ENTRÉE : aucune
* SORTIE : aucune
* FONCTION : Repositionnement de l'adresse du StatusByte, afin d'empłcher
d'écrire n'importe oŚ en mémoire ů la fin du programme
du driver.
}
BEGIN
Regs.BX:= 1;
Regs.DX:= 0;
Regs.AX:= 0;
Intr(CMFDriverIRQ, Regs);
ExitProc := OldExitProc;
END;
BEGIN
{ Déplace l'ancien ExitProc sur la nouvelle Tool-Unit }
OldExitProc := ExitProc;
ExitProc := @CMFToolsExitProc;
{ Initialisation des Variables }
CMFErrStat := 0;
CMFSongPaused := FALSE;
{ Initialisation du Driver }
CMFDriverInstalled := CMFInitDriver;
IF CMFDriverInstalled THEN BEGIN
CMFStatusByte := 0;
CMFSetStatusByte;
END;
END. |
unit Utils;
interface
uses Windows, Messages, Classes, Forms, Dialogs, SysUtils, StrUtils, ShlObj, ShellApi, System.UITypes;
procedure ConvertFileToOEM(const FileName: string);
function isDigit(c: char): Boolean;
function isNumber(s: string): Boolean;
procedure log(s : string);
function leadingZero(n : string):string;
function filterName(name : string):string;
procedure about;
function GetTempDir: string;
function SpecialFolder(Folder: Integer): String;
function ChooseFolder:string;
implementation
uses Unit1;
function SpecialFolder(Folder: Integer): String;
var
SFolder : pItemIDList;
SpecialPath : Array[0..MAX_PATH] Of Char;
begin
SHGetSpecialFolderLocation(Form1.Handle, Folder, SFolder);
SHGetPathFromIDList(SFolder, SpecialPath);
Result := StrPas(SpecialPath);
end;
function BrowseDialogCallBack(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): integer stdcall;
var R: TRect;
tp: TPoint;
begin
if uMsg = BFFM_INITIALIZED then
begin
GetWindowRect(Wnd,R);
tp.x:=(screen.Width div 2)-(R.Right-R.Left) div 2;
tp.y:=(screen.Height div 2)-(R.Bottom-R.Top) div 2;
SetWindowPos(Wnd,HWND_TOP,tp.x,tp.y,R.Right-R.Left,R.Bottom-R.Top,SWP_SHOWWINDOW);
end;
Result := 0;
end;
function ChooseFolder:string;
var
BI: TBrowseInfo;
PIL: PItemIDList;
PathSelection : array[0..MAX_PATH] of Char;
begin
Result := '';
FillChar(BI,SizeOf(BrowseInfo),#0);
BI.hwndOwner := Form1.Handle;
BI.pszDisplayName := @PathSelection[0];
BI.lpszTitle := 'Choose a directory:';
BI.ulFlags := BIF_RETURNONLYFSDIRS or BIF_EDITBOX or $40;//BIF_BROWSEINCLUDEFILES;// ce dernier inclue dossiers et fichiers
BI.lpfn := BrowseDialogCallBack;
PIL := SHBrowseForFolder(BI);
if Assigned(PIL) then
if SHGetPathFromIDList(PIL, PathSelection) then
Result := string(PathSelection);
end;
function filterName(name : string):string;
begin
name := trim(name);
name := ReplaceText(name, ''', '''');
name := ReplaceText(name, '&#039;', '''');
name := ReplaceText(name, '/', '-');
name := ReplaceText(name, '\\', '-');
name := ReplaceText(name, '&', '&');
name := ReplaceText(name, ':', '-');
name := ReplaceText(name, '?', '');
name := ReplaceText(name, '(1/2)', '- 1st part');
name := ReplaceText(name, '(2/2)', '- 2nd part');
name := ReplaceText(name, '(3/2)', '- 3rd part');
name := ReplaceText(name, ' (2005)', '');
Result := name;
end;
function GetTempDir: string;
var
Buffer: array[0..MAX_PATH] of Char;
begin
GetTempPath(SizeOf(Buffer) - 1, Buffer);
Result := IncludeTrailingPathDelimiter(StrPas(Buffer));
end;
function leadingZero(n : string):string;
begin
if ((isNumber(n)) and (Length(n)=1)) then Result := '0' + n
else Result := n;
end;
procedure log(s : string);
var t : string;
begin
DateTimeToString(t, 'hh:nn:ss.zzz', now);
Form1.Memo1.Lines.Add('[' + t + '] - ' + s);
end;
procedure ConvertFileToOEM(const FileName: string);
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ms.LoadFromFile(FileName);
ms.Position := 0;
CharToOemBuffA(ms.Memory, ms.Memory, ms.Size);
ms.Position := 0;
ms.SaveToFile(FileName);
finally
ms.Free;
end;
end;
function isDigit(c: char): Boolean;
begin
result := ((ord(c) >= 48) and (ord(c) <= 57));
end;
function isNumber(s: string): Boolean;
var
i: Integer;
begin
i := 1;
while ((i <= Length(s)) and isDigit(s[i])) do
i := i + 1;
Result := (i > Length(s));
end;
procedure about;
begin
MessageDlg('TV Rename'+#13#10+'Coded By JcConvenant', mtInformation, [mbOK], 0);
end;
end.
|
{ 2020/05/11 5.01 Move tests from unit flcTests into seperate units. }
{$INCLUDE flcTCPTest.inc}
{$IFDEF TCPCLIENT_TEST}
{$DEFINE TCPCLIENT_TEST_WEB}
{$ENDIF}
unit flcTCPTest_Client;
interface
{$IFDEF TCPCLIENT_TEST}
uses
SysUtils,
SyncObjs,
flcStdTypes,
flcTCPClient;
{$ENDIF}
{$IFDEF TCPCLIENT_TEST}
{ }
{ TCP Client Test Object }
{ }
type
TTCPClientTestObj = class
States : array[TTCPClientState] of Boolean;
Connect : Boolean;
LogMsg : String;
Lock : TCriticalSection;
constructor Create;
destructor Destroy; override;
procedure ClientLog(Sender: TF5TCPClient; LogType: TTCPClientLogType; LogMsg: String; LogLevel: Integer);
procedure ClientConnect(Client: TF5TCPClient);
procedure ClientStateChanged(Client: TF5TCPClient; State: TTCPClientState);
end;
{ }
{ Test }
{ }
procedure Test;
{$ENDIF}
implementation
{$IFDEF TCPCLIENT_TEST}
uses
flcTCPConnection;
{$ENDIF}
{$IFDEF TCPCLIENT_TEST}
{$ASSERTIONS ON}
{ }
{ TCP Client Test Object }
{ }
constructor TTCPClientTestObj.Create;
begin
inherited Create;
Lock := TCriticalSection.Create;
end;
destructor TTCPClientTestObj.Destroy;
begin
FreeAndNil(Lock);
inherited Destroy;
end;
procedure TTCPClientTestObj.ClientLog(Sender: TF5TCPClient; LogType: TTCPClientLogType; LogMsg: String; LogLevel: Integer);
begin
{$IFDEF TCP_TEST_LOG_TO_CONSOLE}
Lock.Acquire;
try
Writeln(LogLevel:2, ' ', LogMsg);
finally
Lock.Release;
end;
{$ENDIF}
end;
procedure TTCPClientTestObj.ClientConnect(Client: TF5TCPClient);
begin
Connect := True;
end;
procedure TTCPClientTestObj.ClientStateChanged(Client: TF5TCPClient; State: TTCPClientState);
begin
States[State] := True;
end;
{ }
{ Test }
{ }
{$IFDEF TCPCLIENT_TEST_WEB}
procedure Test_Client_Web;
var
C : TF5TCPClient;
S : RawByteString;
A : TTCPClientTestObj;
begin
A := TTCPClientTestObj.Create;
C := TF5TCPClient.Create(nil);
try
// init
C.OnLog := A.ClientLog;
C.LocalHost := '0.0.0.0';
C.Host := 'www.google.com';
C.Port := '80';
C.OnStateChanged := A.ClientStateChanged;
C.OnConnected := A.ClientConnect;
C.WaitForStartup := True;
Assert(not C.Active);
Assert(C.State = csInit);
Assert(C.IsConnectionClosed);
Assert(not A.Connect);
// start
C.Active := True;
Assert(C.Active);
Assert(C.State <> csInit);
Assert(A.States[csStarting]);
Assert(C.IsConnectingOrConnected);
Assert(not C.IsConnectionClosed);
// wait connect
C.WaitForConnect(8000);
Assert(C.IsConnected);
Assert(C.State = csReady);
Assert(C.Connection.State = cnsConnected);
Assert(A.Connect);
Assert(A.States[csConnecting]);
Assert(A.States[csConnected]);
Assert(A.States[csReady]);
// send request
C.Connection.WriteByteString(
'GET / HTTP/1.1'#13#10 +
'Host: www.google.com'#13#10 +
'Date: 7 Nov 2013 12:34:56 GMT'#13#10 +
#13#10);
// wait response
C.BlockingConnection.WaitForReceiveData(1, 5000);
// read response
S := C.Connection.ReadByteString(C.Connection.ReadBufferUsed);
Assert(S <> '');
// close
C.Connection.Close;
C.WaitForClose(2000);
Assert(not C.IsConnected);
Assert(C.IsConnectionClosed);
Assert(C.Connection.State = cnsClosed);
// stop
C.Active := False;
Assert(not C.Active);
Assert(C.IsConnectionClosed);
finally
C.Finalise;
FreeAndNil(C);
A.Free;
end;
end;
{$ENDIF}
procedure Test;
begin
{$IFDEF TCPCLIENT_TEST_WEB}
Test_Client_Web;
{$ENDIF}
end;
{$ENDIF}
end.
|
unit DOSAPI;
interface
uses Crt;
function InputString(AX, AY, MaxLen: Integer; var AStr: string; ADisplay: Boolean): Boolean;
function InputInteger(AX, AY, MinVal, MaxVal: Integer; var AValue: Integer): Boolean;
implementation
function InputString(AX, AY, MaxLen: Integer; var AStr: string; ADisplay: Boolean): Boolean;
var Str: string;
Pos: Integer;
WindowWidth: Integer;
LastTextAttr: Byte;
procedure Draw;
var I: Integer;
begin
GotoXY(AX, AY);
TextAttr := 15;
for I := 1 to WindowWidth
do Write(' ');
GotoXY(AX + 1, AY);
Write(Str);
end;
procedure Display;
var I: Integer;
begin
GotoXY(AX, AY);
TextAttr := 15;
for I := 1 to WindowWidth
do Write(' ');
if ADisplay
then begin
TextAttr := 15;
GotoXY(AX + 1, AY);
Write(Str);
GotoXY(AX + Pos, AY)
end
else begin
TextAttr := 15;
GotoXY(AX + 1, AY);
for I := 1 to Length(Str)
do Write('*');
GotoXY(AX + Pos, AY);
end;
end;
function Edit: Boolean;
var Key: Char;
Update: Boolean;
begin
Key := ReadKey;
Update := False;
while ((Key <> #13) and (Key <> #27))
do begin
if Key in [#32..#127]
then begin
if Pos <= MaxLen
then begin
Str[Pos] := Key;
if Pos > Length(Str)
then begin
Str[0] := Char(Pos);
end;
Pos := Pos + 1;
Update := True;
end;
end
else begin
if (Key = #0)
then begin
Key := ReadKey;
end;
case Key
of #8: begin
if (Pos > 1)
then begin
Pos := Pos - 1;
Delete(Str,Pos,1);
Update := True;
end;
end;
#83: begin
if (Pos <= Length(Str))
then begin
Delete(Str,Pos,1);
Update := True;
end;
end;
#75: begin
if (Pos > 1)
then begin
Pos := Pos - 1;
Update := True;
end;
end;
#77: begin
if (Pos <= Length(Str))
then begin
Pos := Pos + 1;
Update := True;
end;
end;
end;
end;
if Update
then Display;
Key := ReadKey;
end;
if Key = #13
then begin
Edit := True;
AStr := Str;
end
else begin
Edit := False;
end;
end;
begin
{HideMouse;}
LastTextAttr := TextAttr;
WindowWidth := (MaxLen + 2);
if (Length(AStr) <= MaxLen)
then Str := AStr
else Str := Copy(AStr,1,MaxLen);
Pos := Length(Str) + 1;
Draw;
Display;
TextAttr := LastTextAttr;
InputString := Edit;
{ShowMouse;}
end;
function InputInteger(AX, AY, MinVal, MaxVal: Integer; var AValue: Integer): Boolean;
var S: string;
Accept: Boolean;
Value: Integer;
Code: Integer;
label
Input;
begin
Str(AValue, S);
Input:
Accept := InputString(AX, AY, 4, S, True);
if Accept
then begin
Val(S, Value, Code);
if ((Code <> 0) or (Value < MinVal) or (Value > MaxVal))
then goto Input;
AValue := Value;
end;
InputInteger := Accept;
end;
end. |
unit Const_SearchOptionUnit;
interface
const
STAGE_SEQ_NUM = 5;
STAGE_NAME_LIST: array[0..6] of String = (
'pumping',
'Heatup',
'Growth',
'Stabilization',
'Linear Decreasing',
'Decreasing',
'Cooling'
);
SOP_NAME_SEQ: array[0..6] of String = (
'table',
'columns',
'group',
'round',
'datetime',
'stage',
'stage_auto'
);
SOP_ITEM_SEQ: array[0..17] of String = (
'table.name',
'columns.datetime',
'datetime.split',
'columns.normal',
'columns.group',
'group.use',
'group.timeunit',
'group.func',
'round.use',
'round.decplace',
'stage.use',
'stage.start',
'stage.end',
'stage_auto.use',
'stage_auto.stagenum',
'stage_auto.tablename',
'stage_auto.stagecol',
'stage_auto.datecol'
);
{
0 = table_name
1 = datetime_column
2 = datetime_split
3 = columns
4 = columns.group
5 = group.use
6 = group.several
7 = group.func
8 = round.use
9 = round.decplace
10 = stage.use
11 = stage.start
12 = stage.end
13 = stage_log.use
14 = stage_log.num
15 = stage_log.name
16 = stage_log.stagecol
17 = stage_log.date
}
DATETIME_COLUMN_PATTERN: array[0..2] of String = ( 'date', 'time', 'stage' );
EVENT_LOG_TABLE: array[0..3] of String = ( 'journal', 'currstate', 'eventlog', 'alarmlog' );
ITEM_LIST_GROUP_TIMEUNIT_VIEW: array[0..21] of String = (
'5 sec', '10 sec', '15 sec', '20 sec', '30 sec', //5
'1 min', '2 min', '3 min', '4 min', '5 min', '6 min', '10 min', '15 min', '20 min', '30 min', //10
'1 hour', '2 hour', '3 hour', '4 hour', '6 hour', '8 hour', '12 hour' //7
);
ITEM_LIST_GROUP_TIMEUNIT_FACT: array[0..21] of Integer = (
5, 10, 15, 20, 30,
100, 200, 300, 400, 500, 600, 1000, 1500, 2000, 3000,
10000, 20000, 30000, 40000, 60000, 80000, 100000
);
ITEM_LIST_GROUP_FUNCTION: array[0..2] of String = (
'AVG', 'MIN', 'MAX'
);
ITEM_DEFAULT_GROUP_TIMEUNIT = '1 min';
ITEM_DEFAULT_GROUP_FUNCTION = 'AVG';
ITEM_LIST_ROUND_DECPLACE_MIN = 0;
ITEM_LIST_ROUND_DECPLACE_MAX = 7;
ITEM_LIST_ROUND_DECPLACE_DEF = ITEM_LIST_ROUND_DECPLACE_MAX;
ITEM_LIST_AUTO_STAGE_SEQ: array[0..4] of Integer = (
1, //heating
2, //growth
3, //Stabilization
4, //Linear Decreasing
5 //Decreasing
);
implementation
end.
|
unit ULiveContactsDemo;
interface
uses
FMX.TMSCloudBase, FMX.TMSCloudLiveContacts, FMX.Controls,
FMX.Edit, FMX.ExtCtrls, FMX.ListBox, FMX.StdCtrls, FMX.Grid, FMX.Layouts, SysUtils,
FMX.TMSCloudListView, FMX.Objects, System.Classes, FMX.Types, FMX.Forms,
FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomLive, FMX.TMSCloudLiveFMX,
FMX.TMSCloudCustomLiveContacts;
type
TForm1 = class(TForm)
StyleBook1: TStyleBook;
TMSFMXCloudLiveContacts1: TTMSFMXCloudLiveContacts;
Panel1: TPanel;
Button1: TButton;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label6: TLabel;
edFirstName: TEdit;
btAdd: TButton;
edLastName: TEdit;
cbGender: TComboBox;
CloudListView1: TTMSFMXCloudListView;
dpBirthDay: TCalendarEdit;
Label4: TLabel;
Image1: TImage;
btRemove: TButton;
procedure Button1Click(Sender: TObject);
procedure TMSFMXCloudLiveContacts1ReceivedAccessToken(Sender: TObject);
procedure btAddClick(Sender: TObject);
procedure GetContacts();
procedure ClearControls;
procedure ToggleControls;
procedure Init;
procedure FormCreate(Sender: TObject);
procedure btRemoveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Connected: boolean;
end;
var
Form1: TForm1;
implementation
{$R *.FMX}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// LiveAppkey = 'xxxxxxxxx';
// LiveAppSecret = 'yyyyyyyy';
{$I APPIDS.INC}
procedure TForm1.TMSFMXCloudLiveContacts1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudLiveContacts1.SaveTokens;
Init;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TMSFMXCloudLiveContacts1.App.Key := LiveAppkey;
TMSFMXCloudLiveContacts1.App.Secret := LiveAppSecret;
TMSFMXCloudLiveContacts1.Logging := true;
if not TMSFMXCloudLiveContacts1.TestTokens then
TMSFMXCloudLiveContacts1.RefreshAccess;
if not TMSFMXCloudLiveContacts1.TestTokens then
TMSFMXCloudLiveContacts1.DoAuth
else
Init;
end;
procedure TForm1.btAddClick(Sender: TObject);
var
li: TLiveContactItem;
begin
li := TMSFMXCloudLiveContacts1.Items.Add;
li.FirstName := edFirstName.Text;
li.LastName := edLastName.Text;
if cbGender.ItemIndex = 0 then
li.Gender := geNotSpecified
else if cbGender.ItemIndex = 1 then
li.Gender := geFemale
else if cbGender.ItemIndex = 2 then
li.Gender := geMale;
li.BirthDay := StrToInt(FormatDateTime('dd', dpBirthDay.Date));
li.BirthMonth := StrToInt(FormatDateTime('MM', dpBirthDay.Date));
TMSFMXCloudLiveContacts1.Add(li);
GetContacts;
ClearControls;
end;
procedure TForm1.btRemoveClick(Sender: TObject);
begin
TMSFMXCloudLiveContacts1.ClearTokens;
Connected := false;
ToggleControls;
end;
procedure TForm1.ClearControls;
begin
edFirstName.Text := '';
edLastName.Text := '';
cbGender.ItemIndex := 0;
dpBirthDay.Date := Now;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
TMSFMXCloudLiveContacts1.PersistTokens.Key := ExtractFilePath(ParamStr(0)) + 'live.ini';
TMSFMXCloudLiveContacts1.PersistTokens.Section := 'tokens';
TMSFMXCloudLiveContacts1.LoadTokens;
Connected := False;
ToggleControls;
ClearControls;
end;
procedure TForm1.GetContacts;
var
I: integer;
li: TListItem;
begin
TMSFMXCloudLiveContacts1.GetContacts;
CloudListView1.Items.Clear;
for I := 0 to TMSFMXCloudLiveContacts1.Items.Count - 1 do
begin
li := CloudListView1.Items.Add;
li.Text := TMSFMXCloudLiveContacts1.Items[I].FirstName + ' ' + TMSFMXCloudLiveContacts1.Items[I].LastName;
li.SubItems.Add(IntToStr(TMSFMXCloudLiveContacts1.Items[I].BirthDay) + '/' + IntToStr(TMSFMXCloudLiveContacts1.Items[I].BirthMonth));
if TMSFMXCloudLiveContacts1.Items[I].IsFavorite then
li.SubItems.Add('Yes')
else
li.SubItems.Add('No');
if TMSFMXCloudLiveContacts1.Items[I].Gender = geFemale then
li.SubItems.Add('Female')
else if TMSFMXCloudLiveContacts1.Items[I].Gender = geMale then
li.SubItems.Add('Male')
else
li.SubItems.Add('');
li.Data := TMSFMXCloudLiveContacts1.Items[I];
end;
end;
procedure TForm1.Init;
begin
Connected := True;
ToggleControls;
ClearControls;
GetContacts;
end;
procedure TForm1.ToggleControls;
begin
edFirstName.Enabled := Connected;
edLastName.Enabled := Connected;
cbGender.Enabled := Connected;
dpBirthDay.Enabled := Connected;
btAdd.Enabled := Connected;
btRemove.Enabled := Connected;
Button1.Enabled := not Connected;
end;
end.
|
unit uPrincipal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
uClasse.Veiculo.Terrestre.Caminhao,
uClasse.Veiculo.Terrestre.carro,
uClasse.Veiculo.Aereo.Aviao,
uClasse.Veiculo.Aereo.Helicoptero,
Vcl.ExtCtrls, Vcl.Buttons, Vcl.Samples.Spin, Vcl.ComCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
BtnPreencher: TButton;
EdTipo: TLabeledEdit;
EdMarca: TLabeledEdit;
EdKmRodados: TLabeledEdit;
EdLitrosConsumidos: TLabeledEdit;
Panel2: TPanel;
MemoExibicao: TMemo;
EdTara: TLabeledEdit;
BitBtn1: TBitBtn;
RgClasse: TRadioGroup;
EdDataUltimaTrocaOleo: TDateTimePicker;
Label1: TLabel;
EdDiasProximaTrocaOleo: TSpinEdit;
Label2: TLabel;
procedure BtnPreencherClick(Sender: TObject);
procedure RgClasseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.BtnPreencherClick(Sender: TObject);
Var
lCaminhao : TCaminhao;
begin
lCaminhao := TCaminhao.Create;
try
lCaminhao.Tipo := trim(EdTipo.Text); // propriedade da classe pai TVeiculo
lCaminhao.Marca := trim(EdMarca.Text); // propriedade da classe pai TVeiculo
lCaminhao.tara := StrToFloat(trim(EdTara.Text)); // propriedade da classe TCaminhao
lCaminhao.km_percorridos := StrToFloat(trim(EdKmRodados.Text));
lCaminhao.LitrosConsumidos := StrToFloat(trim(EdLitrosConsumidos.text));
lCaminhao.autonomia := lCaminhao.CalcularAutonomia(lCaminhao.km_percorridos, lCaminhao.LitrosConsumidos);
lCaminhao.DataUltimaTrocaOleo := EdDataUltimaTrocaOleo.DateTime;
lCaminhao.DiasMaximoProximaTrocaOleo := EdDiasProximaTrocaOleo.Value;
lCaminhao.DataProximaTrocaOleo := lCaminhao.RetornarProximaTrocaOleo;
MemoExibicao.Lines.Clear;
MemoExibicao.Lines.Add('Dados do veículo: ' + lCaminhao.Tipo + '.');
MemoExibicao.Lines.Add('Marca: ' + lCaminhao.Marca + '.');
MemoExibicao.Lines.Add('Autonomia: ' + FormatFloat('#.##0.00',lCaminhao.autonomia) + ' Km/L.');
MemoExibicao.Lines.Add('Tara: ' + FloatToStr(lCaminhao.tara) + '.');
MemoExibicao.Lines.Add('Km Percorridos: ' + FloatToStr(lCaminhao.km_percorridos) + '.');
MemoExibicao.Lines.Add('Litros consumidos: ' + FloatToStr(lCaminhao.LitrosConsumidos) + '.');
MemoExibicao.Lines.Add('Ao percorrer ' + FloatToStr(lCaminhao.km_percorridos) + ' km com ' +
FloatToStr(lCaminhao.LitrosConsumidos) + ' litros a autonomia foi de ' +
FormatFloat('#.##0.00',lCaminhao.autonomia) + ' km por litro.');
MemoExibicao.Lines.Add('');
MemoExibicao.Lines.Add('Data da última troca de óleo: ' + DateTimeToStr(lCaminhao.DataUltimaTrocaOleo));
MemoExibicao.Lines.Add('Qtde de dias para próxima troca de óleo: ' + IntToStr(lCaminhao.DiasMaximoProximaTrocaOleo));
MemoExibicao.Lines.Add('Data da próxima troca de óleo: ' + DateTimeToStr(lCaminhao.DataProximaTrocaOleo));
finally
lCaminhao.free;
end;
end;
procedure TForm1.RgClasseClick(Sender: TObject);
Var
lCaminhao: TCaminhao;
lCarro: TCarro;
lAviao: TAviao;
lHelicoptero: THelicoptero;
begin
lCaminhao := TCaminhao.Create;
lCarro := TCarro.Create;
lAviao := TAviao.Create;
lHelicoptero:= THelicoptero.Create;
try
case RgClasse.ItemIndex of
0: ShowMessage(lCaminhao.RetornaAplicacaoUso);
1: ShowMessage(lCarro.RetornaAplicacaoUso);
2: ShowMessage(lAviao.RetornaAplicacaoUso);
3: ShowMessage(lHelicoptero.RetornaAplicacaoUso);
end;
finally
lCaminhao.Free;
lCarro.Free;
lAviao.Free;
lHelicoptero.Free;
end;
end;
end.
|
unit CSWatchform;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, WinSockRDOConnection, RDOServer, RDOInterfaces, RDOObjectProxy;
type
TALSPFrm = class(TForm)
Panel1: TPanel;
Memo: TMemo;
Timer: TTimer;
procedure TimerTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
function ISAlive : integer;
function KillIS : boolean;
function RestartIS : boolean;
private
procedure LogThis( Msg : string );
private
fLaunchInertia : integer;
end;
var
ALSPFrm: TALSPFrm;
implementation
uses
StrUtils, Protocol, RemoteAdm, Logs;
{$R *.DFM}
function TALSPFrm.ISAlive : integer;
var
ISCnx : IRDOConnectionInit;
WSISCnx : TWinSockRDOConnection;
ISProxy : OleVariant;
UserCnt : integer;
begin
try
LogThis( 'Creating connection objects...' );
WSISCnx := TWinSockRDOConnection.Create('');
ISCnx := WSISCnx;
ISCnx.Server := paramstr(1);
ISCnx.Port := StrToInt(paramstr(2));
ISProxy := TRDOObjectProxy.Create as IDispatch;
LogThis( 'Establishing connection...' );
if ISCnx.Connect( 10000 )
then
begin
LogThis( 'Everything is OK!' );
result := 0;
{
LogThis( 'Connected!' );
ISProxy.SetConnection( ISCnx );
ISProxy.BindTo( WSObjectCacherName );
ISProxy.TimeOut := 20000;
LogThis( 'Performing routine checks...' );
try
UserCnt := ISProxy.UserCount;
if UserCnt > 0
then
begin
LogThis( 'Everything is OK!' );
result := 0;
end
else
begin
LogThis( 'Corrupted data from MS!' );
result := 3;
end;
except
LogThis( 'Checks failed!' );
result := 2;
end;
}
end
else
begin
LogThis( 'Connection failed!' );
result := 2
end;
except
LogThis( 'Unkown error.' );
result := -1;
end;
end;
function TALSPFrm.KillIS : boolean;
var
List : TStringList;
idx : integer;
ProcId : THandle;
begin
try
List := GetProcessList;
idx := List.IndexOf( 'FIVECacheServer.exe' );
if idx <> -1
then
begin
ProcId := integer(List.Objects[idx]);
StopProgram( ProcId, INFINITE );
end;
result := true;
except
result := false;
end;
end;
function TALSPFrm.RestartIS : boolean;
var
ProcId : THandle;
begin
try
result := RemoteAdm.StartProgram( 'FIVECacheServer.exe AUTORUN keep', ProcId )
except
result := false;
end;
end;
procedure TALSPFrm.TimerTimer(Sender: TObject);
begin
try
if fLaunchInertia = 0
then
begin
Memo.Lines.Add( '----------****-----------' );
if ISAlive <> 0
then
begin
Beep;
Beep;
Beep;
Beep;
Beep;
Beep;
Beep;
Beep;
Beep;
Beep;
if paramcount > 2
then
begin
LogThis( 'Performing double check:' );
if (ISAlive <> 0) and KillIS
then
if RestartIS
then
begin
LogThis( 'Cache Server successfully restarted!' );
fLaunchInertia := 3;
end
else LogThis( 'Error restarting Cache Server!' )
end
end;
end
else
begin
LogThis( 'Cache Server was recently launched. Still waiting...' );
dec( fLaunchInertia );
end;
except
end;
end;
procedure TALSPFrm.LogThis( Msg : string );
begin
Memo.Lines.Add( TimeToStr(Now) + ' - ' + Msg );
Logs.Log( 'General', TimeToStr(Now) + ' - ' + Msg );
end;
procedure TALSPFrm.FormCreate(Sender: TObject);
begin
if paramcount < 2
then halt(0);
end;
procedure TALSPFrm.FormShow(Sender: TObject);
begin
Application.ProcessMessages;
TimerTimer( self );
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1999 Inprise Corporation }
{ }
{*******************************************************}
unit StdActns;
{$H+,X+}
interface
uses Classes, ActnList, StdCtrls, Forms;
type
{ Hint actions }
THintAction = class(TCustomAction)
public
constructor Create(AOwner: TComponent); override;
published
property Hint;
end;
{ Edit actions }
TEditAction = class(TAction)
private
FControl: TCustomEdit;
procedure SetControl(Value: TCustomEdit);
protected
function GetControl(Target: TObject): TCustomEdit; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
function HandlesTarget(Target: TObject): Boolean; override;
procedure UpdateTarget(Target: TObject); override;
property Control: TCustomEdit read FControl write SetControl;
end;
TEditCut = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TEditCopy = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TEditPaste = class(TEditAction)
public
procedure UpdateTarget(Target: TObject); override;
procedure ExecuteTarget(Target: TObject); override;
end;
TEditSelectAll = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TEditUndo = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TEditDelete = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
{ UpdateTarget is required because TEditAction.UpdateTarget specifically
checks to see if the action is TEditCut or TEditCopy }
procedure UpdateTarget(Target: TObject); override;
end;
{ MDI Window actions }
TWindowAction = class(TAction)
private
FForm: TForm;
procedure SetForm(Value: TForm);
protected
function GetForm(Target: TObject): TForm; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
function HandlesTarget(Target: TObject): Boolean; override;
procedure UpdateTarget(Target: TObject); override;
property Form: TForm read FForm write SetForm;
end;
TWindowClose = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TWindowCascade = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TWindowTileHorizontal = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TWindowTileVertical = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TWindowMinimizeAll = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TWindowArrange = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
{ Help actions }
THelpAction = class(TAction)
public
function HandlesTarget(Target: TObject): Boolean; override;
procedure UpdateTarget(Target: TObject); override;
end;
THelpContents = class(THelpAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
THelpTopicSearch = class(THelpAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
THelpOnHelp = class(THelpAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
implementation
uses Windows, Messages, Clipbrd;
{ THintAction }
constructor THintAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DisableIfNoHandler := False;
end;
{ TEditAction }
function TEditAction.GetControl(Target: TObject): TCustomEdit;
begin
{ We could hard cast Target as a TCustomEdit since HandlesTarget "should" be
called before ExecuteTarget and UpdateTarget, however, we're being safe. }
Result := Target as TCustomEdit;
end;
function TEditAction.HandlesTarget(Target: TObject): Boolean;
begin
Result := ((Control <> nil) and (Target = Control) or
(Control = nil) and (Target is TCustomEdit)) and TCustomEdit(Target).Focused;
end;
procedure TEditAction.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = Control) then Control := nil;
end;
procedure TEditAction.UpdateTarget(Target: TObject);
begin
if (Self is TEditCut) or (Self is TEditCopy) then
Enabled := GetControl(Target).SelLength > 0;
end;
procedure TEditAction.SetControl(Value: TCustomEdit);
begin
if Value <> FControl then
begin
FControl := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
end;
{ TEditCopy }
procedure TEditCopy.ExecuteTarget(Target: TObject);
begin
GetControl(Target).CopyToClipboard;
end;
{ TEditCut }
procedure TEditCut.ExecuteTarget(Target: TObject);
begin
GetControl(Target).CutToClipboard;
end;
{ TEditPaste }
procedure TEditPaste.ExecuteTarget(Target: TObject);
begin
GetControl(Target).PasteFromClipboard;
end;
procedure TEditPaste.UpdateTarget(Target: TObject);
begin
Enabled := Clipboard.HasFormat(CF_TEXT);
end;
{ TEditSelectAll }
procedure TEditSelectAll.ExecuteTarget(Target: TObject);
begin
GetControl(Target).SelectAll;
end;
procedure TEditSelectAll.UpdateTarget(Target: TObject);
begin
Enabled := Length(GetControl(Target).Text) > 0;
end;
{ TEditUndo }
procedure TEditUndo.ExecuteTarget(Target: TObject);
begin
GetControl(Target).Undo;
end;
procedure TEditUndo.UpdateTarget(Target: TObject);
begin
Enabled := GetControl(Target).CanUndo;
end;
{ TEditDelete }
procedure TEditDelete.ExecuteTarget(Target: TObject);
begin
GetControl(Target).ClearSelection;
end;
procedure TEditDelete.UpdateTarget(Target: TObject);
begin
Enabled := GetControl(Target).SelLength > 0;
end;
{ TWindowAction }
function TWindowAction.GetForm(Target: TObject): TForm;
begin
{ We could hard cast Target as a TForm since HandlesTarget "should" be called
before ExecuteTarget and UpdateTarget, however, we're being safe. }
Result := (Target as TForm);
end;
function TWindowAction.HandlesTarget(Target: TObject): Boolean;
begin
Result := ((Form <> nil) and (Target = Form) or
(Form = nil) and (Target is TForm)) and
(TForm(Target).FormStyle = fsMDIForm);
end;
procedure TWindowAction.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = Form) then Form := nil;
end;
procedure TWindowAction.UpdateTarget(Target: TObject);
begin
Enabled := GetForm(Target).MDIChildCount > 0;
end;
procedure TWindowAction.SetForm(Value: TForm);
begin
if Value <> FForm then
begin
FForm := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
end;
{ TWindowClose }
procedure TWindowClose.ExecuteTarget(Target: TObject);
begin
with GetForm(Target) do
if ActiveMDIChild <> nil then ActiveMDIChild.Close;
end;
procedure TWindowClose.UpdateTarget(Target: TObject);
begin
Enabled := GetForm(Target).ActiveMDIChild <> nil;
end;
{ TWindowCascade }
procedure TWindowCascade.ExecuteTarget(Target: TObject);
begin
GetForm(Target).Cascade;
end;
{ TWindowTileHorizontal }
procedure DoTile(Form: TForm; TileMode: TTileMode);
const
TileParams: array[TTileMode] of Word = (MDITILE_HORIZONTAL, MDITILE_VERTICAL);
begin
if (Form.FormStyle = fsMDIForm) and (Form.ClientHandle <> 0) then
SendMessage(Form.ClientHandle, WM_MDITILE, TileParams[TileMode], 0);
end;
procedure TWindowTileHorizontal.ExecuteTarget(Target: TObject);
begin
DoTile(GetForm(Target), tbHorizontal);
end;
{ TWindowTileVertical }
procedure TWindowTileVertical.ExecuteTarget(Target: TObject);
begin
DoTile(GetForm(Target), tbVertical);
end;
{ TWindowMinimizeAll }
procedure TWindowMinimizeAll.ExecuteTarget(Target: TObject);
var
I: Integer;
begin
{ Must be done backwards through the MDIChildren array }
with GetForm(Target) do
for I := MDIChildCount - 1 downto 0 do
MDIChildren[I].WindowState := wsMinimized;
end;
{ TWindowArrange }
procedure TWindowArrange.ExecuteTarget(Target: TObject);
begin
GetForm(Target).ArrangeIcons;
end;
{ THelpAction }
function THelpAction.HandlesTarget(Target: TObject): Boolean;
begin
Result := True;
end;
procedure THelpAction.UpdateTarget(Target: TObject);
begin
Enabled := Assigned(Application);
end;
{ THelpContents }
procedure THelpContents.ExecuteTarget(Target: TObject);
begin
Application.HelpCommand(HELP_FINDER, 0);
end;
{ THelpTopicSearch }
procedure THelpTopicSearch.ExecuteTarget(Target: TObject);
begin
Application.HelpCommand(HELP_PARTIALKEY, Integer(PChar('')));
end;
{ THelpOnHelp }
procedure THelpOnHelp.ExecuteTarget(Target: TObject);
begin
Application.HelpCommand(HELP_HELPONHELP, Integer(PChar('')));
end;
end.
|
unit IdSASL_NTLM;
interface
{$i IdCompilerDefines.inc}
uses
IdSASL,
IdSASLUserPass;
const
DEF_LMCompatibility = 0;
type
TIdSASLNTLM = class(TIdSASLUserPass)
protected
FDomain : String;
FLMCompatibility : LongWord;
procedure InitComponent; override;
public
class function ServiceName: TIdSASLServiceName; override;
function StartAuthenticate(const AChallenge, AHost, AProtocolName:string) : String; override;
function ContinueAuthenticate(const ALastResponse, AHost, AProtocolName: String): string; override;
function IsReadyToStart: Boolean; override;
property Domain : String read FDomain write FDomain;
{
The LMCompatibility property is designed to work directly with the "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\LMCompatibilityLevel"
and will act as this key is documented. This effects how NTLM authentication
is done on the server. We do not pull the value from the registry because other systems
don't have a registry and you may want to set this to a value that's different from
your registry.
http://davenport.sourceforge.net/ntlm.html describes these like this:
=======================================================================
Level | Sent by Client | Accepted by Server
=======================================================================
0 | LM NTLM | LM NTLM /LMv2 NTLMv2
1 | LM NTLM | LM NTLM /LMv2 NTLMv2
2 | NTLM (is sent in both feilds) | LM NTLM /LMv2 NTLMv2
3 | LMv2 NTLMv2 | LM NTLM /LMv2 NTLMv2
4 | LMv2 NTLMv2 | NTLM /LMv2 NTLMv2
5 | LMv2 NTLMv2 | LMv2 NTLMv2
}
property LMCompatibility : LongWord read FLMCompatibility write FLMCompatibility default DEF_LMCompatibility;
end;
implementation
uses
IdFIPS, IdNTLMv2, IdGlobal;
//uses IdNTLM;
{ TIdSASLNTLM }
function TIdSASLNTLM.ContinueAuthenticate(const ALastResponse, AHost,
AProtocolName: String): string;
var
LMsg : TIdBytes;
LNonce : TIdBytes; //this is also called the challange
LTargetName, LTargetInfo : TIdBytes;
LFlags : LongWord;
LDomain, LUserName : String;
begin
LMsg := ToBytes(ALastResponse, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF});
IdNTLMv2.ReadType2Msg(LMsg, LFlags, LTargetName, LTargetInfo, LNonce);
IdGlobal.DebugOutput('Type 2 Flags = '+ DumpFlags(LFlags));
GetDomain(GetUsername, LUsername, LDomain);
Result := BytesToStringRaw( BuildType3Msg(LDomain, LDomain, GetUsername, GetPassword,
LFlags, LNonce, LTargetName, LTargetInfo, FLMCompatibility) );
end;
procedure TIdSASLNTLM.InitComponent;
begin
inherited InitComponent;
Self.FLMCompatibility := DEF_LMCompatibility;
end;
function TIdSASLNTLM.IsReadyToStart: Boolean;
begin
Result := (not GetFIPSMode) and (inherited IsReadyToStart) and
NTLMFunctionsLoaded;
end;
class function TIdSASLNTLM.ServiceName: TIdSASLServiceName;
begin
Result := 'NTLM'; {Do not localize}
end;
function TIdSASLNTLM.StartAuthenticate(const AChallenge, AHost,
AProtocolName: string): String;
var
LDomain, LUsername : String;
begin
GetDomain(GetUsername, LUsername, LDomain);
if LDomain = '' then begin
LDomain := FDomain;
end;
Result := BytesToStringRaw(IdNTLMv2.BuildType1Msg(LDomain, LDomain, FLMCompatibility));
end;
end.
|
unit k2Unknown;
{ Библиотека "K-2" }
{ Автор: Люлин А.В. © }
{ Модуль: k2Unknown - }
{ Начат: 17.12.2002 14:58 }
{ $Id: k2Unknown.pas,v 1.46 2014/06/24 14:53:34 lulin Exp $ }
// $Log: k2Unknown.pas,v $
// Revision 1.46 2014/06/24 14:53:34 lulin
// - делаем регистрацию атрибутов в отдельном списке.
//
// Revision 1.45 2014/04/30 15:03:20 lulin
// - выпрямляем зависимости.
//
// Revision 1.44 2014/04/30 11:24:07 lulin
// - выпрямляем зависимости.
//
// Revision 1.43 2014/04/23 11:13:52 lulin
// - переходим от интерфейсов к объектам.
//
// Revision 1.42 2014/04/22 17:32:36 lulin
// - переходим от интерфейсов к объектам.
//
// Revision 1.41 2014/04/22 10:56:18 lulin
// - прячем ненужный метод.
//
// Revision 1.40 2014/04/08 12:35:19 lulin
// - переходим от интерфейсов к объектам.
//
// Revision 1.39 2014/03/24 12:02:17 lulin
// {RequestLink:522793127}
//
// Revision 1.38 2014/03/14 13:27:33 lulin
// - удаляем ненужный интерфейс.
//
// Revision 1.37 2014/03/04 15:38:31 lulin
// - перетряхиваем работу с тегами.
//
// Revision 1.36 2014/02/27 06:15:44 dinishev
// Bug fix: AV под тестами Эвереста.
//
// Revision 1.35 2014/02/26 12:03:38 lulin
// {RequestLink:518769295}
//
// Revision 1.34 2014/02/13 15:16:01 lulin
// - рефакторим безликие списки.
//
// Revision 1.33 2013/11/05 12:37:44 lulin
// - атомарные теги теперь реализуются специальным классом реализации для каждого типа тега.
//
// Revision 1.32 2013/04/08 18:03:18 lulin
// - пытаемся отладиться под XE.
//
// Revision 1.31 2009/07/23 08:15:03 lulin
// - вычищаем ненужное использование процессора операций.
//
// Revision 1.30 2009/07/03 16:24:13 lulin
// - шаг к переходу от интерфейсов к объектам.
//
// Revision 1.29 2009/04/07 16:18:33 lulin
// [$140837386]. Чистка кода.
//
// Revision 1.28 2009/04/07 15:11:49 lulin
// [$140837386]. №13. Чистка кода.
//
// Revision 1.27 2009/03/04 18:14:18 lulin
// - <K>: 137470629. Удалён ненужный интерфейс.
//
// Revision 1.26 2008/02/12 12:53:20 lulin
// - избавляемся от излишнего метода на базовом классе.
//
// Revision 1.25 2008/02/05 18:20:40 lulin
// - удалено ненужное свойство строк.
//
// Revision 1.24 2008/02/05 17:39:37 lulin
// - избавляемся от ненужного именованного объекта.
//
// Revision 1.23 2008/02/05 16:13:16 lulin
// - избавляем базовый объект от лишнего свойства.
//
// Revision 1.22 2007/08/10 14:44:46 lulin
// - cleanup.
//
// Revision 1.21 2007/08/09 11:19:27 lulin
// - cleanup.
//
// Revision 1.20 2007/01/11 14:36:21 lulin
// - шрифт и информация о шрифте теперь связаны отношением наследования.
//
// Revision 1.19 2006/04/11 17:55:28 lulin
// - оптимизируем при помощи вынесения строк (по следам того как Вован наиграл в фильтрах 20% производительности).
//
// Revision 1.18 2006/01/18 08:54:36 lulin
// - изыскания на тему прямой установки целочисленных атрибутов, без преобразования их к тегам.
//
// Revision 1.17 2005/04/28 15:04:09 lulin
// - переложил ветку B_Tag_Box в HEAD.
//
// Revision 1.16.4.2 2005/04/22 11:04:30 lulin
// - bug fix: была ошибка при присваивании шрифта.
//
// Revision 1.16.4.1 2005/04/22 10:40:30 lulin
// - cleanup: убраны ненужные параметры.
//
// Revision 1.16 2005/04/04 06:44:07 lulin
// - в связи с появлением механизма событий и фасада библиотеки K-2, удалены глобальные "заплатки" связанные с созданием/уничтожением таблицы тегов.
//
// Revision 1.15 2005/03/31 09:27:12 lulin
// - new unit: k2TagTool.
//
// Revision 1.14 2005/03/30 17:27:57 lulin
// - new method: _Ik2TagTool.IsNull.
//
// Revision 1.13 2005/03/30 15:56:30 lulin
// - TevLocation теперь наследуется от Tk2Tool - базового класса для инструментов тегов.
//
// Revision 1.12 2005/03/30 15:12:24 lulin
// - в _QueryTool теперь подаем тег для которого надо сделать инструмент.
//
// Revision 1.11 2005/03/28 11:32:28 lulin
// - интерфейсы переехали в "правильный" модуль.
//
// Revision 1.10 2005/03/25 17:09:17 lulin
// - избавляемся от метода Tk2AtomW.sLong.
//
// Revision 1.9 2005/03/25 12:12:17 lulin
// - используем _Ik2Type вместо Tk2Type.
//
// Revision 1.8 2005/03/22 14:18:15 lulin
// - new method: _Ik2TypeTable.StringToTag.
//
// Revision 1.7 2005/03/22 14:11:38 lulin
// - new method: _Ik2TypeTable._BoolToTag.
//
// Revision 1.6 2005/03/22 14:08:55 lulin
// - new method: _Ik2TypeTable.LongToTag.
//
// Revision 1.5 2005/03/22 12:42:19 lulin
// - bug fix: установка стиля убивала гиперссылки.
//
// Revision 1.4 2004/09/21 12:04:26 lulin
// - Release заменил на Cleanup.
//
// Revision 1.3 2004/06/30 11:42:53 law
// - изменен тип свойства Tk2TagPointer._Target - Ik2TagWrap -> _Ik2Tag.
//
// Revision 1.2 2004/06/28 13:34:49 law
// - remove class: Il3Pointer.
//
// Revision 1.1 2002/12/17 12:20:44 law
// - new unit: k2Unknown.
//
{$Include k2Define.inc }
interface
uses
l3Types,
l3Base,
l3ProtoPersistentWithHandle,
l3IID,
l3Variant,
k2Types,
k2InternalInterfaces,
k2Interfaces,
k2BaseIntf,
k2Base
;
type
_l3COMQueryInterface_Parent_ = Tl3ProtoPersistentWithHandle;
{$Include ..\L3\l3COMQueryInterface.imp.pas}
Tk2InterfacedObject = class(_l3COMQueryInterface_)
protected
// internal methods
function GetTagType: Tk2Type;
virtual;
{-}
procedure NoParam(Index: Long);
{-}
end;//Tk2InterfacedObject
Ik2Unknown = class(Tk2InterfacedObject)
protected
{property methods}
procedure GetParam(Index: Long; TK: Tk2TypeKind; var Dest);
virtual;
procedure SetParam(Index: Long; Source: Tl3Variant);
virtual;
{-}
function GetLongParam(Index: Integer): Long;
procedure SetLongParam(Index: Integer; Value: Long);
virtual;
{-}
function GetBoolParam(Index: Integer): Bool;
procedure SetBoolParam(Index: Integer; Value: Bool);
{-}
function GetStringParam(Index: Integer): AnsiString;
procedure SetStringParam(Index: Integer; const Value: AnsiString);
{-}
end;{Ik2Unknown}
implementation
uses
TypInfo,
l3String,
k2Facade,
k2Tags,
k2Strings,
k2Bool_Const,
k2Attributes
;
{$Include ..\L3\l3COMQueryInterface.imp.pas}
// start class Tk2InterfacedObject
function Tk2InterfacedObject.GetTagType: Tk2Type;
{virtual;}
{-}
begin
Result := nil;
end;
procedure Tk2InterfacedObject.NoParam(Index: Long);
{-}
begin
raise Ek2ParamNotDefined.CreateFmt(k2_errParamNotDefined,
[
Tk2Attributes.Instance.NameByID(Index),
//GetEnumName(TypeInfo(_Tk2TagID), Index),
ClassName
]);
end;
// start class Ik2Unknown
procedure Ik2Unknown.GetParam(Index: Long; TK: Tk2TypeKind; var Dest);
{-}
begin
NoParam(Index);
end;
procedure Ik2Unknown.SetParam(Index: Long; Source: Tl3Variant);
{-}
begin
NoParam(Index);
end;
function Ik2Unknown.GetLongParam(Index: Integer): Long;
{-}
begin
GetParam(Index, k2_tkInteger, Result);
end;
procedure Ik2Unknown.SetLongParam(Index: Integer; Value: Long);
{-}
begin
SetParam(Index, GetTagType.Prop[Index].MakeTag(Value).AsObject);
end;
function Ik2Unknown.GetBoolParam(Index: Integer): Bool;
{-}
begin
GetParam(Index, k2_tkBool, Result);
end;
procedure Ik2Unknown.SetBoolParam(Index: Integer; Value: Bool);
{-}
begin
if Value then
SetParam(Index, k2_typBool.MakeTag(1).AsObject)
else
SetParam(Index, k2_typBool.MakeTag(0).AsObject);
end;
function Ik2Unknown.GetStringParam(Index: Integer): AnsiString;
{-}
var
O : TObject;
begin
GetParam(Index, k2_tkObject, O);
Result := (O As Tl3Tag).AsString;
end;
procedure Ik2Unknown.SetStringParam(Index: Integer; const Value: AnsiString);
{-}
begin
SetParam(Index, Tk2Type(GetTagType.Prop[Index].AtomType).StrToTag(Value));
end;
end.
|
{ Version 1.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, LCLType, fileutilwin, htmlbrowser;
type
{ TfrmMain }
TfrmMain = class(TForm)
btnHelp: TButton;
btnOpen: TButton;
btnSave: TButton;
DirectoryEdit: TDirectoryEdit;
ListBox: TListBox;
SelectDirectoryDialog: TSelectDirectoryDialog;
procedure btnHelpClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure DirectoryEditChange(Sender: TObject);
procedure FormDestroy(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;
function DirectoryIsEmpty(Directory: string): Boolean;
var
aList: TStringList;
SR: TSearchRec;
i: Integer;
begin
Result:=False;
aList:=TStringList.Create;
aList:=FindAllFiles(Directory,'*', False);
if aList.Count=0 then Result:=True;
aList.Free;
end;
procedure TfrmMain.DirectoryEditChange(Sender: TObject);
var
i: integer;
Dir: string;
DirList: TStringList;
aName: string;
begin
ListBox.Clear;
Dir:=IncludeTrailingPathDelimiter(DirectoryEdit.Directory);
DirList:=TStringList.Create;
DirList:=FindAllDirectories(Dir, False);
For i:=DirList.Count-1 downto 0 do begin
aName:=ExtractFilename(DirList[i]);
if not UpperCase(ExtractFilename(DirList[i])).StartsWith('TEMPLATE') then begin
DirList.Delete(i);
end;
end;
if DirList.Count=0 then
ListBox.Items.Add('No templates found in this directory.')
else
ListBox.Items.Assign(DirList);
ListBox.ItemIndex:=0;
DirList.Free;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
Viewer.Free;
end;
procedure TfrmMain.btnSaveClick(Sender: TObject);
var
i: integer;
Reply: integer;
SourceDir, TargetDir: string;
begin
if ListBox.Count=0 then Exit;
if SelectDirectoryDialog.Execute then
TargetDir:=SelectDirectoryDialog.FileName
else
Exit;
if not DirectoryIsEmpty(TargetDir) then begin
if QuestionDlg(Application.Title,'Directory is Not Empty, Overwrite?',
mtWarning,[mrYes,'&Yes',mrNo,'&No','IsDefault'],0) <>IDYES then Exit;
end;
for i:=0 to ListBox.Count-1 do begin
if not ListBox.Selected[i] then
Continue;
SourceDir:=ExpandFileName(ListBox.Items[i]);
if CopyDirWin(SourceDir, TargetDir) then
ShowMessage('Template saved to:'+LE+LE+TargetDir)
else
ShowMessage('Error saving Template');
end;
end;
procedure TfrmMain.btnOpenClick(Sender: TObject);
begin
if ListBox.Count=0 then Exit;
OpenDocument(Listbox.Items[Listbox.ItemIndex]);
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
Viewer:=THTMLBrowserViewer.Create;
Viewer.ExtractResFiles;
DirectoryEdit.Directory:=GetCurrentDir;
//DirectoryEditChange(nil);
if ListBox.Count=0 then
ShowMessage('Error no templates found');
end;
end.
|
{*********************************************************************** }
{ File: Main.pas }
{ }
{ Purpose: }
{ main source file to demonstrate how to get started with VT (1) }
{ <-- Basic VT as a Listbox (no node data used) --> }
{ }
{ Module Record: }
{ }
{ Date AP Details }
{ -------- -- -------------------------------------- }
{ 05-Nov-2002 TC Created (tomc@gripsystems.com) }
{**********************************************************************}
unit Main;
{$mode delphi}
{$H+}
interface
uses
LCLIntf, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, VirtualTrees, ExtCtrls, StdCtrls, Buttons, LResources;
type
TfrmMain =
class(TForm)
imgMaster: TImageList;
panMain: TPanel;
VT: TVirtualStringTree;
panBase: TPanel;
chkRadioButtons: TCheckBox;
chkChangeHeight: TCheckBox;
chkHotTrack: TCheckBox;
Label1: TLabel;
btnViewCode: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure VTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
procedure VTInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure VTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: String);
procedure VTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode;
Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer);
procedure VTDblClick(Sender: TObject);
procedure chkRadioButtonsClick(Sender: TObject);
procedure VTFocusChanging(Sender: TBaseVirtualTree; OldNode, NewNode: PVirtualNode; OldColumn, NewColumn: TColumnIndex;
var Allowed: Boolean);
procedure chkChangeHeightClick(Sender: TObject);
procedure chkHotTrackClick(Sender: TObject);
procedure btnViewCodeClick(Sender: TObject);
private
FCaptions : TStringList;
end;
var
frmMain: TfrmMain;
implementation
uses
VTNoData, VTCheckList, VTPropEdit, VTDBExample, VTEditors, ViewCode;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
Top := 0;
Left:= 0;
{let's make some data to display - it's going to come from somewhere}
FCaptions := TStringList.Create;
FCaptions.Add( 'Basic VT as a Listbox (no node data used)' );
FCaptions.Add( 'Basic VT as a Tree (no node data used)' );
FCaptions.Add( 'Generic CheckListbox selection Form (no node data used)');
FCaptions.Add( 'Dynamic Property Editor example 1.' );
FCaptions.Add( 'Database example 1.' );
{this is first important value to set, 0 is ok if you want to use AddChild later}
VT.RootNodeCount := FCaptions.Count;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
FCaptions.Free;
end;
procedure TfrmMain.VTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
{--------------------------------------------------------------------------------------------
note zero node data size - you don't *have* to store data in the node. Maybe this is very likely
if you are dealing with a list with no children that can be directly indexed into via Node.Index
---------------------------------------------------------------------------------------------}
begin
NodeDataSize := 0;
end;
procedure TfrmMain.VTInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
begin
Node.CheckType := ctRadioButton; {must enable toCheckSupport in TreeOptions.MiscOptions}
end;
procedure TfrmMain.VTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: String);
begin
Celltext := FCaptions[Node.Index]; {this is where we say what the text to display}
end;
procedure TfrmMain.VTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode;
Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer);
begin
ImageIndex := Node.Index; {this is where we say what image to display}
end;
procedure TfrmMain.VTDblClick(Sender: TObject);
begin
//showform is a utility routine for this app - in vteditors.pas
case VT.FocusedNode.Index of
0: ShowMessage( 'This is it...!' ); // Main.pas
1: ShowForm( TfrmVTNoData, Left, Height ); // VTNoData.pas
2: DoVTCheckListExample; // VTCheckList.pas
3: ShowForm( TfrmVTPropEdit, Left + Width, Top ); // VTPropEdit.pas
4: ShowForm( TfrmVTDBExample, Left + Width, Top ); // VTDBExample.pas
end;
end;
procedure TfrmMain.chkHotTrackClick(Sender: TObject);
begin
with VT.TreeOptions do
begin
if chkHotTrack.checked then
PaintOptions := PaintOptions + [toHotTrack]
else
PaintOptions := PaintOptions - [toHotTrack];
VT.Refresh;
end;
end;
procedure TfrmMain.chkRadioButtonsClick(Sender: TObject);
begin
with VT.TreeOptions do
begin
if chkRadioButtons.checked then
MiscOptions := MiscOptions + [toCheckSupport]
else
MiscOptions := MiscOptions - [toCheckSupport];
VT.Refresh;
end;
end;
procedure TfrmMain.VTFocusChanging(Sender: TBaseVirtualTree; OldNode,
NewNode: PVirtualNode; OldColumn, NewColumn: TColumnIndex;
var Allowed: Boolean);
begin
{example of dynamically changing height of node}
if chkChangeHeight.checked then
begin
Sender.NodeHeight[OldNode] := 20;
Sender.NodeHeight[NewNode] := 40;
end;
end;
procedure TfrmMain.chkChangeHeightClick(Sender: TObject);
begin
{example of resetting dynamically changing node heights}
if not chkChangeHeight.checked then with VT do
begin
NodeHeight[FocusedNode] := 20;
InvalidateNode(FocusedNode);
end;
end;
procedure TfrmMain.btnViewCodeClick(Sender: TObject);
var
sFile : string;
f : TForm;
begin
case VT.FocusedNode.Index of
0: sFile := 'Main' ;
1: sFile := 'VTNoData' ;
2: sFile := 'VTCheckList' ;
3: sFile := 'VTPropEdit' ;
4: sFile := 'VTDBExample' ;
end;
f := ShowForm( TfrmViewCode, Left, Height ); // ViewCode.pas
TfrmViewCode(f).SynEdit1.Lines.LoadFromFile( ExtractFilePath(ParamStr(0)) + sFile + '.pas' );
end;
initialization
{$I Main.lrs}
end.
|
unit evdTaskTypes;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "EVD"
// Модуль: "w:/common/components/rtl/Garant/EVD/NOT_FINISHED_evdTaskTypes.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::EVD::Standard::evdTaskTypes
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{$Include ..\EVD\evdDefine.inc}
interface
type
TcsTaskStatus = (cs_tsNone,
cs_tsQuery, { в очереди }
cs_tsRun, { выполняется }
cs_tsFrozen, { заморожено }
cs_tsFrozenRun, { выполнение приостановлено }
cs_tsDelivery, { ожидание доставки пользователю }
cs_tsDone, { обработано }
cs_tsDeleted, { удалено }
cs_tsError, { выполнение привело к ошибке }
cs_tsDelayed, { выполнение отложено до ЕО }
cs_tsDelivering, { выполняется доставка результатов }
cs_tsAsyncRun, { Исполнение в отцепленном процессе }
cs_tsAsyncError, { выполнение в отцепленном процессе привело к ошибке }
cs_tsAborting { выполнение прерывается }
);
const
cs_tsReadyToDelivery = cs_tsDelivery;
cs_tsErrorStatuses = [cs_tsError, cs_tsAsyncError];
cs_tsRunningStatuses = [cs_tsRun, cs_tsAsyncRun];
cs_tsKeepProcessingStatuses = [cs_tsFrozen, cs_tsFrozenRun, cs_tsDeleted, cs_tsReadyToDelivery, cs_tsDelivering, cs_tsAsyncRun, cs_tsQuery];
cs_tsStatusesWithProgress = cs_tsRunningStatuses + [cs_tsDelivering];
cs_tsCanDeleteStatuses = [cs_tsRun, cs_tsAsyncRun, cs_tsQuery, cs_tsFrozen, cs_tsReadyToDelivery];
cs_tsFinishedStatuses = [cs_tsDone, cs_tsDeleted] + cs_tsErrorStatuses;
type
TcsTaskType = (cs_ttImport, // Импорт
cs_ttExport, // Экспорт документов
cs_ttAutoClass, // Автоклассификация
cs_ttAnnoExport, // Экспорт специальных аннотаций
cs_ttDictEdit,
cs_ttRequest,
cs_ttGetTask,
cs_ttLine,
cs_ttServerStatus,
cs_ttTaskResult,
cs_tt_Deprecated_FNSExport,
cs_ttUserEdit,
cs_ttDeleteDocs,
cs_ttCommonData,
cs_ttAExportDoc,
cs_ttAExportAnno,
cs_tt_Deprecated_RemoteDictEdit,
cs_ttRegionAutoExport,
cs_ttRunCommand,
cs_ttDossierMake,
cs_ttCaseCode,
cs_tt_Deprecated_PrimeExport,
cs_ttUserDefinedExport,
cs_ttSpellCheck,
cs_ttAutoSpellCheck,
cs_ttAACImport,
cs_ttRelPublish,
cs_ttUnregistered,
cs_tt_Deprecated_MDPSync,
cs_tt_Deprecated_AACRelExport,
cs_tt_Deprecated_MisspellCorrect,
cs_tt_Deprecated_NCFRExport,
cs_ttUnknown,
cs_ttClientMessage,
cs_ttAsEVD,
cs_ttProcess,
cs_ttAnoncedExport,
cs_ttHavanskyExport,
cs_ttRegionImport,
cs_ttMdpSyncDicts,
cs_ttMdpImportDocs,
cs_ttContainer,
cs_ttSchedulerProxy,
cs_ttMdpSyncStages,
cs_ttMdpSyncImport,
cs_ttDownloadDoc,
cs_ttUploadDoc,
cs_ttMultiModifyDocs,
cs_ttMultiClearAttributes,
cs_ttMultiOperation,
cs_ttDeliveryProfile,
cs_ttAutolinker,
cs_ttMultiChangeHyperLinks
);
TCsNotificationType = (ntEmpty,
ntServerStarted,
ntServerStopped,
ntTaskChanged,
ntTaskProgress,
ntRepeatLogin,
ntAutoLogoff,
ntInformation,
ntUserLogin,
ntUserLogout,
ntMailArrived,
ntTaskAdded,
ntDictEdit,
ntHaveNewMessages,
ntExportDone,
ntImportDone,
ntDelDoc,
ntCalendar,
ntAnouncedDateChanged,
ntAbortAsyncRun,
ntResultsReadyForDelivery);
TCsNotificationTypes = set of TCsNotificationType;
const
usServerService = 65000;
SomeFixedDate = usServerService;
implementation
end. |
unit adEngine;
{ $Id: adEngine.pas,v 1.8 2014/10/20 09:48:04 fireton Exp $ }
interface
uses
l3Types,
l3Interfaces,
l3ProtoObject,
l3StringList,
l3Except,
l3ProtoObjectRefList,
JclSimpleXML;
type
TadItem = class(Tl3ProtoObject)
private
f_Alias: AnsiString;
f_Changed: Boolean;
f_Name: AnsiString;
f_Files: Tl3StringList;
f_IsValid: Boolean;
f_TargetFolder: AnsiString;
f_ValidityArr: array of Boolean;
function pm_GetFiles(aIndex: Integer): AnsiString;
function pm_GetFilesCount: Integer;
function pm_GetIsFileValid(aIndex: Integer): Boolean;
procedure pm_SetName(const Value: AnsiString);
procedure pm_SetTargetFolder(const Value: AnsiString);
procedure RefreshValidity;
protected
procedure Cleanup; override;
public
constructor Create;
function AddFile(const aFileName: AnsiString): Integer;
procedure ClearFiles;
procedure DeleteFile(aIndex: Integer);
procedure Distribute;
procedure Load(const aBox: TJclSimpleXMLElem);
procedure Save(const aBox: TJclSimpleXMLElem);
function CheckDistribution(const aErrorList: Tl3StringList = nil): Boolean;
property Alias: AnsiString read f_Alias write f_Alias;
property Changed: Boolean read f_Changed write f_Changed;
property Files[aIndex: Integer]: AnsiString read pm_GetFiles;
property FilesCount: Integer read pm_GetFilesCount;
property IsFileValid[aIndex: Integer]: Boolean read pm_GetIsFileValid;
property IsValid: Boolean read f_IsValid;
property Name: AnsiString read f_Name write pm_SetName;
property TargetFolder: AnsiString read f_TargetFolder write pm_SetTargetFolder;
end;
TadManager = class(Tl3ProtoObject)
private
f_Filename: AnsiString;
f_IsValid: Boolean;
f_Items: Tl3ProtoObjectRefList;
private
function pm_GetItemCount: Integer;
function pm_GetItems(aIndex: Integer): TadItem;
protected
procedure Cleanup; override;
public
constructor Create(const aFilename: AnsiString);
procedure AddItem(const anItem: TadItem);
procedure Archive(const aZipName: AnsiString; const aProgressProc: Tl3ProgressProc);
function CheckDistribution(const aErrorList: Tl3StringList = nil): Boolean;
function CheckArchive(const aArchiveFileName: AnsiString; const aErrorList: Tl3StringList = nil): Boolean;
procedure DeleteItem(anIndex: Integer);
procedure Distribute(const aProgressProc: Tl3ProgressProc);
procedure Load;
procedure RefreshValidity;
procedure Save;
property IsValid: Boolean read f_IsValid;
property ItemCount: Integer read pm_GetItemCount;
property Items[aIndex: Integer]: TadItem read pm_GetItems;
end;
EadLoadError = class(El3Error);
implementation
uses
Classes,
SysUtils,
l3Base,
l3String,
l3StringListPrim,
l3Stream,
l3Variant,
l3FileUtils,
ZipForge;
const
cLoadErrorStr = 'Ошибка загрузки элемента из XML';
constructor TadItem.Create;
begin
inherited Create;
f_Files := Tl3StringList.MakeSorted;
end;
function TadItem.AddFile(const aFileName: AnsiString): Integer;
begin
Result := f_Files.Add(l3CStr(aFileName));
RefreshValidity;
end;
function TadItem.CheckDistribution(const aErrorList: Tl3StringList = nil): Boolean;
function CheckOneFile(Data: Pointer; Index: Long): Bool;
var
l_FN: AnsiString;
l_TargetFileName: AnsiString;
l_FHandle: Integer;
begin
Result := True;
l_FN := Tl3PrimString(Data^).AsString;
l_TargetFileName := ConcatDirName(TargetFolder, ExtractFileName(l_FN));
if FileExists(l_TargetFileName) then
begin
l_FHandle := FileOpen(l_TargetFileName, fmShareExclusive);
if l_FHandle < 0 then
begin
CheckDistribution := False;
aErrorList.Add(l_TargetFileName);
end
else
FileClose(l_FHandle);
end;
end;
var
l_IA: Tl3IteratorAction;
begin
Result := True;
l_IA := l3L2IA(@CheckOneFile);
f_Files.IterateAllF(l_IA);
end;
procedure TadItem.DeleteFile(aIndex: Integer);
begin
f_Files.Delete(aIndex);
RefreshValidity;
end;
procedure TadItem.Load(const aBox: TJclSimpleXMLElem);
var
I: Integer;
l_List: TJclSimpleXMLElem;
l_Tag: TJclSimpleXMLElem;
procedure CheckTag;
begin
if l_Tag = nil then
raise EadLoadError.Create(cLoadErrorStr);
end;
begin
f_Files.Clear;
l_Tag := aBox.Items.ItemNamed['alias'];
CheckTag;
f_Alias := l_Tag.Value;
l_Tag := aBox.Items.ItemNamed['name'];
CheckTag;
f_Name := l_Tag.Value;
l_Tag := aBox.Items.ItemNamed['target'];
CheckTag;
f_TargetFolder := l_Tag.Value;
l_Tag := aBox.Items.ItemNamed['files'];
CheckTag;
l_List := l_Tag;
for I := 0 to l_List.Items.Count - 1 do
begin
l_Tag :=l_List.Items.Item[I];
f_Files.Add(l3CStr(l_Tag.Value));
end;
RefreshValidity;
end;
procedure TadItem.Cleanup;
begin
FreeAndNil(f_Files);
inherited;
end;
procedure TadItem.ClearFiles;
begin
f_Files.Clear;
end;
procedure TadItem.Distribute;
function DoOneFile(Data: Pointer; Index: Long): Bool;
var
l_FN: AnsiString;
l_TargetFileName: AnsiString;
begin
Result := True;
l_FN := Tl3PrimString(Data^).AsString;
l_TargetFileName := ConcatDirName(TargetFolder, ExtractFileName(l_FN));
CopyFile(l_FN, l_TargetFileName, cmWriteOver + cmNoBakCopy);
end;
var
l_IA: Tl3IteratorAction;
begin
l_IA := l3L2IA(@DoOneFile);
f_Files.IterateAllF(l_IA)
end;
function TadItem.pm_GetFiles(aIndex: Integer): AnsiString;
begin
Result := l3Str(f_Files.ItemW[aIndex]);
end;
function TadItem.pm_GetFilesCount: Integer;
begin
Result := f_Files.Count;
end;
function TadItem.pm_GetIsFileValid(aIndex: Integer): Boolean;
begin
if (Length(f_ValidityArr) = 0) then
RefreshValidity;
Result := f_ValidityArr[aIndex];
end;
procedure TadItem.pm_SetName(const Value: AnsiString);
begin
f_Name := Value;
f_Changed := True;
end;
procedure TadItem.pm_SetTargetFolder(const Value: AnsiString);
begin
f_TargetFolder := Value;
f_Changed := True;
end;
procedure TadItem.RefreshValidity;
var
I: Integer;
begin
SetLength(f_ValidityArr, FilesCount);
if FilesCount > 0 then
begin
f_IsValid := True;
for I := 0 to FilesCount - 1 do
begin
f_ValidityArr[I] := FileExists(Files[I]);
if not f_ValidityArr[I] then
f_IsValid := False;
end;
end
else
f_IsValid := False;
f_IsValid := f_IsValid and DirectoryExists(f_TargetFolder);
end;
procedure TadItem.Save(const aBox: TJclSimpleXMLElem);
var
I: Integer;
l_List : TJclSimpleXMLElem;
l_Tag : TJclSimpleXMLElem;
begin
l_Tag := aBox.Items.Add('alias');
l_Tag.Value := f_Alias;
l_Tag := aBox.Items.Add('name');
l_Tag.Value := f_Name;
l_Tag := aBox.Items.Add('target');
l_Tag.Value := f_TargetFolder;
l_List := aBox.Items.Add('files');
for I := 0 to FilesCount - 1 do
begin
l_Tag := l_List.Items.Add('file');
l_Tag.Value := Files[I];
end;
end;
constructor TadManager.Create(const aFilename: AnsiString);
begin
inherited Create;
f_Filename := aFilename;
f_Items := Tl3ProtoObjectRefList.Make;
end;
procedure TadManager.AddItem(const anItem: TadItem);
begin
f_Items.Add(anItem);
Save;
end;
procedure TadManager.Archive(const aZipName: AnsiString; const aProgressProc: Tl3ProgressProc);
var
I, J: Integer;
l_Zip: TZipForge;
l_Dir: AnsiString;
l_FS : Tl3FileStream;
l_DT : TDateTime;
l_FN: AnsiString;
begin
l_Zip := TZipForge.Create(nil);
try
aProgressProc(piStart, ItemCount, 'Создаём архив дистрибутива');
l_Zip.FileName := aZipName;
l_Zip.OpenArchive(fmCreate);
l_Zip.BeginUpdate;
try
for I := 0 to ItemCount - 1 do
begin
aProgressProc(piCurrent, I+1, 'Архивируем '+Items[I].Name);
l_Dir := Items[I].Alias + '\';
for J := 0 to Items[I].FilesCount - 1 do
begin
if FileExists(Items[I].Files[J]) then
begin
l_DT := FileDateToDateTime(FileAge(Items[I].Files[J]));
l_FS := Tl3FileStream.Create(Items[I].Files[J], l3_fmRead);
try
l_FN := ExtractFileName(Items[I].Files[J]);
l_Zip.AddFromStream(l_Dir + l_FN, l_FS, True, 0, 0, faArchive, l_DT);
finally
FreeAndNil(l_FS);
end;
end;
end;
end;
finally
l_Zip.EndUpdate;
aProgressProc(piEnd, 0, '');
end;
finally
FreeAndNil(l_Zip);
end;
end;
function TadManager.CheckArchive(const aArchiveFileName: AnsiString; const aErrorList: Tl3StringList = nil): Boolean;
var
l_Zip: TZipForge;
begin
Result := False;
l_Zip := TZipForge.Create(nil);
try
l_Zip.FileName := aArchiveFileName;
l_Zip.OpenArchive;
//l_Zip.
finally
FreeAndNil(l_Zip);
end;
end;
function TadManager.CheckDistribution(const aErrorList: Tl3StringList = nil): Boolean;
function DoOne(Data: Pointer; Index: Long): Bool;
begin
Result := True;
if not TadItem(Data^).CheckDistribution(aErrorList) then
CheckDistribution := False;
end;
var
l_IA: Tl3IteratorAction;
begin
Result := True;
l_IA := l3L2IA(@DoOne);
f_Items.IterateAllF(l_IA);
end;
procedure TadManager.Cleanup;
begin
FreeAndNil(f_Items);
inherited;
end;
procedure TadManager.DeleteItem(anIndex: Integer);
begin
f_Items.Delete(anIndex);
Save;
end;
procedure TadManager.Distribute(const aProgressProc: Tl3ProgressProc);
function DoOne(Data: Pointer; Index: Long): Bool;
begin
Result := True;
TadItem(Data^).Distribute;
aProgressProc(piCurrent, Index+1, 'Подкладываем' + TadItem(Data^).Name);
end;
var
l_IA: Tl3IteratorAction;
begin
aProgressProc(piStart, f_Items.Count, 'Подкладываем дистрибутив');
try
l_IA := l3L2IA(@DoOne);
f_Items.IterateAllF(l_IA);
finally
aProgressProc(piEnd, 0);
end;
end;
procedure TadManager.Load;
var
I: Integer;
l_AdItem: TadItem;
l_XML: TJclSimpleXml;
l_ListTag: TJclSimpleXMLElem;
l_Tag : TJclSimpleXMLElem;
begin
if FileExists(f_Filename) then
begin
l_XML := TJclSimpleXml.Create;
try
l_XML.LoadFromFile(f_Filename);
f_Items.Clear;
l_ListTag := l_XML.Root.Items.ItemNamed['items'];
for I := 0 to l_ListTag.Items.Count-1 do
begin
l_AdItem := TadItem.Create;
try
l_AdItem.Load(l_ListTag.Items[I]);
f_Items.Add(l_AdItem);
finally
FreeAndNil(l_AdItem);
end;
end;
finally
FreeAndNil(l_XML);
end;
end;
RefreshValidity;
end;
function TadManager.pm_GetItemCount: Integer;
begin
Result := f_Items.Count;
end;
function TadManager.pm_GetItems(aIndex: Integer): TadItem;
begin
Result := TadItem(f_Items.Items[aIndex]);
end;
procedure TadManager.RefreshValidity;
function DoOne(Data: Pointer; Index: Long): Bool;
begin
Result := True;
TadItem(Data^).RefreshValidity;
if not TadItem(Data^).IsValid then
f_IsValid := False;
end;
var
l_IA : Tl3IteratorAction;
begin
l_IA := l3L2IA(@DoOne);
f_IsValid := True;
f_Items.IterateAllF(l_IA);
end;
procedure TadManager.Save;
var
I: Integer;
l_XML: TJclSimpleXml;
l_ListTag: TJclSimpleXMLElem;
l_Tag : TJclSimpleXMLElem;
begin
l_XML := TJclSimpleXml.Create;
try
l_XML.Prolog.Encoding := 'utf-8';
l_XML.Root.Name := 'root';
l_ListTag := l_XML.Root.Items.Add('items');
for I := 0 to ItemCount - 1 do
begin
l_Tag := l_ListTag.Items.Add('item');
Items[I].Save(l_Tag);
end;
l_XML.SaveToFile(f_Filename);
finally
FreeAndNil(l_XML);
end;
end;
end. |
unit uClasse.Veiculo.Aereo;
interface
uses
uClasse.Veiculo;
type
TAereo = class(TVeiculo)
private
public
Altura_maxima: currency;
Tipo_propulsor: string;
Qtd_Pilotos: integer;
breve: string;
tipo_transporte: string; //carga ou pessoas
possui_armamento: boolean;
tipo_aplicacao: string; //civil/militar/resgate
possui_piloto_automatico: boolean;
end;
implementation
end.
|
unit f2Types;
interface
uses
d2dTypes,
d2dInterfaces,
d2dClasses,
d2dSprite,
d2dFont,
d2dGUITypes,
JclStringLists;
type
Tf2DecorType = (dtInvalid, dtText, dtRectangle, dtPicture, dtAnimation, dtGIF, dtClickArea, dtImgButton, dtTextButton);
const
c_Gametitle = 'gametitle';
c_StyleDosTextcolor = 'Style_dos_textcolor';
c_Textalign = 'textalign';
c_MusicLooped = 'music_looped';
c_Textfont = 'textfont';
c_Sysfont = '_sysfont';
c_SysMenuFont = '_sysmenufont';
c_Textcolor = 'textcolor';
c_EchoColor = 'echocolor';
c_LinkColor = 'linkcolor';
c_LinkHColor = 'linkhcolor';
c_MusicVolume = 'music_volume';
c_VoiceVolume = 'voice_volume';
c_TextPaneLeft = 'textpane_left';
c_TextPaneTop = 'textpane_top';
c_TextPaneWidth = 'textpane_width';
c_TextPaneHeight = 'textpane_height';
c_MouseX = 'mouse_x';
c_MouseY = 'mouse_y';
c_fp_filename = 'fp_filename';
c_HideSaveEchoVar = 'hide_save_echo';
c_HideBtnEchoVar = 'hide_btn_echo';
c_HideInvEchoVar = 'hide_inv_echo';
c_HideLinkEchoVar = 'hide_link_echo';
c_HideLocalActionEchoVar = 'hide_local_echo';
c_MenuFontVar = 'menu_textfont';
c_MenuBGColorVar = 'menu_bgcolor';
c_MenuBorderColorVar = 'menu_bordercolor';
c_MenuTextColorVar = 'menu_textcolor';
c_MenuHIndentVar = 'menu_hindent';
c_MenuVIndentVar = 'menu_vindent';
c_MenuSelectionColorVar = 'menu_selectioncolor';
c_MenuSelectedColorVar = 'menu_seltextcolor';
c_MenuDisabledColorVar = 'menu_disabledcolor';
c_BtnAlign = 'btnalign';
c_BtnTxtAlign = 'btntxtalign';
c_LineSpacing = 'linespacing';
c_ParaSpacing = 'paraspacing';
c_NumButtons = 'numbuttons';
c_BMenuAlign = 'bmenualign';
c_LMenuAlign = 'lmenualign';
c_FullScreen = 'fullscreen';
c_IsMusic = 'is_music';
c_SaveNameBase = 'savenamebase';
type
Tf2DecorationSprite = class(Td2dSprite)
private
f_X: Single;
f_Y: Single;
f_Z: Single;
public
constructor Create(aTex: Id2dTexture; aTexX, aTexY: Integer; aWidth, aHeight: Integer; aX, aY: Single);
procedure Render; reintroduce;
property X: Single read f_X write f_X;
property Y: Single read f_Y write f_Y;
published
property Z: Single read f_Z write f_Z;
end;
type
Tf2OnActionProc = procedure (const anID: string; const aRect: Td2dRect; const aMenuAlign: Td2dAlign) of object;
function CorrectColor(const aColor: Td2dColor): Td2dColor;
function Hex2ColorDef(aHex: string; const aDefault: Td2dColor): Td2dColor;
function IntToAlign(const aNum: Integer): Td2dTextAlignType;
function AlignToInt(const aAlign: Td2dTextAlignType): Integer;
implementation
uses
SysUtils,
d2dCore,
f2FontLoad;
function CorrectColor(const aColor: Td2dColor): Td2dColor;
begin
if (aColor and $FF000000) = 0 then
Result := $FF000000 or aColor
else
Result := aColor;
end;
function AlignToInt(const aAlign: Td2dTextAlignType): Integer;
begin
Result := Ord(aAlign) + 1;
end;
function IntToAlign(const aNum: Integer): Td2dTextAlignType;
begin
case aNum of
2: Result := ptRightAligned;
3: Result := ptCentered;
else
Result := ptLeftAligned;
end;
end;
function Hex2ColorDef(aHex: string; const aDefault: Td2dColor): Td2dColor;
begin
if UpperCase(Copy(aHex, 1, 2)) = '0X' then
begin
Delete(aHex, 1, 1);
aHex[1] := '$';
end;
Result := StrToInt64Def(aHex, aDefault);
end;
constructor Tf2DecorationSprite.Create(aTex: Id2dTexture; aTexX, aTexY: Integer; aWidth, aHeight: Integer; aX, aY:
Single);
begin
inherited Create(aTex, aTexX, aTexY, aWidth, aHeight);
f_X := aX;
f_Y := aY;
f_Z := 3.4e38;
end;
procedure Tf2DecorationSprite.Render;
begin
inherited Render(f_X, f_Y);
end;
end. |
PROGRAM roman (output);
VAR
x, y : integer;
BEGIN
y := 1;
REPEAT
x := y;
write(x:4, ' ');
WHILE x >= 1000 DO BEGIN
write('m');
x := x - 1000;
END;
WHILE x >= 500 DO BEGIN
write('d');
x := x - 500;
END;
WHILE x >= 100 DO BEGIN
write('c');
x := x - 100;
END;
WHILE x >= 50 DO BEGIN
write('l');
x := x - 50;
END;
WHILE x >= 10 DO BEGIN
write('x');
x := x - 10;
END;
WHILE x >= 5 DO BEGIN
write('v');
x := x - 5;
END;
WHILE x >= 1 DO BEGIN
write('i');
x := x - 1;
END;
writeln;
y := 2*y;
UNTIL y > 5000;
END.
|
unit FuturesData_Load;
interface
uses
BaseApp,
FuturesDataAccess;
function LoadFuturesData(App: TBaseApp; ADataAccess: TFuturesDataAccess): Boolean;
function CheckNeedLoadFuturesData(App: TBaseApp; ADataAccess: TFuturesDataAccess; ALastDate: Word): Boolean;
implementation
uses
BaseWinFile,
Define_Price,
define_futures_quotes,
define_dealstore_header,
define_dealstore_file;
function LoadFuturesDataFromBuffer(ADataAccess: TFuturesDataAccess; AMemory: pointer): Boolean; forward;
function LoadFuturesData(App: TBaseApp; ADataAccess: TFuturesDataAccess): Boolean;
var
tmpWinFile: TWinFile;
tmpFileUrl: string;
tmpFileMapView: Pointer;
begin
Result := false;
tmpFileUrl := App.Path.GetFileUrl(FilePath_DBType_DayData, ADataAccess.DataSourceId, 1, ADataAccess.DealItem);
if App.Path.IsFileExists(tmpFileUrl) then
begin
tmpWinFile := TWinFile.Create;
try
if tmpWinFile.OpenFile(tmpFileUrl, false) then
begin
tmpFileMapView := tmpWinFile.OpenFileMap;
if nil <> tmpFileMapView then
begin
Result := LoadFuturesDataFromBuffer(ADataAccess, tmpFileMapView);
end;
end;
finally
tmpWinFile.Free;
end;
end;
end;
function ReadFuturesDataHeader(ADataAccess: TFuturesDataAccess; AMemory: pointer): PStore_Quote_M1_Day_Header_V1Rec;
var
tmpHead: PStore_Quote_M1_Day_Header_V1Rec;
begin
Result := nil;
tmpHead := AMemory;
if tmpHead.Header.BaseHeader.HeadSize = SizeOf(TStore_Quote_M1_Day_Header_V1Rec) then
begin
if (tmpHead.Header.BaseHeader.DataType = DataType_Futures) then
begin
if (tmpHead.Header.BaseHeader.DataMode = DataMode_DayData) then
begin
if 0 = ADataAccess.DataSourceId then
ADataAccess.DataSourceId := tmpHead.Header.BaseHeader.DataSourceId;
if ADataAccess.DataSourceId = tmpHead.Header.BaseHeader.DataSourceId then
begin
Result := tmpHead;
end;
end;
end;
end;
end;
function LoadFuturesDataFromBuffer(ADataAccess: TFuturesDataAccess; AMemory: pointer): Boolean;
var
tmpHead: PStore_Quote_M1_Day_Header_V1Rec;
tmpQuoteData: PStore_Quote64_M1;
tmpStoreDayData: PStore_Quote64_M1_Day_V1;
tmpRTDayData: PRT_Quote_M1_Day;
tmpRecordCount: integer;
i: integer;
begin
Result := false;
tmpHead := ReadFuturesDataHeader(ADataAccess, AMemory);
if nil <> tmpHead then
begin
tmpRecordCount := tmpHead.Header.BaseHeader.RecordCount;
Inc(tmpHead);
tmpQuoteData := PStore_Quote64_M1(tmpHead);
for i := 0 to tmpRecordCount - 1 do
begin
Result := true;
tmpStoreDayData := PStore_Quote64_M1_Day_V1(tmpQuoteData);
tmpRTDayData := ADataAccess.CheckOutRecord(tmpStoreDayData.DealDate);
if nil <> tmpRTDayData then
begin
StorePriceRange2RTPricePackRange(@tmpRTDayData.PriceRange, @tmpStoreDayData.PriceRange);
tmpRTDayData.DealVolume := tmpStoreDayData.DealVolume; // 8 - 24 成交量
tmpRTDayData.DealAmount := tmpStoreDayData.DealAmount; // 8 - 32 成交金额
tmpRTDayData.Weight.Value := tmpStoreDayData.Weight.Value; // 4 - 40 复权权重 * 100
tmpRTDayData.TotalValue := tmpStoreDayData.TotalValue; // 8 - 48 总市值
tmpRTDayData.DealValue := tmpStoreDayData.DealValue; // 8 - 56 流通市值
end;
Inc(tmpQuoteData);
end;
end;
end;
function CheckNeedLoadFuturesData(App: TBaseApp; ADataAccess: TFuturesDataAccess; ALastDate: Word): Boolean;
var
tmpWinFile: TWinFile;
tmpFileUrl: string;
tmpFileMapView: Pointer;
tmpHead: PStore_Quote_M1_Day_Header_V1Rec;
begin
Result := true;
tmpFileUrl := App.Path.GetFileUrl(FilePath_DBType_DayData, ADataAccess.DataSourceId, 1, ADataAccess.DealItem);
if App.Path.IsFileExists(tmpFileUrl) then
begin
tmpWinFile := TWinFile.Create;
try
if tmpWinFile.OpenFile(tmpFileUrl, false) then
begin
tmpFileMapView := tmpWinFile.OpenFileMap;
if nil <> tmpFileMapView then
begin
tmpHead := ReadFuturesDataHeader(ADataAccess, tmpFileMapView);
if nil <> tmpHead then
begin
if tmpHead.Header.LastDealDate >= ALastDate then
begin
Result := false;
end;
if Result then
begin
LoadFuturesDataFromBuffer(ADataAccess, tmpFileMapView);
end;
end;
end;
end;
finally
tmpWinFile.Free;
end;
end;
end;
end.
|
unit URestore;
interface
uses Classes;
type
TRestoreFileInfo = class(TObject)
protected
FBasePath : string;
FList : TStrings;
procedure RestoreList;
public
procedure Restore(const fn : string);
end;
implementation
uses SysUtils, JclStrings, JclFileutils, ISO8601;
{ TRestoreFileInfo }
procedure TRestoreFileInfo.Restore(const fn: string);
begin
FBasePath := ExtractFilePath(fn);
FList := TStringList.Create;
try
FList.LoadFromFile(fn);
RestoreList;
finally
FList.Free;
end;
end;
procedure TRestoreFileInfo.RestoreList;
var
i : Integer;
s : String;
fn : string;
dt : TDateTime;
relpath : string;
begin
for i := 1 to FList.Count - 1 do
begin
s := FList[i];
if (s <> '') and (s[1]='[') then
begin
// read relative path
relpath := copy(s, 2, Length(s)-2);
Continue;
end;
fn := StrToken(s, '|');
if relpath <> '' then
fn := ExtractFileName(fn); // for backward compatibility
fn := FBasePath + relpath + fn;
if FileExists(fn) then
begin
dt := ISO8601StrToDateTime(StrToken(s, '|'));
//SetFileLastAccess(fn, dt);
SetFileLastWrite(fn, dt);
//SetFileCreation(fn, dt);
end;
end;
end;
end.
|
unit TTSPasswordTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSPasswordRecord = record
PUserName: String[10];
PPassword: String[50];
PCreated: TDateTime;
PInvalidAttempts: Integer;
PLastLoginAttempt: TDateTime;
PModifiedBy: String[10];
PStatus: String[10];
End;
TTTSPasswordBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSPasswordRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSPassword = (TTSPasswordByUserPassword, TTSPasswordByUserCreated, TTSPasswordByUserStatus, TTSPasswordByUserPasswordStatus);
TTTSPasswordTable = class( TDBISAMTableAU )
private
FDFUserName: TStringField;
FDFPassword: TStringField;
FDFCreated: TDateTimeField;
FDFInvalidAttempts: TIntegerField;
FDFLastLoginAttempt: TDateTimeField;
FDFModifiedBy: TStringField;
FDFStatus: TStringField;
procedure SetPUserName(const Value: String);
function GetPUserName:String;
procedure SetPPassword(const Value: String);
function GetPPassword:String;
procedure SetPCreated(const Value: TDateTime);
function GetPCreated:TDateTime;
procedure SetPInvalidAttempts(const Value: Integer);
function GetPInvalidAttempts:Integer;
procedure SetPLastLoginAttempt(const Value: TDateTime);
function GetPLastLoginAttempt:TDateTime;
procedure SetPModifiedBy(const Value: String);
function GetPModifiedBy:String;
procedure SetPStatus(const Value: String);
function GetPStatus:String;
procedure SetEnumIndex(Value: TEITTSPassword);
function GetEnumIndex: TEITTSPassword;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSPasswordRecord;
procedure StoreDataBuffer(ABuffer:TTTSPasswordRecord);
property DFUserName: TStringField read FDFUserName;
property DFPassword: TStringField read FDFPassword;
property DFCreated: TDateTimeField read FDFCreated;
property DFInvalidAttempts: TIntegerField read FDFInvalidAttempts;
property DFLastLoginAttempt: TDateTimeField read FDFLastLoginAttempt;
property DFModifiedBy: TStringField read FDFModifiedBy;
property DFStatus: TStringField read FDFStatus;
property PUserName: String read GetPUserName write SetPUserName;
property PPassword: String read GetPPassword write SetPPassword;
property PCreated: TDateTime read GetPCreated write SetPCreated;
property PInvalidAttempts: Integer read GetPInvalidAttempts write SetPInvalidAttempts;
property PLastLoginAttempt: TDateTime read GetPLastLoginAttempt write SetPLastLoginAttempt;
property PModifiedBy: String read GetPModifiedBy write SetPModifiedBy;
property PStatus: String read GetPStatus write SetPStatus;
published
property Active write SetActive;
property EnumIndex: TEITTSPassword read GetEnumIndex write SetEnumIndex;
end; { TTTSPasswordTable }
procedure Register;
implementation
procedure TTTSPasswordTable.CreateFields;
begin
FDFUserName := CreateField( 'UserName' ) as TStringField;
FDFPassword := CreateField( 'Password' ) as TStringField;
FDFCreated := CreateField( 'Created' ) as TDateTimeField;
FDFInvalidAttempts := CreateField( 'InvalidAttempts' ) as TIntegerField;
FDFLastLoginAttempt := CreateField( 'LastLoginAttempt' ) as TDateTimeField;
FDFModifiedBy := CreateField( 'ModifiedBy' ) as TStringField;
FDFStatus := CreateField( 'Status' ) as TStringField;
end; { TTTSPasswordTable.CreateFields }
procedure TTTSPasswordTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSPasswordTable.SetActive }
procedure TTTSPasswordTable.SetPUserName(const Value: String);
begin
DFUserName.Value := Value;
end;
function TTTSPasswordTable.GetPUserName:String;
begin
result := DFUserName.Value;
end;
procedure TTTSPasswordTable.SetPPassword(const Value: String);
begin
DFPassword.Value := Value;
end;
function TTTSPasswordTable.GetPPassword:String;
begin
result := DFPassword.Value;
end;
procedure TTTSPasswordTable.SetPCreated(const Value: TDateTime);
begin
DFCreated.Value := Value;
end;
function TTTSPasswordTable.GetPCreated:TDateTime;
begin
result := DFCreated.Value;
end;
procedure TTTSPasswordTable.SetPInvalidAttempts(const Value: Integer);
begin
DFInvalidAttempts.Value := Value;
end;
function TTTSPasswordTable.GetPInvalidAttempts:Integer;
begin
result := DFInvalidAttempts.Value;
end;
procedure TTTSPasswordTable.SetPLastLoginAttempt(const Value: TDateTime);
begin
DFLastLoginAttempt.Value := Value;
end;
function TTTSPasswordTable.GetPLastLoginAttempt:TDateTime;
begin
result := DFLastLoginAttempt.Value;
end;
procedure TTTSPasswordTable.SetPModifiedBy(const Value: String);
begin
DFModifiedBy.Value := Value;
end;
function TTTSPasswordTable.GetPModifiedBy:String;
begin
result := DFModifiedBy.Value;
end;
procedure TTTSPasswordTable.SetPStatus(const Value: String);
begin
DFStatus.Value := Value;
end;
function TTTSPasswordTable.GetPStatus:String;
begin
result := DFStatus.Value;
end;
procedure TTTSPasswordTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
//VG 260717: RecId added as a primary key, because otherwise DBISAM4 ads one automatically, which causes the VerifyStructure to fail
Add('RecId, AutoInc, 0, N');
Add('UserName, String, 10, N');
Add('Password, String, 50, N');
Add('Created, TDateTime, 0, N');
Add('InvalidAttempts, Integer, 0, N');
Add('LastLoginAttempt, TDateTime, 0, N');
Add('ModifiedBy, String, 10, N');
Add('Status, String, 10, N');
end;
end;
procedure TTTSPasswordTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, RecId, Y, Y, N, N');
Add('ByUserPassword, UserName;Password, N, N, N, N');
Add('ByUserCreated, UserName;Created, N, N, N, N');
Add('ByUserStatus, UserName;Status, N, N, N, N');
Add('ByUserPasswordStatus, UserName;Password;Status, N, N, N, N');
end;
end;
procedure TTTSPasswordTable.SetEnumIndex(Value: TEITTSPassword);
begin
case Value of
TTSPasswordByUserPassword: IndexName := 'ByUserPassword';
TTSPasswordByUserCreated : IndexName := 'ByUserCreated';
TTSPasswordByUserStatus : IndexName := 'ByUserStatus';
TTSPasswordByUserPasswordStatus : IndexName := 'ByUserPasswordStatus';
end;
end;
function TTTSPasswordTable.GetDataBuffer:TTTSPasswordRecord;
var buf: TTTSPasswordRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PUserName := DFUserName.Value;
buf.PPassword := DFPassword.Value;
buf.PCreated := DFCreated.Value;
buf.PInvalidAttempts := DFInvalidAttempts.Value;
buf.PLastLoginAttempt := DFLastLoginAttempt.Value;
buf.PModifiedBy := DFModifiedBy.Value;
buf.PStatus := DFStatus.Value;
result := buf;
end;
procedure TTTSPasswordTable.StoreDataBuffer(ABuffer:TTTSPasswordRecord);
begin
DFUserName.Value := ABuffer.PUserName;
DFPassword.Value := ABuffer.PPassword;
DFCreated.Value := ABuffer.PCreated;
DFInvalidAttempts.Value := ABuffer.PInvalidAttempts;
DFLastLoginAttempt.Value := ABuffer.PLastLoginAttempt;
DFModifiedBy.Value := ABuffer.PModifiedBy;
DFStatus.Value := ABuffer.PStatus;
end;
function TTTSPasswordTable.GetEnumIndex: TEITTSPassword;
var iname : string;
begin
result := TTSPasswordByUserPassword;
iname := uppercase(indexname);
if iname = '' then result := TTSPasswordByUserPassword;
if iname = 'BYUSERCREATED' then result := TTSPasswordByUserCreated;
if iname = 'BYUSERSTATUS' then result := TTSPasswordByUserStatus;
if iname = 'BYUSERPASSWORDSTATUS' then result := TTSPasswordByUserPasswordStatus;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSPasswordTable, TTTSPasswordBuffer ] );
end; { Register }
function TTTSPasswordBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..7] of string = ('USERNAME','PASSWORD','CREATED','INVALIDATTEMPTS','LASTLOGINATTEMPT','MODIFIEDBY'
,'STATUS' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 7) and (flist[x] <> s) do inc(x);
if x <= 7 then result := x else result := 0;
end;
function TTTSPasswordBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftDateTime;
4 : result := ftInteger;
5 : result := ftDateTime;
6 : result := ftString;
7 : result := ftString;
end;
end;
function TTTSPasswordBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PUserName;
2 : result := @Data.PPassword;
3 : result := @Data.PCreated;
4 : result := @Data.PInvalidAttempts;
5 : result := @Data.PLastLoginAttempt;
6 : result := @Data.PModifiedBy;
7 : result := @Data.PStatus;
end;
end;
end. |
unit CliViejo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, ComCtrls, ExtCtrls, Db, DBTables, DBActns, ActnList,
Menus, ImgList, ToolWin, JvFormPlacement, JvAppStorage,
JvAppIniStorage, JvComponentBase,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles,
dxSkinsCore, cxCustomData,
cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView,
cxGrid, System.Actions, cxNavigator;
type
TFCliViejo = class(TForm)
MainMenu1: TMainMenu;
PopupMenu1: TPopupMenu;
ImageList1: TImageList;
ActionList1: TActionList;
Ventana1: TMenuItem;
Salir1: TMenuItem;
Cancel1: TDataSetCancel;
Delete1: TDataSetDelete;
Edit1: TDataSetEdit;
First1: TDataSetFirst;
Insert1: TDataSetInsert;
Last1: TDataSetLast;
Next1: TDataSetNext;
Post1: TDataSetPost;
Prior1: TDataSetPrior;
Refresh1: TDataSetRefresh;
DataSource1: TDataSource;
Panel1: TPanel;
StatusBar1: TStatusBar;
Editar1: TMenuItem;
Primero1: TMenuItem;
Anterior1: TMenuItem;
Siguiente1: TMenuItem;
Ultimo1: TMenuItem;
N1: TMenuItem;
Ayuda1: TMenuItem;
Informacion1: TMenuItem;
Salir: TAction;
ControlBar1: TControlBar;
ToolBar1: TToolBar;
ToolButton7: TToolButton;
ToolButton11: TToolButton;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton10: TToolButton;
ToolButton5: TToolButton;
Activar: TAction;
Activar1: TMenuItem;
Borrar1: TMenuItem;
JvFormPlacement1: TJvFormStorage;
JvAppIniFileStorage1: TJvAppIniFileStorage;
vista: TcxGridDBTableView;
nivel: TcxGridLevel;
cxGrid1: TcxGrid;
vistaCODIGO: TcxGridDBColumn;
vistaDENOMINA: TcxGridDBColumn;
vistaDIRECCION: TcxGridDBColumn;
vistaLOCALIDAD: TcxGridDBColumn;
vistaPCIA: TcxGridDBColumn;
vistaCPOS: TcxGridDBColumn;
vistaTELEFONO: TcxGridDBColumn;
vistaFAX: TcxGridDBColumn;
vistaCUIT: TcxGridDBColumn;
vistaIVA: TcxGridDBColumn;
vistaSALDO: TcxGridDBColumn;
vistaSALDODOC: TcxGridDBColumn;
vistaDESCUENTO: TcxGridDBColumn;
vistaDESTO2: TcxGridDBColumn;
vistadesto3: TcxGridDBColumn;
vistaLISTA: TcxGridDBColumn;
vistaCREDITO: TcxGridDBColumn;
vistaTRANSPORTE: TcxGridDBColumn;
vistaENTREGA: TcxGridDBColumn;
vistaVENDEDOR: TcxGridDBColumn;
vistaDIREPOSTAL: TcxGridDBColumn;
vistaLOCAPOSTAL: TcxGridDBColumn;
vistaPCIAPOSTAL: TcxGridDBColumn;
vistaCPOSPOS: TcxGridDBColumn;
vistaActivo: TcxGridDBColumn;
vistaFecha: TcxGridDBColumn;
vistaCondic: TcxGridDBColumn;
vistaEmail: TcxGridDBColumn;
vistaTipo: TcxGridDBColumn;
vistaModiRec: TcxGridDBColumn;
vistaModiFac: TcxGridDBColumn;
vistaContacto: TcxGridDBColumn;
vistaRubro: TcxGridDBColumn;
vistaZona: TcxGridDBColumn;
vistaIBrutos: TcxGridDBColumn;
vistaObservaciones: TcxGridDBColumn;
vistaELIMINADO: TcxGridDBColumn;
procedure Salir1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SalirExecute(Sender: TObject);
procedure DataSource1UpdateData(Sender: TObject);
procedure ActivarExecute(Sender: TObject);
procedure DBGrid1KeyPress(Sender: TObject; var Key: Char);
procedure Delete1Execute(Sender: TObject);
private
{ Private declarations }
FVieProc: TNotifyEvent;
FValor: string;
procedure AddKey( Tecla: char );
procedure OnNuevoRegistro( DataSet: TDataSet );
public
{ Public declarations }
procedure EnHint( Sender: TObject );
end;
var
FCliViejo: TFCliViejo;
implementation
uses
DMIng;
{$R *.DFM}
procedure TFCliViejo.Salir1Click(Sender: TObject);
begin
Close;
end;
procedure TFCliViejo.FormCreate(Sender: TObject);
begin
FVieProc := Application.OnHint;
Application.OnHint := EnHint;
( DataSource1.DataSet ).OnNewRecord := OnNuevoRegistro;
( DataSource1.DataSet ).Open;
end;
procedure TFCliViejo.FormDestroy(Sender: TObject);
begin
Application.OnHint := FVieProc;
( DataSource1.DataSet ).OnNewRecord := nil;
( DataSource1.DataSet ).Close;
end;
procedure TFCliViejo.EnHint(Sender: TObject);
begin
StatusBar1.SimpleText := Application.Hint;
end;
procedure TFCliViejo.SalirExecute(Sender: TObject);
begin
close;
end;
procedure TFCliViejo.DataSource1UpdateData(Sender: TObject);
begin
// tomar valores de campos para ser insertados en nuevo registro
// como ultimo valor grabado.
end;
procedure TFCliViejo.OnNuevoRegistro(DataSet: TDataSet);
begin
// asignar valores de inicio al nuevo registro
end;
procedure TFCliViejo.ActivarExecute(Sender: TObject);
var
x: integer;
begin
if MessageDlg( 'Confirma Activacion de Cliente ?', mtConfirmation, [ mbYes, mbNo ],0 ) = mrYes then
with DataIng do
begin
application.ProcessMessages;
TDeu.Append;
for x:=0 to TCliVie.Fields.Count-1 do
TDeu.FieldbyName( TCliVie.Fields[ x ].FieldName ).Value := TCliVie.Fields[ x ].Value;
try
TDeuACTIVO.value := true;
TDeuELIMINADO.value := 'N';
MessageBeep( 0 );
TCliVie.delete;
TDeu.post;
except
on e:exception do
begin
TDeu.Cancel;
showmessage( e.Message );
end;
end;
end;
end;
procedure TFCliViejo.DBGrid1KeyPress(Sender: TObject; var Key: Char);
begin
AddKey( Key );
try
Screen.cursor := crHourglass;
DataIng.TCliVie.DisableControls;
DataIng.TCliVie.locate( 'CODIGO', FValor, [locaseinsensitive] );
finally
DataIng.TCliVie.EnableControls;
Screen.cursor := crdefault;
end;
end;
procedure TFCliViejo.AddKey(Tecla: char);
begin
if Tecla = #27 then
FValor := ''
else if Tecla <> #8 then
FValor := FValor + Tecla
else if Length( FValor ) > 1 then
FValor := Copy( FValor, 1, length( FValor ) - 1 )
else
FValor := '';
end;
procedure TFCliViejo.Delete1Execute(Sender: TObject);
begin
if MessageDlg( 'Elimina Definitivamente el Cliente ? ', mtWarning, [ mbYes, mbNo ], 0 ) <> mrYes then
abort;
end;
end.
|
unit SincroDataDM;
interface
uses
SysUtils, Classes, DB, DBTables, StdCtrls, ComCtrls, Forms ;
type
TDSincroData = class(TDataModule)
dbSAT: TDatabase;
dbBAGChanita: TDatabase;
dbBAGP4H: TDatabase;
dbBAGTenerife: TDatabase;
dbBAGSevilla: TDatabase;
qrySAT: TQuery;
dbBAG: TDatabase;
qryBAG: TQuery;
qryBAGChanita: TQuery;
qryBAGP4H: TQuery;
qryBAGTenerife: TQuery;
qryBAGSevilla: TQuery;
dbSATTenerife: TDatabase;
dbSATLlanos: TDatabase;
qrySATLlanos: TQuery;
qrySATTenerife: TQuery;
dbCentral: TDatabase;
qryCentral: TQuery;
dbAlmacen: TDatabase;
qryAlmacen: TQuery;
dbRF: TDatabase;
qryRF: TQuery;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
procedure AlbaranesVenta( var VMsg: string );
procedure TraerRf( var VMsg: string );
public
{ Public declarations }
(*
function ExisteTabla( const ATabName: string ): boolean;
procedure BorrarSiExisteTabla( const ATabName: string );
*)
procedure AlbaranesVentaLlanos( var VMsg: string );
procedure TraerRfChanita( var VMsg: string );
end;
var
DSincroData: TDSincroData;
implementation
uses
dialogs, variants;
{$R *.dfm}
(*
function TDAlmacenes.ExisteTabla( const ATabName: string ): boolean;
begin
with QCentral do
begin
SQL.Clear;
SQL.Add('select * from systables where tabname = :tabname ');
ParamByName('tabname').AsString:= ATabName;
Open;
result:= not IsEmpty;
Close;
end;
end;
procedure TDAlmacenes.BorrarSiExisteTabla( const ATabName: string );
begin
If ExisteTabla(ATabName) then
begin
with QCentral do
begin
SQL.Clear;
SQL.Add('drop table ' + ATabName );
ExecSQL;
end;
end;
end;
*)
procedure TDSincroData.TraerRfChanita( var VMsg: string );
begin
dbRF.Connected:= True;
dbBAGChanita.Connected:= True;
dbCentral:= dbSAT;
dbAlmacen:= dbSATLlanos;
try
TraerRf( VMsg );
finally
dbRF.Connected:= True;
dbBAGChanita.Connected:= True;
end;
end;
procedure TDSincroData.TraerRf( var VMsg: string );
begin
qryCentral.SQL.Clear;
qryCentral.SQL.Add('delete from rf_palet_pb ');
qryCentral.ExecSQL;
qryCentral.SQL.Clear;
qryCentral.SQL.Add('select * from rf_palet_pb ');
qryCentral.Open;
qryAlmacen.SQL.Clear;
qryAlmacen.SQL.Add('select * from rf_palet_pb where date(fechamarca) < today - 365 ');
qryAlmacen.Open;
end;
procedure TDSincroData.AlbaranesVentaLlanos( var VMsg: string );
begin
dbSAT.Connected:= True;
dbSATLlanos.Connected:= True;
dbCentral:= dbSAT;
dbAlmacen:= dbSATLlanos;
try
AlbaranesVenta( VMsg );
finally
dbSAT.Connected:= True;
dbSATLlanos.Connected:= True;
end;
end;
procedure TDSincroData.AlbaranesVenta( var VMsg: string );
begin
qryAlmacen.SQL.Clear;
//qryAlmacen.SQL.Add('select * from frf_salidas_c join frf_salidas_l where fecha_sc between '21/10/2014' and '21/10/2015');
end.
|
unit ATxMsg;
interface
var
MsgViewerErrCannotFindText: string = 'Search string not found: "%s"';
MsgViewerErrInvalidHex: string = 'Hex string is invalid: "%s"';
MsgViewerErrInvalidFilelist: string = 'Cannot handle files list: "%s"';
MsgViewerSearchProgress: string = 'Searching for "%s":';
MsgViewerLangMissed: string = 'Language file "%s" not found.'#13'Try to reinstall application or delete the Viewer.ini file.';
MsgViewerJumpToFirst: string = 'This is the last file in directory. Jump to the first file?';
MsgViewerJumpToLast: string = 'This is the first file in directory. Jump to the last file?';
MsgViewerJumpNotFound: string = 'Current filename "%s" is not found in directory. Jump to the first file?';
MsgViewerJumpDirEmpty: string = 'Current directory is empty. Cannot jump to another file.';
MsgViewerJumpSingleFile: string = 'This is the single file in directory. Cannot jump to another file.';
MsgViewerDirEmpty: string = 'Folder is empty: "%s"';
MsgViewerPluginsNameNotFound: string = '(not found)';
MsgViewerPluginsLabelTCIni: string = 'Total Commander configuration &file:';
MsgViewerPluginsLabelFile: string = '&File:';
MsgViewerPluginsLabelFolder: string = '&Folder:';
MsgViewerPluginsFilterExe: string = 'Applications (*.exe)|*.EXE';
MsgViewerPluginsFilterIni: string = 'Ini files (*.ini)|*.INI';
MsgViewerPluginsFilterWLX: string = 'Plugins (*.wlx)|*.WLX';
MsgViewerPluginsFilterZip: string = 'Archives (*.zip;*.rar)|*.ZIP;*.RAR';
MsgViewerPluginsNone: string = '(none)'#13;
MsgViewerPluginsInstalled: string =
'The following plugins were added:'#13#13'%s'#13+
'The following plugins are already installed and were not added:'#13#13'%s';
MsgViewerPluginsInstalledZip: string =
'The following plugins were added:'#13#13'%s'#13+
'The following plugins were updated:'#13#13'%s';
MsgViewerPluginUnsup: string = 'This archive contains plugin of unsupported type (%s)';
MsgViewerPluginSup: string = 'This archive contains plugin:'#13'"%s".'#13#13'Do you want to install it in Universal Viewer?';
MsgViewerPluginsInvalidFile: string = 'Source file/folder name is not valid';
MsgViewerPluginsInvalidTCExe: string = 'Selected Total Commander executable name is not valid';
MsgViewerDeleteCaption: string = 'Delete file';
MsgViewerDeleteWarningRecycle: string = 'Do you want to move "%s" to Recycle Bin?';
MsgViewerDeleteWarningPermanent: string = 'Do you want to delete "%s"?';
MsgViewerCopyMoveError: string = 'Cannot copy/move "%s" to "%s"';
MsgViewerDeleteError: string = 'Cannot delete "%s"';
MsgViewerIconDef: string = '(Default)';
MsgViewerIconSave: string = '(Save template...)';
MsgViewerExifMissed: string = 'No EXIF information in this file';
MsgViewerNavMissed: string = 'Cannot find NavPanel add-on (Nav.exe)';
implementation
end.
|
unit skykid_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m6809,m680x,namco_snd,main_engine,controls_engine,gfx_engine,rom_engine,
pal_engine,misc_functions,sound_engine;
function iniciar_skykid:boolean;
implementation
const
//Sky Kid
skykid_rom:array[0..2] of tipo_roms=(
(n:'sk2_2.6c';l:$4000;p:$0;crc:$ea8a5822),(n:'sk1-1c.6b';l:$4000;p:$4000;crc:$7abe6c6c),
(n:'sk1_3.6d';l:$4000;p:$8000;crc:$314b8765));
skykid_char:tipo_roms=(n:'sk1_6.6l';l:$2000;p:0;crc:$58b731b9);
skykid_tiles:tipo_roms=(n:'sk1_5.7e';l:$2000;p:0;crc:$c33a498e);
skykid_sprites:array[0..1] of tipo_roms=(
(n:'sk1_8.10n';l:$4000;p:0;crc:$44bb7375),(n:'sk1_7.10m';l:$4000;p:$4000;crc:$3454671d));
skykid_mcu:array[0..1] of tipo_roms=(
(n:'sk2_4.3c';l:$2000;p:$8000;crc:$a460d0e0),(n:'cus63-63a1.mcu';l:$1000;p:$f000;crc:$6ef08fb3));
skykid_prom:array[0..4] of tipo_roms=(
(n:'sk1-1.2n';l:$100;p:$0;crc:$0218e726),(n:'sk1-2.2p';l:$100;p:$100;crc:$fc0d5b85),
(n:'sk1-3.2r';l:$100;p:$200;crc:$d06b620b),(n:'sk1-4.5n';l:$200;p:$300;crc:$c697ac72),
(n:'sk1-5.6n';l:$200;p:$500;crc:$161514a4));
//Dragon Buster
drgnbstr_rom:array[0..2] of tipo_roms=(
(n:'db1_2b.6c';l:$4000;p:$0;crc:$0f11cd17),(n:'db1_1.6b';l:$4000;p:$4000;crc:$1c7c1821),
(n:'db1_3.6d';l:$4000;p:$8000;crc:$6da169ae));
drgnbstr_char:tipo_roms=(n:'db1_6.6l';l:$2000;p:0;crc:$c080b66c);
drgnbstr_tiles:tipo_roms=(n:'db1_5.7e';l:$2000;p:0;crc:$28129aed);
drgnbstr_sprites:array[0..1] of tipo_roms=(
(n:'db1_8.10n';l:$4000;p:0;crc:$11942c61),(n:'db1_7.10m';l:$4000;p:$4000;crc:$cc130fe2));
drgnbstr_mcu:array[0..1] of tipo_roms=(
(n:'db1_4.3c';l:$2000;p:$8000;crc:$8a0b1fc1),(n:'cus60-60a1.mcu';l:$1000;p:$f000;crc:$076ea82a));
drgnbstr_prom:array[0..4] of tipo_roms=(
(n:'db1-1.2n';l:$100;p:$0;crc:$3f8cce97),(n:'db1-2.2p';l:$100;p:$100;crc:$afe32436),
(n:'db1-3.2r';l:$100;p:$200;crc:$c95ff576),(n:'db1-4.5n';l:$200;p:$300;crc:$b2180c21),
(n:'db1-5.6n';l:$200;p:$500;crc:$5e2b3f74));
var
rom_bank:array[0..1,0..$1fff] of byte;
rom_nbank,scroll_y,inputport_selected,priority:byte;
scroll_x:word;
irq_enable,irq_enable_mcu,screen_flip:boolean;
procedure update_video_skykid;
procedure draw_sprites;
var
nchar,color,x:word;
f,flipx_v,flipy_v,atrib,y,size,a,b,c,d,mix:byte;
flipx,flipy:boolean;
begin
for f:=0 to $3f do begin
atrib:=memoria[$5f80+(f*2)];
nchar:=memoria[$4f80+(f*2)]+((atrib and $80) shl 1);
color:=((memoria[$4f81+(f*2)] and $3f) shl 3)+$200;
flipx_v:=not(atrib) and $01;
flipy_v:=not(atrib) and $02;
flipx:=(flipx_v=0);
flipy:=(flipy_v=0);
if screen_flip then begin
x:=((memoria[$5781+(f*2)]+(memoria[$5f81+(f*2)] and 1) shl 8)-71) and $1ff;
y:=((256-memoria[$5780+(f*2)]-7) and $ff)-32;
if (atrib and $8)<>0 then y:=y-16;
end else begin
x:=(327-(memoria[$5781+(f*2)]+(memoria[$5f81+(f*2)] and 1) shl 8)) and $1ff;
y:=(memoria[$5780+(f*2)])-9;
if (atrib and $4)=0 then x:=x+16;
end;
size:=(atrib and $c) shr 2;
case size of
0:begin //16x16
put_gfx_sprite_mask(nchar,color,flipx,flipy,1,$f,$f);
actualiza_gfx_sprite(x,y,3,1);
end;
1:begin //32x16
a:=1 xor flipx_v;
b:=0 xor flipx_v;
put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,15,$f,0,0);
put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,15,$f,16,0);
actualiza_gfx_sprite_size(x,y,3,32,16);
end;
2:begin //16x32
a:=2 xor flipy_v;
b:=0 xor flipy_v;
put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,15,$f,0,0);
put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,15,$f,0,16);
actualiza_gfx_sprite_size(x,y,3,16,32);
end;
3:begin //32x32
if flipx then begin
a:=1;b:=0;c:=3;d:=2
end else begin
a:=0;b:=1;c:=2;d:=3;
end;
if flipy then begin
mix:=a;a:=c;c:=mix;
mix:=b;b:=d;d:=mix;
end;
put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,15,$f,0,0);
put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,15,$f,16,0);
put_gfx_sprite_mask_diff(nchar+c,color,flipx,flipy,1,15,$f,0,16);
put_gfx_sprite_mask_diff(nchar+d,color,flipx,flipy,1,15,$f,16,16);
actualiza_gfx_sprite_size(x,y,3,32,32);
end;
end;
end;
end;
var
f,color,nchar,offs:word;
x,y,sx,sy,atrib:byte;
begin
for x:=0 to 27 do begin
for y:=0 to 35 do begin
sx:=x+2;
sy:=y-2;
if (sy and $20)<>0 then offs:=sx+((sy and $1f) shl 5)
else offs:=sy+(sx shl 5);
if gfx[0].buffer[offs] then begin
color:=((memoria[$4400+offs]) and $3f) shl 2;
put_gfx_trans(y*8,x*8,memoria[$4000+offs],color,1,0);
gfx[0].buffer[offs]:=false;
end;
end;
end;
for f:=0 to $7ff do begin
if gfx[2].buffer[f] then begin
x:=f mod 64;
y:=f div 64;
atrib:=memoria[$2800+f];
color:=(((atrib and $7e) shr 1)+((atrib and $01) shl 6)) shl 2;
nchar:=memoria[$2000+f]+(atrib and $1) shl 8;
put_gfx(x*8,y*8,nchar,color,2,2);
gfx[2].buffer[f]:=false;
end;
end;
scroll_x_y(2,3,scroll_x,scroll_y);
if (priority and $f0)<>$50 then begin
draw_sprites;
actualiza_trozo(0,0,288,224,1,0,0,288,224,3);
end else begin
actualiza_trozo(0,0,288,224,1,0,0,288,224,3);
draw_sprites;
end;
actualiza_trozo_final(0,0,288,224,3);
end;
procedure eventos_skykid;
begin
if event.arcade then begin
//P1
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8);
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.but1[0] then marcade.in3:=(marcade.in3 and $f7) else marcade.in3:=(marcade.in3 or $8);
//P2
if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but1[1] then marcade.in3:=(marcade.in3 and $fb) else marcade.in3:=(marcade.in3 or $4);
//COIN
if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
end;
end;
procedure skykid_principal;
var
f:byte;
frame_m,frame_mcu:single;
begin
init_controls(false,false,false,true);
frame_m:=m6809_0.tframes;
frame_mcu:=m6800_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 223 do begin
//Main CPU
m6809_0.run(frame_m);
frame_m:=frame_m+m6809_0.tframes-m6809_0.contador;
//Sound CPU
m6800_0.run(frame_mcu);
frame_mcu:=frame_mcu+m6800_0.tframes-m6800_0.contador;
end;
if irq_enable then m6809_0.change_irq(ASSERT_LINE);
if irq_enable_mcu then m6800_0.change_irq(ASSERT_LINE);
update_video_skykid;
eventos_skykid;
video_sync;
end;
end;
function skykid_getbyte(direccion:word):byte;
begin
case direccion of
$0..$1fff:skykid_getbyte:=rom_bank[rom_nbank,direccion];
$2000..$2fff,$4000..$5fff,$8000..$ffff:skykid_getbyte:=memoria[direccion];
$6800..$6bff:skykid_getbyte:=namco_snd_0.namcos1_cus30_r(direccion and $3ff);
end;
end;
procedure skykid_putbyte(direccion:word;valor:byte);
begin
case direccion of
$0..$1fff,$a002..$ffff:; //ROM
$2000..$2fff:if memoria[direccion]<>valor then begin
gfx[2].buffer[direccion and $7ff]:=true;
memoria[direccion]:=valor;
end;
$4000..$47ff:if memoria[direccion]<>valor then begin
gfx[0].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$4800..$5fff:memoria[direccion]:=valor;
$6000..$60ff:begin
scroll_y:=direccion and $ff;
if screen_flip then scroll_y:=(scroll_y+25) and $ff
else scroll_y:=(7-scroll_y) and $ff;
end;
$6200..$63ff:begin
scroll_x:=direccion and $1ff;
if screen_flip then scroll_x:=(scroll_x+35) and $1ff
else scroll_x:=(189-(scroll_x xor 1)) and $1ff;
end;
$6800..$6bff:namco_snd_0.namcos1_cus30_w(direccion and $3ff,valor);
$7000..$7fff:begin
irq_enable:=not(BIT((direccion and $fff),11));
if not(irq_enable) then m6809_0.change_irq(CLEAR_LINE);
end;
$8000..$8fff:if not(BIT((direccion and $fff),11)) then m6800_0.reset;
$9000..$9fff:rom_nbank:=(not(BIT_n((direccion and $fff),11))) and 1;
$a000..$a001:priority:=valor;
end;
end;
function mcu_getbyte(direccion:word):byte;
begin
case direccion of
$0..$ff:mcu_getbyte:=m6800_0.m6803_internal_reg_r(direccion);
$1000..$13ff:mcu_getbyte:=namco_snd_0.namcos1_cus30_r(direccion and $3ff);
$8000..$c7ff,$f000..$ffff:mcu_getbyte:=mem_snd[direccion];
end;
end;
procedure mcu_putbyte(direccion:word;valor:byte);
begin
case direccion of
$0..$ff:m6800_0.m6803_internal_reg_w(direccion,valor);
$1000..$13ff:namco_snd_0.namcos1_cus30_w(direccion and $3ff,valor);
$4000..$7fff:begin
irq_enable_mcu:=not(BIT(direccion and $3fff,13));
if not(irq_enable_mcu) then m6800_0.change_irq(CLEAR_LINE);
end;
$8000..$bfff,$f000..$ffff:; //ROM
$c000..$cfff:mem_snd[direccion]:=valor;
end;
end;
procedure skykid_sound_update;
begin
namco_snd_0.update;
end;
procedure out_port1(valor:byte);
begin
if ((valor and $e0)=$60) then inputport_selected:=valor and $07;
end;
function in_port1:byte;
begin
case inputport_selected of
$00:in_port1:=(($ff) and $f8) shr 3; // DSW B (bits 0-4) */
$01:in_port1:=((($ff) and $7) shl 2) or ((($ff) and $c0) shr 6);// DSW B (bits 5-7), DSW A (bits 0-1) */
$02:in_port1:=(($ff) and $3e) shr 1; // DSW A (bits 2-6) */
$03:in_port1:=((($ff) and $1) shl 4) or (marcade.in3 and $f); // DSW A (bit 7), DSW C (bits 0-3) */
$04:in_port1:=marcade.in2; // coins, start */
$05:in_port1:=marcade.in1; // 2P controls */
$06:in_port1:=marcade.in0; // 1P controls */
else in_port1:=$ff;
end;
end;
function in_port2:byte;
begin
in_port2:=$ff;
end;
//Main
procedure reset_skykid;
begin
m6809_0.reset;
m6800_0.reset;
namco_snd_0.reset;
reset_audio;
marcade.in0:=$FF;
marcade.in1:=$FF;
marcade.in2:=$FF;
marcade.in3:=$ff;
rom_nbank:=0;
irq_enable:=false;
irq_enable_mcu:=false;
scroll_y:=0;
inputport_selected:=0;
scroll_x:=0;
end;
function iniciar_skykid:boolean;
var
colores:tpaleta;
f:word;
memoria_temp:array[0..$ffff] of byte;
const
pc_x:array[0..7] of dword=(8*8, 8*8+1, 8*8+2, 8*8+3, 0, 1, 2, 3 );
ps_x:array[0..15] of dword=(0, 1, 2, 3, 8*8, 8*8+1, 8*8+2, 8*8+3,
16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3);
ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8);
pt_x:array[0..7] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3 );
pt_y:array[0..7] of dword=(0*8, 2*8, 4*8, 6*8, 8*8, 10*8, 12*8, 14*8);
begin
iniciar_skykid:=false;
llamadas_maquina.bucle_general:=skykid_principal;
llamadas_maquina.reset:=reset_skykid;
llamadas_maquina.fps_max:=60.60606060606060;
iniciar_audio(false);
screen_init(1,288,224,true);
screen_init(2,512,256);
screen_mod_scroll(2,512,512,511,256,256,255);
screen_init(3,512,256,false,true);
iniciar_video(288,224);
//Main CPU
m6809_0:=cpu_m6809.Create(1536000,224,TCPU_M6809);
m6809_0.change_ram_calls(skykid_getbyte,skykid_putbyte);
//MCU CPU
m6800_0:=cpu_m6800.create(6144000,224,TCPU_HD63701);
m6800_0.change_ram_calls(mcu_getbyte,mcu_putbyte);
m6800_0.change_io_calls(in_port1,in_port2,nil,nil,out_port1,nil,nil,nil);
m6800_0.init_sound(skykid_sound_update);
namco_snd_0:=namco_snd_chip.create(8,true);
case main_vars.tipo_maquina of
123:begin
//cargar roms
if not(roms_load(@memoria_temp,skykid_rom)) then exit;
//Pongo las ROMs en su banco
copymemory(@memoria[$8000],@memoria_temp[$0],$8000);
for f:=0 to 1 do copymemory(@rom_bank[f,0],@memoria_temp[$8000+(f*$2000)],$2000);
//Cargar MCU
if not(roms_load(@mem_snd,skykid_mcu)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,skykid_char)) then exit;
init_gfx(0,8,8,$200);
gfx[0].trans[0]:=true;
gfx_set_desc_data(2,0,16*8,0,4);
convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,false,false);
//sprites
fillchar(memoria_temp[0],$10000,0);
if not(roms_load(@memoria_temp,skykid_sprites)) then exit;
// unpack the third sprite ROM
for f:=0 to $1fff do begin
memoria_temp[f+$4000+$4000]:=memoria_temp[f+$4000]; // sprite set #1, plane 3
memoria_temp[f+$6000+$4000]:=memoria_temp[f+$4000] shr 4; // sprite set #2, plane 3
memoria_temp[f+$4000]:=memoria_temp[f+$2000+$4000]; // sprite set #3, planes 1&2 (plane 3 is empty)
end;
init_gfx(1,16,16,$200);
gfx_set_desc_data(3,0,64*8,$200*64*8+4,0,4);
convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false);
//tiles
if not(roms_load(@memoria_temp,skykid_tiles)) then exit;
init_gfx(2,8,8,$200);
gfx_set_desc_data(2,0,16*8,0,4);
convert_gfx(2,0,@memoria_temp,@pt_x,@pt_y,false,false);
//Paleta
if not(roms_load(@memoria_temp,skykid_prom)) then exit;
screen_flip:=false;
end;
194:begin
//cargar roms
if not(roms_load(@memoria_temp,drgnbstr_rom)) then exit;
//Pongo las ROMs en su banco
copymemory(@memoria[$8000],@memoria_temp[$0],$8000);
for f:=0 to 1 do copymemory(@rom_bank[f,0],@memoria_temp[$8000+(f*$2000)],$2000);
//Cargar MCU
if not(roms_load(@mem_snd,drgnbstr_mcu)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,drgnbstr_char)) then exit;
init_gfx(0,8,8,$200);
gfx[0].trans[0]:=true;
gfx_set_desc_data(2,0,16*8,0,4);
convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,false,false);
//sprites
fillchar(memoria_temp[0],$10000,0);
if not(roms_load(@memoria_temp,drgnbstr_sprites)) then exit;
// unpack the third sprite ROM
for f:=0 to $1fff do begin
memoria_temp[f+$4000+$4000]:=memoria_temp[f+$4000]; // sprite set #1, plane 3
memoria_temp[f+$6000+$4000]:=memoria_temp[f+$4000] shr 4; // sprite set #2, plane 3
memoria_temp[f+$4000]:=memoria_temp[f+$2000+$4000]; // sprite set #3, planes 1&2 (plane 3 is empty)
end;
init_gfx(1,16,16,$200);
gfx_set_desc_data(3,0,64*8,$200*64*8+4,0,4);
convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false);
//tiles
if not(roms_load(@memoria_temp,drgnbstr_tiles)) then exit;
init_gfx(2,8,8,$200);
gfx_set_desc_data(2,0,16*8,0,4);
convert_gfx(2,0,@memoria_temp,@pt_x,@pt_y,false,false);
//Paleta
if not(roms_load(@memoria_temp,drgnbstr_prom)) then exit;
screen_flip:=true;
end;
end;
for f:=0 to $ff do begin
colores[f].r:=(memoria_temp[f] and $f)+((memoria_temp[f] and $f) shl 4);
colores[f].g:=(memoria_temp[f+$100] and $f)+((memoria_temp[f+$100] and $f) shl 4);
colores[f].b:=(memoria_temp[f+$200] and $f)+((memoria_temp[f+$200] and $f) shl 4);
end;
set_pal(colores,$100);
// tiles/sprites color table
for f:=$0 to $3ff do begin
gfx[1].colores[f]:=memoria_temp[$300+f];
gfx[2].colores[f]:=memoria_temp[$300+f];
end;
//final
reset_skykid;
iniciar_skykid:=true;
end;
end.
|
unit LamwinoAvrSerial; {version 0.1 revision 03 - 24 Fev - 2016}
{$mode delphi}
(*references
http://brittonkerin.com/cduino/lessons.html
http://www.delphitricks.com/source-code/math/convert_a_binary_number_into_a_decimal_number.html
http://www.swissdelphicenter.ch/torry/showcode.php?id=442
http://programmersheaven.com/discussion/389747/binary-to-decimal-and-decimal-to-binary-conversion
http://galfar.vevb.net/wp/2009/shift-right-delphi-vs-c/
https://sites.google.com/site/myfeup/avr/avr-gcc/usart
*)
interface
type
TAvrSerial = record
StringTerminator: char;
constructor Init(usart_baud: Cardinal);
procedure WriteChar(c: char);
procedure WriteByte(b: byte);
function ReadChar(): char; overload;
procedure ReadChar(var c: char); overload;
procedure ReadString(var s: shortstring); overload;
function ReadString():shortstring; overload;
function ReadDecimalStringAsByte(): byte; overload;
procedure ReadDecimalStringAsByte(var b:byte); overload;
function ReadByte(): byte;
procedure Flush();
procedure WriteString(PStr: PChar; len: integer); overload;
procedure WriteString(PStr: PChar); overload;
procedure WriteString(str: shortstring); overload;
procedure WriteByteAsBinaryString(value: byte);
function BinaryStringToByte(PBinaryString: PChar): byte;
procedure ByteToBinaryString(value: byte; binStrBuffer: PChar);
procedure WriteByteAsDecimalString(value: byte);
procedure WriteLineBreak();
function DecimalStringToByte(decStr: shortstring): byte;
function ByteToDecimalString(value: byte): shortstring;
function IsDigit(c: char): boolean;
end;
var
Serial: TAvrSerial;
implementation
{8N1
9600 bits per second
8 data bits
No parity (you might see instead: E=even, O=odd)
1 stop bit
http://www.gammon.com.au/forum/?id=10894
}
constructor TAvrSerial.Init(usart_baud: Cardinal);
var
USART_UBBR: byte;
begin
StringTerminator:= '\';
USART_UBBR:= byte(16000000 div usart_baud div 16) - 1; //U2X0 = 0 --> Assyn normal mod
//UCSR0A := (1 shl U2X0); //double mode
//UCSR0A:= 0; //simple mode
// Enable receiver and transmitter
UCSR0B := (1 shl RXEN0) or (1 shl TXEN0);
//Set frame format to 8N1
UCSR0C :=
(3 shl UCSZ0) // 8 data bits 00000110
or (0 shl UPM0) // no parity bit
or (0 shl USBS0); // 1 stop bit
// Set baudrate
UBRR0H := USART_UBBR shr 8;
UBRR0L := USART_UBBR;
UCSR0A:=UCSR0A or (1 shl TXC0); // clear existing transmits
end;
procedure TAvrSerial.WriteLineBreak();
var
brline: char;
begin
brline:= #10;
// Wait if UDR is not free
while( (UCSR0A and (1 shl UDRE0) ) = 0 ) do ;
UCSR0A:= UCSR0A or (1 shl TXC0); // clear txc flag
// Transmit data
UDR0:= byte(brline);
end;
procedure TAvrSerial.WriteChar(c: char );
begin
while( (UCSR0A and (1 shl UDRE0) ) = 0 ) do ;
UCSR0A:= UCSR0A or (1 shl TXC0); // clear txc flag
// Transmit data
UDR0:= byte(c);
end;
procedure TAvrSerial.WriteByte(b: byte);
begin
// Wait if UDR is not free
while( (UCSR0A and (1 shl UDRE0) ) = 0 ) do ;
UCSR0A:= UCSR0A or (1 shl TXC0); // clear txc flag
// Transmit data
UDR0:= b;
end;
function TAvrSerial.ReadChar(): char;
var
value: byte;
begin
//Wait until a byte has been received
value:= UCSR0A and (1 shl RXC0); //Axxxxxxx and 1000 0000 = 0 <---> A=0
while value = 0 do // <> 0 <---> A=1
begin
value:= UCSR0A and (1 shl RXC0);
end;
//Return received data
Result:= char(UDR0);
end;
procedure TAvrSerial.ReadChar(var c: char);
begin
c:= ReadChar();
end;
procedure TAvrSerial.ReadString(var s: shortstring);
var
count: byte;
c: char;
begin
c:= ReadChar();
count:= 1;
while (count < 255) and (c <> StringTerminator) do
begin
s[count]:= c;
c:= ReadChar();
Inc(count);
end;
s[0]:= char(count-1);
end;
function TAvrSerial.ReadString():shortstring;
var
s: shortstring;
begin
ReadString(s);
Result:= s;
end;
function TAvrSerial.ReadByte(): byte;
var
value: byte;
begin
//Wait until a byte has been received
value:= UCSR0A and (1 shl RXC0); //Axxxxxxx and 1000 0000 = 0 <---> A=0
while value = 0 do // <> 0 <---> A=1
begin
value:= UCSR0A and (1 shl RXC0);
end;
//Return received data
Result:= UDR0;
end;
procedure TAvrSerial.Flush();
var
value: byte;
begin
//Wait until a byte has been received
value:= UCSR0A and (1 shl RXC0); //Axxxxxxx and 1000 0000 = 0 <---> A=0
while value <> 0 do // <> 0 <---> A=1
begin
Self.ReadByte(); //empty...
value:= UCSR0A and (1 shl RXC0);
end;
end;
procedure TAvrSerial.WriteString(PStr: PChar; len: integer);
var
i: integer;
begin
for i:=0 to len-1 do
Self.WriteChar( char(PStr[i]) );
end;
procedure TAvrSerial.WriteString(PStr: PChar);
var
i, len: integer;
begin
len:= Length(PStr);
for i:=0 to len-1 do
Self.WriteChar( char(PStr[i]) );
end;
procedure TAvrSerial.WriteString(str: shortstring); overload;
var
p: PChar;
i, count: byte;
begin
count:= byte(str[0]);
p:= @str[1];
for i:=0 to count-1 do
Self.WriteChar( char(p[i]) );
end;
function TAvrSerial.BinaryStringToByte(PBinaryString: PChar): byte;
var
i: byte;
begin
Result:= 0;
for i:= 7 downto 0 do
begin
if PBinaryString[i] = '1' then
Result:= Result + byte(1 shl (8 - i));
end;
end;
procedure TAvrSerial.ByteToBinaryString(value: byte; binStrBuffer: PChar);
var
index: byte;
begin
for index:=8 downto 1 do
begin
if ( (value shr (index-1)) and $01) <> 0 then
binStrBuffer[8-index]:= '1'
else
binStrBuffer[8-index]:= '0'
end;
end;
procedure TAvrSerial.WriteByteAsBinaryString(value: byte);
var
index: byte;
begin
for index:=8 downto 1 do
begin
if ( (value shr (index-1)) and $01) <> 0 then
Self.WriteChar('1')
else
Self.WriteChar('0');
end;
end;
procedure TAvrSerial.WriteByteAsDecimalString(value: byte);
var
t: byte;
begin
t:= value mod 100;
if (value div 100) <> 0 then
Self.WriteChar(char( ORD('0') + (value div 100) ));
Self.WriteChar(char( ORD('0') + (t div 10) ));
Self.WriteChar(char( ORD('0') + (t mod 10) ));
end;
function TAvrSerial.IsDigit(c: char): boolean;
begin
if (ord(c)<48) or (ord(c)>57) then
Result:=False
else
Result:= True;
end;
function TAvrSerial.DecimalStringToByte(decStr: shortstring): byte;
var
value: byte;
error: integer;
begin
Val(decStr, value, error);
if error > 0 then
Result:= 0
else
Result:= value;
end;
function TAvrSerial.ByteToDecimalString(value: byte): shortstring;
var
strValue: shortstring;
begin
Str(value, strValue);
Result:= strValue;
end;
function TAvrSerial.ReadDecimalStringAsByte(): byte;
var
strValue: shortstring;
begin
strValue:= ReadString();
Result:= DecimalStringToByte(strValue);
end;
procedure TAvrSerial.ReadDecimalStringAsByte(var b:byte);
var
strValue: shortstring;
begin
strValue:= ReadString();
b:= DecimalStringToByte(strValue);
end;
end.
|
unit GetAddressBookContactsResponseUnit;
interface
uses
REST.Json.Types,
GenericParametersUnit, AddressBookContactUnit;
type
TGetAddressBookContactsResponse = class(TGenericParameters)
private
[JSONName('results')]
FResults: TAddressBookContactArray;
[JSONName('total')]
FTotal: integer;
public
property Results: TAddressBookContactArray read FResults write FResults;
property Total: integer read FTotal write FTotal;
end;
implementation
end.
|
unit uDepartamentoVO;
interface
uses
System.SysUtils, uDepartamentoAcessoVO, uDepartamentoEmailVO, System.Generics.Collections,
uKeyField, uTableName;
type
[TableName('Departamento')]
TDepartamentoVO = class
private
FAgendamentoQuadro: Boolean;
FAtividadeQuadro: Boolean;
FChamadoStatus: Boolean;
FChamadoAbertura: Boolean;
FAtivo: Boolean;
FAtividadeStatus: Boolean;
FAtividadeAbertura: Boolean;
FCodigo: Integer;
FSolicitacaoOcorrenciaGeral: Boolean;
FSolicitacaoAnalise: Boolean;
FId: Integer;
FSolicitacaoQuadro: Boolean;
FChamadoOcorrencia: Boolean;
FSolicitacaoOcorrenciaTecnica: Boolean;
FAtividadeOcorrencia: Boolean;
FNome: string;
FSolicitacaoStatus: Boolean;
FSolicitacaoAbertura: Boolean;
FChamadoQuadro: Boolean;
FDepartamentoAcesso: TObjectList<TDepartamentoAcessoVO>;
FDepartamentoEmail: TObjectList<TDepartamentoEmailVO>;
FMostrarAnexos: Boolean;
FSolicitacaoOcorrenciaRegra: Boolean;
FHoraFinal: TTime;
FHoraInicial: TTime;
procedure SetAgendamentoQuadro(const Value: Boolean);
procedure SetAtividadeAbertura(const Value: Boolean);
procedure SetAtividadeOcorrencia(const Value: Boolean);
procedure SetAtividadeQuadro(const Value: Boolean);
procedure SetAtividadeStatus(const Value: Boolean);
procedure SetAtivo(const Value: Boolean);
procedure SetChamadoAbertura(const Value: Boolean);
procedure SetChamadoOcorrencia(const Value: Boolean);
procedure SetChamadoQuadro(const Value: Boolean);
procedure SetChamadoStatus(const Value: Boolean);
procedure SetCodigo(const Value: Integer);
procedure SetId(const Value: Integer);
procedure SetNome(const Value: string);
procedure SetSolicitacaoAbertura(const Value: Boolean);
procedure SetSolicitacaoAnalise(const Value: Boolean);
procedure SetSolicitacaoOcorrenciaGeral(const Value: Boolean);
procedure SetSolicitacaoOcorrenciaTecnica(const Value: Boolean);
procedure SetSolicitacaoQuadro(const Value: Boolean);
procedure SetSolicitacaoStatus(const Value: Boolean);
procedure SetDepartamentoAcesso(
const Value: TObjectList<TDepartamentoAcessoVO>);
procedure SetDepartamentoEmail(
const Value: TObjectList<TDepartamentoEmailVO>);
procedure SetMostrarAnexos(const Value: Boolean);
procedure SetSolicitacaoOcorrenciaRegra(const Value: Boolean);
procedure SetHoraFinal(const Value: TTime);
procedure SetHoraInicial(const Value: TTime);
public
[keyField('Dep_Id')]
property Id: Integer read FId write SetId;
[FieldName('Dep_Codigo')]
property Codigo: Integer read FCodigo write SetCodigo;
[FieldName('Dep_Nome')]
property Nome: string read FNome write SetNome;
[FieldName('Dep_Ativo')]
property Ativo: Boolean read FAtivo write SetAtivo;
[FieldName('Dep_SolicitaAbertura')]
property SolicitacaoAbertura: Boolean read FSolicitacaoAbertura write SetSolicitacaoAbertura;
[FieldName('Dep_SolicitaAnalise')]
property SolicitacaoAnalise: Boolean read FSolicitacaoAnalise write SetSolicitacaoAnalise;
[FieldName('Dep_SolicitaOcorGeral')]
property SolicitacaoOcorrenciaGeral: Boolean read FSolicitacaoOcorrenciaGeral write SetSolicitacaoOcorrenciaGeral;
[FieldName('Dep_SolicitaOcorTecnica')]
property SolicitacaoOcorrenciaTecnica: Boolean read FSolicitacaoOcorrenciaTecnica write SetSolicitacaoOcorrenciaTecnica;
[FieldName('Dep_SolicitaStatus')]
property SolicitacaoStatus: Boolean read FSolicitacaoStatus write SetSolicitacaoStatus;
[FieldName('Dep_SolicitaQuadro')]
property SolicitacaoQuadro: Boolean read FSolicitacaoQuadro write SetSolicitacaoQuadro;
[FieldName('Dep_ChamadoAbertura')]
property ChamadoAbertura: Boolean read FChamadoAbertura write SetChamadoAbertura;
[FieldName('Dep_ChamadoStatus')]
property ChamadoStatus: Boolean read FChamadoStatus write SetChamadoStatus;
[FieldName('Dep_ChamadoQuadro')]
property ChamadoQuadro: Boolean read FChamadoQuadro write SetChamadoQuadro;
[FieldName('Dep_ChamadoOcor')]
property ChamadoOcorrencia: Boolean read FChamadoOcorrencia write SetChamadoOcorrencia;
[FieldName('Dep_AtividadeAbertura')]
property AtividadeAbertura: Boolean read FAtividadeAbertura write SetAtividadeAbertura;
[FieldName('Dep_AtividadeStatus')]
property AtividadeStatus: Boolean read FAtividadeStatus write SetAtividadeStatus;
[FieldName('Dep_AtividadeQuadro')]
property AtividadeQuadro: Boolean read FAtividadeQuadro write SetAtividadeQuadro;
[FieldName('Dep_AtividadeOcor')]
property AtividadeOcorrencia: Boolean read FAtividadeOcorrencia write SetAtividadeOcorrencia;
[FieldName('Dep_MostrarAnexos')]
property MostrarAnexos: Boolean read FMostrarAnexos write SetMostrarAnexos;
[FieldName('Dep_AgendamentoQuadro')]
property AgendamentoQuadro: Boolean read FAgendamentoQuadro write SetAgendamentoQuadro;
[FieldName('Dep_SolicitaOcorRegra')]
property SolicitacaoOcorrenciaRegra: Boolean read FSolicitacaoOcorrenciaRegra write SetSolicitacaoOcorrenciaRegra;
[FieldTime('Dep_HoraAtendeInicial')]
property HoraInicial: TTime read FHoraInicial write SetHoraInicial;
[FieldTime('Dep_HoraAtendeFinal')]
property HoraFinal: TTime read FHoraFinal write SetHoraFinal;
property DepartamentoAcesso: TObjectList<TDepartamentoAcessoVO> read FDepartamentoAcesso write SetDepartamentoAcesso;
property DepartamentoEmail: TObjectList<TDepartamentoEmailVO> read FDepartamentoEmail write SetDepartamentoEmail;
constructor Create;
destructor destroy; override;
end;
implementation
{ TDepartamentoVO }
constructor TDepartamentoVO.Create;
begin
FDepartamentoAcesso := TObjectList<TDepartamentoAcessoVO>.Create();
FDepartamentoEmail := TObjectList<TDepartamentoEmailVO>.Create();
end;
destructor TDepartamentoVO.destroy;
begin
FreeAndNil(FDepartamentoAcesso);
FreeAndNil(FDepartamentoEmail);
inherited;
end;
procedure TDepartamentoVO.SetAgendamentoQuadro(const Value: Boolean);
begin
FAgendamentoQuadro := Value;
end;
procedure TDepartamentoVO.SetAtividadeAbertura(const Value: Boolean);
begin
FAtividadeAbertura := Value;
end;
procedure TDepartamentoVO.SetAtividadeOcorrencia(const Value: Boolean);
begin
FAtividadeOcorrencia := Value;
end;
procedure TDepartamentoVO.SetAtividadeQuadro(const Value: Boolean);
begin
FAtividadeQuadro := Value;
end;
procedure TDepartamentoVO.SetAtividadeStatus(const Value: Boolean);
begin
FAtividadeStatus := Value;
end;
procedure TDepartamentoVO.SetAtivo(const Value: Boolean);
begin
FAtivo := Value;
end;
procedure TDepartamentoVO.SetChamadoAbertura(const Value: Boolean);
begin
FChamadoAbertura := Value;
end;
procedure TDepartamentoVO.SetChamadoOcorrencia(const Value: Boolean);
begin
FChamadoOcorrencia := Value;
end;
procedure TDepartamentoVO.SetChamadoQuadro(const Value: Boolean);
begin
FChamadoQuadro := Value;
end;
procedure TDepartamentoVO.SetChamadoStatus(const Value: Boolean);
begin
FChamadoStatus := Value;
end;
procedure TDepartamentoVO.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TDepartamentoVO.SetDepartamentoAcesso(
const Value: TObjectList<TDepartamentoAcessoVO>);
begin
FDepartamentoAcesso := Value;
end;
procedure TDepartamentoVO.SetDepartamentoEmail(
const Value: TObjectList<TDepartamentoEmailVO>);
begin
FDepartamentoEmail := Value;
end;
procedure TDepartamentoVO.SetHoraFinal(const Value: TTime);
begin
FHoraFinal := Value;
end;
procedure TDepartamentoVO.SetHoraInicial(const Value: TTime);
begin
FHoraInicial := Value;
end;
procedure TDepartamentoVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TDepartamentoVO.SetMostrarAnexos(const Value: Boolean);
begin
FMostrarAnexos := Value;
end;
procedure TDepartamentoVO.SetNome(const Value: string);
begin
FNome := Value;
end;
procedure TDepartamentoVO.SetSolicitacaoAbertura(const Value: Boolean);
begin
FSolicitacaoAbertura := Value;
end;
procedure TDepartamentoVO.SetSolicitacaoAnalise(const Value: Boolean);
begin
FSolicitacaoAnalise := Value;
end;
procedure TDepartamentoVO.SetSolicitacaoOcorrenciaGeral(const Value: Boolean);
begin
FSolicitacaoOcorrenciaGeral := Value;
end;
procedure TDepartamentoVO.SetSolicitacaoOcorrenciaRegra(const Value: Boolean);
begin
FSolicitacaoOcorrenciaRegra := Value;
end;
procedure TDepartamentoVO.SetSolicitacaoOcorrenciaTecnica(const Value: Boolean);
begin
FSolicitacaoOcorrenciaTecnica := Value;
end;
procedure TDepartamentoVO.SetSolicitacaoQuadro(const Value: Boolean);
begin
FSolicitacaoQuadro := Value;
end;
procedure TDepartamentoVO.SetSolicitacaoStatus(const Value: Boolean);
begin
FSolicitacaoStatus := Value;
end;
end.
|
unit mnSynHighlighterBVH;
{$mode objfpc}{$H+}
{**
* NOT COMPLETED
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*
* https://research.cs.wisc.edu/graphics/Courses/cs-838-1999/Jeff/BVH.html
*
*}
interface
uses
Classes, SysUtils,
SynEdit, SynEditTypes,
SynHighlighterHashEntries, SynEditHighlighter, mnSynHighlighterMultiProc;
type
{ TBVHProcessor }
TBVHProcessor = class(TCommonSynProcessor)
private
protected
function GetIdentChars: TSynIdentChars; override;
function GetEndOfLineAttribute: TSynHighlighterAttributes; override;
public
procedure Created; override;
procedure QuestionProc;
procedure SlashProc;
procedure BlockProc;
procedure GreaterProc;
procedure LowerProc;
procedure DeclareProc;
procedure Next; override;
procedure Prepare; override;
procedure MakeProcTable; override;
end;
{ TSynDSyn }
TSynBVHSyn = 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_LangBVH = 'BVH';
SYNS_FilterBVH = 'BVH Files (*.BVH)|*.BVH';
cBVHSample = 'HIERARCHY'
+'ROOT Hips'#13
+'{'#13
+''#13
+'}'#13;
const
sBVHTypes =
'Xposition,'+
'Yposition,'+
'Zposition,'+
'Zrotation,'+
'Yrotation,'+
'Xrotation,'+
//not types
'Hips,'+
'Neck,'+
'Chest,'+
'Head';
sBVHKeywords =
'hierarchy,'+
'root,'+
'offset,'+
'channels,'+
'end,' +
'site,' +
'motion,' +
'frames,' +
'frame,' +
'time,' +
'joint';
implementation
uses
mnUtils;
procedure TBVHProcessor.GreaterProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] in ['=', '>'] then
Inc(Parent.Run);
end;
procedure TBVHProcessor.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 TBVHProcessor.DeclareProc;
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 TBVHProcessor.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 TBVHProcessor.BlockProc;
begin
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'*': SpecialCommentMLProc;
else
Parent.FTokenID := tkSymbol;
end;
end;
procedure TBVHProcessor.MakeProcTable;
var
I: Char;
begin
inherited;
for I := #0 to #255 do
case I of
'?': ProcTable[I] := @QuestionProc;
'''': ProcTable[I] := @StringSQProc;
'"': ProcTable[I] := @StringDQProc;
'`': ProcTable[I] := @StringBQProc;
'/': ProcTable[I] := @SlashProc;
'{': ProcTable[I] := @BlockProc;
'>': ProcTable[I] := @GreaterProc;
'<': ProcTable[I] := @LowerProc;
':': ProcTable[I] := @DeclareProc;
'0'..'9':
ProcTable[I] := @NumberProc;
//else
'A'..'Z', 'a'..'z', '_':
ProcTable[I] := @IdentProc;
end;
end;
procedure TBVHProcessor.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 TBVHProcessor.Next;
begin
Parent.FTokenPos := Parent.Run;
if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then
ProcTable[Parent.FLine[Parent.Run]]
else case Range of
rscComment:
begin
CommentMLProc;
end;
rscDocument:
begin
DocumentMLProc;
end;
rscStringSQ, rscStringDQ, rscStringBQ:
StringProc;
else
if ProcTable[Parent.FLine[Parent.Run]] = nil then
UnknownProc
else
ProcTable[Parent.FLine[Parent.Run]];
end;
end;
procedure TBVHProcessor.Prepare;
begin
inherited;
EnumerateKeywords(Ord(tkKeyword), sBVHKeywords, TSynValidStringChars, @DoAddKeyword);
EnumerateKeywords(Ord(tkType), sBVHTypes, TSynValidStringChars, @DoAddKeyword);
SetRange(rscUnknown);
end;
function TBVHProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes;
begin
if (Range = rscDocument) or (LastRange = rscDocument) then
Result := Parent.DocumentAttri
else
Result := inherited GetEndOfLineAttribute;
end;
procedure TBVHProcessor.Created;
begin
inherited Created;
CloseSpecialComment := '*}';
end;
function TBVHProcessor.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars;
end;
constructor TSynBVHSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDefaultFilter := SYNS_FilterBVH;
end;
procedure TSynBVHSyn.InitProcessors;
begin
inherited;
Processors.Add(TBVHProcessor.Create(Self, 'BVH'));
Processors.MainProcessor := 'BVH';
Processors.DefaultProcessor := 'BVH';
end;
class function TSynBVHSyn.GetLanguageName: string;
begin
Result := SYNS_LangBVH;
end;
function TSynBVHSyn.GetSampleSource: string;
begin
Result := cBVHSample;
end;
initialization
RegisterPlaceableHighlighter(TSynBVHSyn);
finalization
end.
|
unit UseIntfForm;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, TypInfo;
type
TFormUseIntf = class(TForm)
BtnChange: TButton;
lbClasses: TListBox;
cbModal: TCheckBox;
Label1: TLabel;
procedure BtnChangeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
public
HandlesPackages: TList;
procedure LoadDynaPackage (PackageName: string);
end;
var
FormUseIntf: TFormUseIntf;
implementation
{$R *.DFM}
uses
IntfColSel;
procedure TFormUseIntf.BtnChangeClick(Sender: TObject);
var
AComponent: TComponent;
ColorSelect: IColorSelect;
begin
AComponent := TComponentClass (ClassesColorSelect
[LbClasses.ItemIndex]).Create (Application);
// if the interface is available
if not Supports (AComponent, IColorSelect) then
ShowMessage ('Interface not supported')
else
begin
// access to the interface
ColorSelect := AComponent as IColorSelect;
// initialize the data
ColorSelect.SelColor := Color;
if cbModal.Checked then
begin
if ColorSelect.Display (True) then
Color := ColorSelect.SelColor;
AComponent.Free;
ColorSelect := nil;
end
else
// modeless execution
ColorSelect.Display(False);
end;
end;
procedure TFormUseIntf.FormCreate(Sender: TObject);
var
I: Integer;
begin
// loads all runtime packages
HandlesPackages := TList.Create;
LoadDynaPackage ('IntfFormPack.bpl');
LoadDynaPackage ('IntfFormPack2.bpl');
// add class names and select the first
for I := 0 to ClassesColorSelect.Count - 1 do
lbClasses.Items.Add (ClassesColorSelect [I].ClassName);
lbClasses.ItemIndex := 0;
end;
procedure TFormUseIntf.LoadDynaPackage(PackageName: string);
var
Handle: HModule;
begin
// try to load the package
Handle := LoadPackage (PackageName);
if Handle > 0 then
// add to the list for later removal
HandlesPackages.Add (Pointer(Handle))
else
ShowMessage ('Package ' + PackageName + ' not found');
end;
procedure TFormUseIntf.FormDestroy(Sender: TObject);
var
I: Integer;
begin
// unlaod all packages
for I := 0 to HandlesPackages.Count - 1 do
UnloadPackage (Cardinal (HandlesPackages [I]));
// free the lists
HandlesPackages.Free;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpDefiniteLengthInputStream;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
Math,
ClpCryptoLibTypes,
ClpLimitedInputStream;
resourcestring
SInvalidLength = 'Negative Lengths not Allowed", "Length"';
SEndOfStream = 'DEF Length %d " TObject truncated by " %d';
SInvalidBufferLength = 'Buffer Length Not Right For Data';
type
TDefiniteLengthInputStream = class(TLimitedInputStream)
strict private
class var
FEmptyBytes: TCryptoLibByteArray;
var
F_originalLength, F_remaining: Int32;
function GetRemaining: Int32; reintroduce; inline;
class function GetEmptyBytes: TCryptoLibByteArray; static; inline;
class constructor DefiniteLengthInputStream();
public
constructor Create(inStream: TStream; length: Int32);
function ReadByte(): Int32; override;
function Read(buf: TCryptoLibByteArray; off, len: LongInt): LongInt; override;
procedure ReadAllIntoByteArray(var buf: TCryptoLibByteArray);
function ToArray: TCryptoLibByteArray;
property Remaining: Int32 read GetRemaining;
class property EmptyBytes: TCryptoLibByteArray read GetEmptyBytes;
end;
implementation
uses
ClpStreams,
ClpStreamSorter; // included here to avoid circular dependency :)
{ TDefiniteLengthInputStream }
constructor TDefiniteLengthInputStream.Create(inStream: TStream; length: Int32);
begin
Inherited Create(inStream, length);
if (length < 0) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidLength);
end;
F_originalLength := length;
F_remaining := length;
if (length = 0) then
begin
SetParentEofDetect(true);
end;
end;
class constructor TDefiniteLengthInputStream.DefiniteLengthInputStream;
begin
System.SetLength(FEmptyBytes, 0);
end;
class function TDefiniteLengthInputStream.GetEmptyBytes: TCryptoLibByteArray;
begin
result := FEmptyBytes;
end;
function TDefiniteLengthInputStream.GetRemaining: Int32;
begin
result := F_remaining;
end;
function TDefiniteLengthInputStream.Read(buf: TCryptoLibByteArray;
off, len: LongInt): LongInt;
var
toRead, numRead: Int32;
begin
if (F_remaining = 0) then
begin
result := 0;
Exit;
end;
toRead := Min(len, F_remaining);
numRead := TStreamSorter.Read(F_in, buf, off, toRead);
if (numRead < 1) then
begin
raise EEndOfStreamCryptoLibException.CreateResFmt(@SEndOfStream,
[F_originalLength, F_remaining]);
end;
F_remaining := F_remaining - numRead;
if (F_remaining = 0) then
begin
SetParentEofDetect(true);
end;
result := numRead;
end;
procedure TDefiniteLengthInputStream.ReadAllIntoByteArray
(var buf: TCryptoLibByteArray);
begin
if (F_remaining <> System.length(buf)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidBufferLength);
end;
F_remaining := F_remaining - TStreams.ReadFully(F_in, buf);
if ((F_remaining <> 0)) then
begin
raise EEndOfStreamCryptoLibException.CreateResFmt(@SEndOfStream,
[F_originalLength, F_remaining]);
end;
SetParentEofDetect(true);
end;
function TDefiniteLengthInputStream.ReadByte: Int32;
begin
if (F_remaining = 0) then
begin
result := -1;
Exit;
end;
// result := F_in.ReadByte();
result := TStreamSorter.ReadByte(F_in);
if (result < 0) then
begin
raise EEndOfStreamCryptoLibException.CreateResFmt(@SEndOfStream,
[F_originalLength, F_remaining]);
end;
System.Dec(F_remaining);
if (F_remaining = 0) then
begin
SetParentEofDetect(true);
end;
end;
function TDefiniteLengthInputStream.ToArray: TCryptoLibByteArray;
var
bytes: TCryptoLibByteArray;
begin
if (F_remaining = 0) then
begin
result := EmptyBytes;
Exit;
end;
System.SetLength(bytes, F_remaining);
F_remaining := F_remaining - TStreams.ReadFully(F_in, bytes);
if (F_remaining <> 0) then
begin
raise EEndOfStreamCryptoLibException.CreateResFmt(@SEndOfStream,
[F_originalLength, F_remaining]);
end;
SetParentEofDetect(true);
result := bytes;
end;
end.
|
unit kwIterate;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwIterate.pas"
// Начат: 12.05.2011 21:40
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::ArrayProcessing::Iterate
//
// Перебирает элементы массива.
// *Пример:*
// {code}
// ARRAY L
// 0 10 FOR
// ++
// DUP
// >>>[] L
// NEXT
// DROP
// @ . ITERATE L
// // - печатает числа от 1 до 10
// '' .
// 0 @ + ITERATE L .
// // - суммирует числа от 1 до 10 и печатает результат
// {code}
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
kwCompiledVarWorker,
tfwScriptingInterfaces,
l3Interfaces,
kwCompiledWord,
l3ParserInterfaces
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\tfwVarWorker.imp.pas}
TkwIterate = class(_tfwVarWorker_)
{* Перебирает элементы массива.
*Пример:*
[code]
ARRAY L
0 10 FOR
++
DUP
>>>[] L
NEXT
DROP
@ . ITERATE L
// - печатает числа от 1 до 10
'' .
0 @ + ITERATE L .
// - суммирует числа от 1 до 10 и печатает результат
[code] }
protected
// realized methods
function CompiledVarWorkerClass: RkwCompiledVarWorker; override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwIterate
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
kwCompiledIterate,
l3Parser,
kwInteger,
kwString,
SysUtils,
TypInfo,
l3Base,
kwIntegerFactory,
kwStringFactory,
l3String,
l3Chars,
tfwAutoregisteredDiction,
tfwScriptEngine
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwIterate;
{$Include ..\ScriptEngine\tfwVarWorker.imp.pas}
// start class TkwIterate
function TkwIterate.CompiledVarWorkerClass: RkwCompiledVarWorker;
//#UC START# *4DCC193801F1_4DCC1B8A0192_var*
//#UC END# *4DCC193801F1_4DCC1B8A0192_var*
begin
//#UC START# *4DCC193801F1_4DCC1B8A0192_impl*
Result := TkwCompiledIterate;
//#UC END# *4DCC193801F1_4DCC1B8A0192_impl*
end;//TkwIterate.CompiledVarWorkerClass
class function TkwIterate.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'ITERATE';
end;//TkwIterate.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\tfwVarWorker.imp.pas}
{$IfEnd} //not NoScripts
end. |
{ ***************************************************************************
Copyright (c) 2015-2021 Kike Pérez
Unit : Quick.Options.Serializer.Json
Description : Configuration groups Json Serializer
Author : Kike Pérez
Version : 1.0
Created : 18/10/2019
Modified : 15/12/2021
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Options.Serializer.Json;
{$i QuickLib.inc}
interface
uses
System.SysUtils,
System.IOUtils,
System.Generics.Collections,
System.Json,
Quick.Commons,
Quick.JSON.Utils,
Quick.Json.Serializer,
Quick.Options;
type
TJsonOptionsSerializer = class(TOptionsFileSerializer)
private
fSerializer : TRTTIJson;
function ParseFile(out aJsonObj : TJsonObject) : Boolean;
public
constructor Create(const aFilename : string);
destructor Destroy; override;
function Load(aSections : TSectionList; aFailOnSectionNotExists : Boolean) : Boolean; override;
function LoadSection(aSections : TSectionList; aOptions: TOptions) : Boolean; override;
procedure Save(aSections : TSectionList); override;
function GetFileSectionNames(out oSections : TArray<string>) : Boolean; override;
function ConfigExists : Boolean; override;
end;
implementation
{ TJsonOptionsSerializer }
function TJsonOptionsSerializer.ConfigExists: Boolean;
begin
Result := FileExists(Filename);
end;
constructor TJsonOptionsSerializer.Create(const aFilename : string);
begin
Filename := aFilename;
fSerializer := TRTTIJson.Create(TSerializeLevel.slPublishedProperty,True);
end;
destructor TJsonOptionsSerializer.Destroy;
begin
fSerializer.Free;
inherited;
end;
function TJsonOptionsSerializer.GetFileSectionNames(out oSections: TArray<string>): Boolean;
var
json : TJsonObject;
i : Integer;
begin
Result := False;
json := nil;
if ParseFile(json) then
begin
try
for i := 0 to json.Count - 1 do
begin
oSections := oSections + [json.Pairs[i].JsonString.Value];
end;
Result := True;
finally
json.Free;
end;
end;
end;
function TJsonOptionsSerializer.ParseFile(out aJsonObj : TJsonObject) : Boolean;
var
fileoptions : string;
begin
aJsonObj := nil;
if FileExists(Filename) then
begin
{$IFDEF DELPHIRX102_UP}
fileoptions := TFile.ReadAllText(Filename,TEncoding.UTF8);
{$ELSE}
fileoptions := TFile.ReadAllText(fFilename);
{$ENDIF}
aJsonObj := TJsonObject.ParseJSONValue(fileoptions) as TJsonObject;
if aJsonObj = nil then raise EOptionLoadError.CreateFmt('Config file "%s" is damaged or not well-formed Json format!',[ExtractFileName(Filename)]);
end;
Result := aJsonObj <> nil;
end;
function TJsonOptionsSerializer.Load(aSections : TSectionList; aFailOnSectionNotExists : Boolean) : Boolean;
var
option : TOptions;
json : TJsonObject;
jpair : TJSONPair;
found : Integer;
begin
Result := False;
if ParseFile(json) then
begin
found := 0;
try
for option in aSections do
begin
jpair := fSerializer.GetJsonPairByName(json,option.Name);
if jpair = nil then
begin
if aFailOnSectionNotExists then raise Exception.CreateFmt('Config section "%s" not found',[option.Name])
else
begin
//count as found if hidden
if option.HideOptions then Inc(found);
Continue;
end;
end;
if jpair.JsonValue <> nil then
begin
//deserialize option
fSerializer.DeserializeObject(option,jpair.JsonValue as TJSONObject);
//validate loaded configuration
option.ValidateOptions;
Inc(found);
end;
end;
finally
json.Free;
end;
//returns true if all sections located into file
Result := found = aSections.Count;
end;
end;
function TJsonOptionsSerializer.LoadSection(aSections : TSectionList; aOptions: TOptions) : Boolean;
var
json : TJsonObject;
jpair : TJSONPair;
begin
Result := False;
//read option file
if ParseFile(json) then
begin
try
jpair := fSerializer.GetJsonPairByName(json,aOptions.Name);
if (jpair <> nil) and (jpair.JsonValue <> nil) then
begin
//deserialize option
fSerializer.DeserializeObject(aOptions,jpair.JsonValue as TJSONObject);
//validate loaded configuration
aOptions.ValidateOptions;
Result := True;
end;
finally
json.Free;
end;
end;
end;
procedure TJsonOptionsSerializer.Save(aSections : TSectionList);
var
option : TOptions;
fileoptions : string;
json : TJSONObject;
jpair : TJSONPair;
begin
json := TJSONObject.Create;
try
for option in aSections do
begin
if not option.HideOptions then
begin
//validate configuration before save
option.ValidateOptions;
//serialize option
jpair := TJSONPair.Create(option.Name,fSerializer.SerializeObject(option));
json.AddPair(jpair);
end;
end;
fileoptions := TJsonUtils.JsonFormat(json.ToJSON);
if not fileoptions.IsEmpty then TFile.WriteAllText(Filename,fileoptions);
finally
json.Free;
end;
end;
end.
|
unit dt_ImgContainer;
{ $Id: dt_ImgContainer.pas,v 1.2 2011/12/05 14:03:32 fireton Exp $ }
// $Log: dt_ImgContainer.pas,v $
// Revision 1.2 2011/12/05 14:03:32 fireton
// - не падаем, если файл битый
//
// Revision 1.1 2008/10/03 10:31:36 fireton
// - образом документа теперь может быть не только TIFF
//
interface
uses
l3Base;
type
TdtImgContainerFile = class(Tl3Base)
private
f_OriginalExt: string;
f_Filename : string;
public
constructor Create(aFileName: string);
function UnwrapFile(aFileName: string): string;
procedure WrapFile(aFileName: string);
property Filename: string read f_Filename write f_Filename;
property OriginalExt: string read f_OriginalExt write f_OriginalExt;
end;
implementation
uses
Classes,
SysUtils,
l3Types,
l3Stream,
imageenio
;
constructor TdtImgContainerFile.Create(aFileName: string);
var
l_File: Tl3FileStream;
l_ExtSize: Byte;
begin
inherited Create;
f_Filename := aFileName;
if FileExists(f_Filename) then
begin
l_File := Tl3FileStream.Create(f_Filename, l3_fmRead);
try
try
l_File.Read(l_ExtSize, 1);
SetLength(f_OriginalExt, l_ExtSize);
l_File.Read(f_OriginalExt[1], l_ExtSize);
except
f_OriginalExt := ''; // если были какие-то ошибки при чтении файла, то считаем, что ничего не было :)
end;
finally
l3Free(l_File);
end;
end
else
f_OriginalExt := '';
end;
function TdtImgContainerFile.UnwrapFile(aFileName: string): string;
var
l_Target: Tl3FileStream;
l_File: Tl3FileStream;
l_TargetFilename: string;
l_HeaderSize: Integer;
begin
Result := '';
l_TargetFilename := ChangeFileExt(aFileName, '.'+OriginalExt);
l_Target := Tl3FileStream.Create(l_TargetFilename, l3_fmWrite);
try
l_File := Tl3FileStream.Create(f_Filename, l3_fmRead);
try
l_HeaderSize := Length(f_OriginalExt)+1;
l_File.Seek(l_HeaderSize, soBeginning);
l_Target.CopyFrom(l_File, l_File.Size - l_HeaderSize);
Result := l_TargetFilename;
finally
l3Free(l_File);
end;
finally
l3Free(l_Target);
end;
end;
procedure TdtImgContainerFile.WrapFile(aFileName: string);
var
l_File: Tl3FileStream;
l_Src : Tl3FileStream;
l_Ext: string;
l_Len: Byte;
begin
if FileExists(aFileName) then
begin
l_File := Tl3FileStream.Create(f_Filename, l3_fmWrite);
try
l_Ext := ExtractFileExt(aFileName);
if l_Ext[1] = '.' then
l_Ext := Copy(l_Ext, 2, MaxInt);
f_OriginalExt := l_Ext;
l_Len := Length(f_OriginalExt);
l_File.WriteBuffer(l_Len, 1);
l_File.WriteBuffer(f_OriginalExt[1], l_Len);
l_Src := Tl3FileStream.Create(aFileName, l3_fmRead);
try
l_File.CopyFrom(l_Src, l_Src.Size);
finally
l3Free(l_Src);
end;
finally
l3Free(l_File);
end;
end
else
raise EFOpenError.CreateFmt('Файл %s не найден.', [aFilename]);
end;
end. |
unit CompSignTools;
{
Inno Setup
Copyright (C) 1997-2010 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Compiler SignTools form
$jrsoftware: issrc/Projects/CompSignTools.pas,v 1.3 2010/03/24 18:34:14 mlaan Exp $
}
interface
uses
Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, UIStateForm;
type
TSignToolsForm = class(TUIStateForm)
OKButton: TButton;
CancelButton: TButton;
GroupBox1: TGroupBox;
SignToolsListBox: TListBox;
AddButton: TButton;
RemoveButton: TButton;
EditButton: TButton;
procedure SignToolsListBoxClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure RemoveButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
private
FSignTools: TStringList;
procedure UpdateSignTools;
procedure UpdateSignToolsButtons;
procedure SetSignTools(SignTools: TStringList);
function InputSignTool(var SignToolName, SignToolCommand: String;
ExistingIndex: Integer): Boolean;
public
property SignTools: TStringList read FSignTools write SetSignTools;
end;
implementation
uses
CmnFunc, CompForm, SysUtils;
{$R *.DFM}
procedure TSignToolsForm.UpdateSignTools;
begin
SignToolsListBox.Items.Assign(FSignTools);
UpdateHorizontalExtent(SignToolsListBox);
end;
procedure TSignToolsForm.UpdateSignToolsButtons;
var
Enabled: Boolean;
begin
Enabled := SignToolsListBox.ItemIndex >= 0;
EditButton.Enabled := Enabled;
RemoveButton.Enabled := Enabled;
end;
procedure TSignToolsForm.SetSignTools(SignTools: TStringList);
begin
FSignTools.Assign(SignTools);
UpdateSignTools;
UpdateSignToolsButtons;
end;
procedure TSignToolsForm.FormCreate(Sender: TObject);
begin
FSignTools := TStringList.Create();
InitFormFont(Self);
end;
procedure TSignToolsForm.FormDestroy(Sender: TObject);
begin
FSignTools.Free();
end;
function TSignToolsForm.InputSignTool(var SignToolName, SignToolCommand: String;
ExistingIndex: Integer): Boolean;
var
I: Integer;
begin
Result := False;
if InputQuery(Caption, 'Name of the Sign Tool:', SignToolName) then begin
if (SignToolName = '') or (Pos('=', SignToolName) <> 0) then begin
AppMessageBox(PChar('Invalid name.'), PChar(Caption), MB_OK or MB_ICONSTOP);
Exit;
end;
for I := 0 to FSignTools.Count-1 do begin
if (I <> ExistingIndex) and (Pos(SignToolName + '=', FSignTools[I]) = 1) then begin
AppMessageBox(PChar('Duplicate name.'), PChar(Caption), MB_OK or MB_ICONSTOP);
Exit;
end;
end;
if InputQuery(Caption, 'Command of the Sign Tool:', SignToolCommand) then begin
if SignToolCommand = '' then begin
AppMessageBox(PChar('Invalid command.'), PChar(Caption), MB_OK or MB_ICONSTOP);
Exit;
end;
end;
Result := True;
end;
end;
procedure TSignToolsForm.AddButtonClick(Sender: TObject);
var
SignToolName, SignToolCommand: String;
begin
SignToolName := '';
SignToolCommand := '';
if InputSignTool(SignToolName, SignToolCommand, -1) then begin
FSignTools.Add(SignToolName + '=' + SignToolCommand);
UpdateSignTools;
UpdateSignToolsButtons;
end;
end;
procedure TSignToolsForm.EditButtonClick(Sender: TObject);
var
SignToolName, SignToolCommand: String;
I, P: Integer;
begin
I := SignToolsListBox.ItemIndex;
P := Pos('=', FSignTools[I]);
if P = 0 then
raise Exception.Create('Internal error: ''='' not found in SignTool');
SignToolName := Copy(FSignTools[I], 1, P-1);
SignToolCommand := Copy(FSignTools[I], P+1, MaxInt);
if InputSignTool(SignToolName, SignToolCommand, I) then begin
FSignTools[I] := SignToolName + '=' + SignToolCommand;
UpdateSignTools;
UpdateSignToolsButtons;
end;
end;
procedure TSignToolsForm.RemoveButtonClick(Sender: TObject);
var
I: Integer;
begin
I := SignToolsListBox.ItemIndex;
FSignTools.Delete(I);
UpdateSignTools;
UpdateSignToolsButtons;
end;
procedure TSignToolsForm.SignToolsListBoxClick(Sender: TObject);
begin
UpdateSignToolsButtons;
end;
end.
|
unit Autocomplete_string_list;
interface
uses classes;
type
TAutocompleteStringList = class (TStringList)
protected
function CompareStrings(const S1, S2: string): Integer; override;
//ищет не точное соответствие, а лишь то, что S1 начинается с S2
//сортировка, к сожалению, работает через нее же
//могут быть проблемы
public
procedure Sort; override;
function GetListOfObjects(str: string):TStringList;
end;
implementation
uses SysUtils,StrUtils,localized_string_lib;
function GoodOlCompareStrings(List: TStringList; Index1, Index2: Integer): Integer;
begin
if List.CaseSensitive then
Result:=LocaleCompareStr(List[Index1],List[Index2])
else
Result := LocaleCompareText(List[Index1], List[Index2]);
end;
function TAutocompleteStringList.CompareStrings(const S1,S2: string): Integer;
begin
Result:=inherited CompareStrings(LeftStr(S1,Length(S2)),S2);
end;
procedure TAutocompleteStringList.Sort;
begin
CustomSort(GoodOlCompareStrings);
end;
function TAutocompleteStringList.GetListOfObjects(str: string): TStringList;
var i,u,d: Integer;
begin
Result:=TStringList.Create;
if Find(str,d) then begin
//Find гарантированно выдаст первое упоминание str
u:=d+1;
while (u<Count) and (CompareStrings(strings[u],str)=0) do inc(u);
dec(u);
for i:=d to u do
Result.AddObject(Strings[i],Objects[i]);
end;
end;
end.
|
unit vtPropEditors;
interface
uses
ImgList,
DesignIntf,
DesignEditors,
evImageIndexProperty
;
type
TvtStatusBarEditor = class(TDefaultEditor)
protected
procedure RunPropertyEditor(const Prop: IProperty);
public
procedure ExecuteVerb(Index : Integer); override;
function GetVerb(Index : Integer): string; override;
function GetVerbCount : Integer; override;
procedure Edit; override;
end;
(* TvtReminderImageIndexProperty = class(TevImageIndexProperty)
protected
function GetImages : TCustomImageList; override;
end;*)
implementation
uses
Dialogs, Windows, vtStatusBar, Classes, SysUtils, TypInfo
//, vtReminder
;
{ TvtStatusBarEditor }
procedure TvtStatusBarEditor.Edit;
var
Components: IDesignerSelections;
begin
Components := CreateSelectionList;
try
Components.Add(Component);
GetComponentProperties(Components, [tkClass], Designer, RunPropertyEditor);
finally
end;
end;
procedure TvtStatusBarEditor.RunPropertyEditor(const Prop: IProperty);
begin
if UpperCase(Prop.GetName) = 'PANELS' then
Prop.Edit;
end;
procedure TvtStatusBarEditor.ExecuteVerb(Index: Integer);
begin
if Index <> 0 then Exit; { We only have one verb, so exit if this ain't it }
Edit; { Invoke the Edit function the same as if double click had happened }
end;
function TvtStatusBarEditor.GetVerb(Index: Integer): string;
begin
Result := '&Panels Editor...'; { Menu item caption for context menu }
end;
function TvtStatusBarEditor.GetVerbCount: Integer;
begin
Result := 1; // Just add one menu item.
end;
(*{ TvtReminderImageIndexProperty }
function TvtReminderImageIndexProperty.GetImages: TCustomImageList;
var
l_Reminder : TvtReminder;
begin
Result := nil;
if GetComponent(0) is TvtReminder then
begin
l_Reminder := TvtReminder(GetComponent(0));
Result := l_Reminder.Images;
end;
end;*)
end.
|
unit kwRULES;
{* Аналог CASE и трансформаторов в MDP. Если условие выполняется, то выполняется следующий за ним оператор и осуществляется выход }
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwRULES.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "RULES" MUID: (4F51EC180118)
// Имя типа: "TkwRULES"
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwBeginLikeWord
, tfwScriptingInterfaces
, kwCompiledWordPrim
;
type
TkwRULES = {final} class(TtfwBeginLikeWord)
{* Аналог CASE и трансформаторов в MDP. Если условие выполняется, то выполняется следующий за ним оператор и осуществляется выход }
protected
function EndBracket(const aContext: TtfwContext;
aSilent: Boolean): RtfwWord; override;
function CompiledWordClass(const aCtx: TtfwContext): RkwCompiledWordPrim; override;
class function GetWordNameForRegister: AnsiString; override;
end;//TkwRULES
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, kwCompiledRules
, kwStandardProcedureCloseBracket
//#UC START# *4F51EC180118impl_uses*
//#UC END# *4F51EC180118impl_uses*
;
function TkwRULES.EndBracket(const aContext: TtfwContext;
aSilent: Boolean): RtfwWord;
//#UC START# *4DB6C99F026E_4F51EC180118_var*
//#UC END# *4DB6C99F026E_4F51EC180118_var*
begin
//#UC START# *4DB6C99F026E_4F51EC180118_impl*
Result := TkwStandardProcedureCloseBracket;
//#UC END# *4DB6C99F026E_4F51EC180118_impl*
end;//TkwRULES.EndBracket
function TkwRULES.CompiledWordClass(const aCtx: TtfwContext): RkwCompiledWordPrim;
//#UC START# *4DBAEE0D028D_4F51EC180118_var*
//#UC END# *4DBAEE0D028D_4F51EC180118_var*
begin
//#UC START# *4DBAEE0D028D_4F51EC180118_impl*
Result := TkwCompiledRules;
//#UC END# *4DBAEE0D028D_4F51EC180118_impl*
end;//TkwRULES.CompiledWordClass
class function TkwRULES.GetWordNameForRegister: AnsiString;
begin
Result := 'RULES';
end;//TkwRULES.GetWordNameForRegister
initialization
TkwRULES.RegisterInEngine;
{* Регистрация RULES }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit WPSyntaxHighlight;
{ -----------------------------------------------------------------------------
Copyright (C) 2002-2015 by wpcubed GmbH - Author: Julian Ziersch
info: http://www.wptools.de mailto:support@wptools.de
__ __ ___ _____ _ _____
/ / /\ \ \/ _ \/__ \___ ___ | |___ |___ |
\ \/ \/ / /_)/ / /\/ _ \ / _ \| / __| / /
\ /\ / ___/ / / | (_) | (_) | \__ \ / /
\/ \/\/ \/ \___/ \___/|_|___/ /_/
*****************************************************************************
WPSyntaxHighlight - WPTools 6 Syntax highlighting engine
Available: TWPXMLSyntax - simple XML highlighter
******************************************************************************
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
----------------------------------------------------------------------------- }
{ Usually the syntax highlighter applies standard attributes.
Optionally, if _NeedCalcAttr is true, it also can use a few non-destructive attribute bits:
cafsMisSpelled2 = $08000000;
cafsInsertedText = $10000000;
cafsHiddenText = $20000000;
cafsWordHighlight = $40000000;
If none of the bits is set the regular attribute of a character will be used, othewise
the attribute will be retrieved using the CalcAttr method which will be executed at
Paint and Initialization time. }
interface
{$I WPINC.INC}
uses {$IFDEF DELPHIXE}WinAPI.Windows, {$ELSE} Windows, {$ENDIF}
Classes, Graphics, WPRTEDefs, WPRTEDefsConsts;
type
TWPCustomSyntaxMode = (wpsynNormal, wpsynMLComment, wpsynComment, wpsynString, wpsynChar, wpsynNumber, wpsynReserved);
TWPCustomSyntax = class(TWPAbstractCustomSyntax)
protected
FMode: TWPCustomSyntaxMode;
FRTFProps: TWPRTFProps;
Ferror: Boolean;
FModeCA: array[TWPCustomSyntaxMode] of Cardinal;
FReservedColor: TColor;
public
procedure Init(Engine: TWPRTFEngineBasis); override;
procedure StartPar(par: TParagraph); override;
procedure NextChar(par: TParagraph; CPos: Integer); override;
procedure EndPar(par: TParagraph); override;
procedure PreProcess(RTFData: TWPRTFDataBlock); override;
procedure PostProcess(RTFData: TWPRTFDataBlock); override;
function CalcAttr(attr: Cardinal; par: TParagraph): Cardinal; override;
property RTFProps: TWPRTFProps read FRTFProps;
end;
{:: This class formats the text using a fix pitch font and highlights XML tags }
TWPXMLSyntax = class(TWPCustomSyntax)
public
constructor Create(aOwner: TComponent); override;
procedure NextChar(par: TParagraph; CPos: Integer); override;
end;
{:: This class highlighs XML tags in the text but does not apply permanent changes to the formatting }
TWPXMLRTFSyntax = class(TWPXMLSyntax)
public
constructor Create(aOwner: TComponent); override;
function CalcAttr(attr: Cardinal; par: TParagraph): Cardinal; override;
end;
{:: This class highlights field tokens marked by certain strings. It does <b>not</b> apply permanent changes to the text. }
TWPFieldSyntax = class(TWPCustomSyntax)
protected
FFieldStart, FFieldEnd: WideString;
FUseBands: Boolean;
// variations of fields to create groups (must be first non whitespace in paragraph)
FBandChar, FGroupChar: WideChar;
FEndCount: Integer;
FIsBandOrGroup: Boolean;
FBandMode: Integer; // 0=std, 1=open, 2=close
public
constructor Create(aOwner: TComponent); override;
procedure NextChar(par: TParagraph; CPos: Integer); override;
procedure EndPar(par: TParagraph); override;
function CalcAttr(attr: Cardinal; par: TParagraph): Cardinal; override;
procedure PreProcess(RTFData: TWPRTFDataBlock); override;
procedure PostProcess(RTFData: TWPRTFDataBlock); override;
protected
property BandChar: WideChar read FBandChar write FBandChar;
property GroupChar: WideChar read FGroupChar write FGroupChar;
published
property FieldStart: WideString read FFieldStart write FFieldStart;
property FieldEnd: WideString read FFieldEnd write FFieldEnd;
end;
{:: This class highlights field and band tokens marked by certain strings. It does <b>not</b> apply permanent changes to the text. <br>
Band tokens start with the sign :, groups with #. Only groups may be nested.
}
TWPFieldBandSyntax = class(TWPFieldSyntax)
public
constructor Create(aOwner: TComponent); override;
published
property FieldStart;
property FieldEnd;
property BandChar;
property GroupChar;
end;
implementation
const SYNBITMASK = $78000000;
procedure TWPCustomSyntax.Init(Engine: TWPRTFEngineBasis);
var atr: TWPStoredCharAttrInterface;
begin
FRTFProps := Engine.RTFData.RTFProps;
atr := TWPStoredCharAttrInterface.Create(Engine.RTFData);
try
atr.SetFontName('Courier New');
FModeCA[wpsynNormal] := atr.CharAttr;
atr.SetColor(TColor(RGB(0, 128, 0))); // Green
atr.SetStyles([afsItalic]);
FModeCA[wpsynComment] := atr.CharAttr; // Comment
FModeCA[wpsynMLComment] := atr.CharAttr; // Multi line comment
atr.SetColor(TColor(RGB(163, 21, 21))); // red
atr.SetStyles([]);
FModeCA[wpsynString] := atr.CharAttr;
FModeCA[wpsynChar] := atr.CharAttr;
atr.SetColor(clBlack); // black
FModeCA[wpsynNumber] := atr.CharAttr;
atr.SetColor(FReservedColor);
atr.SetStyles([afsBold]);
FModeCA[wpsynReserved] := atr.CharAttr;
finally
atr.Free;
end;
end;
procedure TWPCustomSyntax.StartPar(par: TParagraph);
var prev: TParagraph;
begin
if FRTFProps <> nil then
begin
prev := par.prev;
if (prev <> nil) and (paprStartingComment in prev.prop) then
FMode := wpsynMLComment
else FMode := wpsynNormal;
Ferror := false;
end;
end;
procedure TWPCustomSyntax.NextChar(par: TParagraph; CPos: Integer);
var bit: Cardinal;
begin
if FRTFProps <> nil then
begin
if _NeedCalcAttr then // Just set some bits
begin
bit := Integer(FMode) shl 26;
if Ferror then bit := bit or cafsMisSpelled;
par.CharAttr[CPos] := (par.CharAttr[CPos] and $FFFFFF) or bit;
end else // Default, really APPLY the attribute
begin
if Ferror then par.CharAttr[CPos] := FModeCA[FMode] or cafsMisSpelled
else par.CharAttr[CPos] := FModeCA[FMode];
end;
end;
end;
procedure TWPCustomSyntax.EndPar(par: TParagraph);
begin
if FRTFProps <> nil then
begin
if (FMode = wpsynMLComment) <> (paprStartingComment in par.prop) then
begin
if FMode = wpsynMLComment then
include(par.prop, paprStartingComment)
else exclude(par.prop, paprStartingComment);
par := par.next;
while par <> nil do
begin
include(par.prop, paprMustInit);
par := par.next;
end;
_NeedFullReformat := true;
end;
end;
end;
function TWPCustomSyntax.CalcAttr(attr: Cardinal; par: TParagraph): Cardinal;
begin
Result := attr;
end;
procedure TWPCustomSyntax.PreProcess(RTFData: TWPRTFDataBlock);
begin
end;
procedure TWPCustomSyntax.PostProcess(RTFData: TWPRTFDataBlock);
begin
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
constructor TWPXMLSyntax.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
FReservedColor := clBlue;
end;
procedure TWPXMLSyntax.NextChar(par: TParagraph; CPos: Integer);
var C: WideChar;
function CC(i: Integer): WideChar;
begin if (CPos + i < 0) or (CPos + i >= par.CharCount) then Result := #0 else Result := par.CharItem[CPos + i]; end;
begin
if FRTFProps <> nil then
begin
C := par.CharItem[CPos];
if not (FMode in [wpsynMLComment, wpsynComment, wpsynReserved, wpsynString]) then
begin
if (C = '&') then FMode := wpsynChar
else if (C = '<') then
begin
if (CC(1) = '!') and (CC(2) = '-') and (CC(3) = '-') then
FMode := wpsynMLComment
else FMode := wpsynReserved;
end;
if C = '>' then Ferror := true;
end
else
begin
if (FMode = wpsynReserved) and (c = #32) then FMode := wpsynString
else if (FMode = wpsynString) and (c = '>') then FMode := wpsynReserved;
if C = '<' then Ferror := true;
end;
inherited NextChar(par, CPos);
if (FMode = wpsynMLComment) and (C = '>') and (CC(-1) = '-') then
FMode := wpsynNormal
else if (FMode = wpsynReserved) and (C = '>') then
FMode := wpsynNormal
else if (FMode = wpsynChar) and ((C = ';') or (C = #32)) then
FMode := wpsynNormal;
Ferror := false;
end;
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
constructor TWPXMLRTFSyntax.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
_NeedCalcAttr := true;
end;
// called by RTF engine to get character attribute. The context paragraph is
// also provided to make the returned value dependent of other factors
function TWPXMLRTFSyntax.CalcAttr(attr: Cardinal; par: TParagraph): Cardinal;
begin
if (attr and SYNBITMASK) = 0 then
Result := attr
else Result := FModeCA[TWPCustomSyntaxMode(attr shr 26)]
+ (attr and cafsMisSpelled);
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
constructor TWPFieldSyntax.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
_NeedCalcAttr := true;
FFieldStart := '<<';
FFieldEnd := '>>';
FBandChar := #$FFFF;
FGroupChar := #$FFFF;
FReservedColor := clRed;
end;
constructor TWPFieldBandSyntax.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
FBandChar := ':';
FGroupChar := '#';
FUseBands := true;
end;
procedure TWPFieldSyntax.NextChar(par: TParagraph; CPos: Integer);
var C, C2, C3, CB: WideChar;
function CC(i: Integer): WideChar;
begin if (CPos + i < 0) or (CPos + i >= par.CharCount) then Result := #0 else Result := par.CharItem[CPos + i]; end;
var b : Boolean; off, i: Integer; bit: Cardinal;
begin
if (FRTFProps <> nil) and (FFieldStart <> '') and (FFieldEnd <> '') then
begin
C := par.CharItem[CPos];
// Detect Start
if FMode = wpsynNormal then
begin
if C = FFieldStart[1] then
begin
b := true;
for i := 2 to Length(FFieldStart) do
if CC(i - 1) <> FFieldStart[i] then
begin b := false; break; end;
if b then
begin
off := Length(FFieldStart);
C2 := cc(off);
b := true;
// Closed Field (not group!>
if C2 = '/' then
begin
inc(off);
C2 := cc(off);
if (C2 = FBandChar) or (C2 = FGroupChar) then
begin
FIsBandOrGroup := true;
FBandMode := 0; // STD
b := false;
// Wrong syntax, <</# instead of <<#/
end;
end else
// Check for Band or Group
if (C2 = FBandChar) or (C2 = FGroupChar) then
begin
if C2 = FGroupChar then
FBandMode := 1; // OPEN
CB := C2;
inc(off);
C2 := cc(off);
FIsBandOrGroup := true;
if C2 = '/' then
begin
// Bands may not be closed
if CB = FBandChar then b := false
else FBandMode := 2; // CLOSE
// Next Char
inc(off);
C2 := cc(off);
end;
end;
C3 := cc(off + 1);
// Detect if this is just text, not a token
if (C2 <= #32) or (C2 = #39) or (C2 = '"') or
(((C2 = '.') or
(C2 = '!') or
(C2 = '?')) and
(C3 = #32))
or (par.QuickFind(FFieldEnd, false, CPos + Length(FFieldStart)) < 0) // Not closed in this line !
then
begin
// Ignored !!
FIsBandOrGroup := false;
end else
if FIsBandOrGroup then
begin
for i := 0 to CPos - 1 do
if par.ANSIChr[i] > #32 then
begin
b := false;
break;
end;
FMode := wpsynReserved;
FEndCount := -1;
// Not first char in line or inside of a table. (inside group is ok)
if not b or (par.ParentTable <> nil) then
FError := true;
end else // just a field
begin
FMode := wpsynReserved;
FEndCount := -1;
end;
end;
end;
end;
// Update text -------------------------------------------------------------
if FMode = wpsynReserved then
bit := cafsWordHighlight
else if FMode = wpsynComment then
bit := cafsInsertedText
else bit := 0;
if Ferror then bit := bit or cafsMisSpelled2;
par.CharAttr[CPos] := (par.CharAttr[CPos] and not
(cafsWordHighlight + cafsInsertedText + cafsMisSpelled2)
) or bit;
// -------------------------------------------------------------------------
// Switch it off ?
if FEndCount < 0 then
FEndCount := 0 // Skip!
else
if (FMode = wpsynReserved) then
begin
if FEndCount >= Length(FFieldEnd) then
FMode := wpsynNormal
else if FEndCount < Length(FFieldEnd) then
begin
if FFieldEnd[FEndCount + 1] = C then
begin
inc(FEndCount);
if FEndCount >= Length(FFieldEnd) then
begin
if FIsBandOrGroup then
FMode := wpsynComment
else FMode := wpsynNormal;
end;
end else
begin
FEndCount := 0;
if FFieldEnd[FEndCount + 1] = C then
inc(FEndCount);
end;
end
end;
// Leave alone !!
//Ferror := false;
end;
end;
procedure TWPFieldSyntax.EndPar(par: TParagraph);
begin
inherited EndPar(par);
if FUseBands then
begin
if FIsBandOrGroup then
begin
if FBandMode = 0 then
par.state := par.state + [wpstParIsBand] - [wpstLevelBegin, wpstLevelEnd]
else if FBandMode = 1 then
par.state := par.state + [wpstLevelBegin] - [wpstParIsBand, wpstLevelEnd]
else if FBandMode = 2 then
par.state := par.state + [wpstLevelEnd] - [wpstLevelBegin, wpstParIsBand];
end else
par.state := par.state - [wpstLevelEnd, wpstLevelBegin, wpstParIsBand];
end;
FIsBandOrGroup := false;
FBandMode := 0;
FMode := wpsynNormal;
end;
// Sets the levels of all paragraph
procedure TWPFieldSyntax.PreProcess(RTFData: TWPRTFDataBlock);
var par: TParagraph;
begin
if FUseBands and (RTFData <> nil) then
begin
par := RTFData.FirstPar;
while par <> nil do
begin
par.Level := 0;
par := par.NextPar;
end;
end;
end;
// Sets the levels of all paragraph according to their states
procedure TWPFieldSyntax.PostProcess(RTFData: TWPRTFDataBlock);
var par: TParagraph;
l: Integer;
begin
if FUseBands and (RTFData <> nil) then
begin
l := 0;
par := RTFData.FirstPar;
while par <> nil do
begin
par.Level := l;
par.state := par.state - [wpstParError];
if wpstLevelBegin in par.State then inc(l)
else if wpstLevelEnd in par.State then
begin
dec(l);
par.Level := l;
if l < 0 then
par.state := par.state + [wpstParError];
end;
par := par.NextPar;
end;
end;
end;
function TWPFieldSyntax.CalcAttr(attr: Cardinal; par: TParagraph): Cardinal;
begin
if (attr and cafsWordHighlight) <> 0 then
Result := FModeCA[wpsynReserved] + (attr and (cafsMisSpelled + cafsMisSpelled2))
else if (attr and cafsInsertedText) <> 0 then
Result := FModeCA[wpsynComment] + (attr and (cafsMisSpelled + cafsMisSpelled2))
else Result := attr;
if (par <> nil) and (wpstParError in par.state) then Result := Result or cafsMisSpelled; // !!!
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 frmTableFind;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, cxLookAndFeelPainters, cxLabel, cxEdit, cxTextEdit,
StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxListBox, jpeg, DB,
MemDS, DBAccess, Ora, cxCheckBox, cxGroupBox, cxPC;
type
TTableFindFrm = class(TForm)
cxGroupBox2: TcxGroupBox;
btnCancel: TcxButton;
btnOK: TcxButton;
cxPageControl1: TcxPageControl;
cxTabSheet1: TcxTabSheet;
cxGroupBox1: TcxGroupBox;
lbFields: TcxListBox;
edtValue: TcxTextEdit;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
lbFilter: TcxListBox;
btnAdd: TcxButton;
btnDelete: TcxButton;
cbCaseInsensitive: TcxCheckBox;
cbPartialKey: TcxCheckBox;
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Init(QTable: TOraQuery; ActiveColumn: string);
end;
var
TableFindFrm: TTableFindFrm;
implementation
{$R *.dfm}
uses Util, Provider, VisualOptions, GenelDM;
procedure TTableFindFrm.Init(QTable: TOraQuery; ActiveColumn: string);
var
i: integer;
val: TStrings;
field: string;
Options: TLocateOptions;
begin
TableFindFrm := TTableFindFrm.Create(Application);
Self := TableFindFrm;
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
for i := 0 to QTable.FieldList.Count -1 do
begin
lbFields.Items.Add(QTable.FieldList[i].FieldName);
if QTable.FieldList[i].FieldName = ActiveColumn then
lbFields.ItemIndex := i;
end;
ShowModal;
if ModalResult = mrOK then
begin
for i := 0 to lbFilter.Count -1 do
begin
field := field + copy( lbFilter.Items[i], 1, pos('=',lbFilter.Items[i])-1 );
if i <> lbFilter.Count -1 then field := field + ';';
end;
val := TStringList.Create;
for i := 0 to lbFilter.Count -1 do
val.Add(copy( lbFilter.Items[i], pos('=',lbFilter.Items[i])+1, length(lbFilter.Items[i])));
if cbCaseInsensitive.Checked then Options := Options + [loCaseInsensitive];
if cbPartialKey.Checked then Options := Options + [loPartialKey];
if not QTable.Locate(Field,VarArrayFromStrings(val),Options) then
MessageDlg('No records match your search criteria.', mtInformation, [mbOK], 0);
end;
free;
end;
procedure TTableFindFrm.btnAddClick(Sender: TObject);
var
i: integer;
begin
if edtValue.Text = '' then
begin
MessageDlg('You must enter Field Value', mtInformation, [mbOK], 0);
exit;
end;
for i := 0 to lbFields.Count-1 do
begin
if lbFields.Selected[i] then
lbFilter.Items.Add(lbFields.Items[i]+'='+edtValue.Text);
end;
edtValue.Text := '';
end;
procedure TTableFindFrm.btnDeleteClick(Sender: TObject);
begin
if lbFilter.Count < 1 then exit;
lbFilter.DeleteSelected;
end;
end.
|
{*******************************************************}
{ }
{ TDCMinTray Component }
{ }
{ Copyright (c) 1997-2000 Dream Company }
{ http://www.dream-com.com }
{ e-mail: contact@dream-com.com }
{ }
{*******************************************************}
unit dcMinTray;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ShellApi, Menus;
type
TDCRestoreMode=(rmClick,rmDblClick);
TDCTrayMode=(tmOnMinimize,tmAlways);
TDCMinTray = class(TComponent)
private
FHideWhenMinimized:Boolean;
FHint:String;
FIsSetHook:Boolean;
FMinimized:Boolean;
FPopupMenu:TPopupMenu;
FRestoreMode:TDCRestoreMode;
FStreamTrayMode:TDCTrayMode;
FTrayData:TNotifyIconData;
FTrayIconCreated:Boolean;
FTrayMode:TDCTrayMode;
FIcon : TIcon;
Procedure AddTrayIcon;
Function ApplicationHook(Var Message:TMessage):Boolean;
Procedure HookMainForm;
Procedure RemoveTrayIcon;
Procedure SetHideWhenMinimized(Value:Boolean);
Procedure SetHint(const Value:String);
Procedure SetTrayMode(Value:TDCTrayMode);
Procedure UnhookMainForm;
Procedure SetIcon(Value : TIcon);
protected
Procedure Loaded;override;
Procedure Notification(AComponent:TComponent;Operation:TOperation);override;
public
Constructor Create(AOwner:TComponent);override;
Destructor Destroy;override;
Procedure HideFromTaskBar;
Procedure RestoreApplication;
Procedure ShowInTaskBar;
published
Property HideWhenMinimized:Boolean read FHideWhenMinimized write SetHideWhenMinimized default True;
Property Hint:String read FHint write SetHint;
Property PopupMenu:TPopupMenu read FPopupMenu write FPopupMenu;
Property RestoreMode:TDCRestoreMode read FRestoreMode write FRestoreMode default rmDblClick;
Property TrayMode:TDCTrayMode read FTrayMode write SetTrayMode default tmOnMinimize;
property TrayIcon : TIcon read FIcon write SetIcon;
end;
procedure Register;
implementation
const
TrayID=1;
CM_TRAYICON=WM_USER+1;
Constructor TDCMinTray.Create(AOwner:TComponent);
Begin
Inherited;
FIcon := TIcon.Create;
FHideWhenMinimized:=True;
FRestoreMode:=rmDblClick;
End;
{---------------------------------------------------------}
Destructor TDCMinTray.Destroy;
Begin
FIcon.Free;
RemoveTrayIcon;
UnhookMainForm;
Inherited;
End;
{---------------------------------------------------------}
Procedure TDCMinTray.SetIcon(Value : TIcon);
Begin
FIcon.Assign(Value);
End;
{---------------------------------------------------------}
Procedure TDCMinTray.AddTrayIcon;
Var
AHint:String;
Begin
FTrayData.cbSize:=SizeOf(FTrayData);
FTrayData.Wnd:=Application.Handle;
FTrayData.uID:=TrayID;
FTrayData.uFlags:=NIF_ICON Or NIF_MESSAGE Or NIF_TIP;
FTrayData.uCallBackMessage:=CM_TRAYICON;
If Not FIcon.Empty then
FTrayData.hIcon := FIcon.Handle
Else
Begin
FTrayData.hIcon:=Application.Icon.Handle;
If FTrayData.hIcon=0 Then
FTrayData.hIcon:=Application.Icon.Handle;
End;
AHint:=FHint;
If AHint='' Then
AHint:=Application.Title;
StrLCopy(FTrayData.szTip,PChar(AHint),SizeOf(FTrayData.szTip)-1);
Shell_NotifyIcon(NIM_ADD,@FTrayData);
FTrayIconCreated:=True;
End;
{---------------------------------------------------------}
Function TDCMinTray.ApplicationHook(Var Message:TMessage):Boolean;
Var
Pt:TPoint;
Begin
Result:=False;
Case Message.Msg Of
WM_SIZE:
Case Message.wParam Of
SIZE_MINIMIZED:
Begin
If FHideWhenMinimized Then
HideFromTaskBar;
FMinimized:=True;
If FTrayMode=tmOnMinimize Then
AddTrayIcon;
End;
End;
WM_SYSCOMMAND:
Case Message.wParam Of
SC_RESTORE:
RestoreApplication;
End;
WM_DESTROY:
Begin
RemoveTrayIcon;
UnhookMainForm;
End;
CM_TRAYICON:
Begin
Case Message.lParam Of
WM_RBUTTONUP:
If FPopupMenu<>Nil Then
Begin
GetCursorPos(Pt);
SetActiveWindow(TForm(Owner).Handle);
FPopupMenu.Popup(Pt.X,Pt.Y);
End;
WM_LBUTTONUP:
If FRestoreMode=rmClick Then
RestoreApplication;
WM_LBUTTONDBLCLK:
If FRestoreMode=rmDblClick Then
RestoreApplication;
End;
End;
End;
End;
{---------------------------------------------------------}
Procedure TDCMinTray.HideFromTaskBar;
Begin
ShowWindow(Application.Handle,SW_HIDE);
End;
{---------------------------------------------------------}
Procedure TDCMinTray.HookMainForm;
Begin
Application.HookMainWindow(ApplicationHook);
End;
{---------------------------------------------------------}
Procedure TDCMinTray.Loaded;
Begin
Inherited;
If Not (csDesigning In ComponentState) And (Owner Is TForm) And
((Application.MainForm=Nil) Or (Owner=Application.MainForm)) Then
Begin
HookMainForm;
FIsSetHook:=True;
SetTrayMode(FStreamTrayMode);
End;
End;
{---------------------------------------------------------}
Procedure TDCMinTray.Notification(AComponent:TComponent;Operation:TOperation);
Begin
Inherited;
If (AComponent=FPopupMenu) And (Operation=opRemove) Then
FPopupMenu:=Nil;
End;
{---------------------------------------------------------}
Procedure TDCMinTray.RemoveTrayIcon;
Begin
If FTrayIconCreated Then
Begin
Shell_NotifyIcon(NIM_DELETE,@FTrayData);
FTrayIconCreated:=False;
End;
End;
{---------------------------------------------------------}
Procedure TDCMinTray.RestoreApplication;
Begin
If FHideWhenMinimized Then
ShowInTaskBar;
Application.Restore;
FMinimized:=False;
If TrayMode=tmOnMinimize Then
RemoveTrayIcon;
End;
{---------------------------------------------------------}
Procedure TDCMinTray.ShowInTaskBar;
Begin
ShowWindow(Application.Handle,SW_SHOW);
End;
{---------------------------------------------------------}
Procedure TDCMinTray.SetHideWhenMinimized(Value:Boolean);
Begin
If FHideWhenMinimized=Value Then
Exit;
FHideWhenMinimized:=Value;
If FMinimized Then
If Value Then
ShowInTaskBar
Else
HideFromTaskBar;
End;
{---------------------------------------------------------}
Procedure TDCMinTray.SetHint(const Value:String);
Var
Data:TNotifyIconData;
Begin
If FHint=Value Then
Exit;
FHint:=Value;
If FTrayIconCreated Then
Begin
Data:=FTrayData;
Data.uFlags:=NIF_TIP;
StrLCopy(Data.szTip,PChar(FHint),SizeOf(Data.szTip)-1);
Shell_NotifyIcon(NIM_MODIFY,@Data);
End;
End;
{---------------------------------------------------------}
Procedure TDCMinTray.SetTrayMode(Value:TDCTrayMode);
Begin
If FTrayMode=Value Then
Exit;
If csLoading In ComponentState Then
Begin
FStreamTrayMode:=Value;
Exit;
End;
FTrayMode:=Value;
If Not (csDesigning In ComponentState) Then
If FTrayMode=tmOnMinimize Then
Begin
If Not FMinimized Then
RemoveTrayIcon;
End
Else
AddTrayIcon;
End;
{---------------------------------------------------------}
Procedure TDCMinTray.UnhookMainForm;
Begin
If FIsSetHook Then
Application.UnHookMainWindow(ApplicationHook);
End;
procedure Register;
begin
RegisterComponents('Dream Company', [TDCMinTray]);
end;
end. |
unit Unit1;
interface
type
TElem = record
id: integer;
libelle: string[50];
coche: boolean;
end;
TListe = array of TElem;
function ajouter(libelle: string): integer;
procedure modifier(id: integer; libelle: string);
procedure supprimer(id: integer);
procedure cocher(id: integer);
procedure decocher(id: integer);
function estCoché(id: integer): boolean;
function lister: TListe;
implementation
uses system.sysutils, system.ioutils, FireDAC.Comp.Client, FireDAC.Phys.SQLite, FireDAC.UI.Intf, FireDAC.FMXUI.Wait, FireDAC.Stan.Intf, FireDAC.Comp.UI,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, Data.DB,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet;
const
FichName = 'Presentation-RADStudio-Delphi.db';
var
connection: tfdconnection;
qry: tfdquery;
function ajouter(libelle: string): integer;
begin
qry.Insert;
qry.FieldByName('libelle').AsString := libelle;
qry.Post;
qry.Refresh;
end;
procedure modifier(id: integer; libelle: string);
begin
if qry.Locate('id', id) then
begin
qry.Edit;
qry.FieldByName('libelle').AsString := libelle;
qry.Post;
end;
end;
procedure supprimer(id: integer);
begin
if qry.Locate('id', id) then
qry.Delete;
end;
procedure cocher(id: integer);
begin
if qry.Locate('id', id) then
begin
qry.Edit;
qry.FieldByName('coche').AsInteger := 1;
qry.Post;
end;
end;
procedure decocher(id: integer);
begin
if qry.Locate('id', id) then
begin
qry.Edit;
qry.FieldByName('coche').AsInteger := 0;
qry.Post;
end;
end;
function estCoché(id: integer): boolean;
begin
result := qry.Locate('id', id) and (qry.FieldByName('coche').AsInteger = 1);
end;
function lister: TListe;
begin
setlength(result, 0);
if (qry.FindFirst) then
repeat
setlength(result, length(result) + 1);
result[length(result) - 1].id := qry.FieldByName('id').AsInteger;
result[length(result) - 1].libelle := qry.FieldByName('libelle').AsString;
result[length(result) - 1].coche := qry.FieldByName('coche').AsInteger = 1;
until not qry.FindNext;
end;
procedure create;
var
nom_fichier: string;
database_existante: boolean;
begin
nom_fichier := tpath.Combine(tpath.GetDocumentsPath, FichName);
database_existante := tfile.Exists(nom_fichier);
connection := tfdconnection.create(nil);
connection.Params.Clear;
connection.Params.Values['DriverID'] := 'SQLite';
connection.Params.Values['Database'] := nom_fichier;
{$IFDEF DEBUG}
connection.Params.Values['Password'] := '';
connection.Params.Values['Encrypt'] := '';
{$ELSE}
connection.Params.Values['Password'] := FilePassword;
connection.Params.Values['Encrypt'] := 'aes-256';
{$ENDIF}
connection.LoginPrompt := false;
connection.Connected := true;
if not database_existante then
begin
connection.ExecSQL('CREATE TABLE IF NOT EXISTS liste (' + 'id INTEGER PRIMARY Key, ' + 'libelle VARCHAR(50) DEFAULT "", ' +
'coche INTEGER DEFAULT 0' + ')');
connection.ExecSQL('CREATE INDEX IF NOT EXISTS liste_by_id ON liste (id,libelle)');
connection.ExecSQL('CREATE INDEX IF NOT EXISTS liste_by_libelle ON liste (libelle,id)');
end;
qry := tfdquery.create(nil);
qry.connection := connection;
qry.Open('select * from liste order by id');
end;
procedure destroy;
begin
if assigned(qry) then
freeandnil(qry);
if assigned(connection) then
freeandnil(connection);
end;
initialization
create;
finalization
destroy;
end.
|
unit DelphiUp.View.Components.Cards.Interfaces;
interface
uses
System.UITypes;
type
iComponentCardAttributes<T> = interface
['{17BBB4F1-D812-4CAA-B486-241405AC404D}']
function Title ( aValue : String ) : iComponentCardAttributes<T>; overload;
function Title : String; overload;
function FontTitleSize ( aValue : Integer ) : iComponentCardAttributes<T>; overload;
function FontTitleSize : Integer; overload;
function FontTitleColor ( aValue : TAlphaColor ) : iComponentCardAttributes<T>; overload;
function FontTitleColor : TAlphaColor; overload;
function Background ( aValue : TAlphaColor ) : iComponentCardAttributes<T>; overload;
function Background : TAlphaColor; overload;
function DestBackground ( aValue : TAlphaColor ) : iComponentCardAttributes<T>; overload;
function DestBackground : TAlphaColor; overload;
function &End : T;
end;
implementation
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 ClpAsn1Set;
{$I ..\Include\CryptoLib.inc}
interface
uses
SysUtils,
Math,
Generics.Collections,
ClpCryptoLibTypes,
ClpCollectionUtilities,
ClpDerNull,
{$IFDEF DELPHI}
ClpIDerNull,
{$ENDIF DELPHI}
ClpIAsn1TaggedObject,
ClpIAsn1EncodableVector,
ClpAsn1EncodableVector,
ClpIAsn1Sequence,
ClpAsn1Encodable,
ClpIProxiedInterface,
ClpIAsn1SetParser,
ClpIAsn1Set,
ClpAsn1Object;
resourcestring
SInvalidObject = 'Object Implicit - Explicit Expected.';
SUnknownObject = 'Unknown object in GetInstance: %s, "obj"';
SInvalidSequence = '"Failed to Construct Sequence from byte array: " %s';
type
/// <summary>
/// return an Asn1Set from the given object.
/// </summary>
TAsn1Set = class abstract(TAsn1Object, IAsn1Set)
strict private
var
F_set: TList<IAsn1Encodable>;
FisSorted: Boolean;
function GetCount: Int32; virtual;
function GetParser: IAsn1SetParser; inline;
function GetSelf(Index: Integer): IAsn1Encodable; virtual;
function GetCurrent(const e: IAsn1Encodable): IAsn1Encodable;
/// <summary>
/// return true if a <= b (arrays are assumed padded with zeros).
/// </summary>
function LessThanOrEqual(const a, b: TCryptoLibByteArray): Boolean; inline;
type
TAsn1SetParserImpl = class sealed(TInterfacedObject, IAsn1SetParserImpl,
IAsn1SetParser)
strict private
Fouter: IAsn1Set;
Fmax, Findex: Int32;
public
constructor Create(const outer: IAsn1Set);
function ReadObject(): IAsn1Convertible;
function ToAsn1Object(): IAsn1Object;
end;
strict protected
function Asn1GetHashCode(): Int32; override;
function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override;
procedure AddObject(const obj: IAsn1Encodable); inline;
procedure Sort();
constructor Create(capacity: Int32);
public
destructor Destroy(); override;
public
function ToString(): String; override;
function ToArray(): TCryptoLibGenericArray<IAsn1Encodable>; virtual;
function GetEnumerable: TCryptoLibGenericArray<IAsn1Encodable>; virtual;
// /**
// * return the object at the sequence position indicated by index.
// *
// * @param index the sequence number (starting at zero) of the object
// * @return the object at the sequence position indicated by index.
// */
property Self[Index: Int32]: IAsn1Encodable read GetSelf; default;
/// <summary>
/// return an ASN1Set from the given object.
/// </summary>
/// <param name="obj">
/// the object we want converted.
/// </param>
/// <exception cref="EArgumentCryptoLibException">
/// if the object cannot be converted.
/// </exception>
class function GetInstance(const obj: TObject): IAsn1Set; overload; static;
/// <summary>
/// return an Asn1Set from the given object.
/// </summary>
/// <param name="obj">
/// the byte array we want converted.
/// </param>
/// <exception cref="EArgumentCryptoLibException">
/// if the object cannot be converted.
/// </exception>
class function GetInstance(const obj: TCryptoLibByteArray): IAsn1Set;
overload; static;
// /**
// * Return an ASN1 sequence from a tagged object. There is a special
// * case here, if an object appears to have been explicitly tagged on
// * reading but we were expecting it to be implicitly tagged in the
// * normal course of events it indicates that we lost the surrounding
// * sequence - so we need to add it back (this will happen if the tagged
// * object is a sequence that contains other sequences). If you are
// * dealing with implicitly tagged sequences you really <b>should</b>
// * be using this method.
// *
// * @param obj the tagged object.
// * @param explicitly true if the object is meant to be explicitly tagged,
// * false otherwise.
// * @exception ArgumentException if the tagged object cannot
// * be converted.
// */
class function GetInstance(const obj: IAsn1TaggedObject;
explicitly: Boolean): IAsn1Set; overload; static;
property Parser: IAsn1SetParser read GetParser;
property Count: Int32 read GetCount;
end;
implementation
uses
// included here to avoid circular dependency :)
ClpDerSet,
ClpAsn1TaggedObject;
{ TAsn1Set }
procedure TAsn1Set.AddObject(const obj: IAsn1Encodable);
begin
F_set.Add(obj);
end;
function TAsn1Set.GetCurrent(const e: IAsn1Encodable): IAsn1Encodable;
var
encObj: IAsn1Encodable;
begin
encObj := e;
// unfortunately null was allowed as a substitute for DER null
if (encObj = Nil) then
begin
result := TDerNull.Instance;
Exit;
end;
result := encObj;
end;
function TAsn1Set.Asn1Equals(const asn1Object: IAsn1Object): Boolean;
var
other: IAsn1Set;
l1, l2: TCryptoLibGenericArray<IAsn1Encodable>;
o1, o2: IAsn1Object;
Idx: Int32;
begin
if (not Supports(asn1Object, IAsn1Set, other)) then
begin
result := false;
Exit;
end;
if (Count <> other.Count) then
begin
result := false;
Exit;
end;
l1 := GetEnumerable;
l2 := other.GetEnumerable;
for Idx := System.Low(l1) to System.High(l1) do
begin
o1 := GetCurrent(l1[Idx]).ToAsn1Object();
o2 := GetCurrent(l2[Idx]).ToAsn1Object();
if (not(o1.Equals(o2))) then
begin
result := false;
Exit;
end;
end;
result := true;
end;
function TAsn1Set.Asn1GetHashCode: Int32;
var
hc: Int32;
o: IAsn1Encodable;
LListAsn1Encodable: TCryptoLibGenericArray<IAsn1Encodable>;
begin
hc := Count;
LListAsn1Encodable := Self.GetEnumerable;
for o in LListAsn1Encodable do
begin
hc := hc * 17;
if (o = Nil) then
begin
hc := hc xor TDerNull.Instance.GetHashCode();
end
else
begin
hc := hc xor o.GetHashCode();
end;
end;
result := hc;
end;
constructor TAsn1Set.Create(capacity: Int32);
begin
Inherited Create();
F_set := TList<IAsn1Encodable>.Create();
F_set.capacity := capacity;
FisSorted := false;
end;
destructor TAsn1Set.Destroy;
begin
F_set.Free;
inherited Destroy;
end;
function TAsn1Set.GetCount: Int32;
begin
result := F_set.Count;
end;
function TAsn1Set.GetEnumerable: TCryptoLibGenericArray<IAsn1Encodable>;
begin
result := F_set.ToArray;
end;
class function TAsn1Set.GetInstance(const obj: TCryptoLibByteArray): IAsn1Set;
begin
try
result := TAsn1Set.GetInstance(FromByteArray(obj) as TAsn1Object);
except
on e: EIOCryptoLibException do
begin
raise EArgumentCryptoLibException.CreateResFmt(@SInvalidSequence,
[e.Message]);
end;
end;
end;
class function TAsn1Set.GetInstance(const obj: IAsn1TaggedObject;
explicitly: Boolean): IAsn1Set;
var
inner: IAsn1Object;
asn1Set: IAsn1Set;
asn1Sequence: IAsn1Sequence;
v: IAsn1EncodableVector;
ae: IAsn1Encodable;
LListAsn1Encodable: TCryptoLibGenericArray<IAsn1Encodable>;
begin
inner := obj.GetObject();
if (explicitly) then
begin
if (not(obj.IsExplicit())) then
raise EArgumentCryptoLibException.CreateRes(@SInvalidObject);
result := inner as IAsn1Set;
Exit;
end;
//
// constructed object which appears to be explicitly tagged
// when it should be implicit means we have to add the
// surrounding sequence.
//
if (obj.IsExplicit()) then
begin
result := TDerSet.Create(inner);
Exit;
end;
if (Supports(inner, IAsn1Set, asn1Set)) then
begin
result := asn1Set;
Exit;
end;
//
// in this case the parser returns a sequence, convert it
// into a set.
//
if (Supports(inner, IAsn1Sequence, asn1Sequence)) then
begin
v := TAsn1EncodableVector.Create();
LListAsn1Encodable := asn1Sequence.GetEnumerable;
for ae in LListAsn1Encodable do
begin
v.Add(ae);
end;
// TODO Should be able to construct set directly from sequence?
result := TDerSet.Create(v, false);
Exit;
end;
raise EArgumentCryptoLibException.CreateResFmt(@SUnknownObject,
[(obj as TAsn1TaggedObject).ClassName]);
end;
class function TAsn1Set.GetInstance(const obj: TObject): IAsn1Set;
var
primitive: IAsn1Object;
asn1Set: IAsn1Set;
res: IAsn1SetParser;
begin
if ((obj = Nil) or (obj is TAsn1Set)) then
begin
result := obj as TAsn1Set;
Exit;
end;
if (Supports(obj, IAsn1SetParser, res)) then
begin
result := TAsn1Set.GetInstance(res.ToAsn1Object() as TAsn1Object);
Exit;
end;
if (obj is TAsn1Encodable) then
begin
primitive := (obj as TAsn1Encodable).ToAsn1Object();
if (Supports(primitive, IAsn1Set, asn1Set)) then
begin
result := asn1Set;
Exit;
end;
end;
raise EArgumentCryptoLibException.CreateResFmt(@SUnknownObject,
[obj.ClassName]);
end;
function TAsn1Set.GetParser: IAsn1SetParser;
begin
result := TAsn1SetParserImpl.Create(Self as IAsn1Set);
end;
function TAsn1Set.GetSelf(Index: Integer): IAsn1Encodable;
begin
result := F_set[index];
end;
function TAsn1Set.LessThanOrEqual(const a, b: TCryptoLibByteArray): Boolean;
var
len, I: Int32;
begin
len := Math.Min(System.length(a), System.length(b));
I := 0;
while I <> len do
begin
if (a[I] <> b[I]) then
begin
result := (a[I]) < (b[I]);
Exit;
end;
System.Inc(I);
end;
result := len = System.length(a);
end;
procedure TAsn1Set.Sort;
var
swapped: Boolean;
lastSwap, Index, swapIndex: Int32;
a, b: TCryptoLibByteArray;
temp: IAsn1Encodable;
begin
if (not FisSorted) then
begin
FisSorted := true;
if (F_set.Count > 1) then
begin
swapped := true;
lastSwap := F_set.Count - 1;
while (swapped) do
begin
index := 0;
swapIndex := 0;
a := F_set[0].GetEncoded(TAsn1Encodable.Der);
swapped := false;
while (index <> lastSwap) do
begin
b := F_set[index + 1].GetEncoded(TAsn1Encodable.Der);
if (LessThanOrEqual(a, b)) then
begin
a := b;
end
else
begin
temp := F_set[index];
// Review being picky for copy
// temp := System.Copy(F_set.List, Index, 1)[0];
F_set[index] := F_set[index + 1];
F_set[index + 1] := temp;
swapped := true;
swapIndex := index;
end;
System.Inc(index);
end;
lastSwap := swapIndex;
end;
end;
end;
end;
function TAsn1Set.ToArray: TCryptoLibGenericArray<IAsn1Encodable>;
var
values: TCryptoLibGenericArray<IAsn1Encodable>;
I: Int32;
begin
System.SetLength(values, Count);
for I := 0 to System.Pred(Count) do
begin
values[I] := Self[I];
end;
result := values;
end;
function TAsn1Set.ToString: String;
begin
result := TCollectionUtilities.ToStructuredString(F_set);
end;
{ TAsn1Set.TAsn1SetParserImpl }
constructor TAsn1Set.TAsn1SetParserImpl.Create(const outer: IAsn1Set);
begin
Inherited Create();
Fouter := outer;
Fmax := outer.Count;
end;
function TAsn1Set.TAsn1SetParserImpl.ReadObject: IAsn1Convertible;
var
obj: IAsn1Encodable;
sequence: IAsn1Sequence;
asn1Set: IAsn1Set;
begin
if (Findex = Fmax) then
begin
result := Nil;
Exit;
end;
obj := Fouter[Findex];
System.Inc(Findex);
if (Supports(obj, IAsn1Sequence, sequence)) then
begin
result := sequence.Parser;
Exit;
end;
if (Supports(obj, IAsn1Set, asn1Set)) then
begin
result := asn1Set.Parser;
Exit;
end;
// NB: Asn1OctetString implements Asn1OctetStringParser directly
// if (obj is Asn1OctetString)
// return ((Asn1OctetString)obj).Parser;
result := obj;
end;
function TAsn1Set.TAsn1SetParserImpl.ToAsn1Object: IAsn1Object;
begin
result := Fouter;
end;
end.
|
Uses
Crt, Graph;
Procedure Pause;
Var
C: Char;
Begin
while keypressed do
C := readkey;
repeat until keypressed;
End;
Procedure Recur(x, y, r, k: Integer);
Var
rr: Integer;
Begin
if r > k then
begin
Recur(x + r, y, r div 2, k);
Recur(x, y + r, r div 2, k);
Recur(x - r, y, r div 2, k);
Recur(x, y - r, r div 2, k);
Recur(x, y, r div 2, k * 2);
end;
SetColor(Random(GetMaxColor) + 1);
rr := Random(5) - 10;
Circle(x, y, r + rr);
End;
Procedure Draw;
Var
grDriver, grMode, ErrCode, x, y: Integer;
Begin
grDriver := Detect;
InitGraph(grDriver, grMode, '');
ErrCode := GraphResult;
if ErrCode = grOk then
begin
x := GetMaxX div 2;
y := GetMaxY div 2;
Recur(x, y, GetMaxY, 20);
Pause;
CloseGraph;
end
else
WriteLn('Graphics error: ', GraphErrorMsg(ErrCode));
End;
Begin
Randomize;
Draw;
End.
|
unit kinveyDataModule;
interface
uses
System.SysUtils, System.Classes, IPPeerClient, REST.OpenSSL,
REST.Backend.ServiceTypes, REST.Backend.MetaTypes, System.JSON,
REST.Backend.KinveyServices, REST.Backend.Providers,
REST.Backend.ServiceComponents, REST.Backend.KinveyProvider, REST.Client,
REST.Authenticator.Basic, Data.Bind.Components, Data.Bind.ObjectScope,
REST.Backend.KinveyAPI, REST.Types, REST.Backend.BindSource,
System.Generics.Collections, EmployeeTypes;
type
TKinveyAPIExtend = class(TKinveyAPI)
public
procedure ResetPassword(const AUsername: string);
end;
TdmBaaSUser = class(TDataModule)
KinveyProvider1: TKinveyProvider;
BackendUsers1: TBackendUsers;
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
HTTPBasicAuthenticator1: THTTPBasicAuthenticator;
storageEmployeeDirectory: TBackendStorage;
qryEmployeeDirectory: TBackendQuery;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
FKinveyAPI: TKinveyAPIExtend;
FEmployeeBackendObjects : TBackendObjectList<TEmployee>;
public
{ Public declarations }
procedure SignUp(const AUsername, APassword, AFullname, AEmail: string);
function Login(const AUsername, APassword: string): Boolean;
procedure Logout;
procedure ResetPassword(const AUsername: string);
// 3회차 추가
procedure InsertEmployee(AFullName, APhone, AEmail, ADepartment: string);
procedure DeleteEmployee(AEmployeeId : String);
procedure UpdateEmployee(AOriginalEmployee: TEmployee; AUpdatedEmployee: TEmployee);
function GetEmployees : TList<TEmployee>;
end;
var
dmBaaSUser: TdmBaaSUser;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
{ TDataModule1 }
procedure TdmBaaSUser.DataModuleCreate(Sender: TObject);
begin
FKinveyAPI := TKinveyAPIExtend.Create(nil);
KinveyProvider1.UpdateApi(FKinveyAPI);
end;
function TdmBaaSUser.Login(const AUsername, APassword: string): Boolean;
var
Login: TBackendEntityValue;
begin
try
BackendUsers1.Users.LoginUser(AUsername, APassword, Login);
Result := (Login.AuthToken <> '');
except
Exit(False);
end;
end;
procedure TdmBaaSUser.Logout;
begin
BackendUsers1.Users.Logout;
end;
procedure TdmBaaSUser.ResetPassword(const AUsername: string);
begin
{
// #1 REST Client 사용
RESTRequest1.Params.ParameterByName('appkey').Value := KinveyProvider1.AppKey;
RESTRequest1.Params.ParameterByName('username').Value := AUsername;
RESTRequest1.Execute;
}
FKinveyAPI.ResetPassword(AUsername);
end;
procedure TdmBaaSUser.SignUp(const AUsername, APassword, AFullname,
AEmail: string);
var
UserData: TJSONObject;
CreatedObject: TBackendEntityValue;
begin
UserData := TJSONObject.Create;
try
UserData.AddPair('fullname', AFullname);
UserData.AddPair('email', AEmail);
BackendUsers1.Users.SignupUser(AUsername, APassword, UserData, CreatedObject);
BackendUsers1.Users.Login(CreatedObject);
finally
UserData.Free;
end;
end;
function TdmBaaSUser.GetEmployees: TList<TEmployee>;
var
qryString : TArray<String>;
Employee : TEmployee;
EmployeeList : TList<TEmployee>;
begin
FEmployeeBackendObjects := TBackendObjectList<TEmployee>.Create;
qryString := TArray<String>.Create(Format('sort=%s', [TEmployeeMetaData.FullNameColumn]));
storageEmployeeDirectory.Storage.QueryObjects<TEmployee>(
TEmployeeMetaData.BackendType,
qryString,
FEmployeeBackendObjects
);
EmployeeList := TList<TEmployee>.Create;
for Employee in FEmployeeBackendObjects do
begin
Employee.Id := FEmployeeBackendObjects.EntityValues[Employee].ObjectID;
EmployeeList.Add(Employee);
end;
Result := EmployeeList;
end;
procedure TdmBaaSUser.InsertEmployee(AFullName, APhone, AEmail,
ADepartment: string);
var
Employee: TEmployee;
CreatedObject: TBackendEntityValue;
begin
Employee := TEmployee.Create;
Employee.FullName := AFullName;
Employee.Department := ADepartment;
Employee.Phone := APhone;
Employee.Email := AEmail;
storageEmployeeDirectory.Storage.CreateObject<TEmployee>(
TEmployeeMetaData.BackendType,
Employee,
CreatedObject);
end;
procedure TdmBaaSUser.DeleteEmployee(AEmployeeId: String);
begin
storageEmployeeDirectory.Storage.DeleteObject(TEmployeeMetaData.BackendType, AEmployeeId);
end;
procedure TdmBaaSUser.UpdateEmployee(AOriginalEmployee,
AUpdatedEmployee: TEmployee);
var
KnvyEmployeeObject: TBackendEntityValue;
UpdatedObject: TBackendEntityValue;
begin
KnvyEmployeeObject := FEmployeeBackendObjects.EntityValues[AOriginalEmployee];
storageEmployeeDirectory.Storage.UpdateObject<TEmployee>(KnvyEmployeeObject, AUpdatedEmployee, UpdatedObject);
end;
{ TKinveyAPIExtend }
procedure TKinveyAPIExtend.ResetPassword(const AUsername: string);
var
LConnectionInfo: TConnectionInfo;
begin
Request.ResetToDefaults;
// Basic Auth
LConnectionInfo := Self.ConnectionInfo;
LConnectionInfo.UserName := AUsername;
ConnectionInfo := LConnectionInfo;
AddAuthParameter(TAuthentication.UserName);
// App credentials
AddAuthParameter(TAuthentication.AppSecret);
Request.Method := TRESTRequestMethod.rmPOST;
Request.Resource := 'rpc/{appkey}/{username}/user-password-reset-initiate';
Request.AddParameter('username', AUsername, TRESTRequestParameterKind.pkURLSEGMENT );
Request.Execute;
CheckForResponseError([201]);
end;
end.
|
unit DataTrain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids, System.json, REST.json, idHTTP,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent,
Vcl.ComCtrls;
type
TFormData = class(TForm)
Panel1: TPanel;
btnView: TButton;
nethttp: TNetHTTPClient;
Button1: TButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Grid1: TStringGrid;
Memo1: TMemo;
Edit1: TEdit;
procedure FormCreate(Sender: TObject);
procedure btnViewClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure AturKolom;
end;
var
FormData: TFormData;
implementation
{$R *.dfm}
function FormatJSON(json: String): String;
var
tmpJson: TJsonObject;
begin
tmpJson := TJSONObject.ParseJSONValue(json) as TJSONObject;
Result := TJson.Format(tmpJson);
FreeAndNil(tmpJson);
end;
procedure TFormData.AturKolom;
begin
{ "train_name": "Prabu Jaya",
"class_name": "Eksekutif & Bisnis",
"station_departure": "Prabumulih",
"station_arrived": "Kertapati",
"departure_time": "09:00:00",
"arrived_time": "10:21:00"}
Grid1.RowCount := 2;
Grid1.ColCount := 7;
Grid1.Cells [0, 0] := 'No';
Grid1.Cells [1, 0] := 'Train Name';
Grid1.Cells [2, 0] := 'Class Name';
Grid1.Cells [3, 0] := 'Station Departure';
Grid1.Cells [4, 0] := 'Station Arrived';
Grid1.Cells [5, 0] := 'Departure Time';
Grid1.Cells [6, 0] := 'Arrived Time';
Grid1.ColWidths [0] := 40;
Grid1.ColWidths [1] := 175;
Grid1.ColWidths [2] := 225;
Grid1.ColWidths [3] := 100;
Grid1.ColWidths [4] := 100;
Grid1.ColWidths [5] := 100;
Grid1.ColWidths [6] := 100;
Grid1.FixedCols := 0;
end;
procedure TFormData.btnViewClick(Sender: TObject);
var
url: string;
mem: TStringStream;
str: string;
jso: TJSONObject;
jsa: TJSONArray;
iii: integer;
MyF : TFormatSettings;
tgl : string;
ddd : TDateTime;
begin
GetLocaleFormatSettings(GetUserDefaultLCID, MyF);
MyF.DateSeparator := '-';
MyF.TimeSeparator := ':';
MyF.ShortDateFormat := 'yyyy-mm-dd';
MyF.ShortTimeFormat := 'hh:nn:ss';
mem := TStringStream.Create;
//url := 'http://raw.githubusercontent.com/cokroyongky/myjson/master/train_schedules.json';
//url := 'http://researchlumen.lokal/schedule';
url := Edit1.Text;
nethttp.get(url, mem, nil);
str := mem.DataString;
jso := TJSONObject.ParseJSONValue(str) as TJSONObject;
jsa := jso.GetValue('data') as TJSONArray;
Grid1.RowCount := jsa.Count + 1;
for iii := 0 to jsa.Count -1 do
begin
jso := jsa.Items[iii] as TJSONObject;
Memo1.Clear;
Memo1.Lines.Add(FormatJSON(str));
//Memo1.Lines.Add(Format('%d. %s | %s', [iii + 1, jso.GetValue('train_name').Value, jso.GetValue('class_name').Value]));
Grid1.Cells[0, iii+1] := Format('%d', [iii+1]);
Grid1.Cells[1, iii+1] := jso.GetValue('train_name').value;
Grid1.Cells[2, iii+1] := jso.GetValue('class_name').value;
Grid1.Cells[3, iii+1] := jso.GetValue('station_departure').value;
Grid1.Cells[4, iii+1] := jso.GetValue('station_arrived').value;
Grid1.Cells[5, iii+1] := jso.GetValue('departure_time').value;
Grid1.Cells[6, iii+1] := jso.GetValue('arrived_time').value;
end;
mem.Free;
end;
procedure TFormData.Button1Click(Sender: TObject);
var
jso : TJSONObject;
mem : TStringStream;
jss : TJSONObject;
jsa : TJSONArray;
url : string;
str : string;
iii : integer;
begin
mem := TStringStream.Create;
//url := 'http://raw.githubusercontent.com/cokroyongky/myjson/master/train_schedules.json';
url := 'http://localhost:8010/umroh_book/index.php/admin/Jamaah_view/data_jamaah';
nethttp.get(url, mem, nil);
str := mem.DataString;
Memo1.Clear;
Memo1.Lines.Add(FormatJSON(str));
{url :='http://localhost:8010/umroh_book/index.php/admin/Jamaah_view/data_jamaah';
try
url := nethttp.Get(url);
memo1.Clear;
memo1.Lines.Add(url);
finally
FreeAndNil(nethttp);
end;}
end;
procedure TFormData.FormCreate(Sender: TObject);
begin
AturKolom;
//Edit1.Text := '';
end;
end.
|
unit IntfColSel;
interface
uses
Graphics, Contnrs;
type
IColorSelect = interface
['{3F961395-71F6-4822-BD02-3B475FF516D4}']
function Display (Modal: Boolean = True): Boolean;
procedure SetSelColor (Col: TColor);
function GetSelColor: TColor;
property SelColor: TColor
read GetSelColor write SetSelColor;
end;
procedure RegisterColorSelect (AClass: TClass);
var
ClassesColorSelect: TClassList;
implementation
procedure RegisterColorSelect (AClass: TClass);
begin
if ClassesColorSelect.IndexOf (AClass) < 0 then
ClassesColorSelect.Add (AClass);
end;
initialization
ClassesColorSelect := TClassList.Create;
finalization
ClassesColorSelect.Free;
end.
|
unit GetVendorUnit;
interface
uses SysUtils, Classes, BaseExampleUnit, EnumsUnit;
type
TGetVendor = class(TBaseExample)
public
procedure Execute(VendorId: integer);
end;
implementation
uses NullableBasicTypesUnit, VendorUnit;
procedure TGetVendor.Execute(VendorId: integer);
var
ErrorString: String;
Vendor: TVendor;
begin
Vendor := Route4MeManager.Telematics.Get(VendorId, ErrorString);
try
WriteLn('');
if (ErrorString = EmptyStr) then
begin
WriteLn('GetVendor successfully');
WriteLn('');
end
else
WriteLn(Format('GetVendor error: "%s"', [ErrorString]));
finally
FreeAndNil(Vendor);
end;
end;
end.
|
program ex;
type setChar=set of char; {тип "множество символов"}
str80=string[80]; {тип "строка длной 80 символов"}
pTop=^Top; {тип "указатель на вершину"}
Top=record {тип "вершина"}
operator:string[5]; {знак операции}
value:single; {значение константы}
left,right:pTop; {указатель на левое и правое поддерево}
end;
var st:str80; {строка - запись выражения}
root:pTop; {корень дерева выражения}
key:boolean; {признак существования значения в заданной точке}
x,xn,xe,dx,y:single; {начальное, конечное значения и шаг
аргумента, значение аргумента и функции}
n,i:word; {количество точек и номер текущей точки}
{рекурсивная функция констрирования поддерева
выражения с корнем r из строки st}
procedure Constr_Tree(r:pTop; st:str80);
var next:pTop;
SetOp:setChar;
po,code:integer;
stl,stri:str80;
c:single;
{внутренняя функция поиска первого вхождения операции в строке st:
SetOp - множество знаков операций; функция возвращает позицию
разделительного знака или 0}
Function PosOpFirst(st:str80; SetOp:setChar):byte;
var i,j,k,p:byte;
begin
j:=0;
k:=0;
p:=0;
i:=1;
while (i<=length(st)) and (p=0) do
begin
if st[i]='(' then
inc(j) {считаем количество открывающихся скобок}
else
if st[i]=')' then
inc(k) {считаем количество закрывающихся скобок}
else
if (j=k) and (st[i] in SetOp) then
p:=i;
inc(i);
end;
PosOpFirst:=p;
end;
{внутренняя функция поиска последнего вхождения операции в строке
st: SetOp - множество знаков операций; функция возвращает позицию
разделительного знака или 0}
Function PosOpLast(st:str80; SetOp:setChar):byte;
var i,j,k,p:byte;
begin
j:=0;
k:=0;
p:=0;
for i:=1 to length(st) do
begin
if st[i]='(' then
inc(j) {считаем количество открывающихся скобок}
else
if st[i]=')' then
inc(k) {считаем количество закрывающихся скобок}
else
if (j=k) and (st[i] in SetOp) then
p:=i;
inc(i);
end;
PosOpLast:=p;
end;
{раздел операторов функции констрирования дерева выражения}
begin
po:=PosOpLast(st,['+','-']); {ищем знак операции + или -}
if po=0 then
po:=PosOpLast(st,['*','/']); {ищем знак операции * или /}
if po=0 then
po:=PosOpFirst(st,['^']); {ищем знак операции ^}
if po<>0 then {разделяющий знак найден}
begin
r^.operator:=st[po]; {записываем знак операции в вершину}
stl:=copy(st,1,po-1); {копируем подстроку первого операнда}
if (stl[1]='(') and (PosOpLast(stl,['*','/','+','-','^'])=0 then
stl:=copy(stl,2,length(stl)-2; {копируем подстроку второго операнда}
if (stri[1]='(') and (PosOpLast(stri,['*','/','+','-','^'])=0 then
stri:=copy(stri,2,length(stri)-2); {убираем скобки}
new(r^.left); {создаем левое поддерево}
Constr_Tree(r^.left,stl); {конструируем левый операнд}
new(r^.right); {создаем правое поддерево}
Constr_Tree(r^.right,stri); {конструируем правый операнд}
end
else
if st[1]='x' then {аргумент}
begin
r^.operator:='x';
r^.left:=nil;
r^.right:=nil;
end
else
begin
val(st,c,code); {пытаемся получить число}
if code=9 then {константа}
begin
r^.operator:='o';
r^.left:=nil;
r^.right:=nil;
r^.value:=c;
end
else {функция}
begin
po:=Pos('(',st);
r^.operator:=copy(st,1,po-1); {выделяем имя функции}
r^.right:=nil;
stl:=copy(st,po+1,length(st)-po-1); {выделяем подстроку параметра}
new(r^.left);
Constr_Tree(r^.left,stl); {конструируем параметр}
end;
end;
end;
{рекурсивное вычисление значения функции:
если Key=false, то значение не существует}
Function Count(r:pTop; x:single; Var key:boolean):single;
var s,s1:single;
begin
if not key then {значение функции не существует}
begin
Count:=0;
exit;
end;
if r^.operator='o' then
Count:=r^.Value {константа}
else
if r^.operator='x' then
Count:=x {переменная x}
else
case r^.operator[1] of
'+':Count:=Count(r^.left,x,key)+Count(r^.right,x,key);
'-':Count:=Count(r^.left,x,key)-Count(r^.right,x,key);
'*':Count:=Count(r^.left,x,key)*Count(r^.right,x,key);
'/':begin
s:=Count(r^.right,x,key);
if abs(s)<1e-10 then {практический ноль}
begin
Count:=0;
key:=false;
end
else
Count:=Count(r^.left,x,key)/s;
end;
'^':begin
s:=Count(r^.left,x,key);
s1:=Count(r^.right,x,key);
if s<>0 then
Count:=exp(s1*ln(abs(s)))
else
if s1=0 then
Count:=1
else
Count:=0;
end;
's':Count:=sin(Count(r^.left,x,key));
'c':Count:=cos(Count(r^.left,x,key));
else {неопределенная операция}
begin
Count:=0;
key:=false;
end
end
end;
{основная прогамма}
begin
writeln('Vvedite virazhenie:');
readln(st);
write('Vvedite xn, xe, n: ');
readln(xn,xe,n);
new(Root);
Constr_Tree(Root,st);
dx:=(xe-xn)/(n-1);
writeln(' x ',' y');
x:=xn;
for i:=1 to n do
begin
key:=true;
y:=Count(Root,x,key);
if key then
writeln(x:6:3,y:20:3);
else
writeln(x:6:3,' ne sutshestvuet');
x:=x+dx;
end;
end.
|
unit CommonDictionKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы CommonDiction }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Diction\CommonDictionKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "CommonDictionKeywordsPack" MUID: (B862EAF3C351)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, vtPanel
, nscTreeViewWithAdapterDragDrop
{$If Defined(Nemesis)}
, nscContextFilter
{$IfEnd} // Defined(Nemesis)
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, CommonDiction_Form
, tfwControlString
{$If NOT Defined(NoVCL)}
, kwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
, tfwScriptingInterfaces
, tfwPropertyLike
, TypInfo
, tfwTypeInfo
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
;
type
Tkw_Form_CommonDiction = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы CommonDiction
----
*Пример использования*:
[code]
'aControl' форма::CommonDiction TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_CommonDiction
Tkw_CommonDiction_Control_BackgroundPanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола BackgroundPanel
----
*Пример использования*:
[code]
контрол::BackgroundPanel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CommonDiction_Control_BackgroundPanel
Tkw_CommonDiction_Control_BackgroundPanel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола BackgroundPanel
----
*Пример использования*:
[code]
контрол::BackgroundPanel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CommonDiction_Control_BackgroundPanel_Push
Tkw_CommonDiction_Control_WordsTree = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола WordsTree
----
*Пример использования*:
[code]
контрол::WordsTree TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CommonDiction_Control_WordsTree
Tkw_CommonDiction_Control_WordsTree_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола WordsTree
----
*Пример использования*:
[code]
контрол::WordsTree:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CommonDiction_Control_WordsTree_Push
Tkw_CommonDiction_Control_ContextFilter = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола ContextFilter
----
*Пример использования*:
[code]
контрол::ContextFilter TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CommonDiction_Control_ContextFilter
Tkw_CommonDiction_Control_ContextFilter_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола ContextFilter
----
*Пример использования*:
[code]
контрол::ContextFilter:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CommonDiction_Control_ContextFilter_Push
TkwEnCommonDictionBackgroundPanel = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_CommonDiction.BackgroundPanel }
private
function BackgroundPanel(const aCtx: TtfwContext;
aen_CommonDiction: Ten_CommonDiction): TvtPanel;
{* Реализация слова скрипта .Ten_CommonDiction.BackgroundPanel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnCommonDictionBackgroundPanel
TkwEnCommonDictionWordsTree = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_CommonDiction.WordsTree }
private
function WordsTree(const aCtx: TtfwContext;
aen_CommonDiction: Ten_CommonDiction): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .Ten_CommonDiction.WordsTree }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnCommonDictionWordsTree
TkwEnCommonDictionContextFilter = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_CommonDiction.ContextFilter }
private
function ContextFilter(const aCtx: TtfwContext;
aen_CommonDiction: Ten_CommonDiction): TnscContextFilter;
{* Реализация слова скрипта .Ten_CommonDiction.ContextFilter }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnCommonDictionContextFilter
function Tkw_Form_CommonDiction.GetString: AnsiString;
begin
Result := 'en_CommonDiction';
end;//Tkw_Form_CommonDiction.GetString
class function Tkw_Form_CommonDiction.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::CommonDiction';
end;//Tkw_Form_CommonDiction.GetWordNameForRegister
function Tkw_CommonDiction_Control_BackgroundPanel.GetString: AnsiString;
begin
Result := 'BackgroundPanel';
end;//Tkw_CommonDiction_Control_BackgroundPanel.GetString
class procedure Tkw_CommonDiction_Control_BackgroundPanel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_CommonDiction_Control_BackgroundPanel.RegisterInEngine
class function Tkw_CommonDiction_Control_BackgroundPanel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::BackgroundPanel';
end;//Tkw_CommonDiction_Control_BackgroundPanel.GetWordNameForRegister
procedure Tkw_CommonDiction_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('BackgroundPanel');
inherited;
end;//Tkw_CommonDiction_Control_BackgroundPanel_Push.DoDoIt
class function Tkw_CommonDiction_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::BackgroundPanel:push';
end;//Tkw_CommonDiction_Control_BackgroundPanel_Push.GetWordNameForRegister
function Tkw_CommonDiction_Control_WordsTree.GetString: AnsiString;
begin
Result := 'WordsTree';
end;//Tkw_CommonDiction_Control_WordsTree.GetString
class procedure Tkw_CommonDiction_Control_WordsTree.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop);
end;//Tkw_CommonDiction_Control_WordsTree.RegisterInEngine
class function Tkw_CommonDiction_Control_WordsTree.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::WordsTree';
end;//Tkw_CommonDiction_Control_WordsTree.GetWordNameForRegister
procedure Tkw_CommonDiction_Control_WordsTree_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('WordsTree');
inherited;
end;//Tkw_CommonDiction_Control_WordsTree_Push.DoDoIt
class function Tkw_CommonDiction_Control_WordsTree_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::WordsTree:push';
end;//Tkw_CommonDiction_Control_WordsTree_Push.GetWordNameForRegister
function Tkw_CommonDiction_Control_ContextFilter.GetString: AnsiString;
begin
Result := 'ContextFilter';
end;//Tkw_CommonDiction_Control_ContextFilter.GetString
class procedure Tkw_CommonDiction_Control_ContextFilter.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscContextFilter);
end;//Tkw_CommonDiction_Control_ContextFilter.RegisterInEngine
class function Tkw_CommonDiction_Control_ContextFilter.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ContextFilter';
end;//Tkw_CommonDiction_Control_ContextFilter.GetWordNameForRegister
procedure Tkw_CommonDiction_Control_ContextFilter_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('ContextFilter');
inherited;
end;//Tkw_CommonDiction_Control_ContextFilter_Push.DoDoIt
class function Tkw_CommonDiction_Control_ContextFilter_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ContextFilter:push';
end;//Tkw_CommonDiction_Control_ContextFilter_Push.GetWordNameForRegister
function TkwEnCommonDictionBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext;
aen_CommonDiction: Ten_CommonDiction): TvtPanel;
{* Реализация слова скрипта .Ten_CommonDiction.BackgroundPanel }
begin
Result := aen_CommonDiction.BackgroundPanel;
end;//TkwEnCommonDictionBackgroundPanel.BackgroundPanel
class function TkwEnCommonDictionBackgroundPanel.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_CommonDiction.BackgroundPanel';
end;//TkwEnCommonDictionBackgroundPanel.GetWordNameForRegister
function TkwEnCommonDictionBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwEnCommonDictionBackgroundPanel.GetResultTypeInfo
function TkwEnCommonDictionBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnCommonDictionBackgroundPanel.GetAllParamsCount
function TkwEnCommonDictionBackgroundPanel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_CommonDiction)]);
end;//TkwEnCommonDictionBackgroundPanel.ParamsTypes
procedure TkwEnCommonDictionBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx);
end;//TkwEnCommonDictionBackgroundPanel.SetValuePrim
procedure TkwEnCommonDictionBackgroundPanel.DoDoIt(const aCtx: TtfwContext);
var l_aen_CommonDiction: Ten_CommonDiction;
begin
try
l_aen_CommonDiction := Ten_CommonDiction(aCtx.rEngine.PopObjAs(Ten_CommonDiction));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_CommonDiction: Ten_CommonDiction : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aen_CommonDiction));
end;//TkwEnCommonDictionBackgroundPanel.DoDoIt
function TkwEnCommonDictionWordsTree.WordsTree(const aCtx: TtfwContext;
aen_CommonDiction: Ten_CommonDiction): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .Ten_CommonDiction.WordsTree }
begin
Result := aen_CommonDiction.WordsTree;
end;//TkwEnCommonDictionWordsTree.WordsTree
class function TkwEnCommonDictionWordsTree.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_CommonDiction.WordsTree';
end;//TkwEnCommonDictionWordsTree.GetWordNameForRegister
function TkwEnCommonDictionWordsTree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTreeViewWithAdapterDragDrop);
end;//TkwEnCommonDictionWordsTree.GetResultTypeInfo
function TkwEnCommonDictionWordsTree.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnCommonDictionWordsTree.GetAllParamsCount
function TkwEnCommonDictionWordsTree.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_CommonDiction)]);
end;//TkwEnCommonDictionWordsTree.ParamsTypes
procedure TkwEnCommonDictionWordsTree.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству WordsTree', aCtx);
end;//TkwEnCommonDictionWordsTree.SetValuePrim
procedure TkwEnCommonDictionWordsTree.DoDoIt(const aCtx: TtfwContext);
var l_aen_CommonDiction: Ten_CommonDiction;
begin
try
l_aen_CommonDiction := Ten_CommonDiction(aCtx.rEngine.PopObjAs(Ten_CommonDiction));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_CommonDiction: Ten_CommonDiction : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(WordsTree(aCtx, l_aen_CommonDiction));
end;//TkwEnCommonDictionWordsTree.DoDoIt
function TkwEnCommonDictionContextFilter.ContextFilter(const aCtx: TtfwContext;
aen_CommonDiction: Ten_CommonDiction): TnscContextFilter;
{* Реализация слова скрипта .Ten_CommonDiction.ContextFilter }
begin
Result := aen_CommonDiction.ContextFilter;
end;//TkwEnCommonDictionContextFilter.ContextFilter
class function TkwEnCommonDictionContextFilter.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_CommonDiction.ContextFilter';
end;//TkwEnCommonDictionContextFilter.GetWordNameForRegister
function TkwEnCommonDictionContextFilter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscContextFilter);
end;//TkwEnCommonDictionContextFilter.GetResultTypeInfo
function TkwEnCommonDictionContextFilter.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnCommonDictionContextFilter.GetAllParamsCount
function TkwEnCommonDictionContextFilter.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_CommonDiction)]);
end;//TkwEnCommonDictionContextFilter.ParamsTypes
procedure TkwEnCommonDictionContextFilter.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству ContextFilter', aCtx);
end;//TkwEnCommonDictionContextFilter.SetValuePrim
procedure TkwEnCommonDictionContextFilter.DoDoIt(const aCtx: TtfwContext);
var l_aen_CommonDiction: Ten_CommonDiction;
begin
try
l_aen_CommonDiction := Ten_CommonDiction(aCtx.rEngine.PopObjAs(Ten_CommonDiction));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_CommonDiction: Ten_CommonDiction : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(ContextFilter(aCtx, l_aen_CommonDiction));
end;//TkwEnCommonDictionContextFilter.DoDoIt
initialization
Tkw_Form_CommonDiction.RegisterInEngine;
{* Регистрация Tkw_Form_CommonDiction }
Tkw_CommonDiction_Control_BackgroundPanel.RegisterInEngine;
{* Регистрация Tkw_CommonDiction_Control_BackgroundPanel }
Tkw_CommonDiction_Control_BackgroundPanel_Push.RegisterInEngine;
{* Регистрация Tkw_CommonDiction_Control_BackgroundPanel_Push }
Tkw_CommonDiction_Control_WordsTree.RegisterInEngine;
{* Регистрация Tkw_CommonDiction_Control_WordsTree }
Tkw_CommonDiction_Control_WordsTree_Push.RegisterInEngine;
{* Регистрация Tkw_CommonDiction_Control_WordsTree_Push }
Tkw_CommonDiction_Control_ContextFilter.RegisterInEngine;
{* Регистрация Tkw_CommonDiction_Control_ContextFilter }
Tkw_CommonDiction_Control_ContextFilter_Push.RegisterInEngine;
{* Регистрация Tkw_CommonDiction_Control_ContextFilter_Push }
TkwEnCommonDictionBackgroundPanel.RegisterInEngine;
{* Регистрация en_CommonDiction_BackgroundPanel }
TkwEnCommonDictionWordsTree.RegisterInEngine;
{* Регистрация en_CommonDiction_WordsTree }
TkwEnCommonDictionContextFilter.RegisterInEngine;
{* Регистрация en_CommonDiction_ContextFilter }
TtfwTypeRegistrator.RegisterType(TypeInfo(Ten_CommonDiction));
{* Регистрация типа Ten_CommonDiction }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel));
{* Регистрация типа TvtPanel }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop));
{* Регистрация типа TnscTreeViewWithAdapterDragDrop }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscContextFilter));
{* Регистрация типа TnscContextFilter }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
end.
|
unit define_price;
interface
type
TRT_UpDownStatus = (
udNone,
udFlatline, // 持平
udUp, // 上涨
udDown // 下跌
);
TRT_WeightMode = (
weightUnknown,
weightNone, // 不复权
weightForward, // 前复权
weightBackward // 后复权
);
TStore_UpDownStatus = Integer;
PRT_Weight = ^TRT_Weight;
TRT_Weight = record
Value : double;
PackedValue : LongWord;
StartDate : Word;
EndDate : Word;
end;
PRT_WeightPackValue = ^TRT_WeightPackValue;
TRT_WeightPackValue = packed record
Value : LongWord;
end;
PRT_WeightFullValue = ^TRT_WeightFullValue;
TRT_WeightFullValue = packed record
Value : double;
end;
PRT_PricePack = ^TRT_PricePack;
TRT_PricePack = record
Value : LongWord; // 4
end;
PRT_PricePack_Range = ^TRT_PricePack_Range;
TRT_PricePack_Range = record // 16
PriceOpen : TRT_PricePack; // 4
PriceClose : TRT_PricePack; // 4
PriceHigh : TRT_PricePack; // 4
PriceLow : TRT_PricePack; // 4
end;
PRT_PriceFull = ^TRT_PriceFull;
TRT_PriceFull = record
Value : double;
end;
PRT_PriceFull_Range = ^TRT_PriceFull_Range;
TRT_PriceFull_Range = record
PriceOpen : TRT_PriceFull;
PriceClose : TRT_PriceFull;
PriceHigh : TRT_PriceFull;
PriceLow : TRT_PriceFull;
end;
PStore_Price = ^TStore_Price;
TStore_Price = record
Value : LongWord;
end;
PStore_PriceRange = ^TStore_PriceRange;
TStore_PriceRange = packed record
PriceOpen : TStore_Price; // 4 - 4
PriceHigh : TStore_Price; // 4 - 8 ( price * 100 )
PriceLow : TStore_Price; // 4 - 12
PriceClose : TStore_Price; // 4 - 16
end;
PStore_PriceSmall = ^TStore_PriceSmall;
TStore_PriceSmall = record
Value : Word;
end;
PStore_PriceFull = ^TStore_PriceFull;
TStore_PriceFull = record
Value : double;
end;
PStore_Weight = ^TStore_Weight;
TStore_Weight = record
Value : Cardinal;
end;
PStore_WeightRecord = ^TStore_WeightRecord;
TStore_WeightRecord = packed record // 16
WeightValue : TStore_Weight; // 4
WeightValue2 : double; // 8
StartDate : Word; // 2
EndDate : Word; // 2
end;
function GetRTPricePackValue(AValue: double): LongWord; overload;
function GetRTPricePackValue(AValue: string): LongWord; overload;
procedure SetRTPricePack(ARTPrice: PRT_PricePack; AValue: double);
procedure StorePrice2RTPricePack(ARTPrice: PRT_PricePack; AStorePrice: PStore_Price);
procedure RTPricePack2StorePrice(AStorePrice: PStore_Price; ARTPrice: PRT_PricePack);
procedure StorePriceRange2RTPricePackRange(ARTPrice: PRT_PricePack_Range; AStorePrice: PStore_PriceRange);
procedure RTPricePackRange2StorePriceRange(AStorePrice: PStore_PriceRange; ARTPrice: PRT_PricePack_Range);
function tryGetInt64Value(AStringData: string): Int64;
procedure trySetRTPricePack(ARTPrice: PRT_PricePack; AStringData: string);
const
DefaultPriceFactor = 1000;
implementation
uses
Sysutils;
procedure trySetRTPricePack(ARTPrice: PRT_PricePack; AStringData: string);
begin
ARTPrice.Value := Trunc(StrToFloatDef(AStringData, 0.00) * DefaultPriceFactor);
end;
function tryGetInt64Value(AStringData: string): Int64;
var
tmpPos: integer;
begin
tmpPos := Sysutils.LastDelimiter('.', AStringData);
if tmpPos > 0 then
AStringData := Copy(AStringData, 1, tmpPos - 1);
Result := StrToInt64Def(AStringData, 0);
end;
function GetRTPricePackValue(AValue: double): LongWord;
var
tmpValue: double;
begin
tmpValue := AValue * DefaultPriceFactor;
Result := Trunc(tmpValue);
end;
function GetRTPricePackValue(AValue: string): LongWord;
begin
Result := GetRTPricePackValue(StrToFloatDef(AValue, 0.00));
end;
procedure SetRTPricePack(ARTPrice: PRT_PricePack; AValue: double);
begin
ARTPrice.Value := GetRTPricePackValue(AValue);
end;
procedure StorePrice2RTPricePack(ARTPrice: PRT_PricePack; AStorePrice: PStore_Price);
begin
ARTPrice.Value := AStorePrice.Value;
end;
procedure RTPricePack2StorePrice(AStorePrice: PStore_Price; ARTPrice: PRT_PricePack);
begin
AStorePrice.Value := ARTPrice.Value;
end;
procedure StorePriceRange2RTPricePackRange(ARTPrice: PRT_PricePack_Range; AStorePrice: PStore_PriceRange);
begin
StorePrice2RTPricePack(@ARTPrice.PriceClose, @AStorePrice.PriceClose);
StorePrice2RTPricePack(@ARTPrice.PriceHigh, @AStorePrice.PriceHigh);
StorePrice2RTPricePack(@ARTPrice.PriceLow, @AStorePrice.PriceLow);
StorePrice2RTPricePack(@ARTPrice.PriceOpen, @AStorePrice.PriceOpen);
end;
procedure RTPricePackRange2StorePriceRange(AStorePrice: PStore_PriceRange; ARTPrice: PRT_PricePack_Range);
begin
RTPricePack2StorePrice(@AStorePrice.PriceClose, @ARTPrice.PriceClose);
RTPricePack2StorePrice(@AStorePrice.PriceHigh, @ARTPrice.PriceHigh);
RTPricePack2StorePrice(@AStorePrice.PriceLow, @ARTPrice.PriceLow);
RTPricePack2StorePrice(@AStorePrice.PriceOpen, @ARTPrice.PriceOpen);
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Arno Garrels <arno.garrels@gmx.de>
Description: TIcsThreadTimer implements a custom timer class. In doesn't
use windows API timers but sends custom timer messages to an
already existing ICS-window from one or more threads.
It uses resources (handles) very sparingly so 10K timers
are virtually possible, see OverbyteIcsThreadTimerDemo.
Creation: Jul 24, 2009
Version: 1.01
EMail: http://www.overbyte.be francois.piette@overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2009 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to Francois PIETTE. Use a nice stamp and mention your name,
street address, EMail address and any comment you like to say.
History:
07 Sept, 2010 V1.01 Added boolean property TIcsThreadTimer.KeepThreadAlive.
If it's set prevents the underlying, shared thread object from
being freed when its reference count becomes 0. This fixes
a serious performance leak when just a single TIcsThreadTimer
instance was used which was enabled/unabled or its interval
or event handler were changed frequently. Best performance
is achieved by setting this property to TRUE.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsThreadTimer;
interface
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$H+} { Use long strings }
{$I OverbyteIcsDefs.inc}
{$IFDEF COMPILER14_UP}
{$IFDEF NO_EXTENDED_RTTI}
{$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])}
{$ENDIF}
{$ENDIF}
{$IFDEF BCB}
{$ObjExportAll On}
{$ENDIF}
uses
Windows, Messages, SysUtils, Classes,
{$IFDEF Compiler17_UP}
System.Types,
{$ENDIF}
OverbyteIcsWndControl;
type
TIcsClock = class;
TIcsClockThread = class(TThread)
private
FClock : TIcsClock;
FWakeUpEvent : THandle;
FInterval : LongWord;
protected
procedure Execute; override;
public
procedure SetInterval(const Value: LongWord);
constructor Create(AClock: TIcsClock);
destructor Destroy; override;
end;
TIcsThreadTimer = class(TIcsTimer)
private
FMsgQueued : Boolean;
FQueuedTicks : Cardinal;
FClock : TIcsClock;
FCurHandle : HWND;
function GetKeepThreadAlive: Boolean;
procedure SetKeepThreadAlive(const Value: Boolean);
protected
procedure UpdateTimer; override;
procedure WMTimer(var msg: TMessage); override;
public
property KeepThreadAlive: Boolean read GetKeepThreadAlive
write SetKeepThreadAlive;
constructor Create(AOwner: TIcsWndControl);
destructor Destroy; override;
end;
TIcsClockPool = class;
TIcsClock = class(TObject)
private
FThread : TIcsClockThread;
FClockPool : TIcsClockPool;
FTimerList : TThreadList;
FCritSecClock : TRtlCriticalSection;
FKeepThreadAlive : Boolean;
public
constructor Create(AOwner: TIcsClockPool);
destructor Destroy; override;
procedure MessageProcessed(TimerObj: TIcsThreadTimer);
procedure SetTimer(TimerObj: TIcsThreadTimer);
procedure KillTimer(TimerObj: TIcsThreadTimer);
end;
TIcsClockRec = record
Clock : TIcsClock;
RefCount : Integer;
end;
PIcsClockRec = ^TIcsClockRec;
TIcsClockPool = class(TObject)
private
FClockList : TList;
FMaxTimerPerClock : Integer;
FMinTimerRes : Longword;
function InternalAcquire: TIcsClock;
procedure InternalRelease(AClock: TIcsClock);
public
class function Acquire: TIcsClock;
class procedure Release(AClock: TIcsClock);
constructor Create;
destructor Destroy; override;
end;
var
WM_ICS_THREAD_TIMER : Cardinal;
{ It's possible to fine tune timer behaviour by two global vars as long as }
{ no instance of TIcsThreadTimer is allocated. }
{ GMaxIcsTimerPerThread // Maximum timers per TIcsClock instance }
{ GMinIcsTimerResolution // Ticks / Msec interval of TIcsClock }
GMaxIcsTimerPerThread : Integer = 1000;
GMinIcsTimerResolution : Longword = 100;
implementation
uses
OverbyteIcsUtils;
const
ERROR_INVALID_WINDOW_HANDLE = DWORD(1400);
var
GIcsClockPool : TIcsClockPool;
GCritSecClockPool : TRtlCriticalSection;
GTimerID : Integer;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TIcsClockThread }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TIcsClockThread.Create(AClock: TIcsClock);
begin
inherited Create(FALSE);
FClock := AClock;
FInterval := FClock.FClockPool.FMinTimerRes;
FWakeUpEvent := CreateEvent(nil, False, False, nil);
if FWakeUpEvent = 0 then
raise EIcsTimerException.Create(SysErrorMessage(GetLastError));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TIcsClockThread.Destroy;
begin
Terminate;
if FWakeUpEvent <> 0 then
SetEvent(FWakeUpEvent);
inherited Destroy;
if FWakeUpEvent <> 0 then begin
CloseHandle(FWakeUpEvent);
FWakeUpEvent := 0;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsClockThread.Execute;
var
L : TList;
I : Integer;
CurTick : Longword;
wRes : Longword;
CurTimer : TIcsThreadTimer;
begin
{$IFDEF Debug}
IcsNameThreadForDebugging('TIcsClockThread');
{$ENDIF}
try
while not Terminated do begin
wRes := WaitForSingleObject(FWakeUpEvent, FInterval);
case wRes of
WAIT_TIMEOUT :
begin
CurTick := GetTickCount;
L := FClock.FTimerList.LockList;
try
for I := 0 to L.Count - 1 do begin
if Terminated then Exit;
CurTimer := TIcsThreadTimer(L[I]);
if CurTimer.FCurHandle = INVALID_HANDLE_VALUE then
Continue
else if CurTimer.FMsgQueued then
CurTimer.FQueuedTicks := CurTick
else if (IcsCalcTickDiff(CurTimer.FQueuedTicks,
CurTick) >= CurTimer.Interval) then begin
if PostMessage(CurTimer.FCurHandle,
WM_ICS_THREAD_TIMER,
WPARAM(CurTimer),
LPARAM(CurTimer.FUID)) then begin
CurTimer.FQueuedTicks := CurTick;
CurTimer.FMsgQueued := TRUE;
end
else if GetLastError = ERROR_INVALID_WINDOW_HANDLE then
CurTimer.FCurHandle := INVALID_HANDLE_VALUE;
end;
end;
finally
FClock.FTimerList.UnlockList;
end;
//raise EIcsTimerException.Create('Test');
end;
WAIT_FAILED : raise EIcsTimerException.Create(
SysErrorMessage(GetLastError));
WAIT_OBJECT_0 : if Terminated then
Break;
end;
end;
finally
if not Terminated then
Terminate;
FClock.FTimerList.Clear;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsClockThread.SetInterval(const Value: LongWord);
begin
if Value < FClock.FClockPool.FMinTimerRes then
FInterval := FClock.FClockPool.FMinTimerRes
else
FInterval := Value;
SetEvent(FWakeUpEvent);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TIcsClock }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TIcsClock.Create(AOwner: TIcsClockPool);
begin
inherited Create;
FClockPool := AOwner;
FTimerList := TThreadList.Create;
InitializeCriticalSection(FCritSecClock);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TIcsClock.Destroy;
begin
FreeAndNil(FThread);
FreeAndNil(FTimerList);
DeleteCriticalSection(FCritSecClock);
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsClock.KillTimer(TimerObj: TIcsThreadTimer);
var
L : TList;
Flag : Boolean;
begin
EnterCriticalSection(FCritSecClock);
try
L := FTimerList.LockList;
try
L.Remove(TimerObj);
{ Don't free the thread here - prevent deadlock. }
{ Instead free it in outer critical section below. }
Flag := L.Count = 0;
finally
FTimerList.UnlockList;
end;
{ if Flag then
FreeAndNil(FThread); }
if Flag then
begin
if FKeepThreadAlive and (FThread <> nil) then
FThread.SetInterval(INFINITE)
else
FreeAndNil(FThread);
end;
finally
LeaveCriticalSection(FCritSecClock);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsClock.SetTimer(TimerObj: TIcsThreadTimer);
var
L : TList;
begin
EnterCriticalSection(FCritSecClock);
try
if Assigned(FThread) and FThread.Terminated then
{ Thread terminated due to an exception in Execute, should never happen }
FreeAndNil(FThread);
L := FTimerList.LockList;
try
if L.IndexOf(TimerObj) >= 0 then
raise EIcsTimerException.Create('Timer already exists');
if not Assigned(FThread) then
FThread := TIcsClockThread.Create(Self);
TimerObj.FQueuedTicks := GetTickCount;
TimerObj.FMsgQueued := FALSE;
TimerObj.FCurHandle := TimerObj.FIcsWndControl.Handle;
L.Add(TimerObj);
if FThread.FInterval = INFINITE then
FThread.SetInterval(FClockPool.FMinTimerRes);
finally
FTimerList.UnlockList;
end;
finally
LeaveCriticalSection(FCritSecClock);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsClock.MessageProcessed(TimerObj: TIcsThreadTimer);
begin
FTimerList.LockList;
try
TimerObj.FMsgQueued := FALSE;
TimerObj.FQueuedTicks := GetTickCount;
finally
FTimerList.UnlockList;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TIcsClockPool }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class function TIcsClockPool.Acquire: TIcsClock;
begin
EnterCriticalSection(GCritSecClockPool);
try
if not Assigned(GIcsClockPool) then
GIcsClockPool := Create;
Result := GIcsClockPool.InternalAcquire;
finally
LeaveCriticalSection(GCritSecClockPool);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class procedure TIcsClockPool.Release(AClock: TIcsClock);
begin
EnterCriticalSection(GCritSecClockPool);
try
if Assigned(GIcsClockPool) then begin
GIcsClockPool.InternalRelease(AClock);
if GIcsClockPool.FClockList.Count = 0 then
FreeAndNil(GIcsClockPool);
end;
finally
LeaveCriticalSection(GCritSecClockPool);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TIcsClockPool.Create;
begin
inherited Create;
FClockList := TList.Create;
FMaxTimerPerClock := GMaxIcsTimerPerThread;
FMinTimerRes := GMinIcsTimerResolution;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TIcsClockPool.Destroy;
var
I : Integer;
begin
EnterCriticalSection(GCritSecClockPool);
try
for I := 0 to FClockList.Count -1 do begin
FreeAndNil(PIcsClockRec(FClockList[I])^.Clock);
Dispose(PIcsClockRec(FClockList[I]));
end;
FreeAndNil(FClockList);
finally
LeaveCriticalSection(GCritSecClockPool);
end;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsClockPool.InternalAcquire: TIcsClock;
var
I : Integer;
P : PIcsClockRec;
begin
for I := 0 to FClockList.Count -1 do begin
if PIcsClockRec(FClockList[I])^.RefCount < FMaxTimerPerClock then begin
Result := PIcsClockRec(FClockList[I])^.Clock;
Inc(PIcsClockRec(FClockList[I])^.RefCount);
Exit;
end;
end;
New(P);
P^.Clock := TIcsClock.Create(Self);
P^.RefCount := 1;
FClockList.Add(P);
Result := P^.Clock;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsClockPool.InternalRelease(AClock: TIcsClock);
var
I : Integer;
P : PIcsClockRec;
begin
for I := 0 to FClockList.Count -1 do begin
P := PIcsClockRec(FClockList[I]);
if P^.Clock = AClock then begin
if P^.Clock.FKeepThreadAlive then begin
if (P^.RefCount > 1) then
Dec(P^.RefCount);
end
else
Dec(P^.RefCount);
if P^.RefCount = 0 then begin
FreeAndNil(P^.Clock);
Dispose(P);
FClockList.Delete(I);
end;
Exit;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TIcsThreadTimer }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TIcsThreadTimer.Create(AOwner: TIcsWndControl);
begin
inherited Create(AOwner);
FUID := InterlockedIncrement(GTimerID);
FClock := TIcsClockPool.Acquire;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TIcsThreadTimer.Destroy;
begin
{ Ensure the timer is disabled before the UID will be reset in inherited!! }
FEnabled := FALSE;
UpdateTimer;
inherited Destroy;
TIcsClockPool.Release(FClock);
FClock := nil;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsThreadTimer.GetKeepThreadAlive: Boolean;
begin
Result := FClock.FKeepThreadAlive;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsThreadTimer.SetKeepThreadAlive(const Value: Boolean);
begin
FClock.FKeepThreadAlive := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsThreadTimer.WMTimer(var msg: TMessage);
begin
try
if FEnabled and Assigned(FOnTimer) then
FOnTimer(Self);
finally
FClock.MessageProcessed(Self);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsThreadTimer.UpdateTimer;
begin
FClock.KillTimer(Self);
if FEnabled and (FInterval > 0) and Assigned(FOnTimer) then
try
FClock.SetTimer(Self);
except
FEnabled := FALSE;
raise;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
initialization
InitializeCriticalSection(GCritSecClockPool);
WM_ICS_THREAD_TIMER := RegisterWindowMessage('OVERBYTE_ICS_THREAD_TIMER');
if WM_ICS_THREAD_TIMER = 0 then
raise EIcsTimerException.Create(SysErrorMessage(GetLastError));
finalization
FreeAndNil(GIcsClockPool);
DeleteCriticalSection(GCritSecClockPool);
end.
|
(*-------------------------------------------------------------*)
(* Neuhold Michael *)
(* Some initial tests with numbers. *)
(*-------------------------------------------------------------*)
PROGRAM TestNumbers;
CONST
lower = 1;
upper = 5;
FUNCTION CheckIndex(i: INTEGER): BOOLEAN;
BEGIN
CheckIndex := (i <= upper) AND (i >= lower);
END;
VAR
i, i2: INTEGER;
r, r2: REAL;
a: ARRAY[lower..upper] OF INTEGER;
BEGIN
i := 10;
i2 := i;
i := (3 + 7) * (5 - 8) * 3;
WriteLn('i: ', i);
(* TypeCast = TypeIdentifier "("Expr")" . *)
r := 2.5;
{i2 := INTEGER(r) + i;
r2 := r + REAL(i);}
r2 := r + i; (* implicit typecast *)
WriteLn('r2: ',r2);
a[1] := 4;
a[2] := 2;
a[3] := 1;
a[4] := 3;
a[5] := 3;
i:= 6;
(*$B+*)
IF CheckIndex(i) THEN BEGIN
IF a[i] = 3 THEN
WriteLn('OK');
END
ELSE
WriteLn('not OK');
(*$B-*)
(* Mit Kurzschluss Auswertung *)
IF CheckIndex(i) AND (a[i] = 3) THEN BEGIN
WriteLn('OK')
END
ELSE
WriteLn('not OK');
END. |
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
{ Rev 1.4 2004.02.03 5:45:12 PM czhower
{ Name changes
}
{
{ Rev 1.3 1/21/2004 4:03:16 PM JPMugaas
{ InitComponent
}
{
Rev 1.2 10/19/2003 5:57:18 PM DSiders
Added localization comments.
}
{
{ Rev 1.1 5/10/2003 10:10:44 PM JPMugaas
{ Bug fixes.
}
{
{ Rev 1.0 12/16/2002 03:27:22 AM JPMugaas
{ Initial version of IdSASLOTP. This is the OTP (One-Time-only password) SASL
{ mechanism.
}
{This is based on RFC2444}
unit IdSASLOTP;
interface
uses
IdException,
IdSASL,
IdSASLUserPass;
type
TIdSASLOTP = class(TIdSASLUserPass)
protected
function GenerateOTP(const AResponse:string; const APassword:string):string;
procedure InitComponent; override;
public
class function ServiceName: TIdSASLServiceName; override;
function StartAuthenticate(const AChallenge:string) : String; override;
function ContinueAuthenticate(const ALastResponse: String): String;
override;
end;
EIdOTPSASLException = class(EIdException);
EIdOTPSASLUnknownOTPMethodException = class(EIdOTPSASLException);
implementation
uses
IdBaseComponent, IdGlobal, IdOTPCalculator, IdSys, IdUserPassProvider;
{ TIdSASLOTP }
function TIdSASLOTP.ContinueAuthenticate(
const ALastResponse: String): String;
begin
Result := GenerateOTP(ALastResponse, GetPassword);
end;
procedure TIdSASLOTP.InitComponent;
begin
inherited;
FSecurityLevel := 1000;
end;
class function TIdSASLOTP.ServiceName: TIdSASLServiceName;
begin
Result := 'OTP'; {Do not translate}
end;
function TIdSASLOTP.StartAuthenticate(const AChallenge: string): String;
begin
Result := GetUsername;
end;
function TIdSASLOTP.GenerateOTP(const AResponse:string; const APassword:string):string;
var LChallenge:string;
LChallengeStartPos:integer;
LMethod:string;
LSeed:string;
LCount:integer;
begin
LChallengeStartPos:=pos('otp-', AResponse); {do not localize}
if LChallengeStartPos>0 then begin
inc(LChallengeStartPos, 4); // to remove "otp-"
LChallenge:=copy(AResponse, LChallengeStartPos, $FFFF);
LMethod:=Fetch(LChallenge);
LCount:=Sys.StrToInt(Fetch(LChallenge));
LSeed:=Fetch(LChallenge);
if LMethod='md5' then {do not localize} // methods are case sensitive
begin
Result := 'word:' + TIdOTPCalculator.ToSixWordFormat(TIdOTPCalculator.GenerateKeyMD5(lseed, APassword, LCount)) {do not localize}
end
else
begin
if LMethod = 'md4' then {do not localize}
begin
Result := 'word:' + TIdOTPCalculator.ToSixWordFormat(TIdOTPCalculator.GenerateKeyMD4(lseed, APassword, LCount)) {do not localize}
end
else
begin
if LMethod = 'sha1' then {do not localize}
begin
Result := 'word:' + TIdOTPCalculator.ToSixWordFormat(TIdOTPCalculator.GenerateKeySHA1(lseed, APassword, LCount)) {do not localize}
end
else
begin
raise EIdOTPSASLUnknownOTPMethodException.Create('Unknown OTP method'); //rs {do not localize}
end;
end;
end;
end;
end;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Layout options page
Copyright (C) 2006-2011 Koblov Alexander (Alexx2000@mail.ru)
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 fOptionsLayout;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StdCtrls,
fOptionsFrame;
type
{ TfrmOptionsLayout }
TfrmOptionsLayout = class(TOptionsEditor)
cbFlatDiskPanel: TCheckBox;
cbFlatInterface: TCheckBox;
cbFlatToolBar: TCheckBox;
cbFreespaceInd: TCheckBox;
cbLogWindow: TCheckBox;
cbPanelOfOperations: TCheckBox;
cbProgInMenuBar: TCheckBox;
cbShowCmdLine: TCheckBox;
cbShowCurDir: TCheckBox;
cbShowDiskPanel: TCheckBox;
cbShowDriveFreeSpace: TCheckBox;
cbShowDrivesListButton: TCheckBox;
cbShowKeysPanel: TCheckBox;
cbShowMainMenu: TCheckBox;
cbShowMainToolBar: TCheckBox;
cbShowStatusBar: TCheckBox;
cbShowTabHeader: TCheckBox;
cbShowTabs: TCheckBox;
cbTermWindow: TCheckBox;
cbTwoDiskPanels: TCheckBox;
cbShowShortDriveFreeSpace: TCheckBox;
gbScreenLayout: TGroupBox;
procedure cbShowDiskPanelChange(Sender: TObject);
procedure cbShowDriveFreeSpaceChange(Sender: TObject);
procedure cbShowMainToolBarChange(Sender: TObject);
protected
procedure Load; override;
function Save: TOptionsEditorSaveFlags; override;
public
class function GetIconIndex: Integer; override;
class function GetTitle: String; override;
end;
implementation
{$R *.lfm}
uses
uGlobs, uLng;
{ TfrmOptionsLayout }
procedure TfrmOptionsLayout.cbShowDiskPanelChange(Sender: TObject);
begin
cbTwoDiskPanels.Enabled := cbShowDiskPanel.Checked;
cbFlatDiskPanel.Enabled := cbShowDiskPanel.Checked;
end;
procedure TfrmOptionsLayout.cbShowDriveFreeSpaceChange(Sender: TObject);
begin
cbShowShortDriveFreeSpace.Enabled:= cbShowDriveFreeSpace.Checked;
if not(cbShowDriveFreeSpace.Checked) then cbShowShortDriveFreeSpace.Checked:= false;
end;
procedure TfrmOptionsLayout.cbShowMainToolBarChange(Sender: TObject);
begin
cbFlatToolBar.Enabled := cbShowMainToolBar.Checked;
end;
class function TfrmOptionsLayout.GetIconIndex: Integer;
begin
Result := 7;
end;
class function TfrmOptionsLayout.GetTitle: String;
begin
Result := rsOptionsEditorLayout;
end;
procedure TfrmOptionsLayout.Load;
begin
cbShowMainMenu.Checked := gMainMenu;
cbShowMainToolBar.Checked := gButtonBar;
cbFlatToolBar.Checked := gToolBarFlat;
cbShowDiskPanel.Checked := gDriveBar1;
cbTwoDiskPanels.Checked := gDriveBar2;
cbFlatDiskPanel.Checked := gDriveBarFlat;
cbShowDrivesListButton.Checked := gDrivesListButton;
cbShowTabs.Checked := gDirectoryTabs;
cbShowCurDir.Checked := gCurDir;
cbShowTabHeader.Checked := gTabHeader;
cbShowStatusBar.Checked := gStatusBar;
cbShowCmdLine.Checked := gCmdLine;
cbShowKeysPanel.Checked := gKeyButtons;
cbFlatInterface.Checked := gInterfaceFlat;
cbLogWindow.Checked := gLogWindow;
cbTermWindow.Checked := gTermWindow;
cbShowDriveFreeSpace.Checked := gDriveFreeSpace;
cbFreespaceInd.Checked := gDriveInd;
cbProgInMenuBar.Checked := gProgInMenuBar;
cbPanelOfOperations.Checked := gPanelOfOp;
cbShowShortDriveFreeSpace.Checked:= gShortFormatDriveInfo;
end;
function TfrmOptionsLayout.Save: TOptionsEditorSaveFlags;
begin
Result := [];
gMainMenu := cbShowMainMenu.Checked;
gButtonBar := cbShowMainToolBar.Checked;
gToolBarFlat := cbFlatToolBar.Checked;
gDriveBar1 := cbShowDiskPanel.Checked;
gDriveBar2 := cbTwoDiskPanels.Checked;
gDriveBarFlat := cbFlatDiskPanel.Checked;
gDrivesListButton := cbShowDrivesListButton.Checked;
gDirectoryTabs := cbShowTabs.Checked;
gCurDir := cbShowCurDir.Checked;
gTabHeader := cbShowTabHeader.Checked;
gStatusBar := cbShowStatusBar.Checked;
gCmdLine := cbShowCmdLine.Checked;
gKeyButtons := cbShowKeysPanel.Checked;
gInterfaceFlat := cbFlatInterface.Checked;
gLogWindow := cbLogWindow.Checked;
gTermWindow := cbTermWindow.Checked;
gDriveFreeSpace := cbShowDriveFreeSpace.Checked;
gDriveInd := cbFreespaceInd.Checked;
gProgInMenuBar := cbProgInMenuBar.Checked;
gPanelOfOp := cbPanelOfOperations.Checked;
gShortFormatDriveInfo := cbShowShortDriveFreeSpace.Checked;
end;
end.
|
Unit wz_misc;
{$mode objfpc}{$H+}
{$DEFINE DEBUG_OFF}
Interface
Uses
classes, sysutils, dialogs, Forms,
// For opening ini files
INIFiles,
// For decompression routine
Zipper,
// For windows registry access
Registry;
type
TWZConfig = record
// integers
ColorDepth, // Options: 0 - 16bit, 1 - 32bit
Resolution, // Options: 0 - 640 x 480 / 1 - 800 x 600 / 2 - 1024 x 768 / 3 - 1280 x 1024
SoundEffect, // Options: 0 - off, 1 - on
Music, // Options: 0 - off, 1 - on
WindowMode // Options: 0 - off, 1 - on
: integer;
// strings
Username, // Account ID of player
Language, // Default language
MuExe // Mu.exe executable path
: string;
end;
const
wzkey = '\Software\Webzen\Mu\Config';
default_path = 'data\launcher\';
wz_settings_ini = 'settings.ini';
wz_update_server = 'http://updates.warzonemu.com/?id=';
wzexe = 'Main.exe';
var
config : TWZConfig;
procedure CreateDefaultMuRegEntry();
function PatchClient(const fn : string; const debug : boolean): Boolean;
function PatchClient(const fnpath, fn : string; const debug : boolean): Boolean;
function SetRegKey(const cfg: string; const value: string): Boolean;
function SetRegKey(const cfg: string; const value: integer): Boolean;
function GetRegKeyStr(const skey : string): String;
function GetRegKeyInt(const skey : string): Integer;
function GetIni(const fn, section, key : string; const default : Boolean) : Boolean;
function GetIni(const fn, section, key : string; const default : integer) : Integer;
function GetIni(const fn, section, key, default : string) : String;
procedure SetIni(const fn, section, key : string; const value : integer);
procedure SetIni(const fn, section, key, value : string);
procedure SetIni(const fn, section, key : string; const value : boolean);
function GetSkinInfo(const section, key : string; const default : integer) : Integer;
function GetSkinInfo(const section, key : string; const default : boolean) : Boolean;
function GetSkinInfo(const section, key, default : string) : String;
function GetImagePath(const section, key, default : string) : String;
function GetSkinPos(const section, key : string; const default : integer) : integer;
function GetSkinPath : string;
function GetSkinINI : string;
function GetConfig(const section, key, default : string) : string;
function GetConfig(const section, key : string; const default : integer) : integer;
function GetConfig(const section, key : string; const default : boolean) : boolean;
procedure SetConfig(const section, key : string; const value : boolean);
procedure SetConfig(const section, key : string; const value : integer);
procedure SetConfig(const section, key, value : string);
function FormatByteSize(const bytes: Longword): string;
Implementation
function FormatByteSize(const bytes: Longword): string;
var
B: byte;
KB: word;
MB: Longword;
GB: Longword;
TB: UInt64;
begin
B := 1; //byte
KB := 1024 * B; //kilobyte
MB := 1000 * KB; //megabyte
GB := 1000 * MB; //gigabyte
///TB := 1000 * GB; //terabyte
//if bytes > TB then
// result := FormatFloat('#.## TB', bytes / TB)
// else
if bytes > GB then
result := FormatFloat('#.## GB', bytes / GB)
else
if bytes > MB then
result := FormatFloat('#.## MB', bytes / MB)
else
if bytes > KB then
result := FormatFloat('#.## KB', bytes / KB)
else
result := FormatFloat('#.## bytes', bytes) ;
end;
function GetConfig(const section, key, default : string) : string;
begin
result := GetIni(default_path + '\' + wz_settings_ini, section, key, default);
End;
function GetConfig(const section, key : string; const default : integer) : integer;
begin
result := GetIni(default_path + '\' + wz_settings_ini, section, key, default);
End;
function GetConfig(const section, key : string; const default : boolean) : boolean;
begin
result := GetIni(default_path + '\' + wz_settings_ini, section, key, default);
End;
procedure SetConfig(const section, key, value : string);
begin
SetIni(default_path + '\' + wz_settings_ini, section, key, value);
End;
procedure SetConfig(const section, key : string; const value : integer);
begin
SetIni(default_path + '\' + wz_settings_ini, section, key, value);
End;
procedure SetConfig(const section, key : string; const value : boolean);
begin
SetIni(default_path + '\' + wz_settings_ini, section, key, value);
End;
function GetIni(const fn, section, key : string; const default : Boolean) : Boolean;
begin
with TINIFile.Create(fn) do begin
result := ReadBool(section, key, default);
End;
End;
function GetIni(const fn, section, key : string; const default : integer) : Integer;
begin
with TINIFile.Create(fn) do begin
result := ReadInteger(section, key, default);
End;
End;
function GetIni(const fn, section, key, default : string) : String;
begin
with TINIFile.Create(fn) do begin
result := ReadString(section, key, default);
End;
End;
procedure SetIni(const fn, section, key : string; const value : boolean);
begin
with TINIFile.Create(fn) do begin
WriteBool(section, key, value);
Free;
End;
End;
procedure SetIni(const fn, section, key : string; const value : integer);
begin
with TINIFile.Create(fn) do begin
WriteInteger(section, key, value);
Free;
End;
End;
procedure SetIni(const fn, section, key, value : string);
begin
with TINIFile.Create(fn) do begin
WriteString(section, key, value);
Free;
End;
End;
function GetSkinInfo(const section, key : string; const default : boolean) : Boolean;
begin
result := GetIni(GetSkinINI, section, key, default);
{$ifdef DEBUG_ON}showmessage('GetSkinInfo('+section+','+key+','+booltostr(default)+') => ' + booltostr(result));{$ENDIF}
End;
function GetSkinInfo(const section, key : string; const default : integer) : Integer;
begin
result := GetIni(GetSkinINI, section, key, default);
{$ifdef DEBUG_ON}showmessage('GetSkinInfo('+section+','+key+','+inttostr(default)+') => ' + inttostr(result));{$ENDIF}
End;
function GetSkinInfo(const section, key, default : string) : String;
begin
result := GetIni(GetSkinINI, section, key, default);
{$ifdef DEBUG_ON}showmessage('GetSkinInfo('+section+','+key+','+default+') => ' + result);{$ENDIF}
End;
function GetImagePath(const section, key, default : string) : String;
begin
result := GetSkinPath + GetIni(GetSkinINI, section, key, default);
{$ifdef DEBUG_ON}showmessage('GetImagePath('+section+','+key+','+default+') => ' + result);{$ENDIF}
End;
function GetSkinPos(const section, key : string; const default : integer) : integer;
begin
result := GetSkinInfo(section, key, default);
{$ifdef DEBUG_ON}showmessage('GetSkinPos('+section+','+key+','+inttostr(default)+') => ' + inttostr(result));{$ENDIF}
End;
function GetSkinPath : string;
begin
result := default_path + '\' + GetIni(default_path + '\' + wz_settings_ini, 'GENERAL', 'skinpath', 'skins') + '\';
result := result + GetIni(default_path + '\' + wz_settings_ini, 'GENERAL', 'defaultskin', 'default') + '\';
{$ifdef DEBUG_ON}showmessage('GetSkinPath => ' + result);{$ENDIF}
End;
function GetSkinINI : string;
begin
result := default_path + '\' + GetIni(default_path + '\' + wz_settings_ini, 'GENERAL', 'skinpath', 'skins') + '\';
result := result + GetIni(default_path + '\' + wz_settings_ini, 'GENERAL', 'defaultskin', 'default') + '\';
result := result + wz_settings_ini;
{$ifdef DEBUG_ON}showmessage('GetSkinINI => ' + result);{$ENDIF}
End;
{-----------------------------------
Client Updater (decompress files)
------------------------------------}
function PatchClient(const fn : string; const debug : boolean): Boolean;
begin
result := PatchClient('', fn, debug);
End;
function PatchClient(const fnpath, fn : string; const debug : boolean): Boolean;
var
actualpath : string;
begin
if debug then
actualpath := application.Location + '\debug\'
else
actualpath := fnpath;
with TUnZipper.Create do
try
FileName := fn;
OutputPath := actualpath;
Examine;
UnZipAllFiles;
result := true;
Free;
Except
result := false;
Free;
end;
end;
{-----------------------------------
Save registry entries
------------------------------------}
// Save string value
function SetRegKey(const cfg: string; const value: string): Boolean;
begin
with TRegistry.Create do
try
RootKey := HKEY_CURRENT_USER;
if not OpenKey(wzkey, true) then CreateKey(wzkey);
WriteString(cfg, value);
result := true;
free;
except
result := false;
free;
end;
end;
// Save Integer value
function SetRegKey(const cfg: string; const value: integer): Boolean;
begin
with TRegistry.Create do
try
RootKey := HKEY_CURRENT_USER;
if not OpenKey(wzkey, true) then CreateKey(wzkey);
WriteInteger( cfg, value);
result := true;
free;
except
result := false;
free;
end;
end;
{-----------------------------------
Get registry entries
------------------------------------}
function GetRegKeyStr(const skey : string) : String;
begin
with TRegistry.Create do
try
RootKey := HKEY_CURRENT_USER;
OpenKey(wzkey, true);
result := ReadString(skey);
Free;
except
result := '';
Free;
end;
end;
function GetRegKeyInt(const skey : string) : Integer;
begin
with TRegistry.Create do
try
RootKey := HKEY_CURRENT_USER;
OpenKey(wzkey, true);
result := ReadInteger(skey);
Free;
except
result := 0;
Free;
end;
end;
procedure CreateDefaultMuRegEntry();
begin
// default settings
config.Resolution := 1; // 800x600
config.ColorDepth := 1; // 32bit
config.SoundEffect := 1; // On
config.Music := 1; // On
config.WindowMode := 1; // Window mode
config.Username := '';
config.Language := 'ENG';
with TRegistry.Create do begin
RootKey := HKEY_CURRENT_USER;
if not OpenKey(wzkey, true) then begin
// no configuration exists, set default settings
SetRegKey('Resolution', config.Resolution);
SetRegKey('ColorDepth', config.ColorDepth);
SetRegKey('SoundOnOff', config.SoundEffect);
SetRegKey('MusicOnOff', config.Music);
SetRegKey('WindowMode', config.WindowMode);
SetRegKey('ID', config.Username);
SetRegKey('Lang', config.Language);
end else begin
if not ValueExists('Resolution') then SetRegKey('Resolution', config.Resolution);
if not ValueExists('ColorDepth') then SetRegKey('ColorDepth', config.ColorDepth);
if not ValueExists('SoundOnOff') then SetRegKey('SoundOnOff', config.SoundEffect);
if not ValueExists('MusicOnOff') then SetRegKey('MusicOnOff', config.Music);
if not ValueExists('WindowMode') then SetRegKey('WindowMode', config.WindowMode);
if not ValueExists('ID') then SetRegKey('ID', config.Username);
if not ValueExists('Lang') then SetRegKey('Lang', config.Language);
End;
End;
End;
End.
|
{********************************************************************}
{ TTileBMP component }
{ for Delphi & C++Builder }
{ }
{ written by TMS Software }
{ copyright © 1998-2012 }
{ Email: info@tmssoftware.com }
{ Web: http://www.tmssoftware.com }
{ }
{ The source code is given as is. The author is not responsible }
{ for any possible damage done due to the use of this code. }
{ The component can be freely used in any application. The source }
{ code remains property of the author and may not be distributed }
{ freely as such. }
{********************************************************************}
unit Tilebmp;
{$I TMSDEFS.INC}
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, StdCtrls, ExtCtrls
{$IFDEF DELPHI6_LVL}
, Types
{$ENDIF}
;
const
DefaultWidth = 32;
DefaultHeight = 32;
MAJ_VER = 1; // Major version nr.
MIN_VER = 1; // Minor version nr.
REL_VER = 0; // Release nr.
BLD_VER = 0; // Build nr.
// version history
// v1.0.0.0 : First release
type
{$IFDEF DELPHIXE2_LVL}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TTileBmp = class(TGraphicControl)
private
FBmpWidth : Integer;
FBmpHeight : Integer;
FBitMap : TBitmap;
procedure SetBitMap(Value : TBitMap);
procedure WMSize(var Message: TWMSize); message WM_PAINT;
function GetVersion: string;
procedure SetVersion(const Value: string);
protected
function GetVersionNr: Integer; virtual;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property BitMap : TBitMap read FBitMap write SetBitMap;
property Height default 30;
property Width default 30;
property ShowHint;
property OnClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property Visible;
property Version: string read GetVersion write SetVersion;
end;
procedure Register;
implementation
constructor TtileBmp.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := DefaultWidth;
Height := DefaultHeight;
FBmpWidth := DefaultWidth;
FBmpHeight := DefaultHeight;
FBitMap := TBitMap.Create;
ControlStyle := ControlStyle +[csOpaque];
end;
destructor TtileBmp.Destroy;
begin
FBitMap.Free;
inherited Destroy;
end;
procedure TtileBmp.WMSize(var Message: TWMSize);
begin
inherited;
{No resizing allowed}
FBmpWidth :=FBmpWidth;
FBmpHeight:=FBmpHeight;
end;
procedure TtileBmp.SetBitMap(Value : TBitMap);
begin
FBitMap.Assign(Value);
FBmpHeight := FBitMap.Height;
FBmpWidth := FBitMap.Width;
{
Height := FBmpHeight;
Width := FBmpWidth;
}
if Height = 0 then
Height := DefaultHeight;
if Width = 0 then
Width := DefaultWidth;
self.repaint;
end;
procedure TtileBmp.Paint;
var
ARect, BRect : TRect;
x,y,xo,yo:word;
begin
ARect := Rect(0,0,Width,Height);
if (FBitMap.Height > 0) and (FBitmap.Width>0) then
begin
x:=FBitMap.Width;
y:=FBitmap.Height;
ARect := Rect(0,0,x,y);
Brect := Rect(0,0,x,y);
yo:=0;
while (yo<height) do
begin
xo:=0;
while (xo<width) do
begin
ARect := Rect(xo,yo,x+xo,y+yo);
Canvas.CopyRect(ARect,FBitmap.Canvas, BRect);
xo:=xo+FBitmap.Width;
end;
yo:=yo+FBitmap.Height;
end;
end
else
begin {fill it with white color}
Canvas.Brush.Color := clWhite;
Canvas.FillRect(BoundsRect);
end;
if csDesigning in ComponentState then
begin {To see the outline of the Bitmap at designing time}
Canvas.Pen.Style := psDash;
Canvas.Brush.Style := bsClear;
Canvas.Rectangle(0, 0, Width, Height);
end;
end;
function TTileBMP.GetVersion: 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 TTileBMP.GetVersionNr: Integer;
begin
Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER));
end;
procedure TTileBMP.SetVersion(const Value: string);
begin
end;
procedure Register;
begin
RegisterComponents('TMS', [TTileBmp]);
end;
end.
|
unit magmax_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,m68000,main_engine,controls_engine,gfx_engine,ay_8910,rom_engine,
pal_engine,sound_engine;
function iniciar_magmax:boolean;
implementation
const
magmax_rom:array[0..5] of tipo_roms=(
(n:'1.3b';l:$4000;p:1;crc:$33793cbb),(n:'6.3d';l:$4000;p:$0;crc:$677ef450),
(n:'2.5b';l:$4000;p:$8001;crc:$1a0c84df),(n:'7.5d';l:$4000;p:$8000;crc:$01c35e95),
(n:'3.6b';l:$2000;p:$10001;crc:$d06e6cae),(n:'8.6d';l:$2000;p:$10000;crc:$790a82be));
magmax_sound:array[0..1] of tipo_roms=(
(n:'15.17b';l:$2000;p:0;crc:$19e7b983),(n:'16.18b';l:$2000;p:$2000;crc:$055e3126));
magmax_char:tipo_roms=(n:'23.15g';l:$2000;p:0;crc:$a7471da2);
magmax_sprites:array[0..5] of tipo_roms=(
(n:'17.3e';l:$2000;p:0;crc:$8e305b2e),(n:'18.5e';l:$2000;p:$2000;crc:$14c55a60),
(n:'19.6e';l:$2000;p:$4000;crc:$fa4141d8),(n:'20.3g';l:$2000;p:$8000;crc:$6fa3918b),
(n:'21.5g';l:$2000;p:$a000;crc:$dd52eda4),(n:'22.6g';l:$2000;p:$c000;crc:$4afc98ff));
magmax_pal:array[0..5] of tipo_roms=(
(n:'mag_e.10f';l:$100;p:0;crc:$75e4f06a),(n:'mag_d.10e';l:$100;p:$100;crc:$34b6a6e3),
(n:'mag_a.10d';l:$100;p:$200;crc:$a7ea7718),(n:'mag_g.2e';l:$100;p:$300;crc:$830be358),
(n:'mag_b.14d';l:$100;p:$400;crc:$a0fb7297),(n:'mag_c.15d';l:$100;p:$500;crc:$d84a6f78));
magmax_fondo1:array[0..1] of tipo_roms=(
(n:'4.18b';l:$2000;p:0;crc:$1550942e),(n:'5.20b';l:$2000;p:$1;crc:$3b93017f));
magmax_fondo2:array[0..5] of tipo_roms=(
(n:'9.18d';l:$2000;p:$4000;crc:$9ecc9ab8),(n:'10.20d';l:$2000;p:$6000;crc:$e2ff7293),
(n:'11.15f';l:$2000;p:$8000;crc:$91f3edb6),(n:'12.17f';l:$2000;p:$a000;crc:$99771eff),
(n:'13.18f';l:$2000;p:$c000;crc:$75f30159),(n:'14.20f';l:$2000;p:$e000;crc:$96babcba));
magmax_dip:array [0..9] of def_dip=(
(mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'4'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'6'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$c;dip_name:'30K 80K 50K+'),(dip_val:$8;dip_name:'50K 120K 70K+'),(dip_val:$4;dip_name:'70K 160K 90K+'),(dip_val:$0;dip_name:'90K 200K 110K+'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$10;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$10;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$20;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$300;name:'Coin A';number:4;dip:((dip_val:$100;dip_name:'2C 1C'),(dip_val:$300;dip_name:'1C 1C'),(dip_val:$200;dip_name:'1C 2C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c00;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$400;dip_name:'2C 3C'),(dip_val:$c00;dip_name:'1C 3C'),(dip_val:$800;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$1000;name:'Difficulty';number:2;dip:((dip_val:$1000;dip_name:'Easy'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2000;name:'Flip Screen';number:2;dip:((dip_val:$2000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8000;name:'Debug Mode';number:2;dip:((dip_val:$8000;dip_name:'No'),(dip_val:$0;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
gain_control,vreg,scroll_x,scroll_y:word;
rom:array[0..$9fff] of word;
ram:array[0..$7ff] of word;
ram_video:array[0..$3ff] of word;
prom_mem,ram_sprites:array[0..$ff] of word;
LS74_q,LS74_clr,sound_latch:byte;
rom18B:array[0..$ffff] of byte;
redraw_bg:boolean;
procedure update_video_magmax;
procedure draw_background;
var
prom_data,pen_base,scroll_h,map_v_scr_100,rom18D_addr,rom15F_addr,map_v_scr_1fe_6,LS283:word;
scroll_v,f,h,graph_color,graph_data:byte;
pixel1,pixel2:array[0..$ff] of word;
begin
scroll_h:=scroll_x and $3fff;
scroll_v:=scroll_y;
for f:=16 to 239 do begin // only for visible area
fillword(@pixel1,$100,paleta[$100]);
fillword(@pixel2,$100,paleta[MAX_COLORES]);
map_v_scr_100:=(scroll_v+f) and $100;
rom18D_addr:=((scroll_v+f) and $f8)+(map_v_scr_100 shl 5);
rom15F_addr:=(((scroll_v+f) and $07) shl 2)+(map_v_scr_100 shl 5);
map_v_scr_1fe_6:=((scroll_v+f) and $1fe) shl 6;
pen_base:=$20+(map_v_scr_100 shr 1);
for h:=0 to $ff do begin
LS283:=scroll_h+h;
if (map_v_scr_100=0) then begin
if (h and $80)<>0 then LS283:=LS283+(rom18B[ map_v_scr_1fe_6+(h xor $ff)] xor $ff)
else LS283:=LS283+rom18B[map_v_scr_1fe_6+h]+$ff01;
end;
prom_data:=prom_mem[(LS283 shr 6) and $ff];
rom18D_addr:=rom18D_addr and $20f8;
rom18D_addr:=rom18D_addr+((prom_data and $1f00)+((LS283 and $38) shr 3));
rom15F_addr:=rom15F_addr and $201c;
rom15F_addr:=rom15F_addr+((rom18B[$4000+rom18D_addr] shl 5)+((LS283 and $6) shr 1));
rom15F_addr:=rom15F_addr+(prom_data and $4000);
graph_color:=prom_data and $70;
graph_data:=rom18B[$8000+rom15F_addr];
if ((LS283 and 1)<>0) then graph_data:=graph_data shr 4;
graph_data:=graph_data and $0f;
pixel1[h]:=paleta[pen_base+graph_color+graph_data];
// priority: background over sprites
if ((map_v_scr_100<>0) and ((graph_data and $0c)=$0c)) then pixel2[h]:=pixel1[h];
end;
putpixel(0,f,256,@pixel1,1);
putpixel(0,f,256,@pixel2,2);
end;
redraw_bg:=false;
end;
var
f,x,nchar:word;
color,y,atrib:byte;
begin
for f:=$0 to $3ff do begin
if gfx[1].buffer[f] then begin
x:=f mod 32;
y:=f div 32;
nchar:=ram_video[f] and $ff;
put_gfx_trans(x*8,y*8,nchar,0,3,0);
gfx[1].buffer[f]:=false;
end;
end;
if (vreg and $40)<>0 then fill_full_screen(4,$100)
else begin
if redraw_bg then draw_background;
actualiza_trozo(0,0,256,256,1,0,0,256,256,4);
end;
//sprites
for f:=0 to $3f do begin
y:=ram_sprites[f*4];
if y<>0 then begin
y:=239-y;
atrib:=ram_sprites[(f*4)+2];
nchar:=ram_sprites[(f*4)+1] and $ff;
if (nchar and $80)<>0 then nchar:=nchar+((vreg and $30)*8);
x:=(ram_sprites[(f*4)+3] and $ff)-$80+$100*(atrib and 1);
color:=atrib and $f0;
put_gfx_sprite_mask(nchar,color,(atrib and 4)<>0,(atrib and 8)<>0,1,$1f,$1f);
actualiza_gfx_sprite(x,y,4,1);
end;
end;
if (vreg and $40)=0 then actualiza_trozo(0,0,256,256,2,0,0,256,256,4);
actualiza_trozo(0,0,256,256,3,0,0,256,256,4);
actualiza_trozo_final(0,16,256,224,4);
end;
procedure eventos_magmax;
begin
if event.arcade then begin
//P1
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or 1);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or 2);
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or 4);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or 8);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $20);
//P2
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $fffe) else marcade.in2:=(marcade.in2 or 1);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fffd) else marcade.in2:=(marcade.in2 or 2);
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fffb) else marcade.in2:=(marcade.in2 or 4);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fff7) else marcade.in2:=(marcade.in2 or 8);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ffef) else marcade.in2:=(marcade.in2 or $10);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $ffdf) else marcade.in2:=(marcade.in2 or $20);
//SYSTEM
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fff7) else marcade.in0:=(marcade.in0 or $8);
end;
end;
procedure magmax_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
64,192:if (LS74_clr<>0) then LS74_q:=1;
239:begin
update_video_magmax;
m68000_0.irq[1]:=ASSERT_LINE;
end;
end;
end;
eventos_magmax;
video_sync;
end;
end;
function magmax_getword(direccion:dword):word;
begin
case direccion of
0..$13fff:magmax_getword:=rom[direccion shr 1];
$18000..$18fff:magmax_getword:=ram[(direccion and $fff) shr 1];
$20000..$207ff:magmax_getword:=ram_video[(direccion and $7ff) shr 1];
$28000..$281ff:magmax_getword:=ram_sprites[(direccion and $1ff) shr 1];
$30000:magmax_getword:=marcade.in1;
$30002:magmax_getword:=marcade.in2;
$30004:magmax_getword:=marcade.in0;
$30006:magmax_getword:=marcade.dswa;
end;
end;
procedure magmax_putword(direccion:dword;valor:word);
begin
case direccion of
0..$13fff:;
$18000..$18fff:ram[(direccion and $fff) shr 1]:=valor;
$20000..$207ff:if ram_video[(direccion and $7ff) shr 1]<>valor then begin
gfx[1].buffer[(direccion and $7ff) shr 1]:=true;
ram_video[(direccion and $7ff) shr 1]:=valor;
end;
$28000..$281ff:ram_sprites[(direccion and $1ff) shr 1]:=valor;
$30010:vreg:=valor;
$30012:if scroll_x<>valor then begin
redraw_bg:=true;
scroll_x:=valor;
end;
$30014:if scroll_y<>valor then begin
redraw_bg:=true;
scroll_y:=valor
end;
$3001c:begin
sound_latch:=valor;
z80_0.change_irq(ASSERT_LINE);
end;
$3001e:m68000_0.irq[1]:=CLEAR_LINE;
end;
end;
function magmax_snd_getbyte(direccion:word):byte;
begin
direccion:=direccion and $7fff;
case direccion of
0..$3fff:magmax_snd_getbyte:=mem_snd[direccion];
$4000..$5fff:z80_0.change_irq(CLEAR_LINE);
$6000..$7fff:magmax_snd_getbyte:=mem_snd[$6000+(direccion and $7ff)];
end;
end;
procedure magmax_snd_putbyte(direccion:word;valor:byte);
begin
direccion:=direccion and $7fff;
case direccion of
0..$3fff:;
$4000..$5fff:z80_0.change_irq(CLEAR_LINE);
$6000..$7fff:mem_snd[$6000+(direccion and $7ff)]:=valor;
end;
end;
function magmax_snd_inbyte(puerto:word):byte;
begin
case (puerto and $ff) of
0:magmax_snd_inbyte:=ay8910_0.Read;
2:magmax_snd_inbyte:=ay8910_1.Read;
4:magmax_snd_inbyte:=ay8910_2.Read;
6:magmax_snd_inbyte:=(sound_latch shl 1) or LS74_q;
end;
end;
procedure magmax_snd_outbyte(puerto:word;valor:byte);
begin
case (puerto and $ff) of
$0:ay8910_0.Control(valor);
$1:ay8910_0.Write(valor);
$2:ay8910_1.Control(valor);
$3:ay8910_1.Write(valor);
$4:ay8910_2.Control(valor);
$5:ay8910_2.Write(valor);
end;
end;
procedure magmax_sound_update;
begin
ay8910_0.Update;
ay8910_1.Update;
ay8910_2.Update;
end;
procedure magmax_porta_w(valor:byte);
var
gain_t1,gain_t2:single;
begin
if gain_control=(valor and $f) then exit;
gain_control:=valor and $f;
gain_t1:=0.5+0.5*(gain_control and 1);
gain_t2:=0.23+0.23*(gain_control and 1);
ay8910_0.change_gain(gain_t1,gain_t2,gain_t2);
gain_t1:=0.23+0.23*((gain_control and 4) shr 2);
ay8910_1.change_gain(gain_t2,gain_t2,gain_t1);
gain_t2:=0.23+0.23*((gain_control and 8) shr 3);
ay8910_2.change_gain(gain_t1,gain_t2,gain_t2);
end;
procedure magmax_portb_w(valor:byte);
begin
LS74_clr:=valor and 1;
if (LS74_clr=0) then LS74_q:=0;
end;
//Main
procedure reset_magmax;
begin
m68000_0.reset;
z80_0.reset;
ay8910_0.reset;
ay8910_1.reset;
ay8910_2.reset;
reset_audio;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
scroll_x:=0;
scroll_y:=0;
sound_latch:=0;
LS74_clr:=0;
LS74_q:=0;
gain_control:=0;
redraw_bg:=true;
end;
function iniciar_magmax:boolean;
var
colores:tpaleta;
f,v:byte;
memoria_temp:array[0..$ffff] of byte;
const
pc_x:array[0..7] of dword=(4, 0, 12, 8, 20, 16, 28, 24);
ps_x:array[0..15] of dword=(4, 0, 4+512*64*8, 0+512*64*8, 12, 8, 12+512*64*8, 8+512*64*8,
20, 16, 20+512*64*8, 16+512*64*8, 28, 24, 28+512*64*8, 24+512*64*8);
ps_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32,
8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32);
begin
llamadas_maquina.bucle_general:=magmax_principal;
llamadas_maquina.reset:=reset_magmax;
iniciar_magmax:=false;
iniciar_audio(false);
screen_init(1,256,256);
screen_init(2,256,256,true);
screen_init(3,256,256,true);
screen_init(4,512,256,false,true);
iniciar_video(256,224);
//Main CPU
m68000_0:=cpu_m68000.create(8000000,256);
m68000_0.change_ram16_calls(magmax_getword,magmax_putword);
if not(roms_load16w(@rom,magmax_rom)) then exit;
//Sound CPU
z80_0:=cpu_z80.create(2500000,256);
z80_0.change_ram_calls(magmax_snd_getbyte,magmax_snd_putbyte);
z80_0.change_io_calls(magmax_snd_inbyte,magmax_snd_outbyte);
z80_0.init_sound(magmax_sound_update);
if not(roms_load(@mem_snd,magmax_sound)) then exit;
//Sound Chips
ay8910_0:=ay8910_chip.create(1250000,AY8910,1);
ay8910_0.change_io_calls(nil,nil,magmax_porta_w,magmax_portb_w);
ay8910_1:=ay8910_chip.create(1250000,AY8910,1);
ay8910_2:=ay8910_chip.create(1250000,AY8910,1);
//poner los datos de bg
if not(roms_load16b(@rom18B,magmax_fondo1)) then exit;
if not(roms_load(@rom18B,magmax_fondo2)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,magmax_char)) then exit;
init_gfx(0,8,8,$100);
gfx[0].trans[15]:=true;
gfx_set_desc_data(4,0,32*8,0,1,2,3);
convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,false,false);
//convertir sprites
if not(roms_load(@memoria_temp,magmax_sprites)) then exit;
init_gfx(1,16,16,$200);
gfx[1].trans[0]:=true;
gfx_set_desc_data(4,0,64*8,0,1,2,3);
convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false);
//DIP
marcade.dswa:=$ffdf;
marcade.dswa_val:=@magmax_dip;
//poner la paleta
if not(roms_load(@memoria_temp,magmax_pal)) then exit;
for f:=0 to $ff do begin
v:=(memoria_temp[$400+f] shl 4)+memoria_temp[$500+f];
prom_mem[f]:=((v and $1f) shl 8) or ((v and $10) shl 10) or ((v and $e0) shr 1);
end;
for f:=0 to $ff do begin
colores[f].r:=pal4bit(memoria_temp[f]);
colores[f].g:=pal4bit(memoria_temp[f+$100]);
colores[f].b:=pal4bit(memoria_temp[f+$200]);
end;
set_pal(colores,$100);
//color lookup de sprites
for f:=0 to $ff do gfx[1].colores[f]:=(memoria_temp[$300+f] and $f) or $10;
//final
reset_magmax;
iniciar_magmax:=true;
end;
end.
|
unit NtUtils.Exec.Wdc;
interface
uses
NtUtils.Exec;
type
TExecCallWdc = class(TInterfacedObject, IExecMethod)
function Supports(Parameter: TExecParam): Boolean;
function Execute(ParamSet: IExecProvider): TProcessInfo;
end;
implementation
uses
Winapi.Wdc, NtUtils.Exceptions, Winapi.WinError, NtUtils.Ldr;
{ TExecCallWdc }
function TExecCallWdc.Execute(ParamSet: IExecProvider): TProcessInfo;
var
CommandLine: String;
CurrentDir: PWideChar;
ResultCode: HRESULT;
begin
CommandLine := PrepareCommandLine(ParamSet);
if ParamSet.Provides(ppCurrentDirectory) then
CurrentDir := PWideChar(ParamSet.CurrentDircetory)
else
CurrentDir := nil;
LdrxCheckModuleDelayedImport(wdc, 'WdcRunTaskAsInteractiveUser').RaiseOnError;
ResultCode := WdcRunTaskAsInteractiveUser(PWideChar(CommandLine), CurrentDir,
0);
if not Succeeded(ResultCode) then
raise ENtError.Create(Cardinal(ResultCode), 'WdcRunTaskAsInteractiveUser');
// The method does not provide any information about the newly created process
FillChar(Result, SizeOf(Result), 0);
end;
function TExecCallWdc.Supports(Parameter: TExecParam): Boolean;
begin
case Parameter of
ppParameters, ppCurrentDirectory:
Result := True;
else
Result := False;
end;
end;
end.
|
unit Unit1;
{**
* 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
*}
{$mode objfpc}{$H+}
interface
uses
Classes, IntfGraphics, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
FPCanvas, FPImage,
StdCtrls, ExtCtrls, ntvDotMatrix;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
CheckBox1: TCheckBox;
Label1: TLabel;
ThemeList: TComboBox;
Edit1: TEdit;
Image1: TImage;
TextDotMatrix: TntvTextDotMatrix;
TimerX: TTimer;
DimTimer: TTimer;
TimerY: TTimer;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure CheckBox1Change(Sender: TObject);
procedure DimTimerTimer(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ThemeListSelect(Sender: TObject);
procedure TimerXTimer(Sender: TObject);
procedure TimerYTimer(Sender: TObject);
private
DimReverse: Boolean;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
end;
var
Form1: TForm1;
implementation
{$r '*.lfm'}
{ TForm1 }
procedure TForm1.Edit1Change(Sender: TObject);
begin
TextDotMatrix.Text := Edit1.Text;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ThemeList.Items.Add('tdmClassicLCD');
ThemeList.Items.Add('tdmOrange');
ThemeList.Items.Add('tdmGreenLED');
ThemeList.Items.Add('tdmRedLED');
ThemeList.Items.Add('tdmBlueLED');
TextDotMatrix.Dots.RotateOffset := True;
TextDotMatrix.Dots.Power := true;
TextDotMatrix.Text := Edit1.Text;
{$ifdef LINUX}
TextDotMatrix.Font.Name:= 'Misc Fixed';
TextDotMatrix.Font.Size := 10;
{$else}
{$endif}
end;
procedure TForm1.ThemeListSelect(Sender: TObject);
begin
case ThemeList.ItemIndex of
0: TextDotMatrix.Dots.Theme := tdmClassicLCD;
1: TextDotMatrix.Dots.Theme := tdmOrange;
2: TextDotMatrix.Dots.Theme := tdmGreenLED;
3: TextDotMatrix.Dots.Theme := tdmRedLED;
4: TextDotMatrix.Dots.Theme := tdmBlueLED;
end
end;
procedure TForm1.TimerXTimer(Sender: TObject);
begin
TextDotMatrix.Dots.Scroll(2, 0);
end;
procedure TForm1.TimerYTimer(Sender: TObject);
begin
TextDotMatrix.Dots.Scroll(0, 1);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TextDotMatrix.Text := '';
TextDotMatrix.Dots.Canvas.Draw(0, 0, Image1.Picture.Graphic);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
TimerX.Enabled := not TimerX.Enabled;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
DimTimer.Enabled := not DimTimer.Enabled;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
TimerX.Enabled := False;
TimerY.Enabled := False;
DimTimer.Enabled := False;
TextDotMatrix.Dots.Reset;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
TimerY.Enabled := not TimerY.Enabled;
end;
procedure TForm1.Button6Click(Sender: TObject);
begin
TextDotMatrix.Dots.Power := not TextDotMatrix.Dots.Power;
end;
procedure TForm1.CheckBox1Change(Sender: TObject);
begin
TextDotMatrix.Dots.Glow := CheckBox1.Checked;
end;
procedure TForm1.DimTimerTimer(Sender: TObject);
begin
if DimReverse then
begin
TextDotMatrix.Dots.Dim := TextDotMatrix.Dots.Dim - 10;
if TextDotMatrix.Dots.Dim <= 0 then
DimReverse := False;
end
else
begin
TextDotMatrix.Dots.Dim := TextDotMatrix.Dots.Dim + 10;
if TextDotMatrix.Dots.Dim >= 100 then
DimReverse := True;
end;
end;
constructor TForm1.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
end;
destructor TForm1.Destroy;
begin
inherited Destroy;
end;
end.
|
{ Subroutine SST_R_PAS_SYN_PAD (MFLAG)
*
* This subroutine implements the PAD syntax referenced in PAS.SYN. It is
* intended to skip over "irrelevant" characters, such as space, end of line,
* etc. Comments have already been removed from the input stream by the
* pre-processor.
}
module sst_r_pas_SYN_PAD;
define sst_r_pas_syn_pad;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_syn_pad ( {implements PAD syntax}
out mflag: syo_mflag_k_t); {syntax matched yes/no, use SYO_MFLAG_xxx_K}
var
i: sys_int_machine_t; {scratch character value}
label
loop;
begin
mflag := syo_mflag_yes_k; {this syntax always matches}
loop: {back here to try each new character}
syo_p_cpos_push; {save state before getting character}
syo_p_get_ichar (i); {get next input stream character}
if {is this a pad character ?}
(i = ord(' ')) or {space ?}
(i = syo_ichar_eol_k) or {end of line ?}
(i = syo_ichar_eof_k) {end of file ?}
then begin
syo_p_cpos_pop (syo_mflag_yes_k); {remove pushed state from stack}
goto loop; {back to test next character}
end;
syo_p_cpos_pop (syo_mflag_no_k); {restore state to before non-pad character}
end;
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.6 2004.02.03 4:16:42 PM czhower
For unit name changes.
Rev 1.5 2004.01.01 3:13:32 PM czhower
Updated comment.
Rev 1.4 2003.12.31 10:30:24 PM czhower
Comment update.
Rev 1.3 2003.12.31 7:25:14 PM czhower
Now works in .net
Rev 1.2 10/4/2003 9:52:08 AM GGrieve
add IdCoreGlobal to uses list
Rev 1.1 2003.10.01 1:12:30 AM czhower
.Net
Rev 1.0 11/13/2002 08:37:36 AM JPMugaas
}
unit IdAntiFreeze;
{
NOTE - This unit must NOT appear in any Indy uses clauses. This is a ONE way
relationship and is linked in IF the user uses this component. This is done to
preserve the isolation from the massive FORMS unit.
Because it links to Forms:
- The Application.ProcessMessages cannot be done in IdCoreGlobal as an OS
independent function, and thus this unit is allowed to violate the IFDEF
restriction.
}
interface
{$I IdCompilerDefines.inc}
uses
Classes,
IdAntiFreezeBase,
IdBaseComponent;
{ Directive needed for C++Builder HPP and OBJ files for this that will force it
to be statically compiled into the code }
{$I IdCompilerDefines.inc}
{$IFDEF WINDOWS}
{$HPPEMIT '#pragma link "IdAntiFreeze.obj"'} {Do not Localize}
{$ENDIF}
{$IFDEF UNIX}
{$HPPEMIT '#pragma link "IdAntiFreeze.o"'} {Do not Localize}
{$ENDIF}
type
{$IFDEF HAS_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32)]
{$ENDIF}
TIdAntiFreeze = class(TIdAntiFreezeBase)
public
procedure Process; override;
end;
implementation
uses
{$IFDEF WIDGET_KYLIX}
QForms,
{$ENDIF}
{$IFDEF WIDGET_VCL_LIKE}
Forms,
{$ENDIF}
{$IFDEF WINDOWS}
{$IFNDEF FMX}
Messages,
Windows,
{$ENDIF}
{$ENDIF}
{$IFDEF WIDGET_WINFORMS}
System.Windows.Forms,
{$ENDIF}
IdGlobal;
{$IFDEF UNIX}
procedure TIdAntiFreeze.Process;
begin
//TODO: Handle ApplicationHasPriority
Application.ProcessMessages;
end;
{$ENDIF}
{$IFDEF WINDOWS}
{$IFNDEF FMX}
procedure TIdAntiFreeze.Process;
var
LMsg: TMsg;
begin
if ApplicationHasPriority then begin
Application.ProcessMessages;
end else begin
// This guarantees it will not ever call Application.Idle
if PeekMessage(LMsg, 0, 0, 0, PM_NOREMOVE) then begin
Application.HandleMessage;
end;
end;
end;
{$ELSE}
procedure TIdAntiFreeze.Process;
begin
//TODO: Handle ApplicationHasPriority
Application.ProcessMessages;
end;
{$ENDIF}
{$ENDIF}
{$IFDEF WIDGET_WINFORMS}
procedure TIdAntiFreeze.Process;
begin
//TODO: Handle ApplicationHasPriority
Application.DoEvents;
end;
{$ENDIF}
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clEmailAddress;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils;
{$ELSE}
System.Classes, System.SysUtils;
{$ENDIF}
type
TclEmailAddressItem = class(TCollectionItem)
private
FName: string;
FEmail: string;
function GetNormName(const AName: string): string;
function GetDenormName(const AName: string): string;
function GetFullAddress: string;
procedure SetFullAddress(const Value: string);
function IsValidAddressKey(AKey: Char; AIsBasic: Boolean): Boolean;
function ExtractAddress(const AFullAddress: string): string;
function ExtractDisplayName(const AFullAddress, AEmail: string): string;
protected
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); overload; override;
constructor Create; reintroduce; overload;
constructor Create(const AEmail, AName: string); reintroduce; overload;
constructor Create(const AFullAddress: string); reintroduce; overload;
procedure Assign(Source: TPersistent); override;
procedure Clear; virtual;
published
property Name: string read FName write FName;
property Email: string read FEmail write FEmail;
property FullAddress: string read GetFullAddress write SetFullAddress stored False;
end;
TclEmailAddressList = class(TOwnedCollection)
private
function GetItem(Index: Integer): TclEmailAddressItem;
procedure SetItem(Index: Integer; const Value: TclEmailAddressItem);
function GetEmailAddresses: string;
procedure SetEmailAddresses(const Value: string);
function GetDisplayName: string;
public
function Add: TclEmailAddressItem; overload;
function Add(const AEmail, AName: string): TclEmailAddressItem; overload;
function Add(const AFullAddress: string): TclEmailAddressItem; overload;
function ItemByName(const AName: string): TclEmailAddressItem;
function ItemByEmail(const AEmail: string): TclEmailAddressItem;
procedure GetEmailList(AList: TStrings); overload;
procedure GetEmailList(AList: TStrings; IsInit: Boolean); overload;
property Items[Index: Integer]: TclEmailAddressItem read GetItem write SetItem; default;
property EmailAddresses: string read GetEmailAddresses write SetEmailAddresses;
property DisplayName: string read GetDisplayName;
end;
function GetCompleteEmailAddress(const AName, AEmail: string): string;
function GetEmailAddressParts(const ACompleteEmail: string; var AName, AEmail: string): Boolean;
implementation
uses
clUtils, clIdnTranslator, clWUtils;
const
cListSeparator: array[Boolean] of string = ('', ', ');
SpecialSymbols = ['\', '"', '(', ')'];
function GetCompleteEmailAddress(const AName, AEmail: string): string;
var
addr: TclEmailAddressItem;
begin
addr := TclEmailAddressItem.Create();
try
addr.Name := AName;
addr.Email := AEmail;
Result := addr.FullAddress;
finally
addr.Free();
end;
end;
function GetEmailAddressParts(const ACompleteEmail: string; var AName, AEmail: string): Boolean;
var
addr: TclEmailAddressItem;
begin
addr := TclEmailAddressItem.Create();
try
addr.FullAddress := ACompleteEmail;
AEmail := addr.Email;
AName := addr.Name;
Result := (AName <> '');
if not Result then
begin
AName := AEmail;
end;
finally
addr.Free();
end;
end;
{ TclEmailAddressItem }
constructor TclEmailAddressItem.Create;
begin
inherited Create(nil);
end;
constructor TclEmailAddressItem.Create(const AEmail, AName: string);
begin
inherited Create(nil);
Name := AName;
Email := AEmail;
end;
procedure TclEmailAddressItem.Assign(Source: TPersistent);
begin
if (Source is TclEmailAddressItem) then
begin
FName := TclEmailAddressItem(Source).Name;
FEmail := TclEmailAddressItem(Source).Email;
end else
begin
inherited Assign(Source);
end;
end;
procedure TclEmailAddressItem.Clear;
begin
FName := '';
FEmail := '';
end;
constructor TclEmailAddressItem.Create(const AFullAddress: string);
begin
inherited Create(nil);
FullAddress := AFullAddress;
end;
constructor TclEmailAddressItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
end;
function TclEmailAddressItem.ExtractAddress(const AFullAddress: string): string;
var
i, len, addrStart: Integer;
isAt, inQuote, inBracket, inComment, isBasic: Boolean;
begin
Result := '';
addrStart := -1;
isAt := False;
inQuote := False;
inBracket := False;
inComment := False;
len := Length(AFullAddress);
isBasic := TclIdnTranslator.IsBasic(AFullAddress);
for i := 1 to len do
begin
if (not inQuote) and (not inComment) and (AFullAddress[i] = '@') and (i > 1) and (i < len)
and IsValidAddressKey(AFullAddress[i - 1], isBasic) and IsValidAddressKey(AFullAddress[i + 1], isBasic) then
begin
isAt := True;
end;
if (AFullAddress[i] = '"') and ((i = 1) or (AFullAddress[i - 1] <> '\')) then
begin
inQuote := not inQuote;
end;
if (AFullAddress[i] = '<') and ((i = 1) or (AFullAddress[i - 1] <> '\')) then
begin
addrStart := -1;
inBracket := True;
Continue;
end;
if inBracket and (AFullAddress[i] = '>') and ((i = 1) or (AFullAddress[i - 1] <> '\')) then
begin
if (addrStart > -1) then
begin
Result := system.Copy(AFullAddress, addrStart, i - addrStart);
end else
begin
Result := AFullAddress;
end;
inBracket := False;
addrStart := -1;
end;
if (not inQuote) and (AFullAddress[i] = '(') and ((i = 1) or (AFullAddress[i - 1] <> '\')) then
begin
inComment := True;
end;
if inComment and (AFullAddress[i] = ')') and ((i = 1) or (AFullAddress[i - 1] <> '\')) then
begin
inComment := False;
end;
if inQuote or inBracket or IsValidAddressKey(AFullAddress[i], isBasic) then
begin
if (addrStart < 0) then
begin
addrStart := i;
end;
end else
begin
if isAt and (addrStart > -1) then
begin
Result := system.Copy(AFullAddress, addrStart, i - addrStart);
end;
addrStart := -1;
isAt := False;
end;
end;
if (isAt or inBracket) and (addrStart > -1) and (Result = '') then
begin
Result := system.Copy(AFullAddress, addrStart, MaxInt);
end;
end;
function TclEmailAddressItem.ExtractDisplayName(const AFullAddress, AEmail: string): string;
begin
if(system.Pos(UpperCase('<' + AEmail + '>'), UpperCase(AFullAddress)) > 0) then
begin
Result := StringReplace(AFullAddress, '<' + AEmail + '>', '', [rfIgnoreCase]);
end else
begin
Result := StringReplace(AFullAddress, AEmail, '', [rfIgnoreCase]);
end;
Result := Trim(GetDenormName(Result));
Result := ExtractQuotedString(Result, '''');
Result := ExtractQuotedString(Result, '(', ')');
end;
function TclEmailAddressItem.GetDenormName(const AName: string): string;
var
i, j: Integer;
Len: Integer;
SpecSymExpect: Boolean;
Sym: Char;
begin
SpecSymExpect := False;
Len := Length(AName);
SetLength(Result, Len);
i := 1;
j := 1;
while (i <= Length(AName)) do
begin
Sym := AName[i];
case Sym of
'\':
begin
if not SpecSymExpect then
begin
SpecSymExpect := True;
Inc(i);
Continue;
end;
end;
'"':
begin
if not SpecSymExpect then
begin
Sym := ' ';
end;
end;
end;
SpecSymExpect := False;
Result[j] := Sym;
Inc(j);
Inc(i);
end;
SetLength(Result, j - 1);
end;
function TclEmailAddressItem.GetDisplayName: string;
begin
Result := Name;
if (Result = '') then
begin
Result := Email;
end;
end;
function TclEmailAddressItem.GetFullAddress: string;
begin
if (Name = '') or (Name = Email) then
begin
Result := Email;
end else
begin
Result := Format('%s <%s>', [GetNormName(Name), Email]);
end;
end;
function TclEmailAddressItem.GetNormName(const AName: string): string;
function GetSymbolsTotalCount(const AValue: String; ASymbolsSet: TCharSet): Integer;
var
i: Integer;
begin
Result := 0;
for i := 1 to Length(AValue) do
begin
if CharInSet(AValue[i], ASymbolsSet) then Inc(Result);
end;
end;
var
i, j, SpecialCount: Integer;
begin
SpecialCount := GetSymbolsTotalCount(AName, SpecialSymbols);
if (SpecialCount > 0) then
begin
SetLength(Result, SpecialCount + Length(AName));
j := 0;
for i := 1 to Length(AName) do
begin
Inc(j);
if CharInSet(AName[i], SpecialSymbols) then
begin
Result[j] := '\';
Inc(j);
end;
Result[j] := AName[i];
end;
Result := GetQuotedString(Result);
end else
begin
Result := AName;
end;
if (system.Pos(' ', Result) > 0) then
begin
Result := GetQuotedString(Result);
end;
end;
function TclEmailAddressItem.IsValidAddressKey(AKey: Char; AIsBasic: Boolean): Boolean;
const
validKeys = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!#$%&''*+-/=?_`{}|~^.@"';
specKeys = '<>';
begin
if AIsBasic then
begin
Result := Pos(AKey, validKeys) > 0;
end else
begin
Result := Pos(AKey, specKeys) < 1;
end;
end;
procedure TclEmailAddressItem.SetFullAddress(const Value: string);
begin
Email := ExtractAddress(Value);
Name := ExtractDisplayName(Value, Email);
end;
{ TclEmailAddressList }
function TclEmailAddressList.Add: TclEmailAddressItem;
begin
Result := TclEmailAddressItem(inherited Add());
end;
function TclEmailAddressList.Add(const AEmail, AName: string): TclEmailAddressItem;
begin
Result := Add();
Result.Email := AEmail;
Result.Name := AName;
end;
function TclEmailAddressList.Add(const AFullAddress: string): TclEmailAddressItem;
begin
Result := Add();
Result.FullAddress := AFullAddress;
end;
function TclEmailAddressList.GetDisplayName: string;
var
i: Integer;
begin
Result := '';
for i := 0 to Count - 1 do
begin
Result := Result + cListSeparator[i > 0] + Items[i].DisplayName;
end;
end;
function TclEmailAddressList.GetEmailAddresses: string;
var
i: Integer;
begin
Result := '';
for i := 0 to Count - 1 do
begin
Result := Result + cListSeparator[i > 0] + Items[i].FullAddress;
end;
end;
procedure TclEmailAddressList.GetEmailList(AList: TStrings);
begin
GetEmailList(AList, True);
end;
procedure TclEmailAddressList.GetEmailList(AList: TStrings; IsInit: Boolean);
var
i: Integer;
begin
if IsInit then
begin
AList.Clear();
end;
for i := 0 to Count - 1 do
begin
AList.Add(Items[i].FullAddress);
end;
end;
function TclEmailAddressList.GetItem(Index: Integer): TclEmailAddressItem;
begin
Result := TclEmailAddressItem(inherited GetItem(Index));
end;
function TclEmailAddressList.ItemByEmail(const AEmail: string): TclEmailAddressItem;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Items[i];
if SameText(Result.Email, AEmail) then Exit;
end;
Result := nil;
end;
function TclEmailAddressList.ItemByName(const AName: string): TclEmailAddressItem;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Items[i];
if SameText(Result.Name, AName) then Exit;
end;
Result := nil;
end;
procedure TclEmailAddressList.SetEmailAddresses(const Value: string);
var
StartPos, EndPos,
Quote, i, Len: integer;
s: string;
c: Char;
begin
Clear();
Quote := 0;
i := 1;
Len := Length(Value);
while (i <= Len) do
begin
StartPos := i;
EndPos := StartPos;
while (i <= Len) do
begin
c := Value[i];
if (c = '"') or (c = '''') then
begin
Inc(Quote);
end;
if (c = ',') or (c = ';') or (c = #13) then
begin
if (Quote <> 1) then
begin
Break;
end;
end;
Inc(EndPos);
Inc(i);
end;
s := Trim(Copy(Value, StartPos, EndPos - StartPos));
if Length(s) > 0 then
begin
Add(s);
end;
i := EndPos + 1;
Quote := 0;
end;
end;
procedure TclEmailAddressList.SetItem(Index: Integer; const Value: TclEmailAddressItem);
begin
inherited SetItem(Index, Value);
end;
end.
|
unit wwClasses;
{ Базовые объекты мира червяков }
interface
Uses
Types, Contnrs, Classes,
wwTypes;
const
MapHeight = 499;
MapWidth = 499;
Type
TwwPoint = class
Position: TPoint;
Value : Integer;
procedure MoveTo(aDirection : TwwDirection);
end;
TwwWorld = class;
TwwThing = class(TObject)
private
f_Points: TObjectList;
f_IsDead: Boolean;
f_Caption: String;
f_Direction: TwwDirection;
f_Entity: TwwEntity;
FVariety: Integer;
FWorld: TwwWorld;
FAge: Integer;
FAbsoluteIndex: Integer;
private
function GetHead: TwwPoint;
function GetIsLive: Boolean;
function GetLength: Integer;
function GetPoint(Index: Integer): TwwPoint;
function GetTail: TwwPoint;
procedure SetIsDead(const Value: Boolean);
procedure SetIsLive(const Value: Boolean);
procedure SetLength(const Value: Integer);
protected
procedure CorrectSegments; virtual;
procedure Move;
procedure WhileStop; virtual;
function GetDefaultLength: Integer; virtual;
procedure Think; virtual;
public
constructor Create(aWorld: TwwWorld; const aLength: Integer);
destructor Destroy; override;
procedure Enlarge(const aDelta: Integer);
function IsMe(const aPoint: TPoint): Boolean;
procedure Update; virtual;
procedure Die; virtual;
function Eat(const aPOint: TPoint): Boolean; virtual;
function IsFree(const aPOint: TPoint; aWhat: TwwEntities = [weLive]): Boolean;
function IsBusy(const aPOint: TPoint): Boolean;
procedure Ressurect; virtual;
function PointIndex(aPoint: TPoint): Integer;
procedure AddPoint(aPoint: TPoint);
public
property Caption: String
read f_Caption
write f_Caption;
property DefaultLength: Integer
read GetDefaultLength;
property Head: TwwPoint
read GetHead;
property Tail: TwwPoint
read GetTail;
property Length: Integer
read GetLength
write SetLength;
property Points[Index: Integer]: TwwPoint
read GetPoint;
property IsDead: Boolean
read f_IsDead
write SetIsDead;
property IsLive: Boolean
read GetIsLive
write SetIsLive;
property Entity: TwwEntity
read f_Entity
write f_Entity;
property Direction: TwwDirection
read f_Direction
write f_Direction;
property Variety: Integer read FVariety write FVariety;
property World: TwwWorld read FWorld write FWorld;
property Age: Integer read FAge;
property AbsoluteIndex: Integer read FAbsoluteIndex;
end;
TwwIdeas = class(TwwThing)
private
protected
public
constructor Create(aWorld: TwwWorld; const aLength: Integer);
procedure Ressurect; override;
end;
TwwWorld = class
private
f_Things: TObjectList;
f_Bounds: TRect;
f_Ideas : TwwIdeas;
f_OnNewIdea: TNotifyEvent;
FNotIdea: Boolean;
FMap: array[0..MapWidth, 0..MapHeight] of Integer;
function GetCount: Integer;
function GetThings(Index: Integer): TwwThing;
procedure AddThingToMap(aThing: TwwThing);
procedure ClearMap;
protected
procedure Ressurect(aThing: TwwThing); virtual;
public
constructor Create(const aBounds: TRect);
destructor Destroy; override;
function IsFree(const aPOint: TPoint; aWhat: TwwEntities = [weLive]): Boolean;
function IsBusy(const aPOint: TPoint; aWhat: TwwEntities = [weLive]): Boolean;
overload;
function IsBusy(const aPoint: TPoint; var aThing: TwwThing; aWhat: TwwEntities
= [weLive]): Boolean; overload;
function ThingAt(const aPoint: TPoint): TwwThing;
procedure Update; virtual;
procedure DeleteThing(aIndex: Integer);
procedure AddThing(aThing: TwwThing);
function IsLegal(aPoint: TPoint): Boolean;
public
property Count: Integer
read GetCount;
property Things[Index: Integer]: TwwThing
read GetThings;
property Size: TRect
read f_Bounds;
property OnNewIdea: TNotifyEvent
read f_OnNewIdea
write f_OnNewIdea;
end;
implementation
Uses
Math, SysUtils,
wwUtils;
{ TwwPoint }
procedure TwwPoint.MoveTo(aDirection: TwwDirection);
begin
IncPoint(Position, aDirection);
end;
{ TwwThing }
constructor TwwThing.Create(aWorld: TwwWorld; const aLength: Integer);
begin
inherited Create;
World:= aWorld;
f_Points:= TObjectList.Create;
f_Caption:= '';
Enlarge(aLength);
Entity:= weNotLive;
end;
destructor TwwThing.Destroy;
begin
f_Points.Free;
inherited;
end;
procedure TwwThing.Die;
begin
IsDead:= True;
end;
procedure TwwThing.Enlarge(const aDelta: Integer);
var
i: Integer;
l_P: TwwPoint;
l_Tail: TwwPoint;
l_Value: Integer;
begin
if aDelta > 0 then
for i:= 1 to aDelta do
begin
l_P:= TwwPoint.Create;
if Length > 1 then
l_P.Position:= Tail.Position;
f_Points.Add(l_P);
end
else
if aDelta < 0 then
begin
i:= 0;
while i <> Abs(aDelta) do
begin
l_Tail:= Tail;
f_Points.Delete(Pred(f_Points.Count));
Inc(i);
if Length <= DefaultLength then
begin
Die;
break;
end; // Length <= DefaultLenght
end;
end;
end;
function TwwThing.GetHead: TwwPoint;
begin
if Length > 0 then
Result:= Points[0]
else
Result:= nil;
end;
function TwwThing.GetIsLive: Boolean;
begin
Result:= not IsDead;
end;
function TwwThing.GetLength: Integer;
begin
Result:= f_Points.Count;
end;
function TwwThing.GetPoint(Index: Integer): TwwPoint;
begin
if InRange(Index, 0, Pred(Length)) then
Result:= TwwPoint(f_Points.Items[Index])
else
Result:= nil;
end;
function TwwThing.GetTail: TwwPoint;
begin
if Length > 0 then
Result:= Points[Pred(Length)]
else
Result:= nil;
end;
function TwwThing.IsMe(const aPoint: TPoint): Boolean;
begin
Result:= PointIndex(aPoint) <> -1;
end;
procedure TwwThing.Move;
var
i: Integer;
l_Head: TPoint;
begin
if IsLive and (Direction <> dtNone) then
begin
if Direction = dtStop then
WhileStop
else
begin
l_Head:= MovePoint(Head.Position, Direction);
if World.IsLegal(l_Head) and
(IsFree(l_Head, [weLive, weNotLive]) or Eat(l_Head)) then
begin
for i:= Pred(Length) downto 1 do
Points[i].Position:= Points[Pred(i)].Position;
Head.Position:= l_Head;
CorrectSegments;
end
else
Die;
end;
end;
end;
procedure TwwThing.CorrectSegments;
var
i: Integer;
l_Value: Integer;
begin
case Direction of
dtUp: l_Value:= ws_HeadU;
dtDown: l_Value:= ws_HeadD;
dtLeft: l_Value:= ws_HeadR;
dtRight: l_Value:= ws_HeadL;
else
l_Value:= Head.Value;
end;
Head.Value:= l_Value;
if Length > 2 then
for i:= 1 to Length-2 do
begin
case BodySegment(Points[Succ(i)].Position, Points[Pred(i)].Position, Points[i].Position) of
ctUp, ctDown : l_Value:= ws_BodyV;
ctRight, ctLeft : l_Value:= ws_BodyH;
ctLeftUp : l_Value:= ws_RotUL;
ctLeftDown : l_Value:= ws_RotD;
ctRightUp : l_Value:= ws_RotUR;
ctRightDown : l_Value:= ws_RotL;
else
l_Value:= Points[i].Value;
end; // case
Points[i].Value:= l_Value;
end; // for i
case CalcDir(Points[Pred(Length)].Position, Points[Pred(Pred(Length))].Position, ftVertical) of
dtUp: l_Value:= ws_TailU;
dtDown: l_Value:= ws_TailD;
dtLeft: l_Value:= ws_TailR;
dtRight: l_Value:= ws_TailL;
else
l_Value:= Tail.Value;
end;
Tail.Value:= l_Value;
end;
procedure TwwThing.SetIsDead(const Value: Boolean);
begin
f_IsDead := Value;
end;
procedure TwwThing.SetIsLive(const Value: Boolean);
begin
IsDead:= not Value;
end;
procedure TwwThing.SetLength(const Value: Integer);
begin
f_Points.Clear;
Enlarge(Value);
end;
procedure TwwThing.Update;
begin
if IsDead then
Ressurect;
Inc(FAge);
Think;
Move;
end;
procedure TwwThing.WhileStop;
begin
end;
function TwwThing.Eat(const aPoint: TPoint): Boolean;
begin
Result:= IsFree(aPoint);
end;
function TwwThing.IsBusy(const aPOint: TPoint): Boolean;
begin
Result:= World.IsBusy(aPoint);
end;
function TwwThing.IsFree(const aPOint: TPoint; aWhat: TwwEntities = [weLive]):
Boolean;
begin
Result:= World.IsFree(aPoint, aWhat);
end;
procedure TwwThing.Ressurect;
var
A: TPoint;
begin
FAge:= 0;
IsLive:= True;
repeat
A.X := Random(World.Size.Right-5) + 5;
A.Y := Random(World.Size.Bottom-2) + 1;
until IsFree(A, weAny);
Length:= DefaultLength;
Head.Position:= A;
end;
function TwwThing.GetDefaultLength: Integer;
begin
Result:= 1;
end;
procedure TwwThing.Think;
begin
end;
function TwwThing.PointIndex(aPoint: TPoint): Integer;
var
i: Integer;
begin
Result := -1;
if IsLive then
for i:= Pred(Length) downto 0 do
if Equal(Points[i].Position, aPoint) then
begin
Result:= i;
break;
end;
end;
procedure TwwThing.AddPoint(aPoint: TPoint);
var
l_P: TwwPoint;
begin
l_P:= TwwPoint.Create;
l_P.Position:= aPoint;
f_Points.Add(l_P);
end;
{ TwwWorld }
constructor TwwWorld.Create;
begin
inherited Create;
f_Things:= TObjectList.Create;
f_Bounds:= aBounds;
f_Ideas:= TwwIdeas.Create(Self, 0);
FNotIdea:= False;
ClearMap;
end;
destructor TwwWorld.Destroy;
begin
f_Ideas.Free;
f_Things.Free;
inherited;
end;
function TwwWorld.IsBusy(const aPOint: TPoint; aWhat: TwwEntities = [weLive]):
Boolean;
var
l_T: TwwThing;
begin
Result:= IsBusy(aPoint, l_T, aWhat);
end;
function TwwWorld.IsBusy(const aPoint: TPoint; var aThing: TwwThing; aWhat:
TwwEntities = [weLive]): Boolean;
var
i: Integer;
l_T: TwwThing;
begin
aThing:= nil;
Result:= False;
if IsLegal(aPoint) then
begin
i:= FMap[aPoint.X, aPoint.Y];
if i > -1 then
begin
l_T:= Things[i];
if l_T.Entity in aWhat then
begin
aThing:= l_T;
Result:= True;
end;
end; // i > -1
(*
for i:= 0 to Pred(Count) do
if Things[i].IsMe(aPoint) and (Things[i].Entity in aWhat) then
begin
Result:= True;
aThing:= Things[i];
break;
end;
*)
(*
if not FNotIdea then
begin
f_Ideas.AddPoint(aPoint);
if Assigned(f_OnNewIdea) then
f_OnNewIdea(Self);
end;
*)
end
else
Result:= True;
end;
function TwwWorld.IsFree(const aPOint: TPoint; aWhat: TwwEntities = [weLive]):
Boolean;
begin
Result:= not IsBusy(aPoint, aWhat);
end;
function TwwWorld.ThingAt(const aPoint: TPoint): TwwThing;
var
l_T: TwwThing;
begin
Result:= nil;
FNotIdea:= True;
try
if IsBusy(aPoint, l_T, [weLive, weNotLive]) then
Result:= l_T
else
if f_Ideas.IsMe(aPoint) then
Result:= f_Ideas;
finally
FNotIdea:= False;
end
end;
function TwwWorld.GetCount: Integer;
begin
Result:= f_Things.Count;
end;
function TwwWorld.GetThings(Index: Integer): TwwThing;
begin
if InRange(Index, 0, Pred(Count)) then
Result:= TwwThing(f_Things.Items[Index]);
end;
procedure TwwWorld.Update;
var
i, j: Integer;
l_T: TwwThing;
begin
ClearMap;
for i:= 0 to Pred(Count) do
begin
l_T:= Things[i];
if l_T.IsLive then
AddThingToMap(l_T);
end; // for i
for i:= 0 to Pred(Count) do
begin
f_Ideas.Ressurect;
Things[i].Update;
if Things[i].IsDead then
Ressurect(Things[i]);
end;
end;
procedure TwwWorld.Ressurect(aThing: TwwThing);
begin
aThing.Ressurect;
end;
procedure TwwWorld.DeleteThing(aIndex: Integer);
var
l_O: TObject;
begin
l_O:= f_Things.Items[aIndex];
f_Things.Delete(aIndex);
FreeAndNil(l_O);
end;
procedure TwwWorld.AddThing(aThing: TwwThing);
begin
aThing.FAbsoluteIndex:= f_Things.Count;
f_Things.Add(aThing);
aThing.Ressurect;
end;
function TwwWorld.IsLegal(aPoint: TPoint): Boolean;
begin
Result:= f_Bounds.Contains(aPoint);
// Result := InRange(aPoint.X, f_Bounds.Left, f_Bounds.Right) and
// InRange(aPoint.Y, f_Bounds.Top, f_Bounds.Bottom);
end;
procedure TwwWorld.AddThingToMap(aThing: TwwThing);
var
j: Integer;
begin
for j:= 0 to Pred(aThing.Length) do
FMap[aThing.Points[j].Position.X, aThing.Points[j].Position.Y]:= aThing.AbsoluteIndex;
end;
procedure TwwWorld.ClearMap;
var
i, j: Integer;
begin
for i:= 0 to MapWidth do
for j:= 0 to MapHeight do
FMap[i, j]:= -1;
end;
{ TwwIdeas }
constructor TwwIdeas.Create(aWorld: TwwWorld; const aLength: Integer);
begin
inherited Create(aWorld, 0);
Variety:= -1;
end;
procedure TwwIdeas.Ressurect;
begin
Length:= 0;
end;
end.
|
unit bdzxAnalysisForm;
interface
uses
Forms, BaseForm, Classes, Controls, SysUtils, StdCtrls,
QuickSortList, QuickList_double, StockDayDataAccess,
define_price, define_dealitem,
Rule_BDZX;
type
TfrmBdzxAnalysisData = record
Rule_BDZX_Price: TRule_BDZX_Price;
StockDayDataAccess: TStockDayDataAccess;
end;
TfrmBdzxAnalysis = class(TfrmBase)
btnComputeBDZX: TButton;
edtstock: TEdit;
edtdatasrc: TComboBox;
lbl1: TLabel;
lbl2: TLabel;
procedure btnComputeBDZXClick(Sender: TObject);
protected
fBdzxAnalysisData: TfrmBdzxAnalysisData;
function getDataSrcCode: integer;
function getDataSrcWeightMode: TWeightMode;
function getStockCode: integer;
procedure ComputeBDZX(ADataSrcCode: integer; AWeightMode: TWeightMode; AStockPackCode: integer); overload;
procedure ComputeBDZX(ADataSrcCode: integer; ADealItem: PRT_DealItem; AWeightMode: TWeightMode; AOutput: TALDoubleList); overload;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.dfm}
uses
define_datasrc,
StockDayData_Load,
BaseStockApp;
constructor TfrmBdzxAnalysis.Create(AOwner: TComponent);
begin
inherited;
FillChar(fBdzxAnalysisData, SizeOf(fBdzxAnalysisData), 0);
end;
function TfrmBdzxAnalysis.getDataSrcCode: integer;
begin
Result := DataSrc_163;
end;
function TfrmBdzxAnalysis.getDataSrcWeightMode: TWeightMode;
begin
Result := weightNone;
end;
function TfrmBdzxAnalysis.getStockCode: integer;
begin
Result := getStockCodePack(edtstock.Text);
end;
procedure TfrmBdzxAnalysis.btnComputeBDZXClick(Sender: TObject);
begin
ComputeBDZX(getDataSrcCode, getDataSrcWeightMode, getStockCode);
end;
procedure TfrmBdzxAnalysis.ComputeBDZX(ADataSrcCode: integer; ADealItem: PRT_DealItem; AWeightMode: TWeightMode; AOutput: TALDoubleList);
var
tmpAj: double;
begin
if nil = ADealItem then
exit;
if 0 = ADealItem.EndDealDate then
begin
if nil <> fBdzxAnalysisData.StockDayDataAccess then
begin
fBdzxAnalysisData.StockDayDataAccess.Free;
end;
fBdzxAnalysisData.StockDayDataAccess := TStockDayDataAccess.Create(FilePath_DBType_Item, ADealItem, DataSrc_163, weightNone);
try
StockDayData_Load.LoadStockDayData(App, fBdzxAnalysisData.StockDayDataAccess);
if (0 < fBdzxAnalysisData.StockDayDataAccess.RecordCount) then
begin
if nil <> fBdzxAnalysisData.Rule_BDZX_Price then
begin
FreeAndNil(fBdzxAnalysisData.Rule_BDZX_Price);
end;
fBdzxAnalysisData.Rule_BDZX_Price := TRule_BDZX_Price.Create();
try
fBdzxAnalysisData.Rule_BDZX_Price.OnGetDataLength := fBdzxAnalysisData.StockDayDataAccess.DoGetRecords;
fBdzxAnalysisData.Rule_BDZX_Price.OnGetPriceOpen := fBdzxAnalysisData.StockDayDataAccess.DoGetStockOpenPrice;
fBdzxAnalysisData.Rule_BDZX_Price.OnGetPriceClose := fBdzxAnalysisData.StockDayDataAccess.DoGetStockClosePrice;
fBdzxAnalysisData.Rule_BDZX_Price.OnGetPriceHigh := fBdzxAnalysisData.StockDayDataAccess.DoGetStockHighPrice;
fBdzxAnalysisData.Rule_BDZX_Price.OnGetPriceLow := fBdzxAnalysisData.StockDayDataAccess.DoGetStockLowPrice;
fBdzxAnalysisData.Rule_BDZX_Price.Execute;
tmpAj := fBdzxAnalysisData.Rule_BDZX_Price.Ret_AJ.value[fBdzxAnalysisData.StockDayDataAccess.RecordCount - 1];
AOutput.AddObject(tmpAj, TObject(ADealItem));
finally
FreeAndNil(fBdzxAnalysisData.Rule_BDZX_Price);
end;
end;
finally
FreeAndNil(fBdzxAnalysisData.StockDayDataAccess);
end;
end;
end;
procedure TfrmBdzxAnalysis.ComputeBDZX(ADataSrcCode: integer; AWeightMode: TWeightMode; AStockPackCode: integer);
var
i: integer;
tmpStockItem: PRT_DealItem;
tmpBDZX: TALDoubleList;
tmpResultOutput: TStringList;
begin
tmpBDZX := TALDoubleList.Create;
try
tmpBDZX.Duplicates := lstDupAccept;
if 0 <> ADataSrcCode then
begin
tmpStockItem := TBaseStockApp(App).StockItemDB.FindItem(IntToStr(AStockPackCode));
ComputeBDZX(ADataSrcCode, tmpStockItem, AWeightMode, tmpBDZX);
end else
begin
for i := 0 to TBaseStockApp(App).StockItemDB.RecordCount - 1 do
begin
Application.ProcessMessages;
tmpStockItem := TBaseStockApp(App).StockItemDB.RecordItem[i];
ComputeBDZX(ADataSrcCode, tmpStockItem, AWeightMode, tmpBDZX);
end;
end;
tmpBDZX.Sort;
tmpResultOutput := TStringList.Create;
try
for i := 0 to tmpBDZX.Count - 1 do
begin
tmpStockItem := PRT_DealItem(tmpBDZX.Objects[i]);
tmpResultOutput.Add(FloatToStr(tmpBDZX[i]) + ' -- ' + tmpStockItem.sCode);
end;
tmpResultOutput.SaveToFile('bdzx' + FormatDateTime('yyyymmdd', now) + '.txt');
finally
tmpResultOutput.Free;
end;
finally
tmpBDZX.Free;
end;
end;
end.
|
unit Live.Model.Fiscal.SPED.C170;
interface
uses
Live.Model.Fiscal.SPED.Interfaces,
Live.Model.Connection,
System.Classes;
type
TSPEDC170 = class(TInterfacedObject, iExport<TDataConnection>)
private
FArquivo : TStringList;
public
constructor Create;
destructor Destroy; override;
class function New : iExport<TDataConnection>;
function Generated ( aValue : TDataConnection ) : iExport<TDataConnection>;
end;
implementation
uses
System.SysUtils;
const
ARQ = 'SPED.txt';
{ TSPEDC170 }
constructor TSPEDC170.Create;
begin
FArquivo := TStringList.Create;
if FileExists(ARQ) then
FArquivo.LoadFromFile(ARQ);
end;
destructor TSPEDC170.Destroy;
begin
FArquivo.Free;
inherited;
end;
function TSPEDC170.Generated(aValue: TDataConnection): iExport<TDataConnection>;
begin
Result := Self;
if FileExists(ARQ) then
FArquivo.LoadFromFile(ARQ);
aValue.QueryVendaItens.First;
while not aValue.QueryVendaItens.Eof do
begin
FArquivo.Add(
Format('|C170|%d|%d|%s|%f|%f|%f|%f|%f|%f|',
[
aValue.QueryVendaItens.FieldByName('ID').AsInteger,
aValue.QueryVendaItens.FieldByName('VENDAID').AsInteger,
aValue.QueryVendaItens.FieldByName('PRODUTO').AsString,
aValue.QueryVendaItens.FieldByName('VALORUNITARIO').AsCurrency,
aValue.QueryVendaItens.FieldByName('QUANTIDADE').AsCurrency,
aValue.QueryVendaItens.FieldByName('SUBTOTAL').AsCurrency,
aValue.QueryVendaItens.FieldByName('ACRESCIMO').AsCurrency,
aValue.QueryVendaItens.FieldByName('DESCONTO').AsCurrency,
aValue.QueryVendaItens.FieldByName('TOTAL').AsCurrency
])
);
aValue.QueryVendaItens.Next;
end;
FArquivo.SaveToFile(ARQ);
end;
class function TSPEDC170.New: iExport<TDataConnection>;
begin
Result := Self.Create;
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_SoundAmbience
* Implements support for 3D sound ambience reverb effects
***********************************************************************************************************************
}
Unit TERRA_SoundAmbience;
{$I terra.inc}
Interface
Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF}
TERRA_String, TERRA_Utils, TERRA_Math, TERRA_Stream, TERRA_SoundSource;
Type
SoundAmbience = Class(TERRAObject)
Protected
_Name:TERRAString;
_Density: Single;
_Diffusion: Single;
_Gain: Single;
_GainHF: Single;
_GainLF: Single;
_DecayTime: Single;
_DecayHFRatio: Single;
_DecayLFRatio: Single;
_ReflectionsGain: Single;
_ReflectionsDelay: Single;
_ReflectionsPan: packed array[0..2] of Single;
_LateReverbGain: Single;
_LateReverbDelay: Single;
_LateReverbPan: packed array[0..2] of Single;
_EchoTime: Single;
_EchoDepth: Single;
_ModulationTime: Single;
_ModulationDepth: Single;
_AirAbsorptionGainHF: Single;
_HFReference: Single;
_LFReference: Single;
_RoomRolloffFactor: Single;
_DecayHFLimit: integer;
_EffectHandle:Integer;
_SlotHandle:Integer;
Procedure Update;
Public
Constructor Create;
Procedure Release; Override;
Function Load(Source:Stream):Boolean; Overload;
Function Load(Name:TERRAString):Boolean; Overload;
Function Save(Dest:Stream):Boolean;
Property Handle:Integer Read _SlotHandle;
End;
Implementation
Uses TERRA_ResourceManager, TERRA_FileManager, TERRA_SoundManager, TERRA_AL;
Const
// EAX Reverb effect parameters
AL_EAXREVERB_DENSITY = $0001;
AL_EAXREVERB_DIFFUSION = $0002;
AL_EAXREVERB_GAIN = $0003;
AL_EAXREVERB_GAINHF = $0004;
AL_EAXREVERB_GAINLF = $0005;
AL_EAXREVERB_DECAY_TIME = $0006;
AL_EAXREVERB_DECAY_HFRATIO = $0007;
AL_EAXREVERB_DECAY_LFRATIO = $0008;
AL_EAXREVERB_REFLECTIONS_GAIN = $0009;
AL_EAXREVERB_REFLECTIONS_DELAY = $000A;
AL_EAXREVERB_REFLECTIONS_PAN = $000B;
AL_EAXREVERB_LATE_REVERB_GAIN = $000C;
AL_EAXREVERB_LATE_REVERB_DELAY = $000D;
AL_EAXREVERB_LATE_REVERB_PAN = $000E;
AL_EAXREVERB_ECHO_TIME = $000F;
AL_EAXREVERB_ECHO_DEPTH = $0010;
AL_EAXREVERB_MODULATION_TIME = $0011;
AL_EAXREVERB_MODULATION_DEPTH = $0012;
AL_EAXREVERB_AIR_ABSORPTION_GAINHF = $0013;
AL_EAXREVERB_HFREFERENCE = $0014;
AL_EAXREVERB_LFREFERENCE = $0015;
AL_EAXREVERB_ROOM_ROLLOFF_FACTOR = $0016;
AL_EAXREVERB_DECAY_HFLIMIT = $0017;
{ SoundAmbience }
Function SoundAmbience.Load(Name:TERRAString):Boolean;
Var
Source:Stream;
Begin
If (Name='') Then
Begin
Result := False;
Exit;
End;
If Pos('.', Name)<=0 Then
Name := Name + '.afx';
If (Name = _Name) Then
Begin
Result := True;
Exit;
End;
Source := FileManager.Instance().OpenStream(Name);
If Assigned(Source) Then
Begin
Result := Load(Source);
ReleaseObject(Source);
End Else
Result := False;
_Name := Name;
End;
Function SoundAmbience.Load(Source: Stream): Boolean;
Begin
Source.Read(@_Density, 4);
Source.Read(@_Diffusion, 4);
Source.Read(@_Gain, 4);
Source.Read(@_GainHF, 4);
Source.Read(@_GainLF, 4);
Source.Read(@_DecayTime, 4);
Source.Read(@_DecayHFRatio, 4);
Source.Read(@_DecayLFRatio, 4);
Source.Read(@_ReflectionsGain, 4);
Source.Read(@_ReflectionsDelay, 4);
Source.Read(@_ReflectionsPan[0], 4);
Source.Read(@_ReflectionsPan[1], 4);
Source.Read(@_ReflectionsPan[2], 4);
Source.Read(@_LateReverbGain, 4);
Source.Read(@_LateReverbDelay, 4);
Source.Read(@_LateReverbPan[0], 4);
Source.Read(@_LateReverbPan[1], 4);
Source.Read(@_LateReverbPan[2], 4);
Source.Read(@_EchoTime, 4);
Source.Read(@_EchoDepth, 4);
Source.Read(@_ModulationTime, 4);
Source.Read(@_ModulationDepth, 4);
Source.Read(@_AirAbsorptionGainHF, 4);
Source.Read(@_HFReference, 4);
Source.Read(@_LFReference, 4);
Source.Read(@_RoomRolloffFactor, 4);
Source.Read(@_DecayHFLimit, 4);
Self.Update;
Result := True;
End;
Function SoundAmbience.Save(Dest: Stream): Boolean;
Begin
Dest.Write(@_Density, 4);
Dest.Write(@_Diffusion, 4);
Dest.Write(@_Gain, 4);
Dest.Write(@_GainHF, 4);
Dest.Write(@_GainLF, 4);
Dest.Write(@_DecayTime, 4);
Dest.Write(@_DecayHFRatio, 4);
Dest.Write(@_DecayLFRatio, 4);
Dest.Write(@_ReflectionsGain, 4);
Dest.Write(@_ReflectionsDelay, 4);
Dest.Write(@_ReflectionsPan[0], 4);
Dest.Write(@_ReflectionsPan[1], 4);
Dest.Write(@_ReflectionsPan[2], 4);
Dest.Write(@_LateReverbGain, 4);
Dest.Write(@_LateReverbDelay, 4);
Dest.Write(@_LateReverbPan[0], 4);
Dest.Write(@_LateReverbPan[1], 4);
Dest.Write(@_LateReverbPan[2], 4);
Dest.Write(@_EchoTime, 4);
Dest.Write(@_EchoDepth, 4);
Dest.Write(@_ModulationTime, 4);
Dest.Write(@_ModulationDepth, 4);
Dest.Write(@_AirAbsorptionGainHF, 4);
Dest.Write(@_HFReference, 4);
Dest.Write(@_LFReference, 4);
Dest.Write(@_RoomRolloffFactor, 4);
Dest.Write(@_DecayHFLimit, 4);
Result := False;
End;
Procedure SoundAmbience.Update;
Begin
If Not Assigned(alGenEffects) Then
Exit;
alEffectf(_EffectHandle, AL_EAXREVERB_DENSITY, _Density); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_DIFFUSION, _Diffusion); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_GAIN, _Gain); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_GAINHF, _GainHF); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_GAINLF, _GainLF); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_DECAY_TIME, _DecayTime); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_DECAY_HFRATIO, _DecayHFRatio); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_DECAY_LFRATIO, _DecayLFRatio); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_REFLECTIONS_GAIN, _ReflectionsGain); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_REFLECTIONS_DELAY, _ReflectionsDelay); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectfv(_EffectHandle, AL_EAXREVERB_REFLECTIONS_PAN, @_ReflectionsPan); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_LATE_REVERB_GAIN, _LateReverbGain); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_LATE_REVERB_DELAY, _LateReverbDelay); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectfv(_EffectHandle, AL_EAXREVERB_LATE_REVERB_PAN, @_LateReverbPan); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_ECHO_TIME, _EchoTime); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_ECHO_DEPTH, _EchoDepth); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_MODULATION_TIME, _ModulationTime); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_MODULATION_DEPTH, _ModulationDepth); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_AIR_ABSORPTION_GAINHF, _AirAbsorptionGainHF); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_HFREFERENCE, _HFReference); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_LFREFERENCE, _LFReference); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffectf(_EffectHandle, AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, _RoomRolloffFactor); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alEffecti(_EffectHandle, AL_EAXREVERB_DECAY_HFLIMIT, _DecayHFLimit); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
// Load Effect into Auxiliary Effect Slot
alAuxiliaryEffectSloti(_SlotHandle, AL_EFFECTSLOT_EFFECT, _EffectHandle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
End;
Constructor SoundAmbience.Create;
Begin
If Assigned(alGenEffects) Then
Begin
// Generate an Auxiliary Effect Slot
alGenAuxiliaryEffectSlots(1, @_SlotHandle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
// Generate an Effect
alGenEffects(1, @_EffectHandle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
// Set the Effect Type
alEffecti(_EffectHandle, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
End Else
Begin
_EffectHandle := 0;
_SlotHandle := 0;
End;
_Density := 1.0;
_Diffusion := 0.20999999344;
_Gain := 0.31622776389;
_GainHF := 0.10000000149;
_GainLF := 1.0;
_DecayTime := 1.4900000095;
_DecayHFRatio := 0.5;
_DecayLFRatio := 1.0;
_ReflectionsGain := 0.058479003608;
_ReflectionsDelay := 0.17900000513;
_ReflectionsPan[0] := 0.0;
_ReflectionsPan[1] := 0.0;
_ReflectionsPan[2] := 0.0;
_LateReverbGain := 0.10889300704;
_LateReverbDelay := 0.10000000149;
_LateReverbPan[0] := 0.0;
_LateReverbPan[1] := 0.0;
_LateReverbPan[2] := 0.0;
_EchoTime := 0.25;
_EchoDepth := 1.0;
_ModulationTime := 0.25;
_ModulationDepth := 0.0;
_AirAbsorptionGainHF := 0.99426007271;
_HFReference := 5000;
_LFReference := 250;
_RoomRolloffFactor := 0.0;
_DecayHFLimit := 0;
Self.Update;
End;
Procedure SoundAmbience.Release;
Var
I:Integer;
Begin
If (_SlotHandle<>0) Then
Begin
// Load NULL Effect into Effect Slot
alAuxiliaryEffectSloti(_SlotHandle, AL_EFFECTSLOT_EFFECT, AL_EFFECT_NULL); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
// Delete Auxiliary Effect Slot
alDeleteAuxiliaryEffectSlots(1, @_SlotHandle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
_SlotHandle := 0;
End;
// Delete Effect
If (_EffectHandle<>0) Then
Begin
alDeleteEffects(1, @_EffectHandle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
_EffectHandle := 0;
End;
End;
End. |
program statystyka;
{$APPTYPE CONSOLE}
uses
SysUtils, crt;
const
wersja = '0.2';
type
stat = record
c : char;
n : cardinal;
len : cardinal;
end;
var
n_freq : cardinal;
plot : boolean;
query : integer;
fname : string;
input : text;
stats : array[0..255] of stat;
total : cardinal;
ws_filter : boolean;
maxlen : cardinal; // ilosc miejsca zajmowana przez najdluzszy zapis statystyki
sort : boolean;
alphanum : boolean;
procedure print_help;
begin
writeln('Uzycie: statystyka [opcje] <plik_wejsciowy>');
writeln('Opcje:');
writeln(' -a, --alphanumeric pokazuje tylko statystyki znaków alfanumerycznych');
writeln(' -f <n>, --freq=<n> pokazuje n najczęściej występujących znaków');
writeln(' posortowanych wg częstotliwości wystąpień');
writeln(' -p, --plot rysuje wykres częstotliwości wystąpień');
writeln(' znaków');
writeln(' -q <znak>, --query=<znak> podaje szczegółowe statystyki dotyczące danego');
writeln(' znaku');
writeln(' -s, --sort sortuje wyniki rosnąco');
writeln(' -w, --whitespace nie pomija znaków niedrukowanych przy wypisywaniu statystyk');
writeln;
writeln('Autor: Leszek Godlewski <leszgod081@student.polsl.pl>');
end;
function parse_args : boolean;
var
i : integer;
begin
// inicjalizacja stanu opcji programu
parse_args := true;
n_freq := 0;
plot := false;
query := -1;
fname := '';
ws_filter := true;
sort := false;
alphanum := false;
i := 1;
while i <= ParamCount do begin
if ParamStr(i)[1] <> '-' then begin
fname := ParamStr(i);
exit;
end;
if ParamStr(i)[2] = '-' then begin
if pos('--freq=', ParamStr(i)) = 1 then begin
n_freq := strtoint(copy(ParamStr(i), 8, length(ParamStr(i)) - 7));
sort := true; // zadanie n najczesciej wystepujacych implikuje sortowanie
end else if pos('--plot', ParamStr(i)) = 1 then
plot := true
else if pos('--query=', ParamStr(i)) = 1 then
query := ord(ParamStr(i)[9])
else if pos('--whitespace', ParamStr(i)) = 1 then
ws_filter := false
else if pos('--sort', ParamStr(i)) = 1 then
sort := true
else if pos('--alphanumeric', ParamStr(i)) = 1 then
alphanum := true
else begin
parse_args := false;
exit;
end;
end else begin
case ParamStr(i)[2] of
'f' : begin
inc(i);
n_freq := strtoint(ParamStr(i));
sort := true; // zadanie n najczesciej wystepujacych implikuje sortowanie
end;
'p' : plot := true;
'q' : begin
inc(i);
query := ord(ParamStr(i)[1]);
end;
'w' : ws_filter := false;
's' : sort := true;
'a' : alphanum := true;
else begin
parse_args := false;
exit;
end; end;
end;
inc(i);
end;
end;
function open_file : boolean;
begin
open_file := true;
{$I-}
assign(input, fname);
reset(input);
{$I+}
if IOResult <> 0 then
open_file := false;
end;
procedure close_file;
begin
close(input);
end;
procedure count_char(c : char);
begin
if ws_filter and (ord(c) <= ord(' ')) then
exit;
if alphanum and not (c in ['A'..'Z', 'a'..'z', '0'..'9']) then
exit;
inc(stats[ord(c)].n);
inc(total);
end;
procedure parse_text;
var
line : string;
i : integer;
begin
// inicjalizujemy tablice
for i := 0 to 255 do begin
stats[i].c := chr(i);
stats[i].n := 0;
end;
total := 0;
while not eof(input) do begin
readln(input, line);
for i := 1 to length(line) do
count_char(line[i]);
end;
end;
procedure quicksort(var t : array of stat; l, r : integer);
var
pivot, i, j : integer;
b : stat;
begin
if l < r then begin
pivot := t[random(r - l) + l + 1].n; // losowanie elementu dzielacego
//pivot := t[(l + r) div 2].n;
i := l - 1;
j := r + 1;
repeat
repeat
i := i + 1
until pivot <= t[i].n;
repeat
j := j - 1
until pivot >= t[j].n;
b := t[i];
t[i] := t[j];
t[j] := b;
until i >= j;
t[j] := t[i];
t[i] := b;
quicksort(t, l, i - 1);
quicksort(t, i, r);
end;
end;
procedure calc_space(i : integer);
var
temp : integer;
frac : real;
begin
stats[i].len := 12; // stale elementy
// dlugosc liczby wystapien
temp := stats[i].n;
while temp div 10 > 0 do begin
temp := temp div 10;
inc(stats[i].len);
end;
if temp mod 10 > 0 then
inc(stats[i].len);
// dlugosc procentow
frac := stats[i].n / total;
if frac = 1.0 then
stats[i].len := stats[i].len + 3
else if frac >= 0.1 then
stats[i].len := stats[i].len + 2
else
stats[i].len := stats[i].len + 1;
// dlugosc znaku
if (ord(stats[i].c) > ord(' ')) and (ord(stats[i].c) <= 127) then
inc(stats[i].len) // 1 znak
else begin
// #XXX - kod ASCII
if ord(stats[i].c) > 99 then
stats[i].len := stats[i].len + 4
else if ord(stats[i].c) > 9 then
stats[i].len := stats[i].len + 3
else
stats[i].len := stats[i].len + 2;
end;
end;
procedure sort_stats;
var
i : integer;
begin
if sort then begin
randomize;
quicksort(stats, 0, 255);
end;
// przy okazji sprawdz, ile miejsca mamy do wykorzystania na wykres
maxlen := 0;
for i := 0 to 255 do begin
calc_space(i);
if stats[i].len > maxlen then
maxlen := stats[i].len
end;
end;
procedure print_single_stat(i : integer);
var
frac : real;
j, x : integer;
begin
frac := stats[i].n / total;
if (ord(stats[i].c) <= ord(' ')) or (ord(stats[i].c) > 127) then
write('#', ord(stats[i].c), ': ', stats[i].n, ' (', (frac * 100.0):0:2, '%) ')
else
write(stats[i].c, ': ', stats[i].n, ' (', (frac * 100.0):0:2, '%) ');
if not plot then begin
writeln;
exit;
end;
// rysujemy wykres
x := maxlen - stats[i].len;
for i := 1 to x do
write(' ');
write('[');
x := round(real(ScreenWidth - 1 - maxlen) * frac);
for j := 1 to x do
write('*');
x := round(real(ScreenWidth - 1 - maxlen) * (1.0 - frac));
for j := 1 to x do
write(' ');
writeln(']');
{ if x < (ScreenWidth - maxlen) then
writeln; // w przeciwnym wypadku kursor i tak przejdzie do nastepnej linii}
end;
procedure print_stats;
var
i, lim : integer;
percent : real;
begin
writeln('Długość tekstu: ', total, ' znaków');
if sort then begin
if n_freq > 0 then
lim := 255 - n_freq + 1
else
lim := 0;
for i := 255 downto lim do
if (stats[i].n > 0) and ((not alphanum) or (stats[i].c in ['A'..'Z', 'a'..'z', '0'..'9'])) then
print_single_stat(i);
end else for i := 0 to 255 do
if (stats[i].n > 0) and ((not alphanum) or (stats[i].c in ['A'..'Z', 'a'..'z', '0'..'9'])) then
print_single_stat(i);
end;
procedure print_query;
var
i : integer;
begin
for i := 0 to 255 do
if stats[i].c = chr(query) then begin
print_single_stat(i);
exit;
end;
end;
begin
writeln('Statystyka tekstów v', wersja);
if (ParamCount < 1) or not parse_args then begin
print_help;
exit;
end;
if not open_file then begin
writeln('Błąd przy otwieraniu pliku!');
exit;
end;
parse_text;
if total < 1 then begin
writeln('Plik wejściowy jest pusty.');
exit;
end;
close_file;
if query >= 0 then
print_query
else begin
sort_stats;
print_stats; begin
writeln;
end;
end;
writeln;
end.
|
unit Cover;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, ColoredGauge, Synchro, InternationalizerComponent;
type
TCoverForm = class(TForm)
CoverPanel: TPanel;
Backround: TImage;
StatusPanel: TPanel;
OverallProg: TColorGauge;
Comment: TLabel;
InternationalizerComponent1: TInternationalizerComponent;
WorldName: TLabel;
procedure CoverPanelResize(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
fCacheDir : string;
fCancelled : boolean;
public
property CacheDir : string read fCacheDir write fCacheDir;
public
procedure OnSyncNotify( SyncTask : TSyncTask; EventId : TSyncEventId; TaskDesc : string; Progress, OverallProgress : integer; out Cancel : boolean );
end;
var
CoverForm: TCoverForm;
implementation
{$R *.DFM}
uses
jpeg, Literals;
procedure TCoverForm.CoverPanelResize(Sender: TObject);
begin
StatusPanel.Top := Height - StatusPanel.Height;
end;
procedure TCoverForm.FormShow(Sender: TObject);
var
jpg : TJPEGImage;
tmp : TBitmap;
i : integer;
begin
jpg := TJPEGImage.Create;
try
jpg.LoadFromFile( CacheDir + 'otherimages\logonportal.jpg' );
tmp := TBitmap.Create;
try
tmp.Assign( jpg );
Backround.Picture.Bitmap := TBitmap.Create;
Backround.Picture.Bitmap.Width := Backround.Width;
Backround.Picture.Bitmap.Height := Backround.Height;
StretchBlt(
Backround.Picture.Bitmap.Canvas.Handle, 0, 0, Backround.Picture.Bitmap.Width, Backround.Picture.Bitmap.Height,
tmp.Canvas.Handle, 0, 0, tmp.Width, tmp.Height, SRCCOPY );
with Backround.Picture.Bitmap.Canvas do
begin
Pen.Color := clBlack;
Pen.Style := psSolid;
for i := 0 to pred(Backround.Picture.Bitmap.Height) div 2 do
begin
MoveTo( 0, 2*i );
LineTo( Backround.Picture.Bitmap.Width, 2*i );
end;
end;
finally
tmp.Free;
end;
finally
jpg.Free;
end;
end;
procedure TCoverForm.OnSyncNotify( SyncTask : TSyncTask; EventId : TSyncEventId; TaskDesc : string; Progress, OverallProgress : integer; out Cancel : boolean );
begin
Comment.Caption := GetLiteral('Literal26');
OverallProg.Position := OverallProgress;
Application.ProcessMessages;
Cancel := fCancelled;
end;
procedure TCoverForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := true;
fCancelled := true;
end;
end.
|
unit DDrawD3DManager;
interface
uses
Windows, DirectDraw, Direct3D, D3DXCore;
type
TDDrawD3DManager =
class
public
constructor Create(MainWindow : HWND; ScreenWidth, ScreenHeight : integer);
destructor Destroy; override;
private
function InitD3DX : HRESULT;
function ReleaseD3DX : HRESULT;
function InitRenderer : HRESULT;
public
function CreateCompatibleOffscreenSurface(width, height : integer) : IDirectDrawSurface7;
function CreateOffscreenSurface(width, height, bppixel : integer) : IDirectDrawSurface7;
function CreateTextureSurface(width, height, bppixel : integer; managed : boolean) : IDirectDrawSurface7;
function CreatePalette(palentries : pointer) : IDirectDrawPalette;
private
fMainWindow : HWND;
fScreenWidth : integer;
fScreenHeight : integer;
fD3DXContext : ID3DXContext;
fDirectDraw : IDirectDraw7;
fDirect3D : IDirect3D7;
fDirect3DDevice : IDirect3DDevice7;
fPrimarySurface : IDirectDrawSurface7;
fBackBuffer : IDirectDrawSurface7;
fD3DXReady : boolean;
fD3DDeviceCaps : TD3DDeviceDesc7;
public
property D3DXContext : ID3DXContext read fD3DXContext;
property DirectDraw : IDirectDraw7 read fDirectDraw;
property Direct3D : IDirect3D7 read fDirect3D;
property Direct3DDevice : IDirect3DDevice7 read fDirect3DDevice;
property PrimarySurface : IDirectDrawSurface7 read fPrimarySurface;
property BackBuffer : IDirectDrawSurface7 read fBackBuffer;
end;
var
DDrawD3DMgr : TDDrawD3DManager;
procedure InitDDrawD3D(MainWindow : HWND; ScreenWidth, ScreenHeight : integer);
procedure ReleaseDDrawD3D;
implementation
uses
SysUtils, D3DXErr, DirectDrawUtils;
// Utilities
procedure SetPixFormat(BitCount : dword; var Dest : TDDPixelFormat );
begin
with Dest do
begin
// TODO 1 -oJRG -cGraphics : Tengo que aņadir soporte para el formato BGR!!
dwSize := sizeof( TDDPixelFormat );
dwFourCC := 0;
dwRGBBitCount := BitCount;
case BitCount of
1 :
dwFlags := DDPF_RGB or DDPF_PALETTEINDEXED1;
2 :
dwFlags := DDPF_RGB or DDPF_PALETTEINDEXED2;
4 :
dwFlags := DDPF_RGB or DDPF_PALETTEINDEXED4;
8 :
dwFlags := DDPF_RGB or DDPF_PALETTEINDEXED8;
15 :
begin
dwFlags := DDPF_RGB;
dwRGBBitCount := 16;
dwRBitMask := $7C00;
dwGBitMask := $03E0;
dwBBitMask := $001F;
dwRGBAlphaBitMask := 0;
end;
16 :
begin
dwFlags := DDPF_RGB;
dwRBitMask := $F800;
dwGBitMask := $07E0;
dwBBitMask := $001F;
dwRGBAlphaBitMask := 0;
end;
24 :
begin
dwFlags := DDPF_RGB;
dwRBitMask := $FF0000;
dwGBitMask := $00FF00;
dwBBitMask := $0000FF;
dwRGBAlphaBitMask := 0;
end;
// 24 :
// begin
// dwFlags := DDPF_RGB;
// dwRBitMask := $0000FF;
// dwGBitMask := $00FF00;
// dwBBitMask := $FF0000;
// dwRGBAlphaBitMask := 0;
// end;
32 :
begin
dwFlags := DDPF_RGB;
dwRBitMask := $FF0000;
dwGBitMask := $00FF00;
dwBBitMask := $0000FF;
dwRGBAlphaBitMask := 0;
end;
// 32 :
// begin
// dwFlags := DDPF_RGB;
// dwRBitMask := $0000FF;
// dwGBitMask := $00FF00;
// dwBBitMask := $FF0000;
// dwRGBAlphaBitMask := 0;
// end;
end;
end;
end;
// TDDrawD3DManager
constructor TDDrawD3DManager.Create(MainWindow : HWND; ScreenWidth, ScreenHeight : integer);
begin
inherited Create;
fMainWindow := MainWindow;
fScreenWidth := ScreenWidth;
fScreenHeight := ScreenHeight;
if Failed(InitD3DX)
then raise Exception.Create('D3DX Initialization failed!');
end;
destructor TDDrawD3DManager.Destroy;
begin
ReleaseD3DX;
end;
function TDDrawD3DManager.InitD3DX : HRESULT;
var
hr : HRESULT;
dwDevice : dword;
dwDeviceCount : dword;
dev : TD3DX_DEVICEDESC;
d3dDesc : TD3DDEVICEDESC7;
devDesc : TD3DX_DEVICEDESC;
begin
hr := D3DXInitialize;
if Succeeded(hr)
then
begin
// Look for fastest device which supports the desired blending for sprites
dwDeviceCount := D3DXGetDeviceCount;
dev.deviceIndex := D3DX_DEFAULT;
dev.hwLevel := D3DX_DEFAULT;
dev.onPrimary := TRUE;
for dwDevice := 0 to pred(dwDeviceCount) do
begin
if Succeeded(D3DXGetDeviceCaps(dwDevice, nil, @d3dDesc, nil, nil))
then
if (((d3dDesc.dpcTriCaps.dwSrcBlendCaps and D3DPBLENDCAPS_SRCALPHA) <> 0) and
((d3dDesc.dpcTriCaps.dwDestBlendCaps and D3DPBLENDCAPS_INVSRCALPHA) <> 0) and
((d3dDesc.dpcTriCaps.dwTextureFilterCaps and D3DPTFILTERCAPS_LINEAR) <> 0) and
((d3dDesc.dpcTriCaps.dwTextureBlendCaps and D3DPTBLENDCAPS_MODULATE) <> 0))
then
if Succeeded(D3DXGetDeviceDescription(dwDevice, devDesc))
then
if (D3DX_DEFAULT = dev.hwLevel) or
(dev.hwLevel > devDesc.hwLevel) or
(dev.hwLevel = devDesc.hwLevel) and (devDesc.onPrimary)
then dev := devDesc;
end;
if D3DX_DEFAULT = dev.hwLevel
then hr := D3DXERR_NODIRECT3DDEVICEAVAILABLE
else
begin
hr := D3DXCreateContext(
dev.hwLevel, // D3DX device
D3DX_CONTEXT_FULLSCREEN, // flags
fMainWindow, // Main window
fScreenWidth, // width
fScreenHeight, // height
fD3DXContext); // returned D3DX interface
if Succeeded(hr)
then
begin
fD3DXReady := true;
hr := InitRenderer;
end;
end;
end;
Result := hr;
end;
function TDDrawD3DManager.ReleaseD3DX : HRESULT;
begin
fBackBuffer := nil;
fPrimarySurface := nil;
fDirectDraw := nil;
fDirect3DDevice := nil;
fDirect3D := nil;
fD3DXContext := nil;
Result := D3DXUninitialize;
end;
function TDDrawD3DManager.InitRenderer : HRESULT;
begin
if fD3DXReady
then
begin
fDirectDraw := IDirectDraw7(fD3DXContext.GetDD); // >>> this a temporary patch
fPrimarySurface := IDirectDrawSurface7(fD3DXContext.GetPrimary);
fBackBuffer := IDirectDrawSurface7(fD3DXContext.GetBackBuffer(0));
fDirect3DDevice := IDirect3DDevice7(fD3DXContext.GetD3DDevice);
fDirect3DDevice.GetCaps(fD3DDeviceCaps);
if fDirect3DDevice <> nil
then
begin
fDirectDraw := IDirectDraw7(fD3DXContext.GetDD);
if fDirectDraw <> nil
then
begin
// Enable dither, specular, lighting and z-buffer usage
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_COLORKEYENABLE, 1);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_DITHERENABLE, 0);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_SPECULARENABLE, 0);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_LIGHTING, 0);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_ZENABLE, 0);
// Enable vertices to have colors
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_COLORVERTEX, 0);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_DIFFUSEMATERIALSOURCE, 0);
// Set the background to bright blue (red/green/blue/alpha)
fD3DXContext.SetClearColor(TD3DCOLOR(D3DRGBA(0.0, 0.0, 0.0, 0.0)));
fD3DXContext.Clear(D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER);
Result := S_OK;
end
else Result := E_FAIL;
end
else Result := E_FAIL;
end
else Result := E_FAIL;
end;
function TDDrawD3DManager.CreateCompatibleOffscreenSurface(width, height : integer) : IDirectDrawSurface7;
var
ddsd : TDDSurfaceDesc2;
begin
Result := nil;
InitRecord(ddsd, sizeof(ddsd));
with ddsd do
begin
dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH;
ddsCaps.dwCaps := DDSCAPS_OFFSCREENPLAIN;
dwWidth := Width;
dwHeight := Height;
end;
fDirectDraw.CreateSurface(ddsd, Result, nil);
end;
function TDDrawD3DManager.CreateOffscreenSurface(width, height, bppixel : integer) : IDirectDrawSurface7;
var
ddsd : TDDSurfaceDesc2;
begin
InitRecord(ddsd, sizeof(ddsd));
with ddsd do
begin
dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_PIXELFORMAT;
ddsCaps.dwCaps := DDSCAPS_OFFSCREENPLAIN or DDSCAPS_SYSTEMMEMORY;
dwWidth := Width;
dwHeight := Height;
SetPixFormat(bppixel, ddpfPixelFormat);
end;
fDirectDraw.CreateSurface(ddsd, Result, nil);
end;
function TDDrawD3DManager.CreateTextureSurface(width, height, bppixel : integer; managed : boolean) : IDirectDrawSurface7;
var
ddsd : TDDSurfaceDesc2;
begin
Result := nil;
InitRecord(ddsd, sizeof(ddsd));
with ddsd do
begin
dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_PIXELFORMAT or DDSD_TEXTURESTAGE;
ddsCaps.dwCaps := DDSCAPS_TEXTURE;
if managed
then ddsCaps.dwCaps2 := DDSCAPS2_TEXTUREMANAGE;
dwWidth := Width;
dwHeight := Height;
SetPixFormat(bppixel, ddpfPixelFormat);
if (fD3DDeviceCaps.dpcTriCaps.dwTextureCaps and D3DPTEXTURECAPS_POW2) <> 0
then
begin
dwWidth := 1;
while width > dwWidth do
dwWidth := dwWidth shl 1;
dwHeight := 1;
while height > dwHeight do
dwHeight := dwHeight shl 1;
end;
if (fD3DDeviceCaps.dpcTriCaps.dwTextureCaps and D3DPTEXTURECAPS_SQUAREONLY) <> 0
then
if dwWidth > dwHeight
then dwHeight := dwWidth
else dwWidth := dwHeight;
end;
fDirectDraw.CreateSurface(ddsd, Result, nil);
end;
function TDDrawD3DManager.CreatePalette(palentries : pointer) : IDirectDrawPalette;
begin
fDirectDraw.CreatePalette(DDPCAPS_8BIT or DDPCAPS_ALLOW256, palentries, Result, nil);
end;
procedure InitDDrawD3D(MainWindow : HWND; ScreenWidth, ScreenHeight : integer);
begin
DDrawD3DMgr := TDDrawD3DManager.Create(MainWindow, ScreenWidth, ScreenHeight);
end;
procedure ReleaseDDrawD3D;
begin
DDrawD3DMgr.Free;
end;
end.
|
(*
* InIOCP 客户端连接、发送线程、接收线程、投放线程 类
* TInConnection、TInWSConnection 从 TBaseConnection 继承
* TInStreamConnection 未实现
*)
unit iocp_clientBase;
interface
{$I in_iocp.inc}
uses
{$IFDEF DELPHI_XE7UP}
Winapi.Windows, System.Classes, System.SysUtils, Vcl.ExtCtrls, {$ELSE}
Windows, Classes, SysUtils, ExtCtrls, {$ENDIF}
iocp_base, iocp_baseObjs, iocp_Winsock2, iocp_utils, iocp_wsExt,
iocp_lists, iocp_msgPacks, iocp_WsJSON, iocp_api,
iocp_senders, iocp_receivers;
type
// 线程基类
TBaseSendThread = class;
TBaseRecvThread = class;
TBasePostThread = class;
// 消息收发事件
TRecvSendEvent = procedure(Sender: TObject; MsgId: TIOCPMsgId;
TotalSize, CurrentSize: TFileSize) of object;
// 异常事件
TExceptEvent = procedure(Sender: TObject; const Msg: string) of object;
TBaseConnection = class(TComponent)
private
FAutoConnected: Boolean; // 是否自动连接
FLocalPath: String; // 下载文件的本地存放路径
FURL: String; // 请求资源
FServerAddr: String; // 服务器地址
FServerPort: Word; // 服务端口
FAfterConnect: TNotifyEvent; // 连接后
FAfterDisconnect: TNotifyEvent; // 断开后
FBeforeConnect: TNotifyEvent; // 连接前
FBeforeDisconnect: TNotifyEvent; // 断开前
FOnDataReceive: TRecvSendEvent; // 消息接收事件
FOnDataSend: TRecvSendEvent; // 消息发出事件
FOnError: TExceptEvent; // 异常事件
function GetActive: Boolean;
function GetURL: String;
procedure CreateTimer;
procedure Disconnect;
procedure InternalOpen;
procedure InternalClose;
procedure SetActive(Value: Boolean);
procedure TimerEvent(Sender: TObject);
protected
FSendThread: TBaseSendThread; // 发送线程
FRecvThread: TBaseRecvThread; // 接收线程
FPostThread: TBasePostThread; // 投放线程
FSocket: TSocket; // 套接字
FTimer: TTimer; // 定时器
FActive: Boolean; // 开关/连接状态
FErrorcode: Integer; // 异常代码
FInitFlag: AnsiString; // 初始化服务端的字符串
FInMainThread: Boolean; // 进入主线程
FRecvCount: Cardinal; // 收到总数
FSendCount: Cardinal; // 发送总数
procedure Loaded; override;
protected
procedure DoClientError;
procedure DoServerError; virtual; abstract;
procedure InterBeforeConnect; virtual; abstract;
procedure InterAfterConnect; virtual; abstract; // 子类初始化资源
procedure InterAfterDisconnect; virtual; abstract; // 子类释放资源
procedure RecvMsgProgress; virtual;
procedure SendMsgProgress; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
protected
property URL: String read GetURL write FURL;
public
property Errorcode: Integer read FErrorcode;
property PostThread: TBasePostThread read FPostThread;
property RecvCount: Cardinal read FRecvCount;
property SendCount: Cardinal read FSendCount;
property SendThread: TBaseSendThread read FSendThread;
property Socket: TSocket read FSocket;
published
property Active: Boolean read GetActive write SetActive default False;
property AutoConnected: Boolean read FAutoConnected write FAutoConnected default False;
property LocalPath: string read FLocalPath write FLocalPath;
property ServerAddr: string read FServerAddr write FServerAddr;
property ServerPort: Word read FServerPort write FServerPort default DEFAULT_SVC_PORT;
published
property AfterConnect: TNotifyEvent read FAfterConnect write FAfterConnect;
property AfterDisconnect: TNotifyEvent read FAfterDisconnect write FAfterDisconnect;
property BeforeConnect: TNotifyEvent read FBeforeConnect write FBeforeConnect;
property BeforeDisconnect: TNotifyEvent read FBeforeDisconnect write FBeforeDisconnect;
property OnDataReceive: TRecvSendEvent read FOnDataReceive write FOnDataReceive;
property OnDataSend: TRecvSendEvent read FOnDataSend write FOnDataSend;
property OnError: TExceptEvent read FOnError write FOnError;
end;
// =================== 发送线程 类 ===================
// 消息编号数组
TMsgIdArray = array of TIOCPMsgId;
TBaseSendThread = class(TCycleThread)
private
FLock: TThreadLock; // 线程锁
FMsgList: TInList; // 待发消息包列表
FCancelIds: TMsgIdArray; // 分块传输时待取消的消息编号数组
FEventMode: Boolean; // 等待事件模式
FGetFeedback: Integer; // 收到服务器反馈
FWaitState: Integer; // 等待反馈状态
FWaitSemaphore: THandle; // 等待服务器反馈的信号灯
function ClearList: Integer;
function GetCount: Integer;
function GetWork: Boolean;
procedure AddCancelMsgId(MsgId: TIOCPMsgId);
procedure ClearCancelMsgId(MsgId: TIOCPMsgId);
protected
FConnection: TBaseConnection; // 连接
FPostThread: TBasePostThread; // 提交线程
FSender: TClientTaskSender; // 消息发送器
FSendMsg: TBasePackObject; // 当前发出消息
FSendCount: TFileSize; // 当前发出数
FTotalSize: TFileSize; // 当前消息总长度
function GetWorkState: Boolean;
function InCancelArray(MsgId: TIOCPMsgId): Boolean;
procedure AfterWork; override;
procedure DoThreadMethod; override;
procedure IniWaitState;
procedure KeepWaiting;
procedure WaitForFeedback;
procedure OnDataSend(Msg: TBasePackObject; Part: TMessagePart; OutSize: Integer);
procedure OnSendError(IOType: TIODataType; ErrorCode: Integer);
protected
function ChunkRequest(Msg: TBasePackObject): Boolean; virtual;
procedure InterSendMsg(RecvThread: TBaseRecvThread); virtual; abstract;
public
constructor Create(AConnection: TBaseConnection; EventMode: Boolean);
procedure AddWork(Msg: TBasePackObject); virtual;
procedure CancelWork(MsgId: TIOCPMsgId);
procedure ClearAllWorks(var ACount: Integer);
procedure ServerFeedback(Accept: Boolean = False); virtual;
public
property Count: Integer read GetCount;
end;
// ================= 推送结果的线程 类 ===============
// 保存接收到的消息到列表,逐一塞进应用层
TBasePostThread = class(TCycleThread)
protected
FConnection: TBaseConnection; // 连接
FSendThread: TBaseSendThread; // 发送线程
FLock: TThreadLock; // 线程锁
FMsgList: TInList; // 收到的消息列表
FSendMsg: TBasePackObject; // 发送线程的当前消息
procedure AfterWork; override;
procedure DoThreadMethod; override;
procedure SetSendMsg(Msg: TBasePackObject);
protected
procedure HandleMessage(Msg: TBasePackObject); virtual; abstract; // 子类实现
public
constructor Create(AConnection: TBaseConnection);
procedure Add(Msg: TBasePackObject); virtual;
end;
// =================== 接收线程 类 ===================
TBaseRecvThread = class(TThread)
protected
FConnection: TBaseConnection; // 连接
FOverlapped: TOverlapped; // 重叠结构
FRecvBuf: TWsaBuf; // 接收缓存
FReceiver: TBaseReceiver; // 数据接收器
FRecvMsg: TBasePackObject; // 当前的接收消息
FRecvCount: TFileSize; // 当前发出数
FTotalSize: TFileSize; // 当前消息总长度
protected
procedure Execute; override;
procedure HandleDataPacket; virtual; // 接收消息数据
procedure OnCreateMsgObject(Msg: TBasePackObject);
procedure OnDataReceive(Msg: TBasePackObject; Part: TMessagePart; RecvCount: Cardinal); virtual;
procedure OnRecvError(Msg: TBasePackObject; ErrorCode: Integer);
public
constructor Create(AConnection: TBaseConnection; AReceiver: TBaseReceiver);
procedure Stop;
end;
const
ERR_SEND_DATA = -1; // 客户端:发送异常
ERR_USER_CANCEL = -2; // 客户端:用户取消操作
ERR_NO_ANWSER = -3; // 客户端:服务器无应答.
ERR_CHECK_CODE = -4; // 客户端:接收异常.
implementation
{ TBaseConnection }
constructor TBaseConnection.Create(AOwner: TComponent);
begin
inherited;
FSocket := INVALID_SOCKET; // 无效 Socket
FServerPort := DEFAULT_SVC_PORT; // 默认端口
end;
procedure TBaseConnection.CreateTimer;
begin
// 建定时器(关闭连接用)
FTimer := TTimer.Create(Self);
FTimer.Enabled := False;
FTimer.Interval := 50;
FTimer.OnTimer := TimerEvent;
end;
destructor TBaseConnection.Destroy;
begin
SetActive(False);
inherited;
end;
procedure TBaseConnection.Disconnect;
begin
// 尝试关闭客户端
if Assigned(FTimer) then
FTimer.Enabled := True;
end;
procedure TBaseConnection.DoClientError;
begin
// 出现致命异常 -> 断开
try
if Assigned(OnError) then
case FErrorCode of
ERR_SEND_DATA:
OnError(Self, '发送异常.');
ERR_USER_CANCEL:
OnError(Self, '用户取消操作.');
ERR_NO_ANWSER:
OnError(Self, '服务器无应答.');
ERR_CHECK_CODE:
OnError(Self, '接收数据异常.');
else
OnError(Self, GetWSAErrorMessage(FErrorCode));
end;
finally
Disconnect; // 自动断开
end;
end;
function TBaseConnection.GetActive: Boolean;
begin
if (csDesigning in ComponentState) or (csLoading in ComponentState) then
Result := FActive
else
Result := (FSocket <> INVALID_SOCKET) and FActive;
end;
function TBaseConnection.GetURL: String;
begin
if (FURL = '') or (FURL = '/') then
Result := '/'
else
if (FURL[1] <> '/') then
Result := '/' + FURL
else
Result := FURL;
end;
procedure TBaseConnection.InternalClose;
begin
// 断开连接
if Assigned(FBeforeDisConnect) and not (csDestroying in ComponentState) then
FBeforeDisConnect(Self);
if (FSocket <> INVALID_SOCKET) then
begin
// 关闭 Socket
FActive := False;
try
iocp_Winsock2.ShutDown(FSocket, SD_BOTH);
iocp_Winsock2.CloseSocket(FSocket);
finally
FSocket := INVALID_SOCKET;
end;
// 断开,释放子类资源
InterAfterDisconnect;
// 释放接收线程
if Assigned(FRecvThread) then
begin
FRecvThread.Stop; // 100 毫秒后退出
FRecvThread := nil;
end;
// 释放投放线程
if Assigned(FPostThread) then
begin
FPostThread.Stop;
FPostThread := nil;
end;
// 释放发送线程
if Assigned(FSendThread) then
begin
FSendThread.ServerFeedback;
FSendThread.Stop;
FSendThread := nil;
end;
// 释放定时器
if Assigned(FTimer) then
begin
FTimer.Free;
FTimer := nil;
end;
end;
if Assigned(FAfterDisconnect) and not (csDestroying in ComponentState) then
FAfterDisconnect(Self);
end;
procedure TBaseConnection.InternalOpen;
begin
// 创建 WSASocket,连接到服务器
if Assigned(FBeforeConnect) and not (csDestroying in ComponentState) then
FBeforeConnect(Self);
FActive := False;
if (FSocket = INVALID_SOCKET) then
begin
// 准备 FInitFlag
InterBeforeConnect;
// 建 Socket
FSocket := iocp_Winsock2.WSASocket(AF_INET, SOCK_STREAM,
IPPROTO_TCP, nil, 0, WSA_FLAG_OVERLAPPED);
if iocp_utils.ConnectSocket(FSocket, FServerAddr, FServerPort) then // 连接成功
begin
// 定时器
CreateTimer;
// 心跳
iocp_wsExt.SetKeepAlive(FSocket);
if (FInitFlag <> '') then // 发送客户端标志 FInitFlag,服务端转换/准备资源
iocp_Winsock2.Send(FSocket, FInitFlag[1], Length(FInitFlag), 0);
// 连接,设置资源(提交线程在子类建)
InterAfterConnect;
FSendThread.FPostThread := FPostThread;
FPostThread.FSendThread := FSendThread;
FActive := True; // 激活
FRecvCount := 0; // 接收数
FSendCount := 0; // 发出数
end else
try
iocp_Winsock2.ShutDown(FSocket, SD_BOTH);
iocp_Winsock2.CloseSocket(FSocket);
finally
FSocket := INVALID_SOCKET;
end;
end;
if not (csDestroying in ComponentState) then
if FActive then
begin
if Assigned(FAfterConnect) then
FAfterConnect(Self);
end else
if Assigned(FOnError) then
FOnError(Self, '无法连接到服务器.');
end;
procedure TBaseConnection.Loaded;
begin
inherited;
// 如果设计时 FActive = True,装载后 -> 连接
if FActive and not (csDesigning in ComponentState) then
InternalOpen;
end;
procedure TBaseConnection.RecvMsgProgress;
begin
// 显示接收进程
if Assigned(FOnDataReceive) then
try
FOnDataReceive(Self, FRecvThread.FRecvMsg.MsgId,
FRecvThread.FTotalSize, FRecvThread.FRecvCount);
except
raise;
end;
end;
procedure TBaseConnection.SendMsgProgress;
begin
// 显示发送进程(主体、附件各一次 100%)
if Assigned(FOnDataSend) then
try
FOnDataSend(Self, FSendThread.FSendMsg.MsgId,
FSendThread.FTotalSize, FSendThread.FSendCount);
except
raise;
end;
end;
procedure TBaseConnection.SetActive(Value: Boolean);
begin
if Value <> FActive then
if (csDesigning in ComponentState) or (csLoading in ComponentState) then
FActive := Value
else
if Value and not FActive then
InternalOpen
else
if not Value and FActive then
begin
if FInMainThread then // 正在主线程运行
FTimer.Enabled := True
else
InternalClose;
end;
end;
procedure TBaseConnection.TimerEvent(Sender: TObject);
begin
FTimer.Enabled := False;
InternalClose; // 断开连接
end;
{ TBaseSendThread }
procedure TBaseSendThread.AddCancelMsgId(MsgId: TIOCPMsgId);
var
i: Integer;
Exists: Boolean;
begin
// 加入待取消的消息编号 MsgId
Exists := False;
if (FCancelIds <> nil) then
for i := 0 to High(FCancelIds) do
if (FCancelIds[i] = MsgId) then
begin
Exists := True;
Break;
end;
if (Exists = False) then
begin
SetLength(FCancelIds, Length(FCancelIds) + 1);
FCancelIds[High(FCancelIds)] := MsgId;
end;
end;
procedure TBaseSendThread.AddWork(Msg: TBasePackObject);
begin
FLock.Acquire;
try
FMsgList.Add(Msg);
finally
FLock.Release;
end;
Activate; // 激活线程
end;
procedure TBaseSendThread.AfterWork;
begin
inherited;
// 释放资源
CloseHandle(FWaitSemaphore);
ClearList;
FLock.Free;
FMsgList.Free;
FSender.Free;
end;
procedure TBaseSendThread.CancelWork(MsgId: TIOCPMsgId);
var
i, k: Integer;
Msg: TBasePackObject;
begin
// 取消发送,编号 = MsgId
FLock.Acquire;
try
if Assigned(FSendMsg) and
ChunkRequest(FSendMsg) and (FSendMsg.MsgId = MsgId) then
begin
FSender.Stoped := True;
ServerFeedback;
end else
begin
k := FMsgList.Count;
for i := 0 to k - 1 do
begin
Msg := TBasePackObject(FMsgList.PopFirst);
if (Msg.MsgId = MsgId) then
Msg.Free
else // 从新加入
FMsgList.Add(Msg);
end;
if (k = FMsgList.Count) then // 可能是续传
AddCancelMsgId(MsgId);
end;
finally
FLock.Release;
end;
end;
function TBaseSendThread.ChunkRequest(Msg: TBasePackObject): Boolean;
begin
Result := False;
end;
procedure TBaseSendThread.ClearAllWorks(var ACount: Integer);
begin
// 清空待发消息
FLock.Acquire;
try
ACount := ClearList; // 取消总数
finally
FLock.Release;
end;
end;
procedure TBaseSendThread.ClearCancelMsgId(MsgId: TIOCPMsgId);
var
i: Integer;
begin
// 清除数组内的消息编号 MsgId
if (FCancelIds <> nil) then
for i := 0 to High(FCancelIds) do
if (FCancelIds[i] = MsgId) then
begin
FCancelIds[i] := 0; // 清除
Break;
end;
end;
function TBaseSendThread.ClearList: Integer;
var
i: Integer;
begin
// 释放列表的全部消息(在外加锁)
Result := FMsgList.Count;
for i := 0 to Result - 1 do
TBasePackObject(FMsgList.PopFirst).Free;
end;
constructor TBaseSendThread.Create(AConnection: TBaseConnection; EventMode: Boolean);
begin
inherited Create(True); // 内置信号灯
FConnection := AConnection;
FEventMode := EventMode;
FLock := TThreadLock.Create; // 锁
FMsgList := TInList.Create; // 待发任务表
FSender := TClientTaskSender.Create; // 任务发送器
FSender.Socket := FConnection.FSocket; // 发送套接字
FSender.OnDataSend := OnDataSend; // 发出事件
FSender.OnError := OnSendError; // 发出异常事件
// 信号灯
FWaitSemaphore := CreateSemaphore(Nil, 0, 1, Nil);
end;
procedure TBaseSendThread.DoThreadMethod;
function NoServerFeedback: Boolean;
begin
{$IFDEF ANDROID_MODE}
FLock.Acquire;
try
Dec(FGetFeedback);
Result := (FGetFeedback < 0);
finally
FLock.Release;
end;
{$ELSE}
Result := (InterlockedDecrement(FGetFeedback) < 0);
{$ENDIF}
end;
begin
// 取发送任务 -> 发送
while not Terminated and FConnection.FActive and GetWork() do
try
try
FPostThread.SetSendMsg(FSendMsg);
InterSendMsg(FConnection.FRecvThread); // 在子类发送
finally
FLock.Acquire;
try
FreeAndNil(FSendMsg); // 不要在子类释放
finally
FLock.Release;
end;
if FEventMode and NoServerFeedback() then // 等待事件模式, 服务器无应答
begin
FConnection.FErrorcode := ERR_NO_ANWSER;
Synchronize(FConnection.DoClientError);
end;
end;
except
on E: Exception do
begin
FConnection.FErrorcode := GetLastError;
Synchronize(FConnection.DoClientError);
end;
end;
end;
function TBaseSendThread.GetCount: Integer;
begin
// 取任务数
FLock.Acquire;
try
Result := FMsgList.Count;
finally
FLock.Release;
end;
end;
function TBaseSendThread.GetWork: Boolean;
begin
// 从列表中取一个消息
FLock.Acquire;
try
if Terminated or (FMsgList.Count = 0) then
begin
FSendMsg := nil;
Result := False;
end else
begin
FSendMsg := TBasePackObject(FMsgList.PopFirst); // 取任务
FSender.Stoped := False;
Result := True;
end;
finally
FLock.Release;
end;
end;
function TBaseSendThread.GetWorkState: Boolean;
begin
// 取工作状态:线程、发送器未停止
FLock.Acquire;
try
Result := (Terminated = False) and (FSender.Stoped = False);
finally
FLock.Release;
end;
end;
function TBaseSendThread.InCancelArray(MsgId: TIOCPMsgId): Boolean;
var
i: Integer;
begin
// 检查是否要停止
FLock.Acquire;
try
Result := False;
if (FCancelIds <> nil) then
for i := 0 to High(FCancelIds) do
if (FCancelIds[i] = MsgId) then
begin
Result := True;
Break;
end;
finally
FLock.Release;
end;
end;
procedure TBaseSendThread.IniWaitState;
begin
// 初始化等待状态
{$IFDEF ANDROID_MODE}
FLock.Acquire;
try
FGetFeedback := 0;
FWaitState := 0;
finally
FLock.Release;
end;
{$ELSE}
InterlockedExchange(FGetFeedback, 0); // 未收到反馈
InterlockedExchange(FWaitState, 0); // 状态=0
{$ENDIF}
end;
procedure TBaseSendThread.KeepWaiting;
begin
// 继续等待: FWaitState = 1 -> +1
{$IFDEF ANDROID_MODE}
FLock.Acquire;
try
Inc(FGetFeedback);
if (FWaitState = 2) then
begin
FWaitState := 1;
ReleaseSemaphore(FWaitSemaphore, 1, Nil); // 触发
end;
finally
FLock.Release;
end;
{$ELSE}
InterlockedIncrement(FGetFeedback); // 收到反馈
if (iocp_api.InterlockedCompareExchange(FWaitState, 2, 1) = 1) then // 状态+
ReleaseSemaphore(FWaitSemaphore, 1, Nil); // 触发
{$ENDIF}
end;
procedure TBaseSendThread.OnDataSend(Msg: TBasePackObject; Part: TMessagePart; OutSize: Integer);
begin
// 显示发送进程
Inc(FSendCount, OutSize);
Synchronize(FConnection.SendMsgProgress);
end;
procedure TBaseSendThread.OnSendError(IOType: TIODataType; ErrorCode: Integer);
begin
// 处理发送异常
if (GetWorkState = False) then
ServerFeedback; // 忽略等待
FConnection.FErrorcode := ErrorCode;
Synchronize(FConnection.DoClientError); // 线程同步
end;
procedure TBaseSendThread.ServerFeedback(Accept: Boolean);
begin
// 服务器反馈 或 忽略等待
// 1. 取消任务后收到反馈
// 2. 收到反馈,而未等待
// (多线程的调度执行先后不确定,可能已经反馈,但未执行到等待命令)
{$IFDEF ANDROID_MODE}
FLock.Acquire;
try
Inc(FGetFeedback); // +1
Dec(FWaitState); // 0->-1
if (FWaitState = 0) then
ReleaseSemaphore(FWaitSemaphore, 1, Nil); // 信号量+1
finally
FLock.Release;
end;
{$ELSE}
InterlockedIncrement(FGetFeedback); // 收到反馈 +
if (InterlockedDecrement(FWaitState) = 0) then
ReleaseSemaphore(FWaitSemaphore, 1, Nil); // 信号量+1
{$ENDIF}
end;
procedure TBaseSendThread.WaitForFeedback;
{$IFDEF ANDROID_MODE}
function LockedGetWaitState(IncOper: Boolean): Integer;
begin
FLock.Acquire;
try
if IncOper then // +
Inc(FWaitState) // 1: 未反馈,等待; 0:已经收到反馈
else // -
Dec(FWaitState);
Result := FWaitState;
finally
FLock.Release;
end;
end;
{$ENDIF}
begin
// 等服务器反馈,等 WAIT_MILLISECONDS 毫秒
{$IFDEF ANDROID_MODE}
if (LockedGetWaitState(True) = 1) then
repeat
WaitForSingleObject(FWaitSemaphore, WAIT_MILLISECONDS);
until (LockedGetWaitState(False) <= 0);
{$ELSE}
if (InterlockedIncrement(FWaitState) = 1) then
repeat
WaitForSingleObject(FWaitSemaphore, WAIT_MILLISECONDS);
until (InterlockedDecrement(FWaitState) <= 0);
{$ENDIF}
end;
{ TBasePostThread }
procedure TBasePostThread.Add(Msg: TBasePackObject);
begin
// 加入消息到列表
FLock.Acquire;
try
FMsgList.Add(Msg);
finally
FLock.Release;
end;
Activate; // 激活
end;
procedure TBasePostThread.AfterWork;
var
i: Integer;
begin
// 清除消息
for i := 0 to FMsgList.Count - 1 do
TBasePackObject(FMsgList.PopFirst).Free;
FLock.Free;
FMsgList.Free;
inherited;
end;
constructor TBasePostThread.Create(AConnection: TBaseConnection);
begin
inherited Create(True); // 内置信号灯
FConnection := AConnection;
FLock := TThreadLock.Create; // 锁
FMsgList := TInList.Create; // 收到的消息列表
end;
procedure TBasePostThread.DoThreadMethod;
var
Msg: TBasePackObject;
begin
// 循环处理收到的消息
while (Terminated = False) do
begin
FLock.Acquire;
try
Msg := TBasePackObject(FMsgList.PopFirst); // 取出第一个
finally
FLock.Release;
end;
if not Assigned(Msg) then // 跳出
Break;
if FSendThread.InCancelArray(Msg.MsgId) then // 任务被用户取消
begin
Msg.Free;
FSendThread.ServerFeedback;
end else
HandleMessage(Msg); // 进入业务层
end;
end;
procedure TBasePostThread.SetSendMsg(Msg: TBasePackObject);
begin
FLock.Acquire;
try
FSendMsg := Msg;
finally
FLock.Release;
end;
end;
{ TBaseRecvThread }
// 用 WSARecv 回调函数接收数据,效率高
procedure WorkerRoutine(const dwError, cbTransferred: DWORD;
const lpOverlapped: POverlapped; const dwFlags: DWORD); stdcall;
var
Thread: TBaseRecvThread;
Connection: TBaseConnection;
ByteCount, Flags: DWORD;
ErrorCode: Cardinal;
begin
// 不是主线程 !
// 传入的 lpOverlapped^.hEvent = TRecvThread
if (dwError <> 0) then // 出现异常,如关闭、断开
lpOverlapped^.hEvent := 0 // 设为无效 -> 连接即将断开
else
if (cbTransferred > 0) then
begin
// 有数据
// HTTP.SYS-WebSocket会无数据
Thread := TBaseRecvThread(lpOverlapped^.hEvent);
Connection := Thread.FConnection;
try
// 处理一个数据包
Thread.HandleDataPacket;
finally
// 继续执行 WSARecv,等待数据
FillChar(lpOverlapped^, SizeOf(TOverlapped), 0);
lpOverlapped^.hEvent := DWORD(Thread); // 传递自己
ByteCount := 0;
Flags := 0;
// 收到数据时执行 WorkerRoutine
if (iocp_Winsock2.WSARecv(Connection.FSocket, @Thread.FRecvBuf, 1,
ByteCount, Flags, LPWSAOVERLAPPED(lpOverlapped), @WorkerRoutine) = SOCKET_ERROR) then
begin
ErrorCode := WSAGetLastError;
if (ErrorCode <> WSA_IO_PENDING) then
begin
Connection.FErrorcode := ErrorCode;
Thread.Synchronize(Connection.DoClientError); // 线程同步
end;
end;
end;
end;
end;
constructor TBaseRecvThread.Create(AConnection: TBaseConnection; AReceiver: TBaseReceiver);
begin
inherited Create(True);
FConnection := AConnection;
FReceiver := AReceiver;
// 分配接收缓存(不能在线程 Execute 中分配)
GetMem(FRecvBuf.buf, IO_BUFFER_SIZE_2);
FRecvBuf.len := IO_BUFFER_SIZE_2;
FreeOnTerminate := True;
end;
procedure TBaseRecvThread.Execute;
var
ByteCount, Flags: DWORD;
begin
// 执行 WSARecv,等待数据
try
FillChar(FOverlapped, SizeOf(TOverlapped), 0);
FOverlapped.hEvent := DWORD(Self); // 传递自己
ByteCount := 0;
Flags := 0;
// 有数据传入时操作系统自动触发执行 WorkerRoutine
iocp_Winsock2.WSARecv(FConnection.FSocket, @FRecvBuf, 1,
ByteCount, Flags, @FOverlapped, @WorkerRoutine);
while not Terminated and (FOverlapped.hEvent > 0) do
if (SleepEx(80, True) = WAIT_IO_COMPLETION) then // 不能用其他等待模式
{ Empty } ;
finally
if FConnection.FActive and (FOverlapped.hEvent = 0) then
Synchronize(FConnection.Disconnect); // 断开
FreeMem(FRecvBuf.buf); // 释放资源
FreeAndNil(FReceiver);
end;
end;
procedure TBaseRecvThread.HandleDataPacket;
begin
// 接收字节总数
Inc(FConnection.FRecvCount, FOverlapped.InternalHigh);
end;
procedure TBaseRecvThread.OnCreateMsgObject(Msg: TBasePackObject);
begin
// 准备新的消息
FRecvMsg := Msg;
FRecvCount := 0;
FTotalSize := 0;
end;
procedure TBaseRecvThread.OnDataReceive(Msg: TBasePackObject; Part: TMessagePart; RecvCount: Cardinal);
begin
Synchronize(FConnection.RecvMsgProgress);
end;
procedure TBaseRecvThread.OnRecvError(Msg: TBasePackObject; ErrorCode: Integer);
begin
// 接收校验异常
FConnection.FErrorcode := ErrorCode;
Synchronize(FConnection.DoClientError);
end;
procedure TBaseRecvThread.Stop;
begin
if Assigned(FReceiver) then // 服务器关闭时,接收线程已经停止
Terminate;
while Assigned(FReceiver) do
Sleep(10);
end;
end.
|
unit uFunctions.Form;
interface
type
FormHelper = class
private
class var FLastInterface: TGUID;
class var FLastObject: IInterface;
public
class function GetFirstForm(const AInterface: TGUID; out RI): Boolean;
end;
implementation
uses
{ Screen }
Vcl.Forms,
{ Supports }
System.SysUtils;
class function FormHelper.GetFirstForm(const AInterface: TGUID; out RI): Boolean;
var
LCycle: Integer;
begin
Result := False;
{ Simple cache }
if AInterface = FLastInterface then
if FLastObject <> nil then
if Supports(FLastObject, AInterface, RI) then
Exit(True);
{ Search for form which are implement required interface }
for LCycle := 0 to Screen.FormCount - 1 do
if Supports(Screen.Forms[LCycle], AInterface, RI) then
begin
{ Store founded form for cache purpose }
FLastInterface := AInterface;
FLastObject := Screen.Forms[LCycle];
Exit(True);
end;
end;
end.
|
unit View.Dialog;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.ImageList, Vcl.ImgList, Vcl.ExtCtrls, Vcl.Buttons, Vcl.StdCtrls, System.Actions,
Vcl.ActnList, System.UITypes;
type
Tview_Dialog = class(TForm)
panelTitle: TPanel;
imageListDialog: TImageList;
labelDialogTitle: TLabel;
aclDialog: TActionList;
actOK: TAction;
actCancelar: TAction;
panelIcon: TPanel;
imageIcon: TImage;
panelBackGround: TPanel;
panelOK: TPanel;
speedButtonOK: TSpeedButton;
panelCancelar: TPanel;
speedButtonCancelar: TSpeedButton;
labelMensagem: TLabel;
procedure actOKExecute(Sender: TObject);
procedure actCancelarExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
procedure SetupDialog;
public
{ Public declarations }
Tipo: Integer;
Titulo: String;
Mensagem: String;
Resultado: Integer;
end;
var
view_Dialog: Tview_Dialog;
implementation
{$R *.dfm}
procedure Tview_Dialog.actCancelarExecute(Sender: TObject);
begin
Resultado := mrCancel;
Close;
end;
procedure Tview_Dialog.actOKExecute(Sender: TObject);
begin
Resultado := mrOk;
Close;
end;
procedure Tview_Dialog.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
actOKExecute(Self);
end
else if Key = #27 then
begin
actCancelarExecute(Self);
end;
Key := #0;
end;
procedure Tview_Dialog.FormShow(Sender: TObject);
begin
SetupDialog;
end;
procedure Tview_Dialog.SetupDialog;
begin
if Tipo = 0 then
begin
panelIcon.Color := clYellow;
panelOK.Visible := False;
end
else if Tipo = 1 then
begin
panelCancelar.Visible := False;
end
else if Tipo = 2 then
begin
panelIcon.Color := clRed;
panelOK.Visible := False;
end
else
begin
panelIcon.Color := clMenuHighlight;
end;
imageListDialog.GetIcon(Tipo,imageIcon.Picture.Icon);
labelDialogTitle.Caption := Titulo;
labelMensagem.Caption := Mensagem;
Beep;
end;
end.
|
unit modComPort;
interface
uses
windows, modGlobals, dateutils, sysutils, System.Generics.Collections;
const
MOD_COM_RESULT_ERROR = -1;
MOD_COM_RESULT_NOTHING = -2;
MOD_COM_RESULT_PENDING = -3;
// error types that indicate what function failed!
type
TmodComError = (modComPort_NoError, modComPort_CreateFile,
modComPort_SetCommTimeouts, modComPort_CreateIoCompletionPort,
modComPort_GetCommState, modComPort_SetCommState, modComPort_SetCommMask,
modComPort_WriteFile, modComPort_ReadFile);
type
TmodComPortState = (modComPort_Disconnected, modComPort_Connected,
modComPort_Pending_Send, modComPort_Pending_Recv);
type
TmodComPortParameters = packed record
baud: Integer;
parity_bits: Integer;
stop_bits: Integer;
end;
type
TmodComPortError = record
error_time: Int64; // unix timestamp
error_state: TmodComError;
error_code: Integer;
end;
type
TmodComPort = class
public
constructor Create(name: string);
destructor Destroy; override;
function GetComPortName(): string;
function GetComPortHandle(): THandle;
function GetErrorState(): TmodComPortError;
procedure SetComPortParameters(params: TmodComPortParameters);
function Connect(): Boolean;
function Disconnect(): Boolean;
function Send(var data: TArray<Byte>): Integer;
function Recv(var data: TArray<Byte>; len: Integer = MOD_COM_MAX_BYTES): Integer;
procedure SetComPortState(state: TmodComPortState);
function GetComportState(): TmodComPortState;
procedure Purge;
private
_name: string;
_com_handle: THandle;
_comm_timeouts: TCommTimeouts;
_dcb: TDCB;
_overlapped_read: TOverlapped;
_overlapped_write: TOverlapped;
_last_send_operation_byte_count: Integer;
_last_recv_operation_byte_count: Integer;
// statistics
_stat_bytes_sent: Cardinal;
_stat_bytes_recv: Cardinal;
_params: TmodComPortParameters;
_state: TmodComPortState;
// on error, this gets set.
_error: TmodComPortError;
// so we don't need to create this on stack every time
_recv_buf: array[0..MOD_COM_MAX_BYTES - 1] of Byte;
procedure SetError(state: TmodComError; error_code: Integer);
end;
implementation
{ TmodComPort }
function TmodComPort.Connect: Boolean;
var
com_addr: WideString;
begin
Result := True;
_com_handle := INVALID_HANDLE_VALUE;
com_addr := '\\.\' + _name;
_com_handle := CreateFile(@com_addr[1], GENERIC_READ or GENERIC_WRITE, 0, // must be opened with exclusive-access
0, // default security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
FILE_FLAG_OVERLAPPED, // we want overlapped communication
0); // hTemplate must be NULL for comm devices
if (_com_handle = INVALID_HANDLE_VALUE) then
begin
SetError(modComPort_CreateFile, GetLastError());
Result := False;
Exit;
end;
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363190%28v=vs.85%29.aspx
// readfile and writefile returns immediately
_comm_timeouts.ReadIntervalTimeout := MAXDWORD;
_comm_timeouts.ReadTotalTimeoutMultiplier := 0;
_comm_timeouts.ReadTotalTimeoutConstant := 0;
_comm_timeouts.WriteTotalTimeoutMultiplier := 0;
_comm_timeouts.WriteTotalTimeoutConstant := 0;
if (SetCommTimeouts(_com_handle, _comm_timeouts) <> True) then
begin
SetError(modComPort_SetCommTimeouts, GetLastError());
Result := False;
Exit;
end;
if (GetCommState(_com_handle, _dcb) = False) then
begin
SetError(modComPort_GetCommState, GetLastError());
Result := False;
Exit;
end;
_dcb.BaudRate := CBR_115200;
_dcb.Parity := NOPARITY;
_dcb.StopBits := ONESTOPBIT;
_dcb.ByteSize := 8;
if (SetCommState(_com_handle, _dcb) = False) then
begin
SetError(modComPort_SetCommState, GetLastError());
Result := False;
Exit;
end;
// we only want to recieve events that indicate reading and writing. No control stuff.
if (SetCommMask(_com_handle, EV_TXEMPTY or EV_RXCHAR) = False) then
begin
SetError(modComPort_SetCommMask, GetLastError());
Result := False;
Exit;
end;
Self.Purge;
// set port state to connected
Self._state := modComPort_Connected;
// reset statistics
_stat_bytes_sent := 0;
_stat_bytes_recv := 0;
end;
constructor TmodComPort.Create(name: string);
begin
_name := name;
_state := modComPort_Disconnected;
_com_handle := INVALID_HANDLE_VALUE;
// NULL error state
ZeroMemory(@_error, SizeOf(TmodComPortError));
// NULL overlapped structure
ZeroMemory(@_overlapped_read, SizeOf(TOverlapped));
ZeroMemory(@_overlapped_write, SizeOf(TOverlapped));
_last_send_operation_byte_count := 0;
_last_recv_operation_byte_count := 0;
end;
destructor TmodComPort.Destroy;
begin
inherited;
Self.Disconnect();
end;
function TmodComPort.Disconnect: Boolean;
begin
if (_com_handle <> INVALID_HANDLE_VALUE) then
begin
CancelIo(_com_handle);
CloseHandle(_com_handle);
end;
_com_handle := INVALID_HANDLE_VALUE;
_state := modComPort_Disconnected;
Result := True;
end;
function TmodComPort.GetComPortHandle: THandle;
begin
Result := _com_handle;
end;
function TmodComPort.GetComPortName: string;
begin
Result := _name;
end;
function TmodComPort.GetComportState: TmodComPortState;
var
handled_bytes: Cardinal;
begin
GetOverlappedResult(_com_handle, _overlapped_read, handled_bytes, False);
if (_last_recv_operation_byte_count = handled_bytes) then
begin
GetOverlappedResult(_com_handle, _overlapped_write, handled_bytes, False);
if (_last_send_operation_byte_count = handled_bytes) then
begin
_state := modComPort_Connected;
end;
end;
Result := _state;
end;
function TmodComPort.GetErrorState: TmodComPortError;
begin
Result := _error;
end;
procedure TmodComPort.Purge;
begin
PurgeComm(_com_handle, PURGE_RXABORT or PURGE_RXCLEAR or PURGE_TXABORT or
PURGE_TXCLEAR);
end;
function TmodComPort.Recv(var data: TArray<Byte>; len: Integer): Integer;
var
recv_count: Cardinal;
last_error: Integer;
begin
// create a new overlapped finish event
ZeroMemory(@_overlapped_read, SizeOf(TOverlapped));
// _overlapped_read.hEvent := CreateEvent(0, true, false, 0);
try
if (ReadFile(_com_handle, _recv_buf[0], len, recv_count, @_overlapped_read)) then
begin
if (recv_count > 0) then
begin
SetLength(data, recv_count);
CopyMemory(@data[0], @_recv_buf[0], recv_count);
_last_recv_operation_byte_count := recv_count;
Result := _last_recv_operation_byte_count;
Inc(_stat_bytes_recv, recv_count);
end
else
begin
begin
//there is no error, simply returned zero
end;
SetLength(data, 0);
Result := MOD_COM_RESULT_NOTHING;
end;
end
else
begin
last_error := GetLastError();
// TODO: Maybe we need to also check with GetCommMask()?
if (last_error = ERROR_IO_PENDING) then
begin
// now get the result. Wait for event object to signal. (last param)
// GetOverlappedResult(_com_handle, _overlapped_read, recv_count, true);
Result := MOD_COM_RESULT_PENDING;
_state := modComPort_Pending_Recv;
end
else
begin
SetError(modComPort_ReadFile, last_error);
Result := MOD_COM_RESULT_ERROR;
end;
end;
finally
// CloseHandle(_overlapped_read.hEvent);
end;
end;
function TmodComPort.Send(var data: TArray<Byte>): Integer;
var
bytes_written, byte_len: Cardinal;
last_error: Integer;
begin
// create event that signals end of write
ZeroMemory(@_overlapped_write, SizeOf(TOverlapped));
// _overlapped_write.hEvent := CreateEvent(0, true, false, 0);
try
byte_len := Length(data);
if (WriteFile(_com_handle, data[0], byte_len, bytes_written, @_overlapped_write)) then
begin
_last_send_operation_byte_count := bytes_written;
Result := _last_send_operation_byte_count;
Inc(_stat_bytes_sent, bytes_written);
_state := modComPort_Connected;
end
else
begin
last_error := GetLastError();
// TODO: Maybe we need to also check with GetCommMask()?
if (last_error = ERROR_IO_PENDING) then
begin
// GetOverlappedResult(_com_handle, _overlapped_write, bytes_written, true);
Result := MOD_COM_RESULT_PENDING;
_state := modComPort_Pending_Send;
end
else
begin
SetError(modComPort_WriteFile, last_error);
Result := MOD_COM_RESULT_ERROR;
end;
end;
finally
// CloseHandle(_overlapped_write.hEvent);
end;
end;
procedure TmodComPort.SetComPortParameters(params: TmodComPortParameters);
begin
_params := params;
end;
procedure TmodComPort.SetComPortState(state: TmodComPortState);
begin
_state := state;
end;
procedure TmodComPort.SetError(state: TmodComError; error_code: Integer);
begin
_error.error_state := state;
_error.error_code := error_code;
_error.error_time := DateTimeToUnix(Now());
end;
end.
|
program ejercicio5;
const
dimF = 1000;
type
str40 = String[40];
codRol = 1..5;
rangoCod = 1..1000;
participante = record
PaisResidencia : str40;
codProyecto : Integer;
nomProyecto : str40;
rol : codRol;
cantHoras : Integer;
end;
info = record
arquitectos : Integer;
proyectoMonto : Real;
end;
contador = array[rangoCod] of info;
tabla = array[codRol] of Real;
procedure inicializarVectorContador(var c:contador);
var
i: Integer;
begin
for i := 1 to dimF do
begin
c[i].arquitectos:= 0;
c[i].proyectoMonto:= 0;
end;
end;
procedure cargarTabla(var t:tabla);
begin
t[1]:=25.20;
t[2]:=27.45;
t[3]:=31.03;
t[4]:=44.28;
t[5]:=39.81;
end;
procedure leerParticipante(var p: participante);
begin
write('Ingrese el Codigo del participante: ');
readln(p.codProyecto);
if (p.codProyecto <> -1) then
begin
with p do
begin
write('Ingrese el Pais de residencia: ');
readln(PaisResidencia);
write('Ingrese el Nombre del proyecto: ');
readln(nomProyecto);
write('Ingrese el Rol del participante: ');
readln(rol);
write('Ingrese la cantidad de hora: ');
readln(cantHoras);
end;
end;
end;
procedure imprimirProyectoMaximo(c:contador);
var
i,codigoMax: Integer;
max: Real;
begin
max:=-1;
for i := 1 to 1000 do
begin
writeln('Proyecto: ', i, ' Aruitectos: ', c[i].arquitectos);
if (c[i].proyectoMonto > max) then
begin
max:= c[i].proyectoMonto;
codigoMax:= i;
end;
end;
writeln('el proyecto con el mayor monto invertido es de codigo: ', codigoMax);
end;
procedure procesar(p:participante; t:tabla; var c:contador; var montoArgentina:Real; var horasBasesDeDatos: Integer);
begin
leerParticipante(p);
while (p.codProyecto <> -1) do
begin
if (p.PaisResidencia = 'Argentina') then
montoArgentina:= montoArgentina + (p.cantHoras * t[p.rol]);
if (p.rol = 3) then
horasBasesDeDatos:= horasBasesDeDatos + p.cantHoras;
c[p.codProyecto].proyectoMonto:= c[p.codProyecto].proyectoMonto + (p.cantHoras) * t[p.rol];
if (p.rol = 4) then
c[p.codProyecto].arquitectos:= c[p.codProyecto].arquitectos + 1;
leerParticipante(p);
end;
end;
var
t: tabla;
c: contador;
horasBasesDeDatos: Integer;
montoArgentina: Real;
p: participante;
begin
montoArgentina:=0;
horasBasesDeDatos:= 0;
inicializarVectorContador(c);
cargarTabla(t);
procesar(p,t,c,montoArgentina,horasBasesDeDatos);
imprimirProyectoMaximo(c);
writeln('El monto investido en desarroladores Argentions es: ', montoArgentina:4:2);
writeln('Las horas trabajadas por administradores de bades de datos: ', horasBasesDeDatos);
readln();
end. |
{
File: CodeFragments.p
Contains: Public Code Fragment Manager Interfaces.
Version: Technology: Forte CFM and Carbon
Release: Universal Interfaces 3.4.2
Copyright: © 1992-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
}
{
¥
===========================================================================================
The Code Fragment Manager API
=============================
}
{
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 CodeFragments;
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,CFBundle,Files,Multiprocessing;
{$ALIGN MAC68K}
{
¤
===========================================================================================
General Types and Constants
===========================
}
const
kCFragResourceType = FourCharCode('cfrg');
kCFragResourceID = 0;
kCFragLibraryFileType = FourCharCode('shlb');
kCFragAllFileTypes = $FFFFFFFF;
type
CFragArchitecture = OSType;
const
{ Values for type CFragArchitecture. }
kPowerPCCFragArch = FourCharCode('pwpc');
kMotorola68KCFragArch = FourCharCode('m68k');
kAnyCFragArch = $3F3F3F3F;
{$ifc TARGET_CPU_PPC}
kCompiledCFragArch = FourCharCode('pwpc');
{$endc}
{$ifc TARGET_CPU_68K}
kCompiledCFragArch = FourCharCode('m68k');
{$endc}
{$ifc TARGET_CPU_X86}
kCompiledCFragArch = FourCharCode('none');
{$endc}
type
CFragVersionNumber = UInt32;
const
kNullCFragVersion = 0;
kWildcardCFragVersion = $FFFFFFFF;
type
CFragUsage = UInt8;
const
{ Values for type CFragUsage. }
kImportLibraryCFrag = 0; { Standard CFM import library. }
kApplicationCFrag = 1; { MacOS application. }
kDropInAdditionCFrag = 2; { Application or library private extension/plug-in }
kStubLibraryCFrag = 3; { Import library used for linking only }
kWeakStubLibraryCFrag = 4; { Import library used for linking only and will be automatically weak linked }
kIsCompleteCFrag = 0; { A "base" fragment, not an update. }
kFirstCFragUpdate = 1; { The first update, others are numbered 2, 3, ... }
kCFragGoesToEOF = 0;
type
CFragLocatorKind = UInt8;
const
{ Values for type CFragLocatorKind. }
kMemoryCFragLocator = 0; { Container is in memory. }
kDataForkCFragLocator = 1; { Container is in a file's data fork. }
kResourceCFragLocator = 2; { Container is in a file's resource fork. }
kNamedFragmentCFragLocator = 4; { ! Reserved for possible future use! }
kCFBundleCFragLocator = 5; { Container is in the executable of a CFBundle }
kCFBundleIntCFragLocator = 6; { passed to init routines in lieu of kCFBundleCFragLocator }
{
--------------------------------------------------------------------------------------
A 'cfrg' resource consists of a header followed by a sequence of variable length
members. The constant kDefaultCFragNameLen only provides for a legal ANSI declaration
and for a reasonable display in a debugger. The actual name field is cut to fit.
There may be "extensions" after the name, the memberSize field includes them. The
general form of an extension is a 16 bit type code followed by a 16 bit size in bytes.
Only one standard extension type is defined at present, it is used by SOM's searching
mechanism.
}
type
CFragUsage1UnionPtr = ^CFragUsage1Union;
CFragUsage1Union = record
case SInt16 of
{ ! Meaning differs depending on value of "usage". }
0: (
appStackSize: UInt32; { If the fragment is an application. (Not used by CFM!) }
);
end;
CFragUsage2UnionPtr = ^CFragUsage2Union;
CFragUsage2Union = record
case SInt16 of
{ ! Meaning differs depending on value of "usage". }
0: (
appSubdirID: SInt16; { If the fragment is an application. }
);
1: (
libFlags: UInt16; { If the fragment is an import library. }
);
end;
const
{ Bit masks for the CFragUsage2Union libFlags variant. }
kCFragLibUsageMapPrivatelyMask = $0001; { Put container in app heap if necessary. }
type
CFragWhere1UnionPtr = ^CFragWhere1Union;
CFragWhere1Union = record
case SInt16 of
{ ! Meaning differs depending on value of "where". }
0: (
spaceID: UInt32; { If the fragment is in memory. (Actually an AddressSpaceID.) }
);
end;
CFragWhere2UnionPtr = ^CFragWhere2Union;
CFragWhere2Union = record
case SInt16 of
{ ! Meaning differs depending on value of "where". }
0: (
reserved: UInt16;
);
end;
const
kDefaultCFragNameLen = 16;
type
CFragResourceMemberPtr = ^CFragResourceMember;
CFragResourceMember = record
architecture: CFragArchitecture;
reservedA: UInt16; { ! Must be zero! }
reservedB: SInt8; { ! Must be zero! }
updateLevel: SInt8;
currentVersion: CFragVersionNumber;
oldDefVersion: CFragVersionNumber;
uUsage1: CFragUsage1Union;
uUsage2: CFragUsage2Union;
usage: SInt8;
where: SInt8;
offset: UInt32;
length: UInt32;
uWhere1: CFragWhere1Union;
uWhere2: CFragWhere2Union;
extensionCount: UInt16; { The number of extensions beyond the name. }
memberSize: UInt16; { Size in bytes, includes all extensions. }
name: packed array [0..15] of UInt8; { ! Actually a sized PString. }
end;
CFragResourceExtensionHeaderPtr = ^CFragResourceExtensionHeader;
CFragResourceExtensionHeader = record
extensionKind: UInt16;
extensionSize: UInt16;
end;
CFragResourceSearchExtensionPtr = ^CFragResourceSearchExtension;
CFragResourceSearchExtension = record
header: CFragResourceExtensionHeader;
libKind: OSType;
qualifiers: SInt8; { ! Actually four PStrings. }
end;
const
kCFragResourceSearchExtensionKind = $30EE;
type
CFragResourcePtr = ^CFragResource;
CFragResource = record
reservedA: UInt32; { ! Must be zero! }
reservedB: UInt32; { ! Must be zero! }
reservedC: UInt16; { ! Must be zero! }
version: UInt16;
reservedD: UInt32; { ! Must be zero! }
reservedE: UInt32; { ! Must be zero! }
reservedF: UInt32; { ! Must be zero! }
reservedG: UInt32; { ! Must be zero! }
reservedH: UInt16; { ! Must be zero! }
memberCount: UInt16;
firstMember: CFragResourceMember;
end;
CFragResourceHandle = ^CFragResourcePtr;
const
kCurrCFragResourceVersion = 1;
type
CFragContextID = MPProcessID;
CFragConnectionID = ^SInt32; { an opaque 32-bit type }
CFragConnectionIDPtr = ^CFragConnectionID; { when a var xx:CFragConnectionID parameter can be nil, it is changed to xx: CFragConnectionIDPtr }
CFragClosureID = ^SInt32; { an opaque 32-bit type }
CFragClosureIDPtr = ^CFragClosureID; { when a var xx:CFragClosureID parameter can be nil, it is changed to xx: CFragClosureIDPtr }
CFragContainerID = ^SInt32; { an opaque 32-bit type }
CFragContainerIDPtr = ^CFragContainerID; { when a var xx:CFragContainerID parameter can be nil, it is changed to xx: CFragContainerIDPtr }
CFragLoadOptions = OptionBits;
mainAddrPtr = ^Ptr; { when a var mainAddr: Ptr parameter can be nil, it is changed to mainAddr: mainAddrPtr }
symAddrPtr = ^Ptr; { when a var symAddr: Ptr parameter can be nil, it is changed to symAddr: symAddrPtr }
const
{ Values for type CFragLoadOptions. }
kReferenceCFrag = $0001; { Try to use existing copy, increment reference counts. }
kFindCFrag = $0002; { Try find an existing copy, do not increment reference counts. }
kPrivateCFragCopy = $0005; { Prepare a new private copy. (kReferenceCFrag | 0x0004) }
kUnresolvedCFragSymbolAddress = 0;
type
CFragSymbolClass = UInt8;
CFragSymbolClassPtr = ^CFragSymbolClass; { when a var xx:CFragSymbolClass parameter can be nil, it is changed to xx: CFragSymbolClassPtr }
const
{ Values for type CFragSymbolClass. }
kCodeCFragSymbol = 0;
kDataCFragSymbol = 1;
kTVectorCFragSymbol = 2;
kTOCCFragSymbol = 3;
kGlueCFragSymbol = 4;
{
¤
===========================================================================================
Macros and Functions
====================
}
{
* GetSharedLibrary()
*
* Discussion:
* The connID, mainAddr, and errMessage parameters may be NULL with
* MacOS 8.5 and later. Passing NULL as those parameters when
* running Mac OS 8.1 and earlier systems will corrupt low-memory.
*
* Availability:
* Non-Carbon CFM: in CFragManager 1.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function GetSharedLibrary(const (*var*) libName: Str63; archType: CFragArchitecture; options: CFragLoadOptions; var connID: CFragConnectionID; var mainAddr: Ptr; var errMessage: Str255): OSErr; external name '_GetSharedLibrary';
{
* GetDiskFragment()
*
* Availability:
* Non-Carbon CFM: in CFragManager 1.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function GetDiskFragment(const (*var*) fileSpec: FSSpec; offset: UInt32; length: UInt32; fragName: ConstStringPtr; options: CFragLoadOptions; connID: CFragConnectionIDPtr; mainAddr: mainAddrPtr; errMessage: StringPtr): OSErr; external name '_GetDiskFragment';
{
* GetMemFragment()
*
* Availability:
* Non-Carbon CFM: in CFragManager 1.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function GetMemFragment(memAddr: UnivPtr; length: UInt32; fragName: ConstStringPtr; options: CFragLoadOptions; connID: CFragConnectionIDPtr; mainAddr: mainAddrPtr; errMessage: StringPtr): OSErr; external name '_GetMemFragment';
{
* CloseConnection()
*
* Availability:
* Non-Carbon CFM: in CFragManager 1.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function CloseConnection(var connID: CFragConnectionID): OSErr; external name '_CloseConnection';
{
* FindSymbol()
*
* Availability:
* Non-Carbon CFM: in CFragManager 1.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function FindSymbol(connID: CFragConnectionID; const (*var*) symName: Str255; symAddr: symAddrPtr; symClass: CFragSymbolClassPtr): OSErr; external name '_FindSymbol';
{
* CountSymbols()
*
* Availability:
* Non-Carbon CFM: in CFragManager 1.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function CountSymbols(connID: CFragConnectionID; var symCount: SInt32): OSErr; external name '_CountSymbols';
{
* GetIndSymbol()
*
* Availability:
* Non-Carbon CFM: in CFragManager 1.0 and later
* CarbonLib: in CarbonLib 1.0 and later
* Mac OS X: in version 10.0 and later
}
function GetIndSymbol(connID: CFragConnectionID; symIndex: SInt32; symName: StringPtr; symAddr: symAddrPtr; symClass: CFragSymbolClassPtr): OSErr; external name '_GetIndSymbol';
{
¤
===========================================================================================
Initialization & Termination Routines
=====================================
}
{
-----------------------------------------------------------------------------------------
A fragment's initialization and termination routines are called when a new incarnation of
the fragment is created or destroyed, respectively. Exactly when this occurs depends on
what kinds of section sharing the fragment has and how the fragment is prepared. Import
libraries have at most one incarnation per process. Fragments prepared with option
kPrivateCFragCopy may have many incarnations per process.
The initialization function is passed a pointer to an initialization information structure
and returns an OSErr. If an initialization function returns a non-zero value the entire
closure of which it is a part fails. The C prototype for an initialization function is:
OSErr CFragInitFunction ( const CFragInitBlock * initBlock );
The termination procedure takes no parameters and returns nothing. The C prototype for a
termination procedure is:
void CFragTermProcedure ( void );
Note that since the initialization and termination routines are themselves "CFM"-style
routines whether or not they have the "pascal" keyword is irrelevant.
}
{
-----------------------------------------------------------------------------------------
! Note:
! The "System7" portion of these type names was introduced during the evolution towards
! the now defunct Copland version of Mac OS. Copland was to be called System 8 and there
! were slightly different types for System 7 and System 8. The "generic" type names were
! conditionally defined for the desired target system.
! Always use the generic types, e.g. CFragInitBlock! The "System7" names have been kept
! only to avoid perturbing code that (improperly) used the target specific type.
}
type
CFragSystem7MemoryLocatorPtr = ^CFragSystem7MemoryLocator;
CFragSystem7MemoryLocator = record
address: LogicalAddress;
length: UInt32;
inPlace: boolean;
reservedA: SInt8; { ! Must be zero! }
reservedB: UInt16; { ! Must be zero! }
end;
CFragSystem7DiskFlatLocatorPtr = ^CFragSystem7DiskFlatLocator;
CFragSystem7DiskFlatLocator = record
fileSpec: FSSpecPtr;
offset: UInt32;
length: UInt32;
end;
{ ! This must have a file specification at the same offset as a disk flat locator! }
CFragSystem7SegmentedLocatorPtr = ^CFragSystem7SegmentedLocator;
CFragSystem7SegmentedLocator = record
fileSpec: FSSpecPtr;
rsrcType: OSType;
rsrcID: SInt16;
reservedA: UInt16; { ! Must be zero! }
end;
{
The offset and length for a "Bundle" locator refers to the offset in
the CFM executable contained by the bundle.
}
CFragCFBundleLocatorPtr = ^CFragCFBundleLocator;
CFragCFBundleLocator = record
fragmentBundle: CFBundleRef; { Do not call CFRelease on this bundle! }
offset: UInt32;
length: UInt32;
end;
CFragSystem7LocatorPtr = ^CFragSystem7Locator;
CFragSystem7Locator = record
where: SInt32;
case SInt16 of
0: (
onDisk: CFragSystem7DiskFlatLocator;
);
1: (
inMem: CFragSystem7MemoryLocator;
);
2: (
inSegs: CFragSystem7SegmentedLocator;
);
3: (
inBundle: CFragCFBundleLocator;
);
end;
CFragSystem7InitBlockPtr = ^CFragSystem7InitBlock;
CFragSystem7InitBlock = record
contextID: CFragContextID;
closureID: CFragClosureID;
connectionID: CFragConnectionID;
fragLocator: CFragSystem7Locator;
libName: StringPtr;
reservedA: UInt32; { ! Must be zero! }
end;
CFragInitBlock = CFragSystem7InitBlock;
CFragInitBlockPtr = ^CFragInitBlock;
{ These init/term routine types are only of value to CFM itself. }
{$ifc TYPED_FUNCTION_POINTERS}
CFragInitFunction = function(const (*var*) initBlock: CFragInitBlock): OSErr;
{$elsec}
CFragInitFunction = ProcPtr;
{$endc}
{$ifc TYPED_FUNCTION_POINTERS}
CFragTermProcedure = procedure;
{$elsec}
CFragTermProcedure = ProcPtr;
{$endc}
{
For use by init routines. If you get a BundleIntLocator (used to be BundlePreLocator),
convert it to a CFBundleLocator with this. Only call this once per locator.
}
{
* ConvertBundlePreLocator()
*
* Availability:
* Non-Carbon CFM: not available
* CarbonLib: in CarbonLib 1.4 and later
* Mac OS X: in version 10.0 and later
}
function ConvertBundlePreLocator(initBlockLocator: CFragSystem7LocatorPtr): OSErr; external name '_ConvertBundlePreLocator';
{
¤
===========================================================================================
Old Name Spellings
==================
}
{
-------------------------------------------------------------------------------------------
We've tried to reduce the risk of name collisions in the future by introducing the phrase
"CFrag" into constant and type names. The old names are defined below in terms of the new.
}
const
kLoadCFrag = $0001;
{$ifc OLDROUTINENAMES}
type
ConnectionID = CFragConnectionID;
LoadFlags = CFragLoadOptions;
SymClass = CFragSymbolClass;
InitBlock = CFragInitBlock;
InitBlockPtr = ^InitBlock;
MemFragment = CFragSystem7MemoryLocator;
MemFragmentPtr = ^MemFragment;
DiskFragment = CFragSystem7DiskFlatLocator;
DiskFragmentPtr = ^DiskFragment;
SegmentedFragment = CFragSystem7SegmentedLocator;
SegmentedFragmentPtr = ^SegmentedFragment;
FragmentLocator = CFragSystem7Locator;
FragmentLocatorPtr = ^FragmentLocator;
CFragHFSMemoryLocator = CFragSystem7MemoryLocator;
CFragHFSMemoryLocatorPtr = ^CFragHFSMemoryLocator;
CFragHFSDiskFlatLocator = CFragSystem7DiskFlatLocator;
CFragHFSDiskFlatLocatorPtr = ^CFragHFSDiskFlatLocator;
CFragHFSSegmentedLocator = CFragSystem7SegmentedLocator;
CFragHFSSegmentedLocatorPtr = ^CFragHFSSegmentedLocator;
CFragHFSLocator = CFragSystem7Locator;
CFragHFSLocatorPtr = ^CFragHFSLocator;
const
kPowerPCArch = FourCharCode('pwpc');
kMotorola68KArch = FourCharCode('m68k');
kAnyArchType = $3F3F3F3F;
kNoLibName = 0;
kNoConnectionID = 0;
kLoadLib = $0001;
kFindLib = $0002;
kNewCFragCopy = $0005;
kLoadNewCopy = $0005;
kUseInPlace = $80;
kCodeSym = 0;
kDataSym = 1;
kTVectSym = 2;
kTOCSym = 3;
kGlueSym = 4;
kInMem = 0;
kOnDiskFlat = 1;
kOnDiskSegmented = 2;
kIsLib = 0;
kIsApp = 1;
kIsDropIn = 2;
kFullLib = 0;
kUpdateLib = 1;
kWholeFork = 0;
kCFMRsrcType = FourCharCode('cfrg');
kCFMRsrcID = 0;
kSHLBFileType = FourCharCode('shlb');
kUnresolvedSymbolAddress = 0;
kPowerPC = FourCharCode('pwpc');
kMotorola68K = FourCharCode('m68k');
{$endc} {OLDROUTINENAMES}
{$ALIGN MAC68K}
end.
|
unit HireCriminalDlg;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, IBSystem, IBTestMain;
type
THireCriminal = class(TForm)
Label1: TLabel;
Label2: TLabel;
lbExpert: TListBox;
lbRookies: TListBox;
Label3: TLabel;
lbProperties: TListBox;
Button1: TButton;
Button2: TButton;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lbExpertClick(Sender: TObject);
procedure lbRookiesClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
fCriminals : TStringList;
procedure ShowSelected;
public
theIBSystem : TIBSystem;
theTycoonId : integer;
theTeamName : string;
Selected : TClientCriminal;
end;
var
HireCriminal: THireCriminal;
implementation
{$R *.DFM}
procedure THireCriminal.FormShow(Sender: TObject);
var
str : string;
i : integer;
begin
lbExpert.Clear;
lbRookies.Clear;
lbProperties.Clear;
fCriminals.Clear;
str := theIBSystem.RDOGetCriminalList( theTycoonId, theTeamName );
fCriminals.Text := str;
if str <> ''
then
begin
i := 0;
while (fCriminals.Values[EXPERT_PREFIX + 'Name' + IntToStr(i)] <> '') do
begin
lbExpert.Items.add( fCriminals.Values[EXPERT_PREFIX + 'Name' + IntToStr(i)] );
inc( i );
end;
i := 0;
while (fCriminals.Values[ROOKIE_PREFIX + 'Name' + IntToStr(i)] <> '') do
begin
lbRookies.Items.add( fCriminals.Values[ROOKIE_PREFIX + 'Name' + IntToStr(i)] );
inc( i );
end;
end
else
begin
ShowMessage( 'unknow error getting the criminals list' );
ModalResult := mrCancel;
end;
end;
procedure THireCriminal.FormCreate(Sender: TObject);
begin
fCriminals := TStringList.Create;
Selected := TClientCriminal.Create;
end;
procedure THireCriminal.lbExpertClick(Sender: TObject);
begin
if lbExpert.ItemIndex <> -1
then
begin
Selected.DeSerialize( fCriminals, EXPERT_PREFIX, lbExpert.ItemIndex );
ShowSelected;
end;
end;
procedure THireCriminal.lbRookiesClick(Sender: TObject);
begin
if lbRookies.ItemIndex <> -1
then
begin
Selected.DeSerialize( fCriminals, ROOKIE_PREFIX, lbRookies.ItemIndex );
ShowSelected;
end;
end;
procedure THireCriminal.Button2Click(Sender: TObject);
begin
if (lbRookies.ItemIndex <> -1) or (lbExpert.ItemIndex <> -1)
then ModalResult := mrOK
else ShowMessage( 'Select a criminal to hire' );
end;
procedure THireCriminal.ShowSelected;
begin
lbProperties.Clear;
lbProperties.Items.Add( 'Sex : ' + Selected.Sex );
lbProperties.Items.Add( 'Picture : ' + Selected.Picture );
lbProperties.Items.Add( 'Status : ' + Selected.Status );
lbProperties.Items.Add( 'Skills:' );
lbProperties.Items.Add( 'Leadership : ' + IntToStr( Selected.Skills[SKILL_LEADERSHIP] ) + '%' );
lbProperties.Items.Add( 'Driving : ' + IntToStr( Selected.Skills[SKILL_DRIVING] ) + '%' );
lbProperties.Items.Add( 'Brawling : ' + IntToStr( Selected.Skills[SKILL_BRAWLING] ) + '%' );
lbProperties.Items.Add( 'Firearms : ' + IntToStr( Selected.Skills[SKILL_FIREARMS] ) + '%' );
lbProperties.Items.Add( 'Stalking : ' + IntToStr( Selected.Skills[SKILL_STALKING] ) + '%' );
lbProperties.Items.Add( 'Computer : ' + IntToStr( Selected.Skills[SKILL_COMPUTER] ) + '%' );
lbProperties.Items.Add( 'Demolition : ' + IntToStr( Selected.Skills[SKILL_DEMOLITION] ) + '%' );
lbProperties.Items.Add( 'Stealth : ' + IntToStr( Selected.Skills[SKILL_STEALTH] ) + '%' );
lbProperties.Items.Add( 'Medicine : ' + IntToStr( Selected.Skills[SKILL_MEDICINE] ) + '%' );
lbProperties.Items.Add( 'Forgery : ' + IntToStr( Selected.Skills[SKILL_FORGERY] ) + '%' );
end;
procedure THireCriminal.Button1Click(Sender: TObject);
begin
ModalResult := mrCancel;
end;
end.
|
unit Eagle.Alfred.DprojParser;
interface
uses
System.SysUtils,System.Win.ComObj, XML.adomxmldom, ActiveX, XMLDoc, MSXML, MSXMLDOM, XMLIntf,
System.IOUtils, System.Classes, System.Generics.Collections;
type
TDprojParser = class
private
FXMLDocument: IXMLDomDocument;
FPackagePath: string;
FProjectName: string;
FDprojFile: string;
FDprFile: string;
FVersionString: string;
FUnitsList: TList<string>;
procedure SetDprojFile(const Value: string);
procedure SetVersionString(const Value: string);
procedure UpdateDpr;
public
procedure ChangeVersion;
constructor Create(const PackagePath, ProjectName: string);
destructor Destroy; override;
procedure AddForm(const UnitName, FormName, Path: string);
procedure AddUnit(const Name, Path: string);
procedure Save;
property VersionString: string read FVersionString write SetVersionString;
end;
implementation
procedure TDprojParser.AddForm(const UnitName, FormName, Path: string);
var
ItemGroup, NodeBase, Node: IXMLDOMNode;
begin
ItemGroup := FXMLDocument.selectSingleNode('/Project/ItemGroup');
NodeBase := FXMLDocument.selectSingleNode('/Project/ItemGroup/DCCReference/Form').firstChild;
Node := NodeBase.parentNode.parentNode.cloneNode(True);
Node.attributes.getNamedItem('Include').Text := Path;
Node.firstChild.Text := FormName;
ItemGroup.appendChild(Node);
FUnitsList.Add(' ' + UnitName.Replace('.pas', ' in ') + Path.QuotedString + ',');
end;
procedure TDprojParser.AddUnit(const Name, Path: string);
var
ItemGroup, NodeBase, Node: IXMLDOMNode;
begin
ItemGroup := FXMLDocument.selectSingleNode('/Project/ItemGroup');
NodeBase := FXMLDocument.selectSingleNode('/Project/ItemGroup/DCCReference').firstChild;
Node := NodeBase.parentNode.cloneNode(True);
Node.attributes.getNamedItem('Include').Text := Path;
if node.hasChildNodes then
Node.removeChild(Node.firstChild);
ItemGroup.appendChild(Node);
FUnitsList.Add(' ' + Name.Replace('.pas', ' in ') + Path.QuotedString + ',');
end;
procedure TDprojParser.ChangeVersion;
var
Project, Node, VerInfo_Keys: IXMLNode;
I, J, K: Integer;
Keys_String: String;
Keys : TArray<string>;
Version: TArray<string>;
begin
{ try
FXMLDocument.LoadFromFile(DprojFile);
Project := FXMLDocument.ChildNodes.First;
J := Project.ChildNodes.Count - 1;
for I := 0 to J do
begin
Node := Project.ChildNodes.Nodes[I];
VerInfo_Keys := Node.ChildNodes.FindNode('VerInfo_Keys');
if VerInfo_Keys <> nil then
begin
Keys_String := VerInfo_Keys.NodeValue;
Keys := Keys_String.Split([';']);
for K := 0 to Length(Keys) - 1 do
begin
Version := Keys[K].Split(['=']);
if Version[0]= 'FileVersion' then
Keys[K] := 'FileVersion=' + FVersionString;
if Version[0]= 'ProductVersion' then
Keys[K] := 'ProductVersion=' + FVersionString;
end;
Keys_String := '';
for K := 0 to Length(Keys) - 1 do
Keys_String := Keys_String + Keys[K] + ';';
Keys_String := Keys_String.Substring(0,Keys_String.Length -1);
VerInfo_Keys.NodeValue := Keys_String;
end;
end;
FXMLDocument.SaveToFile(Dprojfile);
except
on E: Exception do
WriteLn(E.ClassName + ':' + E.Message)
end;
}
end;
constructor TDprojParser.Create(const PackagePath, ProjectName: string);
begin
CoInitialize(nil);
FPackagePath := PackagePath;
FProjectName := ProjectName;
FDprojFile := FPackagePath + ProjectName + '.dproj';
FDprFile := FPackagePath + ProjectName + '.dpr';
FUnitsList := TList<string>.Create;
FXMLDocument := CreateOleObject('Microsoft.XMLDOM') as IXMLDomDocument;
FXMLDocument.async := False;
FXMLDocument.load(FDprojFile);
end;
destructor TDprojParser.Destroy;
begin
FUnitsList.Free;
end;
procedure TDprojParser.Save;
begin
UpdateDpr;
FXMLDocument.save(FDprojFile);
end;
procedure TDprojParser.SetDprojFile(const Value: string);
begin
FDprojFile := Value;
end;
procedure TDprojParser.SetVersionString(const Value: string);
begin
FVersionString := Value;
end;
procedure TDprojParser.UpdateDpr;
var
DprFile: TStringList;
I, Count: Integer;
Line: string;
begin
DprFile := TStringList.Create;
try
DprFile.LoadFromFile(FDprFile);
Count := DprFile.Count -1;
for I := 0 to Count do
begin
Line := DprFile.Strings[I];
if Line.EndsWith('.pas'';') then
Break;
end;
for Line in FUnitsList do
begin
DprFile.Insert(I, Line);
Inc(I);
end;
DprFile.SaveToFile(FDprFile);
finally
DprFile.Free;
end;
end;
end.
|
{$MODE OBJFPC}
program MaxRect;
const
InputFile = 'RECT.INP';
OutputFile = 'RECT.OUT';
maxMN = Round(5E5);
var
stack: array[1..maxMN] of Integer;
top: Integer;
h: array[1..maxMN] of Integer;
left, right: array[1..maxMN] of Integer;
m, n: Integer;
resS: Int64;
procedure Enter;
var
f: TextFile;
i: Integer;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, m, n);
for i := 1 to n do Read(f, h[i]);
finally
CloseFile(F);
end;
end;
function Get: Integer;
begin
Result := stack[top];
end;
procedure Pop;
begin
Dec(top);
end;
procedure Push(i: Integer);
begin
Inc(top);
stack[top] := i;
end;
procedure DoAnalyse;
var
i: Integer;
begin
top := 0;
for i := 1 to n do
begin
while (top <> 0) and (h[Get] >= h[i]) do
Pop;
if top = 0 then left[i] := 0
else left[i] := Get;
Push(i);
end;
top := 0;
for i := n downto 1 do
begin
while (top <> 0) and (h[Get] >= h[i]) do
Pop;
if top = 0 then right[i] := n + 1
else right[i] := Get;
Push(i);
end;
end;
procedure Solve;
var
i: Integer;
temp: Int64;
begin
DoAnalyse;
resS := -1;
for i := 1 to n do
begin
temp := Int64(right[i] - left[i] - 1) * h[i];
if resS < temp then
resS := temp;
end;
for i := 1 to n do h[i] := m - h[i];
DoAnalyse;
for i := 1 to n do
begin
temp := Int64(right[i] - left[i] - 1) * h[i];
if resS < temp then
resS := temp;
end;
end;
procedure PrintResult;
var
f: TextFile;
i: Integer;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
Write(f, resS);
finally
CloseFile(f);
end;
end;
begin
Enter;
Solve;
PrintResult;
end.
5 9
1 3 4 4 5 4 4 3 1
|
{
lzRichEdit
Copyright (C) 2010 Elson Junio elsonjunio@yahoo.com.br
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library 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 RichBox;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, StdCtrls, Graphics, LCLType, LCLProc;
type
TNumberingStyle=( nsNone, nsBullets);
TCustomRichBox = class;
{ TTextAttributes }
TTextAttributes = class(TPersistent)
private
FRichBox: TCustomRichBox;
private
function GetColor: TColor;
procedure SetColor(Value: TColor);
function GetName: TFontName;
procedure SetName(Value: TFontName);
function GetSize: Integer;
procedure SetSize(Value: Integer);
function GetStyle: TFontStyles;
procedure SetStyle(Value: TFontStyles);
function GetCharset: TFontCharset;
procedure SetCharset(Value: TFontCharset);
function GetPitch: TFontPitch;
procedure SetPitch(Value: TFontPitch);
function GetProtected: Boolean;
procedure SetProtected(Value: Boolean);
public
constructor Create(AOwner: TCustomRichBox);
procedure Assign(Source: TPersistent); override;
property Charset: TFontCharset read GetCharset write SetCharset;
property Color: TColor read GetColor write SetColor;
property Name: TFontName read GetName write SetName;
property Pitch: TFontPitch read GetPitch write SetPitch;
property Protect: Boolean read GetProtected write SetProtected;
property Size: Integer read GetSize write SetSize;
property Style: TFontStyles read GetStyle write SetStyle;
end;
{ TParaAttributes }
TParaAttributes = class(TPersistent)
private
FRichBox: TCustomRichBox;
private
function GetAlignment: TAlignment;
procedure SetAlignment(Value: TAlignment);
function GetFirstIndent: LongInt;
procedure SetFirstIndent(Value:LongInt);
function GetLeftIndent:LongInt;
procedure SetLeftIndent(Value:LongInt);
function GetNumbering: TNumberingStyle;
procedure SetNumbering(Value: TNumberingStyle);
function GetRightIndent: LongInt;
procedure SetRightIndent(Value:LongInt);
function GetTab(Index: Byte): Longint;
procedure SetTab(Index: Byte; Value: Longint);
function GetTabCount: Integer;
procedure SetTabCount(Value: Integer);
public
constructor Create(AOwner: TCustomRichBox);
procedure Assign(Source: TPersistent); override;
property Alignment: TAlignment read GetAlignment write SetAlignment;
property FirstIndent: Longint read GetFirstIndent write SetFirstIndent;
property LeftIndent: Longint read GetLeftIndent write SetLeftIndent;
property Numbering: TNumberingStyle read GetNumbering write SetNumbering;
property RightIndent: Longint read GetRightIndent write SetRightIndent;
property Tab[Index: Byte]: Longint read GetTab write SetTab;
property TabCount: Integer read GetTabCount write SetTabCount;
end;
{ TCustomRichBox }
TCustomRichBox = class(TCustomMemo)
private
FSelAttributes: TTextAttributes;
FParagraph: TParaAttributes;
FPlainText: Boolean;
protected
class procedure WSRegisterClass; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetRealTextBuf: String;
function GetRealtextSel: String;
procedure SaveToStream(Stream: TStream);
procedure LoadFromStream(Stream: TStream);
public
property Paragraph: TParaAttributes read FParagraph;
property SelAttributes: TTextAttributes read FSelAttributes;
property PlainText:Boolean read FPlainText write FPlainText default False;
end;
{ TCustomRichBox }
TRichBox = class(TCustomRichBox)
published
property Align;
property Alignment;
property Anchors;
property BidiMode;
property BorderSpacing;
property BorderStyle;
property CharCase;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property Lines;
property MaxLength;
property OnChange;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEditingDone;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnStartDrag;
property OnUTF8KeyPress;
property ParentBidiMode;
property ParentColor;
property ParentFont;
property PopupMenu;
property ParentShowHint;
property ReadOnly;
property ScrollBars;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property WantReturns;
property WantTabs;
property WordWrap;
end;
TlzRichEdit = class(TRichBox)
end;
procedure Register;
implementation
uses
WSRichBox;
procedure Register;
begin
RegisterComponents('Common Controls', [TlzRichEdit]);
end;
{$I tparaattributes.inc}
{$I ttextattributes.inc}
{$I tcustomrichbox.inc}
initialization
{$I lzrichedit.lrs}
end.
|
unit nsQuestionsWithChoices;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Data"
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Data/nsQuestionsWithChoices.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<UtilityPack::Class>> F1 Базовые определения предметной области::LegalDomain::Data::Сюда вынес все сообщения из StdRes с Choices::nsQuestionsWithChoices
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3StringIDEx,
l3MessageID
;
var
{ Локализуемые строки Questions }
str_ChangedDocumentOnControl : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ChangedDocumentOnControl'; rValue : 'В документ на контроле внесены изменения. Выберите действие:');
{ 'В документ на контроле внесены изменения. Выберите действие:' }
str_SearchUnresolvedContext : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'SearchUnresolvedContext'; rValue : 'В запросе есть слова, поиск по которым может не дать корректного результата: {color:Red}{italic:true}%s{italic}{color}.');
{ 'В запросе есть слова, поиск по которым может не дать корректного результата: [color:Red][italic:true]%s[italic][color].' }
str_DropListToList : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'DropListToList'; rValue : 'Выделенные элементы:');
{ 'Выделенные элементы:' }
str_mtNotGarantDomain : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'mtNotGarantDomain'; rValue : 'Переход по внешней ссылке');
{ 'Переход по внешней ссылке' }
str_EmptySearchResultInBaseList : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'EmptySearchResultInBaseList'; rValue : 'Поиск в базовом (сокращенном) списке не дал результатов по заданному Вами запросу. Выберите варианты для продолжения работы:');
{ 'Поиск в базовом (сокращенном) списке не дал результатов по заданному Вами запросу. Выберите варианты для продолжения работы:' }
str_AutologinDuplicate : Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'AutologinDuplicate'; rValue : 'Пользователь с таким именем уже существует. Сделайте выбор:');
{ 'Пользователь с таким именем уже существует. Сделайте выбор:' }
str_ChangedDocumentOnControl_SettingsCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangedDocumentOnControl_SettingsCaption'; rValue : 'Действие при выборе измененного документа на контроле');
{ undefined }
implementation
uses
Dialogs
;
var
{ Варианты выбора для диалога ChangedDocumentOnControl }
str_ChangedDocumentOnControl_Choice_Open : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangedDocumentOnControl_Choice_Open'; rValue : 'Открыть текст документа');
{ 'Открыть текст документа' }
str_ChangedDocumentOnControl_Choice_Compare : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangedDocumentOnControl_Choice_Compare'; rValue : 'Сравнить с предыдущей редакцией');
{ 'Сравнить с предыдущей редакцией' }
var
{ Варианты выбора для диалога SearchUnresolvedContext }
str_SearchUnresolvedContext_Choice_Back : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'SearchUnresolvedContext_Choice_Back'; rValue : 'Вернуться в карточку и отредактировать запрос');
{ 'Вернуться в карточку и отредактировать запрос' }
str_SearchUnresolvedContext_Choice_Continue : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'SearchUnresolvedContext_Choice_Continue'; rValue : 'Продолжить поиск');
{ 'Продолжить поиск' }
var
{ Варианты выбора для диалога DropListToList }
str_DropListToList_Choice_Append : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DropListToList_Choice_Append'; rValue : 'Добавить в существующий список');
{ 'Добавить в существующий список' }
str_DropListToList_Choice_Copy : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DropListToList_Choice_Copy'; rValue : 'Копировать в новый список');
{ 'Копировать в новый список' }
var
{ Варианты выбора для диалога mtNotGarantDomain }
str_mtNotGarantDomain_Choice_Open : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mtNotGarantDomain_Choice_Open'; rValue : 'Перейти, открыв во внешнем браузере ');
{ 'Перейти, открыв во внешнем браузере ' }
str_mtNotGarantDomain_Choice_Stay : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mtNotGarantDomain_Choice_Stay'; rValue : 'Не переходить');
{ 'Не переходить' }
var
{ Варианты выбора для диалога EmptySearchResultInBaseList }
str_EmptySearchResultInBaseList_Choice_Expand : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'EmptySearchResultInBaseList_Choice_Expand'; rValue : 'расширить базовый список до полного и произвести поиск в нем');
{ 'расширить базовый список до полного и произвести поиск в нем' }
str_EmptySearchResultInBaseList_Choice_AllBase : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'EmptySearchResultInBaseList_Choice_AllBase'; rValue : 'произвести поиск по всему информационному банку');
{ 'произвести поиск по всему информационному банку' }
var
{ Варианты выбора для диалога AutologinDuplicate }
str_AutologinDuplicate_Choice_Back : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'AutologinDuplicate_Choice_Back'; rValue : 'вернуться к регистрации нового пользователя, изменив регистрационные данные');
{ 'вернуться к регистрации нового пользователя, изменив регистрационные данные' }
str_AutologinDuplicate_Choice_Login : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'AutologinDuplicate_Choice_Login'; rValue : 'войти в систему с указанными регистрационными данными, использовав введенное имя пользователя');
{ 'войти в систему с указанными регистрационными данными, использовав введенное имя пользователя' }
initialization
// Инициализация str_ChangedDocumentOnControl_Choice_Open
str_ChangedDocumentOnControl_Choice_Open.Init;
// Инициализация str_ChangedDocumentOnControl_Choice_Compare
str_ChangedDocumentOnControl_Choice_Compare.Init;
// Инициализация str_SearchUnresolvedContext_Choice_Back
str_SearchUnresolvedContext_Choice_Back.Init;
// Инициализация str_SearchUnresolvedContext_Choice_Continue
str_SearchUnresolvedContext_Choice_Continue.Init;
// Инициализация str_DropListToList_Choice_Append
str_DropListToList_Choice_Append.Init;
// Инициализация str_DropListToList_Choice_Copy
str_DropListToList_Choice_Copy.Init;
// Инициализация str_mtNotGarantDomain_Choice_Open
str_mtNotGarantDomain_Choice_Open.Init;
// Инициализация str_mtNotGarantDomain_Choice_Stay
str_mtNotGarantDomain_Choice_Stay.Init;
// Инициализация str_EmptySearchResultInBaseList_Choice_Expand
str_EmptySearchResultInBaseList_Choice_Expand.Init;
// Инициализация str_EmptySearchResultInBaseList_Choice_AllBase
str_EmptySearchResultInBaseList_Choice_AllBase.Init;
// Инициализация str_AutologinDuplicate_Choice_Back
str_AutologinDuplicate_Choice_Back.Init;
// Инициализация str_AutologinDuplicate_Choice_Login
str_AutologinDuplicate_Choice_Login.Init;
// Инициализация str_ChangedDocumentOnControl
str_ChangedDocumentOnControl.Init;
str_ChangedDocumentOnControl.AddChoice(str_ChangedDocumentOnControl_Choice_Open);
str_ChangedDocumentOnControl.AddChoice(str_ChangedDocumentOnControl_Choice_Compare);
str_ChangedDocumentOnControl.SetDlgType(mtConfirmation);
str_ChangedDocumentOnControl.SetSettingsCaption(str_ChangedDocumentOnControl_SettingsCaption);
// Инициализация str_SearchUnresolvedContext
str_SearchUnresolvedContext.Init;
str_SearchUnresolvedContext.AddChoice(str_SearchUnresolvedContext_Choice_Back);
str_SearchUnresolvedContext.AddChoice(str_SearchUnresolvedContext_Choice_Continue);
str_SearchUnresolvedContext.SetDlgType(mtConfirmation);
// Инициализация str_DropListToList
str_DropListToList.Init;
str_DropListToList.AddChoice(str_DropListToList_Choice_Append);
str_DropListToList.AddChoice(str_DropListToList_Choice_Copy);
str_DropListToList.SetDlgType(mtConfirmation);
// Инициализация str_mtNotGarantDomain
str_mtNotGarantDomain.Init;
str_mtNotGarantDomain.AddChoice(str_mtNotGarantDomain_Choice_Open);
str_mtNotGarantDomain.AddChoice(str_mtNotGarantDomain_Choice_Stay);
str_mtNotGarantDomain.SetDlgType(mtConfirmation);
// Инициализация str_EmptySearchResultInBaseList
str_EmptySearchResultInBaseList.Init;
str_EmptySearchResultInBaseList.AddChoice(str_EmptySearchResultInBaseList_Choice_Expand);
str_EmptySearchResultInBaseList.AddChoice(str_EmptySearchResultInBaseList_Choice_AllBase);
str_EmptySearchResultInBaseList.SetDlgType(mtConfirmation);
// Инициализация str_AutologinDuplicate
str_AutologinDuplicate.Init;
str_AutologinDuplicate.AddChoice(str_AutologinDuplicate_Choice_Back);
str_AutologinDuplicate.AddChoice(str_AutologinDuplicate_Choice_Login);
str_AutologinDuplicate.SetDlgType(mtWarning);
// Инициализация str_ChangedDocumentOnControl_SettingsCaption
str_ChangedDocumentOnControl_SettingsCaption.Init;
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 ClpPlainDsaEncoding;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
Math,
ClpBigInteger,
ClpIDsaEncoding,
ClpIPlainDsaEncoding,
ClpBigIntegers,
ClpArrayUtils,
ClpCryptoLibTypes;
resourcestring
SInvalidEncodingLength = 'Encoding has incorrect length, "%s"';
SValueOutOfRange = 'Value out of range, "%s"';
type
TPlainDsaEncoding = class(TInterfacedObject, IDsaEncoding, IPlainDsaEncoding)
strict private
class var
FInstance: IPlainDsaEncoding;
class function GetInstance: IPlainDsaEncoding; static; inline;
class constructor PlainDsaEncoding();
strict protected
function CheckValue(const n, x: TBigInteger): TBigInteger; virtual;
function DecodeValue(const n: TBigInteger; const buf: TCryptoLibByteArray;
off, len: Int32): TBigInteger; virtual;
procedure EncodeValue(const n, x: TBigInteger;
const buf: TCryptoLibByteArray; off, len: Int32); virtual;
public
function Decode(const n: TBigInteger; const encoding: TCryptoLibByteArray)
: TCryptoLibGenericArray<TBigInteger>; virtual;
function Encode(const n, r, s: TBigInteger): TCryptoLibByteArray; virtual;
class property Instance: IPlainDsaEncoding read GetInstance;
end;
implementation
{ TPlainDsaEncoding }
function TPlainDsaEncoding.CheckValue(const n, x: TBigInteger): TBigInteger;
begin
if ((x.SignValue < 0) or ((x.CompareTo(n) >= 0))) then
begin
raise EArgumentCryptoLibException.CreateResFmt(@SValueOutOfRange, ['x']);
end;
result := x;
end;
function TPlainDsaEncoding.Decode(const n: TBigInteger;
const encoding: TCryptoLibByteArray): TCryptoLibGenericArray<TBigInteger>;
var
valueLength: Int32;
begin
valueLength := TBigIntegers.GetUnsignedByteLength(n);
if (System.Length(encoding) <> (valueLength * 2)) then
begin
raise EArgumentCryptoLibException.CreateResFmt(@SInvalidEncodingLength,
['encoding']);
end;
result := TCryptoLibGenericArray<TBigInteger>.Create
(DecodeValue(n, encoding, 0, valueLength), DecodeValue(n, encoding,
valueLength, valueLength));
end;
function TPlainDsaEncoding.DecodeValue(const n: TBigInteger;
const buf: TCryptoLibByteArray; off, len: Int32): TBigInteger;
begin
result := CheckValue(n, TBigInteger.Create(1, buf, off, len));
end;
function TPlainDsaEncoding.Encode(const n, r, s: TBigInteger)
: TCryptoLibByteArray;
var
valueLength: Int32;
begin
valueLength := TBigIntegers.GetUnsignedByteLength(n);
System.SetLength(result, valueLength * 2);
EncodeValue(n, r, result, 0, valueLength);
EncodeValue(n, s, result, valueLength, valueLength);
end;
procedure TPlainDsaEncoding.EncodeValue(const n, x: TBigInteger;
const buf: TCryptoLibByteArray; off, len: Int32);
var
bs: TCryptoLibByteArray;
bsOff, bsLen, pos: Int32;
begin
bs := CheckValue(n, x).ToByteArrayUnsigned();
bsOff := Max(0, System.Length(bs) - len);
bsLen := System.Length(bs) - bsOff;
pos := len - bsLen;
TArrayUtils.Fill(buf, off, off + pos, Byte(0));
System.Move(bs[bsOff], buf[off + pos], bsLen * System.SizeOf(Byte));
end;
class function TPlainDsaEncoding.GetInstance: IPlainDsaEncoding;
begin
result := FInstance;
end;
class constructor TPlainDsaEncoding.PlainDsaEncoding;
begin
FInstance := TPlainDsaEncoding.Create();
end;
end.
|
unit NurseStationStorageU;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.IB,
FireDAC.Phys.IBDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
System.JSON;
type
TNurseStationStorage = class(TDataModule)
FDConnection1: TFDConnection;
qrySelectId: TFDQuery;
qryUpdate: TFDQuery;
qryInsert: TFDQuery;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
FPath : String;
function ExistPatient(const AUserId : string) : boolean;
public
constructor Create(AOwner: TComponent; const APath : String);reintroduce;
{ Public declarations }
public
procedure AddDataPatient(const AData : TJSONObject);
function GetDataPatient(const AUserId : String): TJSONObject;
end;
var
NurseStationStorage: TNurseStationStorage;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
{ TNurseStationStorage }
procedure TNurseStationStorage.AddDataPatient(const AData: TJSONObject);
begin
// Insert or update patient row
if(ExistPatient(AData.GetValue('id').Value))then // Update
begin
qryUpdate.Params.ParamByName('heart').Value := AData.GetValue('heart_rate').Value;
qryUpdate.Params.ParamByName('weight').Value := AData.GetValue('weight').Value;
qryUpdate.Params.ParamByName('id').Value := AData.GetValue('id').Value;
qryUpdate.ExecSQL();
end
else
begin // Insert
qryInsert.Params.ParamByName('heart').Value := AData.GetValue('heart_rate').Value;
qryInsert.Params.ParamByName('weight').Value := AData.GetValue('weight').Value;
qryInsert.Params.ParamByName('id').Value := AData.GetValue('id').Value;
qryInsert.ExecSQL();
end;
end;
constructor TNurseStationStorage.Create(AOwner: TComponent; const APath: String);
begin
inherited Create(AOwner);
FPath := APath;
end;
procedure TNurseStationStorage.DataModuleCreate(Sender: TObject);
begin
// C:\Developer\Embarcadero\NurseDemo\Final\Database\NURSESDB.IB
//FDConnection1.Params.Database := FPath + '..\..\..\DATABASE\NURSESDB.IB';
FDConnection1.Connected := True;
end;
function TNurseStationStorage.ExistPatient(const AUserId: string): boolean;
begin
if(not FDConnection1.Connected)then
FDConnection1.Connected := True;
qrySelectId.ParamByName('id').Value := AUserId;
qrySelectId.Active := True;
if(qrySelectId.Eof)then
Result := False
else
Result := True;
qrySelectId.Active := False;
end;
function TNurseStationStorage.GetDataPatient(const AUserId: String): TJSONObject;
begin
Result := TJSONObject.Create();
// Assign the Id
Result.AddPair('Id', AUserId);
if(not FDConnection1.Connected)then
FDConnection1.Connected := True;
qrySelectId.ParamByName('id').Value := AUserId;
qrySelectId.Active := True;
if(not qrySelectId.Eof) then
begin
Result.AddPair('heart_rate', TJSONString.Create(qrySelectId.FieldByName('heart_rate').AsString));
Result.AddPair('weight', TJSONString.Create(qrySelectId.FieldByName('weight').AsString));
end
else
begin
Result.AddPair('heart_rate', '0');
Result.AddPair('weight', '0');
end;
qrySelectId.Active := False;
end;
end.
|
unit Model_Instruction;
interface
uses
System.SysUtils,
System.Classes, System.UITypes, Data.FMTBcd, Data.DB, FMX.Grid,
Datasnap.DBClient,
Data.SqlExpr, System.Generics.Collections, FMX.Dialogs,
ClientClassesUnit1, ClientModuleUnit1, DBXJSON;
type
TInstructionLink = Class
public
InstructionCode: String;
MenuItemCode: String;
MenuItemDescription1: String;
MenuItemDescription2: String;
Qty: Double;
Condition: Integer;
Price: Double;
MaximunCharge: Boolean;
Kind: Integer;
AllowDiscount: Boolean;
TaxRate: Double;
Constructor Create;
function GetDescription(Index: Integer): String;
End;
TInstructionLinks = Class
public
InstructionLinkList: TList<TInstructionLink>;
Constructor Create;
function GetInstructionByCode(ItemCode: String): TList<TInstructionLink>;
End;
var
ClientDataSet: TClientDataSet;
proxy: TServerMethodsClient;
implementation
{ TInstructionLinks }
constructor TInstructionLinks.Create;
var
newInstructionLink: TInstructionLink;
begin
proxy := ClientModule1.ServerMethods1Client;
ClientDataSet := TClientDataSet.Create(nil);
ClientDataSet.XMLData := proxy.GetInstructionLinks;
InstructionLinkList := TList<TInstructionLink>.Create;
while not ClientDataSet.Eof do
begin
newInstructionLink := TInstructionLink.Create;
newInstructionLink.InstructionCode := ClientDataSet.FieldByName
('Code').AsString;
newInstructionLink.MenuItemCode := ClientDataSet.FieldByName
('ItemCode').AsString;
newInstructionLink.MenuItemDescription1 :=
ClientDataSet.FieldByName('Description1').AsString;
newInstructionLink.MenuItemDescription2 :=
ClientDataSet.FieldByName('Description2').AsString;
newInstructionLink.Qty := ClientDataSet.FieldByName('Qty').AsFloat;
newInstructionLink.Condition := ClientDataSet.FieldByName('Condition')
.AsInteger;
newInstructionLink.Price := ClientDataSet.FieldByName('Price').AsFloat;
newInstructionLink.MaximunCharge := ClientDataSet.FieldByName
('MaximunCharge').AsBoolean;
newInstructionLink.Kind := ClientDataSet.FieldByName('Kind').AsInteger;
newInstructionLink.AllowDiscount := ClientDataSet.FieldByName
('AllowDiscount').AsBoolean;
newInstructionLink.TaxRate := ClientDataSet.FieldByName('TaxRate').AsFloat;
InstructionLinkList.Add(newInstructionLink);
ClientDataSet.Next;
end;
end;
function TInstructionLinks.GetInstructionByCode(ItemCode: String)
: TList<TInstructionLink>;
var
CurrentInstructionLink: TList<TInstructionLink>;
i: Integer;
begin
CurrentInstructionLink := TList<TInstructionLink>.Create;
for i := 0 to InstructionLinkList.Count - 1 do
begin
if InstructionLinkList.Items[i].MenuItemCode = ItemCode then
CurrentInstructionLink.Add(InstructionLinkList.Items[i]);
end;
result := CurrentInstructionLink;
end;
{ TInstructionLink }
constructor TInstructionLink.Create;
begin
end;
function TInstructionLink.GetDescription(Index: Integer): String;
begin
if Index = 1 then
result := MenuItemDescription1;
if Index = 2 then
result := MenuItemDescription2;
end;
end.
|
program a2test1;
{ This program contains 8 test cases to test your implementation. In order
to run this program you must compile the files 'a2unit.pas' and 'BinTrADT.pas'
to the current directory, or to the C:/work directory. After compiling
you should see files named 'a2unit.tpu' and 'BinTrADT.tpu' on the disk.
The program runs 8 labeled tests one by one. You must hit enter to
continue after each test.
NOTE: These tests are by no means exhaustive. You are encouraged to
do your own testing as well, as there may still be subtle bugs in your
code even though they pass the tests here. }
uses a2unit, BinaryTreeADT;
var Collection1, Collection2: collection;
{ Value: collection_element; }
begin
(* 1. Test creation of collections *)
Writeln('1. Create_Collection:');
Create_Collection(Collection1);
Create_Collection(Collection2);
Writeln('Collection1 should be empty (size 0)...');
Writeln;
Writeln('Actual contents of Collection1: ');
Print(Collection1);
Writeln('Reported Size: ',Size(Collection1));
Writeln;Readln;
(* 2. Test insertion *)
Writeln('2. INSERTION');
Insert(Collection1, 'chimpanzee');
Insert(Collection1, 'orangutan');
Insert(Collection1, 'gorilla');
Insert(Collection1, 'bonobo');
Insert(Collection1, 'human');
Insert(Collection1, 'tapir');
Insert(Collection1, 'gerbil');
Write ('Collection1 should contain "chimpanzee", "orangutan", "gorilla", ');
Writeln ('"bonobo", "human", "tapir", and "gerbil" in sorted order (Size 7)...');
Writeln;
Writeln ('Actual Contents of Collection1:');
Print(Collection1);
Writeln;
Writeln ('Reported size: ', Size(Collection1));
Writeln;readln;
(* 3. Test Is_Empty *)
Writeln('3. IS_EMPTY:');
if not Is_Empty(Collection2) then
writeln('Collection2 should be empty, but Is_Empty returned FALSE')
else
writeln('Collection2 ok');
if Is_Empty(Collection1) then
writeln('Collection1 not empty, but Is_Empty returned TRUE')
else
writeln('Collection1 ok');
writeln;Readln;
(* 4. Test deletion *)
Writeln('4. DELETION');
Delete(Collection1, 'chimpanzee');
Delete(Collection1, 'gorilla');
Delete(Collection1, 'hippopotamus');
Writeln ('Collection1 should contain "orangutan", "human", "bonobo", "gerbil", and "tapir" in sorted order (Size 5)...');
Writeln;
Writeln ('Actual Contents of Collection1:');
Print(Collection1);
Writeln;
Writeln ('Reported size: ', Size(Collection1));
writeln;Readln;
(* 5. Join with empty collection*)
Writeln('5. JOIN TO EMPTY COLLECTION:');
Join(Collection1, Collection2);
Writeln('Collection1 should be the same as before.');
Writeln;
Writeln ('Actual Contents of Collection1:');
Print(Collection1);
Writeln;
Writeln ('Reported size: ', Size(Collection1));
writeln; readln;
(* 6. Join to non-empty collection*)
Writeln ('6. JOIN TO NON-EMPTY COLLECTION');
Writeln ('Re-creating Collection2');
Create_Collection(Collection2);
If Size(Collection2) <> 0 then
writeln('Error in re-creation of Collection2');
Insert(Collection2, 'rhesus monkey');
Insert(Collection2, 'snow monkey');
Insert(Collection2, 'marmoset');
Writeln ('Collection2 should contain "snow monkey", "rhesus monkey", and "marmoset" in sorted order (Size 3)...');
Writeln;
Writeln ('Actual Contents of Collection2:');
Print(Collection2);
Writeln;
Writeln ('Reported size: ', Size(Collection2));
Writeln; readln;
Join(Collection2, Collection1);
Write ('Collection2 should contain "orangutan", "human", "bonobo", "gerbil", "tapir", ');
Writeln ('"snow monkey", "rhesus monkey", and "marmoset" in sorted order (Size 8)...');
Writeln;
Writeln ('Actual Contents of Collection2:');
Print(Collection2);
Writeln;
Writeln ('Reported size: ', Size(Collection2));
Writeln; readln;
(* 7. One More Deletion*)
Writeln ('7. ANOTHER DELETION');
Delete(Collection2, 'gerbil');
Write ('Collection2 should contain "orangutan", "human", "bonobo", "tapir", ');
Writeln ('"snow monkey", "rhesus monkey", and "marmoset" in sorted order (Size 7)...');
Writeln;
Writeln ('Actual Contents of Collection2:');
Print(Collection2);
Writeln;
Writeln ('Reported size: ', Size(Collection2));
Writeln; readln;
(* 8. Destroy and check for memory leak *)
Writeln('8. MEMCHECK:');
Destroy(Collection2);
IF MemCheck then
writeln('Memory check passed')
else
writeln('Memory check failed - possible memory leak');
writeln;readln;
Writeln('*** DONE ***');
end. |
unit akShell;
interface
uses Windows, ShlObj;
const
BIF_NEWDIALOGSTYLE = $0040;
CSIDL_APPDATA = $001A;
//------------------------------------------------------------------------------
// Работа с системными каталогами ==============================================
// Возвращает путь к каталогу "Автозагрузка"
function GetStartupFolder: string;
// Возврашает "True", если в автозагрузке есть линк с именем LinkName
function IsInStartup(LinkName: string): Boolean;
// Открывате htm-хелп
procedure OpenHelp(filen, page: string);
// Если SetIt=true, то функа создает линк с именем LinkName к файлу Filename.
// Если SetIt=false, то линк удаляется.
procedure SetStartup(Filename, LinkName: string; SetIt: Boolean);
// Позволяет выбрать фолдер
function SelectDir(hndl: THandle; TitleName: string; var folder: string; mode: Integer = CSIDL_DRIVES): Boolean;
implementation
uses Registry, ActiveX, comobj, SysUtils, ShellApi;
procedure OpenHelp(filen, page: string);
var resCd: Integer;
pg: string;
begin
resCd := 0;
if page <> '' then pg := '::' + page else pg := '';
if FileExists(filen) then
resCd := ShellExecute(0, 'open', 'hh.exe',
PChar(ExtractShortPathName(filen) + pg), nil, SW_SHOW);
if resCd <= 32 then
raise Exception.CreateFmt('Unable to open help file %s', [filen]);
end;
function GetStartupFolder: string;
var
pidl: PItemIdList;
Buffer: array[0..MAX_PATH] of Char;
begin
OleCheck(SHGetSpecialFolderLocation(0, CSIDL_STARTUP, pidl));
try
if SHGetPathFromIDList(pidl, Buffer) then
Result := Buffer;
finally
CoTaskMemFree(pidl);
end;
end;
function IsInStartup(LinkName: string): Boolean;
var
WideFile: WideString;
begin
WideFile := GetStartupFolder + '\' + LinkName + '.lnk';
Result := FileExists(WideFile);
end;
procedure SetStartup(Filename, LinkName: string; SetIt: Boolean);
var
MyObject: IUnknown;
MySLink: IShellLink;
MyPFile: IPersistFile;
WideFile: WideString;
begin
WideFile := GetStartupFolder + '\' + LinkName + '.lnk';
if fileexists(WideFile) then DeleteFile(WideFile);
if SetIt then
begin
MyObject := CreateComObject(CLSID_ShellLink);
MySLink := MyObject as IShellLink;
MyPFile := MyObject as IPersistFile;
with MySLink do
begin
SetPath(PChar(FileName));
SetWorkingDirectory(PChar(ExtractFilePath(FileName)));
end;
MyPFile.Save(PWChar(WideFile), False);
end;
end;
procedure BrowseCallbackProc(handle: hwnd; Msg: integer; lParam: integer; lpData: Integer); stdcall;
begin
if Msg = BFFM_INITIALIZED then
SendMessage(handle, BFFM_SETSELECTION, 1, lpData);
end;
function SelectDir(hndl: THandle; TitleName: string; var folder: string; mode: Integer): Boolean;
var
lpItemID: PItemIDList;
BrowseInfo: TBrowseInfo;
DisplayName: array[0..MAX_PATH] of char;
TempPath: array[0..MAX_PATH] of char;
ppIdl: PItemIdList;
begin
Result := false;
OleInitialize(nil);
try
SHGetSpecialFolderLocation(hndl, mode, ppIdl);
FillChar(BrowseInfo, sizeof(TBrowseInfo), #0);
BrowseInfo.pidlRoot := ppIdl;
BrowseInfo.hwndOwner := hndl;
BrowseInfo.pszDisplayName := @DisplayName;
BrowseInfo.lpszTitle := PChar(TitleName);
BrowseInfo.lParam := Integer(PChar(folder));
BrowseInfo.lpfn := @BrowseCallbackProc;
BrowseInfo.ulFlags := BIF_RETURNONLYFSDIRS or BIF_NEWDIALOGSTYLE;
lpItemID := SHBrowseForFolder(BrowseInfo);
if lpItemId <> nil then begin
SHGetPathFromIDList(lpItemID, TempPath);
Result := true;
folder := TempPath;
GlobalFreePtr(lpItemID);
end;
finally
OleUninitialize();
end;
end;
end.
|
namespace Sugar.Collections;
interface
uses
{$IF ECHOES}System.Linq,{$ENDIF}
Sugar;
type
Dictionary<T, U> = public class mapped to {$IF COOPER}java.util.HashMap<T,U>{$ELSEIF ECHOES}System.Collections.Generic.Dictionary<T,U>{$ELSEIF TOFFEE}Foundation.NSMutableDictionary where T is class, U is class;{$ENDIF}
private
public
method GetKeys: sequence of T;
method GetValues: sequence of U;
method GetItem(Key: T): U;
method SetItem(Key: T; Value: U);
constructor; mapped to constructor();
constructor(aCapacity: Integer);
{$IFNDEF ECHOES}
method GetSequence: sequence of KeyValuePair<T,U>;
{$ENDIF}
method &Add(Key: T; Value: U);
method Clear;
method TryGetValue(aKey: T; out aValue: U): Boolean;
method ContainsKey(Key: T): Boolean;
method ContainsValue(Value: U): Boolean;
method &Remove(Key: T): Boolean;
method ForEach(Action: Action<KeyValuePair<T, U>>);
property Item[Key: T]: U read GetItem write SetItem; default;
property Keys: sequence of T read GetKeys;
property Values: sequence of U read GetValues;
property Count: Integer read {$IF COOPER}mapped.size{$ELSEIF ECHOES OR TOFFEE}mapped.Count{$ENDIF};
{$IF TOFFEE}
operator Implicit(aDictionary: NSDictionary<T,U>): Dictionary<T,U>;
{$ENDIF}
end;
DictionaryHelpers = public static class
public
{$IFDEF COOPER}
method GetSequence<T, U>(aSelf: java.util.HashMap<T,U>) : sequence of KeyValuePair<T,U>; iterator;
method GetItem<T, U>(aSelf: java.util.HashMap<T,U>; aKey: T): U;
method Add<T, U>(aSelf: java.util.HashMap<T,U>; aKey: T; aVal: U);
{$ELSEIF TOFFEE}
method Add<T, U>(aSelf: NSMutableDictionary; aKey: T; aVal: U);
method GetItem<T, U>(aSelf: NSDictionary; aKey: T): U;
method GetSequence<T, U>(aSelf: NSDictionary) : sequence of KeyValuePair<T,U>; iterator;
{$ENDIF}
method Foreach<T, U>(aSelf: Dictionary<T, U>; aAction: Action<KeyValuePair<T, U>>);
end;
implementation
constructor Dictionary<T,U>(aCapacity: Integer);
begin
{$IF COOPER}
result := new java.util.HashMap<T,U>(aCapacity);
{$ELSEIF ECHOES}
result := new System.Collections.Generic.Dictionary<T,U>(aCapacity);
{$ELSEIF TOFFEE}
result := new Foundation.NSMutableDictionary withCapacity(aCapacity);
{$ENDIF}
end;
method Dictionary<T, U>.Add(Key: T; Value: U);
begin
{$IF COOPER}
DictionaryHelpers.Add(mapped, Key, Value);
{$ELSEIF ECHOES}
mapped.Add(Key, Value);
{$ELSEIF TOFFEE}
DictionaryHelpers.Add(mapped, Key, Value);
{$ENDIF}
end;
method Dictionary<T, U>.Clear;
begin
{$IF COOPER OR ECHOES}
mapped.Clear;
{$ELSEIF TOFFEE}
mapped.removeAllObjects;
{$ENDIF}
end;
method Dictionary<T, U>.ContainsKey(Key: T): Boolean;
begin
{$IF COOPER OR ECHOES}
exit mapped.ContainsKey(Key);
{$ELSEIF TOFFEE}
exit mapped.objectForKey(Key) <> nil;
{$ENDIF}
end;
method Dictionary<T, U>.ContainsValue(Value: U): Boolean;
begin
{$IF COOPER OR ECHOES}
exit mapped.ContainsValue(Value);
{$ELSEIF TOFFEE}
exit mapped.allValues.containsObject(NullHelper.ValueOf(Value));
{$ENDIF}
end;
method Dictionary<T, U>.ForEach(Action: Action<KeyValuePair<T, U>>);
begin
DictionaryHelpers.Foreach(self, Action);
end;
method Dictionary<T, U>.GetItem(Key: T): U;
begin
{$IF COOPER}
result := DictionaryHelpers.GetItem(mapped, Key);
{$ELSEIF ECHOES}
result := mapped[Key];
{$ELSEIF TOFFEE}
result := DictionaryHelpers.GetItem<T, U>(mapped, Key);
{$ENDIF}
end;
method Dictionary<T, U>.GetKeys: sequence of T;
begin
{$IF COOPER}
exit mapped.keySet;
{$ELSEIF ECHOES}
exit mapped.Keys;
{$ELSEIF TOFFEE}
exit mapped.allKeys;
{$ENDIF}
end;
method Dictionary<T, U>.GetValues: sequence of U;
begin
{$IF COOPER}
exit mapped.values;
{$ELSEIF ECHOES}
exit mapped.Values;
{$ELSEIF TOFFEE}
exit mapped.allValues;
{$ENDIF}
end;
method Dictionary<T, U>.&Remove(Key: T): Boolean;
begin
{$IF COOPER}
exit mapped.remove(Key) <> nil;
{$ELSEIF ECHOES}
exit mapped.Remove(Key);
{$ELSEIF TOFFEE}
result := ContainsKey(Key);
if result then
mapped.removeObjectForKey(Key);
{$ENDIF}
end;
method Dictionary<T, U>.SetItem(Key: T; Value: U);
begin
{$IF COOPER OR ECHOES}
mapped[Key] := Value;
{$ELSEIF TOFFEE}
mapped.setObject(NullHelper.ValueOf(Value)) forKey(Key);
{$ENDIF}
end;
{$IFDEF TOFFEE}
method DictionaryHelpers.Add<T, U>(aSelf: NSMutableDictionary; aKey: T; aVal: U);
begin
if aSelf.objectForKey(aKey) <> nil then raise new SugarArgumentException(ErrorMessage.KEY_EXISTS);
aSelf.setObject(NullHelper.ValueOf(aVal)) forKey(aKey);
end;
method DictionaryHelpers.GetItem<T, U>(aSelf: NSDictionary; aKey: T): U;
begin
var o := aSelf.objectForKey(aKey);
if o = nil then raise new SugarKeyNotFoundException();
exit NullHelper.ValueOf(o);
end;
method DictionaryHelpers.GetSequence<T, U>(aSelf: NSDictionary) : sequence of KeyValuePair<T,U>;
begin
for each el in aSelf.allKeys do
yield new KeyValuePair<T,U>(el, aSelf[el]);
end;
{$ENDIF}
{$IFDEF COOPER}
method DictionaryHelpers.GetSequence<T, U>(aSelf: java.util.HashMap<T,U>) : sequence of KeyValuePair<T,U>;
begin
for each el in aSelf.entrySet do begin
yield new KeyValue<T,U>(el.Key, el.Value);
end;
end;
method DictionaryHelpers.GetItem<T, U>(aSelf: java.util.HashMap<T,U>; aKey: T): U;
begin
if not aSelf.containsKey(aKey) then raise new SugarKeyNotFoundException();
exit aSelf[aKey];
end;
method DictionaryHelpers.Add<T, U>(aSelf: java.util.HashMap<T,U>; aKey: T; aVal: U);
begin
if aSelf.containsKey(aKey) then raise new SugarArgumentException(ErrorMessage.KEY_EXISTS);
aSelf.put(aKey, aVal)
end;
{$ENDIF}
method DictionaryHelpers.Foreach<T, U>(aSelf: Dictionary<T, U>; aAction: Action<KeyValuePair<T, U>>);
begin
for each el in aSelf.Keys do
aAction(new KeyValuePair<T,U>(T(el), U(aSelf.Item[el])));
end;
method Dictionary<T, U>.TryGetValue(aKey: T; out aValue: U): Boolean;
begin
{$IF ECHOES}
exit mapped.TryGetValue(aKey, out aValue);
{$ELSEIF COOPER}
aValue := mapped[aKey];
exit aValue <> nil;
{$ELSEIF TOFFEE}
aValue := mapped.objectForKey(aKey);
result := aValue <> nil;
aValue := NullHelper.ValueOf(aValue);
{$ENDIF}
end;
{$IFNDEF ECHOES}
method Dictionary<T,U>.GetSequence: sequence of KeyValuePair<T,U>;
begin
exit DictionaryHelpers.GetSequence<T, U>(self);
end;
{$ENDIF}
{$IF TOFFEE}
operator Dictionary<T,U>.Implicit(aDictionary: NSDictionary<T,U>): Dictionary<T,U>;
begin
if aDictionary is NSMutableDictionary then
result := Dictionary<T,U>(aDictionary)
else
result := Dictionary<T,U>(aDictionary:mutableCopy);
end;
{$ENDIF}
end. |
unit Model.Modalidades;
interface
type
TModalidades = class
private
FCodigo: Integer;
FDescricao: String;
FOperacao: String;
FLog: String;
public
property Codigo: Integer read FCodigo write FCodigo;
property Descricao: String read FDescricao write FDescricao;
property Operacao: String read FOperacao write FOperacao;
property Log: String read FLog write FLog;
constructor Create; overload;
constructor Create(pFCodigo: Integer; pFDescricao: String; pFOperacao: String; pFLog: String); overload;
end;
implementation
constructor TModalidades.Create;
begin
inherited Create;
end;
constructor TModalidades.Create(pFCodigo: Integer; pFDescricao: string; pFOperacao: string; pFLog: string);
begin
FCodigo := pFCodigo;
FDescricao := pFDescricao;
FOperacao := pFOperacao;
FLog := pFLog;
end;
end.
|
{****************************************************************************}
{* MOVES.PAS: This file contains the routines which generate, move, and *}
{* otherwise have to do (on a low level) with moves. *}
{****************************************************************************}
{****************************************************************************}
{* Attacked By: Given the row and column of a square, this routine will *}
{* tally the number of other pieces which attack (enemy pieces) or protect *}
{* (friendly pieces) the piece on that square. This is accomplished by *}
{* looking around the piece to all other locations from which a piece *}
{* could protect or protect. This routine does not count an attack by *}
{* en passent. This routine is called to see if a king is in check and *}
{* as part of the position strength calculation. *}
{****************************************************************************}
procedure AttackedBy (row, col : RowColType; var Attacked, _Protected : integer);
var dir, i, distance : integer;
PosRow, PosCol, IncRow, IncCol : RowColType;
FriendColor, EnemyColor : PieceColorType;
begin
{*** initialize ***}
Attacked := 0;
_Protected := 0;
FriendColor := Board[row, col].color;
if (FriendColor = C_WHITE) then begin
dir := 1; {*** row displacement from which an enemy pawn would attack ***}
EnemyColor := C_BLACK;
end else begin
dir := -1;
EnemyColor := C_WHITE;
end;
{*** count number of attacking pawns ***}
with Board[row + dir, col - 1] do
if (image = PAWN) and (color = EnemyColor) then Attacked := Attacked + 1;
with Board[row + dir, col + 1] do
if (image = PAWN) and (color = EnemyColor) then Attacked := Attacked + 1;
{*** count number of protecting pawns ***}
with Board[row - dir, col - 1] do
if (image = PAWN) and (color = FriendColor) then _Protected := _Protected + 1;
with Board[row - dir, col + 1] do
if (image = PAWN) and (color = FriendColor) then _Protected := _Protected + 1;
{*** check for a knight in all positions from which it could attack/protect ***}
for i := 1 to PossibleMoves[KNIGHT].NumDirections do begin
with PossibleMoves[KNIGHT].UnitMove[i] do begin
PosRow := row + DirRow;
PosCol := col + DirCol;
end;
if (Board[PosRow, PosCol].image = KNIGHT) then begin
{*** color determines if knight is attacking or protecting ***}
if (Board[PosRow, PosCol].color = FriendColor) then
_Protected := _Protected + 1
else
Attacked := Attacked + 1;
end;
end;
{*** check for king, queen, bishop, and rook attacking or protecting ***}
for i := 1 to 8 do begin
{*** get the current search direction ***}
with PossibleMoves[QUEEN].UnitMove[i] do begin
IncRow := DirRow;
IncCol := DirCol;
end;
{*** set distance countdown and search position ***}
distance := 7;
PosRow := row;
PosCol := col;
{*** search until something is run into ***}
while distance > 0 do begin
{*** get new position and check it ***}
PosRow := PosRow + IncRow;
PosCol := PosCol + IncCol;
with Board[PosRow, PosCol] do begin
if ValidSquare then begin
if image = BLANK then
{*** continue searching if search_square is blank ***}
distance := distance - 1
else begin
{*** separate cases of straight or diagonal attack/protect ***}
if (IncRow = 0) or (IncCol = 0) then begin
{*** straight: check for queen, rook, or one-away king ***}
if (image = QUEEN) or (image = ROOK) or
((image = KING) and (distance = 7)) then
if (color = FriendColor) then
_Protected := _Protected + 1
else
Attacked := Attacked + 1;
end else begin
{*** diagonal: check for queen, bishop, or one-away king ***}
if (image = QUEEN) or (image = BISHOP) or
((image = KING) and (distance = 7)) then
if (color = FriendColor) then
_Protected := _Protected + 1
else
Attacked := Attacked + 1;
end;
{*** force to stop searching if piece encountered ***}
distance := 0;
end;
end else
{*** force to stop searching if border of board encountered ***}
distance := 0;
end;
end;
end;
end; {AttackedBy}
{****************************************************************************}
{* Gen Move List: Returns the list of all possible moves for the given *}
{* player. Searches the board for all pieces of the given color, and *}
{* adds all of the possible moves for that piece to the move list to be *}
{* returned. *}
{****************************************************************************}
procedure GenMoveList (Turn : PieceColorType; var Movelist : MoveListType);
var row, col : RowColType;
{----------------------------------------------------------------------------}
{ Gen Piece Move List: Generates all of the moves for the given piece at }
{ the given board position, and adds them to the move list for the player. }
{ If the piece is a pawn then all of the moves are checked by brute force. }
{ If the piece is a king, then the castling move is checked by brute force. }
{ For all other moves, each allowed direction for the piece is checked, and }
{ each square off in that direction from the piece, up to the piece's move }
{ distance limit, is added to the list, until the edge of the board is }
{ encountered or another piece is encountered. If the piece encountered }
{ is an enemy piece, then taking that enemy piece is added to the player's }
{ move list as well. }
{----------------------------------------------------------------------------}
procedure GenPieceMoveList (Piece : PieceType; row, col : integer);
var dir : integer;
PosRow, PosCol : RowColType; {*** current scanning position ***}
OrigRow, OrigCol : RowColType; {*** location to search from ***}
IncRow, IncCol : integer; {*** displacement to add to scanning position ***}
DirectionNum : 1..8;
distance : 0..7;
EPPossible : boolean;
EnemyColor : PieceColorType;
Attacked, _Protected : integer;
{----------------------------------------------------------------------------}
{ Gen Add Move: Adds the move to be generated to the player's move list. }
{ Given the location and displacement to move the piece, takes PieceTaken }
{ and PieceMoved from the current board configuration. }
{----------------------------------------------------------------------------}
procedure GenAddMove (row, col : RowColType; drow, dcol : integer);
begin
MoveList.NumMoves := MoveList.NumMoves + 1;
with MoveList.Move[MoveList.NumMoves] do begin
FromRow := row;
FromCol := col;
ToRow := row + drow;
ToCol := col + dcol;
PieceTaken := Board [ToRow, ToCol];
PieceMoved := Board [FromRow, FromCol];
{*** get image of piece after it is moved... ***}
{*** same as before the movement except in the case of pawn promotion ***}
MovedImage := Board [FromRow, FromCol].image;
end;
end; {GenAddMove}
{----------------------------------------------------------------------------}
{ Gen Add Pawn Move: Adds the move to be generated for a pawn to the }
{ player's move list and checks for pawn promotion. }
{----------------------------------------------------------------------------}
procedure GenAddPawnMove (row, col : RowColType; drow, dcol : integer);
begin
GenAddMove (row, col, drow, dcol);
{*** if pawn will move to an end row ***}
if (row + drow = 1) or (row + drow = 8) then
{*** assume the pawn will be promoted to a queen ***}
MoveList.Move[MoveList.NumMoves].MovedImage := QUEEN;
end; {GenAddPawnMove}
{----------------------------------------------------------------------------}
begin {GenPieceMoveList}
OrigRow := row;
OrigCol := col;
{*** pawn movement is a special case ***}
if Piece.image = PAWN then begin
{*** check for En Passent ***}
if Piece.color = C_WHITE then begin
dir := 1;
EPPossible := (row = 5);
EnemyColor := C_BLACK;
end else begin
dir := -1;
EPPossible := (row = 4);
EnemyColor := C_WHITE;
end;
{*** make sure enemy's last move was push pawn two, beside player's pawn ***}
with Player[EnemyColor].LastMove do begin
if EPPossible and Game.EnPassentAllowed and (FromRow <> NULL_MOVE) then
if (abs (FromRow - ToRow) = 2) then
if (abs (ToCol - col) = 1) and (PieceMoved.image = PAWN) then
GenAddPawnMove (row, col, dir, ToCol - col);
end;
{*** square pawn is moving to (1 or 2 ahead) is guaranteed to be valid ***}
if (Board [row + dir, col].image = BLANK) then begin
GenAddPawnMove (row, col, dir, 0);
{*** see if pawn can move two ***}
if (not Piece.HasMoved) and (Board [row + 2*dir, col].image = BLANK) then
GenAddPawnMove (row, col, 2*dir, 0);
end;
{*** check for pawn takes to left ***}
with Board[row + dir, col - 1] do begin
if (image <> BLANK) and (color = EnemyColor) and ValidSquare then
GenAddPawnMove (row, col, dir, -1);
end;
{*** check for pawn takes to right ***}
with Board[row + dir, col + 1] do begin
if (image <> BLANK) and (color = EnemyColor) and ValidSquare then
GenAddPawnMove (row, col, dir, +1);
end;
end else begin
{*** check for the king castling ***}
if (Piece.image = KING) and (not Piece.HasMoved) and (not Player[Turn].InCheck) then begin
{*** check for castling to left ***}
if (Board [row, 1].image = ROOK) and (not Board [row, 1].HasMoved) then
if (Board [row, 2].image = BLANK) and (Board [row, 3].image = BLANK)
and (Board [row, 4].image = BLANK) then begin
{*** make sure not moving through check ***}
Board [row, 4].color := Turn;
AttackedBy (row, 4, Attacked, _Protected);
if (Attacked = 0) then
GenAddMove (row, 5, 0, -2);
end;
{*** check for castling to right ***}
if (Board [row, 8].image = ROOK) and (not Board [row, 8].HasMoved) then
if (Board [row, 6].image = BLANK) and (Board [row, 7].image = BLANK) then begin
{*** make sure not moving through check ***}
Board [row, 6].color := Turn;
AttackedBy (row, 6, Attacked, _Protected);
if (Attacked = 0) then
GenAddMove (row, 5, 0, 2);
end;
end;
{*** Normal moves: for each allowed direction of the piece... ***}
for DirectionNum := 1 to PossibleMoves [Piece.image].NumDirections do begin
{*** initialize search ***}
distance := PossibleMoves [Piece.image].MaxDistance;
PosRow := OrigRow;
PosCol := OrigCol;
with PossibleMoves[Piece.image].UnitMove[DirectionNum] do begin
IncRow := DirRow;
IncCol := DirCol;
end;
{*** search until something is run into ***}
while distance > 0 do begin
PosRow := PosRow + IncRow;
PosCol := PosCol + IncCol;
with Board [PosRow, PosCol] do begin
if (not ValidSquare) then
distance := 0
else begin
if image = BLANK then begin
{*** sqaure is empty: can move there; keep searching ***}
GenAddMove (OrigRow, OrigCol, PosRow - OrigRow, PosCol - OrigCol);
distance := distance - 1;
end else begin
{*** piece is there: can take if enemy; stop searching ***}
distance := 0;
if color <> Turn then
GenAddMove (OrigRow, OrigCol, PosRow - OrigRow, PosCol - OrigCol);
end;
end;
end;
end;
end;
end;
end; {GenPieceMoveList}
{----------------------------------------------------------------------------}
begin {GenMoveList}
{*** empty out player's move list ***}
MoveList.NumMoves := 0;
{*** search for player's pieces on board ***}
for row := 1 to BOARD_SIZE do
for col := 1 to BOARD_SIZE do
with Board [row, col] do begin
{*** if player's piece, add its moves ***}
if (image <> BLANK) and (color = Turn) then
GenPieceMoveList (Board [row, col], row, col);
end;
end; {GenMoveList}
{****************************************************************************}
{* Make Move: Update the Board to reflect making the given movement. If *}
{* given is a PermanentMove, then the end of game pointers is set to the *}
{* current move. Returns the score for the move, which is given by the *}
{* number of points for the piece taken. *}
{****************************************************************************}
procedure MakeMove (Movement : MoveType; PermanentMove : boolean; var Score : integer);
var Row: RowColType;
Attacked, _Protected : integer;
begin
{$ifdef KCCHESS_VERBOSE}
//WriteLn(Format('[Moves.pas.MakeMove] Movement.PieceTaken.image=%d', [Integer(Movement.PieceTaken.image)]));
{$endif}
Score := 0;
{*** update board for most moves ***}
with Movement do begin
{*** pick piece up ***}
Board[FromRow, FromCol].image := BLANK;
{*** put piece down ***}
Board[ToRow, ToCol] := PieceMoved;
end;
{*** check for en passent, pawn promotion, and castling ***}
case Movement.PieceMoved.image of
PAWN: begin
{*** en passent: blank out square taken; get points ***}
if (Movement.FromCol <> Movement.ToCol) and (Movement.PieceTaken.image = BLANK) then begin
Board[Movement.FromRow, Movement.ToCol].image := BLANK;
Score := Score + CapturePoints[PAWN];
end;
{*** pawn promotion: use the after-moved image; get trade-up points ***}
if Movement.PieceMoved.color = C_WHITE then Row := 8 else Row := 1;
if Movement.ToRow = Row then begin
Board[Movement.ToRow, Movement.ToCol].image := Movement.MovedImage;
Score := Score + CapturePoints[Movement.MovedImage] - CapturePoints[PAWN];
end;
end;
KING: begin
{*** update king position in player record ***}
with Player[Movement.PieceMoved.color] do begin
KingRow := Movement.ToRow;
KingCol := Movement.ToCol;
end;
{*** castling left/right: move the rook too ***}
if abs (Movement.FromCol - Movement.ToCol) > 1 then begin
if (Movement.ToCol < Movement.FromCol) then begin
Board[Movement.FromRow, 4] := Board[Movement.FromRow, 1];
Board[Movement.FromRow, 4].HasMoved := true;
Board[Movement.FromRow, 1].image := BLANK;
end else begin
Board[Movement.FromRow, 6] := Board[Movement.FromRow, 8];
Board[Movement.FromRow, 6].HasMoved := true;
Board[Movement.FromRow, 8].image := BLANK;
end;
end;
end;
end;
{*** update player attributes ***}
Player[Movement.PieceMoved.color].LastMove := Movement;
Player[Movement.PieceMoved.color].InCheck := false;
with Player[EnemyColor[Movement.PieceMoved.color]] do begin
AttackedBy (KingRow, KingCol, Attacked, _Protected);
InCheck := Attacked <> 0;
end;
{*** remember that piece has been moved, get score ***}
Board[Movement.ToRow, Movement.ToCol].HasMoved := true;
Score := Score + CapturePoints[Movement.PieceTaken.image];
{*** update game attributes ***}
Game.MoveNum := Game.MoveNum + 1;
Game.MovesPointer := Game.MovesPointer + 1;
Game.Move[Game.MovesPointer] := Movement;
if PermanentMove then
Game.MovesStored := Game.MovesPointer;
Game.InCheck[Game.MovesPointer] := Attacked <> 0;
{*** update nondevelopmental moves counter ***}
if (Movement.PieceMoved.image = PAWN) or (Movement.PieceTaken.image <> BLANK) then begin
Game.NonDevMoveCount[Game.MovesPointer] := 0;
end else begin
{*** if 50 nondevelopmental moves in a row: stalemate ***}
Game.NonDevMoveCount[Game.MovesPointer] := Game.NonDevMoveCount[Game.MovesPointer-1] + 1;
if (Game.NonDevMoveCount[Game.MovesPointer] >= NON_DEV_MOVE_LIMIT) then
Score := STALE_SCORE;
end;
end; {MakeMove}
{****************************************************************************}
{* Un Make Move: Updates the board for taking back the last made move. *}
{* This routine returns (is not given) the last made movement (so it may *}
{* be passed to DisplayUnMadeMove). *}
{****************************************************************************}
procedure UnMakeMove (var Movement: Movetype);
begin
{*** make sure there is a move to un-make ***}
if (Game.MovesPointer > 0) then begin
Movement := Game.Move[Game.MovesPointer];
{*** restore whether player who made move was in check ***}
Player[Movement.PieceMoved.color].InCheck := Game.InCheck[Game.MovesPointer - 1];
{*** the enemy could not have been in check ***}
Player[EnemyColor[Movement.PieceMoved.color]].InCheck := false;
{*** restore the From and To squares ***}
Board[Movement.FromRow, Movement.FromCol] := Movement.PieceMoved;
Board[Movement.ToRow, Movement.ToCol] := Movement.PieceTaken;
{*** special cases ***}
case Movement.PieceMoved.image of
KING: begin
{*** restore position of king in player attributes ***}
with Player[Movement.PieceMoved.color] do begin
KingRow := Movement.FromRow;
KingCol := Movement.FromCol;
end;
{*** un-castle left/right if applicable ***}
if abs (Movement.FromCol - Movement.ToCol) > 1 then begin
if (Movement.FromCol < Movement.ToCol) then begin
Board[Movement.FromRow, 8] := Board[Movement.FromRow, 6];
Board[Movement.FromRow, 6].image := BLANK;
Board[Movement.FromRow, 8].HasMoved := false;
end else begin
Board[Movement.FromRow, 1] := Board[Movement.FromRow, 4];
Board[Movement.FromRow, 4].image := BLANK;
Board[Movement.FromRow, 1].HasMoved := false;
end;
end;
end;
PAWN:
{*** un-en passent: restore the pawn that was taken ***}
if (Movement.FromCol <> Movement.ToCol) and (Movement.PieceTaken.image = BLANK) then
with Board[Movement.FromRow, Movement.ToCol] do begin
image := PAWN;
if Movement.PieceMoved.color = C_WHITE then
color := C_BLACK
else
color := C_WHITE;
HasMoved := true;
end;
end;
{*** roll back move number and pointer ***}
Game.MoveNum := Game.MoveNum - 1;
Game.MovesPointer := Game.MovesPointer - 1;
{*** restore player previous move attributes ***}
if (Game.MovesPointer > 1) then
Player[Movement.PieceMoved.color].LastMove := Game.Move[Game.MovesPointer - 1]
else
Player[Movement.PieceMoved.color].LastMove.FromRow := NULL_MOVE;
end else
{*** indicate no move to take back ***}
Movement.FromRow := NULL_MOVE;
end; {UnMakeMove}
{****************************************************************************}
{* Trim Checks: Given a move list, remove all of the moves which would *}
{* result in the given player moving into check. This is not done *}
{* directly by GenMoveList because it is an expensive operation, since *}
{* each move will have to be made and then unmade. This routine is called *}
{* by the Human Movement routine. The Computer Movement routine *}
{* incorporates this code into its code, since the moves have to be made *}
{* and unmade there anyway. *}
{****************************************************************************}
procedure TrimChecks (Turn : PieceColorType; var MoveList : MoveListType);
var DummyMove : MoveType;
DummyScore, Attacked, _Protected : integer;
ValidMoves, i : integer;
begin
ValidMoves := 0;
for i := 1 to MoveList.NumMoves do begin
MakeMove (MoveList.Move[i], false, DummyScore);
{*** check if the king is attacked (in check) ***}
AttackedBy (Player[Turn].KingRow, Player[Turn].KingCol, Attacked, _Protected);
if Attacked = 0 then begin
{*** if not in check, then re-put valid move ***}
ValidMoves := ValidMoves + 1;
MoveList.Move[ValidMoves] := MoveList.Move[i];
end;
UnMakeMove (DummyMove);
end;
MoveList.NumMoves := ValidMoves;
end; {TrimChecks}
{****************************************************************************}
{* Randomize Move List: Scrambles the order of the given move list. This *}
{* is done to make choosing between tie scores random. It is necassary *}
{* to scramble the moves here because the move list will always be *}
{* generated in the same order. *}
{****************************************************************************}
procedure RandomizeMoveList (var MoveList : MoveListType);
var i, Exch : integer;
ExchMove : MoveType;
begin
for i := 1 to MoveList.NumMoves do begin
{*** swap the current move with some random other one ***}
Exch := Random (MoveList.NumMoves) + 1;
ExchMove := MoveList.Move[Exch];
MoveList.Move[Exch] := MoveList.Move[i];
MoveList.Move[i] := ExchMove;
end;
end; {RandomizeMoveList}
{****************************************************************************}
{* Goto Move: Rolls back/forth the game to the given move number. Each *}
{* move between the current move and the destination is made/retracted to *}
{* update the board and other game status information. If the given move *}
{* number is too small or too large, the game is rolled to the first/last *}
{* move. *}
{****************************************************************************}
procedure GotoMove (GivenMoveTo : integer);
var Movement : MoveType;
DummyScore : integer;
MoveTo, BeginMoveNum, EndMoveNum : integer;
begin
{*** check the bounds of given move number ***}
MoveTo := GivenMoveTo;
BeginMoveNum := Game.MoveNum - Game.MovesPointer;
EndMoveNum := Game.MoveNum + (Game.MovesStored - Game.MovesPointer);
if (MoveTo < BeginMoveNum) then MoveTo := BeginMoveNum;
if (MoveTo > EndMoveNum) then MoveTo := EndMoveNum;
{*** make / retract moves of the game until the destination is reached ***}
while (Game.MoveNum <> MoveTo) do begin
if MoveTo > Game.MoveNum then begin
Movement := Game.Move[Game.MovesPointer + 1];
MakeMove (Movement, false, DummyScore);
end else
UnMakeMove (Movement);
end;
Game.GameFinished := false;
end;
{*** end of the MOVES.PAS include file ***}
|
{
$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.126 4/28/2005 BTaylor
Changed .Size to use Int64
Rev 1.125 4/15/2005 9:10:10 AM JPMugaas
Changed the default timeout in TIdFTP to one minute and made a comment about
this.
Some firewalls don't handle control connections properly during long data
transfers. They will timeout the control connection because it's idle and
making it worse is that they will chop off a connection instead of closing it
causing TIdFTP to wait forever for nothing.
Rev 1.124 3/20/2005 10:42:44 PM JPMugaas
Marked TIdFTP.Quit as deprecated. We need to keep it only for compatibility.
Rev 1.123 3/20/2005 2:44:08 PM JPMugaas
Should now send quit. Verified here.
Rev 1.122 3/12/2005 6:57:12 PM JPMugaas
Attempt to add ACCT support for firewalls. I also used some logic from some
WS-FTP Pro about ACCT to be more consistant with those Firescripts.
Rev 1.121 3/10/2005 2:41:12 PM JPMugaas
Removed the UseTelnetAbort property. It turns out that sending the sequence
is causing problems on a few servers. I have made a comment about this in
the source-code so someone later on will know why I decided not to send
those.
Rev 1.120 3/9/2005 10:05:54 PM JPMugaas
Minor changes for Indy conventions.
Rev 1.119 3/9/2005 9:15:46 PM JPMugaas
Changes submitted by Craig Peterson, Scooter Software He noted this:
"We had a user who's FTP server prompted for account info after a
regular login, so I had to add an explicit Account string property and
an OnNeedAccount event that we could use for a prompt." This does break any
code using TIdFTP.Account.
TODO: See about integrating Account Info into the proxy login sequences.
Rev 1.118 3/9/2005 10:40:16 AM JPMugaas
Made comment explaining why I had made a workaround in a procedure.
Rev 1.117 3/9/2005 10:28:32 AM JPMugaas
Fix for Abort problem when uploading. A workaround I made for WS-FTP Pro
Server was not done correctly.
Rev 1.116 3/9/2005 1:21:38 AM JPMugaas
Made refinement to Abort and the data transfers to follow what Kudzu had
originally done in Indy 8. I also fixed a problem with ABOR at
ftp.ipswitch.com and I fixed a regression at ftp.marist.edu that occured when
getting a directory.
Rev 1.115 3/8/2005 12:14:50 PM JPMugaas
Renamed UseOOBAbort to UseTelnetAbort because that's more accurate. We still
don't support Out of Band Data (hopefully, we'll never have to do that).
Rev 1.114 3/7/2005 10:40:10 PM JPMugaas
Improvements:
1) Removed some duplicate code.
2) ABOR should now be properly handled outside of a data operation.
3) I added a UseOOBAbort read-write public property for controlling how the
ABOR command is sent. If true, the Telnet sequences are sent or if false,
the ABOR without sequences is sent. This is set to false by default because
one FTP client (SmartFTP recently removed the Telnet sequences from their
program).
This code is expiriemental.
Rev 1.113 3/7/2005 5:46:34 PM JPMugaas
Reworked FTP Abort code to make it more threadsafe and make abort work. This
is PRELIMINARY.
Rev 1.112 3/5/2005 3:33:56 PM JPMugaas
Fix for some compiler warnings having to do with TStream.Read being platform
specific. This was fixed by changing the Compressor API to use TIdStreamVCL
instead of TStream. I also made appropriate adjustments to other units for
this.
Rev 1.111 2/24/2005 6:46:36 AM JPMugaas
Clarrified remarks I made and added a few more comments about syntax in
particular cases in the set modified file date procedures.
That's really been a ball....NOT!!!!
Rev 1.110 2/24/2005 6:25:08 AM JPMugaas
Attempt to fix problem setting Date with Titan FTP Server. I had made an
incorrect assumption about MDTM on that system. It uses Syntax 3 (see my
earlier note above the File Date Set problem.
Rev 1.109 2/23/2005 6:32:54 PM JPMugaas
Made note about MDTM syntax inconsistancy. There's a discussion about it.
Rev 1.108 2/12/2005 8:08:04 AM JPMugaas
Attempt to fix MDTM bug where msec was being sent.
Rev 1.107 1/12/2005 11:26:44 AM JPMugaas
Memory Leak fix when processing MLSD output and some minor tweeks Remy had
E-Mailed me last night.
Rev 1.106 11/18/2004 2:39:32 PM JPMugaas
Support for another FTP Proxy type.
Rev 1.105 11/18/2004 12:18:50 AM JPMugaas
Fixed compile error.
Rev 1.104 11/17/2004 3:59:22 PM JPMugaas
Fixed a TODO item about FTP Proxy support with a "Transparent" proxy. I
think you connect to the regular host and the firewall will intercept its
login information.
Rev 1.103 11/16/2004 7:31:52 AM JPMugaas
Made a comment noting that UserSite is the same as USER after login for later
reference.
Rev 1.102 11/5/2004 1:54:42 AM JPMugaas
Minor adjustment - should not detect TitanFTPD better (tested at:
ftp.southrivertech.com).
If MLSD is being used, SITE ZONE will not be issued. It's not needed because
the MLSD spec indicates the time is based on GMT.
Rev 1.101 10/27/2004 12:58:08 AM JPMugaas
Improvement from Tobias Giesen http://www.superflexible.com
His notation is below:
"here's a fix for TIdFTP.IndexOfFeatLine. It does not work the
way it is used in TIdFTP.SetModTime, because it only
compares the first word of the FeatLine."
Rev 1.100 10/26/2004 9:19:10 PM JPMugaas
Fixed references.
Rev 1.99 9/16/2004 3:24:04 AM JPMugaas
TIdFTP now compresses to the IOHandler and decompresses from the IOHandler.
Noted some that the ZLib code is based was taken from ZLibEx.
Rev 1.98 9/13/2004 12:15:42 AM JPMugaas
Now should be able to handle some values better as suggested by Michael J.
Leave.
Rev 1.97 9/11/2004 10:58:06 AM JPMugaas
FTP now decompresses output directly to the IOHandler.
Rev 1.96 9/10/2004 7:37:42 PM JPMugaas
Fixed a bug. We needed to set Passthrough instead of calling StartSSL. This
was causing a SSL problem with upload.
Rev 1.95 8/2/04 5:56:16 PM RLebeau
Tweaks to TIdFTP.InitDataChannel()
Rev 1.94 7/30/2004 1:55:04 AM DSiders
Corrected DoOnRetrievedDir naming.
Rev 1.93 7/30/2004 12:36:32 AM DSiders
Corrected spelling in OnRetrievedDir, DoOnRetrievedDir declarations.
Rev 1.92 7/29/2004 2:15:28 AM JPMugaas
New property for controlling what AUTH command is sent. Fixed some minor
issues with FTP properties. Some were not set to defaults causing
unpredictable results -- OOPS!!!
Rev 1.91 7/29/2004 12:04:40 AM JPMugaas
New events for Get and Put as suggested by Don Sides and to complement an
event done by APR.
Rev 1.90 7/28/2004 10:16:14 AM JPMugaas
New events for determining when a listing is finished and when the dir
parsing begins and ends. Dir parsing is done sometimes when DirectoryListing
is referenced.
Rev 1.89 7/27/2004 2:03:54 AM JPMugaas
New property:
ExternalIP - used to specify an IP address for the PORT and EPRT commands.
This should be blank unless you are behind a NAT and you need to use PORT
transfers with SSL. You would set ExternalIP to the NAT's IP address on the
Internet.
The idea is this:
1) You set up your NAT to forward a range ports ports to your computer behind
the NAT.
2) You specify that a port range with the DataPortMin and DataPortMin
properties.
3) You set ExternalIP to the NAT's Internet IP address.
I have verified this with Indy and WS FTP Pro behind a NAT router.
Rev 1.88 7/23/04 7:09:50 PM RLebeau
Bug fix for TFileStream access rights in Get()
Rev 1.87 7/18/2004 3:00:12 PM DSiders
Added localization comments.
Rev 1.86 7/16/2004 4:28:40 AM JPMugaas
CCC Support in TIdFTP to complement that capability in TIdFTPServer.
Rev 1.85 7/13/04 6:48:14 PM RLebeau
Added support for new DataPort and DataPortMin/Max properties
Rev 1.84 7/6/2004 4:51:46 PM DSiders
Corrected spelling of Challenge in properties, methods, types.
Rev 1.83 7/3/2004 3:15:50 AM JPMugaas
Checked in so everyone else can work on stuff while I'm away.
Rev 1.82 6/27/2004 1:45:38 AM JPMugaas
Can now optionally support LastAccessTime like Smartftp's FTP Server could.
I also made the MLST listing object and parser support this as well.
Rev 1.81 6/20/2004 8:31:58 PM JPMugaas
New events for reporting greeting and after login banners during the login
sequence.
Rev 1.80 6/20/2004 6:56:42 PM JPMugaas
Start oin attempt to support FXP with Deflate compression. More work will
need to be done.
Rev 1.79 6/17/2004 3:42:32 PM JPMugaas
Adjusted code for removal of dmBlock and dmCompressed. Made TransferMode a
property. Note that the Set method is odd because I am trying to keep
compatibility with older Indy versions.
Rev 1.78 6/14/2004 6:19:02 PM JPMugaas
This now refers to TIdStreamVCL when downloading isntead of directly to a
memory stream when compressing data.
Rev 1.77 6/14/2004 8:34:52 AM JPMugaas
Fix for AV on Put with Passive := True.
Rev 1.76 6/11/2004 9:34:12 AM DSiders
Added "Do not Localize" comments.
Rev 1.75 2004.05.20 11:37:16 AM czhower
IdStreamVCL
Rev 1.74 5/6/2004 6:54:26 PM JPMugaas
FTP Port transfers with TransparentProxies is enabled. This only works if
the TransparentProxy supports a "bind" request.
Rev 1.73 5/4/2004 11:16:28 AM JPMugaas
TransferTimeout property added and enabled (Bug 96).
Rev 1.72 5/4/2004 11:07:12 AM JPMugaas
Timeouts should now be reenabled in TIdFTP.
Rev 1.71 4/19/2004 5:05:02 PM JPMugaas
Class rework Kudzu wanted.
Rev 1.70 2004.04.16 9:31:42 PM czhower
Remove unnecessary duplicate string parsing and replaced with .assign.
Rev 1.69 2004.04.15 7:09:04 PM czhower
.NET overloads
Rev 1.68 4/15/2004 9:46:48 AM JPMugaas
List no longer requires a TStrings. It turns out that it was an optional
parameter.
Rev 1.67 2004.04.15 2:03:28 PM czhower
Removed login param from connect and made it a prop like POP3.
Rev 1.66 3/3/2004 5:57:40 AM JPMugaas
Some IFDEF excluses were removed because the functionality is now in DotNET.
Rev 1.65 2004.03.03 11:54:26 AM czhower
IdStream change
Rev 1.64 2/20/2004 1:01:06 PM JPMugaas
Preliminary FTP PRET command support for using PASV with a distributed FTP
server (Distributed PASV -
http://drftpd.org/wiki/wiki.phtml?title=Distributed_PASV).
Rev 1.63 2/17/2004 12:25:52 PM JPMugaas
The client now supports MODE Z (deflate) uploads and downloads as specified
by http://www.ietf.org/internet-drafts/draft-preston-ftpext-deflate-00.txt
Rev 1.62 2004.02.03 5:45:10 PM czhower
Name changes
Rev 1.61 2004.02.03 2:12:06 PM czhower
$I path change
Rev 1.60 1/27/2004 10:17:10 PM JPMugaas
Fix from Steve Loft for a server that sends something like this:
"227 Passive mode OK (195,92,195,164,4,99 )"
Rev 1.59 1/27/2004 3:59:28 PM SPerry
StringStream ->IdStringStream
Rev 1.58 24/01/2004 19:13:58 CCostelloe
Cleaned up warnings
Rev 1.57 1/21/2004 2:27:50 PM JPMugaas
Bullete Proof FTPD and Titan FTP support SITE ZONE. Saw this in a command
database in StaffFTP.
InitComponent.
Rev 1.56 1/19/2004 9:05:38 PM JPMugaas
Fixes to FTP Set Date functionality.
Introduced properties for Time Zone information from the server. The way it
works is this, if TIdFTP detects you are using "Serv-U" or SITE ZONE is
listed in the FEAT reply, Indy obtains the time zone information with the
SITE ZONE command and makes the appropriate calculation. Indy then uses this
information to calculate a timestamp to send to the server with the MDTM
command. You can also use the Time Zone information yourself to convert the
FTP directory listing item timestamps into GMT and than convert that to your
local time.
FTP Voyager uses SITE ZONE as I've described.
Rev 1.55 1/19/2004 4:39:08 AM JPMugaas
You can now set the time for a file on the server. Note that these methods
try to treat the time as relative to GMT.
Rev 1.54 1/17/2004 9:09:30 PM JPMugaas
Should now compile.
Rev 1.53 1/17/2004 7:48:02 PM JPMugaas
FXP site to site transfer code was redone for improvements with FXP with TLS.
It actually works and I verified with RaidenFTPD
(http://www.raidenftpd.com/) and the Indy FTP server components. I also
lowered the requirements for TLS FXP transfers. The requirements now are:
1) Only server (either the recipient or the sendor) has to support SSCN
or
2) The server receiving a PASV must support CPSV and the transfer is done
with IPv4.
Rev 1.52 1/9/2004 2:51:26 PM JPMugaas
Started IPv6 support.
Rev 1.51 11/27/2003 4:55:28 AM JPMugaas
Made STOU functionality separate from PUT functionality. Put now requires a
destination filename except where a source-file name is given. In that case,
the default is the filename from the source string.
Rev 1.50 10/26/2003 04:28:50 PM JPMugaas
Reworked Status.
The old one was problematic because it assumed that STAT was a request to
send a directory listing through the control channel. This assumption is not
correct. It provides a way to get a freeform status report from a server.
With a Path parameter, it should work like a LIST command except that the
control connection is used. We don't support that feature and you should use
our LIst method to get the directory listing anyway, IMAO.
Rev 1.49 10/26/2003 9:17:46 PM BGooijen
Compiles in DotNet, and partially works there
Rev 1.48 10/24/2003 12:43:48 PM JPMugaas
Should work again.
Rev 1.47 2003.10.24 10:43:04 AM czhower
TIdSTream to dos
Rev 1.46 10/20/2003 03:06:10 PM JPMugaas
SHould now work.
Rev 1.45 10/20/2003 01:00:38 PM JPMugaas
EIdException no longer raised. Some things were being gutted needlessly.
Rev 1.44 10/19/2003 12:58:20 PM DSiders
Added localization comments.
Rev 1.43 2003.10.14 9:56:50 PM czhower
Compile todos
Rev 1.42 2003.10.12 3:50:40 PM czhower
Compile todos
Rev 1.41 10/10/2003 11:32:26 PM SPerry
-
Rev 1.40 10/9/2003 10:17:02 AM JPMugaas
Added overload for GetLoginPassword for providing a challanage string which
doesn't have to the last command reply.
Added CLNT support.
Rev 1.39 10/7/2003 05:46:20 AM JPMugaas
SSCN Support added.
Rev 1.38 10/6/2003 08:56:44 PM JPMugaas
Reworked the FTP list parsing framework so that the user can obtain the list
of capabilities from a parser class with TIdFTP. This should permit the user
to present a directory listing differently for each parser (some FTP list
parsers do have different capabilities).
Rev 1.37 10/1/2003 12:51:18 AM JPMugaas
SSL with active (PORT) transfers now should work again.
Rev 1.36 9/30/2003 09:50:38 PM JPMugaas
FTP with TLS should work better. It turned out that we were negotiating it
several times causing a hang. I also made sure that we send PBSZ 0 and PROT
P for both implicit and explicit TLS. Data ports should work in PASV again.
Rev 1.35 9/28/2003 11:41:06 PM JPMugaas
Reworked Eldos's proposed FTP fix as suggested by Henrick HellstrŲm by moving
all of the IOHandler creation code to InitDataChannel. This should reduce
the likelihood of error.
Rev 1.33 9/18/2003 11:22:40 AM JPMugaas
Removed a temporary workaround for an OnWork bug that was in the Indy Core.
That bug was fixed so there's no sense in keeping a workaround here.
Rev 1.32 9/12/2003 08:05:30 PM JPMugaas
A temporary fix for OnWork events not firing. The bug is that OnWork events
aren't used in IOHandler where ReadStream really is located.
Rev 1.31 9/8/2003 02:33:00 AM JPMugaas
OnCustomFTPProxy added to allow Indy to support custom FTP proxies. When
using this event, you are responsible for programming the FTP Proxy and FTP
Server login sequence.
GetLoginPassword method function for returning the password used when logging
into a FTP server which handles OTP calculation. This way, custom firewall
support can handle One-Time-Password system transparently. You do have to
send the User ID before calling this function because the OTP challenge is
part of the reply.
Rev 1.30 6/10/2003 11:10:00 PM JPMugaas
Made comments about our loop that tries several AUTH command variations.
Some servers may only accept AUTH SSL while other servers only accept AUTH
TLS.
Rev 1.29 5/26/2003 12:21:54 PM JPMugaas
Rev 1.28 5/25/2003 03:54:20 AM JPMugaas
Rev 1.27 5/19/2003 08:11:32 PM JPMugaas
Now should compile properly with new code in Core.
Rev 1.26 5/8/2003 11:27:42 AM JPMugaas
Moved feature negoation properties down to the ExplicitTLSClient level as
feature negotiation goes hand in hand with explicit TLS support.
Rev 1.25 4/5/2003 02:06:34 PM JPMugaas
TLS handshake itself can now be handled.
Rev 1.24 4/4/2003 8:01:32 PM BGooijen
now creates iohandler for dataconnection
Rev 1.23 3/31/2003 08:40:18 AM JPMugaas
Fixed problem with QUIT command.
Rev 1.22 3/27/2003 3:41:28 PM BGooijen
Changed because some properties are moved to IOHandler
Rev 1.21 3/27/2003 05:46:24 AM JPMugaas
Updated framework with an event if the TLS negotiation command fails.
Cleaned up some duplicate code in the clients.
Rev 1.20 3/26/2003 04:19:20 PM JPMugaas
Cleaned-up some code and illiminated some duplicate things.
Rev 1.19 3/24/2003 04:56:10 AM JPMugaas
A typecast was incorrect and could cause a potential source of instability if
a TIdIOHandlerStack was not used.
Rev 1.18 3/16/2003 06:09:58 PM JPMugaas
Fixed port setting bug.
Rev 1.17 3/16/2003 02:40:16 PM JPMugaas
FTP client with new design.
Rev 1.16 3/16/2003 1:02:44 AM BGooijen
Added 2 events to give the user more control to the dataconnection, moved
SendTransferType, enabled ssl
Rev 1.15 3/13/2003 09:48:58 AM JPMugaas
Now uses an abstract SSL base class instead of OpenSSL so 3rd-party vendors
can plug-in their products.
Rev 1.14 3/7/2003 11:51:52 AM JPMugaas
Fixed a writeln bug and an IOError issue.
Rev 1.13 3/3/2003 07:06:26 PM JPMugaas
FFreeIOHandlerOnDisconnect to FreeIOHandlerOnDisconnect at Bas's instruction
Rev 1.12 2/21/2003 06:54:36 PM JPMugaas
The FTP list processing has been restructured so that Directory output is not
done by IdFTPList. This now also uses the IdFTPListParserBase for parsing so
that the code is more scalable.
Rev 1.11 2/17/2003 04:45:36 PM JPMugaas
Now temporarily change the transfer mode to ASCII when requesting a DIR.
TOPS20 does not like transfering dirs in binary mode and it might be a good
idea to do it anyway.
Rev 1.10 2/16/2003 03:22:20 PM JPMugaas
Removed the Data Connection assurance stuff. We figure things out from the
draft specificaiton, the only servers we found would not send any data after
the new commands were sent, and there were only 2 server types that supported
it anyway.
Rev 1.9 2/16/2003 10:51:08 AM JPMugaas
Attempt to implement:
http://www.ietf.org/internet-drafts/draft-ietf-ftpext-data-connection-assuranc
e-00.txt
Currently commented out because it does not work.
Rev 1.8 2/14/2003 11:40:16 AM JPMugaas
Fixed compile error.
Rev 1.7 2/14/2003 10:38:32 AM JPMugaas
Removed a problematic override for GetInternelResponse. It was messing up
processing of the FEAT.
Rev 1.6 12-16-2002 20:48:10 BGooijen
now uses TIdIOHandler.ConstructIOHandler to construct iohandlers
IPv6 works again
Independant of TIdIOHandlerStack again
Rev 1.5 12-15-2002 23:27:26 BGooijen
now compiles on Indy 10, but some things like IPVersion still need to be
changed
Rev 1.4 12/15/2002 04:07:02 PM JPMugaas
Started port to Indy 10. Still can not complete it though.
Rev 1.3 12/6/2002 05:29:38 PM JPMugaas
Now decend from TIdTCPClientCustom instead of TIdTCPClient.
Rev 1.2 12/1/2002 04:18:02 PM JPMugaas
Moved all dir parsing code to one place. Reworked to use more than one line
for determining dir format type along with flfNextLine dir format type.
Rev 1.1 11/14/2002 04:02:58 PM JPMugaas
Removed cludgy code that was a workaround for the RFC Reply limitation. That
is no longer limited.
Rev 1.0 11/14/2002 02:20:00 PM JPMugaas
2002-10-25 - J. Peter Mugaas
- added XCRC support - specified by "GlobalSCAPE Secure FTP Server Userís Guide"
which is available at http://www.globalscape.com
and also explained at http://www.southrivertech.com/support/titanftp/webhelp/titanftp.htm
- added COMB support - specified by "GlobalSCAPE Secure FTP Server Userís Guide"
which is available at http://www.globalscape.com
and also explained at http://www.southrivertech.com/support/titanftp/webhelp/titanftp.htm
2002-10-24 - J. Peter Mugaas
- now supports RFC 2640 - FTP Internalization
2002-09-18
_ added AFromBeginning parameter to InternalPut to correctly honor the AAppend parameter of Put
2002-09-05 - J. Peter Mugaas
- now complies with RFC 2389 - Feature negotiation mechanism for the File Transfer Protocol
- now complies with RFC 2428 - FTP Extensions for IPv6 and NATs
2002-08-27 - Andrew P.Rybin
- proxy support fix (non-standard ftp port's)
2002-01-xx - Andrew P.Rybin
- Proxy support, OnAfterGet (ex:decrypt, set srv timestamp)
- J.Peter Mugaas: not readonly ProxySettings
A Neillans - 10/17/2001
Merged changes submitted by Andrew P.Rybin
Correct command case problems - some servers expect commands in Uppercase only.
SP - 06/08/2001
Added a few more functions
Doychin - 02/18/2001
OnAfterLogin event handler and Login method
OnAfterLogin is executed after successfull login but before setting up the
connection properties. This event can be used to provide FTP proxy support
from the user application. Look at the FTP demo program for more information
on how to provide such support.
Doychin - 02/17/2001
New onFTPStatus event
New Quote method for executing commands not implemented by the compoent
-CleanDir contributed by Amedeo Lanza
}
unit IdFTP;
{
TODO: Change the FTP demo to demonstrate the use of the new events and add proxy support
}
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdAssignedNumbers, IdGlobal, IdCustomTransparentProxy, IdExceptionCore,
IdExplicitTLSClientServerBase, IdFTPCommon, IdFTPList, IdFTPListParseBase,
IdException, IdIOHandler, IdIOHandlerSocket, IdReplyFTP, IdBaseComponent,
IdReplyRFC, IdReply, IdSocketHandle, IdTCPConnection, IdTCPClient,
IdThreadSafe, IdZLibCompressorBase;
type
//APR 011216:
TIdFtpProxyType = (
fpcmNone,//Connect method:
fpcmUserSite, //Send command USER user@hostname - USER after login (see: http://isservices.tcd.ie/internet/command_config.php)
fpcmSite, //Send command SITE (with logon)
fpcmOpen, //Send command OPEN
fpcmUserPass,//USER user@firewalluser@hostname / PASS pass@firewallpass
fpcmTransparent, //First use the USER and PASS command with the firewall username and password, and then with the target host username and password.
fpcmUserHostFireWallID, //USER hostuserId@hostname firewallUsername
fpcmNovellBorder, //Novell BorderManager Proxy
fpcmHttpProxyWithFtp, //HTTP Proxy with FTP support. Will be supported in Indy 10
fpcmCustomProxy // use OnCustomFTPProxy to customize the proxy login
); //TIdFtpProxyType
//This has to be in the same order as TLS_AUTH_NAMES
TAuthCmd = (tAuto, tAuthTLS, tAuthSSL, tAuthTLSC, tAuthTLSP);
const
Id_TIdFTP_TransferType = {ftBinary} ftASCII; // RLebeau 1/22/08: per RFC 959
Id_TIdFTP_Passive = False;
Id_TIdFTP_UseNATFastTrack = False;
Id_TIdFTP_HostPortDelimiter = ':';
Id_TIdFTP_DataConAssurance = False;
Id_TIdFTP_DataPortProtection = ftpdpsClear;
//
DEF_Id_TIdFTP_Implicit = False;
DEF_Id_FTP_UseExtendedDataPort = False;
DEF_Id_TIdFTP_UseExtendedData = False;
DEF_Id_TIdFTP_UseMIS = True;
DEF_Id_FTP_UseCCC = False;
DEF_Id_FTP_AUTH_CMD = tAuto;
DEF_Id_FTP_ListenTimeout = 10000; // ten seconds
{
Soem firewalls don't handle control connections properly during long data transfers.
They will timeout the control connection because it's idle and making it worse is that they
will chop off a connection instead of closing it causing TIdFTP to wait forever for nothing.
}
DEF_Id_FTP_READTIMEOUT = 60000; //one minute
DEF_Id_FTP_UseHOST = True;
DEF_Id_FTP_PassiveUseControlHost = False;
DEF_Id_FTP_AutoIssueFEAT = True;
DEF_Id_FTP_AutoLogin = True;
type
//Added by SP
TIdCreateFTPList = procedure(ASender: TObject; var VFTPList: TIdFTPListItems) of object;
//TIdCheckListFormat = procedure(ASender: TObject; const ALine: String; var VListFormat: TIdFTPListFormat) of object;
TOnAfterClientLogin = TNotifyEvent;
TIdFtpAfterGet = procedure(ASender: TObject; AStream: TStream) of object; //APR
TIdOnDataChannelCreate = procedure(ASender: TObject; ADataChannel: TIdTCPConnection) of object;
TIdOnDataChannelDestroy = procedure(ASender: TObject; ADataChannel: TIdTCPConnection) of object;
TIdNeedAccountEvent = procedure(ASender: TObject; var VAcct: string) of object;
TIdFTPBannerEvent = procedure (ASender: TObject; const AMsg : String) of object;
TIdFTPClientIdentifier = class (TPersistent)
protected
FClientName : String;
FClientVersion : String;
FPlatformDescription : String;
procedure SetClientName(const AValue: String);
procedure SetClientVersion(const AValue: String);
procedure SetPlatformDescription(const AValue: String);
function GetClntOutput: String;
public
procedure Assign(Source: TPersistent); override;
property ClntOutput : String read GetClntOutput;
published
property ClientName : String read FClientName write SetClientName;
property ClientVersion : String read FClientVersion write SetClientVersion;
property PlatformDescription : String read FPlatformDescription write SetPlatformDescription;
end;
TIdFtpProxySettings = class (TPersistent)
protected
FHost, FUserName, FPassword: String;
FProxyType: TIdFtpProxyType;
FPort: TIdPort;
public
procedure Assign(Source: TPersistent); override;
published
property ProxyType: TIdFtpProxyType read FProxyType write FProxyType;
property Host: String read FHost write FHost;
property UserName: String read FUserName write FUserName;
property Password: String read FPassword write FPassword;
property Port: TIdPort read FPort write FPort;
end;
TIdFTPTZInfo = class(TPersistent)
protected
FGMTOffset : TDateTime;
FGMTOffsetAvailable : Boolean;
public
procedure Assign(Source: TPersistent); override;
published
property GMTOffset : TDateTime read FGMTOffset write FGMTOffset;
property GMTOffsetAvailable : Boolean read FGMTOffsetAvailable write FGMTOffsetAvailable;
end;
TIdFTPKeepAlive = class(TPersistent)
protected
FUseKeepAlive: Boolean;
FIdleTimeMS: Integer;
FIntervalMS: Integer;
public
procedure Assign(Source: TPersistent); override;
published
property UseKeepAlive: Boolean read FUseKeepAlive write FUseKeepAlive;
property IdleTimeMS: Integer read FIdleTimeMS write FIdleTimeMS;
property IntervalMS: Integer read FIntervalMS write FIntervalMS;
end;
TIdFTP = class(TIdExplicitTLSClient)
protected
FAutoLogin: Boolean;
FAutoIssueFEAT : Boolean;
FCurrentTransferMode : TIdFTPTransferMode;
FClientInfo : TIdFTPClientIdentifier;
FDataSettingsSent: Boolean; // only send SSL data settings once per connection
FUsingSFTP : Boolean; //enable SFTP internel flag
FUsingCCC : Boolean; //are we using FTP with SSL on a clear control channel?
FUseHOST: Boolean;
FServerHOST: String;
FCanUseMLS : Boolean; //can we use MLISx instead of LIST
FUsingExtDataPort : Boolean; //are NAT Extensions (RFC 2428 available) flag
FUsingNATFastTrack : Boolean;//are we using NAT fastrack feature
FCanResume: Boolean;
FListResult: TStrings;
FLoginMsg: TIdReplyFTP;
FPassive: Boolean;
FPassiveUseControlHost: Boolean;
FDataPortProtection : TIdFTPDataPortSecurity;
FAUTHCmd : TAuthCmd;
FDataPort: TIdPort;
FDataPortMin: TIdPort;
FDataPortMax: TIdPort;
FDefStringEncoding: TIdTextEncoding;
FExternalIP : String;
FResumeTested: Boolean;
FServerDesc: string;
FSystemDesc: string;
FTransferType: TIdFTPTransferType;
FTransferTimeout : Integer;
FListenTimeout : Integer;
FDataChannel: TIdTCPConnection;
FDirectoryListing: TIdFTPListItems;
FDirFormat : String;
FListParserClass : TIdFTPListParseClass;
FOnAfterClientLogin: TNotifyEvent;
FOnCreateFTPList: TIdCreateFTPList;
FOnBeforeGet: TNotifyEvent;
FOnBeforePut: TIdFtpAfterGet;
//in case someone needs to do something special with the data being uploaded
FOnAfterGet: TIdFtpAfterGet; //APR
FOnAfterPut: TNotifyEvent; //JPM at Don Sider's suggestion
FOnNeedAccount: TIdNeedAccountEvent;
FOnCustomFTPProxy : TNotifyEvent;
FOnDataChannelCreate: TIdOnDataChannelCreate;
FOnDataChannelDestroy: TIdOnDataChannelDestroy;
FProxySettings: TIdFtpProxySettings;
FUseExtensionDataPort : Boolean;
FTryNATFastTrack : Boolean;
FUseMLIS : Boolean;
FLangsSupported : TStrings;
FUseCCC: Boolean;
//is the SSCN Client method on for this connection?
FSSCNOn : Boolean;
FIsCompressionSupported : Boolean;
FOnBannerBeforeLogin : TIdFTPBannerEvent;
FOnBannerAfterLogin : TIdFTPBannerEvent;
FOnBannerWarning : TIdFTPBannerEvent;
FTZInfo : TIdFTPTZInfo;
FCompressor : TIdZLibCompressorBase;
//ZLib settings
FZLibCompressionLevel : Integer; //7
FZLibWindowBits : Integer; //-15
FZLibMemLevel : Integer; //8
FZLibStratagy : Integer; //0 - default
//dir events for some GUI programs.
//The directory was Retrieved from the FTP server.
FOnRetrievedDir : TNotifyEvent;
//parsing is done only when DirectoryListing is referenced
FOnDirParseStart : TNotifyEvent;
FOnDirParseEnd : TNotifyEvent;
//we probably need an Abort flag so we know when an abort is sent.
//It turns out that one server will send a 550 or 451 error followed by an
//ABOR successfull
FAbortFlag : TIdThreadSafeBoolean;
FAccount: string;
FNATKeepAlive: TIdFTPKeepAlive;
//
procedure DoOnDataChannelCreate;
procedure DoOnDataChannelDestroy;
procedure DoOnRetrievedDir;
procedure DoOnDirParseStart;
procedure DoOnDirParseEnd;
procedure FinalizeDataOperation;
procedure SetTZInfo(const Value: TIdFTPTZInfo);
function IsSiteZONESupported : Boolean;
function IndexOfFeatLine(const AFeatLine : String):Integer;
procedure ClearSSCN;
function SetSSCNToOn : Boolean;
procedure SendInternalPassive(const ACmd : String; var VIP: string; var VPort: TIdPort);
procedure SendCPassive(var VIP: string; var VPort: TIdPort);
function FindAuthCmd : String;
//
function GetReplyClass: TIdReplyClass; override;
//
procedure ParseFTPList;
procedure SetPassive(const AValue : Boolean);
procedure SetTryNATFastTrack(const AValue: Boolean);
procedure DoTryNATFastTrack;
procedure SetUseExtensionDataPort(const AValue: Boolean);
procedure SetIPVersion(const AValue: TIdIPVersion); override;
procedure SetIOHandler(AValue: TIdIOHandler); override;
function GetSupportsTLS: Boolean; override;
procedure ConstructDirListing;
procedure DoAfterLogin;
procedure DoFTPList;
procedure DoCustomFTPProxy;
procedure DoOnBannerAfterLogin(AText : TStrings);
procedure DoOnBannerBeforeLogin(AText : TStrings);
procedure DoOnBannerWarning(AText : TStrings);
procedure SendPBSZ; //protection buffer size
procedure SendPROT; //data port protection
procedure SendDataSettings; //this is for the extensions only;
// procedure DoCheckListFormat(const ALine: String);
function GetDirectoryListing: TIdFTPListItems;
// function GetOnParseCustomListFormat: TIdOnParseCustomListFormat;
procedure InitDataChannel;
//PRET is to help distributed FTP systems by letting them know what you will do
//before issuing a PASV. See: http://drftpd.mog.se/wiki/wiki.phtml?title=Distributed_PASV#PRE_Transfer_Command_for_Distributed_PASV_Transfers
//for a discussion.
procedure SendPret(const ACommand : String);
procedure InternalGet(const ACommand: string; ADest: TStream; AResume: Boolean = false);
procedure InternalPut(const ACommand: string; ASource: TStream; AFromBeginning: Boolean = True; AResume: Boolean = False);
// procedure SetOnParseCustomListFormat(const AValue: TIdOnParseCustomListFormat);
procedure SendPassive(var VIP: string; var VPort: TIdPort);
procedure SendPort(AHandle: TIdSocketHandle); overload;
procedure SendPort(const AIP : String; const APort : TIdPort); overload;
procedure ParseEPSV(const AReply : String; var VIP : String; var VPort : TIdPort);
//These two are for RFC 2428.txt
procedure SendEPort(AHandle: TIdSocketHandle); overload;
procedure SendEPort(const AIP : String; const APort : TIdPort; const AIPVersion : TIdIPVersion); overload;
procedure SendEPassive(var VIP: string; var VPort: TIdPort);
function SendHost: Smallint;
procedure SetProxySettings(const Value: TIdFtpProxySettings);
procedure SetClientInfo(const AValue: TIdFTPClientIdentifier);
procedure SetCompressor(AValue: TIdZLibCompressorBase);
procedure SendTransferType(AValue: TIdFTPTransferType);
procedure SetTransferType(AValue: TIdFTPTransferType);
procedure DoBeforeGet; virtual;
procedure DoBeforePut(AStream: TStream); virtual;
procedure DoAfterGet(AStream: TStream); virtual; //APR
procedure DoAfterPut; virtual;
class procedure FXPSetTransferPorts(AFromSite, AToSite: TIdFTP; const ATargetUsesPasv : Boolean);
class procedure FXPSendFile(AFromSite, AToSite: TIdFTP; const ASourceFile, ADestFile: String);
class function InternalEncryptedTLSFXP(AFromSite, AToSite: TIdFTP; const ASourceFile, ADestFile: String; const ATargetUsesPasv : Boolean) : Boolean;
class function InternalUnencryptedFXP(AFromSite, AToSite: TIdFTP; const ASourceFile, ADestFile: String; const ATargetUsesPasv : Boolean): Boolean;
class function ValidateInternalIsTLSFXP(AFromSite, AToSite: TIdFTP; const ATargetUsesPasv : Boolean): Boolean;
procedure InitComponent; override;
procedure SetUseTLS(AValue : TIdUseTLS); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetDataPortProtection(AValue : TIdFTPDataPortSecurity);
procedure SetAUTHCmd(const AValue : TAuthCmd);
procedure SetDefStringEncoding(AValue: TIdTextEncoding);
procedure SetUseCCC(const AValue: Boolean);
procedure SetNATKeepAlive(AValue: TIdFTPKeepAlive);
procedure IssueFEAT;
//specific server detection
function IsOldServU: Boolean;
function IsBPFTP : Boolean;
function IsTitan : Boolean;
function IsWSFTP : Boolean;
function IsIIS: Boolean;
function CheckAccount: Boolean;
function IsAccountNeeded : Boolean;
function GetSupportsVerification : Boolean;
public
procedure GetInternalResponse(AEncoding: TIdTextEncoding = nil); override;
function CheckResponse(const AResponse: SmallInt; const AAllowedResponses: array of SmallInt): SmallInt; override;
function IsExtSupported(const ACmd : String):Boolean;
procedure ExtractFeatFacts(const ACmd : String; AResults : TStrings);
//this function transparantly handles OTP based on the Last command response
//so it needs to be called only after the USER command or equivilent.
function GetLoginPassword : String; overload;
function GetLoginPassword(const APrompt : String) : String; overload;
procedure Abort; virtual;
procedure Allocate(AAllocateBytes: Integer);
procedure ChangeDir(const ADirName: string);
procedure ChangeDirUp;
procedure Connect; override;
destructor Destroy; override;
procedure Delete(const AFilename: string);
procedure FileStructure(AStructure: TIdFTPDataStructure);
procedure Get(const ASourceFile: string; ADest: TStream; AResume: Boolean = false); overload;
procedure Get(const ASourceFile, ADestFile: string; const ACanOverwrite: boolean = false; AResume: Boolean = false); overload;
procedure Help(AHelpContents: TStrings; ACommand: String = '');
procedure KillDataChannel; virtual;
//.NET Overload
procedure List; overload;
//.NET Overload
procedure List(const ASpecifier: string; ADetails: Boolean = True); overload;
procedure List(ADest: TStrings; const ASpecifier: string = ''; ADetails: Boolean = True); overload;
procedure ExtListDir(ADest: TStrings = nil; const ADirectory: string = '');
procedure ExtListItem(ADest: TStrings; AFList : TIdFTPListItems; const AItem: string=''); overload;
procedure ExtListItem(ADest: TStrings; const AItem: string = ''); overload;
procedure ExtListItem(AFList : TIdFTPListItems; const AItem : String= ''); overload;
function FileDate(const AFileName : String; const AsGMT : Boolean = False): TDateTime;
procedure Login;
procedure MakeDir(const ADirName: string);
procedure Noop;
procedure SetCmdOpt(const ACMD, AOptions : String);
procedure Put(const ASource: TStream; const ADestFile: string;
const AAppend: Boolean = False; const AStartPos: TIdStreamSize = -1); overload;
procedure Put(const ASourceFile: string; const ADestFile: string = '';
const AAppend: Boolean = False; const AStartPos: TIdStreamSize = -1); overload;
procedure StoreUnique(const ASource: TStream; const AStartPos: TIdStreamSize = -1); overload;
procedure StoreUnique(const ASourceFile: string; const AStartPos: TIdStreamSize = -1); overload;
procedure SiteToSiteUpload(const AToSite : TIdFTP; const ASourceFile : String; const ADestFile : String = '');
procedure SiteToSiteDownload(const AFromSite: TIdFTP; const ASourceFile : String; const ADestFile : String = '');
procedure DisconnectNotifyPeer; override;
procedure Quit; {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPECATED_MSG} 'Use Disconnect() instead'{$ENDIF};{$ENDIF}
function Quote(const ACommand: String): SmallInt;
procedure RemoveDir(const ADirName: string);
procedure Rename(const ASourceFile, ADestFile: string);
function ResumeSupported: Boolean;
function RetrieveCurrentDir: string;
procedure Site(const ACommand: string);
function Size(const AFileName: String): Int64;
procedure Status(AStatusList: TStrings);
procedure StructureMount(APath: String);
procedure TransferMode(ATransferMode: TIdFTPTransferMode);
procedure ReInitialize(ADelay: Cardinal = 10);
procedure SetLang(const ALangTag : String);
function CRC(const AFIleName : String; const AStartPoint : Int64 = 0; const AEndPoint : Int64=0) : Int64;
//verify file was uploaded, this is more comprehensive than the above
function VerifyFile(ALocalFile : TStream; const ARemoteFile : String;
const AStartPoint : TIdStreamSize = 0; const AByteCount : TIdStreamSize = 0) : Boolean; overload;
function VerifyFile(const ALocalFile, ARemoteFile : String;
const AStartPoint : TIdStreamSize = 0; const AByteCount : TIdStreamSize = 0) : Boolean; overload;
//file parts must be in order in TStrings parameter
//GlobalScape FTP Pro uses this for multipart simultanious file uploading
procedure CombineFiles(const ATargetFile : String; AFileParts : TStrings);
//Set modified file time.
procedure SetModTime(const AFileName: String; const ALocalTime: TDateTime);
procedure SetModTimeGMT(const AFileName : String; const AGMTTime: TDateTime);
// servers that support MDTM yyyymmddhhmmss[+-xxx] and also support LIST -T
//This is true for servers that are known to support these even if they aren't
//listed in the FEAT reply.
function IsServerMDTZAndListTForm : Boolean;
property IsCompressionSupported : Boolean read FIsCompressionSupported;
//
property SupportsVerification : Boolean read GetSupportsVerification;
property CanResume: Boolean read ResumeSupported;
property CanUseMLS : Boolean read FCanUseMLS;
property DirectoryListing: TIdFTPListItems read GetDirectoryListing;
property DirFormat : String read FDirFormat;
property LangsSupported : TStrings read FLangsSupported;
property ListParserClass : TIdFTPListParseClass read FListParserClass write FListParserClass;
property LoginMsg: TIdReplyFTP read FLoginMsg;
property ListResult: TStrings read FListResult;
property SystemDesc: string read FSystemDesc;
property TZInfo : TIdFTPTZInfo read FTZInfo write SetTZInfo;
property UsingExtDataPort : Boolean read FUsingExtDataPort;
property UsingNATFastTrack : Boolean read FUsingNATFastTrack;
property UsingSFTP : Boolean read FUsingSFTP;
property CurrentTransferMode : TIdFTPTransferMode read FCurrentTransferMode write TransferMode;
published
{$IFDEF DOTNET}
{$IFDEF DOTNET_2_OR_ABOVE}
property IPVersion;
{$ENDIF}
{$ELSE}
property IPVersion;
{$ENDIF}
property AutoIssueFEAT : Boolean read FAutoIssueFEAT write FAutoIssueFEAT default DEF_Id_FTP_AutoIssueFEAT;
property AutoLogin: Boolean read FAutoLogin write FAutoLogin default DEF_Id_FTP_AutoLogin;
// This is an object that can compress and decompress FTP Deflate encoding
property Compressor : TIdZLibCompressorBase read FCompressor write SetCompressor;
property Host;
property UseCCC : Boolean read FUseCCC write SetUseCCC default DEF_Id_FTP_UseCCC;
property Passive: boolean read FPassive write SetPassive default Id_TIdFTP_Passive;
property PassiveUseControlHost: Boolean read FPassiveUseControlHost write FPassiveUseControlHost default DEF_Id_FTP_PassiveUseControlHost;
property DataPortProtection : TIdFTPDataPortSecurity read FDataPortProtection write SetDataPortProtection default Id_TIdFTP_DataPortProtection;
property AUTHCmd : TAuthCmd read FAUTHCmd write SetAUTHCmd default DEF_Id_FTP_AUTH_CMD;
property DataPort: TIdPort read FDataPort write FDataPort default 0;
property DataPortMin: TIdPort read FDataPortMin write FDataPortMin default 0;
property DataPortMax: TIdPort read FDataPortMax write FDataPortMax default 0;
property DefStringEncoding : TIdTextEncoding read FDefStringEncoding write SetDefStringEncoding;
property ExternalIP : String read FExternalIP write FExternalIP;
property Password;
property TransferType: TIdFTPTransferType read FTransferType write SetTransferType default Id_TIdFTP_TransferType;
property TransferTimeout: Integer read FTransferTimeout write FTransferTimeout default IdDefTimeout;
property ListenTimeout : Integer read FListenTimeout write FListenTimeout default DEF_Id_FTP_ListenTimeout;
property Username;
property Port default IDPORT_FTP;
property UseExtensionDataPort : Boolean read FUseExtensionDataPort write SetUseExtensionDataPort default DEF_Id_TIdFTP_UseExtendedData;
property UseMLIS : Boolean read FUseMLIS write FUseMLIS default DEF_Id_TIdFTP_UseMIS;
property TryNATFastTrack : Boolean read FTryNATFastTrack write SetTryNATFastTrack default Id_TIdFTP_UseNATFastTrack;
property NATKeepAlive: TIdFTPKeepAlive read FNATKeepAlive write SetNATKeepAlive;
property ProxySettings: TIdFtpProxySettings read FProxySettings write SetProxySettings;
property Account: string read FAccount write FAccount;
property ClientInfo : TIdFTPClientIdentifier read FClientInfo write SetClientInfo;
property UseHOST: Boolean read FUseHOST write FUseHOST default DEF_Id_FTP_UseHOST;
property ServerHOST: String read FServerHOST write FServerHOST;
property UseTLS;
property OnTLSNotAvailable;
property OnBannerBeforeLogin : TIdFTPBannerEvent read FOnBannerBeforeLogin write FOnBannerBeforeLogin;
property OnBannerAfterLogin : TIdFTPBannerEvent read FOnBannerAfterLogin write FOnBannerAfterLogin;
property OnBannerWarning : TIdFTPBannerEvent read FOnBannerWarning write FOnBannerWarning;
property OnAfterClientLogin: TOnAfterClientLogin read FOnAfterClientLogin write FOnAfterClientLogin;
property OnCreateFTPList: TIdCreateFTPList read FOnCreateFTPList write FOnCreateFTPList;
property OnAfterGet: TIdFtpAfterGet read FOnAfterGet write FOnAfterGet; //APR
property OnAfterPut: TNotifyEvent read FOnAfterPut write FOnAfterPut;
property OnNeedAccount: TIdNeedAccountEvent read FOnNeedAccount write FOnNeedAccount;
property OnCustomFTPProxy : TNotifyEvent read FOnCustomFTPProxy write FOnCustomFTPProxy;
property OnDataChannelCreate: TIdOnDataChannelCreate read FOnDataChannelCreate write FOnDataChannelCreate;
property OnDataChannelDestroy: TIdOnDataChannelDestroy read FOnDataChannelDestroy write FOnDataChannelDestroy;
//The directory was Retrieved from the FTP server.
property OnRetrievedDir : TNotifyEvent read FOnRetrievedDir write FOnRetrievedDir;
//parsing is done only when DirectoryLiusting is referenced
property OnDirParseStart : TNotifyEvent read FOnDirParseStart write FOnDirParseStart;
property OnDirParseEnd : TNotifyEvent read FOnDirParseEnd write FOnDirParseEnd;
property ReadTimeout default DEF_Id_FTP_READTIMEOUT;
end;
EIdFTPException = class(EIdException);
EIdFTPFileAlreadyExists = class(EIdFTPException);
EIdFTPMustUseExtWithIPv6 = class(EIdFTPException);
EIdFTPMustUseExtWithNATFastTrack = class(EIdFTPException);
EIdFTPPassiveMustBeTrueWithNATFT = class(EIdFTPException);
EIdFTPServerSentInvalidPort = class(EIdFTPException);
EIdFTPSiteToSiteTransfer = class(EIdFTPException);
EIdFTPSToSNATFastTrack = class(EIdFTPSiteToSiteTransfer);
EIdFTPSToSNoDataProtection = class(EIdFTPSiteToSiteTransfer);
EIdFTPSToSIPProtoMustBeSame = class(EIdFTPSiteToSiteTransfer);
EIdFTPSToSBothMostSupportSSCN = class(EIdFTPSiteToSiteTransfer);
EIdFTPSToSTransModesMustBeSame = class(EIdFTPSiteToSiteTransfer);
EIdFTPOnCustomFTPProxyRequired = class(EIdFTPException);
EIdFTPConnAssuranceFailure = class(EIdFTPException);
EIdFTPWrongIOHandler = class(EIdFTPException);
EIdFTPUploadFileNameCanNotBeEmpty = class(EIdFTPException);
EIdFTPDataPortProtection = class(EIdFTPException);
EIdFTPNoDataPortProtectionAfterCCC = class(EIdFTPDataPortProtection);
EIdFTPNoDataPortProtectionWOEncryption = class(EIdFTPDataPortProtection);
EIdFTPNoCCCWOEncryption = class(EIdFTPException);
EIdFTPAUTHException = class(EIdFTPException);
EIdFTPNoAUTHWOSSL = class(EIdFTPAUTHException);
EIdFTPCanNotSetAUTHCon = class(EIdFTPAUTHException);
EIdFTPMissingCompressor = class(EIdFTPException);
EIdFTPCompressorNotReady = class(EIdFTPException);
EIdFTPUnsupportedTransferMode = class(EIdFTPException);
EIdFTPUnsupportedTransferType = class(EIdFTPException);
implementation
uses
//facilitate inlining only.
{$IFDEF KYLIXCOMPAT}
Libc,
{$ENDIF}
{$IFDEF USE_VCL_POSIX}
Posix.SysSelect,
Posix.SysTime,
Posix.Unistd,
{$ENDIF}
{$IFDEF WINDOWS}
//facilitate inlining only.
Windows,
{$ENDIF}
{$IFDEF DOTNET}
{$IFDEF USE_INLINE}
System.IO,
System.Threading,
{$ENDIF}
{$ENDIF}
IdComponent,
IdFIPS,
IdResourceStringsCore, IdIOHandlerStack, IdResourceStringsProtocols,
IdSSL, IdGlobalProtocols, IdHash, IdHashCRC, IdHashSHA, IdHashMessageDigest,
IdStack, IdSimpleServer, IdOTPCalculator, SysUtils;
const
cIPVersions: array[TIdIPVersion] of String = ('1', '2'); {do not localize}
type
TIdFTPListResult = class(TStringList)
private
FDetails: Boolean; //Did the developer use the NLST command for the last list command
FUsedMLS : Boolean; //Did the developer use MLSx commands for the last list command
public
property Details: Boolean read FDetails;
property UsedMLS: Boolean read FUsedMLS;
end;
procedure TIdFTP.InitComponent;
begin
inherited InitComponent;
//
FAutoLogin := DEF_Id_FTP_AutoLogin;
FRegularProtPort := IdPORT_FTP;
FImplicitTLSProtPort := IdPORT_ftps;
//
Port := IDPORT_FTP;
Passive := Id_TIdFTP_Passive;
FPassiveUseControlHost := DEF_Id_FTP_PassiveUseControlHost;
FDataPortProtection := Id_TIdFTP_DataPortProtection;
FUseCCC := DEF_Id_FTP_UseCCC;
FAUTHCmd := DEF_Id_FTP_AUTH_CMD;
FUseHOST := DEF_Id_FTP_UseHOST;
FDataPort := 0;
FDataPortMin := 0;
FDataPortMax := 0;
FDefStringEncoding := Indy8BitEncoding;
FUseExtensionDataPort := DEF_Id_TIdFTP_UseExtendedData;
FTryNATFastTrack := Id_TIdFTP_UseNATFastTrack;
FTransferType := Id_TIdFTP_TransferType;
FTransferTimeout := IdDefTimeout;
FListenTimeout := DEF_Id_FTP_ListenTimeout;
FLoginMsg := TIdReplyFTP.Create(nil);
FListResult := TIdFTPListResult.Create;
FLangsSupported := TStringList.Create;
FCanResume := False;
FResumeTested := False;
FProxySettings:= TIdFtpProxySettings.Create; //APR
FClientInfo := TIdFTPClientIdentifier.Create;
FTZInfo := TIdFTPTZInfo.Create;
FTZInfo.FGMTOffsetAvailable := False;
FUseMLIS := DEF_Id_TIdFTP_UseMIS;
FCanUseMLS := False; //initialize MLIS flags
//Settings specified by
// http://www.ietf.org/internet-drafts/draft-preston-ftpext-deflate-00.txt
FZLibCompressionLevel := DEF_ZLIB_COMP_LEVEL;
FZLibWindowBits := DEF_ZLIB_WINDOW_BITS; //-15 - no extra headers
FZLibMemLevel := DEF_ZLIB_MEM_LEVEL;
FZLibStratagy := DEF_ZLIB_STRATAGY; // - default
//
FAbortFlag := TIdThreadSafeBoolean.Create;
FAbortFlag.Value := False;
{
Some firewalls don't handle control connections properly during long
data transfers. They will timeout the control connection because it
is idle and making it worse is that they will chop off a connection
instead of closing it, causing TIdFTP to wait forever for nothing.
}
FNATKeepAlive := TIdFTPKeepAlive.Create;
ReadTimeout := DEF_Id_FTP_READTIMEOUT;
FAutoIssueFEAT := DEF_Id_FTP_AutoIssueFEAT;
end;
{$IFNDEF HAS_TryEncodeTime}
// TODO: move this to IdGlobal or IdGlobalProtocols...
function TryEncodeTime(Hour, Min, Sec, MSec: Word; out VTime: TDateTime): Boolean;
begin
try
VTime := EncodeTime(Hour, Min, Sec, MSec);
Result := True;
except
Result := False;
end;
end;
{$ENDIF}
{$IFNDEF HAS_TryStrToInt}
// TODO: use the implementation already in IdGlobalProtocols...
function TryStrToInt(const S: string; out Value: Integer): Boolean;
{$IFDEF USE_INLINE}inline;{$ENDIF}
var
E: Integer;
begin
Val(S, Value, E);
Result := E = 0;
end;
{$ENDIF}
procedure TIdFTP.Connect;
var
LHost: String;
LPort: TIdPort;
LBuf : String;
LSendQuitOnError: Boolean;
LOffs: Integer;
begin
LSendQuitOnError := False;
FCurrentTransferMode := dmStream;
FTZInfo.FGMTOffsetAvailable := False;
//FSSCNOn should be set to false to prevent problems.
FSSCNOn := False;
FUsingSFTP := False;
FUsingCCC := False;
FDataSettingsSent := False;
if FUseExtensionDataPort then begin
FUsingExtDataPort := True;
end;
FUsingNATFastTrack := False;
FCapabilities.Clear;
try
//APR 011216: proxy support
LHost := FHost;
LPort := FPort;
try
//I think fpcmTransparent means to connect to the regular host and the firewalll
//intercepts the login information.
if (ProxySettings.ProxyType <> fpcmNone) and (ProxySettings.ProxyType <> fpcmTransparent) and
(Length(ProxySettings.Host) > 0) then begin
FHost := ProxySettings.Host;
FPort := ProxySettings.Port;
end;
if FUseTLS = utUseImplicitTLS then begin
//at this point, we treat implicit FTP as if it were explicit FTP with TLS
FUsingSFTP := True;
end;
inherited Connect;
finally
FHost := LHost;
FPort := LPort;
end;
// RLebeau: must not send/receive UTF-8 before negotiating for it...
IOHandler.DefStringEncoding := FDefStringEncoding;
{$IFDEF STRING_IS_ANSI}
IOHandler.DefAnsiEncoding := IndyOSDefaultEncoding;
{$ENDIF}
// RLebeau: RFC 959 says that the greeting can be preceeded by a 1xx
// reply and that the client should wait for the 220 reply when this
// happens. Also, the RFC says that 120 should be used, but some
// servers use other 1xx codes, such as 130, so handle 1xx generically
// calling GetInternalResponse() directly to avoid duplicate calls
// to CheckResponse() for the initial response if it is not 1xx
GetInternalResponse;
if (LastCmdResult.NumericCode div 100) = 1 then begin
DoOnBannerWarning(LastCmdResult.FormattedReply);
GetResponse(220);
end else begin
CheckResponse(LastCmdResult.NumericCode, [220]);
end;
LSendQuitOnError := True;
FGreeting.Assign(LastCmdResult);
// Save initial greeting for server identification in case FGreeting changes
// in response to the HOST command
if FGreeting.Text.Count > 0 then begin
FServerDesc := FGreeting.Text[0];
end else begin
FServerDesc := '';
end;
// Implement HOST command as specified by
// http://tools.ietf.org/html/draft-hethmon-mcmurray-ftp-hosts-01
// Do not check the response for failures. The draft suggests allowing
// 220 (success) and 500/502 (unsupported), but vsftpd returns 530, and
// whatever ftp.microsoft.com is running returns 504.
if UseHOST then begin
if SendHost() <> 220 then begin
// RLebeau: WS_FTP Server 5.x disconnects if the command fails,
// whereas WS_FTP Server 6+ does not. If the server disconnected
// here, let's mimic FTP Voyager by reconnecting without using
// the HOST command again...
if IsWSFTP then begin
try
IOHandler.CheckForDisconnect(True, True);
except
on E: EIdConnClosedGracefully do
begin
Disconnect(False);
IOHandler.InputBuffer.Clear;
UseHOST := False;
try
Connect;
finally
UseHOST := True;
end;
Exit;
end;
end;
end;
end else begin
FGreeting.Assign(LastCmdResult);
end;
end;
DoOnBannerBeforeLogin (FGreeting.FormattedReply);
// RLebeau: having an AutoIssueFeat property doesn't make sense to
// me. There are commands below that require FEAT's response, but
// if the user sets AutoIssueFeat to False, these commands will not
// be allowed to execute!
if AutoLogin then begin
Login;
DoAfterLogin;
//Fast track is set only one time per connection and no more, even
//with REINIT
if TryNATFastTrack then begin
DoTryNATFastTrack;
end;
if FUseTLS = utUseImplicitTLS then begin
//at this point, we treat implicit FTP as if it were explicit FTP with TLS
FUsingSFTP := True;
end;
// OpenVMS 7.1 replies with 200 instead of 215 - What does the RFC say about this?
// if SendCmd('SYST', [200, 215, 500]) = 500 then begin {do not localize}
//Do not fault if SYST was not understood by the server. Novel Netware FTP
//may not understand SYST.
if SendCmd('SYST') = 500 then begin {do not localize}
FSystemDesc := RSFTPUnknownHost;
end else begin
FSystemDesc := LastCmdResult.Text[0];
end;
if IsSiteZONESupported then begin
if SendCmd('SITE ZONE') = 210 then begin {do not localize}
if LastCmdResult.Text.Count > 0 then begin
LBuf := LastCmdResult.Text[0];
// some servers (Serv-U, etc) use a 'UTC' offset string, ie
// "UTC-300", specifying the number of minutes from UTC. Other
// servers (Apache) use a GMT offset string instead, ie "-0300".
if TextStartsWith(LBuf, 'UTC-') then begin {do not localize}
// Titan FTP 6.26.634 incorrectly returns UTC-2147483647 when it's
// first installed.
FTZInfo.FGMTOffsetAvailable :=
TryStrToInt(Copy(LBuf, 4, MaxInt), LOffs) and
TryEncodeTime(Abs(LOffs) div 60, Abs(LOffs) mod 60, 0, 0, FTZInfo.FGMTOffset);
if FTZInfo.FGMTOffsetAvailable and (LOffs < 0) then
FTZInfo.FGMTOffset := -FTZInfo.FGMTOffset
end else begin
FTZInfo.FGMTOffsetAvailable := True;
FTZInfo.GMTOffset := GmtOffsetStrToDateTime(LBuf);
end;
end;
end;
end;
SendTransferType(FTransferType);
DoStatus(ftpReady, [RSFTPStatusReady]);
end else begin
// OpenVMS 7.1 replies with 200 instead of 215 - What does the RFC say about this?
// if SendCmd('SYST', [200, 215, 500]) = 500 then begin {do not localize}
//Do not fault if SYST was not understood by the server. Novel Netware FTP
//may not understand SYST.
if SendCmd('SYST') = 500 then begin {do not localize}
FSystemDesc := RSFTPUnknownHost;
end else begin
FSystemDesc := LastCmdResult.Text[0];
end;
if FAutoIssueFEAT then begin
IssueFEAT;
end;
end;
except
Disconnect(LSendQuitOnError); // RLebeau: do not send the QUIT command if the greeting was not received
raise;
end;
end;
function TIdFTP.SendHost: Smallint;
var
LHost: String;
begin
LHost := FServerHOST;
if LHost = '' then begin
LHost := FHost;
end;
if Socket <> nil then begin
if LHost = Socket.Binding.PeerIP then begin
LHost := '[' + LHost + ']'; {do not localize}
end;
end;
Result := SendCmd('HOST ' + LHost); {do not localize}
end;
procedure TIdFTP.SetTransferType(AValue: TIdFTPTransferType);
begin
if AValue <> FTransferType then begin
if not Assigned(FDataChannel) then begin
if Connected then begin
SendTransferType(AValue);
end;
FTransferType := AValue;
end;
end;
end;
procedure TIdFTP.SendTransferType(AValue: TIdFTPTransferType);
var
s: string;
begin
s := '';
case AValue of
ftAscii: s := 'A'; {do not localize}
ftBinary: s := 'I'; {do not localize}
else
raise EIdFTPUnsupportedTransferType.Create(RSFTPUnsupportedTransferType);
end;
SendCmd('TYPE ' + s, 200); {do not localize}
end;
function TIdFTP.ResumeSupported: Boolean;
begin
if not FResumeTested then begin
FResumeTested := True;
FCanResume := Quote('REST 1') = 350; {do not localize}
Quote('REST 0'); {do not localize}
end;
Result := FCanResume;
end;
procedure TIdFTP.Get(const ASourceFile: string; ADest: TStream; AResume: Boolean = False);
begin
//for SSL FXP, we have to do it here because InternalGet is used by the LIST command
//where SSCN is ignored.
ClearSSCN;
AResume := AResume and CanResume;
DoBeforeGet;
// RLebeau 7/26/06: do not do this! It breaks the ability to resume files
// ADest.Position := 0;
InternalGet('RETR ' + ASourceFile, ADest, AResume);
DoAfterGet(ADest);
end;
procedure TIdFTP.Get(const ASourceFile, ADestFile: string; const ACanOverwrite: Boolean = False;
AResume: Boolean = False);
var
LDestStream: TStream;
begin
AResume := AResume and CanResume;
if ACanOverwrite and (not AResume) then begin
SysUtils.DeleteFile(ADestFile);
LDestStream := TIdFileCreateStream.Create(ADestFile);
end
else if (not ACanOverwrite) and AResume then begin
LDestStream := TIdAppendFileStream.Create(ADestFile);
end
else if not FileExists(ADestFile) then begin
LDestStream := TIdFileCreateStream.Create(ADestFile);
end
else begin
raise EIdFTPFileAlreadyExists.Create(RSDestinationFileAlreadyExists);
end;
try
Get(ASourceFile, LDestStream, AResume);
finally
FreeAndNil(LDestStream);
end;
end;
procedure TIdFTP.DoBeforeGet;
begin
if Assigned(FOnBeforeGet) then begin
FOnBeforeGet(Self);
end;
end;
procedure TIdFTP.DoBeforePut(AStream: TStream);
begin
if Assigned(FOnBeforePut) then begin
FOnBeforePut(Self, AStream);
end;
end;
procedure TIdFTP.DoAfterGet(AStream: TStream);//APR
begin
if Assigned(FOnAfterGet) then begin
FOnAfterGet(Self, AStream);
end;
end;
procedure TIdFTP.DoAfterPut;
begin
if Assigned(FOnAfterPut) then begin
FOnAfterPut(Self);
end;
end;
procedure TIdFTP.ConstructDirListing;
begin
if not Assigned(FDirectoryListing) then begin
if not IsDesignTime then begin
DoFTPList;
end;
if not Assigned(FDirectoryListing) then begin
FDirectoryListing := TIdFTPListItems.Create;
end;
end else begin
FDirectoryListing.Clear;
end;
end;
procedure TIdFTP.List(ADest: TStrings; const ASpecifier: string = ''; ADetails: Boolean = True); {do not localize}
var
LDest: TMemoryStream;
LTrans : TIdFTPTransferType;
begin
if ADetails and UseMLIS and FCanUseMLS then begin
ExtListDir(ADest, ASpecifier);
Exit;
end;
// Note that for LIST, it might be best to put the connection in ASCII mode
// because some old servers such as TOPS20 might require this. We restore
// it if the original mode was not ASCII. It's a good idea to do this
// anyway because some clients still do this such as WS_FTP Pro and
// Microsoft's FTP Client.
LTrans := TransferType;
if LTrans <> ftASCII then begin
Self.TransferType := ftASCII;
end;
try
LDest := TMemoryStream.Create;
try
InternalGet(Trim(iif(ADetails, 'LIST', 'NLST') + ' ' + ASpecifier), LDest); {do not localize}
FreeAndNil(FDirectoryListing);
FDirFormat := '';
LDest.Position := 0;
{$IFDEF HAS_TEncoding}
FListResult.LoadFromStream(LDest, IOHandler.DefStringEncoding);
{$ELSE}
FListResult.Text := ReadStringFromStream(LDest, -1, IOHandler.DefStringEncoding{$IFDEF STRING_IS_ANSI}, IOHandler.DefAnsiEncoding{$ENDIF});
{$ENDIF}
with TIdFTPListResult(FListResult) do begin
FDetails := ADetails;
FUsedMLS := False;
end;
// FDirFormat will be updated in ParseFTPList...
finally
FreeAndNil(LDest);
end;
if ADest <> nil then begin
ADest.Assign(FListResult);
end;
DoOnRetrievedDir;
finally
if LTrans <> ftASCII then begin
TransferType := LTrans;
end;
end;
end;
const
AbortedReplies : array [0..5] of smallint =
(226,426, 450,451,425,550);
//226 was added because one server will return that twice if you aborted
//during an upload.
AcceptableAbortReplies : array [0..8] of smallint =
(225, 226, 250, 426, 450,451,425,550,552);
//GlobalScape Secure FTP Server returns a 552 for an aborted file
procedure TIdFTP.FinalizeDataOperation;
var
LResponse : SmallInt;
begin
DoOnDataChannelDestroy;
if FDataChannel <> nil then begin
FDataChannel.IOHandler.Free;
FDataChannel.IOHandler := nil;
FreeAndNil(FDataChannel);
end;
{
This is a bug fix for servers will do something like this:
[2] Mon 06Jun05 13:33:28 - (000007) PASV
[6] Mon 06Jun05 13:33:28 - (000007) 227 Entering Passive Mode (192,168,1,107,4,22)
[2] Mon 06Jun05 13:33:28 - (000007) RETR test.txt.txt
[6] Mon 06Jun05 13:33:28 - (000007) 550 /test.txt.txt: No such file or directory.
[2] Mon 06Jun05 13:34:28 - (000007) QUIT
[6] Mon 06Jun05 13:34:28 - (000007) 221 Goodbye!
[5] Mon 06Jun05 13:34:28 - (000007) Closing connection for user TEST (00:01:08 connected)
}
if (LastCmdResult.NumericCode div 100) > 2 then
begin
DoStatus(ftpAborted, [RSFTPStatusAbortTransfer]);
Exit;
end;
DoStatus(ftpReady, [RSFTPStatusDoneTransfer]);
// 226 = download successful, 225 = Abort successful}
if FAbortFlag.Value then begin
LResponse := GetResponse(AcceptableAbortReplies);
//Experimental -
if PosInSmallIntArray(LResponse,AbortedReplies)>-1 then begin
GetResponse([226, 225]);
end;
//IMPORTANT!!! KEEP THIS COMMENT!!!
//
//This is a workaround for a problem. When uploading a file on
//one FTP server and aborting that upload, I got this:
//
//Sent 3/9/2005 10:34:58 AM: STOR --------
//Recv 3/9/2005 10:34:58 AM: 150 Opening BINARY mode data connection for [3513]Red_Glas.zip
//Sent 3/9/2005 10:34:59 AM: ABOR
//Recv 3/9/2005 10:35:00 AM: 226 Transfer complete.
//Recv 3/9/2005 10:35:00 AM: 226 Abort successful
//
//but at ftp.ipswitch.com (a WS_FTP Server 5.0.4 (2555009845) server ),
//I was getting this when aborting a download
//
//Sent 3/9/2005 12:43:41 AM: RETR imail6.pdf
//Recv 3/9/2005 12:43:41 AM: 150 Opening BINARY data connection for imail6.pdf (2150082 bytes)
//Sent 3/9/2005 12:43:42 AM: ABOR
//Recv 3/9/2005 12:43:42 AM: 226 abort successful
//Recv 3/9/2005 12:43:43 AM: 425 transfer canceled
//
if LResponse = 226 then begin
if IOHandler.Readable(10) then begin
GetResponse(AbortedReplies);
end;
end;
DoStatus(ftpAborted, [RSFTPStatusAbortTransfer]);
//end experimental section
end else begin
//ftp.marist.edu returns 250
GetResponse([226, 225, 250]);
end;
end;
procedure TIdFTP.InternalPut(const ACommand: string; ASource: TStream;
AFromBeginning: Boolean = True; AResume: Boolean = False);
{$IFNDEF MSWINDOWS}
procedure WriteStreamFromBeginning;
var
LBuffer: TIdBytes;
LBufSize: Integer;
begin
// Copy entire stream without relying on ASource.Size so Unix-to-DOS
// conversion can be done on the fly.
BeginWork(wmWrite, ASource.Size);
try
SetLength(LBuffer, FDataChannel.IOHandler.SendBufferSize);
while True do begin
LBufSize := ASource.Read(LBuffer[0], Length(LBuffer));
if LBufSize > 0 then
FDataChannel.IOHandler.Write(LBuffer, LBufSize)
else
Break;
end;
finally
EndWork(wmWrite);
end;
end;
{$ENDIF}
var
LIP: string;
LPort: TIdPort;
LPasvCl : TIdTCPClient;
LPortSv : TIdSimpleServer;
begin
FAbortFlag.Value := False;
if FCurrentTransferMode = dmDeflate then begin
if not Assigned(FCompressor) then begin
raise EIdFTPMissingCompressor.Create(RSFTPMissingCompressor);
end;
if not FCompressor.IsReady then begin
raise EIdFTPCompressorNotReady.Create(RSFTPCompressorNotReady);
end;
end;
//for SSL FXP, we have to do it here because there is no command were a client
//submits data through a data port where the SSCN setting is ignored.
ClearSSCN;
DoStatus(ftpTransfer, [RSFTPStatusStartTransfer]);
// try
if FPassive then begin
SendPret(ACommand);
if FUsingExtDataPort then begin
SendEPassive(LIP, LPort);
end else begin
SendPassive(LIP, LPort);
end;
if AResume then begin
Self.SendCmd('REST ' + IntToStr(ASource.Position), [350]); {do not localize}
end;
IOHandler.WriteLn(ACommand);
if Socket <> nil then begin
FDataChannel := TIdTCPClient.Create(nil);
end else begin
FDataChannel := nil;
end;
LPasvCl := TIdTCPClient(FDataChannel);
try
InitDataChannel;
if (Self.Socket <> nil) and PassiveUseControlHost then begin
//Do not use an assignment from Self.Host
//because a DNS name may not resolve to the same
//IP address every time. This is the case where
//the workload is distributed around several servers.
//Besides, we already know the Peer's IP address so
//why waste time querying it.
LIP := Self.Socket.Binding.PeerIP;
end;
if LPasvCl <> nil then begin
LPasvCl.Host := LIP;
LPasvCl.Port := LPort;
DoOnDataChannelCreate;
LPasvCl.Connect;
end;
try
Self.GetResponse([110, 125, 150]);
try
if FDataChannel <> nil then begin
if FUsingSFTP and (FDataPortProtection = ftpdpsPrivate) then begin
TIdSSLIOHandlerSocketBase(FDataChannel.IOHandler).Passthrough := False;
end;
if FCurrentTransferMode = dmDeflate then begin
FCompressor.CompressFTPToIO(ASource, FDataChannel.IOHandler,
FZLibCompressionLevel, FZLibWindowBits, FZLibMemLevel, FZLibStratagy);
end else begin
if AFromBeginning then begin
{$IFNDEF MSWINDOWS}
WriteStreamFromBeginning;
{$ELSE}
FDataChannel.IOHandler.Write(ASource, 0, False); // from beginning
{$ENDIF}
end else begin
FDataChannel.IOHandler.Write(ASource, -1, False); // from current position
end;
end;
end;
except
on E: EIdSocketError do
begin
// If 10038 - abort was called. Server will return 225
if E.LastError <> 10038 then begin
raise;
end;
end;
end;
finally
if LPasvCl <> nil then begin
LPasvCl.Disconnect(False);
end;
end;
finally
FinalizeDataOperation;
end;
end else begin
if Socket <> nil then begin
FDataChannel := TIdSimpleServer.Create(nil);
end else begin
FDataChannel := nil;
end;
LPortSv := TIdSimpleServer(FDataChannel);
try
InitDataChannel;
if LPortSv <> nil then begin
LPortSv.BoundIP := Self.Socket.Binding.IP;
LPortSv.BoundPort := FDataPort;
LPortSv.BoundPortMin := FDataPortMin;
LPortSv.BoundPortMax := FDataPortMax;
DoOnDataChannelCreate;
LPortSv.BeginListen;
if FUsingExtDataPort then begin
SendEPort(LPortSv.Binding);
end else begin
SendPort(LPortSv.Binding);
end;
end else begin
// TODO:
{
if FUsingExtDataPort then begin
SendEPort(?);
end else begin
SendPort(?);
end;
}
end;
if AResume then begin
Self.SendCmd('REST ' + IntToStr(ASource.Position), [350]); {do not localize}
end;
Self.SendCmd(ACommand, [125, 150]);
if LPortSv <> nil then begin
LPortSv.Listen(ListenTimeout);
if FUsingSFTP and (FDataPortProtection = ftpdpsPrivate) then begin
TIdSSLIOHandlerSocketBase(FDataChannel.IOHandler).PassThrough := False;
end;
if FCurrentTransferMode = dmDeflate then begin
FCompressor.CompressFTPToIO(ASource, FDataChannel.IOHandler,
FZLibCompressionLevel, FZLibWindowBits, FZLibMemLevel, FZLibStratagy);
end else begin
if AFromBeginning then begin
{$IFNDEF MSWINDOWS}
WriteStreamFromBeginning;
{$ELSE}
FDataChannel.IOHandler.Write(ASource, 0, False); // from beginning
{$ENDIF}
end else begin
FDataChannel.IOHandler.Write(ASource, -1, False); // from current position
end;
end;
end;
finally
FinalizeDataOperation;
end;
end;
{ This will silently ignore the STOR request if the server has forcibly disconnected
(kicked or timed out) before the request starts
except
//Note that you are likely to get an exception you abort a transfer
//hopefully, this will make things work better.
on E: EIdConnClosedGracefully do begin
end;
end;}
{ commented out because we might need to revert back to this
if new code fails.
if (LResponse = 426) or (LResponse = 450) then
begin
// some servers respond with 226 on ABOR
GetResponse([226, 225]);
DoStatus(ftpAborted, [RSFTPStatusAbortTransfer]);
end;
}
end;
procedure TIdFTP.InternalGet(const ACommand: string; ADest: TStream; AResume: Boolean = false);
var
LIP: string;
LPort: TIdPort;
LPasvCl : TIdTCPClient;
LPortSv : TIdSimpleServer;
begin
FAbortFlag.Value := False;
if FCurrentTransferMode = dmDeflate then begin
if not Assigned(FCompressor) then begin
raise EIdFTPMissingCompressor.Create(RSFTPMissingCompressor);
end;
if not FCompressor.IsReady then begin
raise EIdFTPCompressorNotReady.Create(RSFTPCompressorNotReady);
end;
end;
DoStatus(ftpTransfer, [RSFTPStatusStartTransfer]);
if FPassive then begin
SendPret(ACommand);
//PASV or EPSV
if FUsingExtDataPort then begin
SendEPassive(LIP, LPort);
end else begin
SendPassive(LIP, LPort);
end;
if Socket <> nil then begin
FDataChannel := TIdTCPClient.Create(nil);
end else begin
FDataChannel := nil;
end;
LPasvCl := TIdTCPClient(FDataChannel);
try
InitDataChannel;
if (Self.Socket <> nil) and PassiveUseControlHost then begin
//Do not use an assignment from Self.Host
//because a DNS name may not resolve to the same
//IP address every time. This is the case where
//the workload is distributed around several servers.
//Besides, we already know the Peer's IP address so
//why waste time querying it.
LIP := Self.Socket.Binding.PeerIP;
end;
if LPasvCl <> nil then begin
LPasvCl.Host := LIP;
LPasvCl.Port := LPort;
DoOnDataChannelCreate;
LPasvCl.Connect;
end;
try
if AResume then begin
Self.SendCmd('REST ' + IntToStr(ADest.Position), [350]); {do not localize}
end;
// APR: Ericsson Switch FTP
//
// RLebeau: some servers send 450 when no files are
// present, so do not read the stream in that case
if Self.SendCmd(ACommand, [125, 150, 154, 450]) <> 450 then
begin
if LPasvCl <> nil then begin
if FUsingSFTP and (FDataPortProtection = ftpdpsPrivate) then begin
TIdSSLIOHandlerSocketBase(FDataChannel.IOHandler).Passthrough := False;
end;
if FCurrentTransferMode = dmDeflate then begin
FCompressor.DecompressFTPFromIO(LPasvCl.IOHandler, ADest, FZLibWindowBits);
end else begin
LPasvCl.IOHandler.ReadStream(ADest, -1, True);
end;
end;
end;
finally
if LPasvCl <> nil then begin
LPasvCl.Disconnect(False);
end;
end;
finally
FinalizeDataOperation;
end;
end else begin
// PORT or EPRT
if Socket <> nil then begin
FDataChannel := TIdSimpleServer.Create(nil);
end else begin
FDataChannel := nil;
end;
LPortSv := TIdSimpleServer(FDataChannel);
try
InitDataChannel;
if LPortSv <> nil then begin
LPortSv.BoundIP := Self.Socket.Binding.IP;
LPortSv.BoundPort := FDataPort;
LPortSv.BoundPortMin := FDataPortMin;
LPortSv.BoundPortMax := FDataPortMax;
DoOnDataChannelCreate;
LPortSv.BeginListen;
if FUsingExtDataPort then begin
SendEPort(LPortSv.Binding);
end else begin
SendPort(LPortSv.Binding);
end;
end else begin
// TODO:
{
if FUsingExtDataPort then begin
SendEPort(?);
end else begin
SendPort(?);
end;
}
end;
if AResume then begin
SendCmd('REST ' + IntToStr(ADest.Position), [350]); {do not localize}
end;
SendCmd(ACommand, [125, 150, 154]); //APR: Ericsson Switch FTP);
if LPortSv <> nil then begin
LPortSv.Listen(ListenTimeout);
if FUsingSFTP and (FDataPortProtection = ftpdpsPrivate) then begin
TIdSSLIOHandlerSocketBase(FDataChannel.IOHandler).PassThrough := False;
end;
if FCurrentTransferMode = dmDeflate then begin
FCompressor.DecompressFTPFromIO(LPortSv.IOHandler, ADest, FZLibWindowBits);
end else begin
FDataChannel.IOHandler.ReadStream(ADest, -1, True);
end;
end;
finally
FinalizeDataOperation;
end;
end;
// ToDo: Change that to properly handle response code (not just success or except)
// 226 = download successful, 225 = Abort successful}
//commented out in case we need to revert back to this.
{ LResponse := GetResponse([225, 226, 250, 426, 450]);
if (LResponse = 426) or (LResponse = 450) then begin
GetResponse([226, 225]);
DoStatus(ftpAborted, [RSFTPStatusAbortTransfer]);
end; }
end;
procedure TIdFTP.DoOnDataChannelCreate;
begin
// While the Control Channel is idle, Enable/disable TCP/IP keepalives.
// They're very small (40-byte) packages and will be sent every
// NATKeepAlive.IntervalMS after the connection has been idle for
// NATKeepAlive.IdleTimeMS. Prior to Windows 2000, the idle and
// timeout values are system wide and have to be set in the registry;
// the default is idle = 2 hours, interval = 1 second.
if (Socket <> nil) and NATKeepAlive.UseKeepAlive then begin
Socket.Binding.SetKeepAliveValues(True, NATKeepAlive.IdleTimeMS, NATKeepAlive.IntervalMS);
end;
if Assigned(FOnDataChannelCreate) then begin
OnDataChannelCreate(Self, FDataChannel);
end;
end;
procedure TIdFTP.DoOnDataChannelDestroy;
begin
if Assigned(FOnDataChannelDestroy) then begin
OnDataChannelDestroy(Self, FDataChannel);
end;
if (Socket <> nil) and NATKeepAlive.UseKeepAlive then begin
Socket.Binding.SetKeepAliveValues(False, 0, 0);
end;
end;
procedure TIdFTP.SetNATKeepAlive(AValue: TIdFTPKeepAlive);
begin
FNATKeepAlive.Assign(AValue);
end;
{ TIdFtpKeepAlive }
procedure TIdFtpKeepAlive.Assign(Source: TPersistent);
begin
if Source is TIdFTPKeepAlive then begin
with TIdFTPKeepAlive(Source) do begin
Self.FUseKeepAlive := UseKeepAlive;
Self.FIdleTimeMS := IdleTimeMS;
Self.FIntervalMS := IntervalMS;
end;
end else begin
inherited Assign(Source);
end;
end;
procedure TIdFTP.DisconnectNotifyPeer;
begin
if IOHandler.Connected then begin
IOHandler.WriteLn('QUIT'); {do not localize}
IOHandler.CheckForDataOnSource(100);
if not IOHandler.InputBufferIsEmpty then begin
GetInternalResponse;
end;
end;
end;
procedure TIdFTP.Quit;
begin
Disconnect;
end;
procedure TIdFTP.KillDataChannel;
begin
// Had kill the data channel ()
if Assigned(FDataChannel) then begin
FDataChannel.Disconnect(False); //FDataChannel.IOHandler.DisconnectSocket; {//BGO}
end;
end;
// IMPORTANT!!! THis is for later reference.
//
// Note that we do not send the Telnet IP and Sync as suggestedc by RFC 959.
// We do not do so because some servers will mistakenly assume that the sequences
// are part of the command and than give a syntax error.
// I noticed this with FTPSERVE IBM VM Level 510, Microsoft FTP Service (Version 5.0),
// GlobalSCAPE Secure FTP Server (v. 2.0), and Pure-FTPd [privsep] [TLS].
//
// Thus, I feel that sending sequences is just going to aggravate this situation.
// It is probably the reason why some FTP clients no longer are sending Telnet IP
// and Sync with the ABOR command.
procedure TIdFTP.Abort;
begin
// only send the abort command. The Data channel is supposed to disconnect
if Connected then begin
IOHandler.WriteLn('ABOR'); {do not localize}
end;
// Kill the data channel: usually, the server doesn't close it by itself
KillDataChannel;
if Assigned(FDataChannel) then begin
FAbortFlag.Value := True;
end else begin
GetResponse([]);
end;
end;
procedure TIdFTP.SendPort(AHandle: TIdSocketHandle);
begin
if FExternalIP <> '' then begin
SendPort(FExternalIP, AHandle.Port);
end else begin
SendPort(AHandle.IP, AHandle.Port);
end;
end;
procedure TIdFTP.SendPort(const AIP: String; const APort: TIdPort);
begin
SendDataSettings;
SendCmd('PORT ' + StringReplace(AIP, '.', ',', [rfReplaceAll]) {do not localize}
+ ',' + IntToStr(APort div 256) + ',' + IntToStr(APort mod 256), [200]); {do not localize}
end;
procedure TIdFTP.InitDataChannel;
var
LSSL : TIdSSLIOHandlerSocketBase;
begin
if FDataChannel = nil then begin
Exit;
end;
if FDataPortProtection = ftpdpsPrivate then begin
LSSL := TIdSSLIOHandlerSocketBase(IOHandler);
FDataChannel.IOHandler := LSSL.Clone;
//we have to delay the actual negotiation until we get the reply and
//and just before the readString
TIdSSLIOHandlerSocketBase(FDataChannel.IOHandler).Passthrough := True;
end else begin
FDataChannel.IOHandler := TIdIOHandler.MakeDefaultIOHandler(Self);
end;
if FDataChannel is TIdTCPClient then
begin
TIdTCPClient(FDataChannel).ReadTimeout := FTransferTimeout;
//Now SocksInfo are multi-thread safe
FDataChannel.IOHandler.ConnectTimeout := IOHandler.ConnectTimeout;
end;
if Assigned(FDataChannel.Socket) then
begin
if Assigned(Socket) then
begin
FDataChannel.Socket.TransparentProxy := Socket.TransparentProxy;
FDataChannel.Socket.IPVersion := Socket.IPVersion;
end else
begin
FDataChannel.Socket.IPVersion := IPVersion;
end;
end;
FDataChannel.IOHandler.ReadTimeout := FTransferTimeout;
FDataChannel.IOHandler.SendBufferSize := IOHandler.SendBufferSize;
FDataChannel.IOHandler.RecvBufferSize := IOHandler.RecvBufferSize;
FDataChannel.IOHandler.LargeStream := True;
// FDataChannel.IOHandler.DefStringEncoding := Indy8BitEncoding;
// FDataChannel.IOHandler.DefAnsiEncoding := IndyOSDefaultEncoding;
FDataChannel.WorkTarget := Self;
end;
procedure TIdFTP.Put(const ASource: TStream; const ADestFile: string;
const AAppend: Boolean = False; const AStartPos: TIdStreamSize = -1);
begin
if ADestFile = '' then begin
EIdFTPUploadFileNameCanNotBeEmpty.Toss(RSFTPFileNameCanNotBeEmpty);
end;
if AStartPos > -1 then begin
ASource.Position := AStartPos;
end;
DoBeforePut(ASource); //APR);
if AAppend then begin
InternalPut('APPE ' + ADestFile, ASource, False, False); {Do not localize}
end else begin
InternalPut('STOR ' + ADestFile, ASource, AStartPos = -1, AStartPos > -1); {Do not localize}
end;
DoAfterPut;
end;
procedure TIdFTP.Put(const ASourceFile: string; const ADestFile: string = '';
const AAppend: Boolean = False; const AStartPos: TIdStreamSize = -1);
var
LSourceStream: TStream;
LDestFileName : String;
begin
LDestFileName := ADestFile;
if LDestFileName = '' then begin
LDestFileName := ExtractFileName(ASourceFile);
end;
LSourceStream := TIdReadFileNonExclusiveStream.Create(ASourceFile);
try
Put(LSourceStream, LDestFileName, AAppend, AStartPos);
finally
FreeAndNil(LSourceStream);
end;
end;
procedure TIdFTP.StoreUnique(const ASource: TStream; const AStartPos: TIdStreamSize = -1);
begin
if AStartPos > -1 then begin
ASource.Position := AStartPos;
end;
DoBeforePut(ASource);
InternalPut('STOU', ASource, AStartPos = -1, False); {Do not localize}
DoAfterPut;
end;
procedure TIdFTP.StoreUnique(const ASourceFile: string; const AStartPos: TIdStreamSize = -1);
var
LSourceStream: TStream;
begin
LSourceStream := TIdReadFileExclusiveStream.Create(ASourceFile);
try
StoreUnique(LSourceStream, AStartPos);
finally
FreeAndNil(LSourceStream);
end;
end;
procedure TIdFTP.SendInternalPassive(const ACmd: String; var VIP: string;
var VPort: TIdPort);
function IsRoutableAddress(AIP: string): Boolean;
begin
Result := not TextStartsWith(AIP, '127') and // Loopback 127.0.0.0-127.255.255.255
not TextStartsWith(AIP, '10.') and // Private 10.0.0.0-10.255.255.255
not TextStartsWith(AIP, '169.254') and // Link-local 169.254.0.0-169.254.255.255
not TextStartsWith(AIP, '192.168') and // Private 192.168.0.0-192.168.255.255
not (TextStartsWith(AIP, '172') and (AIP[7] = '.') and // Private 172.16.0.0-172.31.255.255
(IndyStrToInt(Copy(AIP, 5, 2)) in [16..31]))
end;
var
i, bLeft, bRight: integer;
s: string;
begin
SendDataSettings;
SendCmd(ACmd, 227); {do not localize}
s := Trim(LastCmdResult.Text[0]);
// Case 1 (Normal)
// 227 Entering passive mode(100,1,1,1,23,45)
bLeft := IndyPos('(', s); {do not localize}
bRight := IndyPos(')', s); {do not localize}
// Microsoft FTP Service may include a leading ( but not a trailing ),
// so handle any combination of "(..)", "(..", "..)", and ".."
if bLeft = 0 then bLeft := RPos(#32, S);
if bRight = 0 then bRight := Length(S) + 1;
S := Copy(S, bLeft + 1, bRight - bLeft - 1);
VIP := ''; {do not localize}
for i := 1 to 4 do begin
VIP := VIP + '.' + Fetch(s, ','); {do not localize}
end;
IdDelete(VIP, 1, 1);
// Server sent an unroutable address (private/reserved/etc). Use the IP we
// connected to instead
if not IsRoutableAddress(VIP) and IsRoutableAddress(Socket.Binding.PeerIP) then begin
VIP := Socket.Binding.PeerIP;
end;
// Determine port
VPort := TIdPort(IndyStrToInt(Fetch(s, ',')) and $FF) shl 8; {do not localize}
//use trim as one server sends something like this:
//"227 Passive mode OK (195,92,195,164,4,99 )"
VPort := VPort or TIdPort(IndyStrToInt(Fetch(s, ',')) and $FF); {Do not translate}
end;
procedure TIdFTP.SendPassive(var VIP: string; var VPort: TIdPort);
begin
SendInternalPassive('PASV', VIP, VPort); {do not localize}
end;
procedure TIdFTP.SendCPassive(var VIP: string; var VPort: TIdPort);
begin
SendInternalPassive('CPSV', VIP, VPort); {do not localize}
end;
procedure TIdFTP.Noop;
begin
SendCmd('NOOP', 200); {do not localize}
end;
procedure TIdFTP.MakeDir(const ADirName: string);
begin
SendCmd('MKD ' + ADirName, 257); {do not localize}
end;
function TIdFTP.RetrieveCurrentDir: string;
begin
SendCmd('PWD', 257); {do not localize}
Result := LastCmdResult.Text[0];
IdDelete(Result, 1, IndyPos('"', Result)); // Remove first doublequote {do not localize}
Result := Copy(Result, 1, IndyPos('"', Result) - 1); // Remove anything from second doublequote {do not localize} // to end of line
// TODO: handle embedded quotation marks. RFC 959 allows them to be present
end;
procedure TIdFTP.RemoveDir(const ADirName: string);
begin
SendCmd('RMD ' + ADirName, 250); {do not localize}
end;
procedure TIdFTP.Delete(const AFilename: string);
begin
// Linksys NSLU2 NAS returns 200, Ultimodule IDAL returns 257
SendCmd('DELE ' + AFilename, [200, 250, 257]); {do not localize}
end;
(*
CHANGE WORKING DIRECTORY (CWD)
This command allows the user to work with a different
directory or dataset for file storage or retrieval without
altering his login or accounting information. Transfer
parameters are similarly unchanged. The argument is a
pathname specifying a directory or other system dependent
file group designator.
CWD
250
500, 501, 502, 421, 530, 550
*)
procedure TIdFTP.ChangeDir(const ADirName: string);
begin
SendCmd('CWD ' + ADirName, [200, 250, 257]); //APR: Ericsson Switch FTP {do not localize}
end;
(*
CHANGE TO PARENT DIRECTORY (CDUP)
This command is a special case of CWD, and is included to
simplify the implementation of programs for transferring
directory trees between operating systems having different
syntaxes for naming the parent directory. The reply codes
shall be identical to the reply codes of CWD. See
Appendix II for further details.
CDUP
200
500, 501, 502, 421, 530, 550
*)
procedure TIdFTP.ChangeDirUp;
begin
// RFC lists 200 as the proper response, but in another section says that it can return the
// same as CWD, which expects 250. That is it contradicts itself.
// MS in their infinite wisdom chnaged IIS 5 FTP to return 250.
SendCmd('CDUP', [200, 250]); {do not localize}
end;
procedure TIdFTP.Site(const ACommand: string);
begin
SendCmd('SITE ' + ACommand, 200); {do not localize}
end;
procedure TIdFTP.Rename(const ASourceFile, ADestFile: string);
begin
SendCmd('RNFR ' + ASourceFile, 350); {do not localize}
SendCmd('RNTO ' + ADestFile, 250); {do not localize}
end;
function TIdFTP.Size(const AFileName: String): Int64;
var
LTrans : TIdFTPTransferType;
SizeStr: String;
begin
Result := -1;
// RLebeau 03/13/2009: some servers refuse to accept the SIZE command in
// ASCII mode, returning a "550 SIZE not allowed in ASCII mode" reply.
// We put the connection in BINARY mode, even though no data connection is
// actually being used. We restore it if the original mode was not BINARY.
// It's a good idea to do this anyway because some other clients do this
// as well.
LTrans := TransferType;
if LTrans <> ftBinary then begin
Self.TransferType := ftBinary;
end;
try
if SendCmd('SIZE ' + AFileName) = 213 then begin {do not localize}
SizeStr := Trim(LastCmdResult.Text.Text);
IdDelete(SizeStr, 1, IndyPos(' ', SizeStr)); // delete the response {do not localize}
Result := IndyStrToInt64(SizeStr, -1);
end;
finally
if LTrans <> ftBinary then begin
TransferType := LTrans;
end;
end;
end;
//Added by SP
procedure TIdFTP.ReInitialize(ADelay: Cardinal = 10);
begin
IndySleep(ADelay); //Added
if SendCmd('REIN', [120, 220, 500]) <> 500 then begin {do not localize}
FLoginMsg.Clear;
FCanResume := False;
if Assigned(FDirectoryListing) then begin
FDirectoryListing.Clear;
end;
FUsername := ''; {do not localize}
FPassword := ''; {do not localize}
FPassive := Id_TIdFTP_Passive;
FCanResume := False;
FResumeTested := False;
FSystemDesc := '';
FTransferType := Id_TIdFTP_TransferType;
IOHandler.DefStringEncoding := Indy8BitEncoding;
{$IFDEF STRING_IS_ANSI}
IOHandler.DefAnsiEncoding := IndyOSDefaultEncoding;
{$ENDIF}
if FUsingSFTP and (FUseTLS <> utUseImplicitTLS) then begin
(IOHandler as TIdSSLIOHandlerSocketBase).PassThrough := True;
FUsingSFTP := False;
FUseCCC := False;
end;
end;
end;
procedure TIdFTP.Allocate(AAllocateBytes: Integer);
begin
SendCmd('ALLO ' + IntToStr(AAllocateBytes), [200]); {do not localize}
end;
procedure TIdFTP.Status(AStatusList: TStrings);
begin
if SendCmd('STAT', [211, 212, 213, 500]) <> 500 then begin {do not localize}
AStatusList.Text := LastCmdResult.Text.Text;
end;
end;
procedure TIdFTP.Help(AHelpContents: TStrings; ACommand: String = ''); {do not localize}
begin
if SendCmd(Trim('HELP ' + ACommand), [211, 214, 500]) <> 500 then begin {do not localize}
AHelpContents.Text := LastCmdResult.Text.Text;
end;
end;
function TIdFTP.CheckAccount: Boolean;
begin
if (FAccount = '') and Assigned(FOnNeedAccount) then begin
FOnNeedAccount(Self, FAccount);
end;
Result := FAccount <> '';
end;
procedure TIdFTP.StructureMount(APath: String);
begin
SendCmd('SMNT ' + APath, [202, 250, 500]); {do not localize}
end;
procedure TIdFTP.FileStructure(AStructure: TIdFTPDataStructure);
const
StructureTypes: array[TIdFTPDataStructure] of String = ('F', 'R', 'P'); {do not localize}
begin
SendCmd('STRU ' + StructureTypes[AStructure], [200, 500]); {do not localize}
{ TODO: Needs to be finished }
end;
procedure TIdFTP.TransferMode(ATransferMode: TIdFTPTransferMode);
var
s: String;
begin
if FCurrentTransferMode <> ATransferMode then begin
s := '';
case ATransferMode of
// dmBlock: begin
// s := 'B'; {do not localize}
// end;
// dmCompressed: begin
// s := 'C'; {do not localize}
// end;
dmStream: begin
s := 'S'; {do not localize}
end;
dmDeflate: begin
if not Assigned(FCompressor) then begin
raise EIdFTPMissingCompressor.Create(RSFTPMissingCompressor);
end;
if Self.IsCompressionSupported then begin
s := 'Z'; {Do not localize}
end;
end;
end;
if s = '' then begin
raise EIdFTPUnsupportedTransferMode.Create(RSFTPUnsupportedTransferMode);
end;
SendCmd('MODE ' + s, 200); {do not localize}
FCurrentTransferMode := ATransferMode;
end;
end;
destructor TIdFTP.Destroy;
begin
FreeAndNil(FClientInfo);
FreeAndNil(FListResult);
FreeAndNil(FLoginMsg);
FreeAndNil(FDirectoryListing);
FreeAndNil(FLangsSupported);
FreeAndNil(FProxySettings); //APR
FreeAndNil(FTZInfo);
FreeAndNil(FAbortFlag);
FreeAndNil(FNATKeepAlive);
inherited Destroy;
end;
function TIdFTP.Quote(const ACommand: String): SmallInt;
begin
Result := SendCmd(ACommand);
end;
procedure TIdFTP.IssueFEAT;
var
LClnt: String;
LBuf : String;
i : Integer;
begin
//Feat data
SendCmd('FEAT'); {do not localize}
FCapabilities.Clear;
//Ipswitch's FTP WS-FTP Server may issue 221 as success
if LastCmdResult.NumericCode in [211,221] then begin
FCapabilities.AddStrings(LastCmdResult.Text);
//we remove the first and last lines because we only want the list
if FCapabilities.Count > 0 then begin
FCapabilities.Delete(0);
end;
if FCapabilities.Count > 0 then begin
FCapabilities.Delete(FCapabilities.Count-1);
end;
end;
if FUsingExtDataPort then begin
FUsingExtDataPort := IsExtSupported('EPRT') and IsExtSupported('EPSV'); {do not localize}
end;
FCanUseMLS := IsExtSupported('MLSD') or IsExtSupported('MLST'); {do not localize}
ExtractFeatFacts('LANG', FLangsSupported); {do not localize}
//see if compression is supported.
//we parse this way because IxExtensionSupported can only work
//with one word.
FIsCompressionSupported := False;
for i := 0 to FCapabilities.Count-1 do begin
LBuf := Trim(FCapabilities[i]);
if LBuf = 'MODE Z' then begin {do not localize}
FIsCompressionSupported := True;
Break;
end;
end;
// send the CLNT command before sending the OPTS UTF8 command.
// some servers need this in order to work around a bug in
// Microsoft Internet Explorer's UTF-8 handling
if IsExtSupported('CLNT') then begin {do not localize}
LClnt := FClientInfo.ClntOutput;
if LClnt = '' then begin
LClnt := gsIdProductName + ' '+ gsIdVersion;
end;
SendCmd('CLNT '+ LClnt); {do not localize}
end;
if IsExtSupported('UTF8') then begin {do not localize}
// trying non-standard UTF-8 extension first, many servers use this...
// Cerberus and RaidenFTP return 220, but TitanFTP and Gene6 return 200 instead...
if not SendCmd('OPTS UTF8 ON') in [200, 220] then begin {do not localize}
// trying draft-ietf-ftpext-utf-8-option-00.txt next...
if SendCmd('OPTS UTF-8 NLST') <> 200 then begin {do not localize}
Exit;
end;
end;
IOHandler.DefStringEncoding := IndyUTF8Encoding;
end;
end;
procedure TIdFTP.Login;
var
i : Integer;
LResp : Word;
LCmd : String;
function FtpHost: String;
begin
if FPort = IDPORT_FTP then begin
Result := FHost;
end else begin
Result := FHost + Id_TIdFTP_HostPortDelimiter + IntToStr(FPort);
end;
end;
begin
//This has to be here because the Rein command clears encryption.
//RFC 4217
//TLS part
FUsingSFTP := False;
if UseTLS in ExplicitTLSVals then begin
if FAUTHCmd = tAuto then begin
{Note that we can not call SupportsTLS at all. That depends upon the FEAT response
and unfortunately, some servers such as WS_FTP Server 4.0.0 (78162662)
will not accept a FEAT command until you login. In other words, you have to do
this by trial and error.
}
//334 has to be accepted because of a broekn implementation
//see: http://www.ford-hutchinson.com/~fh-1-pfh/ftps-ext.html#bad
{Note that we have to try several commands because some servers use AUTH TLS while others use
AUTH SSL. GlobalScape's FTP Server only uses AUTH SSL while IpSwitch's uses AUTH TLS (the correct behavior).
We try two other commands for historical reasons.
}
for i := 0 to 3 do begin
LResp := SendCmd('AUTH ' + TLS_AUTH_NAMES[i]); {do not localize}
if (LResp = 234) or (LResp = 334) then begin
//okay. do the handshake
TLSHandshake;
FUsingSFTP := True;
//we are done with the negotiation, let's close this.
Break;
end;
//see if the error was not any type of syntax error code
//if it wasn't, we fail the command.
if (LResp div 500) <> 1 then begin
ProcessTLSNegCmdFailed;
Break;
end;
end;
end else begin
LResp := SendCmd('AUTH ' + TLS_AUTH_NAMES[Ord(FAUTHCmd)-1]); {do not localize}
if (LResp = 234) or (LResp = 334) then begin
//okay. do the handshake
TLSHandshake;
FUsingSFTP := True;
end else begin
ProcessTLSNegCmdFailed;
end;
end;
end;
if not FUsingSFTP then begin
ProcessTLSNotAvail;
end;
//login
case ProxySettings.ProxyType of
fpcmNone:
begin
LCmd := MakeXAUTCmd( Greeting.Text.Text , FUserName, GetLoginPassword);
if (LCmd <> '') and (not GetFIPSMode ) then begin
if SendCmd(LCmd, [230, 232, 331]) = 331 then begin {do not localize}
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end else begin
if SendCmd('USER ' + FUserName, [230, 232, 331]) = 331 then begin {do not localize}
SendCmd('PASS ' + GetLoginPassword, [230, 332]); {do not localize}
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
end;
fpcmUserSite:
begin
//This also supports WinProxy
if Length(ProxySettings.UserName) > 0 then begin
if SendCmd('USER ' + ProxySettings.UserName, [230, 331]) = 331 then begin {do not localize}
SendCmd('PASS ' + ProxySettings.Password, 230); {do not localize}
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
if SendCmd('USER ' + FUserName + '@' + FtpHost, [230, 232, 331]) = 331 then begin {do not localize}
SendCmd('PASS ' + GetLoginPassword, [230, 331]); {do not localize}
if IsAccountNeeded then
begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
fpcmSite:
begin
if Length(ProxySettings.UserName) > 0 then begin
if SendCmd('USER ' + ProxySettings.UserName, [230, 331]) = 331 then begin {do not localize}
SendCmd('PASS ' + ProxySettings.Password, 230); {do not localize}
end;
end;
SendCmd('SITE ' + FtpHost); // ? Server Reply? 220? {do not localize}
if SendCmd('USER ' + FUserName, [230, 232, 331]) = 331 then begin {do not localize}
SendCmd('PASS ' + GetLoginPassword, [230, 332]); {do not localize}
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
fpcmOpen:
begin
if Length(ProxySettings.UserName) > 0 then begin
if SendCmd('USER ' + ProxySettings.UserName, [230, 331]) = 331 then begin {do not localize}
SendCmd('PASS ' + GetLoginPassword, [230, 332]); {do not localize}
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
SendCmd('OPEN ' + FtpHost);//? Server Reply? 220? {do not localize}
if SendCmd('USER ' + FUserName, [230, 232, 331]) = 331 then begin {do not localize}
SendCmd('PASS ' + GetLoginPassword, [230, 332]); {do not localize}
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
fpcmUserPass: //USER user@firewalluser@hostname / PASS pass@firewallpass
begin
if SendCmd(IndyFormat('USER %s@%s@%s',
[FUserName, ProxySettings.UserName, FtpHost]), [230, 232, 331]) = 331 then begin {do not localize}
if Length(ProxySettings.Password) > 0 then begin
SendCmd('PASS ' + GetLoginPassword + '@' + ProxySettings.Password, [230, 332]); {do not localize}
end else begin
//// needs otp ////
SendCmd('PASS ' + GetLoginPassword, [230,332]); {do not localize}
end;
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
fpcmTransparent:
begin
//I think fpcmTransparent means to connect to the regular host and the firewalll
//intercepts the login information.
if Length(ProxySettings.UserName) > 0 then begin
if SendCmd('USER ' + ProxySettings.UserName, [230, 331]) = 331 then begin {do not localize}
SendCmd('PASS ' + ProxySettings.Password, [230,332]); {do not localize}
end;
end;
if SendCmd('USER ' + FUserName, [230, 232, 331]) = 331 then begin {do not localize}
SendCmd('PASS ' + GetLoginPassword, [230,332]); {do not localize}
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]);
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
fpcmUserHostFireWallID : //USER hostuserId@hostname firewallUsername
begin
if SendCmd(Trim('USER ' + Username + '@' + FtpHost + ' ' + ProxySettings.UserName), [230, 331]) = 331 then begin {do not localize}
if SendCmd('PASS ' + GetLoginPassword, [230,232,202,332]) = 332 then begin
SendCmd('ACCT ' + ProxySettings.Password, [230,232,332]);
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
end;
fpcmNovellBorder : //Novell Border PRoxy
begin
{Done like this:
USER ProxyUserName$ DestFTPUserName$DestFTPHostName
PASS UsereDirectoryPassword$ DestFTPPassword
Novell BorderManager 3.8 Proxy and Firewall Overview and Planning Guide
Copyright © 1997-1998, 2001, 2002-2003, 2004 Novell, Inc. All rights reserved.
===
From a WS-FTP Pro firescript at:
http://support.ipswitch.com/kb/WS-20050315-DM01.htm
send ("USER %FwUserId$%HostUserId$%HostAddress")
//send ("PASS %FwPassword$%HostPassword")
}
if SendCmd(Trim('USER ' + ProxySettings.UserName + '$' + Username + '$' + FtpHost), [230, 331]) = 331 then begin {do not localize}
if SendCmd('PASS ' + ProxySettings.UserName + '$' + GetLoginPassword, [230,232,202,332]) = 332 then begin
if IsAccountNeeded then begin
if CheckAccount then begin
SendCmd('ACCT ' + FAccount, [202, 230, 500]); {do not localize}
end else begin
RaiseExceptionForLastCmdResult;
end;
end;
end;
end;
end;
fpcmHttpProxyWithFtp :
begin
{GET ftp://XXX:YYY@indy.nevrona.com/ HTTP/1.0
Host: indy.nevrona.com
User-Agent: Mozilla/4.0 (compatible; Wincmd; Windows NT)
Proxy-Authorization: Basic B64EncodedUserPass==
Connection: close}
raise EIdSocksServerCommandError.Create(RSSocksServerCommandError);
end;//fpcmHttpProxyWithFtp
fpcmCustomProxy :
begin
DoCustomFTPProxy;
end;
end;//case
FLoginMsg.Assign(LastCmdResult);
DoOnBannerAfterLogin(FLoginMsg.FormattedReply);
//should be here because this can be issued more than once per connection.
if FAutoIssueFEAT then begin
IssueFEAT;
end;
SendTransferType(FTransferType);
end;
procedure TIdFTP.DoAfterLogin;
begin
if Assigned(FOnAfterClientLogin) then begin
OnAfterClientLogin(Self);
end;
end;
procedure TIdFTP.DoFTPList;
begin
if Assigned(FOnCreateFTPList) then begin
FOnCreateFTPList(Self, FDirectoryListing);
end;
end;
function TIdFTP.GetDirectoryListing: TIdFTPListItems;
begin
if FDirectoryListing = nil then begin
if Assigned(FOnDirParseStart) then begin
FOnDirParseStart(Self);
end;
ConstructDirListing;
ParseFTPList;
end;
Result := FDirectoryListing;
end;
procedure TIdFTP.SetProxySettings(const Value: TIdFtpProxySettings);
begin
FProxySettings.Assign(Value);
end;
{ TIdFtpProxySettings }
procedure TIdFtpProxySettings.Assign(Source: TPersistent);
begin
if Source is TIdFtpProxySettings then begin
with Source as TIdFtpProxySettings do begin
Self.FProxyType := ProxyType;
Self.FHost := Host;
Self.FUserName := UserName;
Self.FPassword := Password;
Self.FPort := Port;
end;
end else begin
inherited Assign(Source);
end;
end;
procedure TIdFTP.SendPBSZ;
begin
{NOte that PBSZ - protection buffer size must always be zero for FTP TLS}
if FUsingSFTP or (FUseTLS = utUseImplicitTLS) then begin
//protection buffer size
SendCmd('PBSZ 0'); {do not localize}
end;
end;
procedure TIdFTP.SendPROT;
begin
case FDataPortProtection of
ftpdpsClear : SendCmd('PROT C', 200); //'C' - Clear - neither Integrity nor Privacy {do not localize}
// NOT USED - 'S' - Safe - Integrity without Privacy
// NOT USED - 'E' - Confidential - Privacy without Integrity
// 'P' - Private - Integrity and Privacy
ftpdpsPrivate : SendCmd('PROT P', 200); {do not localize}
end;
end;
procedure TIdFTP.SendDataSettings;
begin
if FUsingSFTP then begin
if not FDataSettingsSent then begin
FDataSettingsSent := True;
SendPBSZ;
SendPROT;
if FUseCCC then begin
FUsingCCC := (SendCmd('CCC') div 100) = 2; {do not localize}
if FUsingCCC then begin
(IOHandler as TIdSSLIOHandlerSocketBase).PassThrough := True;
end;
end;
end;
end;
end;
procedure TIdFTP.SetIOHandler(AValue: TIdIOHandler);
begin
inherited SetIOHandler(AValue);
// UseExtensionDataPort must be true for IPv6 connections.
// PORT and PASV can not communicate IPv6 Addresses
if Socket <> nil then begin
if Socket.IPVersion = Id_IPv6 then begin
FUseExtensionDataPort := True;
end;
end;
end;
procedure TIdFTP.SetUseExtensionDataPort(const AValue: Boolean);
begin
if (not AValue) and (IPVersion = Id_IPv6) then begin
EIdFTPMustUseExtWithIPv6.Toss(RSFTPMustUseExtWithIPv6);
end;
if TryNATFastTrack then begin
EIdFTPMustUseExtWithNATFastTrack.Toss(RSFTPMustUseExtWithNATFastTrack);
end;
FUseExtensionDataPort := AValue;
end;
procedure TIdFTP.ParseEPSV(const AReply : String; var VIP : String; var VPort : TIdPort);
var
bLeft, bRight, LPort: Integer;
delim : Char;
s : String;
begin
s := Trim(AReply);
// "229 Entering Extended Passive Mode (|||59028|)"
bLeft := IndyPos('(', s); {do not localize}
bRight := IndyPos(')', s); {do not localize}
s := Copy(s, bLeft + 1, bRight - bLeft - 1);
delim := s[1]; // normally is | but the RFC say it may be different
Fetch(S, delim);
Fetch(S, delim);
VIP := Fetch(S, delim);
if VIP = '' then begin
VIP := Host;
end;
s := Trim(Fetch(S, delim));
LPort := IndyStrToInt(s, 0);
if (LPort < 1) or (LPort > 65535) then begin
raise EIdFTPServerSentInvalidPort.CreateFmt(RSFTPServerSentInvalidPort, [s]);
end;
VPort := TIdPort(LPort and $FFFF);
end;
procedure TIdFTP.SendEPassive(var VIP: string; var VPort: TIdPort);
begin
SendDataSettings;
//Note that for FTP Proxies, it is not desirable for the server to choose
//the EPSV data port IP connection type. We try to if we can.
if FProxySettings.ProxyType <> fpcmNone then begin
if SendCMD('EPSV ' + cIPVersions[IPVersion]) <> 229 then begin {do not localize}
//Raidon and maybe a few others may honor EPSV but not with the proto numbers
SendCMD('EPSV'); {do not localize}
end;
end else begin
SendCMD('EPSV'); {do not localize}
end;
if LastCmdResult.NumericCode <> 229 then begin
SendPassive(VIP, VPort);
FUsingExtDataPort := False;
Exit;
end;
try
ParseEPSV(LastCmdResult.Text[0], VIP, VPort);
except
SendCmd('ABOR'); {do not localize}
raise;
end;
end;
procedure TIdFTP.SendEPort(AHandle: TIdSocketHandle);
begin
SendDataSettings;
if FExternalIP <> '' then begin
SendEPort(FExternalIP, AHandle.Port, AHandle.IPVersion);
end else begin
SendEPort(AHandle.IP, AHandle.Port, AHandle.IPVersion);
end;
end;
procedure TIdFTP.SendEPort(const AIP: String; const APort: TIdPort; const AIPVersion: TIdIPVersion);
begin
if SendCmd('EPRT |' + cIPVersions[AIPVersion] + '|' + AIP + '|' + IntToStr(APort) + '|') <> 200 then begin {do not localize}
SendPort(AIP, APort);
FUsingExtDataPort := False;
end;
end;
procedure TIdFTP.SetPassive(const AValue: Boolean);
begin
if (not AValue) and TryNATFastTrack then begin
EIdFTPPassiveMustBeTrueWithNATFT.Toss(RSFTPFTPPassiveMustBeTrueWithNATFT);
end;
FPassive := AValue;
end;
procedure TIdFTP.SetTryNATFastTrack(const AValue: Boolean);
begin
FTryNATFastTrack := AValue;
if FTryNATFastTrack then begin
FPassive := True;
FUseExtensionDataPort := True;
end;
end;
procedure TIdFTP.DoTryNATFastTrack;
begin
if IsExtSupported('EPSV') then begin {do not localize}
if SendCmd('EPSV ALL') = 229 then begin {do not localize}
//Surge FTP treats EPSV ALL as if it were a standard EPSV
//We send ABOR in that case so it can close the data connection it created
SendCmd('ABOR'); {do not localize}
end;
FUsingNATFastTrack := True;
end;
end;
procedure TIdFTP.SetCmdOpt(const ACmd, AOptions: String);
begin
SendCmd('OPTS ' + ACmd + ' ' + AOptions, 200); {do not localize}
end;
procedure TIdFTP.ExtListDir(ADest: TStrings = nil; const ADirectory: string = '');
var
LDest: TMemoryStream;
begin
// RLebeau 6/4/2009: According to RFC 3659 Section 7.2:
//
// The data connection opened for a MLSD response shall be a connection
// as if the "TYPE L 8", "MODE S", and "STRU F" commands had been given,
// whatever FTP transfer type, mode and structure had actually been set,
// and without causing those settings to be altered for future commands.
// That is, this transfer type shall be set for the duration of the data
// connection established for this command only. While the content of
// the data sent can be viewed as a series of lines, implementations
// should note that there is no maximum line length defined.
// Implementations should be prepared to deal with arbitrarily long
// lines.
LDest := TMemoryStream.Create;
try
InternalGet(Trim('MLSD ' + ADirectory), LDest); {do not localize}
FreeAndNil(FDirectoryListing);
FDirFormat := '';
DoOnRetrievedDir;
LDest.Position := 0;
// RLebeau: using Indy8BitEncoding() here. TIdFTPListParseBase will
// decode UTF-8 sequences later on...
{$IFDEF HAS_TEncoding}
FListResult.LoadFromStream(LDest, Indy8BitEncoding);
{$ELSE}
FListResult.Text := ReadStringFromStream(LDest, -1, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF});
{$ENDIF}
with TIdFTPListResult(FListResult) do begin
FDetails := True;
FUsedMLS := True;
end;
FDirFormat := MLST;
finally
FreeAndNil(LDest);
end;
if Assigned(ADest) then begin //APR: User can use ListResult and DirectoryListing
ADest.Assign(FListResult);
end;
end;
procedure TIdFTP.ExtListItem(ADest: TStrings; AFList : TIdFTPListItems; const AItem: string);
var
i : Integer;
begin
ADest.Clear;
SendCmd(Trim('MLST ' + AItem), 250, Indy8BitEncoding); {do not localize}
for i := 0 to LastCmdResult.Text.Count -1 do begin
if IndyPos(';', LastCmdResult.Text[i]) > 0 then begin
ADest.Add(LastCmdResult.Text[i]);
end;
end;
if Assigned(AFList) then begin
IdFTPListParseBase.ParseListing(ADest, AFList, 'MLST'); {do not localize}
end;
end;
procedure TIdFTP.ExtListItem(ADest: TStrings; const AItem: string);
begin
ExtListItem(ADest, nil, AItem);
end;
procedure TIdFTP.ExtListItem(AFList: TIdFTPListItems; const AItem: String);
var
LBuf : TStrings;
begin
LBuf := TStringList.Create;
try
ExtListItem(LBuf, AFList, AItem);
finally
FreeAndNil(LBuf);
end;
end;
function TIdFTP.IsExtSupported(const ACmd: String): Boolean;
var
i : Integer;
LBuf : String;
begin
Result := False;
for i := 0 to FCapabilities.Count -1 do begin
LBuf := TrimLeft(FCapabilities[i]);
if TextIsSame(Fetch(LBuf), ACmd) then begin
Result := True;
Exit;
end;
end;
end;
function TIdFTP.FileDate(const AFileName: String; const AsGMT: Boolean): TDateTime;
var
LBuf : String;
begin
//Do not use the FEAT list because some servers
//may support it even if FEAT isn't supported
if SendCmd('MDTM ' + AFileName) = 213 then begin {do not localize}
LBuf := LastCmdResult.Text[0];
LBuf := Trim(LBuf);
if AsGMT then begin
Result := FTPMLSToGMTDateTime(LBuf);
end else begin
Result := FTPMLSToLocalDateTime(LBuf);
end;
end else begin
Result := 0;
end;
end;
procedure TIdFTP.SiteToSiteUpload(const AToSite : TIdFTP; const ASourceFile : String;
const ADestFile : String = '');
{
SiteToSiteUpload
From: PASV To: PORT - ATargetUsesPasv = False
From: RETR To: STOR
SiteToSiteDownload
From: PORT To: PASV - ATargetUsesPasv = True
From: RETR To: STOR
}
begin
if ValidateInternalIsTLSFXP(Self, AToSite, True) then begin
InternalEncryptedTLSFXP(Self, AToSite, ASourceFile, ADestFile, True);
end else begin
InternalUnencryptedFXP(Self, AToSite, ASourceFile, ADestFile, True);
end;
end;
procedure TIdFTP.SiteToSiteDownload(const AFromSite: TIdFTP; const ASourceFile : String;
const ADestFile : String = '');
{
The only use of this function is to get the passive mode on the other connection.
Because not all hosts allow it. This way you get a second chance.
If uploading from host A doesn't work, try downloading from host B
}
begin
if ValidateInternalIsTLSFXP(AFromSite, Self, True) then begin
InternalEncryptedTLSFXP(AFromSite, Self, ASourceFile, ADestFile, False);
end else begin
InternalUnencryptedFXP(AFromSite, Self, ASourceFile, ADestFile, False);
end;
end;
procedure TIdFTP.ExtractFeatFacts(const ACmd: String; AResults: TStrings);
var
i : Integer;
LBuf, LFact : String;
begin
AResults.Clear;
for i := 0 to FCapabilities.Count -1 do begin
LBuf := FCapabilities[i];
if TextIsSame(Fetch(LBuf), ACmd) then begin
LBuf := Trim(LBuf);
while LBuf <> '' do begin
LFact := Trim(Fetch(LBuf, ';'));
if LFact <> '' then begin
AResults.Add(LFact);
end;
end;
Exit;
end;
end;
end;
procedure TIdFTP.SetLang(const ALangTag: String);
begin
if IsExtSupported('LANG') then begin {do not localize}
SendCMD('LANG ' + ALangTag, 200); {do not localize}
end;
end;
function TIdFTP.CRC(const AFIleName : String; const AStartPoint : Int64 = 0;
const AEndPoint : Int64 = 0) : Int64;
var
LCmd : String;
LCRC : String;
begin
Result := -1;
if IsExtSupported('XCRC') then begin {do not localize}
LCmd := 'XCRC "' + AFileName + '"'; {do not localize}
if AStartPoint <> 0 then begin
LCmd := LCmd + ' ' + IntToStr(AStartPoint);
if AEndPoint <> 0 then begin
LCmd := LCmd + ' ' + IntToStr(AEndPoint);
end;
end;
if SendCMD(LCMD) = 250 then begin
LCRC := Trim(LastCmdResult.Text.Text);
IdDelete(LCRC, 1, IndyPos(' ', LCRC)); // delete the response
Result := IndyStrToInt64('$' + LCRC, -1);
end;
end;
end;
procedure TIdFTP.CombineFiles(const ATargetFile: String; AFileParts: TStrings);
var
i : Integer;
LCmd: String;
begin
if IsExtSupported('COMB') and (AFileParts.Count > 0) then begin {do not localize}
LCmd := 'COMB "' + ATargetFile + '"'; {do not localize}
for i := 0 to AFileParts.Count -1 do begin
LCmd := LCmd + ' ' + AFileParts[i];
end;
SendCmd(LCmd, 250);
end;
end;
procedure TIdFTP.ParseFTPList;
begin
DoOnDirParseStart;
try
// Parse directory listing
if FListResult.Count > 0 then begin
if TIdFTPListResult(FListResult).UsedMLS then begin
FDirFormat := MLST;
IdFTPListParseBase.ParseListing(FListResult, FDirectoryListing, MLST);
end else begin
CheckListParseCapa(FListResult, FDirectoryListing, FDirFormat,
FListParserClass, SystemDesc, TIdFTPListResult(FListResult).Details);
end;
end else begin
FDirFormat := '';
end;
finally
DoOnDirParseEnd;
end;
end;
function TIdFTP.GetSupportsTLS: Boolean;
begin
Result := (FindAuthCmd <> '');
end;
function TIdFTP.FindAuthCmd: String;
var
i : Integer;
LBuf : String;
LWord : String;
begin
Result := '';
for i := 0 to FCapabilities.Count -1 do begin
LBuf := TrimLeft(FCapabilities[i]);
if TextIsSame(Fetch(LBuf), 'AUTH') then begin {do not localize}
repeat
LWord := Trim(Fetch(LBuf, ';'));
if PosInStrArray(LWord, TLS_AUTH_NAMES, False) > -1 then begin
Result := 'AUTH ' + LWord; {do not localize}
Exit;
end;
until LBuf = '';
Break;
end;
end;
end;
procedure TIdFTP.DoCustomFTPProxy;
begin
if Assigned(FOnCustomFTPProxy) then begin
FOnCustomFTPProxy(Self);
end else begin
raise EIdFTPOnCustomFTPProxyRequired.Create(RSFTPOnCustomFTPProxyReq);
end;
end;
function TIdFTP.GetLoginPassword: String;
begin
Result := GetLoginPassword(LastCmdResult.Text.Text);
end;
function TIdFTP.GetLoginPassword(const APrompt: String): String;
begin
if TIdOTPCalculator.IsValidOTPString(APrompt) then begin
TIdOTPCalculator.GenerateSixWordKey(APrompt, FPassword, Result);
end else begin
Result := FPassword;
end;
end;
function TIdFTP.SetSSCNToOn : Boolean;
begin
Result := FUsingSFTP;
if not Result then begin
Exit;
end;
Result := (DataPortProtection = ftpdpsPrivate);
if not Result then begin
Exit;
end;
Result := not IsExtSupported(SCCN_FEAT);
if not Result then begin
Exit;
end;
if not FSSCNOn then begin
SendCmd(SSCN_ON, SSCN_OK_REPLY);
FSSCNOn := True;
end;
end;
procedure TIdFTP.ClearSSCN;
begin
if FSSCNOn then begin
SendCmd(SSCN_OFF, SSCN_OK_REPLY);
end;
end;
procedure TIdFTP.SetClientInfo(const AValue: TIdFTPClientIdentifier);
begin
FClientInfo.Assign(AValue);
end;
procedure TIdFTP.SetCompressor(AValue: TIdZLibCompressorBase);
begin
if FCompressor <> AValue then begin
if Assigned(FCompressor) then begin
FCompressor.RemoveFreeNotification(Self);
end;
FCompressor := AValue;
if Assigned(FCompressor) then begin
FCompressor.FreeNotification(Self);
end
else if Connected then begin
TransferMode(dmStream);
end;
end;
end;
procedure TIdFTP.GetInternalResponse(AEncoding: TIdTextEncoding = nil);
var
LLine: string;
LResponse: TStringList;
LReplyCode: string;
begin
CheckConnected;
LResponse := TStringList.Create;
try
// Some servers with bugs send blank lines before reply. Dont remember
// which ones, but I do remember we changed this for a reason
//
// RLebeau 9/14/06: this can happen in between lines of the reply as well
// RLebeau 3/9/09: according to RFC 959, when reading a multi-line reply,
// we are supposed to look at the first line's reply code and then keep
// reading until that specific reply code is encountered again, and
// everything in between is the text. So, do not just look for arbitrary
// 3-digit values on each line, but instead look for the specific reply
// code...
LLine := IOHandler.ReadLnWait(MaxInt, AEncoding);
LResponse.Add(LLine);
if CharEquals(LLine, 4, '-') then begin
LReplyCode := Copy(LLine, 1, 3);
repeat
LLine := IOHandler.ReadLnWait(MaxInt, AEncoding);
LResponse.Add(LLine);
until TIdReplyFTP(FLastCmdResult).IsEndReply(LReplyCode, LLine);
end;
//Note that FormattedReply uses an assign in it's property set method.
FLastCmdResult.FormattedReply := LResponse;
finally
FreeAndNil(LResponse);
end;
end;
function TIdFTP.CheckResponse(const AResponse: SmallInt;
const AAllowedResponses: array of SmallInt): SmallInt;
var
i: Integer;
begin
// any FTP command can return a 421 reply if the server is going to shut
// down the command connection. This way, we can close the connection
// immediately instead of waiting for a future action that would raise
// an EIdConnClosedGracefully exception instead...
if AResponse = 421 then
begin
// check if the caller explicitally wants to handle 421 replies...
if High(AAllowedResponses) > -1 then begin
for i := Low(AAllowedResponses) to High(AAllowedResponses) do begin
if AResponse = AAllowedResponses[i] then begin
Result := AResponse;
Exit;
end;
end;
end;
Disconnect(False);
if IOHandler <> nil then begin
IOHandler.InputBuffer.Clear;
end;
RaiseExceptionForLastCmdResult;
end;
Result := inherited CheckResponse(AResponse, AAllowedResponses);
end;
function TIdFTP.GetReplyClass: TIdReplyClass;
begin
Result := TIdReplyFTP;
end;
procedure TIdFTP.SetIPVersion(const AValue: TIdIPVersion);
begin
if AValue <> FIPVersion then begin
inherited SetIPVersion(AValue);
if IPVersion = Id_IPv6 then begin
UseExtensionDataPort := True;
end;
end;
end;
class function TIdFTP.InternalEncryptedTLSFXP(AFromSite, AToSite: TIdFTP;
const ASourceFile, ADestFile: String; const ATargetUsesPasv : Boolean): Boolean;
{
SiteToSiteUpload
From: PASV To: PORT - ATargetUsesPasv = False
From: RETR To: STOR
SiteToSiteDownload
From: PORT To: PASV - ATargetUsesPasv = True
From: RETR To: STOR
To do FXP transfers with TLS FTP, you have to have one computer do the
TLS handshake as a client (ssl_connect). Thus, one of the following conditions must be meet.
1) SSCN must be supported on one of the FTP servers
or
2) If IPv4 is used, the computer receiving a "PASV" command must support
CPSV. CPSV will NOT work with IPv6.
IMAO, when doing FXP transfers, you should use SSCN whenever possible as
SSCN will support IPv6 and SSCN may be in wider use than CPSV. CPSV should
only be used as a fallback if SSCN isn't supported by both servers and IPv4
is being used.
}
var
LIP : String;
LPort : TIdPort;
begin
Result := True;
if AFromSite.SetSSCNToOn then begin
AToSite.ClearSSCN;
end
else if AToSite.SetSSCNToOn then begin
AFromSite.ClearSSCN;
end
else if AToSite.IPVersion = Id_IPv4 then begin
if ATargetUsesPasv then begin
AToSite.SendCPassive(LIP, LPort);
AFromSite.SendPort(LIP, LPort);
end else begin
AFromSite.SendCPassive(LIP, LPort);
AToSite.SendPort(LIP, LPort);
end;
end;
FXPSendFile(AFromSite, AToSite, ASourceFile, ADestFile);
end;
class function TIdFTP.InternalUnencryptedFXP(AFromSite, AToSite: TIdFTP;
const ASourceFile, ADestFile: String; const ATargetUsesPasv : Boolean): Boolean;
{
SiteToSiteUpload
From: PASV To: PORT - ATargetUsesPasv = False
From: RETR To: STOR
SiteToSiteDownload
From: PORT To: PASV - ATargetUsesPasv = True
From: RETR To: STOR
}
begin
FXPSetTransferPorts(AFromSite, AToSite, ATargetUsesPasv);
FXPSendFile(AFromSite, AToSite, ASourceFile, ADestFile);
Result := True;
end;
class function TIdFTP.ValidateInternalIsTLSFXP(AFromSite, AToSite: TIdFTP;
const ATargetUsesPasv : Boolean): Boolean;
{
SiteToSiteUpload
From: PASV To: PORT - ATargetUsesPasv = False
From: RETR To: STOR
SiteToSiteDownload
From: PORT To: PASV - ATargetUsesPasv = True
From: RETR To: STOR
This will raise an exception if FXP can not be done. Result = True for encrypted
or False for unencrypted.
Note:
The following is required:
SiteToSiteUpload
Source must do P
}
begin
if ATargetUsesPasv then begin
if AToSite.UsingNATFastTrack then begin
EIdFTPSToSNATFastTrack.Toss(RSFTPNoSToSWithNATFastTrack);
end;
end else begin
if AFromSite.UsingNATFastTrack then begin
EIdFTPSToSNATFastTrack.Toss(RSFTPNoSToSWithNATFastTrack);
end;
end;
if AFromSite.IPVersion <> AToSite.IPVersion then begin
EIdFTPStoSIPProtoMustBeSame.Toss(RSFTPSToSProtosMustBeSame);
end;
if AFromSite.CurrentTransferMode <> AToSite.CurrentTransferMode then begin
EIdFTPSToSTransModesMustBeSame.Toss(RSFTPSToSTransferModesMusbtSame);
end;
if AFromSite.FUsingSFTP <> AToSite.FUsingSFTP then begin
EIdFTPSToSNoDataProtection.Toss(RSFTPSToSNoDataProtection);
end;
Result := AFromSite.FUsingSFTP and AToSite.FUsingSFTP;
if Result then begin
if not (AFromSite.IsExtSupported('SSCN') or AToSite.IsExtSupported('SSCN')) then begin {do not localize}
//Second chance fallback, is CPSV supported on the server where PASV would
// be sent
if AToSite.IPVersion = Id_IPv4 then begin
if ATargetUsesPasv then begin
if not AToSite.IsExtSupported('CPSV') then begin {do not localize}
EIdFTPSToSNATFastTrack.Toss(RSFTPSToSSSCNNotSupported);
end;
end else begin
if not AFromSite.IsExtSupported('CPSV') then begin {do not localize}
EIdFTPSToSNATFastTrack.Toss(RSFTPSToSSSCNNotSupported);
end;
end;
end;
end;
end;
end;
class procedure TIdFTP.FXPSendFile(AFromSite, AToSite: TIdFTP; const ASourceFile, ADestFile: String);
var
LDestFile : String;
begin
LDestFile := ADestFile;
if LDestFile = '' then begin
LDestFile := ASourceFile;
end;
AToSite.SendCmd('STOR ' + LDestFile, [110, 125, 150]); {do not localize}
try
AFromSite.SendCmd('RETR ' + ASourceFile, [110, 125, 150]); {do not localize}
except
AToSite.Abort;
raise;
end;
AToSite.GetInternalResponse;
AFromSite.GetInternalResponse;
AToSite.CheckResponse(AToSite.LastCmdResult.NumericCode, [225, 226, 250]);
AFromSite.CheckResponse(AFromSite.LastCmdResult.NumericCode, [225, 226, 250]);
end;
class procedure TIdFTP.FXPSetTransferPorts(AFromSite, AToSite: TIdFTP; const ATargetUsesPasv: Boolean);
var
LIP : String;
LPort : TIdPort;
{
{
SiteToSiteUpload
From: PASV To: PORT - ATargetUsesPasv = False
From: RETR To: STOR
SiteToSiteDownload
From: PORT To: PASV - ATargetUsesPasv = True
From: RETR To: STOR
}
begin
if ATargetUsesPasv then begin
if AToSite.UsingExtDataPort then begin
AToSite.SendEPassive(LIP, LPort);
end else begin
AToSite.SendPassive(LIP, LPort);
end;
if AFromSite.UsingExtDataPort then begin
AFromSite.SendEPort(LIP, LPort, AToSite.IPVersion);
end else begin
AFromSite.SendPort(LIP, LPort);
end;
end else begin
if AFromSite.UsingExtDataPort then begin
AFromSite.SendEPassive(LIP, LPort);
end else begin
AFromSite.SendPassive(LIP, LPort);
end;
if AToSite.UsingExtDataPort then begin
AToSite.SendEPort(LIP, LPort, AFromSite.IPVersion);
end else begin
AToSite.SendPort(LIP, LPort);
end;
end;
end;
{ TIdFTPClientIdentifier }
procedure TIdFTPClientIdentifier.Assign(Source: TPersistent);
begin
if Source is TIdFTPClientIdentifier then begin
with Source as TIdFTPClientIdentifier do begin
Self.ClientName := ClientName;
Self.ClientVersion := ClientVersion;
Self.PlatformDescription := PlatformDescription;
end;
end else begin
inherited Assign(Source);
end;
end;
//assume syntax such as this:
//214 Syntax: CLNT <sp> <client-name> <sp> <client-version> [<sp> <optional platform info>] (Set client name)
function TIdFTPClientIdentifier.GetClntOutput: String;
begin
if FClientName <> '' then begin
Result := FClientName;
if FClientVersion <> '' then begin
Result := Result + ' ' + FClientVersion;
if FPlatformDescription <> '' then begin
Result := Result + ' ' + FPlatformDescription;
end;
end;
end else begin
Result := '';
end;
end;
procedure TIdFTPClientIdentifier.SetClientName(const AValue: String);
begin
FClientName := Trim(AValue);
// Don't call Fetch; it prevents multi-word client names
end;
procedure TIdFTPClientIdentifier.SetClientVersion(const AValue: String);
begin
FClientVersion := Trim(AValue);
end;
procedure TIdFTPClientIdentifier.SetPlatformDescription(const AValue: String);
begin
FPlatformDescription := AValue;
end;
{Note about SetTime procedures:
The first syntax is one used by current Serv-U versions and servers that report "MDTM YYYYMMDDHHMMSS[+-TZ];filename " in their FEAT replies is:
1) MDTM [Time in GMT format] Filename
some Bullete Proof FTPD versions, Indy's FTP Server component, and servers reporting "MDTM YYYYMMDDHHMMSS[+-TZ] filename" in their FEAT replies uses an older Syntax which is:
2) MDTM yyyymmddhhmmss[+-minutes from Universal Time] Filename
and then there is the classic
3) MDTM [local timestamp] Filename
So for example, if I was a file dated Jan 3, 5:00:00 pm from my computer in the Eastern Standard Time (-5 hours from Universal Time), the 3 syntaxes
Indy would use are:
Syntax 1:
1) MDTM 0103220000 MyFile.exe †(notice the 22 hour)
Syntax 2:
2) MDTM 0103170000-300 MyFile.exe (notice the 17 hour and the -300 offset)
Syntax 3;
3) MDTM 0103170000 MyFile.exe (notice the 17 hour)
Note from:
http://www.ftpvoyager.com/releasenotes10x.asp
====
Added support for RFC change and the MDTM. MDTM requires sending the server
GMT (UTC) instead of a "fixed" date and time. FTP Voyager supports this with
Serv-U automatically by checking the Serv-U version number and by checking the
response to the FEAT command for MDTM. Servers returning "MDTM" or
"MDTM YYYYMMDDHHMMSS[+-TZ] filename" will use the old method. Servers
returning "MDTM YYYYMMDDHHMMSS" only will use the new method where the date a
and time is GMT (UTC).
===
}
procedure TIdFTP.SetModTime(const AFileName: String; const ALocalTime: TDateTime);
var
LCmd: String;
begin
//use MFMT instead of MDTM because that always takes the time as Universal
//time (the most accurate).
if IsExtSupported('MFMT') then begin {do not localize}
LCmd := 'MFMT ' + FTPLocalDateTimeToMLS(ALocalTime, False) + ' ' + AFileName; {do not localize}
end
//Syntax 1 - MDTM [Time in GMT format] Filename
else if (IndexOfFeatLine('MDTM YYYYMMDDHHMMSS[+-TZ];filename') > 0) or IsIIS then begin {do not localize}
//we use the new method
LCmd := 'MDTM ' + FTPLocalDateTimeToMLS(ALocalTime, False) + ' ' + AFileName; {do not localize}
end
//Syntax 2 - MDTM yyyymmddhhmmss[+-minutes from Universal Time] Filename
//use old method for old versions of Serv-U and BPFTP Server
else if (IndexOfFeatLine('MDTM YYYYMMDDHHMMSS[+-TZ] filename') > 0) or IsOldServU or IsBPFTP then begin {do not localize}
LCmd := 'MDTM '+ FTPDateTimeToMDTMD(ALocalTime, False, True) + ' ' + AFileName; {do not localize}
end
//syntax 3 - MDTM [local timestamp] Filename
else if FTZInfo.FGMTOffsetAvailable then begin
//send it relative to the server's time-zone
LCmd := 'MDTM '+ FTPDateTimeToMDTMD(ALocalTime - OffSetFromUTC + FTZInfo.FGMTOffset, False, False) + ' ' + AFileName; {do not localize}
end
else begin
LCmd := 'MDTM '+ FTPDateTimeToMDTMD(ALocalTime, False, False) + ' ' + AFileName; {do not localize}
end;
// When using MDTM, Titan FTP 5 returns 200 and vsFTPd returns 213
SendCmd(LCmd, [200, 213, 253]);
end;
{
Note from:
http://www.ftpvoyager.com/releasenotes10x.asp
====
Added support for RFC change and the MDTM. MDTM requires sending the server
GMT (UTC) instead of a "fixed" date and time. FTP Voyager supports this with
Serv-U automatically by checking the Serv-U version number and by checking the
response to the FEAT command for MDTM. Servers returning "MDTM" or
"MDTM YYYYMMDDHHMMSS[+-TZ] filename" will use the old method. Servers
returning "MDTM YYYYMMDDHHMMSS" only will use the new method where the date a
and time is GMT (UTC).
===
}
procedure TIdFTP.SetModTimeGMT(const AFileName : String; const AGMTTime: TDateTime);
var
LCmd: String;
begin
//use MFMT instead of MDTM because that always takes the time as Universal
//time (the most accurate).
if IsExtSupported('MFMT') then begin {do not localize}
LCmd := 'MFMT ' + FTPGMTDateTimeToMLS(AGMTTime) + ' ' + AFileName; {do not localize}
end
//Syntax 1 - MDTM [Time in GMT format] Filename
else if (IndexOfFeatLine('MDTM YYYYMMDDHHMMSS[+-TZ];filename') > 0) or IsIIS then begin {do not localize}
//we use the new method
LCmd := 'MDTM ' + FTPGMTDateTimeToMLS(AGMTTime, False) + ' ' + AFileName; {do not localize}
end
//Syntax 2 - MDTM yyyymmddhhmmss[+-minutes from Universal Time] Filename
//use old method for old versions of Serv-U and BPFTP Server
else if (IndexOfFeatLine('MDTM YYYYMMDDHHMMSS[+-TZ] filename') > 0) or IsOldServU or IsBPFTP then begin {do not localize}
LCmd := 'MDTM '+ FTPDateTimeToMDTMD(AGMTTime + OffSetFromUTC, False, True) + ' ' + AFileName; {do not localize}
end
//syntax 3 - MDTM [local timestamp] Filename
else if FTZInfo.FGMTOffsetAvailable then begin
//send it relative to the server's time-zone
LCmd := 'MDTM '+ FTPDateTimeToMDTMD(AGMTTime + FTZInfo.FGMTOffset, False, False) + ' ' + AFileName; {do not localize}
end
else begin
LCmd := 'MDTM '+ FTPDateTimeToMDTMD(AGMTTime + OffSetFromUTC, False, False) + ' ' + AFileName; {do not localize}
end;
// When using MDTM, Titan FTP 5 returns 200 and vsFTPd returns 213
SendCmd(LCmd, [200, 213, 253]);
end;
{Improvement from Tobias Giesen http://www.superflexible.com
His notation is below:
"here's a fix for TIdFTP.IndexOfFeatLine. It does not work the
way it is used in TIdFTP.SetModTime, because it only
compares the first word of the FeatLine." }
function TIdFTP.IndexOfFeatLine(const AFeatLine: String): Integer;
var
LBuf : String;
LNoSpaces: Boolean;
begin
LNoSpaces := IndyPos(' ', AFeatLine) = 0;
for Result := 0 to FCapabilities.Count -1 do begin
LBuf := TrimLeft(FCapabilities[Result]);
// RLebeau: why Fetch() if no spaces are present?
if LNoSpaces then begin
LBuf := Fetch(LBuf);
end;
if TextIsSame(AFeatLine, LBuf) then begin
Exit;
end;
end;
Result := -1;
end;
{ TIdFTPTZInfo }
procedure TIdFTPTZInfo.Assign(Source: TPersistent);
begin
if Source is TIdFTPTZInfo then begin
with Source as TIdFTPTZInfo do begin
Self.FGMTOffset := GMTOffset;
Self.FGMTOffsetAvailable := GMTOffsetAvailable;
end;
end else begin
inherited Assign(Source);
end;
end;
function TIdFTP.IsSiteZONESupported: Boolean;
var
LFacts : TStrings;
i : Integer;
begin
Result := False;
if IsServerMDTZAndListTForm then begin
Result := True;
Exit;
end;
LFacts := TStringList.Create;
try
ExtractFeatFacts('SITE', LFacts);
for i := 0 to LFacts.Count-1 do begin
if TextIsSame(LFacts[i], 'ZONE') then begin {do not localize}
Result := True;
Exit;
end;
end;
finally
FreeAndNil(LFacts);
end;
end;
procedure TIdFTP.SetTZInfo(const Value: TIdFTPTZInfo);
begin
FTZInfo.Assign(Value);
end;
function TIdFTP.IsOldServU: Boolean;
begin
Result := TextStartsWith(FServerDesc, 'Serv-U '); {do not localize}
end;
function TIdFTP.IsBPFTP : Boolean;
begin
Result := TextStartsWith(FServerDesc, 'BPFTP Server '); {do not localize}
end;
function TIdFTP.IsTitan : Boolean;
begin
Result := TextStartsWith(FServerDesc, 'TitanFTP server ') or {do not localize}
TextStartsWith(FServerDesc, 'Titan FTP Server '); {do not localize}
end;
function TIdFTP.IsWSFTP : Boolean;
begin
Result := IndyPos('WS_FTP Server', FServerDesc) > 0; {do not localize}
end;
function TIdFTP.IsIIS: Boolean;
begin
Result := TextStartsWith(FServerDesc, 'Microsoft FTP Service'); {do not localize}
end;
function TIdFTP.IsServerMDTZAndListTForm: Boolean;
begin
Result := IsOldServU or IsBPFTP or IsTitan;
end;
procedure TIdFTP.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FCompressor) then begin
SetCompressor(nil);
end;
end;
procedure TIdFTP.SendPret(const ACommand: String);
begin
if IsExtSupported('PRET') then begin {do not localize}
//note that we don't check for success or failure here
//as some servers might fail and then succede with the transfer.
//Pret might not work for some commands.
SendCmd('PRET ' + ACommand); {do not localize}
end;
end;
procedure TIdFTP.List;
begin
List(nil);
end;
procedure TIdFTP.List(const ASpecifier: string; ADetails: Boolean);
begin
List(nil, ASpecifier, ADetails);
end;
procedure TIdFTP.DoOnBannerAfterLogin(AText: TStrings);
begin
if Assigned(OnBannerAfterLogin) then begin
OnBannerAfterLogin(Self, AText.Text);
end;
end;
procedure TIdFTP.DoOnBannerBeforeLogin(AText: TStrings);
begin
if Assigned(OnBannerBeforeLogin) then begin
OnBannerBeforeLogin(Self, AText.Text);
end;
end;
procedure TIdFTP.DoOnBannerWarning(AText: TStrings);
begin
if Assigned(OnBannerWarning) then begin
OnBannerWarning(Self, AText.Text);
end;
end;
procedure TIdFTP.SetDataPortProtection(AValue: TIdFTPDataPortSecurity);
begin
if IsLoading then begin
FDataPortProtection := AValue;
Exit;
end;
if FDataPortProtection <> AValue then begin
if FUseTLS = utNoTLSSupport then begin
EIdFTPNoDataPortProtectionWOEncryption.Toss(RSFTPNoDataPortProtectionWOEncryption);
end;
if FUsingCCC then begin
EIdFTPNoDataPortProtectionAfterCCC.Toss(RSFTPNoDataPortProtectionAfterCCC);
end;
FDataPortProtection := AValue;
end;
end;
procedure TIdFTP.SetAUTHCmd(const AValue : TAuthCmd);
begin
if IsLoading then begin
FAUTHCmd := AValue;
Exit;
end;
if FAUTHCmd <> AValue then begin
if FUseTLS = utNoTLSSupport then begin
EIdFTPNoAUTHWOSSL.Toss(RSFTPNoAUTHWOSSL);
end;
if FUsingSFTP then begin
EIdFTPCanNotSetAUTHCon.Toss(RSFTPNoAUTHCon);
end;
FAUTHCmd := AValue;
end;
end;
procedure TIdFTP.SetDefStringEncoding(AValue: TIdTextEncoding);
begin
FDefStringEncoding := AValue;
if IOHandler <> nil then begin
IOHandler.DefStringEncoding := FDefStringEncoding;
end;
end;
procedure TIdFTP.SetUseTLS(AValue: TIdUseTLS);
begin
inherited SetUseTLS(AValue);
if IsLoading then begin
Exit;
end;
if AValue = utNoTLSSupport then begin
FDataPortProtection := Id_TIdFTP_DataPortProtection;
FUseCCC := DEF_Id_FTP_UseCCC;
FAUTHCmd := DEF_Id_FTP_AUTH_CMD;
end;
end;
procedure TIdFTP.SetUseCCC(const AValue: Boolean);
begin
if (not IsLoading) and (FUseTLS = utNoTLSSupport) then begin
EIdFTPNoCCCWOEncryption.Toss(RSFTPNoCCCWOEncryption);
end;
FUseCCC := AValue;
end;
procedure TIdFTP.DoOnRetrievedDir;
begin
if Assigned(OnRetrievedDir) then begin
OnRetrievedDir(Self);
end;
end;
procedure TIdFTP.DoOnDirParseEnd;
begin
if Assigned(FOnDirParseEnd) then begin
FOnDirParseEnd(Self);
end;
end;
procedure TIdFTP.DoOnDirParseStart;
begin
if Assigned(FOnDirParseStart) then begin
FOnDirParseStart(Self);
end;
end;
//we do this to match some WS-FTP Pro firescripts I saw
function TIdFTP.IsAccountNeeded: Boolean;
begin
Result := LastCmdResult.NumericCode = 332;
if not Result then begin
if IndyPos('ACCOUNT', LastCmdResult.Text.Text) > 0 then begin {do not localize}
Result := FAccount <> '';
end;
end;
end;
//we can use one of three commands for verifying a file or stream
function TIdFTP.GetSupportsVerification: Boolean;
begin
Result := Connected;
if Result then begin
Result := TIdHashSHA512.IsAvailable and IsExtSupported('XSHA512');
if not Result then begin
Result := TIdHashSHA256.IsAvailable and IsExtSupported('XSHA256');
end;
if not Result then begin
Result := IsExtSupported('XSHA1') or
(IsExtSupported('XMD5') and (not GetFIPSMode)) or
IsExtSupported('XCRC');
end;
end;
end;
function TIdFTP.VerifyFile(const ALocalFile, ARemoteFile: String; const AStartPoint, AByteCount: TIdStreamSize): Boolean;
var
LLocalStream: TStream;
LRemoteFileName : String;
begin
LRemoteFileName := ARemoteFile;
if LRemoteFileName = '' then begin
LRemoteFileName := ExtractFileName(ALocalFile);
end;
LLocalStream := TIdReadFileExclusiveStream.Create(ALocalFile);
try
Result := VerifyFile(LLocalStream, LRemoteFileName, AStartPoint, AByteCount);
finally
FreeAndNil(LLocalStream);
end;
end;
{
This procedure can use three possible commands to verify file integriety and the
syntax does very amoung these. The commands are:
XSHA1 - get SHA1 checksum for a file or file part
XMD5 - get MD5 checksum for a file or file part
XCRC - get CRC32 checksum
The command preference is from first to last (going from longest length to shortest).
}
function TIdFTP.VerifyFile(ALocalFile: TStream; const ARemoteFile: String;
const AStartPoint, AByteCount: TIdStreamSize): Boolean;
var
LRemoteCRC : String;
LLocalCRC : String;
LCmd : String;
LRemoteFile: String;
LStartPoint : TIdStreamSize;
LByteCount : TIdStreamSize; //used instead of AByteCount so we don't exceed the file size
LHashClass: TIdHashClass;
begin
LLocalCRC := '';
LRemoteCRC := '';
if AStartPoint > -1 then begin
ALocalFile.Position := AStartPoint;
end;
LStartPoint := ALocalFile.Position;
LByteCount := ALocalFile.Size - LStartPoint;
if (LByteCount > AByteCount) and (AByteCount > 0) then begin
LByteCount := AByteCount;
end;
//just in case the server doesn't support file names in quotes.
if IndyPos(' ', ARemoteFile) > 0 then begin
LRemoteFile := '"' + ARemoteFile + '"';
end else begin
LRemoteFile := ARemoteFile;
end;
if TIdHashSHA512.IsAvailable and IsExtSupported('XSHA512') then begin
//XSHA256 <sp> pathname [<sp> startposition <sp> endposition]
LCmd := 'XSHA512 ' + LRemoteFile;
if AByteCount > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint) + ' ' + IntToStr(LByteCount);
end
else if AStartPoint > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint);
end;
LHashClass := TIdHashSHA512;
end
else if TIdHashSHA256.IsAvailable and IsExtSupported('XSHA256') then begin
//XSHA256 <sp> pathname [<sp> startposition <sp> endposition]
LCmd := 'XSHA256 ' + LRemoteFile;
if AByteCount > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint) + ' ' + IntToStr(LByteCount);
end
else if AStartPoint > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint);
end;
LHashClass := TIdHashSHA256;
end
else if IsExtSupported('XSHA1') then begin
//XMD5 "filename" startpos endpos
//I think there's two syntaxes to this:
//
//Raiden Syntax if FEAT line contains " XMD5 filename;start;end"
//
//or what's used by some other servers if "FEAT line contains XMD5"
//
//XCRC "filename" [startpos] [number of bytes to calc]
if IndexOfFeatLine('XSHA1 filename;start;end') > -1 then begin
LCmd := 'XSHA1 ' + LRemoteFile + ' ' + IntToStr(LStartPoint) + ' ' + IntToStr(LStartPoint + LByteCount-1);
end else
begin
//BlackMoon FTP Server uses this one.
LCmd := 'XSHA1 ' + LRemoteFile;
if AByteCount > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint) + ' ' + IntToStr(LByteCount);
end
else if AStartPoint > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint);
end;
end;
LHashClass := TIdHashSHA1;
end
else if IsExtSupported('XMD5') and (not GetFIPSMode) then begin
//XMD5 "filename" startpos endpos
//I think there's two syntaxes to this:
//
//Raiden Syntax if FEAT line contains " XMD5 filename;start;end"
//
//or what's used by some other servers if "FEAT line contains XMD5"
//
//XCRC "filename" [startpos] [number of bytes to calc]
if IndexOfFeatLine('XMD5 filename;start;end') > -1 then begin
LCmd := 'XMD5 ' + LRemoteFile + ' ' + IntToStr(LStartPoint) + ' ' + IntToStr(LStartPoint + LByteCount-1);
end else
begin
//BlackMoon FTP Server uses this one.
LCmd := 'XMD5 ' + LRemoteFile;
if AByteCount > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint) + ' ' + IntToStr(LByteCount);
end
else if AStartPoint > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint);
end;
end;
LHashClass := TIdHashMessageDigest5;
end else
begin
LCmd := 'XCRC ' + LRemoteFile;
if AByteCount > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint) + ' ' + IntToStr(LByteCount);
end
else if AStartPoint > 0 then begin
LCmd := LCmd + ' ' + IntToStr(LStartPoint);
end;
LHashClass := TIdHashCRC32;
end;
with LHashClass.Create do
try
LLocalCRC := HashStreamAsHex(ALocalFile, LStartPoint, LByteCount);
finally
Free;
end;
if SendCmd(LCmd) = 250 then begin
LRemoteCRC := Trim(LastCmdResult.Text.Text);
IdDelete(LRemoteCRC, 1, IndyPos(' ', LRemoteCRC)); // delete the response
Result := TextIsSame(LLocalCRC, LRemoteCRC);
end else begin
Result := False;
end;
end;
end.
|
unit LogUtils;
interface
uses
Winapi.Windows, System.SysUtils;
procedure Log(const Msg: string);
implementation
var
LastLog: Cardinal = 0;
Loging : Boolean = False;
procedure Log(const Msg: string);
var
n: string;
h: TextFile;
t, d: Cardinal;
begin
t := GetTickCount;
if LastLog <> 0 then
d := t - LastLog
else
d := 0;
LastLog := t;
n := ChangeFileExt(ParamStr(0), '.log');
AssignFile(h, n);
if FileExists(n) then
Append(h)
else
Rewrite(h);
try
WriteLn(h, DateTimeToStr(Now) + ' (' + IntToStr(d) + 'ms): ' + Msg);
finally
CloseFile(h);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.