text stringlengths 14 6.51M |
|---|
unit cmdlinelclutils;
interface
uses Controls, SysUtils, StdCtrls, Classes, cmdlinecfg;
var
ADirsDialogs : function (var path: string): Boolean = nil;
AFilesDialogs : function (var path: string): Boolean = nil;
procedure CreateComboBoxWithLabel(opt: TCmdLineCfgOption; AOwner: TWinControl; var combo: TComboBox; var lbl: TLabel);
procedure CreateComboBox(opt: TCmdLineCfgOption; AOwner: TWinControl; var combo: TComboBox);
procedure CreateCheckBox(opt: TCmdLineCfgOption; AOwner: TWinControl; SetCaptionToDisplay: Boolean; var chk: TCheckBox);
procedure AnchorControls(left, right: TControl; Spacing: Integer = 10);
procedure ControlSpanToRight(ctrl: TControl; XOffset: Integer = 10);
function SerializeComboBox(opt: TCmdLineCfgOption; combo: TComboBox): string;
function SerializeCheckBox(opt: TCmdLineCfgOption; chk: TCheckBox): string;
function SerializeEdit(opt: TCmdLineCfgOption; edt: TEdit): string;
procedure SetValueComboBox(opt: TCmdLineCfgOption; const vl: string; combo: TComboBox);
procedure SetValueCheckBox(opt: TCmdLineCfgOption; const vl: string; chk: TCheckBox);
procedure SetValueEdit(opt: TCmdLineCfgOption; const vl: string; edt: TEdit);
procedure SetMultiValueEdit(opt: TCmdLineCfgOption; const vl: string; const Delim: string; edt: TEdit);
procedure ResetValue(ctrl: TControl);
function SerializeAControl(opt: TCmdLineCfgOption; ctrl: TControl; var v: string): Boolean;
type
TEditPathsOpt = (epoSingleFileOnly, epoSingleDirOnly, epoFilesOnly, epoDirsOnly);
function ExecuteEditPathsDialogs(var path: string; DialogOption: TEditPathsOpt ): Boolean;
procedure CreatePathsEdit(opt: TCmdLineCfgOption; AOwner: TWinControl;
var lbl: TLabel; var edit: TEdit; var lookupbtn: TButton);
procedure CreateEdit(opt: TCmdLineCfgOption; AOwner: TWinControl; var lbl: TLabel; var edit: TEdit);
function OptKeyLabel(opt: TCmdLineCfgOption): string;
implementation
function OptKeyLabel(opt: TCmdLineCfgOption): string;
begin
if not Assigned(opt) then Result:=''
else Result:='('+StringReplace(opt.key, '%value%','', [rfIgnoreCase, rfReplaceAll])+')';
end;
procedure AnchorControls(left, right: TControl; Spacing: Integer);
begin
right.AnchorSideLeft.Control:=left;
right.AnchorSideLeft.Side:=asrRight;
right.BorderSpacing.Left:=Spacing;
end;
function SerializeEdit(opt: TCmdLineCfgOption; edt: TEdit): string;
begin
Result:=edt.Text;
end;
procedure SetValueComboBox(opt: TCmdLineCfgOption; const vl: string; combo: TComboBox);
var
j : Integer;
begin
if vl='' then begin
combo.ItemIndex:=-1;
Exit;
end;
for j:=0 to opt.ValCount-1 do begin
if (opt.Values[j].CmdLineValue =vl) then begin
if j<=combo.Items.Count then begin
combo.ItemIndex:=j;
end;
Exit;
end;
end;
end;
procedure SetValueCheckBox(opt: TCmdLineCfgOption; const vl: string; chk: TCheckBox);
begin
chk.Checked:=vl<>'';
end;
procedure SetValueEdit(opt: TCmdLineCfgOption; const vl: string; edt: TEdit);
begin
edt.Text:=vl;
end;
procedure SetMultiValueEdit(opt: TCmdLineCfgOption; const vl: string;
const Delim: string; edt: TEdit);
begin
if vl<>'' then begin
if edt.Text<>'' then edt.Text:=edt.Text+Delim+vl
else edt.Text:=vl;
end;
end;
procedure ControlSpanToRight(ctrl: TControl; XOffset: Integer = 10);
begin
if not Assigned(ctrl) or not Assigned(ctrl.Parent) then Exit;
ctrl.Anchors:=ctrl.Anchors-[akRight];
ctrl.Width:=ctrl.Parent.ClientWidth-ctrl.Left-XOffset;
ctrl.Anchors:=ctrl.Anchors+[akRight];
end;
function ExecuteEditPathsDialogs(var path: string; DialogOption: TEditPathsOpt
): Boolean;
begin
case DialogOption of
epoSingleFileOnly: begin
end;
epoSingleDirOnly: begin
end;
epoDirsOnly: if not Assigned(ADirsDialogs) then Result:=false
else Result:=ADirsDialogs(path);
epoFilesOnly: if not Assigned(AFilesDialogs) then Result:=false;
else Result:=AFilesDialogs(path);
end;
end;
procedure CreatePathsEdit(opt: TCmdLineCfgOption; AOwner: TWinControl;
var lbl: TLabel; var edit: TEdit; var lookupbtn: TButton);
begin
lbl:=TLabel.Create(AOwner);
lbl.Caption:=opt.Display+' '+OptKeyLabel(opt);
edit:=TEdit.Create(AOwner);
lookupbtn:=TButton.Create(AOwner);
lookupbtn.Caption:='...';
lookupbtn.AutoSize:=true;
AnchorControls(lbl, edit);
AnchorControls(edit, lookupbtn);
end;
procedure CreateEdit(opt: TCmdLineCfgOption; AOwner: TWinControl; var lbl: TLabel; var edit: TEdit);
begin
lbl:=TLabel.Create(AOwner);
lbl.Caption:=opt.Display+' '+OptKeyLabel(opt);
edit:=TEdit.Create(AOwner);
edit.Parent:=AOwner;
lbl.Parent:=AOwner;
end;
procedure CreateComboBoxWithLabel(opt: TCmdLineCfgOption; AOwner: TWinControl;
var combo: TComboBox; var lbl: TLabel);
begin
lbl:=TLabel.Create(AOwner);
lbl.Caption:=opt.Display + ' '+OptKeyLabel(opt);
lbl.Parent:=AOwner;
CreateComboBox(opt, AOwner, combo);
end;
procedure CreateComboBox(opt: TCmdLineCfgOption; AOwner: TWinControl; var combo: TComboBox);
var
dd : TComboBox;
j : Integer;
nm : string;
begin
dd:=TComboBox.Create(AOwner);
for j:=0 to opt.ValCount-1 do begin
nm:=opt.Values[j].DisplayName;
if nm='' then nm:=opt.Values[j].CmdLineValue;
dd.Items.Add(nm);
end;
dd.Parent:=AOwner;
combo:=dd;
end;
function SerializeComboBox(opt: TCmdLineCfgOption; combo: TComboBox): string;
var
vl : string;
j : Integer;
begin
vl:=combo.Text;
Result:='';
if vl='' then Exit;
for j:=0 to opt.ValCount-1 do
if (opt.Values[j].DisplayName='') then begin
if (opt.Values[j].CmdLineValue =vl) then begin
Result:=vl;
Exit;
end;
end else if (opt.Values[j].DisplayName=vl) then begin
Result:=opt.Values[j].CmdLineValue;
Exit;
end;
Result:=vl;
end;
procedure CreateCheckBox(opt: TCmdLineCfgOption; AOwner: TWinControl;
SetCaptionToDisplay: Boolean; var chk: TCheckBox);
begin
chk := TCheckBox.Create(AOwner);
if SetCaptionToDisplay then chk.Caption:=opt.Display+' '+ OptKeyLabel(opt);
chk.Parent:=AOwner;
end;
function SerializeCheckBox(opt: TCmdLineCfgOption; chk: TCheckBox): string;
begin
if chk.Checked then Result:='1' else Result:='';
end;
procedure ResetValue(ctrl: TControl);
begin
if ctrl is TEdit then TEdit(ctrl).Text:=''
else if ctrl is TCheckBox then TCheckBox(ctrl).Checked:=false
else if ctrl is TComboBox then TComboBox(ctrl).ItemIndex:=-1;
end;
function SerializeAControl(opt: TCmdLineCfgOption; ctrl: TControl; var v: string): Boolean;
begin
v:='';
Result:=true;
if ctrl is TComboBox then v:=SerializeComboBox(opt, TComboBox(ctrl))
else if ctrl is TCheckBox then v:=SerializeCheckBox(opt, TCheckBox(ctrl))
else if ctrl is TEdit then v:=SerializeEdit(opt, TEdit(ctrl))
else Result:=false;
end;
end.
|
UNIT bintree;
INTERFACE
USES deftypes;
PROCEDURE MkTreeNode(w : String; VAR t : Tree);
PROCEDURE InsertNode(n : Tree; VAR t : Tree);
FUNCTION TreeHeight(VAR rt : Tree) : Integer;
PROCEDURE PrintTree(indent : String; l : Integer; t : Tree);
IMPLEMENTATION
PROCEDURE MkTreeNode(w : String; VAR t : Tree);
VAR pp : Tree;
BEGIN
New(pp);
WITH pp^ DO
BEGIN
desc := w;
count := 1;
left := NIL;
right := NIL
END;
t := pp
END;
(* insert new node n to the binary search tree specified by t. *)
PROCEDURE InsertNode(n : Tree; VAR t : Tree);
VAR tw : String;
BEGIN
IF t <> NIL THEN
BEGIN
tw := t^.desc;
IF tw = n^.desc THEN
BEGIN
Inc(t^.count);
Dispose(n)
END
ELSE
IF tw > n^.desc THEN
InsertNode(n, t^.left)
ELSE
InsertNode(n, t^.right);
END
ELSE
t := n;
END;
FUNCTION TreeHeight(VAR rt : Tree) : Integer;
VAR lh, rh, hh : Integer;
BEGIN
IF rt = NIL THEN
hh := 0
ELSE
BEGIN
lh := TreeHeight(rt^.left);
rh := TreeHeight(rt^.right);
IF lh >= rh THEN
hh := 1 + lh
ELSE
hh := 1 + rh
END;
TreeHeight := hh
END;
PROCEDURE PrintTree(indent : String; l : Integer; t : Tree);
BEGIN
IF t <> NIL THEN
BEGIN
Writeln(indent, 'description: ', t^.desc, ' count: ', t^.count, ' @ line: ', l);
PrintTree(indent, l+1, t^.left);
PrintTree(indent + indent, l+1, t^.right)
END
END;
END.
|
unit JSONNullableMarshalConverterUnit;
interface
uses
System.JSON, REST.JsonReflect, System.RTTI, SysUtils,
System.Generics.Collections;
type
TJSONNullableConverter = class(TJSONConverter)
private
FRemovedPairs: TObjectList<TObject>;
procedure RemoveNullableFields(Root: TJSONAncestor);
procedure PrepareDictionaryFields(Root: TJSONAncestor);
function IsNullableObject(JSONAncestor: TJSONAncestor;
out IsRequired: boolean; out Value: TValue; out IsNull: boolean): boolean;
function IsNullableArray(JSONAncestor: TJSONAncestor;
out IsRequired: boolean; out Value: TJSONValue): boolean;
function IsDictionaryIntermediateObject(JSONAncestor: TJSONAncestor;
out Pairs: TArray<TJSONPair>): boolean;
protected
function GetSerializedData: TJSONValue; override;
public
destructor Destroy; override;
end;
implementation
{ TJSONNullableConverter }
uses
NullableInterceptorUnit, NullableArrayInterceptorUnit;
destructor TJSONNullableConverter.Destroy;
begin
inherited;
end;
function TJSONNullableConverter.GetSerializedData: TJSONValue;
begin
Result := Inherited GetSerializedData;
FRemovedPairs := TObjectList<TObject>.Create;
RemoveNullableFields(Result);
FreeAndNil(FRemovedPairs);
PrepareDictionaryFields(Result);
end;
function TJSONNullableConverter.IsDictionaryIntermediateObject(
JSONAncestor: TJSONAncestor; out Pairs: TArray<TJSONPair>): boolean;
var
JSONObject: TJSONObject;
JSONPair: TJSONPair;
Value: TJSONValue;
DictName: String;
DictValue: TJSONValue;
begin
Result := False;
Pairs := nil;
if (JSONAncestor is TJSONObject) then
begin
JSONObject := TJSONObject(JSONAncestor);
if (JSONObject.Count = 1) and (JSONObject.Pairs[0].JsonString <> nil) then
begin
JSONPair := JSONObject.Pairs[0];
if (JSONPair.JsonString.Value.ToUpper = 'DictionaryIntermediateObject'.ToUpper) then
begin
SetLength(Pairs, 0);
for Value in (JSONPair.JsonValue as TJSONArray) do
begin
DictName := ((Value as TJSONArray).Items[0] as TJSONString).Value;
DictValue := (Value as TJSONArray).Items[1];
SetLength(Pairs, Length(Pairs) + 1);
Pairs[High(Pairs)] := TJSONPair.Create(DictName, DictValue);
end;
Exit(True);
end;
end;
end;
end;
function TJSONNullableConverter.IsNullableArray(JSONAncestor: TJSONAncestor;
out IsRequired: boolean; out Value: TJSONValue): boolean;
var
JSONObject: TJSONObject;
JSONPair: TJSONPair;
begin
Result := False;
if (JSONAncestor is TJSONObject) then
begin
JSONObject := TJSONObject(JSONAncestor);
if (JSONObject.Count = 1) and (JSONObject.Pairs[0].JsonString <> nil) then
begin
JSONPair := JSONObject.Pairs[0];
Result := ('T' + JSONPair.JsonString.Value.ToUpper = TNullableArrayIntermediateObject.ClassName.ToUpper);
if not Result then
Exit;
JSONObject := TJSONObject(JSONPair.JsonValue);
Value := JSONObject.GetValue('value');
IsRequired := (JSONObject.GetValue('isRequired') as TJSONBool).AsBoolean;
end;
end;
end;
function TJSONNullableConverter.IsNullableObject(JSONAncestor: TJSONAncestor;
out IsRequired: boolean; out Value: TValue; out IsNull: boolean): boolean;
var
JSONObject: TJSONObject;
JSONPair: TJSONPair;
begin
Result := False;
if (JSONAncestor is TJSONObject) then
begin
JSONObject := TJSONObject(JSONAncestor);
if (JSONObject.Count = 1) and (JSONObject.Pairs[0].JsonString <> nil) then
begin
JSONPair := JSONObject.Pairs[0];
Result := ('T' + JSONPair.JsonString.Value.ToUpper = TNullableIntermediateObject.ClassName.ToUpper);
if not Result then
Exit;
IsNull := (TJSONObject(JSONPair.JsonValue).GetValue('isNull') as TJSONBool).AsBoolean;
IsRequired := (TJSONObject(JSONPair.JsonValue).GetValue('isRequired') as TJSONBool).AsBoolean;
Value := TJSONObject(JSONPair.JsonValue).GetValue('value');
end;
end;
end;
procedure TJSONNullableConverter.PrepareDictionaryFields(Root: TJSONAncestor);
var
i: integer;
JSONObject: TJSONObject;
JSONValue: TJSONValue;
Pairs: TArray<TJSONPair>;
Pair: TJSONPair;
Name: String;
NewJSONValue: TJSONObject;
begin
if (Root is TJSONArray) then
for JSONValue in TJSONArray(Root) do
PrepareDictionaryFields(JSONValue);
if (Root is TJSONObject) then
begin
JSONObject := TJSONObject(Root);
i := 0;
while (i < JSONObject.Count) do
begin
if IsDictionaryIntermediateObject(JSONObject.Pairs[i].JsonValue, Pairs) then
begin
Name := JSONObject.Pairs[i].JsonString.Value;
JSONObject.RemovePair(JSONObject.Pairs[i].JsonString.Value);
NewJSONValue := TJSONObject.Create;
for Pair in Pairs do
NewJSONValue.AddPair(Pair);
JSONObject.AddPair(Name, NewJSONValue);
end
else
begin
PrepareDictionaryFields(JSONObject.Pairs[i].JsonValue);
inc(i);
end;
end;
end;
end;
procedure TJSONNullableConverter.RemoveNullableFields(Root: TJSONAncestor);
var
i: integer;
JSONObject: TJSONObject;
IsRequired: boolean;
IsNull: boolean;
Value: TValue;
Name: String;
JSONValue: TJSONValue;
begin
if (Root is TJSONArray) then
for JSONValue in TJSONArray(Root) do
RemoveNullableFields(JSONValue);
if (Root is TJSONObject) then
begin
JSONObject := TJSONObject(Root);
i := 0;
while (i < JSONObject.Count) do
begin
if IsNullableObject(JSONObject.Pairs[i].JsonValue, IsRequired, Value, IsNull) then
begin
Name := JSONObject.Pairs[i].JsonString.Value;
JSONValue := (Value.AsObject as TJsonValue).Clone as TJsonValue;
FRemovedPairs.Add(JSONObject.RemovePair(JSONObject.Pairs[i].JsonString.Value));
if (not IsNull) then
JSONObject.AddPair(Name, JSONValue)
else
begin
if IsRequired then
JSONObject.AddPair(Name, TJSONNull.Create);
FreeAndNil(JSONValue);
end;
end
else
if IsNullableArray(JSONObject.Pairs[i].JsonValue, IsRequired, JSONValue) then
begin
Name := JSONObject.Pairs[i].JsonString.Value;
JSONValue := JSONValue.Clone as TJSONValue;
FRemovedPairs.Add(JSONObject.RemovePair(JSONObject.Pairs[i].JsonString.Value));
IsNull := (JSONValue is TJSONNull) or (
(JSONValue is TJSONArray) and (TJSONArray(JSONValue).Count = 0));
if (not IsNull) then
JSONObject.AddPair(Name, JSONValue)
else
begin
if IsRequired then
JSONObject.AddPair(Name, TJSONNull.Create);
FreeAndNil(JSONValue);
end;
end
else
begin
RemoveNullableFields(JSONObject.Pairs[i].JsonValue);
inc(i);
end;
end;
end;
end;
end.
|
unit DW.PermissionsTypes {$IF CompilerVersion > 32} deprecated 'use System.Permissions'{$ENDIF};
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
type
TPermissionResult = record
Permission: string;
Granted: Boolean
end;
TPermissionResults = TArray<TPermissionResult>;
TPermissionResultsHelper = record helper for TPermissionResults
public
function Add(const AValue: TPermissionResult): Integer;
function AreAllGranted: Boolean;
procedure Clear;
function Count: Integer;
function DeniedResults: TPermissionResults;
end;
implementation
{ TPermissionResultsHelper }
function TPermissionResultsHelper.Add(const AValue: TPermissionResult): Integer;
begin
SetLength(Self, Count + 1);
Self[Count - 1] := AValue;
Result := Count - 1;
end;
function TPermissionResultsHelper.AreAllGranted: Boolean;
var
I: Integer;
begin
Result := True;
for I := 0 to Count - 1 do
begin
if not Self[I].Granted then
begin
Result := False;
Break;
end;
end;
end;
procedure TPermissionResultsHelper.Clear;
begin
SetLength(Self, 0);
end;
function TPermissionResultsHelper.Count: Integer;
begin
Result := Length(Self);
end;
function TPermissionResultsHelper.DeniedResults: TPermissionResults;
var
I: Integer;
begin
for I := 0 to Count - 1 do
begin
if not Self[I].Granted then
Result.Add(Self[I]);
end;
end;
end.
|
unit uEnemy;
interface
type
TBaseEnemy = class(TObject)
private
FY: Byte;
FX: Byte;
FID: Byte;
procedure SetX(const Value: Byte);
procedure SetY(const Value: Byte);
procedure SetID(const Value: Byte);
public
constructor Create;
destructor Destroy; override;
property ID: Byte read FID write SetID;
property X: Byte read FX write SetX;
property Y: Byte read FY write SetY;
end;
TEnemies = array of TBaseEnemy;
TCreatures = class(TObject)
private
FEnemy: TEnemies;
procedure SetEnemy(const Value: TEnemies);
public
procedure Add(const AX, AY, AID: Byte);
property Enemy: TEnemies read FEnemy write SetEnemy;
procedure Empty;
constructor Create;
destructor Destroy; override;
end;
var
Creatures: TCreatures;
implementation
uses uUtils;
{ TBaseEnemy }
constructor TBaseEnemy.Create;
begin
ID := 0;
X := 0;
Y := 0;
end;
destructor TBaseEnemy.Destroy;
begin
inherited;
end;
procedure TBaseEnemy.SetID(const Value: Byte);
begin
FID := Value;
end;
procedure TBaseEnemy.SetX(const Value: Byte);
begin
FX := Value;
end;
procedure TBaseEnemy.SetY(const Value: Byte);
begin
FY := Value;
end;
{ TCreatures }
procedure TCreatures.Add(const AX, AY, AID: Byte);
var
I: Word;
begin
I := Length(FEnemy) + 1;
SetLength(FEnemy, I);
FEnemy[I - 1] := TBaseEnemy.Create;
with FEnemy[I - 1] do
begin
X := AX;
Y := AY;
ID := AID;
end;
end;
constructor TCreatures.Create;
//var
// I: Word;
begin
// for I := 0 to 49 do
// Add(Rand(10, 140), Rand(10, 140), 0);
end;
destructor TCreatures.Destroy;
var
I: Word;
begin
if (Length(Enemy) > 0) then
for I := 0 to Length(Enemy) - 1 do
Enemy[I].Free;
inherited;
end;
procedure TCreatures.Empty;
begin
SetLength(FEnemy, 0);
end;
procedure TCreatures.SetEnemy(const Value: TEnemies);
begin
FEnemy := Value;
end;
initialization
// Creatures := TCreatures.Create;
finalization
Creatures.Free;
end.
|
unit QueryCardKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы QueryCard }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Search\Forms\QueryCardKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "QueryCardKeywordsPack" MUID: (4AA9393C0164_Pack)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(Admin) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, QueryCard_Form
, tfwPropertyLike
, evQueryCardEditor
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, evTextSource
, tfwControlString
, kwBynameControlPush
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *4AA9393C0164_Packimpl_uses*
//#UC END# *4AA9393C0164_Packimpl_uses*
;
type
TkwEnQueryCardEditor = {final} class(TtfwPropertyLike)
{* Слово скрипта .TenQueryCard.Editor }
private
function Editor(const aCtx: TtfwContext;
aenQueryCard: TenQueryCard): TevQueryCardEditor;
{* Реализация слова скрипта .TenQueryCard.Editor }
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;//TkwEnQueryCardEditor
TkwEnQueryCardTextSource = {final} class(TtfwPropertyLike)
{* Слово скрипта .TenQueryCard.TextSource }
private
function TextSource(const aCtx: TtfwContext;
aenQueryCard: TenQueryCard): TevTextSource;
{* Реализация слова скрипта .TenQueryCard.TextSource }
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;//TkwEnQueryCardTextSource
Tkw_Form_QueryCard = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы QueryCard
----
*Пример использования*:
[code]форма::QueryCard TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_QueryCard
Tkw_QueryCard_Control_Editor = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола Editor
----
*Пример использования*:
[code]контрол::Editor TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_QueryCard_Control_Editor
Tkw_QueryCard_Control_Editor_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола Editor
----
*Пример использования*:
[code]контрол::Editor:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_QueryCard_Control_Editor_Push
Tkw_QueryCard_Component_TextSource = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола TextSource
----
*Пример использования*:
[code]компонент::TextSource TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_QueryCard_Component_TextSource
function TkwEnQueryCardEditor.Editor(const aCtx: TtfwContext;
aenQueryCard: TenQueryCard): TevQueryCardEditor;
{* Реализация слова скрипта .TenQueryCard.Editor }
begin
Result := aenQueryCard.Editor;
end;//TkwEnQueryCardEditor.Editor
class function TkwEnQueryCardEditor.GetWordNameForRegister: AnsiString;
begin
Result := '.TenQueryCard.Editor';
end;//TkwEnQueryCardEditor.GetWordNameForRegister
function TkwEnQueryCardEditor.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TevQueryCardEditor);
end;//TkwEnQueryCardEditor.GetResultTypeInfo
function TkwEnQueryCardEditor.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnQueryCardEditor.GetAllParamsCount
function TkwEnQueryCardEditor.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TenQueryCard)]);
end;//TkwEnQueryCardEditor.ParamsTypes
procedure TkwEnQueryCardEditor.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Editor', aCtx);
end;//TkwEnQueryCardEditor.SetValuePrim
procedure TkwEnQueryCardEditor.DoDoIt(const aCtx: TtfwContext);
var l_aenQueryCard: TenQueryCard;
begin
try
l_aenQueryCard := TenQueryCard(aCtx.rEngine.PopObjAs(TenQueryCard));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aenQueryCard: TenQueryCard : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(Editor(aCtx, l_aenQueryCard));
end;//TkwEnQueryCardEditor.DoDoIt
function TkwEnQueryCardTextSource.TextSource(const aCtx: TtfwContext;
aenQueryCard: TenQueryCard): TevTextSource;
{* Реализация слова скрипта .TenQueryCard.TextSource }
begin
Result := aenQueryCard.TextSource;
end;//TkwEnQueryCardTextSource.TextSource
class function TkwEnQueryCardTextSource.GetWordNameForRegister: AnsiString;
begin
Result := '.TenQueryCard.TextSource';
end;//TkwEnQueryCardTextSource.GetWordNameForRegister
function TkwEnQueryCardTextSource.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TevTextSource);
end;//TkwEnQueryCardTextSource.GetResultTypeInfo
function TkwEnQueryCardTextSource.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnQueryCardTextSource.GetAllParamsCount
function TkwEnQueryCardTextSource.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TenQueryCard)]);
end;//TkwEnQueryCardTextSource.ParamsTypes
procedure TkwEnQueryCardTextSource.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству TextSource', aCtx);
end;//TkwEnQueryCardTextSource.SetValuePrim
procedure TkwEnQueryCardTextSource.DoDoIt(const aCtx: TtfwContext);
var l_aenQueryCard: TenQueryCard;
begin
try
l_aenQueryCard := TenQueryCard(aCtx.rEngine.PopObjAs(TenQueryCard));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aenQueryCard: TenQueryCard : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(TextSource(aCtx, l_aenQueryCard));
end;//TkwEnQueryCardTextSource.DoDoIt
function Tkw_Form_QueryCard.GetString: AnsiString;
begin
Result := 'enQueryCard';
end;//Tkw_Form_QueryCard.GetString
class procedure Tkw_Form_QueryCard.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TenQueryCard);
end;//Tkw_Form_QueryCard.RegisterInEngine
class function Tkw_Form_QueryCard.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::QueryCard';
end;//Tkw_Form_QueryCard.GetWordNameForRegister
function Tkw_QueryCard_Control_Editor.GetString: AnsiString;
begin
Result := 'Editor';
end;//Tkw_QueryCard_Control_Editor.GetString
class procedure Tkw_QueryCard_Control_Editor.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TevQueryCardEditor);
end;//Tkw_QueryCard_Control_Editor.RegisterInEngine
class function Tkw_QueryCard_Control_Editor.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Editor';
end;//Tkw_QueryCard_Control_Editor.GetWordNameForRegister
procedure Tkw_QueryCard_Control_Editor_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('Editor');
inherited;
end;//Tkw_QueryCard_Control_Editor_Push.DoDoIt
class function Tkw_QueryCard_Control_Editor_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Editor:push';
end;//Tkw_QueryCard_Control_Editor_Push.GetWordNameForRegister
function Tkw_QueryCard_Component_TextSource.GetString: AnsiString;
begin
Result := 'TextSource';
end;//Tkw_QueryCard_Component_TextSource.GetString
class procedure Tkw_QueryCard_Component_TextSource.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TevTextSource);
end;//Tkw_QueryCard_Component_TextSource.RegisterInEngine
class function Tkw_QueryCard_Component_TextSource.GetWordNameForRegister: AnsiString;
begin
Result := 'компонент::TextSource';
end;//Tkw_QueryCard_Component_TextSource.GetWordNameForRegister
initialization
TkwEnQueryCardEditor.RegisterInEngine;
{* Регистрация enQueryCard_Editor }
TkwEnQueryCardTextSource.RegisterInEngine;
{* Регистрация enQueryCard_TextSource }
Tkw_Form_QueryCard.RegisterInEngine;
{* Регистрация Tkw_Form_QueryCard }
Tkw_QueryCard_Control_Editor.RegisterInEngine;
{* Регистрация Tkw_QueryCard_Control_Editor }
Tkw_QueryCard_Control_Editor_Push.RegisterInEngine;
{* Регистрация Tkw_QueryCard_Control_Editor_Push }
Tkw_QueryCard_Component_TextSource.RegisterInEngine;
{* Регистрация Tkw_QueryCard_Component_TextSource }
TtfwTypeRegistrator.RegisterType(TypeInfo(TenQueryCard));
{* Регистрация типа TenQueryCard }
TtfwTypeRegistrator.RegisterType(TypeInfo(TevQueryCardEditor));
{* Регистрация типа TevQueryCardEditor }
TtfwTypeRegistrator.RegisterType(TypeInfo(TevTextSource));
{* Регистрация типа TevTextSource }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Image1: TImage;
PaintBox1: TPaintBox;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
f_Edit: TWinControl;
public
{ Public declarations }
end;
TXEdit = class(TEdit)
private
FFocusedBorder: Boolean;
f_ImageRGN: HRGN;
procedure WMNCPaint(var Msg: TWMNCPaint);
message WM_NCPAINT;
procedure WMNCCalcSize(var Msg: TWMNCCalcSize);
message WM_NCCALCSIZE;
procedure WMEraseBkGnd(var Msg: TWMEraseBkGnd);
message WM_ERASEBKGND;
procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
procedure WMKillFocus(var Message: TWMSetFocus); message WM_KILLFOCUS;
procedure CMParentColorChanged(var Message: TMessage); message CM_PARENTCOLORCHANGED;
procedure UpdateWindowRegion;
procedure SetFocusedBorder(const Value: Boolean);
procedure ClearImageRGN;
function GetImageRGN: HRGN;
function TestThemeAvail: Boolean;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure DestroyWnd; override;
procedure Resize; override;
property FocusedBorder: Boolean read FFocusedBorder write SetFocusedBorder;
// procedure Paint; override;
public
constructor Create(aComponent: TComponent); override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Themes;
procedure TForm1.Button1Click(Sender: TObject);
begin
Color := not Color;
end;
{ TXEdit }
const cBorder = 3;
procedure TXEdit.ClearImageRGN;
begin
if f_ImageRGN <> 0 then
begin
DeleteObject(f_ImageRGN);
f_ImageRGN := 0;
end;
end;
procedure TXEdit.CMParentColorChanged(var Message: TMessage);
begin
inherited;
RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE);
end;
constructor TXEdit.Create(aComponent: TComponent);
begin
inherited Create(aComponent);
ControlStyle := ControlStyle - [csOpaque];
Width := Width + 2*Height + cBorder * 2;
Height := Height + cBorder * 2;
AutoSize := False;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
l_Edit: TWinControl;
begin
l_Edit := TXEdit.Create(Self);
l_Edit.Top := 100;
l_Edit.Left := 150;
l_Edit.Parent := Self;
// l_Edit.Ctl3D := False;
l_Edit := TXEdit.Create(Self);
l_Edit.Top := 200;
l_Edit.Left := 150;
l_Edit.Parent := Self;
f_Edit := l_Edit;
// l_Edit.Ctl3D := False;
end;
procedure TXEdit.CreateParams(var Params: TCreateParams);
begin
inherited;
// Params.WindowClass.style := Params.WindowClass.style or CS_PARENTDC;
end;
(*
procedure TXEdit.Paint;
begin
Canvas.Brush.Color := clRed;
Canvas.FillRect(ClientRect);
end;
*)
procedure TXEdit.CreateWnd;
begin
inherited;
if not TestThemeAvail then
UpdateWindowRegion;
end;
procedure TXEdit.DestroyWnd;
begin
inherited;
ClearImageRGN;
end;
function TXEdit.GetImageRGN: HRGN;
var
l_DrawRect: TRect;
l_ClientRect: TRect;
begin
if (f_ImageRGN = 0) and not TestThemeAvail then
begin
GetWindowRect(Handle, l_DrawRect);
OffsetRect(l_DrawRect, -l_DrawRect.Left, -l_DrawRect.Top);
l_ClientRect := l_DrawRect;
InflateRect(l_ClientRect, -cBorder, -cBorder);
InflateRect(l_ClientRect, -(l_ClientRect.Bottom - l_ClientRect.Top), 0);
if not FocusedBorder then
InflateRect(l_DrawRect, -cBorder, -cBorder);
f_ImageRGN := CreateRoundRectRgn(l_DrawRect.Left, l_DrawRect.Top, l_DrawRect.Right, l_DrawRect.Bottom, l_ClientRect.Left - l_DrawRect.Left, (l_DrawRect.Bottom - l_DrawRect.Top));
end;
Result := f_ImageRGN;
end;
procedure TXEdit.Resize;
begin
inherited;
UpdateWindowRegion;
end;
procedure TXEdit.SetFocusedBorder(const Value: Boolean);
begin
if FFocusedBorder <> Value then
begin
FFocusedBorder := Value;
UpdateWindowRegion;
RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE);
end
end;
function TXEdit.TestThemeAvail: Boolean;
begin
Result := ThemeServices.ThemesAvailable;
end;
procedure TXEdit.UpdateWindowRegion;
begin
if not HandleAllocated or TestThemeAvail then
exit;
ClearImageRgn;
SetWindowRgn(Handle, GetImageRGN, True);
end;
procedure TXEdit.WMEraseBkGnd(var Msg: TWMEraseBkGnd);
begin
// inherited;
Msg.Result := 1;
end;
procedure TXEdit.WMKillFocus(var Message: TWMSetFocus);
begin
inherited;
FocusedBorder := False;
end;
procedure TXEdit.WMNCCalcSize(var Msg: TWMNCCalcSize);
begin
inherited;
InflateRect(Msg.CalcSize_Params^.rgrc[0], -cBorder - ((Msg.CalcSize_Params^.rgrc[0].Bottom - Msg.CalcSize_Params^.rgrc[0].Top) div 2), -cBorder);
Msg.Result := 0;
end;
type
THack = class(TWinControl);
procedure TXEdit.WMNCPaint(var Msg: TWMNCPaint);
var
l_DC: HDC;
l_Canvas: TControlCanvas;
l_Rect: TRect;
l_DrawRect: TRect;
l_ClientRect: TRect;
l_ParentRect: TRect;
OldP: TPoint;
P: TPoint;
l_IDX: Integer;
begin
// inherited;
Msg.Result := 0;
l_Canvas := TControlCanvas.Create;
l_DC := GetWindowDC(Handle);
l_Canvas.Handle := l_DC;
GetWindowRect(Handle, l_Rect);
OffsetRect(l_Rect, -l_Rect.Left, -l_Rect.Top);
l_ParentRect := l_Rect;
l_ClientRect := l_Rect;
InflateRect(l_ClientRect, -cBorder, -cBorder);
InflateRect(l_ClientRect, -(l_ClientRect.Bottom - l_ClientRect.Top), 0);
// ExcludeClipRect(l_Canvas.Handle, l_ClientRect.Left, l_ClientRect.Top, l_ClientRect.Right, l_ClientRect.Bottom);
if TestThemeAvail then
begin
// P := Point(l_ClientRect.Left, l_ClientRect.Top);
// P := Point(17, 5);
P := Point((l_ClientRect.bottom - l_ClientRect.top) div 2 + 2*cBorder, 2 + cBorder);
// SetMapMode(l_DC, MM_ANISOTROPIC);
SetViewPortOrgEx(l_DC, P.x, P.y, @OldP);
ThemeServices.DrawParentBackground(Handle, l_DC, nil, False, nil);
SetViewPortOrgEx(l_DC, OldP.x, OldP.y, nil);
// SetMapMode(l_DC, MM_TEXT);
end
else
begin
l_Canvas.Pen.Color := THack(Parent).Color;
l_Canvas.Brush.Color := THack(Parent).Color;
l_Canvas.FillRect(l_Rect);
end;
l_DrawRect := l_Rect;
if FocusedBorder then
begin
l_Canvas.Pen.Color := clBlue;
l_Canvas.Brush.Color := clBlue;
for l_IDX := 1 to cBorder do
begin
l_Canvas.RoundRect(l_DrawRect.Left, l_DrawRect.Top, l_DrawRect.Right, l_DrawRect.Bottom, l_ClientRect.Left - l_DrawRect.Left, (l_DrawRect.Bottom - l_DrawRect.Top));
InflateRect(l_DrawRect, -1, -1);
end;
end
else
InflateRect(l_DrawRect, -cBorder, -cBorder);
l_Canvas.Brush.Color := Color;
l_Canvas.Brush.Style := bsSolid;
l_Canvas.Pen.Color := clRed;
l_Canvas.RoundRect(l_DrawRect.Left, l_DrawRect.Top, l_DrawRect.Right, l_DrawRect.Bottom, l_ClientRect.Left - l_DrawRect.Left, (l_DrawRect.Bottom - l_DrawRect.Top));
Msg.Result := 0;
end;
procedure TXEdit.WMSetFocus(var Message: TWMSetFocus);
begin
inherited;
FocusedBorder := True;
end;
procedure TForm1.PaintBox1Paint(Sender: TObject);
begin
PaintBox1.Canvas.Brush.Color := clRed;
// PaintBox1.Canvas.Chord(50,50,100,100,75,50,75,100);
PaintBox1.Canvas.RoundRect(50,50,150,72,22,22);
// PaintBox1.Canvas.Arc(50,50,100,100,75,50,75,100);
end;
procedure TForm1.FormResize(Sender: TObject);
begin
if Assigned(f_Edit) then
f_Edit.Width := Width - f_Edit.Left - 100;
end;
end.
|
const inputFileName = 'input.txt';
const outputFileName = 'output.txt';
const generatedArraySize = 100;
const separatorsArraySize = 2;
type stringArrayType = array [1..generatedArraySize] of string;
type separatorsType = array [1..separatorsArraySize] of string;
type integerArrayType = array [1..generatedArraySize] of integer;
Type sizedIntegerArrayType = record
arr: integerArrayType;
size: integer;
end;
Type sizedStringArrayType = record
arr: stringArrayType;
size: integer;
end;
function concatArrays(arr1: sizedIntegerArrayType; arr2: sizedIntegerArrayType): sizedIntegerArrayType;
begin
var concatedArray: sizedIntegerArrayType;
concatedArray.size := 0;
for var index := 1 to arr1.size do
begin
concatedArray.size := concatedArray.size + 1;
concatedArray.arr[concatedArray.size] := arr1.arr[index];
end;
for var index := 1 to arr2.size do
begin
concatedArray.size := concatedArray.size + 1;
concatedArray.arr[concatedArray.size] := arr2.arr[index];
end;
Result := concatedArray;
end;
function oneOfSeparators(symbol: string; separators: separatorsType): boolean;
begin
for var index := 1 to separatorsArraySize do
begin
if symbol = separators[index] then
begin
Result := true;
end;
end;
end;
function isWordSeparator(sympol: string): boolean;
begin
var separators: separatorsType = (' ', ',');
Result := oneOfSeparators(sympol, separators);
end;
var arrayLength: integer := 0;
procedure push(var stringArray: stringArrayType; var currentArrayIndex: integer; var tempWord: string);
begin
stringArray[currentArrayIndex] := tempWord;
currentArrayIndex := currentArrayIndex + 1;
end;
function splitString(text: string): sizedStringArrayType;
begin
var stringArray: stringArrayType;
var currentArrayIndex: integer := 1;
var tempWord: string := '';
for var index := 1 to text.Length do
begin
var wordSeparator: boolean := isWordSeparator(text[index]);
if wordSeparator = true then
begin
if tempWord = '' then
begin
tempWord := '';
continue;
end;
push(stringArray, currentArrayIndex, tempWord);
arrayLength := currentArrayIndex - 1;
tempWord := '';
end
else
begin
tempWord := tempWord + text[index];
end;
end;
var wordSeparator: boolean := isWordSeparator(text[text.Length]);
if wordSeparator = false then
begin
push(stringArray, currentArrayIndex, tempWord);
arrayLength := currentArrayIndex - 1;
end;
var sizedStringArray: sizedStringArrayType;
sizedStringArray.arr := stringArray;
sizedStringArray.size := currentArrayIndex - 1;
Result := sizedStringArray;
end;
procedure viewArray(generatedArray: sizedIntegerArrayType);
begin
write('[');
for var index := 1 to generatedArray.size - 1 do
begin
write(generatedArray.arr[index] + ', ');
end;
writeln(generatedArray.arr[generatedArray.size] + ']');
end;
function arrayToNumber(stringArray: sizedStringArrayType): sizedIntegerArrayType;
begin
var integerArray: sizedIntegerArrayType;
integerArray.size := stringArray.size;
for var index := 1 to generatedArraySize do
begin
if stringArray.arr[index] <> '' then
begin
integerArray.arr[index] := stringArray.arr[index].ToInteger();
end;
end;
Result := integerArray;
end;
function getEvenNumbers(sizedArr: sizedIntegerArrayType): sizedIntegerArrayType;
begin
var evenNumbers: sizedIntegerArrayType;
evenNumbers.size := 0;
for var index := 1 to sizedArr.size do
begin
if sizedArr.arr[index] mod 2 = 0 then
begin
evenNumbers.size := evenNumbers.size + 1;
evenNumbers.arr[evenNumbers.size] := sizedArr.arr[index];
end;
end;
Result := evenNumbers;
end;
function getDevidableOnThreeNoSeven(sizedArr: sizedIntegerArrayType): sizedIntegerArrayType;
begin
var devidableNumbers: sizedIntegerArrayType;
devidableNumbers.size := 0;
for var index := 1 to sizedArr.size do
begin
if (sizedArr.arr[index] mod 3 = 0) and (sizedArr.arr[index] mod 7 <> 0) then
begin
devidableNumbers.size := devidableNumbers.size + 1;
devidableNumbers.arr[devidableNumbers.size] := sizedArr.arr[index];
end;
end;
Result := devidableNumbers;
end;
function getExactSquare(sizedArr: sizedIntegerArrayType): sizedIntegerArrayType;
begin
var exactSquareNumbers: sizedIntegerArrayType;
exactSquareNumbers.size := 0;
for var index := 1 to sizedArr.size do
begin
var roundedValue: integer := Round(Sqrt(sizedArr.arr[index]));
if roundedValue * roundedValue = sizedArr.arr[index] then
begin
exactSquareNumbers.size := exactSquareNumbers.size + 1;
exactSquareNumbers.arr[exactSquareNumbers.size] := sizedArr.arr[index];
end;
end;
Result := exactSquareNumbers;
end;
procedure writeToFile(outputFile: TextFile; sizedArr: sizedIntegerArrayType);
begin
for var index := 1 to sizedArr.size - 1 do
begin
write(outputFile, sizedArr.arr[index] + ', ');
end;
writeln(outputFile, sizedArr.arr[sizedArr.size]);
end;
begin
var inputFile: TextFile;
var outputFile: TextFile;
AssignFile(inputFile, inputFileName);
AssignFile(outputFile, outputFileName);
var fileText: string;
var allNumbers: sizedIntegerArrayType;
reset(inputFile);
while not eof(inputFile) do
begin
readln(inputFile, fileText);
var splittedText: sizedStringArrayType := splitString(fileText);
allNumbers := concatArrays(allNumbers, arrayToNumber(splittedText));
end;
viewArray(allNumbers);
var evenNumbers: sizedIntegerArrayType := getEvenNumbers(allNumbers);
viewArray(evenNumbers);
var devidableNumbers: sizedIntegerArrayType := getDevidableOnThreeNoSeven(allNumbers);
viewArray(devidableNumbers);
var exactSquareNumbers: sizedIntegerArrayType := getExactSquare(allNumbers);
viewArray(exactSquareNumbers);
rewrite(outputFile);
write(outputFile, 'All numbers: ');
writeToFile(outputFile, allNumbers);
write(outputFile, 'Even numbers: ');
writeToFile(outputFile, evenNumbers);
write(outputFile, 'Devidable numbers: ');
writeToFile(outputFile, devidableNumbers);
write(outputFile, 'Exact square numbers: ');
writeToFile(outputFile, exactSquareNumbers);
CloseFile(inputFile);
CloseFile(outputFile);
end.
|
unit MailConsts;
interface
// Text constants
const
tidAccount_File = 'account.ini';
tidMessage_Header = 'msg.header';
tidMessage_Body = 'msg.body';
tidAttchment_Mask = 'attach*.ini';
const
tidGeneral = 'General';
tidAlias = 'Alias';
tidForward = 'Forward';
tidAddress = 'Address';
tidKeep = 'Keep';
const
tidHeader = 'Header';
tidFromAddr = 'FromAddr';
tidToAddr = 'ToAddr';
tidFrom = 'From';
tidTo = 'To';
tidSubject = 'Subject';
tidMessageId = 'MessageId';
tidDate = 'Date';
tidDateFmt = tidDate + 'Fmt';
tidRead = 'Read';
tidAttachments = 'Attachments';
tidClass = 'Class';
tidName = 'Name';
tidPriority = 'Priority';
tidStamp = 'Stamp';
tidNoReply = 'NoReply';
// Mail domains
const
tidTycoons = 'tycoons';
tidCompanies = 'companies';
tidTowns = 'towns';
tidCluster = 'clusters';
// Mail Floders
const
tidInbox = 'Inbox';
tidSentItems = 'Sent';
tidDraft = 'Draft';
tidFolder_Inbox = tidInbox;
tidFolder_SentItems = tidSentItems;
tidFolder_Draft = tidDraft;
implementation
end.
|
unit TransportHandler;
interface
uses
VoyagerInterfaces, VoyagerServerInterfaces, Controls, ActorPool, Vehicles, StateEngine,
ExtCtrls, ActorTypes, Automaton, Collection, ClientTrain;
type
TTransportHandler =
class( TInterfacedObject, IMetaURLHandler, IURLHandler, IVehicleArray )
public
constructor Create( anActorPoolId : TActorPoolId;
HighResFreq : integer;
aMetaPoolLocator : TMetaPoolLocator );
destructor Destroy; override;
private
fActorPool : TClientActorPool;
fAutomatons : TLockableCollection;
fHighResTimer : TTimer;
private
function ClientActorFactory( ActorKind : TActorKind; ActorId : TActorId ) : IClientActor;
//function MetaPoolLocator( MetaPoolId : TMetaPoolId ) : TMetaStatePool;
procedure ClientAutomatonModified( Automaton : TClientAutomaton; Operation : TAutomationOperation );
public
procedure ClientCarModified( Car : TClientCar; Modification : TClientCarModification );
// IMetaURLHandler
private
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL( URL : TURL ) : THandlingAbility;
function Instantiate : IURLHandler;
// IURLHandler
private
function HandleURL( URL : TURL ) : TURLHandlingResult;
function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler( URLHandler : IMasterURLHandler );
private
fMasterURLHandler : IMasterURLHandler;
// IVehicleArray
private
function getVehicleCount : integer;
function getVehicle( index : integer ) : IVehicle;
procedure RegisterNotificationProc ( aOnArrayChanged : TOnVehicleArrayChanged );
procedure UnregisterNotificationProc( aOnArrayChanged : TOnVehicleArrayChanged );
private
fOnArrayChanged : TOnVehicleArrayChanged;
private
procedure OnHighResTick( Sender : TObject );
end;
const
tidMetaHandler_Transport = 'Transport';
implementation
uses
SysUtils, ClassStorage, Events, ServerCnxEvents;
// TTransportHandler
constructor TTransportHandler.Create( anActorPoolId : TActorPoolId; HighResFreq : integer; aMetaPoolLocator : TMetaPoolLocator );
begin
inherited Create;
fActorPool := TClientActorPool.Create( anActorPoolId );
fActorPool.ClientActorFactory := ClientActorFactory;
fActorPool.MetaPoolLocator := aMetaPoolLocator;
fAutomatons := TLockableCollection.Create( 0, rkUse );
fHighResTimer := TTimer.Create( nil );
fHighResTimer.Interval := HighResFreq;
fHighResTimer.OnTimer := OnHighResTick;
end;
destructor TTransportHandler.Destroy;
begin
fHighResTimer.Free;
fActorPool.Free;
fAutomatons.Free;
inherited;
end;
function TTransportHandler.ClientActorFactory( ActorKind : TActorKind; ActorId : TActorId ) : IClientActor;
var
MA : TMetaClientAutomaton;
CA : TClientAutomaton;
begin
MA := TMetaClientAutomaton(TheClassStorage.ClassById[IntToStr(fActorPool.Id), IntToStr(ActorKind)]);
if MA <> nil
then
begin
CA := MA.Instantiate( ActorId, self );
CA.OnAutomatonModified := ClientAutomatonModified;
CA.Automatable := MA.InstantiateAutomatable( self );
fAutomatons.Insert( CA );
result := CA;
end
else result := nil;
end;
{
function TTransportHandler.MetaPoolLocator( MetaPoolId : TMetaPoolId ) : TMetaStatePool;
var
MA : TMetaClientAutomaton;
begin
MA := TMetaClientAutomaton(TheClassStorage.ClassById[IntToStr(fActorPool.Id), IntToStr(MetaPoolId)]);
if MA <> nil
then result := MA.Behavior
else result := nil;
end;
}
procedure TTransportHandler.ClientAutomatonModified( Automaton : TClientAutomaton; Operation : TAutomationOperation );
begin
if Operation = aopDeleted
then fAutomatons.Delete( Automaton );
end;
procedure TTransportHandler.ClientCarModified( Car : TClientCar; Modification : TClientCarModification );
var
Vehicle : IVehicle;
begin
if (Modification = ccmDeleted) and assigned(fOnArrayChanged)
then
begin
Vehicle := Car;
fOnArrayChanged( self, achVehicleDeletion, Vehicle );
end;
end;
function TTransportHandler.getName : string;
begin
result := tidMetaHandler_Transport + IntToStr(fActorPool.Id);
end;
function TTransportHandler.getOptions : TURLHandlerOptions;
begin
result := [hopCacheable, hopNonVisual];
end;
function TTransportHandler.getCanHandleURL( URL : TURL ) : THandlingAbility;
begin
result := 0;
end;
function TTransportHandler.Instantiate : IURLHandler;
begin
result := self;
end;
function TTransportHandler.HandleURL( URL : TURL ) : TURLHandlingResult;
begin
result := urlNotHandled;
end;
function TTransportHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
var
AnswerVehicleArrayInfo : TMsgAnswerVehicleArrayInfo absolute info;
ActorPoolModifiedInfo : TMsgActorPoolModifiedInfo absolute info;
begin
result := evnHandled;
case EventId of
evnAnswerVehicleArray :
if AnswerVehicleArrayInfo.ActorPoolId = fActorPool.Id
then AnswerVehicleArrayInfo.VehicleArray := self;
evnActorPoolModified :
if ActorPoolModifiedInfo.ActorPoolId = fActorPool.Id
then fActorPool.Act( ActorPoolModifiedInfo.Data );
evnShutDown :
fOnArrayChanged := nil;
else
result := evnNotHandled;
end;
end;
function TTransportHandler.getControl : TControl;
begin
result := nil;
end;
procedure TTransportHandler.setMasterURLHandler( URLHandler : IMasterURLHandler );
begin
fMasterURLHandler := URLHandler;
end;
function TTransportHandler.getVehicleCount : integer;
begin
result := fAutomatons.Count;
end;
function TTransportHandler.getVehicle( index : integer ) : IVehicle;
var
A : TClientAutomaton;
Msg : TMsgAnswerVehicle;
begin
A := TClientAutomaton(fAutomatons[index]);
Msg.MsgId := msgAnswerVehicle;
A.Automatable.Dispatch( Msg );
result := Msg.Vehicle;
end;
procedure TTransportHandler.RegisterNotificationProc( aOnArrayChanged : TOnVehicleArrayChanged );
begin
fOnArrayChanged := aOnArrayChanged;
end;
procedure TTransportHandler.UnregisterNotificationProc( aOnArrayChanged : TOnVehicleArrayChanged );
begin
fOnArrayChanged := nil;
end;
procedure TTransportHandler.OnHighResTick( Sender : TObject );
begin
fActorPool.HighResAct;
if assigned(fOnArrayChanged)
then fOnArrayChanged( self, achUpdate, self );
end;
end.
|
unit uKeyField;
interface
type
KeyField = class(TCustomAttribute)
private
FName: String;
public
property Name: String read FName write FName;
constructor Create(aName: String);
end;
type
FieldName = class(TCustomAttribute)
private
FName: String;
public
property Name: String read FName write FName;
constructor Create(aName: String);
end;
type
ForeingKey = class(TCustomAttribute)
private
FName: String;
public
property Name: String read FName write FName;
constructor Create(aName: String);
end;
type
FieldNull = class(TCustomAttribute)
private
FName: String;
public
property Name: String read FName write FName;
constructor Create(aName: String);
end;
type
FieldDate = class(TCustomAttribute)
private
FName: String;
public
property Name: String read FName write FName;
constructor Create(aName: String);
end;
type
FieldTime = class(TCustomAttribute)
private
FName: String;
public
property Name: String read FName write FName;
constructor Create(aName: String);
end;
implementation
{ KeyField }
constructor KeyField.Create(aName: String);
begin
FName := aName;
end;
{ Field }
constructor FieldName.Create(aName: String);
begin
FName := aName;
end;
{ ForeingKey }
constructor ForeingKey.Create(aName: String);
begin
FName := aName;
end;
{ FieldNull }
constructor FieldNull.Create(aName: String);
begin
FName := aName;
end;
{ FieldDate }
constructor FieldDate.Create(aName: String);
begin
FName := aName;
end;
{ FieldTime }
constructor FieldTime.Create(aName: String);
begin
FName := aName;
end;
end.
|
unit TestMarshalAddressBookContactUnit;
interface
uses
TestFramework,
SysUtils, TestBaseJsonMarshalUnit;
type
TTestMarshalAddressBookContact = class(TTestBaseJsonMarshal)
published
procedure DefaultAddressBookContact();
procedure FullAddressBookContact();
end;
implementation
{ TTestAddressBookContactToJson }
uses AddressBookContactUnit, IAddressBookContactProviderUnit,
FullAddressBookContactProviderUnit, DefaultAddressBookContactProviderUnit;
procedure TTestMarshalAddressBookContact.DefaultAddressBookContact;
var
Provider: IAddressBookContactProvider;
AddressBookContact: TAddressBookContact;
begin
Provider := TDefaultAddressBookContactProvider.Create;
try
AddressBookContact := Provider.AddressBookContact;
try
CheckEquals(
EtalonFilename('AddressBookContactToJson\DefaultAddressBookContact'),
AddressBookContact.ToJsonString);
finally
FreeAndNil(AddressBookContact);
end;
finally
Provider := nil;
end;
end;
procedure TTestMarshalAddressBookContact.FullAddressBookContact;
var
Provider: IAddressBookContactProvider;
AddressBookContact: TAddressBookContact;
begin
Provider := TFullAddressBookContactProvider.Create;
try
AddressBookContact := Provider.AddressBookContact;
try
CheckEquals(
EtalonFilename('AddressBookContactToJson\FullAddressBookContact'),
AddressBookContact.ToJsonString);
finally
FreeAndNil(AddressBookContact);
end;
finally
Provider := nil;
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest('JSON\Marshal\', TTestMarshalAddressBookContact.Suite);
end.
|
unit ZMXcpt19;
(*
ZMXcpt19.pas - Exception class for ZipMaster
Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht,
Eric W. Engler and Chris Vleghert.
This file is part of TZipMaster Version 1.9.
TZipMaster is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TZipMaster is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TZipMaster. If not, see <http://www.gnu.org/licenses/>.
contact: problems@delphizip.org (include ZipMaster in the subject).
updates: http://www.delphizip.org
DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip
modified 2009-11-22
---------------------------------------------------------------------------*)
interface
uses
SysUtils;
{$IFNDEF UNICODE}
type
TZMXArgs = (zxaNoStr, zxaStr, zxa2Str);
{$ENDIF}
type
EZMException = class(Exception)
{$IFNDEF UNICODE}
private
fArgs: TZMXArgs;
fStr1: String;
fStr2: string;
{$ENDIF}
protected
// We do not always want to see a message after an exception.
fDisplayMsg: Boolean;
// We also save the Resource ID in case the resource is not linked in the application.
fResIdent: Integer;
constructor CreateResFmt(Ident: Integer; const Args: array of const);
public
constructor CreateDisp(const Message: String; const Display: Boolean);
constructor CreateResDisp(Ident: Integer; const Display: Boolean);
constructor CreateResInt(Ident, anInt: Integer);
constructor CreateResStr(Ident: Integer; const Str1: String);
constructor CreateRes2Str(Ident: Integer; const Str1, Str2: String);
{$IFNDEF UNICODE}
function TheMessage(AsUTF8: boolean): string;
{$ENDIF}
property ResId: Integer Read fResIdent write fResIdent;
property DisplayMsg: boolean Read fDisplayMsg;
end;
type
EZipMaster = class(EZMException)
end;
implementation
uses
ZMMsg19, ZMMsgStr19 {$IFNDEF UNICODE}, ZMUTF819{$ENDIF};
const
ERRORMSG: String = 'Failed to Locate string';
// allow direct translation for negative error values
function Id(err: integer): integer;
begin
Result := err;
if (Result < 0) and (Result >= -TM_SystemError)
and (Result <= -DT_Language) then
Result := -Result;
end;
//constructor EZMException.Create(const msg: String);
//begin
// inherited Create(msg);
// fDisplayMsg := True;
// fResIdent := DS_UnknownError;
//end;
constructor EZMException.CreateDisp(const Message: String; const Display: Boolean);
begin
inherited Create(Message);
fDisplayMsg := Display;
fResIdent := DS_UnknownError;
{$IFNDEF UNICODE}
fArgs := zxaNoStr;
{$ENDIF}
end;
constructor EZMException.CreateResFmt(Ident: Integer; const Args: array of const);
begin
// CreateFmt(Ident, Args);
inherited Create(ERRORMSG);
fResIdent := Id(Ident);
Message := LoadZipStr(fResIdent);
Message := Format(Message, Args);
fDisplayMsg := True;
{$IFNDEF UNICODE}
fArgs := zxaNoStr;
{$ENDIF}
end;
constructor EZMException.CreateResDisp(Ident: Integer; const Display: Boolean);
begin
inherited Create(ERRORMSG);
fResIdent := Id(Ident);
Message := LoadZipStr(fResIdent);
fDisplayMsg := Display;
{$IFNDEF UNICODE}
fArgs := zxaNoStr;
{$ENDIF}
end;
constructor EZMException.CreateResInt(Ident, anInt: Integer);
begin
CreateResFmt(Ident, [anInt]);
end;
constructor EZMException.CreateResStr(Ident: Integer; const Str1: String);
begin
CreateResFmt(Ident, [Str1]);
{$IFNDEF UNICODE}
fArgs := zxaStr;
fStr1 := Str1;
{$ENDIF}
end;
constructor EZMException.CreateRes2Str(Ident: Integer; const Str1, Str2: String);
begin
CreateResFmt(Ident, [Str1, Str2]);
{$IFNDEF UNICODE}
fArgs := zxa2Str;
fStr1 := Str1;
fStr2 := Str2;
{$ENDIF}
end;
{$IFNDEF UNICODE}
function EZMException.TheMessage(AsUTF8: boolean): string;
begin
if not AsUTF8 then
Result := Message
else
begin
if fArgs <= zxaNoStr then
Result := StrToUTF8(Message)
else
begin
Result := LoadZipStr(fResIdent);
if Result <> '' then
begin
// we need the format string as UTF8
Result := StrToUTF8(Result);
case fArgs of
zxaStr:Result := Format(Result, [fStr1]);
zxa2Str:Result := Format(Result, [fStr1, fStr2]);
end;
end;
end;
end;
end;
{$ENDIF}
end.
|
unit mivSettings;
interface
uses
IniFiles;
type
TmivSettings = class(TObject)
private
f_Login: AnsiString;
f_Data: AnsiString;
f_FirstMenuItemURL: String;
f_SecondMenuItemURL: String;
procedure pm_SetData(const Value: AnsiString);
procedure pm_SetFirstMenuItemURL(const Value: String);
procedure pm_SetLogin(const Value: AnsiString);
procedure pm_SetSecondMenuItemURL(const Value: String);
function pm_GetIsValid: Boolean;
public
class function Instance: TmivSettings;
property Login: AnsiString
read f_Login
write pm_SetLogin;
property Data: AnsiString
read f_Data
write pm_SetData;
property FirstMenuItemURL: String
read f_FirstMenuItemURL
write pm_SetFirstMenuItemURL;
property SecondMenuItemURL: String
read f_SecondMenuItemURL
write pm_SetSecondMenuItemURL;
property IsValid: Boolean
read pm_GetIsValid;
end;
TmivSettingsIniValidationResult = (ivrNotExists, ivrNotValidIniFile, ivrOk);
TmivSettingsLoader = class(TObject)
private
f_IniFileName: AnsiString;
f_IniFile: TIniFile;
function pm_GetIniFile: TIniFile;
procedure LoadSettings;
protected
property IniFile: TIniFile
read pm_GetIniFile;
public
function Validate: TmivSettingsIniValidationResult;
constructor Create(const AIniFileName: AnsiString);
destructor Destroy; override;
public
property IniFileName: AnsiString
read f_IniFileName;
end;
implementation
uses
SysUtils;
const
cGarantSectionName = 'garant';
cLoginParamName = 'login';
cDataParamName = 'data';
cMenuSectionName = 'menu';
cFirstMenuItemURLParamName = '1';
cSecondMenuItemURLParamName = '2';
{ TmivSettings }
var
g_mivSettingsInstance : TmivSettings = nil;
procedure TmivSettings_Delete;
begin
if (g_mivSettingsInstance <> nil) then
FreeAndNil(g_mivSettingsInstance);
end;//TmivSettings_Delete
class function TmivSettings.Instance: TmivSettings;
begin
if (g_mivSettingsInstance = nil) then
begin
g_mivSettingsInstance := Create;
AddExitProc(TmivSettings_Delete);
end;
Result := g_mivSettingsInstance;
end;//TmivSettings.Instance
function TmivSettings.pm_GetIsValid: Boolean;
begin
Result := (f_FirstMenuItemURL <> EmptyStr) and (f_SecondMenuItemURL <> EmptyStr);
end;//TmivSettings.pm_GetIsValid
procedure TmivSettings.pm_SetData(const Value: AnsiString);
begin
if (Value <> f_Data) then
f_Data := Value;
end;//TmivSettings.pm_SetData
procedure TmivSettings.pm_SetFirstMenuItemURL(const Value: String);
begin
if (Value <> f_FirstMenuItemURL) then
f_FirstMenuItemURL := Value;
end;//TmivSettings.pm_SetFirstMenuItemURL
procedure TmivSettings.pm_SetLogin(const Value: AnsiString);
begin
if (Value <> f_Login) then
f_Login := Value;
end;//TmivSettings.pm_SetLogin
procedure TmivSettings.pm_SetSecondMenuItemURL(const Value: String);
begin
if (Value <> f_SecondMenuItemURL) then
f_SecondMenuItemURL := Value;
end;//TmivSettings.pm_SetSecondMenuItemURL
{ TmivSettingsLoader }
constructor TmivSettingsLoader.Create(const AIniFileName: AnsiString);
begin
inherited Create;
f_IniFileName := AIniFileName;
end;//TmivSettingsLoader.Create
destructor TmivSettingsLoader.Destroy;
begin
FreeAndNil(f_IniFile);
inherited;
end;//TmivSettingsLoader.Destroy
procedure TmivSettingsLoader.LoadSettings;
begin
with TmivSettings.Instance do
begin
Login := IniFile.ReadString(cGarantSectionName, cLoginParamName, EmptyStr);
Data := IniFile.ReadString(cGarantSectionName, cDataParamName, EmptyStr);
FirstMenuItemURL := IniFile.ReadString(cMenuSectionName,
cFirstMenuItemURLParamName, EmptyStr);
SecondMenuItemURL := IniFile.ReadString(cMenuSectionName,
cSecondMenuItemURLParamName, EmptyStr);
end;//with TmivSettings.Instance
end;//TmivSettingsLoader.LoadSettings
function TmivSettingsLoader.pm_GetIniFile: TIniFile;
begin
if (f_IniFile = nil) and (FileExists(f_IniFileName)) then
f_IniFile := TIniFile.Create(f_IniFileName);
Result := f_IniFile;
end;//TmivSettingsLoader.pm_GetIniFile
function TmivSettingsLoader.Validate: TmivSettingsIniValidationResult;
function lp_ValidateSections: Boolean;
begin
Result := IniFile.SectionExists(cGarantSectionName) and
IniFile.SectionExists(cMenuSectionName);
end;//lp_ValidateSections
function lp_ValidateKeys: Boolean;
begin
Result := IniFile.ValueExists(cGarantSectionname, cDataParamName) and
IniFile.ValueExists(cMenuSectionName, cFirstMenuItemURLParamName) and
IniFile.ValueExists(cMenuSectionName, cSecondMenuItemURLParamName) and
IniFile.ValueExists(cGarantSectionName, cLoginParamName);
end;//lp_ValidateKeys
begin
Result := ivrOk;
if not FileExists(f_IniFileName) then
begin
Result := ivrNotExists;
Exit;
end;//if not FileExists(f_IniFileName)
if not (lp_ValidateSections and lp_ValidateKeys) then
begin
Result := ivrNotValidIniFile;
Exit;
end;//if not (lp_ValidateSections and lp_ValidateKeys)
LoadSettings;
if not TmivSettings.Instance.IsValid then
Result := ivrNotValidIniFile;
end;//TmivSettingsLoader.Validate
end.
|
{
TATIniFile is a helper class that:
- Inherits from TMemIniFile (recommended) or TIniFile
- When inherits from TMemIniFile, it removes double-quotes from strings on reading
- Should NOT be used for saving
TATIniFileSave is another helper class that:
- Should be used for saving
- Writes strings with double-quotes, when needed
}
{$I ViewerOptions.inc}
unit ATxIniFile;
interface
uses
IniFiles;
type
TATIniFile = class({$ifdef MEMINI} TMemIniFile {$else} TIniFile {$endif})
public
procedure WriteString(const Section, Ident, Value: string); override;
procedure DeleteKey(const Section, Ident: string); override;
{$ifdef MEMINI}
function ReadString(const Section, Ident, Default: string): string; override;
{$endif}
end;
type
TATIniFileSave = class(TIniFile)
public
procedure WriteString(const Section, Ident, Value: string); override;
end;
implementation
const
cQuote = '"';
function SQuoted(const S: string): boolean;
begin
Result := (Length(S) >= 2) and
(S[1] = cQuote) and (S[Length(S)] = cQuote);
end;
procedure SQuoteIfNeeded(var S: string);
const
cChars = [cQuote, ' ', #9];
begin
if (S <> '') then
if (S[1] in cChars) or (S[Length(S)] in cChars) then
S := cQuote + S + cQuote;
end;
procedure TATIniFile.WriteString(const Section, Ident, Value: string);
begin
Assert(False, 'TATIniFile.WriteString should not be used');
end;
procedure TATIniFile.DeleteKey(const Section, Ident: string);
begin
Assert(False, 'TATIniFile.DeleteKey should not be used');
end;
{$ifdef MEMINI}
function TATIniFile.ReadString(const Section, Ident, Default: string): string;
begin
Result := inherited ReadString(Section, Ident, Default);
if SQuoted(Result) then
Result := Copy(Result, 2, Length(Result) - 2);
end;
{$endif}
procedure TATIniFileSave.WriteString(const Section, Ident, Value: string);
var
S: string;
begin
S := Value;
SQuoteIfNeeded(S);
try
inherited WriteString(Section, Ident, S);
except
//except for RO files
end
end;
end.
|
PROGRAM TreeSort(INPUT, OUTPUT);
{ Программа сортирует данные с помощью BinTree }
TYPE
Tree = ^Node;
Node = RECORD
Key: CHAR;
Left, Right: Tree;
END;
VAR
Root: Tree;
Ch: CHAR;
BEGIN { TreeSort }
Root := NIL;
NEW(Root);
IF NOT EOLN THEN READ(Ch);
Root^.Key := Ch;
IF NOT EOLN THEN READ(Ch);
NEW(Root^.Left);
Root^.Left^.Key := Ch;
IF NOT EOLN THEN READ(Ch);
NEW(Root^.Right);
Root^.Right^.Key := Ch;
WRITELN(' Left ELMNT: ', Root^.Left^.Key, ' ROOT: ', Root^.Key, ' Right ELMNT: ', Root^.Right^.Key)
END. { TreeSort }
|
//******************************************************************************
//*** Cactus Jukebox ***
//*** ***
//*** (c) Massimo Magnano 2002-2009 ***
//*** ***
//*** ***
//******************************************************************************
// File : CJ_Interfaces.pas
//
// Description : Interfaces declaration that can be accessed by a plugin.
//
//******************************************************************************
unit cj_interfaces;
{$mode delphi}{$H+}
interface
uses Messages;
const
//Icon States
STATE_NORMAL = 0;
STATE_SELECTED = 1;
STATE_DISABLED = 2;
STATE_HIGHLIGHTED = 3;
STATE_DOWN = 4;
//Options Categories
OPT_CAT_LANGUAGE = 1;
//Menu IDs
CJ_MENU_NULL = $0000;
CJ_MAINMENU_ROOT = $0100;
CJ_MAINMENU_FILE = (CJ_MAINMENU_ROOT or $01);
CJ_MAINMENU_LIBRARY = (CJ_MAINMENU_ROOT or $02);
CJ_MAINMENU_PLAYLIST = (CJ_MAINMENU_ROOT or $03);
CJ_MAINMENU_DEVICES = (CJ_MAINMENU_ROOT or $04);
CJ_MAINMENU_PLUGINS = (CJ_MAINMENU_ROOT or $05);
CJ_MAINMENU_HELP = (CJ_MAINMENU_ROOT or $06);
CJ_TRAYMENU_ROOT = $0200;
MSG_ICON_IMGLIST = -1; // MSG_ICON_IMGLIST-MyIndex -> MyIndex in ADefImageList
type
TCJ_MenuItem = Integer;
TCJ_MenuItemClick = procedure (Sender :TCJ_MenuItem) of object;
//(EN) Strange behavior of the abstract classes:
// In order to maintain compatibility with older plugins, new methods in the
// abstract class must always be declared to the last, while in deployment can have any order.
// Obviously research in VT class method is not done by name but by position.
//(IT) Comportamento strano delle classi astratte :
// Per poter mantenere la compatibilità con i vecchi plugin, i nuovi metodi
// nella classe astratta devono essere dichiarati sempre per ultimi, mentre
// nell' implementazione posso avere qualunque ordine.
// Evidentemente la ricerca nella VT della classe di un metodo non viene fatta per nome ma per posizione.
TCJ_Menu = class
public
function Add(Parent :TCJ_MenuItem;
Caption :PChar; OnClick :TCJ_MenuItemClick) :TCJ_MenuItem; virtual; abstract;
function AddSeparator(Parent :TCJ_MenuItem) :TCJ_MenuItem; virtual; abstract;
function Remove(MenuItem :TCJ_MenuItem) :Boolean; virtual; abstract;
function SetCaption(MenuItem :TCJ_MenuItem;
NewCaption :PChar):PChar; virtual; abstract;
function SetEnabled(MenuItem :TCJ_MenuItem; Value :Boolean):Boolean; virtual; abstract;
function SetChecked(MenuItem :TCJ_MenuItem; Value :Boolean):Boolean; virtual; abstract;
function SetIcon(MenuItem :TCJ_MenuItem;
State, NewIcon :Integer):Integer; virtual; abstract;
function SetOnClick(MenuItem :TCJ_MenuItem;
NewOnClick :TCJ_MenuItemClick):TCJ_MenuItemClick; virtual; abstract;
function GetCount(MenuItem :TCJ_MenuItem) :Integer; virtual; abstract;
function GetItem(MenuItem :TCJ_MenuItem; Index :Integer) :TCJ_MenuItem; virtual; abstract;
function GetCaption(MenuItem :TCJ_MenuItem; Buffer :PChar) :Integer; virtual; abstract;
function GetEnabled(MenuItem :TCJ_MenuItem) :Boolean; virtual; abstract;
function GetChecked(MenuItem :TCJ_MenuItem) :Boolean; virtual; abstract;
function GetIcon(MenuItem :TCJ_MenuItem; State :Integer):Integer; virtual; abstract;
function GetOnClick(MenuItem :TCJ_MenuItem):TCJ_MenuItemClick; virtual; abstract;
end;
TCJ_TrayIcon = class
public
procedure AddNotificationIcon(Icon :Integer; //-xxx = Predefs Icons, +xxx = User Icon
Sound :PChar; //%GT-SOUNDS%Predefs Sounds, x:\mmmmm
ShowEverySec :Integer;
DelAfterSec :Integer //-1 = when tray menù appear, 0 = manual
); virtual; abstract;
procedure ShowNotification(AImageList :Integer; Icon :Integer; Msg :PChar; Sound :PChar); virtual; abstract;
procedure PlaySound(Sound :PChar); virtual; abstract;
end;
TCJ_SignalMethod = function (var Message: TMessage):Boolean of object;
{ TCJ_Signals }
TCJ_Signals = class
public
procedure Connect(ClassMethod :TCJ_SignalMethod; MessageID :Integer); virtual; abstract;
procedure ConnectAsync(ClassMethod :TCJ_SignalMethod; MessageID :Integer; Priority :Integer=0); virtual; abstract;
procedure Disconnect(ClassMethod :TCJ_SignalMethod; MessageID :Integer); virtual; overload; abstract;
procedure Disconnect(ClassPointer :TObject); virtual; overload; abstract;
function Signal(MessageID :Cardinal; WParam, LParam :Integer; var Handled :Boolean) :Integer; virtual; overload; abstract;
function Signal(var aMessage: TMessage) :Boolean; virtual; overload; abstract;
end;
TCJ_Interface = class
public
function GetMenu : TCJ_Menu; virtual; abstract;
function GetTrayIcon : TCJ_TrayIcon; virtual; abstract;
function GetSignals : TCJ_Signals; virtual; abstract;
function GetOption(OptionCategoryID :Integer; OptionID :Integer;
Buffer :Pointer):Integer; virtual; abstract;
end;
implementation
end.
|
unit udmItensCartaCorrecao;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS;
type
TdmItensCartaCorrecao = class(TdmPadrao)
qryLocalizacaoFIL_CARTA: TStringField;
qryLocalizacaoNRO_CARTA: TIntegerField;
qryLocalizacaoCOD_OCORRENCIA: TSmallintField;
qryLocalizacaoHISTORICO: TBlobField;
qryLocalizacaoDT_ALTERACAO: TDateTimeField;
qryLocalizacaoOPERADOR: TStringField;
qryLocalizacaoNM_OCORRENCIA: TStringField;
qryManutencaoFIL_CARTA: TStringField;
qryManutencaoNRO_CARTA: TIntegerField;
qryManutencaoCOD_OCORRENCIA: TSmallintField;
qryManutencaoHISTORICO: TBlobField;
qryManutencaoDT_ALTERACAO: TDateTimeField;
qryManutencaoOPERADOR: TStringField;
qryManutencaoNM_OCORRENCIA: TStringField;
qryManutencaoSEQUENCIA: TIntegerField;
qryManutencaoDIGEST_VALUE: TStringField;
qryManutencaoPROTOCOLO: TStringField;
qryManutencaoXML_EVENTO: TBlobField;
qryLocalizacaoSEQUENCIA: TIntegerField;
qryLocalizacaoDIGEST_VALUE: TStringField;
qryLocalizacaoPROTOCOLO: TStringField;
qryLocalizacaoXML_EVENTO: TBlobField;
qryManutencaoTRANSMITIDO: TStringField;
qryLocalizacaoTRANSMITIDO: TStringField;
protected
procedure MontaSQLBusca(DataSet: TDataSet = nil); override;
procedure MontaSQLRefresh; override;
private
FCod_Ocorrencia: Integer;
FNro_Carta: Real;
FEmissora: string;
FFilial: string;
FDocumento: string;
FNumero: Real;
public
property Emissora: string read FEmissora write FEmissora;
property Nro_Carta: Real read FNro_Carta write FNro_Carta;
property Cod_Ocorrencia: Integer read FCod_Ocorrencia write FCod_Ocorrencia;
property Documento: string read FDocumento write FDocumento;
property Filial: string read FFilial write FFilial;
property Numero: Real read FNumero write FNumero;
function LocalizarPorCarta(DataSet: TDataSet = nil; ANaoProtocolado: Boolean = False): Boolean;
function LocalizarUltimaCorrecaoDocumento(DataSet: TDataSet = nil): Boolean;
function LocalizarTodasCorrecoesDocumento(DataSet: TDataSet = nil): Boolean;
function GerarSequencia(DataSet: TDataSet = nil): Integer;
end;
const
SQL_DEFAULT =
' SELECT ' +
' ICC.FIL_CARTA, ' +
' ICC.NRO_CARTA, ' +
' ICC.COD_OCORRENCIA, ' +
' ICC.HISTORICO, ' +
' ICC.DT_ALTERACAO, ' +
' ICC.OPERADOR, ' +
' ICC.SEQUENCIA, ' +
' ICC.DIGEST_VALUE, ' +
' ICC.PROTOCOLO, ' +
' ICC.XML_EVENTO, ' +
' OCO.DESCRICAO NM_OCORRENCIA, ' +
' CASE WHEN COALESCE(ICC.PROTOCOLO, '''') <> '''' THEN ''T'' ELSE ''F'' END TRANSMITIDO ' +
' FROM STWFATTITMC ICC ' +
' LEFT JOIN STWFATTOCOR OCO ON OCO.CODIGO = ICC.COD_OCORRENCIA ';
var
dmItensCartaCorrecao: TdmItensCartaCorrecao;
implementation
{$R *.dfm}
{ TdmItensCartaCorrecao }
function TdmItensCartaCorrecao.GerarSequencia(DataSet: TDataSet): Integer;
begin
if DataSet = nil then
DataSet := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
Close;
SQL.Clear;
SQL.Add('SELECT MAX(SEQUENCIA) + 1 as SEQUENCIA FROM STWFATTITMC ICC ');
SQL.Add(' WHERE ICC.FIL_CARTA = :FIL_CARTA');
SQL.Add(' AND ICC.NRO_CARTA = :NRO_CARTA');
ParamByName('FIL_CARTA').AsString := FEmissora;
ParamByName('NRO_CARTA').AsFloat := FNro_Carta;
Open;
Result := DataSet.FieldByName('SEQUENCIA').AsInteger;
end;
end;
function TdmItensCartaCorrecao.LocalizarPorCarta(DataSet: TDataSet; ANaoProtocolado: Boolean): Boolean;
begin
if DataSet = nil then
DataSet := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
Close;
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE ICC.FIL_CARTA = :FIL_CARTA');
SQL.Add(' AND ICC.NRO_CARTA = :NRO_CARTA');
if ANaoProtocolado then
SQL.Add('AND COALESCE(ICC.PROTOCOLO, '''') = '''' ');
SQL.Add('ORDER BY ICC.FIL_CARTA, ICC.NRO_CARTA, ICC.SEQUENCIA DESC, ICC.COD_OCORRENCIA');
ParamByName('FIL_CARTA').AsString := FEmissora;
ParamByName('NRO_CARTA').AsFloat := FNro_Carta;
Open;
Result := not IsEmpty;
end;
end;
function TdmItensCartaCorrecao.LocalizarTodasCorrecoesDocumento(
DataSet: TDataSet): Boolean;
begin
if DataSet = nil then
DataSet := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
Close;
SQL.Clear;
SQL.Add(StringReplace(SQL_DEFAULT, 'SELECT ', 'SELECT ', []));
SQL.Add('WHERE EXISTS (SELECT * FROM STWFATTCRTA CAR ');
SQL.Add(' WHERE CAR.FIL_CARTA = ICC.FIL_CARTA');
SQL.Add(' AND CAR.NRO_CARTA = ICC.NRO_CARTA');
SQL.Add(' AND CAR.CTO_DOCUMENTO = :DOCUMENTO');
SQL.Add(' AND CAR.CTO_FILIAL = :FILIAL');
SQL.Add(' AND CAR.CTO_NUMERO = :NUMERO');
SQL.Add(')');
SQL.Add('ORDER BY ICC.FIL_CARTA, ICC.NRO_CARTA, ICC.SEQUENCIA DESC, ICC.COD_OCORRENCIA');
ParamByName('DOCUMENTO').AsString := FDocumento;
ParamByName('FILIAL').AsString := FFilial;
ParamByName('NUMERO').AsFloat := FNumero;
Open;
Result := not IsEmpty;
end;
end;
function TdmItensCartaCorrecao.LocalizarUltimaCorrecaoDocumento(DataSet: TDataSet): Boolean;
begin
if DataSet = nil then
DataSet := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
Close;
SQL.Clear;
SQL.Add(StringReplace(SQL_DEFAULT, 'SELECT ', 'SELECT FIRST(1) ', []));
SQL.Add('WHERE EXISTS (SELECT * FROM STWFATTCRTA CAR ');
SQL.Add(' WHERE CAR.FIL_CARTA = ICC.FIL_CARTA');
SQL.Add(' AND CAR.NRO_CARTA = ICC.NRO_CARTA');
SQL.Add(' AND CAR.CTO_DOCUMENTO = :DOCUMENTO');
SQL.Add(' AND CAR.CTO_FILIAL = :FILIAL');
SQL.Add(' AND CAR.CTO_NUMERO = :NUMERO');
SQL.Add(')');
SQL.Add('ORDER BY ICC.FIL_CARTA, ICC.NRO_CARTA, ICC.SEQUENCIA DESC, ICC.COD_OCORRENCIA');
ParamByName('DOCUMENTO').AsString := FDocumento;
ParamByName('FILIAL').AsString := FFilial;
ParamByName('NUMERO').AsFloat := FNumero;
Open;
Result := not IsEmpty;
end;
end;
procedure TdmItensCartaCorrecao.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE ICC.FIL_CARTA = :FIL_CARTA');
SQL.Add(' AND ICC.NRO_CARTA = :NRO_CARTA');
SQL.Add(' AND ICC.COD_OCORRENCIA = :COD_OCORRENCIA');
SQL.Add('ORDER BY ICC.FIL_CARTA, ICC.NRO_CARTA, ICC.COD_OCORRENCIA');
Params[0].AsString := FEmissora;
Params[1].AsFloat := FNro_Carta;
Params[2].AsInteger := FCod_Ocorrencia;
end;
end;
procedure TdmItensCartaCorrecao.MontaSQLRefresh;
begin
inherited;
with qryManutencao do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('ORDER BY ICC.FIL_CARTA, ICC.NRO_CARTA, ICC.COD_OCORRENCIA');
end;
end;
end.
|
unit InventionSets;
interface
const
BitCount = 8;
type
Bits = 0..BitCount-1;
TBitSet = set of Bits;
PInventionIdArray = ^TInventionIdArray;
TInventionIdArray = array[0..$FFFF div BitCount] of TBitSet;
TInventionNumId = integer;
TInventionSet =
class
public
constructor Create(IniCount : integer);
destructor Destroy; override;
private
fSets : PInventionIdArray;
private
function CountToSets(count : integer) : integer;
function Capacity : integer;
procedure Decompose(Elem : TInventionNumId; var Index : integer; var Value : Bits);
public
function Include(Elem : TInventionNumId) : boolean;
function Exclude(Elem : TInventionNumId) : boolean;
function Included(Elem : TInventionNumId) : boolean;
end;
implementation
uses
SysUtils;
type
pinteger = ^integer;
// TInventionSet
constructor TInventionSet.Create(IniCount : integer);
var
size : integer;
begin
inherited Create;
size := CountToSets(IniCount)*sizeof(fSets[0]);
ReallocMem(fSets, size);
if fSets <> nil
then FillChar(fSets[0], Capacity*sizeof(fSets[0]), 0);
end;
destructor TInventionSet.Destroy;
begin
ReallocMem(fSets, 0);
inherited;
end;
function TInventionSet.CountToSets(count : integer) : integer;
begin
result := succ(count div BitCount);
end;
function TInventionSet.Capacity : integer;
begin
if fSets <> nil
then result := (pinteger(pchar(fSets)-4)^ - 6) div sizeof(fSets[0])
else result := 0;
end;
procedure TInventionSet.Decompose(Elem : TInventionNumId; var Index : integer; var Value : Bits);
begin
Index := Elem div BitCount;
Value := Elem mod BitCount;
end;
function TInventionSet.Include(Elem : TInventionNumId) : boolean;
var
idx : integer;
val : Bits;
OldCap : integer;
NewCap : integer;
begin
Decompose(Elem, idx, val);
if idx >= Capacity
then
begin
OldCap := Capacity;
ReallocMem(fSets, succ(idx)*sizeof(fSets[0]));
NewCap := Capacity;
FillChar(fSets[OldCap], (NewCap - OldCap)*sizeof(fSets[0]), 0);
end;
if val in fSets[idx]
then result := false
else
begin
System.Include(fSets[idx], val);
result := true;
end;
end;
function TInventionSet.Exclude(Elem : TInventionNumId) : boolean;
var
idx : integer;
val : Bits;
begin
Decompose(Elem, idx, val);
if idx < Capacity
then
begin
result := val in fSets[idx];
System.Exclude(fSets[idx], val);
end
else result := false;
end;
function TInventionSet.Included(Elem : TInventionNumId) : boolean;
var
idx : integer;
val : Bits;
begin
Decompose(Elem, idx, val);
if idx < Capacity
then result := val in fSets[idx]
else result := false;
end;
end.
|
(*
* Copyright (c) 2010-2020, Alexandru Ciobanu (alex+git@ciobanu.org)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of this library nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
program TZView;
{$INCLUDE '../TZDBPK/Version.inc'}
{$IFDEF DELPHI}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
SysUtils,
DateUtils,
Character,
Classes,
Types,
StrUtils,
{$IFNDEF FPC}
Generics.Collections,
Generics.Defaults,
{$ELSE}
FGL,
{$ENDIF}
TZDB in '../TZDBPK/TZDB.pas';
const
CDateTimePatterns: array[0..4] of string = (
'now',
'yyyy-MM-dd',
'yyyy-MM-dd hh:mm',
'yyyy-MM-dd hh:mm:ss',
'yyyy-MM-dd hh:mm:ss.zzz'
);
COutDateTimeFormat = 'yyyy-MM-dd hh:mm:ss.zzz';
function TryScanDateTime(const AStr: string; out ADateTime: TDateTime): boolean;
var
I: Integer;
begin
if SameText(AStr, 'now') then
begin
ADateTime := Now;
Exit(true);
end;
for I := Length(CDateTimePatterns) - 1 downto 1 do
try
ADateTime := ScanDateTime(CDateTimePatterns[I], AStr);
Exit(true);
except
end;
Result := false;
end;
function FormatOffset(AOffset: Int64): string;
var
LHours, LMinutes, LSeconds: Integer;
LSign: Char;
begin
if AOffset = 0 then
Result := '0'
else begin
if AOffset < 0 then
LSign := '-' else LSign := '+';
AOffset := Abs(AOffset);
LHours := AOffset div 3600;
LMinutes := (AOffset mod 3600) div 60;
LSeconds := AOffset mod 60;
Result := LSign;
if LHours > 0 then
Result := Result + IntToStr(LHours) + 'h';
if LMinutes > 0 then
Result := Result + IntToStr(LMinutes) + 'm';
if LSeconds > 0 then
Result := Result + IntToStr(LSeconds) + 's';
end;
end;
procedure PrintHeaderAndExit;
var
I: Integer;
begin
WriteLn('tzview - view and compare time zone data. (c) 2019 Alexandru Ciobanu (alex+git@ciobanu.org).');
WriteLn('database v', TBundledTimeZone.DbVersion, ' provided by IANA (https://www.iana.org/time-zones).');
WriteLn('usage: tzview command [options...]');
WriteLn(' tzview list [all|aliases|tz] -- lists all known time zones or aliases, or both.');
WriteLn(' tzview dump <timezone> <year> -- deconstructs a time zone for a given year.');
WriteLn(' tzview local <timezone> <date> -- displays info on a given local date/time.');
WriteLn(' tzview utc <timezone> <date> -- displays info on a given UTC date/time.');
WriteLn;
WriteLn('accepted date/time patterns:');
for I := 0 to Length(CDateTimePatterns) - 1 do
WriteLn(' ', CDateTimePatterns[I]);
Halt(1);
end;
procedure ErrorAndExit(const AMessage: string);
begin
WriteLn('[ERR] ' + AMessage);
Halt(2);
end;
var
LYear: Integer;
LDate: TDateTime;
LTimeZones: TStringDynArray;
LCommand: string;
S: string;
LTZ: TBundledTimeZone;
LSegment: TYearSegment;
begin
if (ParamCount >= 1) then
LCommand := Trim(ParamStr(1));
if SameText(LCommand, 'list') then
begin
if (ParamCount < 2) then
ErrorAndExit('The "list" command expects two other arguments.');
if ParamStr(2) = 'all' then
LTimeZones := TBundledTimeZone.KnownTimeZones
else if ParamStr(2) = 'tz' then
LTimeZones := TBundledTimeZone.KnownTimeZones(false)
else if ParamStr(2) = 'aliases' then
LTimeZones := TBundledTimeZone.KnownAliases
else
ErrorAndExit('The "list" command expects either "all", "tz" or "aliases".');
for S in LTimeZones do
WriteLn(S);
end else if SameText(LCommand, 'dump') then
begin
if (ParamCount < 2) then
ErrorAndExit('The "view" command expects two other arguments.');
if (not TryStrToInt(Trim(ParamStr(3)), LYear)) then
ErrorAndExit('The "view" command expects a valid year.');
S := Trim(ParamStr(2));
try
LTZ := TBundledTimeZone.Create(S);
if not SameText(LTZ.ID, S) then
WriteLn(S + ' (' + LTZ.ID + '):')
else
WriteLn(LTZ.ID + ':');
WriteLn(
PadRight('Period', 10),
PadRight('Start (Local)', 25),
PadRight('End (Local)', 25),
PadRight('Abbrv.', 10),
'Bias'
);
for LSegment in LTZ.GetYearBreakdown(LYear) do
begin
case LSegment.LocalType of
lttStandard: S := 'Standard';
lttDaylight: S := 'Daylight';
lttAmbiguous: S := 'Ambiguous';
lttInvalid: S := 'Invalid';
end;
WriteLn(
PadRight(S, 10),
PadRight(FormatDateTime(COutDateTimeFormat, LSegment.StartsAt), 25),
PadRight(FormatDateTime(COutDateTimeFormat, LSegment.EndsAt), 25),
PadRight(LSegment.DisplayName, 10),
FormatOffset(LSegment.UtcOffset)
);
end;
except
on E: ETimeZoneInvalid do
ErrorAndExit('The time zone "' + S + '" cannot be found.');
on E: EUnknownTimeZoneYear do
ErrorAndExit('The time zone "' + S + '" does not have data for year ' + IntToStr(LYear) + '.');
end;
end else if SameText(LCommand, 'local') or SameText(LCommand, 'utc') then
begin
if (ParamCount < 2) then
ErrorAndExit('The "' + LCommand + '" command expects two other arguments.');
if (not TryScanDateTime(Trim(ParamStr(3)), LDate)) then
ErrorAndExit('The "' + LCommand + '" command expects a valid date/time.');
S := Trim(ParamStr(2));
try
LTZ := TBundledTimeZone.Create(S);
if SameText(LCommand, 'utc') then
LDate := LTZ.ToLocalTime(LDate);
case LTZ.GetLocalTimeType(LDate) of
lttStandard: S := 'Standard';
lttDaylight: S := 'Daylight';
lttAmbiguous: S := 'Ambiguous';
lttInvalid: S := 'Invalid';
end;
WriteLn(
PadRight('Period', 10),
PadRight('Local', 25),
PadRight('UTC', 25),
PadRight('Abbrv.', 10),
PadRight('Name', 10),
'Bias'
);
if LTZ.GetLocalTimeType(LDate) = lttInvalid then
begin
WriteLn(
PadRight(S, 10),
PadRight(FormatDateTime(COutDateTimeFormat, LDate), 25),
PadRight('', 25),
PadRight('', 10),
PadRight('', 10)
);
end else
begin
WriteLn(
PadRight(S, 10),
PadRight(FormatDateTime(COutDateTimeFormat, LDate), 25),
PadRight(FormatDateTime(COutDateTimeFormat, LTZ.ToUniversalTime(LDate)), 25),
PadRight(LTZ.GetAbbreviation(LDate), 10),
PadRight(LTZ.GetDisplayName(LDate), 10),
FormatOffset(LTZ.GetUtcOffset(LDate))
);
end;
except
on E: ETimeZoneInvalid do
ErrorAndExit('The time zone "' + S + '" cannot be found.');
on E: EUnknownTimeZoneYear do
ErrorAndExit('The time zone "' + S + '" does not have data for date ' + ParamStr(3) + '.');
end;
end
else PrintHeaderAndExit;
end.
|
unit uProtocolo;
interface
uses System.Classes, System.SysUtils, Synautil;
type
EProtocoloError = class(Exception);
TOperacaoProtocolo = (opIncluir = 1, opAlterar, opExcluir, opListar);
TProtocoloRequisicao = class
private
FOperacao: TOperacaoProtocolo;
FModel: string;
FMensagem: string;
public
class function CreateFromString(cmd: string): TProtocoloRequisicao;
class function GetOperacaoFromString(ATipo: string): TOperacaoProtocolo;
property Operacao: TOperacaoProtocolo read FOperacao;
property Model: string read FModel;
property Mensagem: string read FMensagem;
end;
TStatusProtocolo = (spOk = 1, spErro);
TProtocoloResposta = class
private
FStatus: TStatusProtocolo;
FMensagem: string;
public
class function CreateFromString(cmd: string): TProtocoloResposta;
property Status: TStatusProtocolo read FStatus;
property Mensagem: string read FMensagem;
end;
const
OPERACAO_INCLUIR = 'INCLUIR';
OPERACAO_ALTERAR = 'ALTERAR';
OPERACAO_EXCLUIR = 'EXCLUIR';
OPERACAO_LISTAR = 'LISTAR';
FORMAT_PROTOCOLO_REQ = '%s_%s %s';
FORMAT_PROTOCOLO_RESP = '%s %s';
STATUS_OK = 'OK';
STATUS_ERRO = 'ERRO';
TOperacaoProtocoloString: array[TOperacaoProtocolo] of string = (OPERACAO_INCLUIR,
OPERACAO_ALTERAR, OPERACAO_EXCLUIR, OPERACAO_LISTAR);
TStatusProtocoloString: array[TStatusProtocolo] of string = (STATUS_OK,
STATUS_ERRO);
implementation
{ TProtocolo }
uses uMJD.Messages;
class function TProtocoloRequisicao.CreateFromString(cmd: string): TProtocoloRequisicao;
var Parte, Operacao: string;
begin
if (cmd = '') then
raise EProtocoloError.Create(rsProtocoloNaoInformado);
Result := TProtocoloRequisicao.Create();
Parte := Fetch(cmd, ' ');
Operacao := Fetch(Parte, '_');
Result.FOperacao := TProtocoloRequisicao.GetOperacaoFromString(Operacao);
Result.FModel := Fetch(Parte, '_');
Result.FMensagem := cmd;
end;
class function TProtocoloRequisicao.GetOperacaoFromString(
ATipo: string): TOperacaoProtocolo;
begin
if AnsiSameText(ATipo, OPERACAO_INCLUIR) then
Result := opIncluir
else if AnsiSameText(ATipo, OPERACAO_ALTERAR) then
Result := opAlterar
else if AnsiSameText(ATipo, OPERACAO_EXCLUIR) then
Result := opExcluir
else if AnsiSameText(ATipo, OPERACAO_LISTAR) then
Result := opListar
else
raise EProtocoloError.CreateFmt(rsOperacaoNaoSuportada, [ATipo]);
end;
{ TProtocoloResposta }
class function TProtocoloResposta.CreateFromString(
cmd: string): TProtocoloResposta;
var Parte: string;
begin
if (cmd = '') then
raise EProtocoloError.Create(rsProtocoloNaoInformado);
Result := TProtocoloResposta.Create();
Parte := Fetch(cmd, ' ');
if AnsiSameText(Parte, STATUS_OK) then
Result.FStatus := spOk
else if AnsiSameText(Parte, STATUS_ERRO) then
Result.FStatus := spErro
else
raise EProtocoloError.CreateFmt(rsStatusNaoSuportado, [Parte]);
Result.FMensagem := cmd;
end;
end.
|
unit Langs;
interface
uses
Windows, SysUtils, Graphics, Classes;
type
TLanguage = 0..$FFFF;
TLangOption = (loLocalized, loEnglish, loNative, loAbbrev);
function LanguageName(Language: TLanguage): String;
function CharSetFromLocale(Language: TLanguage): TFontCharSet;
function CodePageFromLocale(Language: TLanguage): Integer;
{$IfDef DisignTime}
procedure Register;
{$EndIf DisignTime}
implementation
{$IfDef DisignTime}
uses
DsgnIntf;
type
TLanguageProperty = class(TIntegerProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(TLanguage), nil, '', TLanguageProperty);
end;
{$EndIf DisignTime}
function LanguageName(Language: TLanguage): String;
var
Buf: array[0..255] of Char;
begin
GetLocaleInfo(Language, LOCALE_SLanguage, Buf, 255);
Result:= StrPas(Buf);
end;
function CodePageFromLocale(Language: TLanguage): Integer;
var
Buf: array[0..6] of Char;
begin
GetLocaleInfo(Language, LOCALE_IDefaultAnsiCodePage, Buf, 6);
Result:= StrToIntDef(Buf, GetACP);
end;
function CharSetFromLocale(Language: TLanguage): TFontCharSet;
var
CP: Integer;
begin
CP:= CodePageFromLocale(Language);
{ The proper solution is to use TranslateCharsetInfo. This function
is described to be exported from user32.dll, but this works
only in Windows NT. In Windows 95 this function is absent. So...
}
case CP of
1250:
Result:= EastEurope_CharSet;
1251:
Result:= Russian_CharSet;
1252:
Result:= Ansi_CharSet;
1253:
Result:= Turkish_CharSet;
1254:
Result:= Greek_CharSet;
1255:
Result:= Hebrew_CharSet;
1256:
Result:= Arabic_CharSet;
1257:
Result:= Baltic_CharSet;
1258:
Result:= Vietnamese_CharSet;
end;
end;
function LanguageToIdent(Language: Longint; var Ident: string): Boolean;
var
Buf: array[0..255]of Char;
begin
Result:= IsValidLocale(Language, LCID_INSTALLED);
if Result then
begin
GetLocaleInfo(Language, LOCALE_SLANGUAGE, Buf, 255);
SetString(Ident, Buf, StrLen(Buf));
end;
end;
var
SearchId: String;
SearchLang: Integer;
LCType: Integer;
function EnumGetLang(LocaleStr: LPSTR): Integer;
stdcall;
var
Buf: array[0..255]of Char;
Locale: LCID;
Z: Integer;
begin
Val('$'+StrPas(LocaleStr), Locale, Z);
Result:= 1;
GetLocaleInfo(Locale, LCType, Buf, 255);
if AnsiCompareText(SearchId, Buf)=0 then
begin
SearchLang:= Locale;
Result:= 0;
end;
end;
function IdentToLanguage(const Ident: string; var Language: Longint): Boolean;
begin
SearchId:= Ident;
SearchLang:= -1;
LCType:= LOCALE_SLANGUAGE;
EnumSystemLocales(@EnumGetLang, LCID_INSTALLED);
if SearchLang<0 then
begin
LCType:= LOCALE_SENGLANGUAGE;
EnumSystemLocales(@EnumGetLang, LCID_INSTALLED);
end;
if SearchLang<0 then
begin
LCType:= LOCALE_SABBREVLANGNAME;
EnumSystemLocales(@EnumGetLang, LCID_INSTALLED);
end;
Result:= SearchLang>-1;
if Result then
Language:= SearchLang;
end;
{$IfDef DisignTime}
function TLanguageProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paSortList, paValueList];
end;
function TLanguageProperty.GetValue: string;
begin
if not LanguageToIdent(TLanguage(GetOrdValue), Result) then
FmtStr(Result, '%d', [GetOrdValue]);
end;
var
GetStrProc: TGetStrProc;
function EnumGetValues(LocaleStr: LPSTR): Integer;
stdcall;
var
Buf: array[0..255]of Char;
Locale: LCID;
Z: Integer;
begin
Val('$'+StrPas(LocaleStr), Locale, Z);
GetLocaleInfo(Locale, LOCALE_SLANGUAGE, Buf, 255);
GetStrProc(Buf);
Result:= 1;
end;
procedure TLanguageProperty.GetValues(Proc: TGetStrProc);
begin
GetStrProc:= Proc;
EnumSystemLocales(@EnumGetValues, LCID_INSTALLED);
end;
procedure TLanguageProperty.SetValue(const Value: string);
var
NewValue: Longint;
begin
if IdentToLanguage(Value, NewValue) then
SetOrdValue(NewValue)
else inherited SetValue(Value);
end;
{$EndIf DisignTime}
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Description: Multi-threaded socket server component derived from TWSocketServer
Based on code written by Arno Garrels, Berlin, Germany,
contact: <arno.garrels@gmx.de>
Creation: November 2005
Version: 7.02
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2005-2012 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium.
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
History:
Mar 06, 2006 A. Garrels: Fixed synchronisation in ClientAttachThread and
TriggerClientDisconnect. Multi-threading: OpenSSL library is
thread safe as long as the application provides an appropriate
locking callback. Implemented such callbacks as two components
see unit IcsSslThrdLock and changed TSslWSocketThrdServer to
use TSslDynamicLock.
Apr 09, 2012 V7.02 Arno - 64-bit and message handling fix.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsWSocketTS;
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$H+} { Use long strings }
{$J+} { Allow typed constant to be modified }
{$I OVERBYTEICSDEFS.INC}
{$IFDEF DELPHI6_UP}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
{$IFDEF BCB3_UP}
{$ObjExportAll On}
{$ENDIF}
interface
uses
Messages,
{$IFDEF USEWINDOWS}
Windows,
{$ELSE}
WinTypes, WinProcs,
{$ENDIF}
SysUtils, Classes, OverbyteIcsWSocket, OverbyteIcsWSocketS,
{$IFDEF USE_SSL}
OverbyteIcsSSLEAY, OverbyteIcsLIBEAY, OverbyteIcsSslThrdLock,
{$ENDIF}
OverbyteIcsWinsock;
const
WSocketThrdServerVersion = 700;
CopyRight : String = ' TWSocketThrdServer (c) 2005-2010 F. Piette V7.00 ';
WM_THREAD_BASE_MSG = WM_USER + 100;
WM_THREAD_ADD_CLIENT = WM_THREAD_BASE_MSG + 0;
WM_THREAD_REMOVE_CLIENT = WM_THREAD_BASE_MSG + 1;
WM_THREAD_TERMINATE = WM_THREAD_BASE_MSG + 2;
WM_THREAD_DISCONNECT_ALL = WM_THREAD_BASE_MSG + 5;
WM_THREAD_EXCEPTION_TEST = WM_THREAD_BASE_MSG + 7;
type
TWSocketThrdServer = class;
TWSocketThrdClient = class;
TWsClientThreadEventID = (cteiClientAttached,
cteiClientRemoved,
cteiThreadUnlock,
cteiThreadReady);
TWsClientThread = class(TThread)
private
FReadyForMsgs : Boolean;
FServer : TWSocketThrdServer;
FClients : TList;
FEventArray : array [TWsClientThreadEventID] of THandle;
protected
procedure DetachClient(Client: TWSocketThrdClient);
procedure AttachClient(Client: TWSocketThrdClient);
procedure DisconnectAll;
procedure PumpMessages(WaitForMessages : Boolean); virtual;
procedure Execute; override;
function GetClientCount : Integer;
public
constructor Create(Suspended : Boolean);
destructor Destroy; override;
property ClientCount : Integer read GetClientCount;
property ReadyForMsgs : Boolean read FReadyForMsgs;
end;
TWsClientThreadClass = class of TWsClientThread;
TWSocketThrdClient = class(TWSocketClient)
protected
FServer : TWSocketThrdServer;
FClientThread : TWsClientThread;
FMsg_WM_THREAD_START_CNX : UINT;
procedure AllocateMsgHandlers; override;
procedure FreeMsgHandlers; override;
function MsgHandlersCount: Integer; override;
procedure WndProc(var MsgRec: TMessage); override;
procedure WMThreadStartCnx(var Msg: TMessage);
public
procedure StartConnection; override;
property ClientThread : TWsClientThread read FClientThread;
end;
TThreadCreate = procedure(Sender : TObject;
AThread : TWsClientThread) of object;
TBeforeThreadDestroy = procedure(Sender : TObject;
AThread : TWsClientThread) of object;
TClientAttached = procedure(Sender : TObject;
AClient : TWSocketThrdClient;
AThread : TWsClientThread) of object;
TClientDetached = procedure(Sender : TObject;
AClient : TWSocketThrdClient;
AThread : TWsClientThread) of object;
TThreadExceptionEvent = procedure(Sender : TObject;
AThread : TWsClientThread;
const AErrMsg : String) of object;
TWSocketThrdServer = class(TWSocketServer)
private
FThreadList : TList;
FClientsPerThread : Integer;
FClientThreadClass : TWSClientThreadClass;
FThreadCount : Integer;
FMsg_WM_THREAD_TERMINATED : UINT;
FMsg_WM_THREAD_EXCEPTION : UINT;
FOnThreadCreate : TThreadCreate;
FOnBeforeThreadDestroy : TBeforeThreadDestroy;
FOnClientAttached : TClientAttached;
FOnClientDetached : TClientDetached;
FOnThreadException : TThreadExceptionEvent;
protected
procedure AllocateMsgHandlers; override;
procedure FreeMsgHandlers; override;
function MsgHandlersCount: Integer; override;
procedure WndProc(var MsgRec: TMessage); override;
procedure WmThreadTerminated(var Msg: TMessage);
procedure WmThreadException(var Msg: TMessage);
function ClientAttachThread(Client: TWSocketThrdClient): TWSClientThread;
function AcquireThread: TWsClientThread; virtual;
procedure TerminateThreads;
procedure SetClientsPerThread(const Value : Integer);
procedure TriggerClientCreate(Client : TWSocketClient); override;
procedure TriggerClientDisconnect(Client : TWSocketClient;
ErrCode : Word); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DisconnectAll; override;
property ThreadCount : Integer read FThreadCount;
property ClientThreadClass : TWsClientThreadClass
read FClientThreadClass
write FClientThreadClass;
published
property ClientsPerThread : Integer read FClientsPerThread
write SetClientsPerThread;
property OnThreadCreate : TThreadCreate
read FOnThreadCreate
write FOnThreadCreate;
property OnBeforeThreadDestroy : TBeforeThreadDestroy
read FOnBeforeThreadDestroy
write FOnBeforeThreadDestroy;
property OnClientAttached : TClientAttached
read FOnClientAttached
write FOnClientAttached;
property OnClientDetached : TClientDetached
read FOnClientDetached
write FOnClientDetached;
property OnThreadException : TThreadExceptionEvent
read FOnThreadException
write FOnThreadException;
end;
{$IFDEF USE_SSL}
TSslWSocketThrdClient = class(TWSocketThrdClient)
protected
procedure WndProc(var MsgRec: TMessage); override;
procedure WMThreadStartCnx(var Msg: TMessage);
end;
TSslWSocketThrdServer = class(TWSocketThrdServer)
protected
FSslLock : TSslDynamicLock;
procedure TriggerClientConnect(Client : TWSocketClient; Error : Word); override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Listen; override;
property ClientClass;
property ClientCount;
property Client;
property SslMode;
published
property SslContext;
property Banner;
property BannerTooBusy;
property MaxClients;
property OnClientDisconnect;
property OnClientConnect;
property SslEnable;
property SslAcceptableHosts;
property OnSslVerifyPeer;
property OnSslSetSessionIDContext;
property OnSslSvrNewSession;
property OnSslSvrGetSession;
property OnSslHandshakeDone;
end;
{$ENDIF}
//procedure Register;
implementation
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
(*
procedure Register;
begin
RegisterComponents('FPiette', [TWSocketThrdServer
{$IFDEF USE_SSL}
, TSslWSocketThrdServer
{$ENDIF}
]);
end;
*)
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
(*
var
DbLock : TRtlCriticalSection;
procedure LogDebug(const Msg: string);
begin
if IsConsole then
begin
EnterCriticalSection(DbLock);
try
WriteLn('T: ' + IntToHex(GetCurrentThreadID, 8) + ' C: ' + Msg);
finally
LeaveCriticalSection(DbLock);
end;
end;
end;
*)
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TWSocketThrdServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClientsPerThread := 1;
FThreadList := TList.Create;
FClientThreadClass := TWsClientThread;
FClientClass := TWSocketThrdClient;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWSocketThrdServer.MsgHandlersCount : Integer;
begin
Result := 2 + inherited MsgHandlersCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.AllocateMsgHandlers;
begin
inherited AllocateMsgHandlers;
FMsg_WM_THREAD_TERMINATED := FWndHandler.AllocateMsgHandler(Self);
FMsg_WM_THREAD_EXCEPTION := FWndHandler.AllocateMsgHandler(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.FreeMsgHandlers;
begin
if Assigned(FWndHandler) then begin
FWndHandler.UnregisterMessage(FMsg_WM_THREAD_TERMINATED);
FWndHandler.UnregisterMessage(FMsg_WM_THREAD_EXCEPTION);
end;
inherited FreeMsgHandlers;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.WmThreadTerminated(var Msg: TMessage);
var
AThread : TWsClientThread;
I : Integer;
begin
AThread := TWsClientThread(Msg.WParam);
I := FThreadList.IndexOf(AThread);
if I >= 0 then
FThreadList.Delete(I);
if Assigned(FOnBeforeThreadDestroy) then
FOnBeforeThreadDestroy(Self, AThread);
FThreadCount := FThreadList.Count;
if Assigned(AThread) then
AThread.Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.TerminateThreads;
var
AThread : TWsClientThread;
I : Integer;
begin
for I := 0 to FThreadList.Count - 1 do begin
AThread := TWsClientThread(FThreadList[I]);
if not PostThreadMessage(AThread.ThreadID,
WM_THREAD_TERMINATE, 0, 0) then
raise Exception.Create('PostThreadMessage ' +
SysErrorMessage(GetLastError));
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TWSocketThrdServer.Destroy;
var
WaitRes : LongWord;
Dummy : Byte;
Msg : tagMsg;
begin
Close; // while waiting for our threads do not accept any new client!!
try
TerminateThreads; // may raise, otherwise wait below would loop infinite
if FThreadList.Count > 0 then
repeat
WaitRes := MsgWaitForMultipleObjects(0, Dummy, FALSE, 500,
QS_POSTMESSAGE or QS_SENDMESSAGE);
if WaitRes = WAIT_FAILED then
raise Exception.Create('Wait for threads failed ' +
SysErrorMessage(GetLastError))
else if WaitRes = WAIT_OBJECT_0 then
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
until FThreadList.Count = 0;
finally
inherited Destroy;
FreeAndNil(FThreadList);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.DisconnectAll;
var
I : Integer;
begin
for I := 0 to FThreadList.Count - 1 do begin
PostThreadMessage(TThread(FThreadList[I]).ThreadID,
WM_THREAD_DISCONNECT_ALL, 0, 0);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWSocketThrdServer.AcquireThread: TWsClientThread;
var
I : Integer;
begin
for I := 0 to FThreadList.Count - 1 do begin
Result := TWSClientThread(FThreadList[I]);
if (Result.ClientCount < FClientsPerThread) and
(not Result.Terminated) then
Exit; //***
end;
Result := FClientThreadClass.Create(FALSE); // create suspended not required
Result.OnTerminate := nil;
Result.FreeOnTerminate := FALSE;
Result.FServer := TWSocketThrdServer(Self);
FThreadList.Add(Result);
FThreadCount := FThreadList.Count;
if Assigned(FOnThreadCreate) then
FOnThreadCreate(Self, Result);
Sleep(0); // not sure if required?
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWSocketThrdServer.ClientAttachThread(
Client: TWSocketThrdClient): TWsClientThread;
var
WaitRes : Longword;
H : array[0..1] of THandle;
begin
if Client.ThreadID <> 0 then
Client.ThreadDetach;
//LogDebug(IntToHex(Integer(Client), 8) + ' Main Thread Detached');
Client.FClientThread := nil;
Client.FServer := Self;
Result := AcquireThread;
H[1] := Result.Handle;
{ Wait until the thread has initialized its message queue }
if not Result.FReadyForMsgs then begin
H[0] := Result.FEventArray[cteiThreadReady];
WaitRes := WaitForMultipleObjects(2, @H, FALSE, Infinite);
if WaitRes = WAIT_FAILED then
raise Exception.Create('Wait failed ' +
SysErrorMessage(GetLastError))
else if WaitRes = WAIT_OBJECT_0 + 1 then
raise Exception.Create('Thread terminated while waiting');
end;
if not PostThreadMessage(Result.ThreadID,
WM_THREAD_ADD_CLIENT, WPARAM(Client), 0) then { V7.02 }
raise Exception.Create('PostThreadMessage ' +
SysErrorMessage(GetLastError));
H[0] := Result.FEventArray[cteiClientAttached];
{ Wait until thread has attached client socket to his own context. }
WaitRes := WaitForMultipleObjects(2, @H, FALSE, Infinite);
if WaitRes = WAIT_FAILED then
raise Exception.Create('Wait client ThreadAttach ' +
SysErrorMessage(GetLastError))
else if WaitRes = WAIT_OBJECT_0 + 1 then begin
{ ThreadAttach failed due to the thread terminated, let's try again }
ClientAttachThread(Client);
Exit;
end;
if Assigned(FOnClientAttached) then
FOnClientAttached(Self, Client, Result);
//LogDebug(IntToHex(Integer(Client), 8) + ' W att ID: ' + IntToHex(Result.ThreadID, 8));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.TriggerClientCreate(Client: TWSocketClient);
begin
inherited TriggerClientCreate(Client);
ClientAttachThread(TWSocketThrdClient(Client));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.TriggerClientDisconnect(
Client : TWSocketClient;
ErrCode : Word);
var
AThread : TWsClientThread;
WaitRes : Longword;
H : array[0..1] of THandle;
begin
inherited TriggerClientDisconnect(Client, ErrCode);
AThread := TWSocketThrdClient(Client).ClientThread;
if Assigned(AThread) then begin
H[1] := AThread.Handle;
if not PostThreadMessage(AThread.ThreadID,
WM_THREAD_REMOVE_CLIENT,
WPARAM(Client), 0) then { V7.02 }
raise Exception.Create('PostThreadMessage ' +
SysErrorMessage(GetLastError));
H[0] := AThread.FEventArray[cteiClientRemoved];
{ Wait until thread has Detached client socket to his context. }
WaitRes := WaitForMultipleObjects(2, @H, FALSE, Infinite);
if WaitRes = WAIT_FAILED then
raise Exception.Create('Wait client ThreadDetach ' +
SysErrorMessage(GetLastError));
{else if WaitRes = WAIT_OBJECT_0 + 1 then ...
{ The thread has terminated so we are already detached }
end;
if Assigned(FOnClientDetached) then
FOnClientDetached(Self, TWSocketThrdClient(Client), AThread);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.SetClientsPerThread(const Value: Integer);
begin
if Value <= 0 then
raise Exception.Create('At least one client per thread must be allowed')
else
FClientsPerThread := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TWSClientThread }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TWSClientThread.Create(Suspended: Boolean);
var
I : TWsClientThreadEventID;
begin
inherited Create(Suspended);
for I := Low(FEventArray) to High(FEventArray) do begin
FEventArray[I] := CreateEvent(nil, False, False, nil);
if FEventArray[I] = 0 then
raise Exception.Create('Cannot create event: ' +
SysErrorMessage(GetLastError));
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TWSClientThread.Destroy;
var
I : TWsClientThreadEventID;
begin
//FreeOnTerminate := FALSE;
inherited Destroy;
for I := Low(FEventArray) to High(FEventArray) do
if FEventArray[I] <> 0 then
CloseHandle(FEventArray[I]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWsClientThread.PumpMessages(WaitForMessages: Boolean);
var
HasMessage : Boolean;
Msg : TMsg;
Client : TWSocketThrdClient;
WaitRes : LongWord;
begin
while TRUE do begin
if Terminated and WaitForMessages then
Break;
if WaitForMessages then
HasMessage := GetMessage(Msg, 0, 0, 0)
else
HasMessage := PeekMessage(Msg, 0, 0, 0, PM_REMOVE);
if not HasMessage then
break;
if Msg.hwnd = 0 then begin
case Msg.message of
WM_THREAD_ADD_CLIENT :
begin
Client := TWSocketThrdClient(Msg.WParam);
AttachClient(Client);
{ Tell the main thread that a client attached }
{ to this thread. Unlocks the waiting main thread }
SetEvent(FEventArray[cteiClientAttached]);
{ Wait until the main thread signals }
WaitRes := WaitForSingleObject(FEventArray[cteiThreadUnlock],
INFINITE);
if WaitRes = WAIT_FAILED then
raise Exception.Create('Wait failed ' + SysErrorMessage(GetLastError));
{else if WaitRes = WAIT_TIMEOUT then
raise Exception.Create('Wait timeout');}
end;
WM_THREAD_REMOVE_CLIENT :
begin
Client := TWSocketThrdClient(Msg.WParam);
DetachClient(Client);
{ Tell the main thread that a client detached from }
{ this thread. Unlocks the waiting main thread }
SetEvent(FEventArray[cteiClientRemoved]);
if ClientCount = 0 then begin
Terminate;
Exit; //***
end;
end;
WM_THREAD_DISCONNECT_ALL :
DisconnectAll;
WM_QUIT,
WM_THREAD_TERMINATE :
begin
//FreeOnTerminate := TRUE;
Terminate;
Exit; //***
end;
WM_THREAD_EXCEPTION_TEST :
raise Exception.Create('** TEST EXCEPTION ***');
else
TranslateMessage(Msg); { V7.02 }
DispatchMessage(Msg); { V7.02 }
end;
end
else begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSClientThread.Execute;
var
I : Integer;
Client : TWSocketThrdClient;
Msg : tagMsg;
ErrMsg : PChar;
ExcFlag : Boolean;
begin
try
{ Initialize thread's message queue }
PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE);
ExcFlag := FALSE;
FClients := TList.Create;
try
try
FReadyForMsgs := TRUE;
SetEvent(FEventArray[cteiThreadReady]);
PumpMessages(True);
except
// No exception can go outside of a thread !
on E:Exception do begin
ExcFlag := TRUE;
ErrMsg := AllocMem(1024 * SizeOf(Char));
StrLCopy(ErrMsg, PChar(E.ClassName + ': ' + E.Message), 1023);
PostMessage(FServer.Handle, FServer.FMsg_WM_THREAD_EXCEPTION,
WPARAM(Self), LPARAM(ErrMsg)); { V7.02 }
end;
end;
for I := 0 to FClients.Count - 1 do begin
Client := FClients[I];
if Assigned(Client) then begin
try
try
Client.ThreadDetach;
if ExcFlag then begin
Client.Abort;
// Quick hack to close the socket
//WSocket.WSocket_closesocket(Client.HSocket);
//Client.HSocket := -1;
end;
except
end;
finally
Client.FClientThread := nil;
end;
end;
end;
finally
FClients.Free;
FClients := nil;
end;
finally
if FreeOnTerminate then
FreeOnTerminate := FALSE;
if not Terminated then
Terminate;
PostMessage(FServer.Handle, FServer.FMsg_WM_THREAD_TERMINATED, WPARAM(Self), 0); { V7.02 }
{ Just to make sure the main thread isn't waiting for this thread }
{ we signal the events }
//SetEvent(FEventArray[cteiClientRemoved]);
//SetEvent(FEventArray[cteiClientAttached]);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSClientThread.AttachClient(Client: TWSocketThrdClient);
begin
Client.ThreadAttach;
Client.FClientThread := Self;
FClients.Add(Client);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSClientThread.DetachClient(Client: TWSocketThrdClient);
var
I : Integer;
begin
try
if Assigned(Client) then begin
try
Client.ThreadDetach;
finally
Client.FClientThread := nil;
end;
end;
finally
I := FClients.IndexOf(Client);
if I > -1 then
FClients.Delete(I);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWsClientThread.DisconnectAll;
var
I : Integer;
begin
for I := 0 to FClients.Count - 1 do
TWSocket(FClients[I]).CloseDelayed;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWsClientThread.GetClientCount: Integer;
begin
if Assigned(FClients) then
Result := FClients.Count
else
Result := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.WmThreadException(var Msg: TMessage);
begin
try
if Assigned(FOnThreadException) then
FOnThreadException(Self,
TObject(Msg.WParam) as TWsClientThread,
StrPas(PChar(Msg.LParam)));
finally
FreeMem(PChar(Msg.LParam));
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdServer.WndProc(var MsgRec: TMessage);
begin
try
if MsgRec.Msg = FMsg_WM_THREAD_TERMINATED then
WmThreadTerminated(MsgRec)
else if MsgRec.Msg = FMsg_WM_THREAD_EXCEPTION then
WmThreadException(MsgRec)
else
inherited WndProc(MsgRec);
except
on E:Exception do
HandleBackGroundException(E);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TWSocketThrdClient }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TWSocketThrdClient.MsgHandlersCount : Integer;
begin
Result := 1 + inherited MsgHandlersCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdClient.AllocateMsgHandlers;
begin
inherited AllocateMsgHandlers;
FMsg_WM_THREAD_START_CNX := FWndHandler.AllocateMsgHandler(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdClient.FreeMsgHandlers;
begin
if Assigned(FWndHandler) then begin
FWndHandler.UnregisterMessage(FMsg_WM_THREAD_START_CNX);
end;
inherited FreeMsgHandlers;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdClient.StartConnection;
begin
PostMessage(Self.Handle, FMsg_WM_THREAD_START_CNX, 0, 0);
{ Now unlock the worker thread }
SetEvent(ClientThread.FEventArray[cteiThreadUnlock]);
//LogDebug(IntToHex(Integer(Self), 8) + ' Worker unlocked');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdClient.WMThreadStartCnx(var Msg: TMessage);
begin
//LogDebug(IntToHex(Integer(Self), 8) + ' StartConnection (in worker thread)');
if (Length(FBanner) > 0) and (State = wsConnected) then
SendStr(FBanner + #13#10);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TWSocketThrdClient.WndProc(var MsgRec: TMessage);
begin
try
if MsgRec.Msg = FMsg_WM_THREAD_START_CNX then
WMThreadStartCnx(MsgRec)
else
inherited WndProc(MsgRec);
except
on E:Exception do
HandleBackGroundException(E);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF USE_SSL}
{ TSslWSocketThrdServer }
constructor TSslWSocketThrdServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSslEnable := TRUE;
Port := '443';
Proto := 'tcp';
Addr := '0.0.0.0';
SslMode := sslModeServer;
FSslLock := TSslDynamicLock.Create(nil);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TSslWSocketThrdServer.Destroy;
begin
inherited Destroy;
FSslLock.Free;
FSslLock := nil;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSslWSocketThrdServer.Listen;
begin
inherited;
FSslLock.Enabled := SslEnable;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSslWSocketThrdServer.TriggerClientConnect(
Client : TWSocketClient;
Error : Word);
begin
inherited TriggerClientConnect(Client, Error);
{ The event handler may have closed the connection. }
{ The event handler may also have started the SSL though it won't work. }
if (Error <> 0) or (Client.State <> wsConnected) or
(Client.SslState > sslNone) or (not FSslEnable) then
Exit;
Client.Pause;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TSslWSocketThrdClient }
procedure TSslWSocketThrdClient.WMThreadStartCnx(var Msg: TMessage);
begin
if (State = wsConnected) and (SslState = sslNone) then begin
SslEnable := FServer.SslEnable;
if SslEnable then begin
{ Once SslEnable is set to TRUE we may resume the socket }
Resume;
SslMode := FServer.SslMode;
SslAcceptableHosts := FServer.SslAcceptableHosts;
SslContext := FServer.SslContext;
OnSslVerifyPeer := FServer.OnSslVerifyPeer;
OnSslSetSessionIDContext := FServer.OnSslSetSessionIDContext;
OnSslSvrNewSession := FServer.OnSslSvrNewSession;
OnSslSvrGetSession := FServer.OnSslSvrGetSession;
OnSslHandshakeDone := FServer.OnSslHandshakeDone;
try
if SslMode = sslModeClient then
StartSslHandshake
else
AcceptSslHandshake;
except
SslEnable := False;
Abort;
Exit;
end;
end;
end;
inherited WMThreadStartCnx(Msg);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSslWSocketThrdClient.WndProc(var MsgRec: TMessage);
begin
try
if MsgRec.Msg = FMsg_WM_THREAD_START_CNX then
WMThreadStartCnx(MsgRec)
else
inherited WndProc(MsgRec);
except
on E:Exception do
HandleBackGroundException(E);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$ENDIF}
end.
|
{ @abstract(This unit contains advanced graphic functions used by KControls suite.)
@author(Tomas Krysl (tk@tkweb.eu))
@created(5 May 2004)
@lastmod(20 Jun 2010)
Copyright © 2004 Tomas Krysl (tk@@tkweb.eu)<BR><BR>
<B>License:</B><BR>
This code is distributed as a freeware. You are free to use it as part
of your application for any purpose including freeware, commercial and
shareware applications. The origin of this source code must not be
misrepresented; you must not claim your authorship. You may modify this code
solely for your own purpose. Please feel free to contact the author if you
think your changes might be useful for other users. You may distribute only
the original package. The author accepts no liability for any damage
that may result from using this code. }
unit KGraphics;
{$include kcontrols.inc}
{$WEAKPACKAGEUNIT ON}
interface
uses
{$IFDEF FPC}
// use the LCL interface support whenever possible
{$IFDEF USE_WINAPI}
Windows,
{$ENDIF}
GraphType, IntfGraphics, LCLType, LCLIntf, LMessages, LResources,
{$ELSE}
Windows, Messages,
{$IFDEF USE_PNG_SUPPORT}
PngImage,
{$ENDIF}
{$ENDIF}
Classes, Forms, Graphics, Controls, KFunctions;
resourcestring
{ @exclude }
SGDIError = 'GDI object could not be created.';
const
{ PNG Support }
PNGHeader = #137'PNG'#13#10#26#10;
MNGHeader = #138'MNG'#13#10#26#10;
type
{ Declares possible values for the Style parameter of the @link(BrightColor) function. }
TKBrightMode = (
{ The Color will be brightened with Percent of its entire luminosity range. }
bsAbsolute,
{ The Color will be brightened with Percent of its current luminosity value. }
bsOfBottom,
{ The Color will be brightened with Percent of the difference of its entire
luminosity range and current luminosity value. }
bsOfTop
);
{ Declares RGB + Alpha channel color description allowing both to
access single channels and the whole color item. }
TKColorRec = packed record
case Integer of
0: (R, G, B, A: Byte);
1: (Value: Cardinal);
end;
{ Pointer to TKColorRec. }
PKColorRec = ^TKColorRec;
{ Dynamic array for TKColorRec. }
TKColorRecs = array[0..MaxInt div SizeOf(TKColorRec) - 1] of TKColorRec;
{ Dynamic array for TKColorRecs. }
PKColorRecs = ^TKColorRecs;
{ Dynamic array for TKColorRec. }
TKDynColorRecs = array of TKColorRec;
{ String type for @link(ImageByType) function. }
TKImageHeaderString = string[10];
{$IFDEF USE_PNG_SUPPORT}
{$IFDEF FPC}
{ @exclude }
TKPngImage = TPortableNetworkGraphic;
{$ELSE}
{$IFDEF COMPILER12_UP}
{ @exclude }
TKPngImage = TPngImage;
{$ELSE}
{ @exclude }
TKPngImage = TPngObject;
{$ENDIF}
{$ENDIF}
{$ENDIF}
{ Declares possible values for the Attributes parameter in the @link(DrawAlignedText) function. }
TKTextAttribute = (
{ Bounding rectangle is calculated. No text is drawn. }
taCalcRect,
{ Text will be clipped within the given rectangle. }
taClip,
{ Text will be drawn with end ellipsis if it does not fit within given width. }
taEndEllipsis,
{ Given rectangle will be filled. }
taFillRect,
{ Only yhe text within given rectangle will be filled. }
taFillText,
{ Text will be drawn as multi-line text if it contains carriage returns and line feeds. }
taLineBreak,
{ Text will be drawn with path ellipsis if it does not fit within given width. }
taPathEllipsis,
{ Text line(s) will be broken between words if they don't fit within given width. }
taWordBreak,
{ Text line(s) will be broken if they don't fit within col width. }
taWrapText, //JR:20091229
{ No white spaces will be trimmed at the beginning or end of text lines. }
taTrimWhiteSpaces
);
{ Set type for @link(TKTextAttribute) enumeration. }
TKTextAttributes = set of TKTextAttribute;
{ Declares possible values for the HAlign parameter in the @link(DrawAlignedText) function. }
TKHAlign = (
{ Text is aligned to the left border of a cell rectangle. }
halLeft,
{ Text is horizontally centered within the cell rectangle. }
halCenter,
{ Text is aligned to the right border of a cell rectangle. }
halRight
);
{ Declares possible values for the StretchMode parameter in the @link(ExcludeShapeFromBaseRect) function. }
TKStretchMode = (
{ Shape is not stretched. }
stmNone,
{ Shape is zoomed out. }
stmZoomOutOnly,
{ Shape is zoomed in. }
stmZoomInOnly,
{ Shape is zoomed arbitrary. }
stmZoom
);
{ For backward compatibility. }
TKTextHAlign = TKHAlign;
{ Declares possible values for the VAlign parameter in the @link(DrawAlignedText) function. }
TKVAlign = (
{ Text is aligned to the upper border of a cell rectangle. }
valTop,
{ Text is vertically centered within the cell rectangle. }
valCenter,
{ Text is aligned to the lower border of a cell rectangle. }
valBottom
);
{ For backward compatibility. }
TKTextVAlign = TKVAlign;
{ A simple platform independent encapsulation for a 32bpp bitmap with
alpha channel with the ability to modify it's pixels directly. }
TKAlphaBitmap = class(TGraphic)
private
FCanvas: TCanvas;
FDirectCopy: Boolean;
FHandle: HBITMAP;
FHeight: Integer;
{$IFNDEF USE_WINAPI}
FImage: TLazIntfImage; // Lazarus only
FMaskHandle: HBITMAP;
{$ENDIF}
FOldBitmap: HBITMAP;
FPixels: PKColorRecs;
FPixelsChanged: Boolean;
FWidth: Integer;
function GetScanLine(Index: Integer): PKColorRecs;
function GetHandle: HBITMAP;
function GetPixel(X, Y: Integer): TKColorRec;
procedure SetPixel(X, Y: Integer; Value: TKColorRec);
protected
{ Paints itself to ACanvas at location ARect. }
procedure Draw(ACanvas: TCanvas; const ARect: TRect); override;
{ Returns True if bitmap is empty. }
function GetEmpty: Boolean; override;
{ Returns the bitmap height. }
function GetHeight: Integer; override;
{ Returns True. Treat alpha bitmap as transparent because of the
possible alpha channel. }
function GetTransparent: Boolean; override;
{ Returns the bitmap width. }
function GetWidth: Integer; override;
{ Specifies new bitmap height. }
procedure SetHeight(Value: Integer); override;
{ Specifies new bitmap width. }
procedure SetWidth(Value: Integer); override;
{ Does nothing. Bitmap is never transparent. }
procedure SetTransparent(Value: Boolean); override;
{ Updates the bitmap handle from bitmap pixels. }
procedure UpdateHandle; dynamic;
{ Updates the pixels from bitmap handle. }
procedure UpdatePixels; dynamic;
public
{ Creates the instance. }
constructor Create; override;
{ Creates the instance from application resources. For Lazarus 'BMP' type is
taken, for Delphi RT_RCDATA is taken. }
constructor CreateFromRes(const ResName: string);
{ Destroys the instance. }
destructor Destroy; override;
{ Paints alpha bitmap onto Canvas at position given by X, Y. The alpha bitmap
is combined with the background already drawn on Canvas using alpha channel
stored in the alpha bitmap. }
procedure AlphaDrawTo(ACanvas: TCanvas; X, Y: Integer);
{ Paints alpha bitmap onto Canvas at position given by ARect. The alpha bitmap
is combined with the background already drawn on Canvas using alpha channel
stored in the alpha bitmap. }
procedure AlphaStretchDrawTo(ACanvas: TCanvas; const ARect: TRect);
{ Fills the alpha channel with Alpha. If the optional IfEmpty parameter is True,
the alpha channel won't be modified unless it has zero value for all pixels. }
procedure AlphaFill(Alpha: Byte; IfEmpty: Boolean = False); overload;
{ Fills the alpha channel according to given parameters. Currently it is used
internally by @link(TKDragWindow). }
procedure AlphaFill(Alpha: Byte; BlendColor: TColor; Gradient, Translucent: Boolean); overload;
{ Combines the pixel at given location with the given color. }
procedure CombinePixel(X, Y: Integer; Color: TKColorRec);
{ Takes dimensions and pixels from ABitmap. }
procedure CopyFrom(ABitmap: TKAlphaBitmap);
{ Takes 90°-rotated dimensions and pixels from ABitmap. }
procedure CopyFromRotated(ABitmap: TKAlphaBitmap);
{ Copies a location specified by ARect from ACanvas to bitmap. }
procedure DrawFrom(ACanvas: TCanvas; const ARect: TRect);
{ Calls @link(TKAlphaBitmap.Draw). }
procedure DrawTo(ACanvas: TCanvas; const ARect: TRect);
{$IFNDEF FPC}
{ Does nothing. }
procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle;
APalette: HPALETTE); override;
{$ENDIF}
{ Loads the bitmap from a stream. }
procedure LoadFromStream(Stream: TStream); override;
{ Mirrors the bitmap pixels horizontally. }
procedure MirrorHorz;
{ Mirrors the bitmap pixels vertically. }
procedure MirrorVert;
{$IFNDEF FPC}
{ Does nothing. }
procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle;
var APalette: HPALETTE); override;
{$ENDIF}
{ Saves the bitmap to a stream. }
procedure SaveToStream(Stream: TStream); override;
{ Specifies the bitmap size. }
procedure SetSize(AWidth, AHeight: Integer); {$IFNDEF FPC} reintroduce;{$ENDIF}
{ Returns the bitmap memory canvas. }
property Canvas: TCanvas read FCanvas;
{ Temporary flag. Use when copying data directly from another TGraphic to TKAlphaBitmap. }
property DirectCopy: Boolean read FDirectCopy write FDirectCopy;
{ Returns the bitmap handle. }
property Handle: HBITMAP read GetHandle;
{ Specifies the pixel color. Does range checking. }
property Pixel[X, Y: Integer]: TKColorRec read GetPixel write SetPixel;
{ Returns the pointer to bitmap pixels. }
property Pixels: PKColorRecs read FPixels;
{ Set this property to True if you have modified the bitmap pixels. }
property PixelsChanged: Boolean read FPixelsChanged write FPixelsChanged;
{ Returns the pointer to a bitmap scan line. }
property ScanLine[Index: Integer]: PKColorRecs read GetScanLine;
end;
{$IFDEF USE_WINAPI}
TUpdateLayeredWindowProc = function(Handle: THandle; hdcDest: HDC; pptDst: PPoint;
_psize: PSize; hdcSrc: HDC; pptSrc: PPoint; crKey: COLORREF; pblend: PBLENDFUNCTION;
dwFlags: DWORD): Boolean; stdcall;
{$ENDIF}
{ @abstract(Encapsulates the drag window)
Drag window is top level window used for dragging with mouse. It displays
some portion of associated control. It can be translucent under Windows. }
TKDragWindow = class(TObject)
private
FActive: Boolean;
FAlphaEffects: Boolean;
FBitmap: TKAlphaBitmap;
FBitmapFilled: Boolean;
FControl: TCustomControl;
FGradient: Boolean;
FInitialPos: TPoint;
FLayered: Boolean;
FMasterAlpha: Byte;
{$IFDEF USE_WINAPI}
FBlend: TBlendFunction;
FUpdateLayeredWindow: TUpdateLayeredWindowProc;
FWindow: HWND;
{$ELSE}
FDragForm: TCustomForm;
{$ENDIF}
public
{ Creates the instance. }
constructor Create;
{ Destroys the instance. }
destructor Destroy; override;
{ Shows the drag window on screen. Takes a rectangular part as set by ARect from
IniCtrl's Canvas and displays it at position InitialPos. MasterAlpha and
Gradient are used to premaster the copied image with a specific fading effect. }
procedure Show(IniCtrl: TCustomControl; const ARect: TRect; const InitialPos,
CurrentPos: TPoint; MasterAlpha: Byte; Gradient: Boolean);
{ Moves the drag window to a new location. }
procedure Move(const NewPos: TPoint);
{ Hides the drag window. }
procedure Hide;
{ Returns True if the drag window is shown. }
property Active: Boolean read FActive;
{ Returns the pointer to the bitmap that holds the copied control image. }
property Bitmap: TKAlphaBitmap read FBitmap;
{ Returns True if the control already copied itself to the bitmap. }
property BitmapFilled: Boolean read FBitmapFilled;
end;
{ @abstract(Base class for KControls hints)
This class extends the standard THintWindow class. It adds functionality
common to all hints used in KControls. }
TKHintWindow = class(THintWindow)
private
FExtent: TPoint;
procedure WMEraseBkGnd(var Msg: TLMessage); message LM_ERASEBKGND;
public
{ Creates the instance. }
constructor Create(AOwner: TComponent); override;
{ Shows the hint at given position. This is an IDE independent implementation. }
procedure ShowAt(const Origin: TPoint);
{ Returns the extent of the hint. }
property Extent: TPoint read FExtent;
end;
{ @abstract(Hint window to display formatted text)
This class implements the textual hint window. The text is displayed . }
TKTextHint = class(TKHintWindow)
private
FText: {$IFDEF STRING_IS_UNICODE}string{$ELSE}WideString{$ENDIF};
procedure SetText(const Value: {$IFDEF STRING_IS_UNICODE}string{$ELSE}WideString{$ENDIF});
protected
{ Overriden method. Paints the hint. }
procedure Paint; override;
public
{ Creates the instance. }
constructor Create(AOwner: TComponent); override;
{ }
property Text: {$IFDEF STRING_IS_UNICODE}string{$ELSE}WideString{$ENDIF} read FText write SetText;
end;
TKGraphicHint = class(TKHintWindow)
private
FGraphic: TGraphic;
procedure SetGraphic(const Value: TGraphic);
protected
{ Overriden method. Paints the hint. }
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
property Graphic: TGraphic read FGraphic write SetGraphic;
end;
{ Draws Src to Dest with per pixel weighting by alpha channel saved in Src. }
procedure BlendLine(Src, Dest: PKColorRecs; Count: Integer);
{ Calculates a brighter color of given color based on the HSL color space.
<UL>
<LH>Parameters:</LH>
<LI><I>Color</I> - input color.</LI>
<LI><I>Percent</I> - percentage of luminosity to bright the color (0 to 1).</LI>
<LI><I>Mode</I> - identifies how the Percent parameter should be interpreted.</LI>
</UL> }
function BrightColor(Color: TColor; Percent: Single; Mode: TKBrightMode = bsAbsolute): TColor;
{ Returns current canvas window/wiewport scaling. }
procedure CanvasGetScale(ACanvas: TCanvas; out MulX, MulY, DivX, DivY: Integer);
{ Selects the default window/wiewport scaling to given canvas for both axes. }
procedure CanvasResetScale(ACanvas: TCanvas);
{ Returns True if the ACanvas's device context has been mapped to anything else
than MM_TEXT. }
function CanvasScaled(ACanvas: TCanvas): Boolean;
{ Selects the window/wiewport scaling to given canvas for both axes. }
procedure CanvasSetScale(ACanvas: TCanvas; MulX, MulY, DivX, DivY: Integer);
{ Selects the wiewport offset to given canvas for both axes. }
procedure CanvasSetOffset(ACanvas: TCanvas; OfsX, OfsY: Integer);
{ Makes a grayscale representation of the given color. }
function ColorToGrayScale(Color: TColor): TColor;
{ Calls BitBlt. }
procedure CopyBitmap(DestDC: HDC; DestRect: TRect; SrcDC: HDC; SrcX, SrcY: Integer);
{ Creates an empty rectangular region. }
function CreateEmptyRgn: HRGN;
{ Draws Text to the Canvas at location given by ARect.
HAlign and VAlign specify horizontal resp. vertical alignment of the text
within ARect. HPadding and VPadding specify horizontal (both on left and right side)
and vertical (both on top and bottom side) padding of the Text from ARect.
BackColor specifies the fill color for brush gaps if a non solid Brush
is defined in Canvas. Attributes specift various text output attributes. }
procedure DrawAlignedText(Canvas: TCanvas; var ARect: TRect;
HAlign: TKHAlign; VAlign: TKVAlign; HPadding, VPadding: Integer;
const AText: {$IFDEF STRING_IS_UNICODE}string{$ELSE}WideString{$ENDIF};
BackColor: TColor = clWhite; Attributes: TKTextAttributes = []);
{ Simulates WinAPI DrawEdge with customizable colors. }
procedure DrawEdges(Canvas: TCanvas; const R: TRect; HighlightColor,
ShadowColor: TColor; Flags: Cardinal);
{ Draws a rectangle to Canvas. The rectangle coordinates are given by Rect.
The rectangle is filled by Brush. If Brush is not solid, its gaps are filled
with BackColor. If BackColor is clNone these gaps are not filled and the Brush
appears transparent. }
procedure DrawFilledRectangle(Canvas: TCanvas; const ARect: TRect;
BackColor: TColor);
{ This helper function excludes a rectangular area occupied by a shape from
BaseRect and calculates the shape area rectangles Bounds and Interior.
The shape area is specified by the shape extent (ShapeWidth and ShapeHeight),
padding (HPadding and VPadding) and stretching mode (StretchMode).
The returned Bounds includes (possibly stretched) shape + padding,
and Interior includes only the (possibly stretched) shape.
HAlign specifies the horizontal alignment of shape area within BaseRect.
VAlign specifies the vertical alignment of shape area within BaseRect.
The shape area is always excluded horizontally from BaseRect, as needed by cell
data calculations in KGrid. }
procedure ExcludeShapeFromBaseRect(var BaseRect: TRect; ShapeWidth, ShapeHeight: Integer;
HAlign: TKHAlign; VAlign: TKVAlign; HPadding, VPadding: Integer;
StretchMode: TKStretchMode; out Bounds, Interior: TRect);
{ Selects ARect into device context. Returns previous clipping region. }
function ExtSelectClipRect(DC: HDC; ARect: TRect; Mode: Integer; out PrevRgn: HRGN): Boolean;
{ Selects ARect into device context. Combines with CurRgn and
returns previous clipping region. Both regions have to be created first. }
function ExtSelectClipRectEx(DC: HDC; ARect: TRect; Mode: Integer; CurRgn, PrevRgn: HRGN): Boolean;
{ Fills the area specified by the difference Boundary - Interior on ACanvas with current Brush.
If Brush is not solid, its gaps are filled with BackColor. If BackColor is
clNone these gaps are not filled and the Brush appears transparent. }
procedure FillAroundRect(ACanvas: TCanvas; const Boundary, Interior: TRect; BackColor: TColor);
{ Selects the region into given device context and deletes the region. }
procedure FinalizePrevRgn(DC: HDC; ARgn: HRGN);
{ Determine the height (ascent + descent) of the font currently selected into given DC. }
function GetFontHeight(DC: HDC): Integer;
{ Raises an exception if GDI resource has not been created. }
function GDICheck(Value: Integer): Integer;
{ Creates a TGraphic instance according to the image file header.
Currently supported images are BMP, PNG, MNG, JPG, ICO. }
function ImageByType(const Header: TKImageHeaderString): TGraphic;
{ Calls the IntersectClipRect function. }
function IntersectClipRectIndirect(DC: HDC; ARect: TRect): Boolean;
{ Determines if given color has lightness > 0.5. }
function IsBrightColor(Color: TColor): Boolean;
{ Loads a custom mouse cursor. }
procedure LoadCustomCursor(Cursor: TCursor; const ResName: string);
{ Builds a TKColorRec structure. }
function MakeColorRec(R, G, B, A: Byte): TKColorRec;
{ Returns a pixel format that matches Bpp. }
function PixelFormatFromBpp(Bpp: Cardinal): TPixelFormat;
{ In Lazarus this WinAPI function is missing. }
function RectInRegion(Rgn: HRGN; ARect: TRect): Boolean;
{ Paints an image so that it fits in ARect. Performs double buffering and fills
the background with current brush for mapped device contexts. }
procedure SafeStretchDraw(ACanvas: TCanvas; ARect: TRect; AGraphic: TGraphic; ABackColor: TColor = clWhite);
{ Selects ARect as new clipping region into the device context. }
procedure SelectClipRect(DC: HDC; const ARect: TRect);
{ Calls StretchBlt. }
procedure StretchBitmap(DestDC: HDC; DestRect: TRect; SrcDC: HDC; SrcRect: TRect);
{ Swaps the color format from RGB to BGR and vice versa. }
function SwitchRGBToBGR(Value: TColor): TColor;
{ Subtracts the current device context offset to ARect. }
procedure TranslateRectToDevice(DC: HDC; var ARect: TRect);
implementation
uses
Math, SysUtils, Types, KControls
{$IFDEF FPC}
, FPImage
{$ELSE}
, JPeg
{$ENDIF}
;
procedure BlendLine(Src, Dest: PKColorRecs; Count: Integer);
var
I: Integer;
R, G, B, A1, A2: Integer;
begin
// without assembler
for I := 0 to Count - 1 do
begin
A1 := Src[I].A;
A2 := 255 - A1;
Inc(A1);
Inc(A2);
R := Src[I].R * A1 + Dest[I].R * A2;
G := Src[I].G * A1 + Dest[I].G * A2;
B := Src[I].B * A1 + Dest[I].B * A2;
Dest[I].R := R shr 8;
Dest[I].G := G shr 8;
Dest[I].B := B shr 8;
end;
end;
function CalcLightness(Color: TColor): Single;
var
X: TKColorRec;
begin
X.Value := ColorToRGB(Color);
Result := (X.R + X.G + X.B) / (3 * 256);
end;
function BrightColor(Color: TColor; Percent: Single; Mode: TKBrightMode): TColor;
var
L, Tmp: Single;
function Func1(Value: Single): Single;
begin
Result := Value * (L + Percent) / L;
end;
function Func2(Value: Single): Single;
begin
Result := 1 - (0.5 - Tmp) * (1 - Value) / (1 - L);
{ this is the shorter form of
Value := 1 - 0.5 * (1 - Value) / (1 - L) ; // get color with L = 0.5
Result := 1 - (0.5 - Tmp) * (1 - Value) / 0.5; // get corresponding color
}
end;
function Rd(Value: Single): Byte;
begin
Result := Min(Integer(Round(Value * 255)), 512);
end;
var
R, G, B, Cmax, Cmin: Single;
X: TKColorRec;
begin
X.Value := ColorToRGB(Color);
R := X.R / 255;
G := X.G / 255;
B := X.B / 255;
Cmax := Max(R, Max(G, B));
Cmin := Min(R, Min(G, B));
L := (Cmax + Cmin) / 2;
if L < 1 then
begin
case Mode of
bsOfBottom: Percent := L * Percent;
bsOfTop: Percent := (1 - L) * Percent;
end;
Percent := Min(Percent, 1 - L);
if L = 0 then
begin
// zero length singularity
R := R + Percent; G := G + Percent; B := B + Percent;
end else
begin
Tmp := L + Percent - 0.5;
// lumination below 0.5
if L < 0.5 then
begin
// if L + Percent is >= 0.5, get color with L = 0.5
Percent := Min(Percent, 0.5 - L);
R := Func1(R); G := Func1(G); B := Func1(B);
L := 0.5;
end;
// lumination above 0.5
if Tmp > 0 then
begin
R := Func2(R); G := Func2(G); B := Func2(B);
end;
end;
X.R := Rd(R);
X.G := Rd(G);
X.B := Rd(B);
end;
Result := X.Value;
end;
procedure CanvasGetScale(ACanvas: TCanvas; out MulX, MulY, DivX, DivY: Integer);
{$IFDEF USE_DC_MAPPING}
var
WindowExt, ViewPortExt: TSize;
{$ENDIF}
begin
{$IFDEF USE_DC_MAPPING}
if Boolean(GetWindowExtEx(ACanvas.Handle, {$IFDEF FPC}@{$ENDIF}WindowExt)) and
Boolean(GetViewPortExtEx(ACanvas.Handle, {$IFDEF FPC}@{$ENDIF}ViewPortExt)) then
begin
DivX := WindowExt.cx; DivY := WindowExt.cy;
MulX := ViewPortExt.cx; MulY := ViewPortExt.cy;
end else
{$ENDIF}
begin
MulX := 1; DivX := 1;
MulY := 1; DivY := 1;
end;
end;
procedure CanvasResetScale(ACanvas: TCanvas);
begin
{$IFDEF USE_DC_MAPPING}
SetMapMode(ACanvas.Handle, MM_TEXT);
{$ENDIF}
end;
function CanvasScaled(ACanvas: TCanvas): Boolean;
begin
{$IFDEF USE_DC_MAPPING}
Result := not (GetMapMode(ACanvas.Handle) in [0, MM_TEXT]);
{$ELSE}
Result := False;
{$ENDIF}
end;
procedure CanvasSetScale(ACanvas: TCanvas; MulX, MulY, DivX, DivY: Integer);
begin
{$IFDEF USE_DC_MAPPING}
SetMapMode(ACanvas.Handle, MM_ANISOTROPIC);
SetWindowExtEx(ACanvas.Handle, DivX, DivY, nil);
SetViewPortExtEx(ACanvas.Handle, MulX, MulY, nil);
{$ELSE}
{$WARNING 'Device context window/viewport transformations not working!'}
{$ENDIF}
end;
procedure CanvasSetOffset(ACanvas: TCanvas; OfsX, OfsY: Integer);
begin
{$IFDEF USE_DC_MAPPING}
SetMapMode(ACanvas.Handle, MM_ANISOTROPIC);
SetViewPortOrgEx(ACanvas.Handle, OfsX, OfsY, nil);
{$ENDIF}
end;
function ColorToGrayScale(Color: TColor): TColor;
var
GreyValue: Integer;
X: TKColorRec;
begin
X.Value := ColorToRGB(Color);
GreyValue := (X.R + X.G + X.B) div 3;
X.R := GreyValue;
X.G := GreyValue;
X.B := GreyValue;
Result := X.Value;
end;
procedure CopyBitmap(DestDC: HDC; DestRect: TRect; SrcDC: HDC; SrcX, SrcY: Integer);
begin
{$IFDEF USE_WINAPI}Windows.{$ENDIF}BitBlt(DestDC,
DestRect.Left, DestRect.Top, DestRect.Right - DestRect.Left, DestRect.Bottom - DestRect.Top,
SrcDC, 0, 0, SRCCOPY);
end;
function CreateEmptyRgn: HRGN;
begin
Result := CreateRectRgn(0,0,0,0);
end;
procedure DrawAlignedText(Canvas: TCanvas; var ARect: TRect;
HAlign: TKHAlign; VAlign: TKVAlign; HPadding, VPadding: Integer;
const AText: {$IFDEF STRING_IS_UNICODE}string{$ELSE}WideString{$ENDIF};
BackColor: TColor; Attributes: TKTextAttributes);
var
DC: HDC;
FontHeight: Integer;
ClipRect: TRect;
function MeasureOrOutput(Y: Integer; Output: Boolean): TSize;
var
EndEllipsis, PathEllipsis: Boolean;
Width, EllipsisWidth: Integer;
function TextExtent(AText: {$IFDEF STRING_IS_UNICODE}PChar{$ELSE}PWideChar{$ENDIF}; ALen: Integer; Trim: Boolean = False): TSize;
begin
if Trim then
begin
if taLineBreak in Attributes then
TrimWhiteSpaces(AText, ALen, cLineBreaks);
if taTrimWhiteSpaces in Attributes then
TrimWhiteSpaces(AText, ALen, cWordBreaks);
end;
{$IFDEF STRING_IS_UNICODE}
{$IFDEF FPC}
{$IFDEF USE_CANVAS_METHODS}
Result := Canvas.TextExtent(Copy(AText, 0, ALen)); // little slower but more secure in Lazarus
{$ELSE}
GetTextExtentPoint32(DC, AText, ALen, Result);
{$ENDIF}
{$ELSE}
GetTextExtentPoint32(DC, AText, ALen, Result);
{$ENDIF}
{$ELSE}
GetTextExtentPoint32W(DC, AText, ALen, Result);
{$ENDIF}
end;
procedure FmtTextOut(Y: Integer; AText: {$IFDEF STRING_IS_UNICODE}PChar{$ELSE}PWideChar{$ENDIF}; ALen: Integer);
var
DrawEllipsis, DrawFileName: Boolean;
AWidth, Index, NewIndex,SlashPos, FileNameLen, EllipsisMaxX, X: Integer;
S: {$IFDEF STRING_IS_UNICODE}string{$ELSE}WideString{$ENDIF};
begin
DrawEllipsis := False;
DrawFileName := False;
SlashPos := 0;
FileNameLen := 0;
if taLineBreak in Attributes then
TrimWhiteSpaces(AText, ALen, cLineBreaks);
if taTrimWhiteSpaces in Attributes then
TrimWhiteSpaces(AText, ALen, cWordBreaks);
if (EndEllipsis or PathEllipsis) and (ALen > 1) then
begin
AWidth := TextExtent(AText, ALen).cx;
if AWidth > Width then
begin
AWidth := 0;
Index := 0;
if EndEllipsis then
begin
EllipsisMaxX := Width - EllipsisWidth;
while (Index < ALen) do
begin
NewIndex := StrNextCharIndex(AText, Index);
Inc(AWidth, TextExtent(@AText[Index], NewIndex - Index).cx);
if (AWidth > EllipsisMaxX) and (Index > 0) then
Break
else
Index := NewIndex;
end;
ALen := Index;
DrawEllipsis := True;
end
else if PathEllipsis then
begin
SlashPos := ALen;
while (SlashPos > 0) and not CharInSetEx(AText[SlashPos], ['/', '\']) do
Dec(SlashPos);
if SlashPos > 0 then
begin
DrawEllipsis := True;
DrawFileName := True;
FileNameLen := ALen - SlashPos;
EllipsisMaxX := Width - TextExtent(@AText[SlashPos], FileNameLen).cx - EllipsisWidth;
while (Index < SlashPos) do
begin
NewIndex := StrNextCharIndex(AText, Index);
Inc(AWidth, TextExtent(@AText[Index], NewIndex - Index).cx);
if AWidth > EllipsisMaxX then
Break
else
Index := NewIndex;
end;
ALen := Index;
end;
end;
end;
end;
if DrawEllipsis then
begin
if DrawFileName then
begin
S := Copy(AText, 0, ALen) + cEllipsis + Copy(AText, SlashPos + 1, FileNameLen);
end else
S := Copy(AText, 0, ALen) + cEllipsis;
AText := {$IFDEF STRING_IS_UNICODE}PChar{$ELSE}PWideChar{$ENDIF}(S);
ALen := Length(S);
end;
case HAlign of
halCenter:
X := Max(ClipRect.Left, (ClipRect.Left + ClipRect.Right - TextExtent(AText, ALen).cx) div 2);
halRight:
X := ClipRect.Right - TextExtent(AText, ALen).cx;
else
X := ClipRect.Left;
end;
{$IFDEF STRING_IS_UNICODE}
{$IFDEF FPC}
{$IFDEF USE_CANVAS_METHODS}
Canvas.TextOut(X, Y, Copy(AText, 0, ALen)); // little slower but more secure in Lazarus
{$ELSE}
TextOut(DC, X, Y, AText, ALen);
{$ENDIF}
{$ELSE}
TextOut(DC, X, Y, AText, ALen);
{$ENDIF}
{$ELSE}
TextOutW(DC, X, Y, AText, ALen);
{$ENDIF}
end;
var
I, Index, TextLen, LineBegin, LineBreaks, Vert: Integer;
CalcRect, WordBreak, LineBreak, WhiteSpace, PrevWhiteSpace, FirstWord,
WrapText: Boolean;
Size: TSize;
begin
Result.cx := 0;
Vert := Y;
if AText <> '' then
begin
LineBegin := 1;
LineBreaks := 0;
TextLen := Length(AText);
Width := ClipRect.Right - ClipRect.Left;
CalcRect := taCalcRect in Attributes;
WordBreak := taWordBreak in Attributes;
LineBreak := taLineBreak in Attributes;
WrapText := taWrapText in Attributes; //JR:20091229
if Output then
begin
EndEllipsis := taEndEllipsis in Attributes;
PathEllipsis := taPathEllipsis in Attributes;
EllipsisWidth := TextExtent(cEllipsis, Length(cEllipsis)).cx;
end;
if WordBreak or LineBreak then
begin
I := LineBegin;
Index := LineBegin;
WhiteSpace := True;
FirstWord := True;
while I <= TextLen + 1 do
begin
PrevWhiteSpace := WhiteSpace;
WhiteSpace := CharInSetEx(AText[I], cWordBreaks + cLineBreaks);
if (not PrevWhiteSpace and WhiteSpace and (I > LineBegin))
or (not PrevWhiteSpace and WrapText and (I > LineBegin)) then //JR:20091229
begin
if (WordBreak or WrapText) and (LineBreaks = 0) and not FirstWord then
begin
Size := TextExtent(@AText[LineBegin], I - LineBegin, True);
if Size.cx > Width then
Inc(LineBreaks);
end;
if LineBreaks > 0 then
begin
if Index > LineBegin then
begin
if Output and (Vert >= ClipRect.Top - FontHeight) and (Vert <= ClipRect.Bottom) then
FmtTextOut(Vert, @AText[LineBegin], Index - LineBegin)
else if CalcRect then
Result.cx := Max(Result.cx, TextExtent(@AText[LineBegin], Index - LineBegin, True).cx);
LineBegin := Index;
end;
Inc(Vert, FontHeight * LineBreaks);
LineBreaks := 0;
end;
Index := I;
FirstWord := False;
end;
if LineBreak and (AText[I] = cCR) then
Inc(LineBreaks);
Inc(I);
end;
end;
if LineBegin <= TextLen then
begin
if Output and (Vert >= ClipRect.Top - FontHeight) and (Vert <= ClipRect.Bottom) then
FmtTextOut(Vert, @AText[LineBegin], TextLen - LineBegin + 1)
else if CalcRect then
Result.cx := Max(Result.cx, TextExtent(@AText[LineBegin], TextLen - LineBegin + 1, True).cx);
Inc(Vert, FontHeight * (1 + LineBreaks));
end;
end;
Result.cy := Vert - Y;
end;
procedure Initialize;
begin
ClipRect := ARect;
InflateRect(ClipRect, -HPadding, -VPadding);
DC := Canvas.Handle;
FontHeight := GetFontHeight(DC);
end;
var
Y: Integer;
TmpRect: TRect;
Extent: TSize;
PrevRgn: HRGN;
begin
if taCalcRect in Attributes then
begin
Initialize;
Extent := MeasureOrOutput(0, False);
ARect.Right := ARect.Left + Extent.cx;
ARect.Bottom := ARect.Top + Extent.cy;
end
else if not IsRectEmpty(ARect) then
begin
if taFillRect in Attributes then
DrawFilledRectangle(Canvas, ARect, BackColor);
if AText <> '' then
begin
Initialize;
if not IsRectEmpty(ClipRect) then
begin
case VAlign of
valCenter:
Y := Max(ClipRect.Top, (ClipRect.Bottom + ClipRect.Top - MeasureOrOutput(0, False).cy) div 2);
valBottom:
Y := ClipRect.Bottom - MeasureOrOutput(0, False).cy;
else
Y := ClipRect.Top;
end;
TmpRect := ClipRect;
if taClip in Attributes then
begin
TranslateRectToDevice(DC, TmpRect);
if ExtSelectClipRect(DC, TmpRect, RGN_AND, PrevRgn) then
try
if not (taFillText in Attributes) then
SetBkMode(DC, TRANSPARENT);
MeasureOrOutput(Y, True);
finally
FinalizePrevRgn(DC, PrevRgn);
end;
end else
begin
if not (taFillText in Attributes) then
SetBkMode(DC, TRANSPARENT);
MeasureOrOutput(Y, True);
end;
end;
end;
end;
end;
procedure DrawEdges(Canvas: TCanvas; const R: TRect; HighlightColor,
ShadowColor: TColor; Flags: Cardinal);
begin
with Canvas do
begin
Brush.Style := bsSolid;
Brush.Color := HighlightColor;
if Flags and BF_LEFT <> 0 then
FillRect(Rect(R.Left, R.Top + 1, R.Left + 1, R.Bottom));
if Flags and BF_TOP <> 0 then
FillRect(Rect(R.Left, R.Top, R.Right, R.Top + 1));
Brush.Color := ShadowColor;
if Flags and BF_RIGHT <> 0 then
FillRect(Rect(R.Right - 1, R.Top + 1, R.Right, R.Bottom));
if Flags and BF_BOTTOM <> 0 then
FillRect(Rect(R.Left + 1, R.Bottom - 1, R.Right - 1, R.Bottom));
end;
end;
procedure DrawFilledRectangle(Canvas: TCanvas; const ARect: TRect; BackColor: TColor);
var
DC: HDC;
begin
DC := Canvas.Handle;
SetBkMode(DC, OPAQUE);
SetBkColor(DC, ColorToRGB(BackColor));
FillRect(DC, ARect, Canvas.Brush.Handle);
end;
procedure ExcludeShapeFromBaseRect(var BaseRect: TRect; ShapeWidth, ShapeHeight: Integer;
HAlign: TKHAlign; VAlign: TKVAlign; HPadding, VPadding: Integer;
StretchMode: TKStretchMode; out Bounds, Interior: TRect);
var
MaxHeight, MaxWidth, StretchHeight, StretchWidth: Integer;
RatioX, RatioY: Single;
begin
MaxHeight := BaseRect.Bottom - BaseRect.Top - 2 * VPadding;
MaxWidth := BaseRect.Right - BaseRect.Left - HPadding;
if ((MaxWidth <> ShapeWidth) or (MaxHeight <> ShapeHeight)) and (
(StretchMode = stmZoom) or
(StretchMode = stmZoomInOnly) and (MaxWidth >= ShapeWidth) and (MaxHeight >= ShapeHeight) or
(StretchMode = stmZoomOutOnly) and ((MaxWidth < ShapeWidth) or (MaxHeight < ShapeHeight))
) then
begin
RatioX := MaxWidth / ShapeWidth;
RatioY := MaxHeight / ShapeHeight;
if RatioY >= RatioX then
begin
StretchWidth := MaxWidth;
StretchHeight := ShapeHeight * StretchWidth div ShapeWidth;
end else
begin
StretchHeight := MaxHeight;
StretchWidth := ShapeWidth * StretchHeight div ShapeHeight;
end;
end else
begin
StretchHeight := ShapeHeight;
StretchWidth := ShapeWidth;
end;
Bounds := BaseRect;
Interior := BaseRect;
case HAlign of
halLeft:
begin
Inc(BaseRect.Left, StretchWidth + HPadding);
// Bounds.Left remains unchanged
Bounds.Right := BaseRect.Left;
Inc(Interior.Left, HPadding);
end;
halCenter:
begin
BaseRect.Right := BaseRect.Left; // BaseRect empty, no space for next item!
// Bounds remains unchanged
Inc(Interior.Left, HPadding + (MaxWidth - StretchWidth) div 2);
end;
halRight:
begin
Dec(BaseRect.Right, StretchWidth + HPadding);
Bounds.Left := BaseRect.Right;
// Bounds.Right remains unchanged
Interior.Left := BaseRect.Right;
end;
end;
Interior.Right := Interior.Left + StretchWidth;
case VAlign of
valTop: Inc(Interior.Top, VPadding);
valCenter: Inc(Interior.Top, VPadding + (MaxHeight - StretchHeight) div 2);
valBottom: Interior.Top := BaseRect.Bottom - VPadding - StretchHeight;
end;
Interior.Bottom := Interior.Top + StretchHeight;
end;
function ExtSelectClipRect(DC: HDC; ARect: TRect; Mode: Integer; out PrevRgn: HRGN): Boolean;
var
TmpRgn: HRGN;
begin
PrevRgn := CreateEmptyRgn;
GetClipRgn(DC, PrevRgn);
TmpRgn := CreateEmptyRgn;
try
Result := ExtSelectClipRectEx(DC, ARect, Mode, TmpRgn, PrevRgn)
finally
DeleteObject(TmpRgn);
end;
end;
function ExtSelectClipRectEx(DC: HDC; ARect: TRect; Mode: Integer; CurRgn, PrevRgn: HRGN): Boolean;
var
RectRgn: HRGN;
begin
RectRgn := CreateRectRgnIndirect(ARect);
try
Result := CombineRgn(CurRgn, PrevRgn, RectRgn, Mode) <> NULLREGION;
if Result then
SelectClipRgn(DC, CurRgn);
finally
DeleteObject(RectRgn);
end;
end;
procedure FillAroundRect(ACanvas: TCanvas; const Boundary, Interior: TRect; BackColor: TColor);
var
R: TRect;
begin
R := Rect(Boundary.Left, Boundary.Top, Boundary.Right, Interior.Top);
if not IsRectEmpty(R) then DrawFilledRectangle(ACanvas, R, BackColor);
R := Rect(Boundary.Left, Interior.Top, Interior.Left, Interior.Bottom);
if not IsRectEmpty(R) then DrawFilledRectangle(ACanvas, R, BackColor);
R := Rect(Interior.Right, Interior.Top, Boundary.Right, Interior.Bottom);
if not IsRectEmpty(R) then DrawFilledRectangle(ACanvas, R, BackColor);
R := Rect(Boundary.Left, Interior.Bottom, Boundary.Right, Boundary.Bottom);
if not IsRectEmpty(R) then DrawFilledRectangle(ACanvas, R, BackColor);
end;
procedure FinalizePrevRgn(DC: HDC; ARgn: HRGN);
begin
SelectClipRgn(DC, ARgn);
DeleteObject(ARgn);
end;
function GetFontHeight(DC: HDC): Integer;
var
TM: TTextMetric;
begin
FillChar(TM, SizeOf(TTextMetric), 0);
GetTextMetrics(DC, TM);
Result := TM.tmHeight;
end;
function GDICheck(Value: Integer): Integer;
begin
if Value = 0 then
raise EOutOfResources.Create(SGDIError);
Result := Value;
end;
function ImageByType(const Header: TKImageHeaderString): TGraphic;
begin
if Pos('BM', {$IFDEF COMPILER12_UP}string{$ENDIF}(Header)) = 1 then
Result := TBitmap.Create
{$IFDEF USE_PNG_SUPPORT }
else if (Pos(#137'PNG', {$IFDEF COMPILER12_UP}string{$ENDIF}(Header)) = 1) or
(Pos(#138'MNG', {$IFDEF COMPILER12_UP}string{$ENDIF}(Header)) = 1) then
Result := TKPngImage.Create
{$ENDIF }
else if (Pos(#$FF#$D8, {$IFDEF COMPILER12_UP}string{$ENDIF}(Header)) = 1) then
Result := TJPegImage.Create
else if (Pos(#$FF#$D8, {$IFDEF COMPILER12_UP}string{$ENDIF}(Header)) = 1) then
Result := TIcon.Create
else
Result := nil;
end;
function IntersectClipRectIndirect(DC: HDC; ARect: TRect): Boolean;
begin
with ARect do
Result := IntersectClipRect(DC, Left, Top, Right, Bottom) <> NULLREGION;
end;
function IsBrightColor(Color: TColor): Boolean;
begin
Result := CalcLightness(Color) > 0.5;
end;
function MakeColorRec(R, G, B, A: Byte): TKColorRec;
begin
Result.R := R;
Result.G := G;
Result.B := B;
Result.A := A;
end;
procedure LoadCustomCursor(Cursor: TCursor; const ResName: string);
begin
Screen.Cursors[Cursor] :=
{$IFDEF FPC}
LoadCursorFromLazarusResource(ResName);
{$ELSE}
LoadCursor(HInstance, PChar(ResName));
{$ENDIF}
end;
function PixelFormatFromBpp(Bpp: Cardinal): TPixelFormat;
begin
case Bpp of
1: Result := pf1bit;
2..4: Result := pf4bit;
5..8: Result := pf8bit;
9..16: Result := pf16bit;
else
Result := pf32bit;
end;
end;
function RectInRegion(Rgn: HRGN; ARect: TRect): Boolean;
{$IFDEF FPC}
var
RectRgn, TmpRgn: HRGN;
{$ENDIF}
begin
{$IFDEF FPC}
RectRgn := CreateRectRgnIndirect(ARect);
try
TmpRgn := CreateEmptyRgn;
try
Result := CombineRgn(TmpRgn, RectRgn, Rgn, RGN_AND) <> NULLREGION;
finally
DeleteObject(TmpRgn);
end;
finally
DeleteObject(RectRgn);
end;
{$ELSE}
Result := Windows.RectInRegion(Rgn, ARect);
{$ENDIF}
end;
procedure SafeStretchDraw(ACanvas: TCanvas; ARect: TRect; AGraphic: TGraphic; ABackColor: TColor);
{$IFDEF USE_WINAPI}
var
BM: TBitmap;
W, H, MulX, MulY, DivX, DivY: Integer;
R: TRect;
{$ENDIF}
begin
{$IFDEF USE_WINAPI}
if AGraphic.Transparent then
begin
// WinAPI StretchBlt function does not read properly from screen buffer
// so we have to append double buffering
CanvasGetScale(ACanvas, MulX, MulY, DivX, DivY);
W := MulDiv(ARect.Right - ARect.Left, MulX, DivX);
H := MulDiv(ARect.Bottom - ARect.Top, MulY, DivY);
BM := TBitmap.Create;
try
BM.Width := W;
BM.Height := H;
BM.Canvas.Brush := ACanvas.Brush;
R := Rect(0, 0, W, H);
DrawFilledRectangle(BM.Canvas, R, ABackColor);
BM.Canvas.StretchDraw(R, AGraphic);
ACanvas.StretchDraw(ARect, BM);
finally
BM.Free;
end;
end else
{$ENDIF}
ACanvas.StretchDraw(ARect, AGraphic);
end;
procedure SelectClipRect(DC: HDC; const ARect: TRect);
var
Rgn: HRGN;
begin
Rgn := CreateRectRgnIndirect(ARect);
try
SelectClipRgn(DC, Rgn);
finally
DeleteObject(Rgn);
end;
end;
procedure StretchBitmap(DestDC: HDC; DestRect: TRect; SrcDC: HDC; SrcRect: TRect);
begin
{$IFDEF USE_WINAPI}Windows.{$ENDIF}StretchBlt(DestDC,
DestRect.Left, DestRect.Top, DestRect.Right - DestRect.Left, DestRect.Bottom - DestRect.Top,
SrcDC, SrcRect.Left, SrcRect.Top, SrcRect.Right - SrcRect.Left, SrcRect.Bottom - SrcRect.Top,
SRCCOPY);
end;
procedure SwapBR(var ColorRec: TKColorRec);
var
Tmp: Byte;
begin
Tmp := ColorRec.R;
ColorRec.R := ColorRec.B;
ColorRec.B := Tmp;
end;
function SwitchRGBToBGR(Value: TColor): TColor;
var
B: Byte;
begin
Result := Value;
B := PKColorRec(@Value).B;
PKColorRec(@Result).B := PKColorRec(@Result).R;
PKColorRec(@Result).R := B;
end;
procedure TranslateRectToDevice(DC: HDC; var ARect: TRect);
var
P: TPoint;
{$IFDEF USE_DC_MAPPING}
{$IFNDEF LCLQT}
WindowExt, ViewportExt: TSize;
{$ENDIF}
{$ENDIF}
begin
{$IFDEF USE_DC_MAPPING}
{$IFNDEF LCLQT}
if not (GetMapMode(DC) in [0, MM_TEXT]) and
Boolean(GetWindowExtEx(DC, {$IFDEF FPC}@{$ENDIF}WindowExt)) and
Boolean(GetViewportExtEx(DC, {$IFDEF FPC}@{$ENDIF}ViewportExt)) then
begin
ARect.Left := MulDiv(ARect.Left, ViewportExt.cx, WindowExt.cx);
ARect.Right := MulDiv(ARect.Right, ViewportExt.cx, WindowExt.cx);
ARect.Top := MulDiv(ARect.Top, ViewportExt.cy, WindowExt.cy);
ARect.Bottom := MulDiv(ARect.Bottom, ViewportExt.cy, WindowExt.cy);
end;
if Boolean(GetViewPortOrgEx(DC, {$IFDEF FPC}@{$ENDIF}P)) then
OffsetRect(ARect, P.X, P.Y);
{$ENDIF}
{$ENDIF}
if Boolean(GetWindowOrgEx(DC, {$IFDEF FPC}@{$ENDIF}P)) then
OffsetRect(ARect, -P.X, -P.Y);
end;
{ TKAlphaBitmap }
constructor TKAlphaBitmap.Create;
begin
inherited;
FCanvas := TCanvas.Create;
FCanvas.Handle := CreateCompatibleDC(0);
FDirectCopy := False;
FHandle := 0;
{$IFNDEF USE_WINAPI}
FImage := TLazIntfImage.Create(0, 0);
{$ENDIF}
FHeight := 0;
FOldBitmap := 0;
FPixels := nil;
FWidth := 0;
end;
constructor TKAlphaBitmap.CreateFromRes(const ResName: string);
var
Stream: {$IFDEF FPC}TLazarusResourceStream{$ELSE}TResourceStream{$ENDIF};
begin
Create;
try
{$IFDEF FPC}
Stream := TLazarusResourceStream.Create(LowerCase(ResName), 'BMP');
{$ELSE}
Stream := TResourceStream.Create(HInstance, ResName, RT_RCDATA);
{$ENDIF}
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
except
end;
end;
destructor TKAlphaBitmap.Destroy;
var
DC: HDC;
begin
inherited;
SetSize(0, 0);
{$IFNDEF USE_WINAPI}
FImage.Free;
{$ENDIF}
DC := FCanvas.Handle;
FCanvas.Handle := 0;
DeleteDC(DC);
FCanvas.Free;
end;
procedure TKAlphaBitmap.AlphaDrawTo(ACanvas: TCanvas; X, Y: Integer);
begin
AlphaStretchDrawTo(ACanvas, Rect(X, Y, X + FWidth, Y + FHeight));
end;
procedure TKAlphaBitmap.AlphaFill(Alpha: Byte; IfEmpty: Boolean);
var
I: Integer;
HasAlpha: Boolean;
begin
HasAlpha := False;
if IfEmpty then
for I := 0 to FWidth * FHeight - 1 do
if FPixels[I].A <> 0 then
begin
HasAlpha := True;
Break;
end;
if not HasAlpha then
for I := 0 to FWidth * FHeight - 1 do
FPixels[I].A := Alpha;
end;
procedure TKAlphaBitmap.AlphaFill(Alpha: Byte; BlendColor: TColor; Gradient, Translucent: Boolean);
var
I, J, A1, A2, AR, AG, AB, HAlpha: Integer;
HStep, HSum, VStep, VSum: Single;
Scan: PKColorRecs;
CS: TKColorRec;
begin
VSum := 0; VStep := 0;
HSum := 0; HStep := 0;
if Gradient then
begin
VStep := Alpha / FHeight;
VSum := Alpha;
end;
CS.Value := ColorToRGB(BlendColor);
{$IFNDEF USE_WINAPI}
for I := 0 to FHeight - 1 do
{$ELSE}
for I := FHeight - 1 downto 0 do
{$ENDIF}
begin
Scan := ScanLine[I];
HAlpha := Alpha;
if Gradient then
begin
HStep := HAlpha / FWidth;
HSum := HAlpha;
end;
for J := 0 to FWidth - 1 do with Scan[J] do
begin
A1 := HAlpha;
A2 := 255 - HAlpha;
AR := R * A1 + CS.R * A2;
AG := G * A1 + CS.G * A2;
AB := B * A1 + CS.B * A2;
R := AR shr 8;
G := AG shr 8;
B := AB shr 8;
if Translucent then
A := HAlpha
else
A := 255;
if Gradient then
begin
HAlpha := Round(HSum);
HSum := HSum - HStep;
end;
end;
if Gradient then
begin
Alpha := Round(VSum);
VSum := VSum - VStep;
end;
end;
FPixelsChanged := True;
end;
procedure TKAlphaBitmap.AlphaStretchDrawTo(ACanvas: TCanvas;
const ARect: TRect);
{$IFDEF USE_WINAPI}
var
I: Integer;
Tmp: TKAlphaBitmap;
Ps, Pd: PKColorRecs;
{$ENDIF}
begin
{$IFNDEF USE_WINAPI}
DrawTo(ACanvas, ARect);
{$ELSE}
Tmp := TKAlphaBitmap.Create;
try
Tmp.SetSize(FWidth, FHeight);
Tmp.DrawFrom(ACanvas, ARect);
for I := 0 to FHeight - 1 do
begin
Ps := ScanLine[I];
Pd := Tmp.ScanLine[I];
BlendLine(Ps, Pd, FWidth);
end;
Tmp.PixelsChanged := True;
Tmp.DrawTo(ACanvas, ARect);
finally
Tmp.Free;
end;
{$ENDIF}
end;
procedure TKAlphaBitmap.CombinePixel(X, Y: Integer; Color: TKColorRec);
var
Index, A1, A2, AR, AG, AB: Integer;
begin
if (X >= 0) and (X < FWidth) and (Y >= 0) and (Y < FHeight) then
begin
SwapBR(Color);
{$IFDEF USE_WINAPI}
Index := (FHeight - Y - 1) * FWidth + X;
{$ELSE}
Index := Y * FWidth + X;
{$ENDIF}
A2 := Color.A;
if A2 = 255 then
FPixels[Index] := Color
else if A2 <> 0 then
begin
A1 := 255 - Color.A;
AR := FPixels[Index].R * A1 + Color.R * A2;
AG := FPixels[Index].G * A1 + Color.G * A2;
AB := FPixels[Index].B * A1 + Color.B * A2;
FPixels[Index].R := AR shr 8;
FPixels[Index].G := AG shr 8;
FPixels[Index].B := AB shr 8;
FPixels[Index].A := 255;
end;
FPixelsChanged := True;
end;
end;
procedure TKAlphaBitmap.CopyFrom(ABitmap: TKAlphaBitmap);
var
I, Size: Integer;
begin
SetSize(ABitmap.Width, ABitmap.Height);
Size := FWidth * SizeOf(TKColorRec);
for I := 0 to FHeight - 1 do
Move(ABitmap.ScanLine[I]^, ScanLine[I]^, Size);
FPixelsChanged := True;
end;
procedure TKAlphaBitmap.CopyFromRotated(ABitmap: TKAlphaBitmap);
var
I, J: Integer;
SrcScan, DstScan: PKColorRecs;
begin
SetSize(ABitmap.Height, ABitmap.Width);
for J := 0 to ABitmap.Height - 1 do
begin
SrcScan := ABitmap.ScanLine[J];
for I := 0 to ABitmap.Width - 1 do
begin
DstScan := ScanLine[ABitmap.Width - I - 1];
DstScan[J] := SrcScan[I];
end;
end;
FPixelsChanged := True;
end;
procedure TKAlphaBitmap.Draw(ACanvas: TCanvas; const ARect: TRect);
begin
if FDirectCopy then
DrawTo(ACanvas, ARect)
else
AlphaStretchDrawTo(ACanvas, ARect);
end;
procedure TKAlphaBitmap.DrawFrom(ACanvas: TCanvas; const ARect: TRect);
begin
if not Empty then
begin
if not CanvasScaled(ACanvas) then
StretchBitmap(FCanvas.Handle, Rect(0, 0, FWidth, FHeight), ACanvas.Handle, ARect)
else
begin
FCanvas.Brush := ACanvas.Brush;
DrawFilledRectangle(FCanvas, Rect(0, 0, FWidth, FHeight),
{$IFDEF USE_WINAPI}GetBkColor(ACanvas.Handle){$ELSE}clWindow{$ENDIF});
end;
UpdatePixels;
end;
end;
procedure TKAlphaBitmap.DrawTo(ACanvas: TCanvas; const ARect: TRect);
begin
if not Empty then
begin
UpdateHandle;
StretchBitmap(ACanvas.Handle, ARect, FCanvas.Handle, Rect(0, 0, FWidth, FHeight))
end;
end;
function TKAlphaBitmap.GetEmpty: Boolean;
begin
Result := (FWidth = 0) and (FHeight = 0);
end;
function TKAlphaBitmap.GetHeight: Integer;
begin
Result := FHeight;
end;
function TKAlphaBitmap.GetPixel(X, Y: Integer): TKColorRec;
begin
if (X >= 0) and (X < FWidth) and (Y >= 0) and (Y < FHeight) then
begin
{$IFDEF USE_WINAPI}
Result := FPixels[(FHeight - Y - 1) * FWidth + X];
{$ELSE}
Result := FPixels[Y * FWidth + X];
{$ENDIF}
SwapBR(Result);
end else
Result := MakeColorRec(0,0,0,0);
end;
function TKAlphaBitmap.GetTransparent: Boolean;
begin
Result := True;
end;
function TKAlphaBitmap.GetScanLine(Index: Integer): PKColorRecs;
begin
// no checks here
Result := @FPixels[Index * FWidth];
end;
function TKAlphaBitmap.GetHandle: HBITMAP;
begin
Result := FHandle;
end;
function TKAlphaBitmap.GetWidth: Integer;
begin
Result := FWidth;
end;
{$IFNDEF FPC}
procedure TKAlphaBitmap.LoadFromClipboardFormat(AFormat: Word; AData: THandle;
APalette: HPALETTE);
begin
// does nothing
end;
{$ENDIF}
procedure TKAlphaBitmap.LoadFromStream(Stream: TStream);
var
BF: TBitmapFileHeader;
BI: TBitmapInfoHeader;
begin
SetSize(0, 0);
Stream.Read(BF, SizeOf(TBitmapFileHeader));
Stream.Read(BI, SizeOf(TBitmapInfoHeader));
if BI.biBitCount = 32 then
begin
SetSize(BI.biWidth, BI.biHeight);
Stream.Read(FPixels^, BI.biSizeImage);
// if bitmap has no alpha channel, create full opacity
AlphaFill($FF, True);
end;
FPixelsChanged := True;
end;
procedure TKAlphaBitmap.MirrorHorz;
var
I, J, Index: Integer;
SrcScan: PKColorRecs;
Buf: TKColorRec;
begin
for I := 0 to FHeight - 1 do
begin
SrcScan := ScanLine[I];
Index := FWidth - 1;
for J := 0 to (FWidth shr 1) - 1 do
begin
Buf := SrcScan[Index];
SrcScan[Index] := SrcScan[J];
SrcScan[J] := Buf;
Dec(Index);
end;
end;
FPixelsChanged := True;
end;
procedure TKAlphaBitmap.MirrorVert;
var
I, Size, Index: Integer;
SrcScan, DstScan: PKColorRecs;
Buf: PKColorRec;
begin
Size:= FWidth * SizeOf(TKColorRec);
Index := FHeight - 1;
GetMem(Buf, Size);
try
for I := 0 to (FHeight shr 1) - 1 do
begin
SrcScan := ScanLine[I];
DstScan := ScanLine[Index];
Move(SrcScan^, Buf^, Size);
Move(DstScan^, SrcScan^, Size);
Move(Buf^, DstScan^, Size);
Dec(Index);
end;
finally
FreeMem(Buf);
end;
FPixelsChanged := True;
end;
{$IFNDEF FPC}
procedure TKAlphaBitmap.SaveToClipboardFormat(var AFormat: Word;
var AData: THandle; var APalette: HPALETTE);
begin
// does nothing
end;
{$ENDIF}
procedure TKAlphaBitmap.SaveToStream(Stream: TStream);
var
Size: Integer;
BF: TBitmapFileHeader;
BI: TBitmapInfoHeader;
begin
Size := FWidth * FHeight * 4;
FillChar(BF, SizeOf(TBitmapFileHeader), 0);
BF.bfType := $4D42;
BF.bfSize := SizeOf(TBitmapFileHeader) + SizeOf(TBitmapInfoHeader) + Size;
BF.bfOffBits := SizeOf(TBitmapFileHeader) + SizeOf(TBitmapInfoHeader);
Stream.Write(BF, SizeOf(TBitmapFileHeader));
FillChar(BI, SizeOf(TBitmapInfoHeader), 0);
BI.biSize := SizeOf(TBitmapInfoHeader);
BI.biWidth := FWidth;
BI.biHeight := FHeight;
BI.biPlanes := 1;
BI.biBitCount := 32;
BI.biCompression := BI_RGB;
BI.biSizeImage := Size;
Stream.Write(BI, SizeOf(TBitmapInfoHeader));
Stream.Write(FPixels^, Size);
end;
procedure TKAlphaBitmap.SetHeight(Value: Integer);
begin
SetSize(FWidth, Value);
end;
procedure TKAlphaBitmap.SetPixel(X, Y: Integer; Value: TKColorRec);
begin
if (X >= 0) and (X < FWidth) and (Y >= 0) and (Y < FHeight) then
begin
SwapBR(Value);
{$IFDEF USE_WINAPI}
FPixels[(FHeight - Y - 1) * FWidth + X] := Value;
{$ELSE}
FPixels[Y * FWidth + X] := Value;
{$ENDIF}
FPixelsChanged := True;
end;
end;
procedure TKAlphaBitmap.SetSize(AWidth, AHeight: Integer);
var
{$IFNDEF USE_WINAPI}
ImgFormatDescription: TRawImageDescription;
{$ELSE}
BI: TBitmapInfoHeader;
{$ENDIF}
begin
AWidth := Max(AWidth, 0);
AHeight := Max(AHeight, 0);
if (AWidth <> FWidth) or (AHeight <> FHeight) then
begin
FWidth := AWidth;
FHeight := AHeight;
if FHandle <> 0 then
begin
SelectObject(FCanvas.Handle, FOldBitmap);
DeleteObject(FHandle);
FHandle := 0;
{$IFNDEF USE_WINAPI}
DeleteObject(FMaskHandle);
FMaskHandle := 0;
{$ENDIF}
end;
{$IFNDEF USE_WINAPI}
FImage.SetSize(0, 0);
{$ENDIF}
FPixels := nil;
if (FWidth <> 0) and (FHeight <> 0) then
begin
{$IFNDEF USE_WINAPI}
ImgFormatDescription.Init_BPP32_B8G8R8A8_BIO_TTB(FWidth,FHeight);
FImage.DataDescription := ImgFormatDescription;
FPixelsChanged := True;
UpdateHandle;
{$ELSE}
FillChar(BI, SizeOf(TBitmapInfoHeader), 0);
BI.biSize := SizeOf(TBitmapInfoHeader);
BI.biWidth := FWidth;
BI.biHeight := FHeight;
BI.biPlanes := 1;
BI.biBitCount := 32;
BI.biCompression := BI_RGB;
FHandle := GDICheck(CreateDIBSection(FCanvas.Handle, PBitmapInfo(@BI)^, DIB_RGB_COLORS, Pointer(FPixels), 0, 0));
FOldBitmap := SelectObject(FCanvas.Handle, FHandle);
{$ENDIF}
end;
end;
end;
procedure TKAlphaBitmap.SetWidth(Value: Integer);
begin
SetSize(Value, FWidth);
end;
procedure TKAlphaBitmap.SetTransparent(Value: Boolean);
begin
// does nothing
end;
procedure TKAlphaBitmap.UpdateHandle;
begin
{$IFNDEF USE_WINAPI}
if FPixelsChanged then
begin
PixelsChanged := False;
if FHandle <> 0 then
begin
DeleteObject(FMaskHandle);
DeleteObject(SelectObject(FCanvas.Handle, FOldBitmap));
end;
FImage.CreateBitmaps(FHandle, FMaskHandle, False);
FOldBitmap := SelectObject(FCanvas.Handle, FHandle);
FPixels := PKColorRecs(FImage.PixelData);
end;
{$ENDIF}
end;
procedure TKAlphaBitmap.UpdatePixels;
begin
{$IFNDEF USE_WINAPI}
FImage.LoadFromDevice(FCanvas.Handle);
FPixelsChanged := True;
UpdateHandle;
{$ENDIF}
end;
{$IFDEF USE_WINAPI}
const
cLayeredWndClass = 'KControls drag window';
function DragWndProc(Window: HWnd; Msg, WParam, LParam: Longint): Longint; stdcall;
var
DC: HDC;
PS: TPaintStruct;
AWindow: TKDragWindow;
begin
case Msg of
WM_PAINT:
begin
AWindow := TKDragWindow(GetWindowLong(Window, GWL_USERDATA));
if (AWindow <> nil) and AWindow.BitmapFilled then
begin
if wParam = 0 then
DC := BeginPaint(Window, PS)
else
DC := wParam;
try
BitBlt(DC, 0, 0, AWindow.Bitmap.Width, AWindow.Bitmap.Height,
AWindow.Bitmap.Canvas.Handle, 0, 0, SRCCOPY);
finally
if wParam = 0 then EndPaint(Window, PS);
end;
end;
Result := 1;
end;
else
Result := DefWindowProc(Window, Msg, WParam, LParam);
end;
end;
{$ELSE}
type
{ TKDragForm }
TKDragForm = class(THintWindow)
private
FWindow: TKDragWindow;
procedure WMEraseBkGnd(var Msg: TLMessage); message LM_ERASEBKGND;
protected
procedure Paint; override;
public
constructor CreateDragForm(AWindow: TKDragWindow);
end;
{ TKDragForm }
constructor TKDragForm.CreateDragForm(AWindow: TKDragWindow);
begin
inherited Create(nil);
FWindow := AWindow;
ShowInTaskBar := stNever;
end;
procedure TKDragForm.Paint;
begin
if FWindow.Active and FWindow.BitmapFilled then
Canvas.Draw(0, 0, FWindow.FBitmap);
end;
procedure TKDragForm.WMEraseBkGnd(var Msg: TLMessage);
begin
Msg.Result := 1;
end;
{$ENDIF}
constructor TKDragWindow.Create;
{$IFDEF USE_WINAPI}
var
Cls: Windows.TWndClass;
ExStyle: Cardinal;
{$ENDIF}
begin
inherited;
FActive := False;
FBitmap := TKAlphaBitmap.Create;
FInitialPos := Point(0, 0);
{$IFDEF USE_WINAPI}
FUpdateLayeredWindow := GetProcAddress(GetModuleHandle('user32.dll'), 'UpdateLayeredWindow');
FLayered := Assigned(FUpdateLayeredWindow);
Cls.style := CS_SAVEBITS;
Cls.lpfnWndProc := @DragWndProc;
Cls.cbClsExtra := 0;
Cls.cbWndExtra := 0;
Cls.hInstance := HInstance;
Cls.hIcon := 0;
Cls.hCursor := 0;
Cls.hbrBackground := 0;
Cls.lpszMenuName := nil;
Cls.lpszClassName := cLayeredWndClass;
Windows.RegisterClass(Cls);
ExStyle := WS_EX_TOOLWINDOW or WS_EX_TOPMOST;
if FLayered then
ExStyle := ExStyle or WS_EX_LAYERED or WS_EX_TRANSPARENT;
FWindow := CreateWindowEx(ExStyle, cLayeredWndClass, '', WS_POPUP,
Integer(CW_USEDEFAULT), Integer(CW_USEDEFAULT), Integer(CW_USEDEFAULT),
Integer(CW_USEDEFAULT), 0, 0, HInstance, nil);
Windows.SetWindowLong(FWindow, GWL_USERDATA, Integer(Self));
{$ELSE}
FDragForm := TKDragForm.CreateDragForm(Self);
FLayered := False;
{$ENDIF}
end;
destructor TKDragWindow.Destroy;
begin
inherited;
Hide;
{$IFDEF USE_WINAPI}
DestroyWindow(FWindow);
Windows.UnregisterClass(cLayeredWndClass, HInstance);
{$ELSE}
FDragForm.Free;
{$ENDIF}
FBitmap.Free;
end;
procedure TKDragWindow.Hide;
begin
if FActive then
begin
{$IFDEF USE_WINAPI}
ShowWindow(FWindow, SW_HIDE);
{$ELSE}
FDragForm.Hide;
{$ENDIF}
FActive := False;
end;
end;
procedure TKDragWindow.Show(IniCtrl: TCustomControl; const ARect: TRect;
const InitialPos, CurrentPos: TPoint; MasterAlpha: Byte; Gradient: Boolean);
var
Org: TPoint;
W, H: Integer;
ScreenDC: HDC;
begin
if not (IniCtrl is TKCustomControl) then Exit;
if not FActive then
begin
FActive := True;
FBitmapFilled := False;
FControl := IniCtrl;
FMasterAlpha := MasterAlpha;
FGradient := Gradient;
FInitialPos := InitialPos;
W := ARect.Right - ARect.Left;
H := ARect.Bottom - ARect.Top;
FBitmap.SetSize(W, H);
Org := IniCtrl.ClientToScreen(ARect.TopLeft);
ScreenDC := GetDC(0);
try
FAlphaEffects := GetDeviceCaps(ScreenDC, BITSPIXEL) >= 15;
// because alpha blending is not nice elsewhere
finally
ReleaseDC(0, ScreenDC);
end;
// to be compatible with all LCL widgetsets we must copy the control's part
// while painting in TKCustomControl.Paint!
TKCustomControl(FControl).MemoryCanvas := FBitmap.Canvas;
TKCustomControl(FControl).MemoryCanvasRect := ARect;
TKCustomControl(FControl).Repaint;
{$IFDEF USE_WINAPI}
if FLayered then with FBlend do
begin
BlendOp := AC_SRC_OVER;
BlendFlags := 0;
SourceConstantAlpha := 255;
if FAlphaEffects then
AlphaFormat := AC_SRC_ALPHA
else
AlphaFormat := 0;
end;
SetWindowPos(FWindow, 0, Org.X, Org.Y, W, H,
SWP_NOACTIVATE or SWP_NOZORDER);
{$ELSE}
FDragForm.SetBounds(Org.X, Org.Y, W, H);
{$ENDIF}
Move(CurrentPos);
end;
end;
procedure TKDragWindow.Move(const NewPos: TPoint);
var
R: TRect;
DX, DY: Integer;
BlendColor: TColor;
{$IFDEF USE_WINAPI}
ScreenDC: HDC;
CanvasOrigin: TPoint;
{$ENDIF}
begin
if FActive then
begin
if (TKCustomControl(FControl).MemoryCanvas = nil) and not FBitmapFilled then
begin
FBitmapFilled := True;
FBitmap.UpdatePixels;
if FAlphaEffects then
begin
if FLayered then
BlendColor := clBlack
else
BlendColor := clWhite;
FBitmap.AlphaFill(FMasterAlpha, BlendColor, FGradient, FLayered);
FBitmap.UpdateHandle;
end;
end;
DX := NewPos.X - FInitialPos.X;
DY := NewPos.Y - FInitialPos.Y;
if (DX <> 0) or (DY <> 0) then
begin
FInitialPos := NewPos;
{$IFDEF USE_WINAPI}
GetWindowRect(FWindow, R);
OffsetRect(R, DX, DY);
if FLayered then
begin
R.Right := FBitmap.Width;
R.Bottom := FBitmap.Height;
CanvasOrigin := Point(0, 0);
ScreenDC := GetDC(0);
try
if FUpdateLayeredWindow(FWindow, ScreenDC, @R.TopLeft, PSize(@R.BottomRight),
FBitmap.Canvas.Handle, @CanvasOrigin, clNone, @FBlend, ULW_ALPHA) then
if FBitmapFilled then
ShowWindow(FWindow, SW_SHOWNOACTIVATE);
finally
ReleaseDC(0, ScreenDC);
end;
end
else if FBitmapFilled then
SetWindowPos(FWindow, 0, R.Left, R.Top, 0, 0,
SWP_NOACTIVATE or SWP_NOSIZE or SWP_NOZORDER or SWP_SHOWWINDOW);
{$ELSE}
R := FDragForm.BoundsRect;
OffsetRect(R, DX, DY);
FDragForm.BoundsRect := R;
if FBitmapFilled then
begin
FDragForm.Visible := True;
SetCaptureControl(FControl);
end;
{$ENDIF}
end;
end;
end;
{ TKHintWindow }
constructor TKHintWindow.Create(AOwner: TComponent);
begin
inherited;
{$IFDEF FPC}
ShowInTaskBar := stNever;
{$ENDIF}
DoubleBuffered := True;
end;
procedure TKHintWindow.ShowAt(const Origin: TPoint);
begin
ActivateHint(Rect(Origin.X, Origin.Y, Origin.X + FExtent.X + 10, Origin.Y + FExtent.Y + 10), '');
end;
procedure TKHintWindow.WMEraseBkGnd(var Msg: TLMessage);
begin
Msg.Result := 1;
end;
{ TKTextHint }
constructor TKTextHint.Create(AOwner: TComponent);
begin
inherited;
FText := '';
end;
procedure TKTextHint.Paint;
var
R: TRect;
begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := clInfoBk;
Canvas.FillRect(ClientRect);
Canvas.Brush.Style := bsClear;
R := Rect(0, 0, FExtent.X + 10, FExtent.Y + 10);
DrawAlignedText(Canvas, R, halLeft, valCenter,
5, 5, FText, clInfoBk, [taEndEllipsis, taWordBreak, taLineBreak])
end;
procedure TKTextHint.SetText(const Value: {$IFDEF STRING_IS_UNICODE}string{$ELSE}WideString{$ENDIF});
var
R: TRect;
begin
if Value <> FText then
begin
FText := Value;
R := Rect(0, 0, 300, 0);
DrawAlignedText(Canvas, R, halLeft, valCenter,
0, 0, FText, clInfoBk, [taCalcRect, taWordBreak, taLineBreak]);
FExtent.X := R.Right - R.Left;
FExtent.Y := R.Bottom - R.Top;
end;
end;
{ TKGraphicHint }
constructor TKGraphicHint.Create(AOwner: TComponent);
begin
inherited;
FGraphic := nil;
{$IFDEF FPC}
ShowInTaskBar := stNever;
{$ENDIF}
DoubleBuffered := True;
end;
procedure TKGraphicHint.Paint;
begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := clInfoBk;
Canvas.FillRect(ClientRect);
if Assigned(FGraphic) then
Canvas.Draw(5, 5, FGraphic)
end;
procedure TKGraphicHint.SetGraphic(const Value: TGraphic);
begin
if Value <> FGraphic then
begin
FGraphic := Value;
FExtent.X := FGraphic.Width;
FExtent.Y := FGraphic.Height;
end;
end;
end.
|
unit BufferListForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TBufferListFrm = class(TForm)
BufferListBox: TListBox;
OKButton: TButton;
CancelButton: TButton;
procedure BufferListBoxDblClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
var
g_Top : Integer = -1;
g_Left : Integer = -1;
g_Width : Integer = 0;
g_Height : Integer = 0;
procedure TBufferListFrm.BufferListBoxDblClick(Sender: TObject);
begin
if BufferListBox.ItemIndex > -1 then ModalResult := mrOK;
end;
procedure TBufferListFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
g_Width := Width;
g_Height := Height;
g_Top := Top;
g_Left := Left;
end;
procedure TBufferListFrm.FormShow(Sender: TObject);
begin
if (g_Top >= 0) then
Top := g_Top;
if (g_Left >= 0) then
Left := g_Left;
if (g_Width > 0) then
Width := g_Width;
if (g_Height > 0) then
Height := g_Height;
end;
end.
|
unit FCM_Unit;
interface
uses IdHTTP, IdGlobal, IdMultipartFormData, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL,
XSuperObject, System.Classes, System.SysUtils, System.DateUtils;
type
TFCM = class(TThread)
private
{ Private declarations }
public
HTTPClient: TIdHTTP;
IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL;
FTopics : ISuperArray;
FFcmType : Byte;
FObj : ISuperObject;
Key : string;
Host : string; //https://fcm.googleapis.com/fcm/send
FCM_MessageID : int64;
FCM_MessageTime : TDateTime;
constructor Create(Topics: ISuperArray; Obj: ISuperObject; FcmType: byte);
protected
procedure Execute; override;
end;
const
FCM_NOTICE = 1;
FCM_DATA = 2;
var
FCM : TFCM;
implementation
uses Service;
constructor TFCM.Create(Topics: ISuperArray; Obj: ISuperObject; FcmType: byte);
begin
inherited Create(False);
FreeOnTerminate := True;
FTopics := Topics.Clone;
FFcmType := FcmType;
FObj := Obj.Clone;
HTTPClient := TIdHTTP.Create(nil);
IdSSLIOHandlerSocketOpenSSL1 := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
HTTPClient.IOHandler := IdSSLIOHandlerSocketOpenSSL1;
HTTPClient.Request.Accept := 'json';
HTTPClient.Request.AcceptCharSet := 'utf-8';
HTTPClient.Request.CharSet := 'utf-8';
HTTPClient.Request.ContentType := 'application/json';
HTTPClient.IOHandler.ReadTimeout := 3;
end;
procedure TFCM.Execute;
var ToSend, ToRead : TStringStream; Host: string;
RX, TX: string;
DataJSON, JSON: ISuperObject;
i: integer; Note: ISuperObject;
Body: string;
begin
if FTopics.Length = 0 then Exit;
// HTTPClient.Request.CustomHeaders.Add('Authorization:key=' + SynCore.KeyFCM);
for i := 0 to FTopics.Length - 1 do
begin
ToRead := TStringStream.Create;
DataJSON := SO();
DataJSON.S['to'] := '/topics/' + FTopics.S[i];
DataJSON.S['priority'] := 'high';
if FFcmType = FCM_NOTICE then
begin
Note := SO();
Note.S['title'] := 'ÎÁ Äîçîð-Ð';
Body := FObj.S['body'];
Note.S['body'] := Body;
DataJSON.O['notification'] := Note;
end
else
DataJSON.O['data'] := FObj;
TX := DataJSON.AsJSON;
ToSend := TStringStream.Create(TX, TEncoding.UTF8);
Host := 'https://fcm.googleapis.com/fcm/send';
try
HTTPClient.Post(Host, ToSend, ToRead);
RX := ToRead.DataString;
DataJSON := SO(RX);
if DataJSON.Contains('message_id') then
FCM_MessageID := DataJSON.I['message_id']
else
FCM_MessageID := -1;
FCM_MessageTime := Now;
except
on E: Exception do begin
RX := '';
end;
end;
ToSend.Free;
ToRead.Free;
end;
end;
end.
|
unit MFichas.Model.Caixa.Metodos.Interfaces;
interface
uses
MFichas.Model.Caixa.Interfaces;
type
iModelCaixaMetodosFactory = interface
['{430FF626-FC73-4CEE-BA4F-E98DEF26218B}']
function CaixaMetodoAbrir(AParent: iModelCaixa) : iModelCaixaMetodosAbrir;
function CaixaMetodoFechar(AParent: iModelCaixa) : iModelCaixaMetodosFechar;
function CaixaMetodoSuprimento(AParent: iModelCaixa): iModelCaixaMetodosSuprimento;
function CaixaMetodoSangria (AParent: iModelCaixa): iModelCaixaMetodosSangria;
end;
implementation
end.
|
unit FDirectory;
interface
uses
SysUtils,FStrUtiles,EntSal,Classes;
type
IDirectory = interface
end;
TFile = class(Tobject)
private
AName:String;
AFullName:String;
AExtension:String;
ASize:Integer;
AIsHidden:Boolean;
AIsSystemFile:Boolean;
AIsReadOnly:Boolean;
AExists:Boolean;
procedure setName(value:String);
procedure setFullName(value:String);
procedure setExtension(value:String);
procedure setSize(value:Integer);
procedure setIsHidden(value:Boolean);
procedure setIsSystemFile(value:Boolean);
procedure setIsReadOnly(value:Boolean);
procedure setExists(value:Boolean);
procedure Inicializar;
procedure Clone(var archivoDestino:TFile);
public
property Name:String Read AName Write setName;
property FullName:String Read AFullName Write setFullName;
property Size:Integer Read Asize Write setSize;
property IsHidden:Boolean Read AIsHidden Write setIsHidden;
property IsSystemFile:Boolean Read AIsSystemFile write setIsSystemFile;
property IsReadOnly:Boolean Read AIsReadOnly write setIsReadOnly;
property Exists:Boolean Read AExists write setExists;
Constructor Create;overload;
Constructor Create(path:String);overload;
published
property Extension:String Read AExtension;
end;
TFiles = Array Of TFile;
TDirectoryItem = class(TObject)
private
AName:String;
AFullName:String;
AExists:Boolean;
procedure setName(value:String);
procedure setFullName(value:String);
procedure setExists(value:Boolean);
procedure Inicializar;
public
property Name:String Read AName Write setName;
property FullName:String read AFullName Write setFullName;
property Exists:Boolean read AExists Write setExists;
Constructor Create; Overload;
Constructor Create(path:String); Overload;
end;
TDirectories = Array of TDirectoryItem;
TDirectory = class(TDirectoryItem) //class(TInterfacedObject,IDirectory)
private
APath:String;
ArDirectories:TDirectories;
ArFiles:TFiles;
procedure setPath(Value:String);
function validarRuta:Boolean;
public
property Path:String Read APath Write setPath;
function Exists():Boolean;
function getDirectories():TDirectories;
function getFiles(extensiones:String=''):TFiles;
function getAllFiles(extensiones:String=''):TFiles;
function extraerArchivos(path:String;extensiones:String=''):TFiles;
end;
implementation
{TFile}
Constructor TFile.Create;
begin
inherited;
end;
Constructor TFile.Create(path:String);
begin
self.AFullName := path;
self.Inicializar;
end;
procedure TFile.setName(value:String);
begin
self.AName := value;
self.setExtension(value);
end;
procedure TFile.setFullName(value:String);
begin
self.AFullName := value;
end;
procedure TFile.setExtension(value:String);
var posDot:Integer;
tmpExt:String;
begin
tmpExt := '';
posDot:= getIndexPosFromSTR(value,'.',length(value),True);
if posDot>-1 then tmpExt:=StrRight(value,Length(value)-posDot);
self.AExtension := tmpExt;
end;
procedure TFile.setSize(value:Integer);
begin
self.ASize := value;
end;
procedure TFile.setIsHidden(value:Boolean);
begin
self.AIsHidden := value;
end;
procedure TFile.setIsSystemFile(value:Boolean);
begin
self.AIsSystemFile := value;
end;
procedure TFile.setIsReadOnly(value:Boolean);
begin
self.AIsReadOnly := value;
end;
procedure TFile.setExists(value:Boolean);
begin
self.Exists := value;
end;
procedure TFile.Inicializar;
var fSlash:Integer;
attr:Integer;
archivo:File;
begin
//Inicializa un Archivo File.
if self.AFullName<>'' then begin
self.AExists := FileExists(self.AFullName);
fslash := getIndexPosFromSTR(self.AFullName,'\',length(self.AFullName),True);
self.Name := STRRight(self.AFullName,Length(self.FullName)-fslash);
if self.AExists then begin
attr := FileGetAttr(self.AFullName);
if (attr and faReadOnly) > 0 then self.AIsReadOnly := True
else self.AIsReadOnly := False;
if (attr and faSysFile) > 0 then self.AIsSystemFile := True
else self.AIsSystemFile := False;
if (attr and faHidden) > 0 then self.AIsHidden := True
else self.AIsHidden := False;
self.ASize := TamanoArchivo(self.FullName);
end else begin
self.AIsReadOnly := false;
self.AIsSystemFile:=false;
self.AIsHidden := false;
end;
end;
end;
procedure TFile.Clone(var archivoDestino:TFile);
begin
//Clona el archivo.
archivoDestino := TFile.Create(self.FullName);
end;
{TDirectoryItem}
Constructor TDirectoryItem.Create;
begin
inherited;
self.AFullName := '';
end;
Constructor TDirectoryItem.Create(path:String);
begin
self.AFullName := path;
end;
procedure TDirectoryItem.Inicializar;
begin
//Inicializa el Directorio.
if self.AFullName <> '' then begin
end;
end;
procedure TDirectoryItem.setName(value:String);
begin
self.AName:=value;
end;
procedure TDirectoryItem.setFullName(value:String);
begin
self.AFullName := value;
end;
procedure TDirectoryItem.setExists(value:Boolean);
begin
self.AExists := value;
end;
{TDirectory}
procedure TDirectory.setPath(Value:String);
begin
APath := Value;
end;
function TDirectory.validarRuta:Boolean;
begin
If self.APath = '' then begin
raise Exception.Create('Error. No se ha declarado la Ruta (Path)');
Result := False;
Exit;
end;
Result := True;
end;
Function TDirectory.Exists:Boolean;
begin
//Regresa verdadero si encuentra la carpeta
if self.validarRuta then begin
Result := DirectoryExists(self.APath);
exit;
end;
Result := False;
end;
function TDirectory.getDirectories:TDirectories;
var Rec:TSearchRec;
Contador :Integer;
begin
if not self.validarRuta then Exit;
Contador := 0;
if FindFirst(self.APath + '\*', faAnyFile, Rec) = 0 then
try
repeat
if (Rec.Name = '.') or (Rec.Name = '..') then
continue;
if (Rec.Attr and faVolumeID) = faVolumeID then
continue; // nothing useful to do with volume IDs
if (Rec.Attr and faHidden) = faHidden then
continue; // honor the OS "hidden" setting
if (Rec.Attr and faDirectory) = faDirectory then begin
inc(Contador,1);
setLength(self.ArDirectories,Contador);
self.ArDirectories[Contador -1] := TDirectoryItem.Create;
self.ArDirectories[Contador -1].setName(Rec.Name);
self.ArDirectories[Contador - 1].setFullName(self.APath + '\' + Rec.Name);
end;
until FindNext(Rec) <> 0;
finally
SysUtils.FindClose(Rec);
end;
Result := self.ArDirectories;
end;
function TDirectory.getFiles(extensiones:String=''):TFiles;
var listaEx:TStringList;
Rec:TSearchRec;
Contador:Integer;
tmpFile : TFile;
begin
//Retorna los archivos
if trim(extensiones) <> '' then listaEx := SplitStr(UC(extensiones),',');
if not self.validarRuta then Exit;
Contador := 0;
if FindFirst(self.APath + '\*', faAnyFile, Rec)=0 then begin
try
repeat
if ((Rec.Attr and faArchive) = faArchive) then begin
tmpFile := TFile.Create(self.Path+'\'+Rec.Name);
if trim(extensiones) <> '' then
if not existsIn(UC(tmpFile.Extension),listaEx) then Continue;
inc(Contador,1);
setLength(self.ArFiles,Contador);
self.ArFiles[Contador - 1] := TFile.Create(self.Path+'\'+Rec.Name);
end else begin
Continue;
end;
until Findnext(Rec)<>0;
finally
Sysutils.FindClose(Rec);
end;
end;
Result := self.ArFiles;
end;
function TDirectory.getAllFiles(extensiones:String=''):TFiles;
begin
//Retorna todos los archivos.
Result := self.extraerArchivos(self.Path,extensiones);
end;
function TDirectory.extraerArchivos(path:String;extensiones:String=''):TFiles;
var carpeta:TDirectory; archivos:TFiles; subcarpetas:TDirectories;
i,j:Integer;
subFiles, tmpArch:TFiles;
begin
//Exrae los archivos.
carpeta := TDirectory.Create;
carpeta.setPath(path);
subcarpetas := carpeta.getDirectories;
archivos := carpeta.getFiles(extensiones);
for i:=0 to (Length(subcarpetas) - 1) do begin
subFiles := self.extraerArchivos(subcarpetas[i].FullName);
for j:=0 to (Length(subFiles)-1) do begin
setLength(tmpArch,Length(tmpArch)+1);
subFiles[j].Clone(tmpArch[Length(tmpArch)-1]);
end;
end;
for i:=0 to (Length(archivos) - 1) do begin
setLength(tmpArch, Length(tmpArch)+1);
archivos[i].Clone(tmpArch[Length(tmpArch)-1]);
archivos[i].Free;
end;
carpeta.Free;
Result := tmpArch;
end;
end.
{
faAnyFile : Any file
faReadOnly : Read-only files
faHidden : Hidden files
faSysFile : System files
faVolumeID : Volume ID files
faDirectory : Directory files
faArchive : Archive files
}
|
unit LocationSearchUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TLocationSearch = class(TBaseExample)
public
procedure Execute(Query: String; Fields: TArray<String>);
end;
implementation
uses AddressBookContactUnit, CommonTypesUnit;
procedure TLocationSearch.Execute(Query: String; Fields: TArray<String>);
var
ErrorString: String;
Total: integer;
FindedResults: T2DimensionalStringArray;
Limit, Offset: integer;
begin
Limit := 10;
Offset := 0;
FindedResults := Route4MeManager.AddressBookContact.Find(
Query, Fields, Limit, Offset, Total, ErrorString);
try
WriteLn('');
if (Length(FindedResults) > 0) then
begin
WriteLn(Format('LocationSearch executed successfully, ' +
'%d contacts returned, total = %d', [Length(FindedResults), Total]));
WriteLn('');
end
else
WriteLn(Format('LocationSearch error: "%s"', [ErrorString]));
finally
Finalize(FindedResults);
end;
end;
end.
|
unit uUniSqlService;
interface
uses
SysUtils, Classes, Uni, Db, uServices, UniScript;
type
TMetadataLocateProc = function (Sender: TUniMetaData; AParams: array of Variant): Boolean;
TAssignParamsProc = procedure (Sender: TUniParams; AParams: array of Variant);
TUniSqlService = class(TInterfacedObject, ISqlService)
private
FConnection: TUniConnection;
function InternalSqlCalc(ASqlText: String; AParams: array of Variant;
AAssignParamsProc: TAssignParamsProc): Variant;
function InternalSqlExec(ASqlText: String; AParams: array of Variant;
AAssignParamsProc: TAssignParamsProc): Variant;
function InternalSqlExecSp(AStoredProcedureName: String; AParams: array of
Variant; AAssignParamsProc: TAssignParamsProc): Variant;
function InternalSqlSelect(ASqlText: String; AParams: array of Variant;
AAssignParamsProc: TAssignParamsProc): TDataSet;
function MetadataExists(AMetadataKind: string; AParams: array of Variant;
AMetadataLocateProc: TMetadataLocateProc): Boolean;
public
constructor Create(AConnection: TUniConnection);
function ColumnExists(ATableName, AColumnName: string): Boolean; stdcall;
function DatabaseToString: string; stdcall;
function DataModule: TDataModule; stdcall;
function GetCurrentDbVersion: Integer; stdcall;
procedure RefreshDataSet(ADataSet: TDataSet); stdcall;
procedure ScanDataSet(ADataSet: TDataSet; RecordAction:
TDataSetRecordAction; AContext: IInterface); stdcall;
procedure SetCurrentDbVersion(AVersion: Integer); stdcall;
function SqlCalc(ASqlText: String; AParams: array of Variant): Variant;
stdcall;
function SqlCalcIntf(ASqlText: String; AParams: array of IInterface):
Variant; stdcall;
function SqlExec(ASqlText: String; AParams: array of Variant): Variant;
stdcall;
function SqlExecIntf(ASqlText: String; AParams: array of IInterface):
Variant; stdcall;
function SqlExecScript(ASqlText: String): Boolean; stdcall;
function SqlExecSp(AStoredProcedureName: String; AParams: array of
Variant): Variant; stdcall;
function SqlExecSpIntf(AStoredProcedureName: String; AParams: array of
IInterface): Variant; stdcall;
function SqlSelect(ASqlText: String; AParams: array of Variant): TDataSet;
stdcall;
function SqlSelectIntf(ASqlText: String; AParams: array of IInterface):
TDataSet; stdcall;
function StoredProcedureExists(AStoredProcedureName: String): Boolean;
stdcall;
function TableExists(ATableName: string): Boolean; stdcall;
function UpdateDatabase(RequiredDbVersion: Integer): Boolean; stdcall;
end;
implementation
uses
variants, Controls, Dialogs, Forms, uProgressForm, JclAnsiStrings,
uDataSetInterface, uKeyValue;
procedure AssignParamsFromDataSet(Sender: TUniParams; ADataSet: TDataSet);
var
Field: TField;
I: Integer;
begin
for I := 0 to Sender.Count-1 do
begin
Field := ADataSet.FindField(Sender[I].Name);
if Field <> nil then
Sender[I].Value := Field.Value;
end;
end;
procedure AssignInterfaceParams(Sender: TUniParams; AParams: array of Variant);
var
D: IDataSetInterface;
I: Integer;
P: IKeyValue;
Pbn: TUniParam;
begin
for I := Low(AParams) to High(AParams) do
begin
if VarIsType(AParams[I], varUnknown) then
begin
if Supports(AParams[I], IDataSetInterface, D) then
AssignParamsFromDataSet(Sender, D.DataSet);
if Supports(AParams[I], IKeyValue, P) then
begin
Pbn := Sender.FindParam(VarToStr(P.Key));
if Pbn <> nil then
Pbn.Value := P.Value;
end;
end;
end;
end;
procedure AssignParamsByOrderNum(Sender: TUniParams; AParams: array of Variant);
var
I: Integer;
begin
for I := 0 to Sender.Count-1 do
begin
Sender[I].Value := AParams[I];
end;
end;
function LocateColumn(Sender: TUniMetaData; AParams: array of Variant): Boolean;
begin
Result := Sender.Locate('Table_Name;Column_Name', VarArrayOf(AParams), [loCaseInsensitive])
end;
function LocateSp(Sender: TUniMetaData; AParams: array of Variant): Boolean;
begin
Result := Sender.Locate('Procedure_Name', VarArrayOf(AParams),
[loCaseInsensitive])
end;
function LocateTable(Sender: TUniMetaData; AParams: array of Variant): Boolean;
begin
Result := Sender.Locate('Table_Name', VarArrayOf(AParams), [loCaseInsensitive])
end;
{
******************************** TUniSqlService ********************************
}
constructor TUniSqlService.Create(AConnection: TUniConnection);
begin
inherited Create;
FConnection := AConnection;
end;
function TUniSqlService.ColumnExists(ATableName, AColumnName: string): Boolean;
begin
Result := MetadataExists('Columns', [ATableName, AColumnName], LocateColumn);
end;
function TUniSqlService.DatabaseToString: string;
begin
Result := 'Нет подключения к БД';
if (FConnection <> nil) and (FConnection.Connected) then
Result := Format('Сервер БД: "%s". База данных "%s"',
[FConnection.Server, FConnection.Database]);
end;
function TUniSqlService.DataModule: TDataModule;
begin
Result := nil;
if FConnection <> nil then
Result := FConnection.Owner as TDataModule;
end;
function TUniSqlService.GetCurrentDbVersion: Integer;
var
V: Variant;
begin
Result := 1;
if TableExists('DbVersion') then
begin
V := SqlCalc('SELECT MAX(CurrentVersion) FROM DbVersion', []);
if VarIsNull(V) then
V := 1;
Result := V;
end;
end;
function TUniSqlService.InternalSqlCalc(ASqlText: String; AParams: array of
Variant; AAssignParamsProc: TAssignParamsProc): Variant;
var
Q: TDataSet;
begin
Result := Null;
Q := InternalSqlSelect(ASqlText, AParams, AAssignParamsProc);
if (Q <> nil) then
begin
try
if (not Q.Eof) then
Result := Q.Fields[0].Value
finally
Q.Free;
end;
end;
end;
function TUniSqlService.InternalSqlExec(ASqlText: String; AParams: array of
Variant; AAssignParamsProc: TAssignParamsProc): Variant;
var
I: Integer;
Q: TUniSQL;
begin
Result := Null;
Q := TUniSQL.Create(FConnection.Owner);
try
Q.Connection := FConnection;
Q.SQL.Text := ASqlText;
AAssignParamsProc(Q.Params, AParams);
Q.Execute;
if Q.Params.Count > 0 then
begin
Result := VarArrayCreate([0, Q.Params.Count-1], varVariant);
for I := 0 to Q.Params.Count-1 do
Result[I] := Q.Params[I].Value;
end;
finally
Q.Free;
end;
end;
function TUniSqlService.InternalSqlExecSp(AStoredProcedureName: String;
AParams: array of Variant; AAssignParamsProc: TAssignParamsProc): Variant;
var
I: Integer;
Q: TUniStoredProc;
begin
Result := Null;
Q := TUniStoredProc.Create(FConnection.Owner);
try
Q.Connection := FConnection;
Q.StoredProcName := AStoredProcedureName;
Q.PrepareSQL();
AAssignParamsProc(Q.Params, AParams);
Q.Execute;
if Q.Params.Count > 0 then
begin
Result := VarArrayCreate([0, Q.Params.Count-1], varVariant);
for I := 0 to Q.Params.Count-1 do
Result[I] := Q.Params[I].Value;
end;
finally
Q.Free;
end;
end;
function TUniSqlService.InternalSqlSelect(ASqlText: String; AParams: array of
Variant; AAssignParamsProc: TAssignParamsProc): TDataSet;
var
Q: TUniQuery;
begin
Result := nil;
Q := TUniQuery.Create(FConnection.Owner);
Q.Connection := FConnection;
Q.SQL.Text := ASqlText;
Q.Params.ParseSQL(ASqlText, True);
AAssignParamsProc(Q.Params, AParams);
try
Q.Open;
Result := Q;
except
on E: Exception do Q.Free;
end;
end;
function TUniSqlService.MetadataExists(AMetadataKind: string; AParams: array of
Variant; AMetadataLocateProc: TMetadataLocateProc): Boolean;
var
Q: TUniMetaData;
begin
Q := TUniMetaData.Create(FConnection.Owner);
try
Q.Connection := FConnection;
Q.MetaDataKind := AMetadataKind;
Q.Open;
Result := AMetadataLocateProc(Q, AParams);
Q.Close;
finally
Q.Free;
end;
end;
procedure TUniSqlService.RefreshDataSet(ADataSet: TDataSet);
var
V: Variant;
begin
if ADataSet <> nil then
begin
V := ADataSet.Fields[0].Value;
ADataSet.DisableControls;
ADataSet.Close;
ADataSet.Open;
if not VarIsNull(V) then
ADataSet.Locate(ADataSet.Fields[0].FieldName, V, []);
ADataSet.EnableControls;
end;
end;
procedure TUniSqlService.ScanDataSet(ADataSet: TDataSet; RecordAction:
TDataSetRecordAction; AContext: IInterface);
var
V: Variant;
begin
if ADataSet <> nil then
begin
V := ADataSet.Fields[0].Value;
ADataSet.DisableControls;
with ADataSet do
begin
First;
while not Eof do
begin
if Assigned(RecordAction) then
RecordAction(ADataSet, AContext);
Next;
end;
end;
if not VarIsNull(V) then
ADataSet.Locate(ADataSet.Fields[0].FieldName, V, []);
ADataSet.EnableControls;
end;
end;
procedure TUniSqlService.SetCurrentDbVersion(AVersion: Integer);
begin
SqlExec('INSERT INTO DbVersion (CurrentVersion) VALUES (:Version)', [AVersion]);
end;
function TUniSqlService.SqlCalc(ASqlText: String; AParams: array of Variant):
Variant;
begin
Result := InternalSqlCalc(ASqlText, AParams, AssignParamsByOrderNum);
end;
function TUniSqlService.SqlCalcIntf(ASqlText: String; AParams: array of
IInterface): Variant;
var
I: Integer;
VarArr: array of Variant;
begin
SetLength(VarArr, Length(AParams));
for I := 0 to Length(AParams)-1 do
VarArr[I] := AParams[I];
Result := InternalSqlCalc(ASqlText, VarArr, AssignInterfaceParams);
end;
function TUniSqlService.SqlExec(ASqlText: String; AParams: array of Variant):
Variant;
begin
Result := InternalSqlExec(ASqlText, AParams, AssignParamsByOrderNum);
end;
function TUniSqlService.SqlExecIntf(ASqlText: String; AParams: array of
IInterface): Variant;
var
I: Integer;
VarArr: array of Variant;
begin
SetLength(VarArr, Length(AParams));
for I := 0 to Length(AParams)-1 do
VarArr[I] := AParams[I];
Result := InternalSqlExec(ASqlText, VarArr, AssignInterfaceParams);
end;
function TUniSqlService.SqlExecScript(ASqlText: String): Boolean;
var
Q: TUniScript;
begin
Q := TUniScript.Create(FConnection.Owner);
try
Q.Connection := FConnection;
Q.SQL.Text := ASqlText;
Q.Execute;
Result := True;
finally
Q.Free;
end;
end;
function TUniSqlService.SqlExecSp(AStoredProcedureName: String; AParams: array
of Variant): Variant;
begin
Result := InternalSqlExecSp(AStoredProcedureName, AParams, AssignParamsByOrderNum);
end;
function TUniSqlService.SqlExecSpIntf(AStoredProcedureName: String; AParams:
array of IInterface): Variant;
var
I: Integer;
VarArr: array of Variant;
begin
SetLength(VarArr, Length(AParams));
for I := 0 to Length(AParams)-1 do
VarArr[I] := AParams[I];
Result := InternalSqlExecSp(AStoredProcedureName, VarArr, AssignInterfaceParams);
end;
function TUniSqlService.SqlSelect(ASqlText: String; AParams: array of Variant):
TDataSet;
begin
Result := InternalSqlSelect(ASqlText, AParams, AssignParamsByOrderNum);
end;
function TUniSqlService.SqlSelectIntf(ASqlText: String; AParams: array of
IInterface): TDataSet;
var
I: Integer;
VarArr: array of Variant;
begin
SetLength(VarArr, Length(AParams));
for I := 0 to Length(AParams)-1 do
VarArr[I] := AParams[I];
Result := InternalSqlSelect(ASqlText, VarArr, AssignInterfaceParams);
end;
function TUniSqlService.StoredProcedureExists(AStoredProcedureName: String):
Boolean;
begin
Result := MetadataExists('StoredProcedures', [AStoredProcedureName], LocateSp)
end;
function TUniSqlService.TableExists(ATableName: string): Boolean;
begin
Result := MetadataExists('Tables', [ATableName], LocateTable)
end;
function TUniSqlService.UpdateDatabase(RequiredDbVersion: Integer): Boolean;
var
CurrentDbVersion: Integer;
FileName: string;
MessageText: string;
Script: TUniScript;
begin
Result := True;
CurrentDbVersion := GetCurrentDbVersion();
if (CurrentDbVersion < RequiredDbVersion) then
begin
Result := False;
MessageText := Format('Текущая версия БД = %d , для работы требуется версия %d.'
+ #13#10 + 'Обновить структуру БД ? (требуется монопольный доступ к БД)',
[CurrentDbVersion, RequiredDbVersion]);
if IsPositiveResult(MessageDlg(MessageText, mtInformation, mbOkCancel, 0)) then
begin
while CurrentDbVersion < RequiredDbVersion do
begin
FileName := ExtractFilePath(Application.ExeName) +
'UpdateScript\Update' + IntToStr(CurrentDbVersion) + '.sql';
MessageText := Format('Обновление БД до версии %d', [CurrentDbVersion+1]);
ShowProgress(MessageText, CurrentDbVersion, RequiredDbVersion, False);
if FileExists(FileName) then
begin
Script := TUniScript.Create(FConnection.Owner);
Script.Connection := FConnection;
Script.SQL.Text := FileToString(FileName);
try
Script.Execute;
Inc(CurrentDbVersion);
SetCurrentDbVersion(CurrentDbVersion);
Result := True;
except
on E: Exception do
begin
HideProgress;
Result := False;
MessageDlg('Ошибка исполнения скрипта обновления "' + E.Message +
'"', mtError, [mbOK], 0);
end;
end;
Script.Free;
end
else
begin
HideProgress;
MessageDlg('Файл скрипта обновления "' + FileName + '" не найден', mtError, [mbOK], 0);
Result := False;
end;
if not Result then Break;
end;
end;
HideProgress;
if Result then
begin
MessageDlg('Обновление БД успешно проведено. Текущая версия БД = ' +
IntToStr(CurrentDbVersion), mtInformation, [mbOK], 0);
end;
end;
end;
end.
|
unit BalanceService;
interface
uses
JunoApi4Delphi.Interfaces, REST.Types;
type
TBalanceService = class(TInterfacedObject, iBalanceService)
private
FParent : iJunoApi4DelphiConig;
FAuth : iAuthorizationService;
public
constructor Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService);
destructor Destroy; override;
class function New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iBalanceService;
function Balance : String;
end;
implementation
uses
RESTRequest4D, System.JSON, System.SysUtils, Balance, REST.Json;
CONST
BALANCE_ENDPOINT = '/balance';
{ TBalanceService }
function TBalanceService.Balance: String;
var
JSONObj : TJSONObject;
Balance : TBalance;
begin
JsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(
TRequest.New
.BaseURL(FParent.ResourceEndpoint + BALANCE_ENDPOINT)
.Token(FAuth.Token)
.AddParam('X-Api-Version','2',pkHTTPHEADER)
.AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER)
.Get.Content), 0) as TJSONObject;
Balance := TJson.JsonToObject<TBalance>(JsonObj);
Result := 'Transferable:' + FloatToStr(Balance.TransferableBalance) +#13#10+
'Withheld: ' + FloatToStr(Balance.WithheldBalance) +#13#10+
'Balance:' + FloatToStr(Balance.Balance);
end;
constructor TBalanceService.Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService);
begin
FParent := Parent;
FAuth := AuthService;
end;
destructor TBalanceService.Destroy;
begin
inherited;
end;
class function TBalanceService.New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iBalanceService;
begin
Result := Self.Create(Parent, AuthService);
end;
end.
|
unit uBaseConh;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBaseCadastro, Data.DB, Vcl.StdCtrls,
Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.ComCtrls, uDMBaseConh,
uBaseConhController, Vcl.Mask, Vcl.DBCtrls, uFuncoesSIDomper, Vcl.OleCtnrs,
uFraUsuario, uFraTipo, uFraStatus, uFraModulo, uFraProduto, uEnumerador,
uPosicaoBotao, uBaseConhDetalhe, uParametrosController, uDepartamentoController;
type
TfrmBaseConh = class(TfrmBaseCadastro)
PageControl1: TPageControl;
tsPrincipal: TTabSheet;
Panel7: TPanel;
edtCodigo: TDBEdit;
Label4: TLabel;
Label6: TLabel;
edtData: TDBEdit;
edtCodProduto: TDBEdit;
Label9: TLabel;
DBEdit5: TDBEdit;
btnProduto: TSpeedButton;
edtCodUsuario: TDBEdit;
Label10: TLabel;
DBEdit7: TDBEdit;
edtNome: TDBEdit;
Label11: TLabel;
edtCodTipo: TDBEdit;
Label12: TLabel;
DBEdit10: TDBEdit;
btnTipo: TSpeedButton;
edtCodStatus: TDBEdit;
Label13: TLabel;
DBEdit12: TDBEdit;
btnStatus: TSpeedButton;
Label14: TLabel;
DBMemo1: TDBMemo;
Label15: TLabel;
edtNomeArquivo: TDBEdit;
btnAnexar: TSpeedButton;
btnVisualizar: TSpeedButton;
dlgAbrirArquivo: TOpenDialog;
tsFiltroModulo: TTabSheet;
Panel8: TPanel;
tsFiltroUsuario: TTabSheet;
Panel9: TPanel;
FraUsuario: TFraUsuario;
tsFiltroTipo: TTabSheet;
tsFiltroStatus: TTabSheet;
Panel10: TPanel;
Panel11: TPanel;
FraTipo: TFraTipo;
FraStatus: TFraStatus;
Label39: TLabel;
edtDataInicial: TMaskEdit;
edtDataFinal: TMaskEdit;
Label40: TLabel;
edtCodModulo: TDBEdit;
DBEdit3: TDBEdit;
btnModulo: TSpeedButton;
Label5: TLabel;
FraModulo: TFraModulo;
lblMensagem: TLabel;
btnDetalhes: TBitBtn;
btnDetalhes2: TBitBtn;
procedure btnAnexarClick(Sender: TObject);
procedure btnProdutoClick(Sender: TObject);
procedure edtDescricaoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnFiltroClick(Sender: TObject);
procedure dbDadosKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormDestroy(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure btnFecharEdicaoClick(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
procedure btnModuloClick(Sender: TObject);
procedure btnStatusClick(Sender: TObject);
procedure btnTipoClick(Sender: TObject);
procedure btnVisualizarClick(Sender: TObject);
procedure cbbCamposChange(Sender: TObject);
procedure DBMemo1Enter(Sender: TObject);
procedure DBMemo1Exit(Sender: TObject);
procedure DBMemo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edtCodModuloExit(Sender: TObject);
procedure edtCodProdutoExit(Sender: TObject);
procedure edtCodProdutoKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
procedure edtCodStatusExit(Sender: TObject);
procedure edtCodTipoExit(Sender: TObject);
procedure edtCodUsuarioExit(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dbDadosTitleClick(Column: TColumn);
procedure FraStatusbtnProcClick(Sender: TObject);
procedure FraTipobtnProcClick(Sender: TObject);
procedure FraStatusedtCodigoEnter(Sender: TObject);
procedure FraTipoedtCodigoEnter(Sender: TObject);
procedure btnDetalhesClick(Sender: TObject);
procedure btnDetalhes2Click(Sender: TObject);
procedure btnFiltrarClick(Sender: TObject);
private
{ Private declarations }
FController: TBaseConhController;
FCaminhoAnexo: string;
procedure Localizar(ATexto: string);
procedure BuscarUsuario(AId, ACodigo: Integer);
procedure BuscarTipo(AId, ACodigo: Integer);
procedure BuscarStatus(AId, ACodigo: Integer);
procedure BuscarModulo(AId, ACodigo: Integer);
procedure BuscarProduto(AId, ACodigo: Integer);
procedure BuscarObservacao;
procedure PosicaoBotoes;
procedure BuscarDetalhes(AId: Integer);
procedure CaminhoAnexos();
procedure MostrarAnexo();
public
{ Public declarations }
constructor create(APesquisar: Boolean = False);
end;
var
frmBaseConh: TfrmBaseConh;
implementation
{$R *.dfm}
uses uGrade, uDM, uImagens,
uUsuarioController, uTipo, uTipoController, uStatusController, uStatus,
uFiltroBaseConhecimento, uModuloController, uClienteModuloController,
uProdutoController, uProduto, uModulo, uObservacao, uObsevacaoController;
procedure TfrmBaseConh.btnDetalhes2Click(Sender: TObject);
begin
inherited;
BuscarDetalhes(FController.Model.CDSCadastroBas_Id.AsInteger);
end;
procedure TfrmBaseConh.btnDetalhesClick(Sender: TObject);
begin
inherited;
BuscarDetalhes(FController.Model.CDSConsultaBas_Id.AsInteger);
end;
procedure TfrmBaseConh.btnEditarClick(Sender: TObject);
begin
FController.Editar(dbDados.Columns[0].Field.AsInteger, Self);
inherited;
if edtNome.Enabled then
edtNome.SetFocus;
end;
procedure TfrmBaseConh.btnExcluirClick(Sender: TObject);
begin
if TFuncoes.Confirmar('Excluir Registro?') then
begin
FController.Excluir(dm.IdUsuario, dbDados.Columns[0].Field.AsInteger);
inherited;
end;
end;
procedure TfrmBaseConh.btnFecharEdicaoClick(Sender: TObject);
begin
FController.Cancelar;
inherited;
end;
procedure TfrmBaseConh.btnFiltrarClick(Sender: TObject);
begin
inherited;
edtDataInicial.SetFocus;
end;
procedure TfrmBaseConh.btnFiltroClick(Sender: TObject);
begin
inherited;
Localizar(edtDescricao.Text);
end;
procedure TfrmBaseConh.btnImprimirClick(Sender: TObject);
begin
FController.Imprimir(dm.IdUsuario);
inherited;
end;
procedure TfrmBaseConh.btnNovoClick(Sender: TObject);
begin
FController.Novo(dm.IdUsuario);
inherited;
edtNome.SetFocus;
end;
procedure TfrmBaseConh.btnSalvarClick(Sender: TObject);
begin
FController.Salvar(dm.IdUsuario);
FController.FiltrarCodigo(FController.CodigoAtual());
inherited;
end;
procedure TfrmBaseConh.BuscarDetalhes(AId: Integer);
var
form: TfrmBaseConhDetalhe;
begin
if AId = 0 then
raise Exception.Create('Não há Itens para Detalhes!');
form := TfrmBaseConhDetalhe.create(AId);
form.ShowModal;
form.Free;
end;
procedure TfrmBaseConh.BuscarModulo(AId, ACodigo: Integer);
var
obj: TModuloController;
ClienteModulo: TClienteModuloController;
begin
obj := TModuloController.Create;
try
try
obj.Pesquisar(AId, ACodigo);
except
On E: Exception do
begin
ShowMessage(E.Message);
edtCodModulo.SetFocus;
end;
end;
finally
FController.ModoEdicaoInsercao();
FController.Model.CDSCadastroBas_Modulo.AsString := obj.Model.CDSCadastroMod_Id.AsString;
FController.Model.CDSCadastroMod_Codigo.AsString := obj.Model.CDSCadastroMod_Codigo.AsString;
FController.Model.CDSCadastroMod_Nome.AsString := obj.Model.CDSCadastroMod_Nome.AsString;
FreeAndNil(obj);
end;
edtCodModulo.Modified := False;
edtCodProduto.Modified := False;
end;
procedure TfrmBaseConh.BuscarObservacao;
var
obs: TObservacaoController;
begin
if edtNome.Enabled = False then
Exit;
TFuncoes.CriarFormularioModal(TfrmObservacao.create(true, prBase));
if dm.IdSelecionado > 0 then
begin
FController.ModoEdicaoInsercao;
obs := TObservacaoController.Create;
try
obs.LocalizarId(dm.IdSelecionado);
FController.Model.CDSCadastroBas_Descricao.AsString :=
FController.Model.CDSCadastroBas_Descricao.AsString + ' ' + obs.Model.CDSCadastroObs_Descricao.AsString;
finally
FreeAndNil(obs);
end;
end;
end;
procedure TfrmBaseConh.BuscarProduto(AId, ACodigo: Integer);
var
obj: TProdutoController;
begin
obj := TProdutoController.Create;
try
try
obj.Pesquisar(AId, ACodigo);
except
On E: Exception do
begin
ShowMessage(E.Message);
edtCodProduto.SetFocus;
end;
end;
finally
FController.ModoEdicaoInsercao;
FController.Model.CDSCadastroBas_Produto.AsString := obj.Model.CDSCadastroProd_Id.AsString;
FController.Model.CDSCadastroProd_Codigo.AsString := obj.Model.CDSCadastroProd_Codigo.AsString;
FController.Model.CDSCadastroProd_Nome.AsString := obj.Model.CDSCadastroProd_Nome.AsString;
FreeAndNil(obj);
end;
edtCodProduto.Modified := False;
end;
procedure TfrmBaseConh.BuscarStatus(AId, ACodigo: Integer);
var
obj: TStatusController;
begin
obj := TStatusController.Create;
try
try
obj.Pesquisar(AId, ACodigo, TEnumPrograma.prBase);
except
On E: Exception do
begin
ShowMessage(E.Message);
edtCodStatus.SetFocus;
end;
end;
finally
FController.ModoEdicaoInsercao();
FController.Model.CDSCadastroBas_Status.AsString := obj.Model.CDSCadastroSta_Id.AsString;
FController.Model.CDSCadastroSta_Codigo.AsString := obj.Model.CDSCadastroSta_Codigo.AsString;
FController.Model.CDSCadastroSta_Nome.AsString := obj.Model.CDSCadastroSta_Nome.AsString;
FreeAndNil(obj);
end;
edtCodStatus.Modified := False;
end;
procedure TfrmBaseConh.BuscarTipo(AId, ACodigo: Integer);
var
obj: TTipoController;
begin
obj := TTipoController.Create;
try
try
obj.Pesquisar(AId, ACodigo, prBase);
except
On E: Exception do
begin
ShowMessage(E.Message);
edtCodTipo.SetFocus;
end;
end;
finally
FController.ModoEdicaoInsercao();
FController.Model.CDSCadastroBas_Tipo.AsString := obj.Model.CDSCadastroTip_Id.AsString;
FController.Model.CDSCadastroTip_Codigo.AsString := obj.Model.CDSCadastroTip_Codigo.AsString;
FController.Model.CDSCadastroTip_Nome.AsString := obj.Model.CDSCadastroTip_Nome.AsString;
FreeAndNil(obj);
end;
edtCodTipo.Modified := False;
end;
procedure TfrmBaseConh.BuscarUsuario(AId, ACodigo: Integer);
var
obj: TUsuarioController;
begin
obj := TUsuarioController.Create;
try
try
obj.Pesquisar(AId, ACodigo);
except
On E: Exception do
begin
ShowMessage(E.Message);
end;
end;
finally
FController.ModoEdicaoInsercao();
FController.Model.CDSCadastroBas_Usuario.AsString := obj.Model.CDSCadastroUsu_Id.AsString;
FController.Model.CDSCadastroUsu_Codigo.AsString := obj.Model.CDSCadastroUsu_Codigo.AsString;
FController.Model.CDSCadastroUsu_Nome.AsString := obj.Model.CDSCadastroUsu_Nome.AsString;
FreeAndNil(obj);
end;
edtCodUsuario.Modified := False;
end;
procedure TfrmBaseConh.CaminhoAnexos;
var
parametros: TParametrosController;
begin
parametros := TParametrosController.Create;
try
FCaminhoAnexo := parametros.CaminhoAnexos();
finally
FreeAndNil(parametros);
end;
end;
constructor TfrmBaseConh.create(APesquisar: Boolean);
begin
inherited create(nil);
FController := TBaseConhController.Create;
dsPesquisa.DataSet := FController.Model.CDSConsulta;
dsCad.DataSet := FController.Model.CDSCadastro;
TGrade.RetornaCamposGrid(dbDados, cbbCampos);
cbbCampos.ItemIndex := 2;
Localizar('ABCDE'); // para trazer vazio
if APesquisar then
begin
cbbSituacao.ItemIndex := 0;
Pesquisa := APesquisar;
end;
FraModulo.Inicializar();
FraUsuario.Inicializar();
FraTipo.Inicializar();
FraStatus.Inicializar();
end;
procedure TfrmBaseConh.btnAnexarClick(Sender: TObject);
begin
inherited;
dlgAbrirArquivo.InitialDir := FCaminhoAnexo;
if dlgAbrirArquivo.Execute then
begin
if Trim(dlgAbrirArquivo.FileName) = '' then
raise Exception.Create('Informe o Nome do Arquivo.');
FController.ModoEdicaoInsercao;
FController.Model.CDSCadastroBas_Anexo.AsString := dlgAbrirArquivo.FileName;
end;
end;
procedure TfrmBaseConh.btnProdutoClick(Sender: TObject);
begin
inherited;
TFuncoes.CriarFormularioModal(TfrmProduto.create(true));
if dm.IdSelecionado > 0 then
BuscarProduto(dm.IdSelecionado, 0);
end;
procedure TfrmBaseConh.btnModuloClick(Sender: TObject);
begin
inherited;
TFuncoes.CriarFormularioModal(TfrmModulo.create(true));
if dm.IdSelecionado > 0 then
BuscarModulo(dm.IdSelecionado, 0);
end;
procedure TfrmBaseConh.btnStatusClick(Sender: TObject);
begin
inherited;
TFuncoes.CriarFormularioModal(TfrmStatus.create(TEnumPrograma.prBase, true));
if dm.IdSelecionado > 0 then
BuscarStatus(dm.IdSelecionado, 0);
end;
procedure TfrmBaseConh.btnTipoClick(Sender: TObject);
begin
inherited;
TFuncoes.CriarFormularioModal(TfrmTipo.create(prBase, true));
if dm.IdSelecionado > 0 then
BuscarTipo(dm.IdSelecionado, 0);
end;
procedure TfrmBaseConh.btnVisualizarClick(Sender: TObject);
begin
inherited;
TFuncoes.VisualizarArquivo(edtNomeArquivo.Text);
end;
procedure TfrmBaseConh.cbbCamposChange(Sender: TObject);
begin
inherited;
lblMensagem.Visible := TFuncoes.MostrarDescricaoPesquisaData(cbbCampos.Text);
end;
procedure TfrmBaseConh.dbDadosKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
dbDadosDblClick(Self);
if edtCodigo.Enabled then
edtCodigo.SetFocus;
end;
end;
procedure TfrmBaseConh.dbDadosTitleClick(Column: TColumn);
begin
inherited;
TFuncoes.OrdenarCamposGrid(FController.Model.cdsconsulta, Column.FieldName);
end;
procedure TfrmBaseConh.DBMemo1Enter(Sender: TObject);
begin
inherited;
Self.KeyPreview := False;
end;
procedure TfrmBaseConh.DBMemo1Exit(Sender: TObject);
begin
inherited;
Self.KeyPreview := True;
end;
procedure TfrmBaseConh.DBMemo1KeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
begin
inherited;
if Key = VK_F8 then
begin
if btnSalvar.Enabled then
begin
btnSalvar.SetFocus;
btnSalvarClick(Self);
end;
end;
if Key = VK_F9 then
BuscarObservacao();
if Key = VK_ESCAPE then
btnCancelarClick(Self);
end;
procedure TfrmBaseConh.edtCodModuloExit(Sender: TObject);
begin
inherited;
if edtCodModulo.Modified then
BuscarModulo(0, StrToIntDef(edtCodModulo.Text, 0));
end;
procedure TfrmBaseConh.edtCodProdutoExit(Sender: TObject);
begin
inherited;
if edtCodProduto.Modified then
BuscarProduto(0, StrToIntDef(edtCodProduto.Text,0));
end;
procedure TfrmBaseConh.edtCodProdutoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key = VK_F9 then
begin
if Sender = edtCodTipo then
btnTipoClick(Self)
else if Sender = edtCodModulo then
btnModuloClick(Self)
else if Sender = edtCodProduto then
btnProdutoClick(Self)
else if Sender = edtCodStatus then
btnStatusClick(Self);
end;
end;
procedure TfrmBaseConh.edtCodStatusExit(Sender: TObject);
begin
inherited;
if edtCodStatus.Modified then
BuscarStatus(0, StrToIntDef(edtCodStatus.Text,0));
end;
procedure TfrmBaseConh.edtCodTipoExit(Sender: TObject);
begin
inherited;
if edtCodTipo.Modified then
BuscarTipo(0, StrToIntDef(edtCodTipo.Text, 0));
end;
procedure TfrmBaseConh.edtCodUsuarioExit(Sender: TObject);
begin
inherited;
if edtCodUsuario.Modified then
BuscarUsuario(0, StrToIntDef(edtCodUsuario.Text, 0));
end;
procedure TfrmBaseConh.edtDescricaoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then
Localizar(edtDescricao.Text);
end;
procedure TfrmBaseConh.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FController);
end;
procedure TfrmBaseConh.FormShow(Sender: TObject);
var
Img: TfrmImagens;
begin
inherited;
Img := TfrmImagens.Create(Self);
try
btnProduto.Glyph := Img.btnProcurar.Glyph;
btnModulo.Glyph := Img.btnProcurar.Glyph;
btnTipo.Glyph := Img.btnProcurar.Glyph;
btnStatus.Glyph := Img.btnProcurar.Glyph;
btnAnexar.Glyph := Img.btnAnexar.Glyph;
btnVisualizar.Glyph := Img.btnExportar.Glyph;
btnDetalhes.Glyph := Img.btnDetalhe.Glyph;
btnDetalhes2.Glyph := Img.btnDetalhe.Glyph;
finally
FreeAndNil(Img);
end;
PosicaoBotoes();
CaminhoAnexos();
MostrarAnexo();
end;
procedure TfrmBaseConh.FraStatusbtnProcClick(Sender: TObject);
begin
inherited;
FraStatus.TipoPrograma := prBase;
FraStatus.btnProcClick(Sender);
end;
procedure TfrmBaseConh.FraStatusedtCodigoEnter(Sender: TObject);
begin
inherited;
FraStatus.TipoPrograma := prBase;
end;
procedure TfrmBaseConh.FraTipobtnProcClick(Sender: TObject);
begin
inherited;
FraTipo.TipoPrograma := prBase;
FraTipo.btnProcClick(Sender);
end;
procedure TfrmBaseConh.FraTipoedtCodigoEnter(Sender: TObject);
begin
inherited;
FraTipo.TipoPrograma := prBase;
end;
procedure TfrmBaseConh.Localizar(ATexto: string);
var
sCampo: string;
sSituacao: string;
bContem: Boolean;
Filtro: TFiltroBaseConhecimento;
begin
Filtro := TFiltroBaseConhecimento.Create;
try
Filtro.DataInicial := edtDataInicial.Text;
Filtro.DataFinal := edtDataFinal.Text;
Filtro.IdTipo := FraTipo.RetornoSelecao();
Filtro.IdStatus := FraStatus.RetornoSelecao();
Filtro.IdUsuario := FraUsuario.RetornoSelecao();
Filtro.IdModulo := FraModulo.RetornoSelecao();
sCampo := TGrade.FiltrarCampo(dbDados, cbbCampos);
sSituacao := Copy(cbbSituacao.Items.Strings[cbbSituacao.ItemIndex], 1, 1);
bContem := (cbbPesquisa.ItemIndex = 1);
FController.FiltrarBaseConh(Filtro, sCampo, ATexto, dm.IdUsuario, bContem);
FController.Model.CDSConsulta.IndexFieldNames := sCampo;
finally
FreeAndNil(Filtro);
end;
end;
procedure TfrmBaseConh.MostrarAnexo;
var
Departamento: TDepartamentoController;
bResultado: Boolean;
begin
Departamento := TDepartamentoController.Create;
try
bResultado := Departamento.MostrarAnexos();
Label15.Visible := bResultado;
edtNomeArquivo.Visible := bResultado;
btnAnexar.Visible := bResultado;
btnVisualizar.Visible := bResultado;
finally
FreeAndNil(Departamento);
end;
end;
procedure TfrmBaseConh.PosicaoBotoes;
var
botao: TPosicaoBotao;
begin
botao := TPosicaoBotao.Create(btnPrimeiro, 6, 6, true);
try
botao.PosicaoBotaoNavegacao(btnAnterior);
botao.PosicaoBotaoNavegacao(btnProximo);
botao.PosicaoBotaoNavegacao(btnUltimo);
botao.PosicaoBotao(btnNovo);
botao.PosicaoBotao(btnEditar);
botao.PosicaoBotao(btnExcluir);
botao.PosicaoBotao(btnFiltrar);
botao.PosicaoBotao(btnDetalhes);
botao.PosicaoBotao(btnSair);
finally
FreeAndNil(botao);
end;
botao := TPosicaoBotao.Create(btnSalvar, 6, 6);
try
botao.PosicaoBotao(btnCancelar);
botao.PosicaoBotao(btnDetalhes2);
finally
FreeAndNil(botao);
end;
//------------------------------------------------------------------------------
// filtro
Botao := TPosicaoBotao.Create(btnFiltro, 6, 6);
try
Botao.PosicaoBotao(btnImprimir);
Botao.PosicaoBotao(btnFecharFiltro);
finally
FreeAndNil(Botao);
end;
end;
end.
|
unit CheckMem;
interface
implementation
uses
SysUtils;
const
FName = 'LostMem.txt';
var
HPs, HPe: THeapStatus;
Lost: Integer;
Report : Text;
initialization
HPs := GetHeapStatus;
finalization
HPe := GetHeapStatus;
Lost := HPe.TotalAllocated - HPs.TotalAllocated;
DeleteFile(FName);
if Lost > 0 then
begin
AssignFile(Report, FName);
Rewrite(Report);
Writeln(Report, Format('LostMem: %d', [Lost]));
CloseFile(Report);
end;
end.
|
unit FindUnit.StringPositionList;
interface
uses
FindUnit.Header, Generics.Collections, Classes;
type
TStringPositionList = class(TList<TStringPosition>)
private
FDuplicates: TDuplicates;
function IsDuplicated(Item: TStringPosition): Boolean;
public
function Add(const Value: TStringPosition): Integer;
property Duplicates: TDuplicates read FDuplicates write FDuplicates;
end;
implementation
uses
SysUtils;
{ TStringPositionList }
function TStringPositionList.Add(const Value: TStringPosition): Integer;
begin
case Duplicates of
dupIgnore:
begin
if not IsDuplicated(Value) then
inherited Add(Value);
end;
dupAccept: inherited Add(Value);
dupError:
begin
if IsDuplicated(Value) then
raise Exception.Create('Duplicated item');
inherited Add(Value);
end;
end;
end;
function TStringPositionList.IsDuplicated(Item: TStringPosition): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Count -1 do
if Item.Value = Items[i].Value then
begin
Result := True;
Exit;
end;
end;
end.
|
unit uFuncoesServidor;
interface
uses
System.SysUtils, System.Generics.Collections;
type
TFuncoes = class
public
class function EmailExisteNaLista(Email: string; Lista: TList<string>): Boolean;
class function RetornaListaEmail(Lista: TList<string>): string;
class function SomenteNumeros(Texto: string): string;
class function DataIngles(AData: string): string;
class function HoraToDecimal(Hora: String): double;
class function DecimalToHora(Hora: double): string;
class function ValorAmericano(AValor: string): string;
class function TrocaCaracter(AValor, AOldCacracter, ANewCaracter: string): string;
class function BolToString(AValor: Boolean): string;
class function ValorOrNull(AValor: Integer): string;
class function DataOrNull(AData: TDate): string;
class function HoraOrNull(AHora: TTime): string;
class function StringOrNull(AValor: string): string;
class function UltimoDiaMes(AData: TDateTime): TDateTime;
class function CalcularDias(ADataInicial, ADataFinal: TDate): Double;
end;
implementation
{ TFuncoes }
class function TFuncoes.BolToString(AValor: Boolean): string;
begin
if AValor then
Result := '1'
else
Result := '0';
end;
class function TFuncoes.CalcularDias(ADataInicial, ADataFinal: TDate): Double;
begin
try
Result := ADataFinal - ADataInicial;
except
Result := 0;
end;
end;
class function TFuncoes.DataIngles(AData: string): string;
begin
try
Result := QuotedStr(FormatDateTime('YYYYMMDD', StrToDate(AData)));
except
raise Exception.Create('Data Inválida.');
end;
end;
class function TFuncoes.DataOrNull(AData: TDate): string;
begin
if AData > 0 then
Result := QuotedStr(FormatDateTime('yyyymmdd', AData))
else
Result := 'NULL';
end;
class function TFuncoes.DecimalToHora(Hora: double): string;
var
a,b,c: double;
d,e,f: string;
begin
try
a := frac(Hora);
b := int(hora);
c := (a * 60);
d := formatfloat('00', b);
e := formatfloat('00', c);
f := d + ':' + e;
except
f := '00:00';
end;
result := f;
end;
class function TFuncoes.EmailExisteNaLista(Email: string; Lista: TList<string>): Boolean;
begin
Result := Lista.Contains(Email);
end;
class function TFuncoes.HoraOrNull(AHora: TTime): string;
begin
if AHora > 0 then
Result := QuotedStr(FormatDateTime('hh:mm', AHora))
else
Result := 'NULL';
end;
class function TFuncoes.HoraToDecimal(Hora: String): double;
var a,b,c,d: double;
begin
try
a := StrToFloat(copy(Hora, 4, 2));
b := a / 60;
c := int(StrToFloat(copy(Hora, 1, 2)));
d := c + b;
except
d := 0;
end;
result := d;
end;
class function TFuncoes.RetornaListaEmail(Lista: TList<string>): string;
var
sReturn: string;
sEmail: string;
begin
sReturn := '';
for sEmail in Lista do
begin
if sReturn = '' then
sReturn := sEmail
else
sReturn := sReturn + ';' + sEmail;
end;
Result := sReturn;
end;
class function TFuncoes.SomenteNumeros(Texto: string): string;
var
i: Integer;
schar: string;
begin
schar := '';
for i := 1 to Length(Texto) do
begin
if Texto[i] in ['0','1','2','3','4','5','6','7','8','9'] then
schar := schar + Texto[i];
end;
Result := schar;
end;
class function TFuncoes.StringOrNull(AValor: string): string;
begin
if AValor.Trim() = '' then
Result := 'NULL'
else
Result := QuotedStr(AValor);
end;
class function TFuncoes.TrocaCaracter(AValor, AOldCacracter,
ANewCaracter: string): string;
begin
Result := StringReplace(AValor, AOldCacracter, ANewCaracter, [rfReplaceAll]);
end;
class function TFuncoes.UltimoDiaMes(AData: TDateTime): TDateTime;
var
ano, mes, dia : word;
mDtTemp : TDateTime;
begin
Decodedate(AData, ano, mes, dia);
mDtTemp := (AData - dia) + 33;
Decodedate(mDtTemp, ano, mes, dia);
Result := mDtTemp - dia;
end;
class function TFuncoes.ValorAmericano(AValor: string): string;
begin
Result := TrocaCaracter(AValor, ',','.');
end;
class function TFuncoes.ValorOrNull(AValor: Integer): string;
begin
if AValor = 0 then
Result := 'Null'
else
Result := IntToStr(AValor);
end;
end.
|
//
// opus_custom.h header binding for the Free Pascal Compiler aka FPC
//
// Binaries and demos available at http://www.djmaster.com/
//
(* Copyright (c) 2007-2008 CSIRO
Copyright (c) 2007-2009 Xiph.Org Foundation
Copyright (c) 2008-2012 Gregory Maxwell
Written by Jean-Marc Valin and Gregory Maxwell *)
(*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
(**
@file opus_custom.h
@brief Opus-Custom reference implementation API
*)
unit opus_custom;
{$mode objfpc}{$H+}
interface
uses
ctypes;
const
LIB_OPUS = 'libopus-0.dll';
// #ifndef OPUS_CUSTOM_H
// #define OPUS_CUSTOM_H
{$include opus_types.inc}
{$include opus_defines.inc}
// #ifdef __cplusplus
// extern "C" {
// #endif
//TODO #ifdef CUSTOM_MODES
//TODO # define OPUS_CUSTOM_EXPORT OPUS_EXPORT
//TODO # define OPUS_CUSTOM_EXPORT_STATIC OPUS_EXPORT
//TODO #else
//TODO # define OPUS_CUSTOM_EXPORT
//TODO # ifdef OPUS_BUILD
//TODO # define OPUS_CUSTOM_EXPORT_STATIC static OPUS_INLINE
//TODO # else
//TODO # define OPUS_CUSTOM_EXPORT_STATIC
//TODO # endif
//TODO #endif
(** @defgroup opus_custom Opus Custom
* @{
* Opus Custom is an optional part of the Opus specification and
* reference implementation which uses a distinct API from the regular
* API and supports frame sizes that are not normally supported.\ Use
* of Opus Custom is discouraged for all but very special applications
* for which a frame size different from 2.5, 5, 10, or 20 ms is needed
* (for either complexity or latency reasons) and where interoperability
* is less important.
*
* In addition to the interoperability limitations the use of Opus custom
* disables a substantial chunk of the codec and generally lowers the
* quality available at a given bitrate. Normally when an application needs
* a different frame size from the codec it should buffer to match the
* sizes but this adds a small amount of delay which may be important
* in some very low latency applications. Some transports (especially
* constant rate RF transports) may also work best with frames of
* particular durations.
*
* Libopus only supports custom modes if they are enabled at compile time.
*
* The Opus Custom API is similar to the regular API but the
* @ref opus_encoder_create and @ref opus_decoder_create calls take
* an additional mode parameter which is a structure produced by
* a call to @ref opus_custom_mode_create. Both the encoder and decoder
* must create a mode using the same sample rate (fs) and frame size
* (frame size) so these parameters must either be signaled out of band
* or fixed in a particular implementation.
*
* Similar to regular Opus the custom modes support on the fly frame size
* switching, but the sizes available depend on the particular frame size in
* use. For some initial frame sizes on a single on the fly size is available.
*)
type
(** Contains the state of an encoder. One encoder state is needed
for each stream. It is initialized once at the beginning of the
stream. Do *not* re-initialize the state for every frame.
@brief Encoder state
*)
POpusCustomEncoder = ^OpusCustomEncoder;
OpusCustomEncoder = record
end;
(** State of the decoder. One decoder state is needed for each stream.
It is initialized once at the beginning of the stream. Do *not*
re-initialize the state for every frame.
@brief Decoder state
*)
POpusCustomDecoder = ^OpusCustomDecoder;
OpusCustomDecoder = record
end;
(** The mode contains all the information necessary to create an
encoder. Both the encoder and decoder need to be initialized
with exactly the same mode, otherwise the output will be
corrupted.
@brief Mode configuration
*)
POpusCustomMode = ^OpusCustomMode;
OpusCustomMode = record
end;
(** Creates a new mode struct. This will be passed to an encoder or
* decoder. The mode MUST NOT BE DESTROYED until the encoders and
* decoders that use it are destroyed as well.
* @param [in] Fs <tt>int</tt>: Sampling rate (8000 to 96000 Hz)
* @param [in] frame_size <tt>int</tt>: Number of samples (per channel) to encode in each
* packet (64 - 1024, prime factorization must contain zero or more 2s, 3s, or 5s and no other primes)
* @param [out] error <tt>int*</tt>: Returned error code (if NULL, no error will be returned)
* @return A newly created mode
*)
function opus_custom_mode_create(Fs: opus_int32; frame_size: cint; error: pcint): POpusCustomMode; cdecl; external LIB_OPUS;
(** Destroys a mode struct. Only call this after all encoders and
* decoders using this mode are destroyed as well.
* @param [in] mode <tt>OpusCustomMode*</tt>: Mode to be freed.
*)
procedure opus_custom_mode_destroy(mode: POpusCustomMode); cdecl; external LIB_OPUS;
//TODO #if !defined(OPUS_BUILD) || defined(CELT_ENCODER_C)
(* Encoder *)
(** Gets the size of an OpusCustomEncoder structure.
* @param [in] mode <tt>OpusCustomMode *</tt>: Mode configuration
* @param [in] channels <tt>int</tt>: Number of channels
* @returns size
*)
function opus_custom_encoder_get_size(const mode: POpusCustomMode; channels: cint): cint; cdecl; external LIB_OPUS;
//TODO # ifdef CUSTOM_MODES
(** Initializes a previously allocated encoder state
* The memory pointed to by st must be the size returned by opus_custom_encoder_get_size.
* This is intended for applications which use their own allocator instead of malloc.
* @see opus_custom_encoder_create(),opus_custom_encoder_get_size()
* To reset a previously initialized state use the OPUS_RESET_STATE CTL.
* @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state
* @param [in] mode <tt>OpusCustomMode *</tt>: Contains all the information about the characteristics of
* the stream (must be the same characteristics as used for the
* decoder)
* @param [in] channels <tt>int</tt>: Number of channels
* @return OPUS_OK Success or @ref opus_errorcodes
*)
function opus_custom_encoder_init(st: POpusCustomEncoder; const mode: POpusCustomMode; channels: cint): cint; cdecl; external LIB_OPUS;
//TODO # endif
//TODO #endif
(** Creates a new encoder state. Each stream needs its own encoder
* state (can't be shared across simultaneous streams).
* @param [in] mode <tt>OpusCustomMode*</tt>: Contains all the information about the characteristics of
* the stream (must be the same characteristics as used for the
* decoder)
* @param [in] channels <tt>int</tt>: Number of channels
* @param [out] error <tt>int*</tt>: Returns an error code
* @return Newly created encoder state.
*)
function opus_custom_encoder_create(const mode: POpusCustomMode; channels: cint; error: pcint): POpusCustomEncoder; cdecl; external LIB_OPUS;
(** Destroys a an encoder state.
* @param[in] st <tt>OpusCustomEncoder*</tt>: State to be freed.
*)
procedure opus_custom_encoder_destroy(st: POpusCustomEncoder); cdecl; external LIB_OPUS;
(** Encodes a frame of audio.
* @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state
* @param [in] pcm <tt>float*</tt>: PCM audio in float format, with a normal range of +/-1.0.
* Samples with a range beyond +/-1.0 are supported but will
* be clipped by decoders using the integer API and should
* only be used if it is known that the far end supports
* extended dynamic range. There must be exactly
* frame_size samples per channel.
* @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal
* @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long.
* @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame
* (can change from one frame to another)
* @return Number of bytes written to "compressed".
* If negative, an error has occurred (see error codes). It is IMPORTANT that
* the length returned be somehow transmitted to the decoder. Otherwise, no
* decoding is possible.
*)
function opus_custom_encode_float(st: POpusCustomEncoder; const pcm: pcfloat; frame_size: cint; compressed: pcuchar; maxCompressedBytes: cint): cint; cdecl; external LIB_OPUS;
(** Encodes a frame of audio.
* @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state
* @param [in] pcm <tt>opus_int16*</tt>: PCM audio in signed 16-bit format (native endian).
* There must be exactly frame_size samples per channel.
* @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal
* @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long.
* @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame
* (can change from one frame to another)
* @return Number of bytes written to "compressed".
* If negative, an error has occurred (see error codes). It is IMPORTANT that
* the length returned be somehow transmitted to the decoder. Otherwise, no
* decoding is possible.
*)
function opus_custom_encode(st: POpusCustomEncoder; const pcm: Popus_int16; frame_size: cint; compressed: pcuchar; maxCompressedBytes: cint): cint; cdecl; external LIB_OPUS;
(** Perform a CTL function on an Opus custom encoder.
*
* Generally the request and subsequent arguments are generated
* by a convenience macro.
* @see opus_encoderctls
*)
function opus_custom_encoder_ctl(st: POpusCustomEncoder; request: cint; args: array of const): cint; cdecl; external LIB_OPUS;
//TODO #if !defined(OPUS_BUILD) || defined(CELT_DECODER_C)
(* Decoder *)
(** Gets the size of an OpusCustomDecoder structure.
* @param [in] mode <tt>OpusCustomMode *</tt>: Mode configuration
* @param [in] channels <tt>int</tt>: Number of channels
* @returns size
*)
function opus_custom_decoder_get_size(const mode: POpusCustomMode; channels: cint): cint; cdecl; external LIB_OPUS;
(** Initializes a previously allocated decoder state
* The memory pointed to by st must be the size returned by opus_custom_decoder_get_size.
* This is intended for applications which use their own allocator instead of malloc.
* @see opus_custom_decoder_create(),opus_custom_decoder_get_size()
* To reset a previously initialized state use the OPUS_RESET_STATE CTL.
* @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state
* @param [in] mode <tt>OpusCustomMode *</tt>: Contains all the information about the characteristics of
* the stream (must be the same characteristics as used for the
* encoder)
* @param [in] channels <tt>int</tt>: Number of channels
* @return OPUS_OK Success or @ref opus_errorcodes
*)
function opus_custom_decoder_init(st: POpusCustomDecoder; const mode: POpusCustomMode; channels: cint): cint; cdecl; external LIB_OPUS;
//TODO #endif
(** Creates a new decoder state. Each stream needs its own decoder state (can't
* be shared across simultaneous streams).
* @param [in] mode <tt>OpusCustomMode</tt>: Contains all the information about the characteristics of the
* stream (must be the same characteristics as used for the encoder)
* @param [in] channels <tt>int</tt>: Number of channels
* @param [out] error <tt>int*</tt>: Returns an error code
* @return Newly created decoder state.
*)
function opus_custom_decoder_create(const mode: POpusCustomMode; channels: cint; error: pcint): POpusCustomDecoder; cdecl; external LIB_OPUS;
(** Destroys a an decoder state.
* @param[in] st <tt>OpusCustomDecoder*</tt>: State to be freed.
*)
procedure opus_custom_decoder_destroy(st: POpusCustomDecoder); cdecl; external LIB_OPUS;
(** Decode an opus custom frame with floating point output
* @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state
* @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss
* @param [in] len <tt>int</tt>: Number of bytes in payload
* @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length
* is frame_size*channels*sizeof(float)
* @param [in] frame_size Number of samples per channel of available space in *pcm.
* @returns Number of decoded samples or @ref opus_errorcodes
*)
function opus_custom_decode_float(st: POpusCustomDecoder; const data: pcuchar; len: cint; pcm: pcfloat; frame_size: cint): cint; cdecl; external LIB_OPUS;
(** Decode an opus custom frame
* @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state
* @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss
* @param [in] len <tt>int</tt>: Number of bytes in payload
* @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length
* is frame_size*channels*sizeof(opus_int16)
* @param [in] frame_size Number of samples per channel of available space in *pcm.
* @returns Number of decoded samples or @ref opus_errorcodes
*)
function opus_custom_decode(st: POpusCustomDecoder; const data: pcuchar; len: cint; pcm: Popus_int16; frame_size: cint): cint; cdecl; external LIB_OPUS;
(** Perform a CTL function on an Opus custom decoder.
*
* Generally the request and subsequent arguments are generated
* by a convenience macro.
* @see opus_genericctls
*)
function opus_custom_decoder_ctl(st: POpusCustomDecoder; request: cint; args: array of const): cint; cdecl; external LIB_OPUS;
(**@}*)
// #ifdef __cplusplus
// }
// #endif
// #endif (* OPUS_CUSTOM_H *)
implementation
end.
|
unit FilePreviewErrorResponseUnit;
interface
uses
REST.Json.Types, SysUtils,
JSONNullableAttributeUnit,
CommonTypesUnit;
type
/// <summary>
/// Errors data-structure
/// </summary>
TFilePreviewErrorResponse = class
private
[JSONName('status')]
FStatus: boolean;
[JSONName('errors')]
FErrors: TStringArray;
public
/// <remarks>
/// Constructor with 0-arguments must be and be public.
/// For JSON-deserialization.
/// </remarks>
constructor Create;
destructor Destroy; override;
property Status: boolean read FStatus write FStatus;
/// <summary>
/// Errors
/// </summary>
property Errors: TStringArray read FErrors write FErrors;
end;
implementation
uses UtilsUnit;
constructor TFilePreviewErrorResponse.Create;
begin
Inherited;
SetLength(FErrors, 0);
end;
destructor TFilePreviewErrorResponse.Destroy;
begin
Finalize(FErrors);
inherited;
end;
end.
|
unit trade;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, JvExControls, JvFormWallpaper;
type
Tf_trade = class(TForm)
e_your: TEdit;
wallpaper: TJvFormWallpaper;
Label1: TLabel;
e_your_cash: TEdit;
Label2: TLabel;
lb_offer: TLabel;
e_his: TEdit;
e_his_cash: TEdit;
bt_propose: TPanel;
bt_accept: TPanel;
bt_deny: TPanel;
Label3: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure e_yourDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure e_yourDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure e_his_cashEnter(Sender: TObject);
procedure e_yourClick(Sender: TObject);
procedure bt_proposeClick(Sender: TObject);
procedure e_your_cashChange(Sender: TObject);
procedure bt_acceptClick(Sender: TObject);
procedure bt_denyClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CreateParams(var Params: TCreateParams); override;
private
{ Private declarations }
public
nick: string;
trade_id:string;
proposed:boolean;
incoming:boolean;
end;
var
f_trade: Tf_trade;
implementation
uses main, items, net, Math;
{$R *.dfm}
procedure Tf_trade.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
end;
procedure Tf_trade.FormCreate(Sender: TObject);
begin
wallpaper.Image.LoadFromFile(AppDir+'\img\bg.jpg');
end;
procedure Tf_trade.FormShow(Sender: TObject);
begin
lb_offer.Caption:='Oferta '+nick+':';
proposed:=false;
incoming:=false;
trade_id:='0';
e_your.text:='';
e_your_cash.text:='0';
e_his.text:='';
e_his_cash.text:='0';
bt_propose.font.Color:=$0053524D;
bt_propose.enabled:=false;
bt_accept.font.Color:=$0053524D;
bt_accept.enabled:=false;
bt_deny.font.Color:=$0053524D;
bt_deny.enabled:=false;
end;
procedure Tf_trade.e_yourDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
accept:=false;
if Source is TListBox then
if (Source as tcomponent).Name='lb_items' then
accept:=true;
end;
procedure Tf_trade.e_yourDragDrop(Sender, Source: TObject; X, Y: Integer);
begin
e_your.Text:=itemlist[f_items.lb_items.Itemindex].name;
trade_id:=itemlist[f_items.lb_items.Itemindex].id;
bt_propose.font.Color:=$00CECCC1;
bt_propose.enabled:=true;
e_your_cashChange(self);
end;
procedure Tf_trade.e_his_cashEnter(Sender: TObject);
begin
FocusControl(f_trade.e_your_cash);
end;
procedure Tf_trade.e_yourClick(Sender: TObject);
begin
stdsend('/items');
end;
procedure Tf_trade.bt_proposeClick(Sender: TObject);
begin
if proposed then exit;
proposed:=true;
bt_propose.font.Color:=$0053524D;
bt_propose.enabled:=false;
bt_accept.font.Color:=$00CECCC1;
bt_accept.enabled:=true;
bt_deny.font.Color:=$00CECCC1;
bt_deny.enabled:=true;
stdsend('/trade '+trade_id+' '+e_your_cash.Text+' '+nick);
end;
procedure Tf_trade.e_your_cashChange(Sender: TObject);
var i:integer;
begin
bt_propose.font.Color:=$0053524D;
bt_propose.enabled:=false;
try
i:=StrToInt(e_your_cash.text);
except
on EConvertError do
exit;
end;
if (i<0) then exit;
if (i>chr_duk) then exit;
bt_propose.font.Color:=$00CECCC1;
bt_propose.enabled:=true;
end;
procedure Tf_trade.bt_acceptClick(Sender: TObject);
begin
bt_propose.font.Color:=$0053524D;
bt_propose.enabled:=false;
bt_accept.font.Color:=$0053524D;
bt_accept.enabled:=false;
stdsend('/trade_yes');
end;
procedure Tf_trade.bt_denyClick(Sender: TObject);
begin
stdsend('/trade_no');
hide();
end;
procedure Tf_trade.FormClose(Sender: TObject; var Action: TCloseAction);
begin
stdsend('/trade_no');
end;
end.
|
unit uUtils;
interface
uses
System.JSON, Soap.XSBuiltIns, System.SysUtils, System.Classes, System.IOUtils,
IdTCPClient,
IdHTTP,
REST.Client;
/// <summary>
/// Проверка JSON на Null & empty
/// </summary>
function ValidateJSONObject(AJsonValue : TJsonValue; var tempJson : TJSONObject) : Boolean; Overload;
function ValidateJSONObject(AJsonValue : TJsonValue; var tempJson : string) : Boolean; Overload;
/// <summary>
/// Перевод UTC формат времени в обычный
/// </summary>
function UtcToNative(var dateTime : TDateTime; Utc : string) : Boolean;
/// <summary>
/// Перевод обычный формат времени в UTC
/// </summary>
function NativeToUtc(dateTime : TDateTime; var Utc : string) : Boolean;
/// <summary>
/// Проверка JSONArray на Null & empty
/// </summary>
function ValidateJSONArray(AJsonValue : TJsonValue; var tempJson : TJSONArray) : Boolean;
/// <summary>
/// Проверка интернета
/// </summary>
function CheckNetworkState : Boolean;
/// <summary>
/// Запрос текста
/// </summary>
function HttpGetText(url : string; var st : TStringList) : Boolean;
/// <summary>
/// Запрос бинарных данных
/// </summary>
function HttpGetBinary(url : string; var stream : TMemoryStream) : Boolean;
/// </summary>
/// Полный путь к папке
/// </summary>
function GetPath(dirName : string = '') : string;
implementation
{------------------------------------------------------------------------------}
/// Проверка JSON на Null & empty
function ValidateJSONObject(AJsonValue : TJsonValue; var tempJson : TJSONObject) : Boolean;
var
res : Boolean;
temp : string;
begin
Result := True;
try
if not Assigned(AJsonValue) then
Exit(True);
res := AJsonValue.Null;
temp := AJsonValue.Value;
if res then
Exit;
tempJson := AJsonValue as TJSONObject;
if not Assigned(tempJson) then
begin
res := true;
end;
except
res := True;
end;
Result := res;
end;
{------------------------------------------------------------------------------}
function ValidateJSONObject(AJsonValue : TJsonValue; var tempJson : string) : Boolean;
var
res : Boolean;
temp : string;
begin
Result := True;
try
if not Assigned(AJsonValue) then
Exit(True);
res := AJsonValue.Null;
temp := AJsonValue.Value;
if res then
Exit;
tempJson := temp;
except
res := True;
end;
Result := res;
end;
{------------------------------------------------------------------------------}
/// Перевод UTC формат времени в обычный
function UtcToNative(var dateTime : TDateTime; Utc : string) : Boolean;
var
utcTime : TXsDateTime;
begin
if Utc.IsEmpty then
Exit;
utcTime := TXsDateTime.Create;
try
utcTime.XSToNative(Utc);
dateTime := utcTime.AsDateTime;
finally
FreeAndNil(utcTime);
end;
end;
{------------------------------------------------------------------------------}
/// Перевод обычный формат времени в UTC
function NativeToUtc(dateTime : TDateTime; var Utc : string) : Boolean;
var
utcTime : TXsDateTime;
begin
utcTime := TXsDateTime.Create;
try
utcTime.AsDateTime := dateTime;
Utc := utcTime.NativeToXS;
finally
FreeAndNil(utcTime);
end;
end;
{------------------------------------------------------------------------------}
/// Проверка JSONArray на Null & empty
function ValidateJSONArray(AJsonValue : TJsonValue; var tempJson : TJSONArray) : Boolean;
var
res : Boolean;
temp : string;
begin
Result := True;
try
if not Assigned(AJsonValue) then
Exit(True);
res := AJsonValue.Null;
if res then
Exit;
tempJson := AJsonValue as TJSONArray;
if not Assigned(tempJson) then
begin
res := true;
end;
except
res := True;
end;
Result := res;
end;
{------------------------------------------------------------------------------}
/// Проверка интернета
function CheckNetworkState : Boolean;
var
TCP : TIdTCPClient;
begin
TCP:=TIdTCPClient.Create(nil);
try
TCP.Host := 'www.google.com';
TCP.Port := 80;
TCP.ReadTimeout := 1000;
try
TCP.Connect;
Result := TCP.Connected;
except
Result := false;
end;
finally
FreeAndNil(TCP);
end;
end;
{------------------------------------------------------------------------------}
/// Запрос текста
function HttpGetText(url : string; var st : TStringList) : Boolean;
var
stream : TMemoryStream;
begin
Result := false;
if string.IsNullOrEmpty(url) then
exit;
if not Assigned(st) then
st := TStringList.Create;
stream := TMemoryStream.Create;
try
REST.Client.TDownloadURL.DownloadRawBytes(url, stream);
st.LoadFromStream(stream);
except
end;
FreeAndNil(stream);
Result := not st.Text.IsEmpty;
end;
{------------------------------------------------------------------------------}
/// Запрос бинарных данных
function HttpGetBinary(url : string; var stream : TMemoryStream) : Boolean;
begin
Result := false;
if string.IsNullOrEmpty(url) then
exit;
if not Assigned(stream) then
stream := TMemoryStream.Create;
try
REST.Client.TDownloadURL.DownloadRawBytes(url, stream);
except
end;
stream.Position := 0;
Result := True;
end;
{------------------------------------------------------------------------------}
/// Полный путь к папке
function GetPath(dirName : string) : string;
var
Path : string;
begin
{$IFDEF MSWINDOWS}
Path := ExtractFilePath(ParamStr(0));
{$ELSE}
Path := System.IOUtils.TPath.GetDocumentsPath;
{$ENDIF}
//Path := Path + System.SysUtils.PathDelim;
if not dirName.IsEmpty then
Path := Path + dirName + System.SysUtils.PathDelim;
Result := Path;
end;
{------------------------------------------------------------------------------}
end.
|
unit rainbowislands_hw;
//{$DEFINE MCU=1}
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m68000,main_engine,controls_engine,gfx_engine,ym_2151,
taitosnd,rom_engine,pal_engine,sound_engine{$IFDEF MCU},taito_cchip{$ELSE IF},rainbow_cchip{$ENDIF};
function iniciar_rainbow:boolean;
implementation
const
rainbow_rom:array[0..5] of tipo_roms=(
(n:'b22-10-1.19';l:$10000;p:0;crc:$e34a50ca),(n:'b22-11-1.20';l:$10000;p:$1;crc:$6a31a093),
(n:'b22-08-1.21';l:$10000;p:$20000;crc:$15d6e17a),(n:'b22-09-1.22';l:$10000;p:$20001;crc:$454e66bc),
(n:'b22-03.23';l:$20000;p:$40000;crc:$3ebb0fb8),(n:'b22-04.24';l:$20000;p:$40001;crc:$91625e7f));
rainbow_char:tipo_roms=(n:'b22-01.2';l:$80000;p:0;crc:$b76c9168);
rainbow_sound:tipo_roms=(n:'b22-14.43';l:$10000;p:0;crc:$113c1a5b);
rainbow_sprites1:tipo_roms=(n:'b22-02.5';l:$80000;p:0;crc:$1b87ecf0);
rainbow_sprites2:array[0..1] of tipo_roms=(
(n:'b22-12.7';l:$10000;p:$80000;crc:$67a76dc6),(n:'b22-13.6';l:$10000;p:$80001;crc:$2fda099f));
rainbowe_rom:array[0..5] of tipo_roms=(
(n:'b39-01.19';l:$10000;p:0;crc:$50690880),(n:'b39-02.20';l:$10000;p:$1;crc:$4dead71f),
(n:'b39-03.21';l:$10000;p:$20000;crc:$4a4cb785),(n:'b39-04.22';l:$10000;p:$20001;crc:$4caa53bd),
(n:'b22-03.23';l:$20000;p:$40000;crc:$3ebb0fb8),(n:'b22-04.24';l:$20000;p:$40001;crc:$91625e7f));
{$IFDEF MCU}rainbow_cchip_eeprom:tipo_roms=(n:'cchip_b22-15.53';l:$2000;p:0;crc:$08c588a6);
rainbowe_cchip_eeprom:tipo_roms=(n:'cchip_b39-05.53';l:$2000;p:0;crc:$397735e3);{$ENDIF}
//DIP
rainbow_dip1:array [0..2] of def_dip=(
(mask:$30;name:'Coin A';number:4;dip:((dip_val:$10;dip_name:'ModeA 2C-1C/ModeB 3C-1C'),(dip_val:$30;dip_name:'ModeAB 1C-1C'),(dip_val:$0;dip_name:'ModeA 2C-3C/ModeB 4C-1C'),(dip_val:$20;dip_name:'ModeA 1C-2C/ModeB 2C-1C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Coin B';number:4;dip:((dip_val:$40;dip_name:'ModeA 2C-1C/ModeB 1C-4C'),(dip_val:$c0;dip_name:'ModeA 1C-1C/ModeB 1C-2C'),(dip_val:$0;dip_name:'ModeA 2C-3C/ModeB 1C-6C'),(dip_val:$80;dip_name:'ModeA 1C-2C/ModeB 1C-3C'),(),(),(),(),(),(),(),(),(),(),(),())),());
//DIP
rainbow_dip2:array [0..5] of def_dip=(
(mask:$4;name:'Bonus Life';number:2;dip:((dip_val:$4;dip_name:'100k 1000k'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Complete Bonus';number:2;dip:((dip_val:$8;dip_name:'1up'),(dip_val:$0;dip_name:'100k'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Lives';number:4;dip:((dip_val:$10;dip_name:'1'),(dip_val:$0;dip_name:'2'),(dip_val:$30;dip_name:'3'),(dip_val:$20;dip_name:'4'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Languaje';number:2;dip:((dip_val:$0;dip_name:'English'),(dip_val:$40;dip_name:'Japanese'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Coin Mode';number:2;dip:((dip_val:$80;dip_name:'Mode A (Japan)'),(dip_val:$0;dip_name:'Mode B (World)'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
CPU_SYNC=1;
var
scroll_x1,scroll_y1,scroll_x2,scroll_y2:word;
bank_sound:array[0..3,$0..$3fff] of byte;
rom:array[0..$3ffff] of word;
ram1,ram3:array[0..$1fff] of word;
ram2:array [0..$7fff] of word;
spritebank,sound_bank:byte;
procedure update_video_rainbow;
var
f,x,y,nchar,atrib,color:word;
flipx,flipy:boolean;
begin
for f:=$fff downto $0 do begin
//background
atrib:=ram2[f*2];
color:=atrib and $7f;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
x:=f mod 64;
y:=f div 64;
nchar:=(ram2[$1+(f*2)]) and $3fff;
flipx:=(atrib and $4000)<>0;
flipy:=(atrib and $8000)<>0;
put_gfx_flip(x*8,y*8,nchar,color shl 4,1,0,flipx,flipy);
gfx[0].buffer[f]:=false;
end;
//foreground
atrib:=ram2[$4000+(f*2)];
color:=atrib and $7f;
if (gfx[0].buffer[f+$1000] or buffer_color[color]) then begin
x:=f mod 64;
y:=f div 64;
nchar:=(ram2[$4001+(f*2)]) and $3fff;
flipx:=(atrib and $4000)<>0;
flipy:=(atrib and $8000)<>0;
put_gfx_trans_flip(x*8,y*8,nchar,color shl 4,2,0,flipx,flipy);
gfx[0].buffer[f+$1000]:=false;
end;
end;
scroll_x_y(1,3,scroll_x1,scroll_y1);
//Sprites
for f:=$ff downto 0 do begin
nchar:=(ram3[$2+(f*4)]) mod $1400;
atrib:=ram3[f*4];
color:=((atrib and $f) or (spritebank shl 4)) shl 4;
put_gfx_sprite(nchar,color,(atrib and $4000)<>0,(atrib and $8000)<>0,1);
x:=ram3[$3+(f*4)]+16;
y:=ram3[$1+(f*4)];
actualiza_gfx_sprite(x and $1ff,y and $1ff,3,1);
end;
scroll_x_y(2,3,scroll_x2,scroll_y2);
actualiza_trozo_final(16,16,320,224,3);
fillchar(buffer_color[0],MAX_COLOR_BUFFER,0);
end;
procedure eventos_rainbow;
begin
if event.arcade then begin
//800007
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40);
//800009
if arcade_input.coin[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe);
if arcade_input.coin[1] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd);
//80000B
if arcade_input.left[0] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
if arcade_input.right[0] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20);
if arcade_input.but0[0] then marcade.in2:=(marcade.in2 and $bf) else marcade.in2:=(marcade.in2 or $40);
if arcade_input.but1[0] then marcade.in2:=(marcade.in2 and $7f) else marcade.in2:=(marcade.in2 or $80);
end;
end;
procedure rainbow_principal;
var
frame_m,frame_s{$IFDEF MCU},frame_mcu{$ENDIF}:single;
h,f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=tc0140syt_0.z80.tframes;
{$IFDEF MCU}frame_mcu:=cchip_0.upd7810.tframes;{$ENDIF}
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
for h:=1 to CPU_SYNC do begin
//Main CPU
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//Sound CPU
tc0140syt_0.z80.run(frame_s);
frame_s:=frame_s+tc0140syt_0.z80.tframes-tc0140syt_0.z80.contador;
//MCU
{$IFDEF MCU}
cchip_0.upd7810.run(frame_mcu);
frame_mcu:=frame_mcu+cchip_0.upd7810.tframes-cchip_0.upd7810.contador;
{$ENDIF}
end;
if f=239 then begin
update_video_rainbow;
m68000_0.irq[4]:=HOLD_LINE;
{$IFDEF MCU}cchip_0.set_int;{$ENDIF}
end;
end;
eventos_rainbow;
video_sync;
end;
end;
function rainbow_getword(direccion:dword):word;
begin
case direccion of
0..$7ffff:rainbow_getword:=rom[direccion shr 1];
$10c000..$10ffff:rainbow_getword:=ram1[(direccion and $3fff) shr 1];
$200000..$203fff:rainbow_getword:=buffer_paleta[(direccion and $3fff) shr 1];
$390000..$390002:rainbow_getword:=marcade.dswa;
$3b0000..$3b0002:rainbow_getword:=marcade.dswb;
$3e0002:if m68000_0.read_8bits_hi_dir then rainbow_getword:=tc0140syt_0.comm_r;
{$IFDEF MCU}
$800000..$8007ff:rainbow_getword:=cchip_0.mem_r((direccion and $7ff) shr 1);
$800800..$800fff:rainbow_getword:=cchip_0.asic_r((direccion and $7ff) shr 1);
{$ELSE IF}
$800000..$8007ff:rainbow_getword:=rbisland_cchip_ram_r(direccion and $7ff);
$800802:rainbow_getword:=rbisland_cchip_ctrl_r;
{$ENDIF}
$c00000..$c0ffff:rainbow_getword:=ram2[(direccion and $ffff) shr 1];
$d00000..$d03fff:rainbow_getword:=ram3[(direccion and $3fff) shr 1];
end;
end;
procedure rainbow_putword(direccion:dword;valor:word);
procedure cambiar_color(tmp_color,numero:word);
var
color:tcolor;
begin
color.b:=pal5bit(tmp_color shr 10);
color.g:=pal5bit(tmp_color shr 5);
color.r:=pal5bit(tmp_color);
set_pal_color(color,numero);
buffer_color[(numero shr 4) and $7f]:=true;
end;
begin
case direccion of
0..$7ffff:;
$10c000..$10ffff:ram1[(direccion and $3fff) shr 1]:=valor;
$200000..$200fff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin
buffer_paleta[(direccion and $fff) shr 1]:=valor;
cambiar_color(valor,(direccion and $fff) shr 1);
end;
$201000..$203fff:buffer_paleta[(direccion and $3fff) shr 1]:=valor;
$350008,$3c0000:;
$3a0000:spritebank:=(valor and $e0) shr 5;
$3e0000:tc0140syt_0.port_w(valor and $ff);
$3e0002:tc0140syt_0.comm_w(valor and $ff);
{$IFDEF MCU}
$800000..$8007ff:cchip_0.mem_w((direccion and $7ff) shr 1,valor);
$800800..$800fff:cchip_0.asic_w((direccion and $7ff) shr 1,valor);
{$ELSE IF}
$800000..$8007ff:rbisland_cchip_ram_w(direccion and $7ff,valor);
$800802:rbisland_cchip_ctrl_w;
$800c00:rbisland_cchip_bank_w(valor);
{$ENDIF}
$c00000..$c03fff:begin
ram2[(direccion and $ffff) shr 1]:=valor;
gfx[0].buffer[(direccion and $3fff) shr 2]:=true;
end;
$c04000..$c07fff,$c0c000..$c0ffff:ram2[(direccion and $ffff) shr 1]:=valor;
$c08000..$c0bfff:begin
ram2[(direccion and $ffff) shr 1]:=valor;
gfx[0].buffer[((direccion and $3fff) shr 2)+$1000]:=true;
end;
$c20000:scroll_y1:=(512-valor) and $1ff;
$c20002:scroll_y2:=(512-valor) and $1ff;
$c40000:scroll_x1:=(512-valor) and $1ff;
$c40002:scroll_x2:=(512-valor) and $1ff;
$c50000..$c50003:;
$d00000..$d03fff:ram3[(direccion and $3fff) shr 1]:=valor;
end;
end;
function rainbow_snd_getbyte(direccion:word):byte;
begin
case direccion of
$4000..$7fff:rainbow_snd_getbyte:=bank_sound[sound_bank,direccion and $3fff];
$9001:rainbow_snd_getbyte:=ym2151_0.status;
$a001:rainbow_snd_getbyte:=tc0140syt_0.slave_comm_r;
else rainbow_snd_getbyte:=mem_snd[direccion];
end;
end;
procedure rainbow_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7fff:;
$9000:ym2151_0.reg(valor);
$9001:ym2151_0.write(valor);
$a000:tc0140syt_0.slave_port_w(valor);
$a001:tc0140syt_0.slave_comm_w(valor);
else mem_snd[direccion]:=valor;
end;
end;
procedure sound_bank_rom(valor:byte);
begin
sound_bank:=valor and 3;
end;
procedure sound_instruccion;
begin
ym2151_0.update;
end;
procedure ym2151_snd_irq(irqstate:byte);
begin
tc0140syt_0.z80.change_irq(irqstate);
end;
function rainbow_800007:byte;
begin
rainbow_800007:=marcade.in0;
end;
function rainbow_800009:byte;
begin
rainbow_800009:=marcade.in1;
end;
function rainbow_80000c:byte;
begin
rainbow_80000c:=marcade.in2;
end;
function rainbow_80000d:byte;
begin
rainbow_80000d:=marcade.in3;
end;
//Main
procedure reset_rainbow;
begin
m68000_0.reset;
tc0140syt_0.reset;
ym2151_0.reset;
{$IFDEF MCU}cchip_0.reset;{$ENDIF}
reset_audio;
marcade.in0:=$ff;
marcade.in1:=0;//$fc;
marcade.in2:=$ff;
marcade.in3:=$ff;
sound_bank:=0;
scroll_x1:=0;
scroll_y1:=0;
scroll_x2:=0;
scroll_y2:=0;
end;
function iniciar_rainbow:boolean;
const
pc_y:array[0..7] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32);
ps_x:array[0..15] of dword=(8, 12, 0, 4, 24, 28, 16, 20, 40, 44, 32, 36, 56, 60, 48, 52);
ps_y:array[0..15] of dword=(0*64, 1*64, 2*64, 3*64, 4*64, 5*64, 6*64, 7*64,
8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64);
var
memoria_temp,ptemp:pbyte;
procedure convert_chars;
begin
init_gfx(0,8,8,$4000);
gfx[0].trans[0]:=true;
gfx_set_desc_data(4,0,32*8,0,1,2,3);
convert_gfx(0,0,memoria_temp,@ps_x,@pc_y,false,false);
end;
procedure convert_sprites;
begin
init_gfx(1,16,16,$1400);
gfx[1].trans[0]:=true;
gfx_set_desc_data(4,0,128*8,0,1,2,3);
convert_gfx(1,0,memoria_temp,@ps_x,@ps_y,false,false);
end;
begin
iniciar_rainbow:=false;
llamadas_maquina.bucle_general:=rainbow_principal;
llamadas_maquina.reset:=reset_rainbow;
iniciar_audio(false);
screen_init(1,512,512);
screen_mod_scroll(1,512,512,511,512,256,511);
screen_init(2,512,512,true);
screen_mod_scroll(2,512,512,511,512,256,511);
screen_init(3,512,512,false,true);
iniciar_video(320,224);
//Main CPU
m68000_0:=cpu_m68000.create(8000000,256*CPU_SYNC);
m68000_0.change_ram16_calls(rainbow_getword,rainbow_putword);
//Sound CPU
tc0140syt_0:=tc0140syt_chip.create(4000000,256*CPU_SYNC);
tc0140syt_0.z80.change_ram_calls(rainbow_snd_getbyte,rainbow_snd_putbyte);
tc0140syt_0.z80.init_sound(sound_instruccion);
//Sound Chips
ym2151_0:=ym2151_chip.create(4000000);
ym2151_0.change_port_func(sound_bank_rom);
ym2151_0.change_irq_func(ym2151_snd_irq);
//cargar roms
getmem(memoria_temp,$100000);
case main_vars.tipo_maquina of
179:begin
//MCU
{$IFDEF MCU}
cchip_0:=cchip_chip.create(12000000,256*CPU_SYNC);
cchip_0.change_ad(rainbow_80000d);
cchip_0.change_in(rainbow_800007,rainbow_800009,rainbow_80000c,nil,nil);
if not(roms_load(cchip_0.get_eeprom_dir,rainbow_cchip_eeprom)) then exit;
{$ELSE IF}
rbisland_init_cchip(m68000_0.numero_cpu,0);
{$ENDIF}
if not(roms_load16w(@rom,rainbow_rom)) then exit;
//cargar sonido+ponerlas en su banco
ptemp:=memoria_temp;
if not(roms_load(memoria_temp,rainbow_sound)) then exit;
copymemory(@mem_snd[0],memoria_temp,$4000);
copymemory(@bank_sound[0,0],ptemp,$4000);inc(ptemp,$4000);
copymemory(@bank_sound[1,0],ptemp,$4000);inc(ptemp,$4000);
copymemory(@bank_sound[2,0],ptemp,$4000);inc(ptemp,$4000);
copymemory(@bank_sound[3,0],ptemp,$4000);
//convertir chars
if not(roms_load(memoria_temp,rainbow_char)) then exit;
convert_chars;
//convertir sprites
if not(roms_load(memoria_temp,rainbow_sprites1)) then exit;
if not(roms_load16b(memoria_temp,rainbow_sprites2)) then exit;
convert_sprites;
end;
180:begin
//MCU
{$IFDEF MCU}
cchip_0:=cchip_chip.create(12000000,256*CPU_SYNC);
cchip_0.change_ad(rainbow_80000d);
cchip_0.change_in(rainbow_800007,rainbow_800009,rainbow_80000c,nil,nil);
if not(roms_load(cchip_0.get_eeprom_dir,rainbow_cchip_eeprom)) then exit;
{$ELSE IF}
rbisland_init_cchip(m68000_0.numero_cpu,1);
{$ENDIF}
if not(roms_load16w(@rom,rainbowe_rom)) then exit;
//cargar sonido+ponerlas en su banco
ptemp:=memoria_temp;
if not(roms_load(memoria_temp,rainbow_sound)) then exit;
copymemory(@mem_snd[0],memoria_temp,$4000);
copymemory(@bank_sound[0,0],ptemp,$4000);inc(ptemp,$4000);
copymemory(@bank_sound[1,0],ptemp,$4000);inc(ptemp,$4000);
copymemory(@bank_sound[2,0],ptemp,$4000);inc(ptemp,$4000);
copymemory(@bank_sound[3,0],ptemp,$4000);
//convertir chars
if not(roms_load(memoria_temp,rainbow_char)) then exit;
convert_chars;
//convertir sprites
if not(roms_load(memoria_temp,rainbow_sprites1)) then exit;
if not(roms_load16b(memoria_temp,rainbow_sprites2)) then exit;
convert_sprites;
end;
end;
//DIP
marcade.dswa:=$fe;
marcade.dswa_val:=@rainbow_dip1;
marcade.dswb:=$bf;
marcade.dswb_val:=@rainbow_dip2;
//final
freemem(memoria_temp);
reset_rainbow;
iniciar_rainbow:=true;
end;
end.
|
unit UInterface; // Fully annotated
interface
type
TCoord = record
x: integer;
y: integer;
end;
TRoute = Array of TCoord;
TwoDArray = Array of Array of integer;
OneDArray = Array of integer;
procedure ReturnItemsToFind(x, y, LastIndex: integer;
var ItemsToFind: TwoDArray; var ItemsToFindLength: integer);
implementation
// Returns the coordinates of cells next to a specified cell
procedure ReturnItemsToFind(x, y, LastIndex: integer;
var ItemsToFind: TwoDArray; var ItemsToFindLength: integer);
begin
ItemsToFindLength := 0;
// Determines whether the cell to the left of it is in the maze
if (((x - 1) >= 0) and ((y) >= 0)) then
begin
if (((x - 1) <= LastIndex) and ((y) <= LastIndex)) then
begin
// Adds it to the list of cells adjacent
ItemsToFind[ItemsToFindLength, 0] := x - 1;
ItemsToFind[ItemsToFindLength, 1] := y;
inc(ItemsToFindLength);
end;
end;
// Determines whether the cell to the right of it is in the maze
if (((x + 1) >= 0) and ((y) >= 0)) then
begin
if (((x + 1) <= LastIndex) and ((y) <= LastIndex)) then
begin
// Adds it to the list of cells adjacent
ItemsToFind[ItemsToFindLength, 0] := x + 1;
ItemsToFind[ItemsToFindLength, 1] := y;
inc(ItemsToFindLength);
end;
end;
// Determines whether the cell below it is in the maze
if (((x) >= 0) and ((y - 1) >= 0)) then
begin
if (((x) <= LastIndex) and ((y - 1) <= LastIndex)) then
begin
// Adds it to the list of cells adjacent
ItemsToFind[ItemsToFindLength, 0] := x;
ItemsToFind[ItemsToFindLength, 1] := y - 1;
inc(ItemsToFindLength);
end;
end;
// Determines whether the cell above it is in the maze
if (((x) >= 0) and ((y + 1) >= 0)) then
begin
if (((x) <= LastIndex) and ((y + 1) <= LastIndex)) then
begin
// Adds it to the list of cells adjacent
ItemsToFind[ItemsToFindLength, 0] := x;
ItemsToFind[ItemsToFindLength, 1] := y + 1;
inc(ItemsToFindLength);
end;
end;
end;
end.
|
unit RegistryData;
interface
uses
Classes, SysUtils;
// GetClassPath returns the path of the given Class
function GetClassPath( Name : WideString ) : WideString;
type
ECacheRegistryError = class(Exception);
implementation
uses
Windows, ActiveX, ComObj, Registry, CacheRegistryKeys, CacheObjects, CacheCommon;
type
POleVariant = ^OleVariant;
const
NoIndex = -1;
function GetClassPath( Name : WideString ) : WideString;
begin
result := GetCacheRootPath + 'Classes\' + Name + '\' + FiveExt;
end;
procedure ReadCacheRootFromRegistry;
var
Root : string;
Reg : TRegistry;
begin
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
try
if Reg.OpenKey( CacheKey, false )
then
begin
Root := Reg.ReadString( 'RootPath' );
CacheObjects.SetCacheRootPath( Root );
end
else raise ECacheRegistryError.Create( 'Cannot read the root path from registry' );
finally
Reg.Free;
end;
end;
initialization
ReadCacheRootFromRegistry;
end.
|
unit YWDictionarys;
interface
uses classes, SysUtils, RTLConsts, Generics.Collections, Generics.Defaults;
type
TModDictionary<TKey,TValue,TItem> = class abstract(TEnumerable<TPair<TKey,TValue>>)
private
type
TItemArray = array of TItem;
var
FItems: TItemArray;
FCount: Integer;
FComparer: IEqualityComparer<TKey>;
FGrowThreshold: Integer;
function ToArrayImpl(Count: Integer): TArray<TPair<TKey,TValue>>;
procedure SetCapacity(ACapacity: Integer);
procedure Rehash(NewCapPow2: Integer);
procedure Grow;
function GetBucketIndex(const Key: TKey; HashCode: Integer): Integer;
function GetItem(const Key: TKey): TValue;
procedure SetItem(const Key: TKey; const Value: TValue);
procedure RehashAdd(HashCode: Integer; const Key: TKey; const Value: TValue);
procedure DoAdd(HashCode, Index: Integer; const Key: TKey; const Value: TValue);
procedure DoSetValue(Index: Integer; const Value: TValue);
function DoRemove(const Key: TKey; HashCode: Integer; Notification: TCollectionNotification): TValue;
protected
function DoGetEnumerator: TEnumerator<TPair<TKey,TValue>>; override;
procedure KeyNotify(const Key: TKey; Action: TCollectionNotification); virtual;
procedure ValueNotify(const Value: TValue; Action: TCollectionNotification); virtual;
procedure SetHashCodeForItem(var I : TItem; H : integer); virtual; abstract;
function GetHashCodeFromItem(var I : TItem):integer; virtual; abstract;
procedure SetKeyForItem(var I : TItem; H : TKey); virtual; abstract;
function GetKeyFromItem(var I : TItem):TKey; virtual; abstract;
procedure SetValueForItem(var I : TItem; H : TValue); virtual; abstract;
function GetValueFromItem(var I : TItem):TValue; virtual; abstract;
function Hash(const Key: TKey): Integer; virtual;
public
constructor Create(ACapacity: Integer = 0); overload;
constructor Create(const AComparer: IEqualityComparer<TKey>); overload;
constructor Create(ACapacity: Integer; const AComparer: IEqualityComparer<TKey>); overload;
constructor Create(const Collection: TEnumerable<TPair<TKey,TValue>>); overload;
constructor Create(const Collection: TEnumerable<TPair<TKey,TValue>>; const AComparer: IEqualityComparer<TKey>); overload;
destructor Destroy; override;
procedure Add(const Key: TKey; const Value: TValue);
procedure Remove(const Key: TKey);
function ExtractPair(const Key: TKey): TPair<TKey,TValue>;
procedure Clear;
procedure TrimExcess;
function TryGetValue(const Key: TKey; out Value: TValue): Boolean;
procedure AddOrSetValue(const Key: TKey; const Value: TValue);
function TryAdd(const Key: TKey; const Value: TValue): Boolean;
function ContainsKey(const Key: TKey): Boolean;
function ContainsValue(const Value: TValue): Boolean;
function ToArray: TArray<TPair<TKey,TValue>>; override; final;
property Items[const Key: TKey]: TValue read GetItem write SetItem; default;
property Count: Integer read FCount;
type
TPairEnumerator = class(TEnumerator<TPair<TKey,TValue>>)
private
FDictionary: TModDictionary<TKey,TValue,TItem>;
FIndex: Integer;
function GetCurrent: TPair<TKey,TValue>;
protected
function DoGetCurrent: TPair<TKey,TValue>; override;
function DoMoveNext: Boolean; override;
public
constructor Create(const ADictionary: TModDictionary<TKey,TValue,TItem>);
property Current: TPair<TKey,TValue> read GetCurrent;
function MoveNext: Boolean;
end;
TKeyEnumerator = class(TEnumerator<TKey>)
private
FDictionary: TModDictionary<TKey,TValue,TItem>;
FIndex: Integer;
function GetCurrent: TKey;
protected
function DoGetCurrent: TKey; override;
function DoMoveNext: Boolean; override;
public
constructor Create(const ADictionary: TModDictionary<TKey,TValue,TItem>);
property Current: TKey read GetCurrent;
function MoveNext: Boolean;
end;
TValueEnumerator = class(TEnumerator<TValue>)
private
FDictionary: TModDictionary<TKey,TValue,TItem>;
FIndex: Integer;
function GetCurrent: TValue;
protected
function DoGetCurrent: TValue; override;
function DoMoveNext: Boolean; override;
public
constructor Create(const ADictionary: TModDictionary<TKey,TValue,TItem>);
property Current: TValue read GetCurrent;
function MoveNext: Boolean;
end;
TValueCollection = class(TEnumerable<TValue>)
private
[Weak] FDictionary: TModDictionary<TKey,TValue,TItem>;
function GetCount: Integer;
function ToArrayImpl(Count: Integer): TArray<TValue>;
protected
function DoGetEnumerator: TEnumerator<TValue>; override;
public
constructor Create(const ADictionary: TModDictionary<TKey,TValue,TItem>);
function GetEnumerator: TValueEnumerator; reintroduce;
function ToArray: TArray<TValue>; override; final;
property Count: Integer read GetCount;
end;
TKeyCollection = class(TEnumerable<TKey>)
private
[Weak] FDictionary: TModDictionary<TKey,TValue,TItem>;
function GetCount: Integer;
function ToArrayImpl(Count: Integer): TArray<TKey>;
protected
function DoGetEnumerator: TEnumerator<TKey>; override;
public
constructor Create(const ADictionary: TModDictionary<TKey,TValue,TItem>);
function GetEnumerator: TKeyEnumerator; reintroduce;
function ToArray: TArray<TKey>; override; final;
property Count: Integer read GetCount;
end;
private
FOnKeyNotify: TCollectionNotifyEvent<TKey>;
FOnValueNotify: TCollectionNotifyEvent<TValue>;
FKeyCollection: TKeyCollection;
FValueCollection: TValueCollection;
function GetKeys: TKeyCollection;
function GetValues: TValueCollection;
public
function GetEnumerator: TPairEnumerator; reintroduce;
property Keys: TKeyCollection read GetKeys;
property Values: TValueCollection read GetValues;
property Comparer: IEqualityComparer<TKey> read FComparer;
property OnKeyNotify: TCollectionNotifyEvent<TKey> read FOnKeyNotify write FOnKeyNotify;
property OnValueNotify: TCollectionNotifyEvent<TValue> read FOnValueNotify write FOnValueNotify;
end;
_TGUIDItem<TValue> = record
Key : TGuid;
Value : TValue;
end;
TGUIDDictionary<TValue>=class(TModDictionary<TGuid,TValue,_TGUIDItem<TValue>>)
protected
procedure SetHashCodeForItem(var I : _TGUIDItem<TValue>; H : integer); override;
function GetHashCodeFromItem(var I : _TGUIDItem<TValue>):integer; override;
procedure SetKeyForItem(var I : _TGUIDItem<TValue>; H : TGUID); override;
function GetKeyFromItem(var I : _TGUIDItem<TValue>):TGUID; override;
procedure SetValueForItem(var I : _TGUIDItem<TValue>; H : TValue); override;
function GetValueFromItem(var I : _TGUIDItem<TValue>):TValue; override;
function Hash(const Key: TGUID): Integer; override;
end;
_TKeyedObjItem<TValue> = record
HashCode : integer;
Value : TValue;
end;
TKeyedObjDictionary<TKey,TValue>= class abstract(TModDictionary<TKey,TValue,_TKeyedObjItem<TValue>>)
protected
function GetKeyFromValue(V : TValue):TKey; virtual; abstract;
procedure SetHashCodeForItem(var I : _TKeyedObjItem<TValue>; H : integer); override;
function GetHashCodeFromItem(var I : _TKeyedObjItem<TValue>):integer; override;
procedure SetKeyForItem(var I : _TKeyedObjItem<TValue>; H : TKey); override;
function GetKeyFromItem(var I : _TKeyedObjItem<TValue>):TKey; override;
procedure SetValueForItem(var I : _TKeyedObjItem<TValue>; H : TValue); override;
function GetValueFromItem(var I : _TKeyedObjItem<TValue>):TValue; override;
end;
TGUIDedObjDictionary<TValue>=class abstract(TKeyedObjDictionary<TGuid,TValue>)
protected
function Hash(const Key: TGUID): Integer; override;
end;
function InCircularRange(Bottom, Item, TopInc: Integer): Boolean; inline;
implementation
const
EMPTY_HASH = -1;
procedure TModDictionary<TKey,TValue,TItem>.Rehash(NewCapPow2: Integer);
var
oldItems, newItems: TItemArray;
i: Integer;
begin
if NewCapPow2 = Length(FItems) then
Exit
else if NewCapPow2 < 0 then
OutOfMemoryError;
oldItems := FItems;
SetLength(newItems, NewCapPow2);
for i := 0 to Length(newItems) - 1 do
SetHashCodeForItem(newItems[i],EMPTY_HASH);
FItems := newItems;
FGrowThreshold := NewCapPow2 shr 1 + NewCapPow2 shr 2; // 75%
for i := 0 to Length(oldItems) - 1 do
if GetHashCodeFromItem(oldItems[i]) <> EMPTY_HASH then
RehashAdd(GetHashCodeFromItem(oldItems[i]), GetKeyFromItem(oldItems[i]),
GetValueFromItem(oldItems[i]));
end;
procedure TModDictionary<TKey,TValue,TItem>.SetCapacity(ACapacity: Integer);
var
newCap: Integer;
begin
if ACapacity < Count then
ErrorArgumentOutOfRange;
if ACapacity = 0 then
Rehash(0)
else
begin
newCap := 4;
while newCap < ACapacity do
newCap := newCap shl 1;
Rehash(newCap);
end
end;
procedure TModDictionary<TKey,TValue,TItem>.Grow;
var
newCap: Integer;
begin
newCap := Length(FItems) * 2;
if newCap = 0 then
newCap := 4;
Rehash(newCap);
end;
function TModDictionary<TKey,TValue,TItem>.GetBucketIndex(const Key: TKey; HashCode: Integer): Integer;
var
start, hc: Integer;
begin
if Length(FItems) = 0 then
Exit(not High(Integer));
start := HashCode and (Length(FItems) - 1);
Result := start;
while True do
begin
hc := GetHashCodeFromItem(FItems[Result]);
// Not found: return complement of insertion point.
if hc = EMPTY_HASH then
Exit(not Result);
// Found: return location.
if (hc = HashCode) and FComparer.Equals(GetKeyFromItem(FItems[Result]), Key) then
Exit(Result);
Inc(Result);
if Result >= Length(FItems) then
Result := 0;
end;
end;
function TModDictionary<TKey,TValue,TItem>.Hash(const Key: TKey): Integer;
const
PositiveMask = not Integer($80000000);
begin
// Double-Abs to avoid -MaxInt and MinInt problems.
// Not using compiler-Abs because we *must* get a positive integer;
// for compiler, Abs(Low(Integer)) is a null op.
Result := PositiveMask and ((PositiveMask and FComparer.GetHashCode(Key)) + 1);
end;
function TModDictionary<TKey,TValue,TItem>.GetItem(const Key: TKey): TValue;
var
index: Integer;
begin
index := GetBucketIndex(Key, Hash(Key));
if index < 0 then
raise EListError.CreateRes(@SGenericItemNotFound);
Result := GetValueFromItem(FItems[index]);
end;
procedure TModDictionary<TKey,TValue,TItem>.SetItem(const Key: TKey; const Value: TValue);
var
index: Integer;
oldValue: TValue;
begin
index := GetBucketIndex(Key, Hash(Key));
if index < 0 then
raise EListError.CreateRes(@SGenericItemNotFound);
oldValue := GetValueFromItem(FItems[index]);
SetValueForItem(FItems[index],Value);
ValueNotify(oldValue, cnRemoved);
ValueNotify(Value, cnAdded);
end;
procedure TModDictionary<TKey,TValue,TItem>.RehashAdd(HashCode: Integer; const Key: TKey; const Value: TValue);
var
index: Integer;
begin
index := not GetBucketIndex(Key, HashCode);
SetHashCodeForItem(FItems[index],HashCode);
SetKeyForItem(FItems[index],Key);
SetValueForItem(FItems[index],Value);
end;
procedure TModDictionary<TKey,TValue,TItem>.KeyNotify(const Key: TKey; Action: TCollectionNotification);
begin
if Assigned(FOnKeyNotify) then
FOnKeyNotify(Self, Key, Action);
end;
procedure TModDictionary<TKey,TValue,TItem>.ValueNotify(const Value: TValue; Action: TCollectionNotification);
begin
if Assigned(FOnValueNotify) then
FOnValueNotify(Self, Value, Action);
end;
constructor TModDictionary<TKey,TValue,TItem>.Create(ACapacity: Integer = 0);
begin
Create(ACapacity, nil);
end;
constructor TModDictionary<TKey,TValue,TItem>.Create(const AComparer: IEqualityComparer<TKey>);
begin
Create(0, AComparer);
end;
constructor TModDictionary<TKey,TValue,TItem>.Create(ACapacity: Integer; const AComparer: IEqualityComparer<TKey>);
var
cap: Integer;
begin
inherited Create;
if ACapacity < 0 then
ErrorArgumentOutOfRange;
FComparer := AComparer;
if FComparer = nil then
FComparer := TEqualityComparer<TKey>.Default;
SetCapacity(ACapacity);
end;
constructor TModDictionary<TKey, TValue,TItem>.Create(const Collection: TEnumerable<TPair<TKey, TValue>>);
var
item: TPair<TKey,TValue>;
begin
Create(0, nil);
for item in Collection do
AddOrSetValue(item.Key, item.Value);
end;
constructor TModDictionary<TKey, TValue,TItem>.Create(const Collection: TEnumerable<TPair<TKey, TValue>>;
const AComparer: IEqualityComparer<TKey>);
var
item: TPair<TKey,TValue>;
begin
Create(0, AComparer);
for item in Collection do
AddOrSetValue(item.Key, item.Value);
end;
destructor TModDictionary<TKey,TValue,TItem>.Destroy;
begin
Clear;
FKeyCollection.Free;
FValueCollection.Free;
inherited;
end;
procedure TModDictionary<TKey,TValue,TItem>.Add(const Key: TKey; const Value: TValue);
var
index, hc: Integer;
begin
if Count >= FGrowThreshold then
Grow;
hc := Hash(Key);
index := GetBucketIndex(Key, hc);
if index >= 0 then
raise EListError.CreateRes(@SGenericDuplicateItem);
DoAdd(hc, not index, Key, Value);
end;
function InCircularRange(Bottom, Item, TopInc: Integer): Boolean;
begin
Result := (Bottom < Item) and (Item <= TopInc) // normal
or (TopInc < Bottom) and (Item > Bottom) // top wrapped
or (TopInc < Bottom) and (Item <= TopInc) // top and item wrapped
end;
function TModDictionary<TKey,TValue,TItem>.DoRemove(const Key: TKey; HashCode: Integer;
Notification: TCollectionNotification): TValue;
var
gap, index, hc, bucket: Integer;
LKey: TKey;
begin
index := GetBucketIndex(Key, HashCode);
if index < 0 then
Exit(Default(TValue));
// Removing item from linear probe hash table is moderately
// tricky. We need to fill in gaps, which will involve moving items
// which may not even hash to the same location.
// Knuth covers it well enough in Vol III. 6.4.; but beware, Algorithm R
// (2nd ed) has a bug: step R4 should go to step R1, not R2 (already errata'd).
// My version does linear probing forward, not backward, however.
// gap refers to the hole that needs filling-in by shifting items down.
// index searches for items that have been probed out of their slot,
// but being careful not to move items if their bucket is between
// our gap and our index (so that they'd be moved before their bucket).
// We move the item at index into the gap, whereupon the new gap is
// at the index. If the index hits a hole, then we're done.
// If our load factor was exactly 1, we'll need to hit this hole
// in order to terminate. Shouldn't normally be necessary, though.
SetHashCodeForItem(FItems[index],EMPTY_HASH);
Result := GetValueFromItem(FItems[index]);
LKey := GetKeyFromItem(FItems[index]);
gap := index;
while True do
begin
Inc(index);
if index = Length(FItems) then
index := 0;
hc := GetHashCodeFromItem(FItems[index]);
if hc = EMPTY_HASH then
Break;
bucket := hc and (Length(FItems) - 1);
if not InCircularRange(gap, bucket, index) then
begin
FItems[gap] := FItems[index];
gap := index;
// The gap moved, but we still need to find it to terminate.
SetHashCodeForItem(FItems[gap],EMPTY_HASH);
end;
end;
SetHashCodeForItem(FItems[gap],EMPTY_HASH);
SetKeyForItem(FItems[gap],Default(TKey));
SetValueForItem(FItems[gap],Default(TValue));
Dec(FCount);
KeyNotify(LKey, Notification);
ValueNotify(Result, Notification);
end;
procedure TModDictionary<TKey,TValue,TItem>.Remove(const Key: TKey);
begin
DoRemove(Key, Hash(Key), cnRemoved);
end;
function TModDictionary<TKey,TValue,TItem>.ExtractPair(const Key: TKey): TPair<TKey,TValue>;
var
hc, index: Integer;
begin
hc := Hash(Key);
index := GetBucketIndex(Key, hc);
if index < 0 then
Exit(TPair<TKey,TValue>.Create(Key, Default(TValue)));
Result := TPair<TKey,TValue>.Create(Key, DoRemove(Key, hc, cnExtracted));
end;
procedure TModDictionary<TKey,TValue,TItem>.Clear;
var
i: Integer;
oldItems: TItemArray;
begin
oldItems := FItems;
FCount := 0;
SetLength(FItems, 0);
SetCapacity(0);
FGrowThreshold := 0;
for i := 0 to Length(oldItems) - 1 do
begin
if GetHashCodeFromItem(oldItems[i]) = EMPTY_HASH then
Continue;
KeyNotify(GetKeyFromItem(oldItems[i]), cnRemoved);
ValueNotify(GetValueFromItem(oldItems[i]), cnRemoved);
end;
end;
function TModDictionary<TKey, TValue,TItem>.ToArray: TArray<TPair<TKey,TValue>>;
begin
Result := ToArrayImpl(Count);
end;
function TModDictionary<TKey, TValue, TItem>.ToArrayImpl(
Count: Integer): TArray<TPair<TKey, TValue>>;
var
Value: TPair<TKey, TValue>;
begin
// We assume our caller has passed correct Count
SetLength(Result, Count);
Count := 0;
for Value in Self do
begin
Result[Count] := Value;
Inc(Count);
end;
end;
procedure TModDictionary<TKey,TValue,TItem>.TrimExcess;
begin
// Ensure at least one empty slot for GetBucketIndex to terminate.
SetCapacity(Count + 1);
end;
function TModDictionary<TKey,TValue,TItem>.TryGetValue(const Key: TKey; out Value: TValue): Boolean;
var
index: Integer;
begin
index := GetBucketIndex(Key, Hash(Key));
Result := index >= 0;
if Result then
Value := GetValueFromItem(FItems[index])
else
Value := Default(TValue);
end;
procedure TModDictionary<TKey,TValue,TItem>.DoAdd(HashCode, Index: Integer; const Key: TKey; const Value: TValue);
begin
SetHashCodeForItem(FItems[Index],HashCode);
SetKeyForItem(FItems[Index],Key);
SetValueForItem(FItems[Index],Value);
Inc(FCount);
KeyNotify(Key, cnAdded);
ValueNotify(Value, cnAdded);
end;
function TModDictionary<TKey, TValue,TItem>.DoGetEnumerator: TEnumerator<TPair<TKey, TValue>>;
begin
Result := GetEnumerator;
end;
procedure TModDictionary<TKey,TValue,TItem>.DoSetValue(Index: Integer; const Value: TValue);
var
oldValue: TValue;
begin
oldValue := GetValueFromItem(FItems[Index]);
SetValueForItem(FItems[Index],Value);
ValueNotify(oldValue, cnRemoved);
ValueNotify(Value, cnAdded);
end;
procedure TModDictionary<TKey,TValue,TItem>.AddOrSetValue(const Key: TKey; const Value: TValue);
var
hc: Integer;
index: Integer;
begin
hc := Hash(Key);
index := GetBucketIndex(Key, hc);
if index >= 0 then
DoSetValue(index, Value)
else
begin
// We only grow if we are inserting a new value.
if Count >= FGrowThreshold then
begin
Grow;
// We need a new Bucket Index because the array has grown.
index := GetBucketIndex(Key, hc);
end;
DoAdd(hc, not index, Key, Value);
end;
end;
function TModDictionary<TKey,TValue,TItem>.TryAdd(const Key: TKey; const Value: TValue): Boolean;
var
hc: Integer;
index: Integer;
begin
hc := Hash(Key);
index := GetBucketIndex(Key, hc);
Result := index < 0;
if Result then
begin
// We only grow if we are inserting a new value.
if Count >= FGrowThreshold then
begin
Grow;
// We need a new Bucket Index because the array has grown.
index := GetBucketIndex(Key, hc);
end;
DoAdd(hc, not index, Key, Value);
end;
end;
function TModDictionary<TKey,TValue,TItem>.ContainsKey(const Key: TKey): Boolean;
begin
Result := GetBucketIndex(Key, Hash(Key)) >= 0;
end;
function TModDictionary<TKey,TValue,TItem>.ContainsValue(const Value: TValue): Boolean;
var
i: Integer;
c: IEqualityComparer<TValue>;
begin
c := TEqualityComparer<TValue>.Default;
for i := 0 to Length(FItems) - 1 do
if (GetHashCodeFromItem(FItems[i]) <> EMPTY_HASH) and
c.Equals(GetValueFromItem(FItems[i]), Value) then
Exit(True);
Result := False;
end;
function TModDictionary<TKey,TValue,TItem>.GetEnumerator: TPairEnumerator;
begin
Result := TPairEnumerator.Create(Self);
end;
function TModDictionary<TKey,TValue,TItem>.GetKeys: TKeyCollection;
begin
if FKeyCollection = nil then
FKeyCollection := TKeyCollection.Create(Self);
Result := FKeyCollection;
end;
function TModDictionary<TKey,TValue,TItem>.GetValues: TValueCollection;
begin
if FValueCollection = nil then
FValueCollection := TValueCollection.Create(Self);
Result := FValueCollection;
end;
// Pairs
constructor TModDictionary<TKey,TValue,TItem>.TPairEnumerator.Create(
const ADictionary: TModDictionary<TKey,TValue,TItem>);
begin
inherited Create;
FIndex := -1;
FDictionary := ADictionary;
end;
function TModDictionary<TKey, TValue,TItem>.TPairEnumerator.DoGetCurrent: TPair<TKey, TValue>;
begin
Result := GetCurrent;
end;
function TModDictionary<TKey, TValue,TItem>.TPairEnumerator.DoMoveNext: Boolean;
begin
Result := MoveNext;
end;
function TModDictionary<TKey,TValue,TItem>.TPairEnumerator.GetCurrent: TPair<TKey,TValue>;
begin
Result.Key := FDictionary.GetKeyFromItem(FDictionary.FItems[FIndex]);
Result.Value := FDictionary.GetValueFromItem(FDictionary.FItems[FIndex]);
end;
function TModDictionary<TKey,TValue,TItem>.TPairEnumerator.MoveNext: Boolean;
begin
while FIndex < Length(FDictionary.FItems) - 1 do
begin
Inc(FIndex);
if FDictionary.GetHashCodeFromItem(FDictionary.FItems[FIndex]) <> EMPTY_HASH then
Exit(True);
end;
Result := False;
end;
// Keys
constructor TModDictionary<TKey,TValue,TItem>.TKeyEnumerator.Create(
const ADictionary: TModDictionary<TKey,TValue,TItem>);
begin
inherited Create;
FIndex := -1;
FDictionary := ADictionary;
end;
function TModDictionary<TKey, TValue,TItem>.TKeyEnumerator.DoGetCurrent: TKey;
begin
Result := GetCurrent;
end;
function TModDictionary<TKey, TValue,TItem>.TKeyEnumerator.DoMoveNext: Boolean;
begin
Result := MoveNext;
end;
function TModDictionary<TKey,TValue,TItem>.TKeyEnumerator.GetCurrent: TKey;
begin
Result := FDictionary.GetKeyFromItem(FDictionary.FItems[FIndex]);
end;
function TModDictionary<TKey,TValue,TItem>.TKeyEnumerator.MoveNext: Boolean;
begin
while FIndex < Length(FDictionary.FItems) - 1 do
begin
Inc(FIndex);
if FDictionary.GetHashCodeFromItem(FDictionary.FItems[FIndex]) <> EMPTY_HASH then
Exit(True);
end;
Result := False;
end;
// Values
constructor TModDictionary<TKey,TValue,TItem>.TValueEnumerator.Create(
const ADictionary: TModDictionary<TKey,TValue,TItem>);
begin
inherited Create;
FIndex := -1;
FDictionary := ADictionary;
end;
function TModDictionary<TKey, TValue,TItem>.TValueEnumerator.DoGetCurrent: TValue;
begin
Result := GetCurrent;
end;
function TModDictionary<TKey, TValue,TItem>.TValueEnumerator.DoMoveNext: Boolean;
begin
Result := MoveNext;
end;
function TModDictionary<TKey,TValue,TItem>.TValueEnumerator.GetCurrent: TValue;
begin
Result := FDictionary.GetValueFromItem(FDictionary.FItems[FIndex]);
end;
function TModDictionary<TKey,TValue,TItem>.TValueEnumerator.MoveNext: Boolean;
begin
while FIndex < Length(FDictionary.FItems) - 1 do
begin
Inc(FIndex);
if FDictionary.GetHashCodeFromItem(FDictionary.FItems[FIndex]) <> EMPTY_HASH then
Exit(True);
end;
Result := False;
end;
{ TGUIDDictionary<TValue> }
function TGUIDDictionary<TValue>.GetHashCodeFromItem(
var I: _TGUIDItem<TValue>): integer;
begin
Result := I.Key.D1;
end;
function TGUIDDictionary<TValue>.GetKeyFromItem(
var I: _TGUIDItem<TValue>): TGUID;
begin
Result := I.Key;
end;
function TGUIDDictionary<TValue>.GetValueFromItem(
var I: _TGUIDItem<TValue>): TValue;
begin
Result := I.Value;
end;
function TGUIDDictionary<TValue>.Hash(const Key: TGUID): Integer;
begin
Result := Key.D1;
end;
procedure TGUIDDictionary<TValue>.SetHashCodeForItem(var I: _TGUIDItem<TValue>;
H: integer);
begin
I.Key.D1 := H;
end;
procedure TGUIDDictionary<TValue>.SetKeyForItem(var I: _TGUIDItem<TValue>;
H: TGUID);
begin
I.Key := H;
end;
procedure TGUIDDictionary<TValue>.SetValueForItem(var I: _TGUIDItem<TValue>;
H: TValue);
begin
I.Value := H;
end;
{ TKeyedObjDictionary<TKey, TValue> }
function TKeyedObjDictionary<TKey, TValue>.GetHashCodeFromItem(
var I: _TKeyedObjItem<TValue>): integer;
begin
Result := I.HashCode;
end;
function TKeyedObjDictionary<TKey, TValue>.GetKeyFromItem(
var I: _TKeyedObjItem<TValue>): TKey;
begin
Result := GetKeyFromValue(I.Value);
end;
function TKeyedObjDictionary<TKey, TValue>.GetValueFromItem(
var I: _TKeyedObjItem<TValue>): TValue;
begin
Result := I.Value;
end;
procedure TKeyedObjDictionary<TKey, TValue>.SetHashCodeForItem(
var I: _TKeyedObjItem<TValue>; H: integer);
begin
I.HashCode := H;
end;
procedure TKeyedObjDictionary<TKey, TValue>.SetKeyForItem(
var I: _TKeyedObjItem<TValue>; H: TKey);
begin
end;
procedure TKeyedObjDictionary<TKey, TValue>.SetValueForItem(
var I: _TKeyedObjItem<TValue>; H: TValue);
begin
I.Value := H;
end;
{ TGUIDedObjDictionary<TValue> }
function TGUIDedObjDictionary<TValue>.Hash(const Key: TGUID): Integer;
begin
Result := Key.D1;
end;
{ TModDictionary<TKey, TValue, TItem>.TValueCollection }
constructor TModDictionary<TKey, TValue, TItem>.TValueCollection.Create(
const ADictionary: TModDictionary<TKey, TValue, TItem>);
begin
inherited Create;
FDictionary := ADictionary;
end;
function TModDictionary<TKey, TValue, TItem>.TValueCollection.DoGetEnumerator: TEnumerator<TValue>;
begin
Result := GetEnumerator;
end;
function TModDictionary<TKey, TValue, TItem>.TValueCollection.GetCount: Integer;
begin
Result := FDictionary.Count;
end;
function TModDictionary<TKey, TValue, TItem>.TValueCollection.GetEnumerator: TValueEnumerator;
begin
Result := TValueEnumerator.Create(FDictionary);
end;
function TModDictionary<TKey, TValue, TItem>.TValueCollection.ToArray: TArray<TValue>;
begin
Result := ToArrayImpl(FDictionary.Count);
end;
function TModDictionary<TKey, TValue, TItem>.TValueCollection.ToArrayImpl(
Count: Integer): TArray<TValue>;
var
Value: TValue;
begin
// We assume our caller has passed correct Count
SetLength(Result, Count);
Count := 0;
for Value in Self do
begin
Result[Count] := Value;
Inc(Count);
end;
end;
{ TModDictionary<TKey, TValue, TItem>.TKeyCollection }
constructor TModDictionary<TKey, TValue, TItem>.TKeyCollection.Create(
const ADictionary: TModDictionary<TKey, TValue, TItem>);
begin
inherited Create;
FDictionary := ADictionary;
end;
function TModDictionary<TKey, TValue, TItem>.TKeyCollection.DoGetEnumerator: TEnumerator<TKey>;
begin
Result := GetEnumerator;
end;
function TModDictionary<TKey, TValue, TItem>.TKeyCollection.GetCount: Integer;
begin
Result := FDictionary.Count;
end;
function TModDictionary<TKey, TValue, TItem>.TKeyCollection.GetEnumerator: TKeyEnumerator;
begin
Result := TKeyEnumerator.Create(FDictionary);
end;
function TModDictionary<TKey, TValue, TItem>.TKeyCollection.ToArray: TArray<TKey>;
begin
Result := ToArrayImpl(FDictionary.Count);
end;
function TModDictionary<TKey, TValue, TItem>.TKeyCollection.ToArrayImpl(
Count: Integer): TArray<TKey>;
var
Value: TKey;
begin
// We assume our caller has passed correct Count
SetLength(Result, Count);
Count := 0;
for Value in Self do
begin
Result[Count] := Value;
Inc(Count);
end;
end;
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$
}
unit IdSys;
{$I IdCompilerDefines.inc}
interface
{
The model we are using is this:
IdSysBase - base class for everything
IdSysFCL - stuff for DotNET with NO VCL dependancies for Visual Studio and Mono
IdSysVCL - stuff that uses the VCL including packages for Borland Delphi VCL NET
IdSysNativeVCL - stuff that is shared betwen Linux and Win32 versions that uses pointers
and would make NO sense in DotNET.
IdSysLinux - Linux specific stuff
IdSysWindows - Windows specific stuff
}
uses
{$IFDEF DotNetDistro}
IdSysNet;
{$ELSE}
SysUtils, //SysUtils has to be here for non-Dot NET stuff
{$IFDEF MSWindows}
IdSysWin32;
{$ELSE}
{$IFDEF Linux}
IdSysLinux;
{$ELSE}
{$IFDEF DOTNET}
IdSysVCL,
IdSysVCLNET;
{$ELSE}
IdSysVCL;
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
type
{$IFDEF DotNetDistro}
Sys = class(TIdSysNet);
{$ELSE}
{$IFDEF MSWindows}
Sys = TIdSysWin32;
{$ELSE}
{$IFDEF Linux}
Sys = TIdSysLinux;
{$ELSE}
{$IFDEF DOTNET}
Sys = TIdSysVCLNET;
{$ELSE}
Sys = TIdSysVCL;
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
TIdDateTime = TIdDateTimeBase;
// Exceptions
//
// ALL Indy exceptions must descend from EIdException or descendants of it and not directly
// from EIdExceptionBase. This is the class that differentiates Indy exceptions from non Indy
// exceptions in a cross platform way
//
// Do NOT use the class keyword, we do not want a new class, we just want an alias
// so that it actually IS the base.
//
{$IFDEF DotNetDistro}
EIdExceptionBase = System.Exception;
EAbort = IdSysNET.EAbort;
{$ELSE}
EIdExceptionBase = Exception;
{$IFDEF DOTNET}
Exception = System.Exception;
{$ELSE}
Exception = SysUtils.Exception;
{$ENDIF}
EAbort = SysUtils.EAbort;
{$ENDIF}
implementation
end.
|
unit DataBuf;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, db;
type
TDataBuf = class(Tcomponent)
private
{ Private declarations }
ptr : Pointer;
function GetAsBoolean(index: integer): boolean;
procedure SetAsBoolean(index: integer; const Value: boolean);
function GetAsFloat(index: integer): double;
procedure SetAsFloat(index: integer; const Value: double);
protected
{ Protected declarations }
function GetAsInt(index: integer): integer;
procedure SetAsInt(index: integer; const Value: integer);
function GetAsCurrency(index: integer): currency;
function GetAsString(index: integer): shortstring;
procedure SetAsCurrency(index: integer; const Value: currency);
procedure SetAsString(index: integer; const Value: shortstring);
function PtrIndex(index:integer):pointer; virtual;
public
{ Public declarations }
property AsInt[index:integer]:integer read GetAsInt write SetAsInt;
property AsString[index:integer]:shortstring read GetAsString write SetAsString;
property AsCurrency[index:integer]:currency read GetAsCurrency write SetAsCurrency;
property AsBoolean[index:integer]:boolean read GetAsBoolean write SetAsBoolean;
property AsFloat[index:integer]:double read GetAsFloat write SetAsFloat;
function FieldNameToIndex(s:string):integer; virtual;
function FieldType(index:integer):TFieldType; virtual;
published
{ Published declarations }
end;
implementation
{ TDataBuf }
function TDataBuf.FieldNameToIndex(s: string): integer;
begin
result := 0;
end;
function TDataBuf.FieldType(index: integer): TFieldType;
begin
result := ftUnknown;
end;
function TDataBuf.GetAsBoolean(index: integer): boolean;
begin
ptr := PtrIndex(index);
if ptr <> nil then result := boolean(ptr^)
else result := false;
end;
function TDataBuf.GetAsCurrency(index: integer): currency;
begin
ptr := PtrIndex(index);
if ptr <> nil then result := currency(ptr^)
else result := 0;
end;
function TDataBuf.GetAsFloat(index: integer): double;
begin
ptr := PtrIndex(index);
if ptr <> nil then result := double(ptr^)
else result := 0;
end;
function TDataBuf.GetAsInt(index: integer): integer;
begin
ptr := PtrIndex(index);
if ptr <> nil then result := integer(ptr^)
else result := 0;
end;
function TDataBuf.GetAsString(index: integer): shortstring;
begin
ptr := PtrIndex(index);
if ptr <> nil then result := shortstring(ptr^)
else result := '';
end;
function TDataBuf.PtrIndex(index: integer): pointer;
begin
result := nil;
end;
procedure TDataBuf.SetAsBoolean(index: integer; const Value: boolean);
begin
ptr := PtrIndex(index);
if ptr <> nil then boolean(ptr^) := value;
end;
procedure TDataBuf.SetAsCurrency(index: integer; const Value: currency);
begin
ptr := PtrIndex(index);
if ptr <> nil then currency(ptr^) := value;
end;
procedure TDataBuf.SetAsFloat(index: integer; const Value: double);
begin
ptr := PtrIndex(index);
if ptr <> nil then double(ptr^) := value;
end;
procedure TDataBuf.SetAsInt(index: integer; const Value: integer);
begin
ptr := PtrIndex(index);
if ptr <> nil then integer(ptr^) := value;
end;
procedure TDataBuf.SetAsString(index: integer; const Value: shortstring);
begin
ptr := PtrIndex(index);
if ptr <> nil then shortstring(ptr^) := value;
end;
end.
|
unit nsParentedTagNode;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "f1DocumentTagsImplementation"
// Автор: Люлин А.В.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/f1DocumentTagsImplementation/nsParentedTagNode.pas"
// Начат: 2005/06/23 16:38:20
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> F1 Базовые определения предметной области::LegalDomain::f1DocumentTagsImplementation::DocumentTagNodes::TnsParentedTagNode
//
// Тег над адаптерной нодой, представляющий ссылку на родителя
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
k2Interfaces,
nsTagNodePrim,
k2Base,
F1TagDataProviderInterface,
Classes
;
type
_k2ParentedTagObject_Parent_ = TnsTagNodePrim;
{$Include w:\common\components\rtl\Garant\K2\k2ParentedTagObject.imp.pas}
TnsParentedTagNode = class(_k2ParentedTagObject_)
{* Тег над адаптерной нодой, представляющий ссылку на родителя }
public
// public methods
class function MakeNodeTag(const aNode: DocTagNodeType;
const aParent: Ik2Tag = nil;
aState: TnsNodeStates = []): Ik2Tag;
constructor Create(aType: Tk2Type;
const aNode: DocTagNodeType;
const aParent: Ik2Tag;
aState: TnsNodeStates); reintroduce; virtual;
end;//TnsParentedTagNode
implementation
uses
nsTagNode,
k2Facade,
QueryCard_Const,
Document_Const,
nsDocumentTagNodePrim,
CommentPara_Const,
Block_Const,
ReqRow_Const,
ReqCell_Const,
ParaList_Const,
ControlPara_Const,
TextPara_Const,
BitmapPara_Const,
SectionBreak_Const,
LeafPara_Const,
SysUtils,
nsSubNode,
nsSectionBreakNode,
nsTextParaNode,
nsControlParaNode,
nsBitmapParaNode,
nsReqCellNode,
nsReqRowNode,
nsBlockNode,
nsBlockNodePrim,
nsLeafParaNode
;
type _Instance_R_ = TnsParentedTagNode;
{$Include w:\common\components\rtl\Garant\K2\k2ParentedTagObject.imp.pas}
// start class TnsParentedTagNode
class function TnsParentedTagNode.MakeNodeTag(const aNode: DocTagNodeType;
const aParent: Ik2Tag = nil;
aState: TnsNodeStates = []): Ik2Tag;
//#UC START# *4C6E60FE0011_467FCD4401BD_var*
var
l_Tag : TnsParentedTagNode;
l_Type : Tk2Type;
//#UC END# *4C6E60FE0011_467FCD4401BD_var*
begin
//#UC START# *4C6E60FE0011_467FCD4401BD_impl*
if (aNode = nil) then
Result := k2NullTag
else
begin
l_Type := k2.TypeTable[aNode.TypeID];
if (l_Type = nil) then
Result := k2NullTag
else
begin
l_Tag := nil;
if (aParent = nil) OR not aParent.IsValid then
begin
if l_Type.InheritsFrom(k2_idQueryCard) then
begin
//l_Tag := TnsQueryCardNode.CreatePrim(aNode)
l_Tag := nil;
Assert(false, 'Устаревший код');
end//l_Type.InheritsFrom(k2_idQueryCard)
else
if l_Type.InheritsFrom(k2_idDocument) then
begin
//l_Tag := TnsDocumentTagNode.CreatePrim(aNode);
l_Tag := nil;
Assert(false, 'Устаревший код');
end;//l_Type.InheritsFrom(k2_idDocument)
end;//aParent = nil..
if (l_Tag = nil) then
begin
if l_Type.InheritsFrom(k2_idDocument) then
l_Tag := TnsDocumentTagNodePrim.Create(l_Type, aNode, aParent, aState)
else
if l_Type.InheritsFrom(k2_idCommentPara) then
begin
//l_Tag := TnsCommentNode.Create(l_Type, aNode, aParent, aState);
l_Tag := nil;
Assert(false, 'Устаревший код');
end
else
if l_Type.InheritsFrom(k2_idBlock) then
l_Tag := TnsBlockNode.Create(l_Type, aNode, aParent, aState)
else
if l_Type.InheritsFrom(k2_idReqRow) then
begin
l_Tag := TnsReqRowNode.Create(l_Type, aNode, aParent, aState);
end//l_Type.InheritsFrom(k2_idReqRow)
else
if l_Type.InheritsFrom(k2_idReqCell) then
begin
l_Tag := TnsReqCellNode.Create(l_Type, aNode, aParent, aState);
end//l_Type.InheritsFrom(k2_idReqCell)
else
if l_Type.InheritsFrom(k2_idParaList) then
l_Tag := TnsParaListNode.Create(l_Type, aNode, aParent, aState)
else
if l_Type.InheritsFrom(k2_idControlPara) then
begin
l_Tag := TnsControlParaNode.Create(l_Type, aNode, aParent, aState)
end//l_Type.InheritsFrom(k2_idControlPara)
else
if l_Type.InheritsFrom(k2_idTextPara) then
l_Tag := TnsTextParaNode.Create(l_Type, aNode, aParent, aState)
else
if l_Type.InheritsFrom(k2_idBitmapPara) then
l_Tag := TnsBitmapParaNode.Create(l_Type, aNode, aParent, aState)
else
if l_Type.InheritsFrom(k2_idSectionBreak) then
l_Tag := TnsSectionBreakNode.Create(l_Type, aNode, aParent, aState)
else
if l_Type.InheritsFrom(k2_idLeafPara) then
l_Tag := TnsLeafParaNode.Create(l_Type, aNode, aParent, aState)
else
l_Tag := Create(l_Type, aNode, aParent, aState);
end;//l_Tag = nil
try
Result := l_Tag;
finally
FreeAndNil(l_Tag);
end;//try..finally
end;//l_Type = nil
end;//aNode = nil
//#UC END# *4C6E60FE0011_467FCD4401BD_impl*
end;//TnsParentedTagNode.MakeNodeTag
constructor TnsParentedTagNode.Create(aType: Tk2Type;
const aNode: DocTagNodeType;
const aParent: Ik2Tag;
aState: TnsNodeStates);
//#UC START# *4C6E60C80037_467FCD4401BD_var*
//#UC END# *4C6E60C80037_467FCD4401BD_var*
begin
//#UC START# *4C6E60C80037_467FCD4401BD_impl*
Parent := aParent;
inherited Create(aType, aNode, aState);
//#UC END# *4C6E60C80037_467FCD4401BD_impl*
end;//TnsParentedTagNode.Create
end. |
{$IfNDef l3ThreadNotifier_imp}
// Модуль: "w:\common\components\rtl\Garant\L3\NOT_FINISHED_l3ThreadNotifier.imp.pas"
// Стереотип: "Impurity"
// Элемент модели: "l3ThreadNotifier" MUID: (48FD8E460027)
// Имя типа: "_l3ThreadNotifier_"
{$Define l3ThreadNotifier_imp}
type
Rl3DataHolder = class of Tl3DataHolder;
Tl3DataHolder = class(Tl3CacheableBase)
private
f_Intf: array of IUnknown;
f_Data: Pointer;
protected
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aData: Pointer;
aDataSize: Integer;
const anIntf: array of IUnknown); reintroduce;
public
property Data: Pointer
read f_Data;
end;//Tl3DataHolder
TnsOnChangeInOtherThreadMethod = procedure(aDataPtr: Tl3DataHolder) of object;
_l3ThreadNotifier_ = class(_l3ThreadNotifier_Parent_)
private
f_CustomChangeWindow: hWnd;
f_PostMessageCounter: Integer;
private
class function SynchronizeMessage: Longword;
procedure WndProc(var aMessage: TMessage);
protected
function HolderClass: Rl3DataHolder; virtual;
procedure InitFields; override;
procedure Cleanup; override;
procedure Synchronize(aOnChangeInOtherThread: TnsOnChangeInOtherThreadMethod;
aDataPtr: Pointer;
aDataSize: Integer;
const anIntf: array of IUnknown); overload;
procedure Synchronize(aOnChangeInOtherThread: TnsOnChangeInOtherThreadMethod;
aDataPtr: Pointer;
aDataSize: Integer); overload;
procedure Synchronize(aOnChangeInOtherThread: TnsOnChangeInOtherThreadMethod;
aDataPtr: Tl3DataHolder = nil); overload;
end;//_l3ThreadNotifier_
{$Else l3ThreadNotifier_imp}
{$IfNDef l3ThreadNotifier_imp_impl}
{$Define l3ThreadNotifier_imp_impl}
constructor Tl3DataHolder.Create(aData: Pointer;
aDataSize: Integer;
const anIntf: array of IUnknown);
//#UC START# *48FD94F00280_48FD94080208_var*
//#UC END# *48FD94F00280_48FD94080208_var*
begin
//#UC START# *48FD94F00280_48FD94080208_impl*
!!! Needs to be implemented !!!
//#UC END# *48FD94F00280_48FD94080208_impl*
end;//Tl3DataHolder.Create
procedure Tl3DataHolder.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_48FD94080208_var*
//#UC END# *479731C50290_48FD94080208_var*
begin
//#UC START# *479731C50290_48FD94080208_impl*
!!! Needs to be implemented !!!
//#UC END# *479731C50290_48FD94080208_impl*
end;//Tl3DataHolder.Cleanup
function _l3ThreadNotifier_.HolderClass: Rl3DataHolder;
//#UC START# *48FD9562004C_48FD8E460027_var*
//#UC END# *48FD9562004C_48FD8E460027_var*
begin
//#UC START# *48FD9562004C_48FD8E460027_impl*
!!! Needs to be implemented !!!
//#UC END# *48FD9562004C_48FD8E460027_impl*
end;//_l3ThreadNotifier_.HolderClass
class function _l3ThreadNotifier_.SynchronizeMessage: Longword;
//#UC START# *48FD977D00E2_48FD8E460027_var*
//#UC END# *48FD977D00E2_48FD8E460027_var*
begin
//#UC START# *48FD977D00E2_48FD8E460027_impl*
!!! Needs to be implemented !!!
//#UC END# *48FD977D00E2_48FD8E460027_impl*
end;//_l3ThreadNotifier_.SynchronizeMessage
procedure _l3ThreadNotifier_.WndProc(var aMessage: TMessage);
//#UC START# *48FD978F02C0_48FD8E460027_var*
//#UC END# *48FD978F02C0_48FD8E460027_var*
begin
//#UC START# *48FD978F02C0_48FD8E460027_impl*
!!! Needs to be implemented !!!
//#UC END# *48FD978F02C0_48FD8E460027_impl*
end;//_l3ThreadNotifier_.WndProc
procedure _l3ThreadNotifier_.InitFields;
//#UC START# *48FD97AF03AF_48FD8E460027_var*
//#UC END# *48FD97AF03AF_48FD8E460027_var*
begin
//#UC START# *48FD97AF03AF_48FD8E460027_impl*
!!! Needs to be implemented !!!
//#UC END# *48FD97AF03AF_48FD8E460027_impl*
end;//_l3ThreadNotifier_.InitFields
procedure _l3ThreadNotifier_.Cleanup;
//#UC START# *48FD97BC0335_48FD8E460027_var*
//#UC END# *48FD97BC0335_48FD8E460027_var*
begin
//#UC START# *48FD97BC0335_48FD8E460027_impl*
!!! Needs to be implemented !!!
//#UC END# *48FD97BC0335_48FD8E460027_impl*
end;//_l3ThreadNotifier_.Cleanup
procedure _l3ThreadNotifier_.Synchronize(aOnChangeInOtherThread: TnsOnChangeInOtherThreadMethod;
aDataPtr: Pointer;
aDataSize: Integer;
const anIntf: array of IUnknown);
//#UC START# *48FD98230314_48FD8E460027_var*
//#UC END# *48FD98230314_48FD8E460027_var*
begin
//#UC START# *48FD98230314_48FD8E460027_impl*
!!! Needs to be implemented !!!
//#UC END# *48FD98230314_48FD8E460027_impl*
end;//_l3ThreadNotifier_.Synchronize
procedure _l3ThreadNotifier_.Synchronize(aOnChangeInOtherThread: TnsOnChangeInOtherThreadMethod;
aDataPtr: Pointer;
aDataSize: Integer);
//#UC START# *48FD989D02FB_48FD8E460027_var*
//#UC END# *48FD989D02FB_48FD8E460027_var*
begin
//#UC START# *48FD989D02FB_48FD8E460027_impl*
!!! Needs to be implemented !!!
//#UC END# *48FD989D02FB_48FD8E460027_impl*
end;//_l3ThreadNotifier_.Synchronize
procedure _l3ThreadNotifier_.Synchronize(aOnChangeInOtherThread: TnsOnChangeInOtherThreadMethod;
aDataPtr: Tl3DataHolder = nil);
//#UC START# *48FD98BB0289_48FD8E460027_var*
//#UC END# *48FD98BB0289_48FD8E460027_var*
begin
//#UC START# *48FD98BB0289_48FD8E460027_impl*
!!! Needs to be implemented !!!
//#UC END# *48FD98BB0289_48FD8E460027_impl*
end;//_l3ThreadNotifier_.Synchronize
{$EndIf l3ThreadNotifier_imp_impl}
{$EndIf l3ThreadNotifier_imp}
|
unit DAO.ItensManutencao;
interface
uses DAO.base, Model.ItensManutencao, Generics.Collections, System.Classes;
type
TItensManutencaoDAO = class(TDAO)
public
function Insert(aItens: Model.ItensManutencao.TItensManutencao): Boolean;
function Update(aItens: Model.ItensManutencao.TItensManutencao): Boolean;
function Delete(sFiltro: String): Boolean;
function FindItem(sFiltro: String): TObjectList<Model.ItensManutencao.TItensManutencao>;
end;
CONST
TABLENAME = 'tbitensmanutencao';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TItensManutencaoDAO.Insert(aItens: TItensManutencao): Boolean;
var
sSQL: String;
begin
Result := False;
aItens.ID := GetKeyValue(TABLENAME, 'ID_ITEM');
sSQL := 'INSERT INTO ' + TABLENAME + ' ' +
'(ID_ITEM, DES_ITEM, ID_INSUMO, DES_LOG) ' +
'VALUES ' +
'(:ID, :DESCRICAO, :INSUMO, :LOG);';
Connection.ExecSQL(sSQL,[aItens.ID, aItens.Descricao, aItens.Insumo, aItens.Log],[ftInteger, ftString, ftInteger,
ftString]);
Result := True;
end;
function TItensManutencaoDAO.Update(aItens: TItensManutencao): Boolean;
var
sSQL: String;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'DES_ITEM = :DESCRICAO, ID_INSUMO = :INSUMO, DES_LOG = :LOG WHERE ID_ITEM = :ID;';
Connection.ExecSQL(sSQL,[aItens.Descricao, aItens.Insumo, aItens.Log, aItens.ID],[ftString, ftInteger, ftString,
ftInteger]);
Result := True;
end;
function TItensManutencaoDAO.Delete(sFiltro: string): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + ' ';
if not sFiltro.IsEmpty then
begin
sSQl := sSQL + sFiltro;
end
else
begin
Exit;
end;
Result := True;
end;
function TItensManutencaoDAO.FindItem(sFiltro: string): TObjectList<TItensManutencao>;
var
FDQuery: TFDQuery;
Extratos: TObjectList<TItensManutencao>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if not sFiltro.IsEmpty then
begin
FDQuery.SQL.Add(sFiltro);
end;
FDQuery.Open();
Extratos := TObjectList<TItensManutencao>.Create();
while not FDQuery.Eof do
begin
Extratos.Add(TItensManutencao.Create(FDQuery.FieldByName('ID_ITEM').AsInteger,
FDQuery.FieldByName('DES_ITEM').AsString, FDQuery.FieldByName('ID_INSUMO').AsInteger,
FDQuery.FieldByName('DES_LOG').AsString));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := Extratos;
end;
end.
|
UNIT MATH;
INTERFACE
function Signe(x:real):integer;
function Diraczero(x:integer):integer;
function Puissance(x,y:real):real;
function Puis_entiere(x,y:integer):longint;
function Factorielle(n:word):word;
IMPLEMENTATION
{*******************************************************}
FUNCTION SIGNE(x:real):integer;
{*******************************************************}
begin
if x=0 then signe:=0 else
if x>0 then signe:=1 else signe:=-1;
end;
{*******************************************************}
FUNCTION DIRACZERO(x:integer):integer;
{*******************************************************}
begin
if x=0 then diraczero:=1 else diraczero:=0;
end;
{*******************************************************}
FUNCTION PUISSANCE(x,y:real):real;
{*******************************************************}
begin
if x=0 then
if y=0 then puissance:=1
else puissance:=0
else
if x>0 then puissance:=exp(y*ln(x))
else
if odd(round(y)) then puissance:=SIGNE(x)*exp(y*ln(abs(x)))
else puissance:=-SIGNE(x)*exp(y*ln(abs(x)));
end;
{*******************************************************}
FUNCTION PUIS_ENTIERE(x,y:integer):longint;
{*******************************************************}
var i,ii:longint;
begin
i:=1;
for ii:=1 to y do i:=i*x;
puis_entiere:=i;
end;
{*******************************************************}
FUNCTION FACTORIELLE(n:word):word;
{*******************************************************}
label boucle;
begin
asm
mov cx,n;
mov ax,1h;
boucle:
mul cx;
loop boucle;
mov n,ax
end;
factorielle:=n;
end;
end. |
unit AddRouteDestinationsOptimallyUnit;
interface
uses SysUtils, BaseOptimizationExampleUnit;
type
TAddRouteDestinationsOptimally = class(TBaseOptimizationExample)
public
function Execute(RouteId: String): TArray<integer>;
end;
implementation
uses
AddressUnit, CommonTypesUnit;
function TAddRouteDestinationsOptimally.Execute(RouteId: String): TArray<integer>;
var
Addresses: TAddressesArray;
OptimalPosition: boolean;
ErrorString: String;
AddressIds: TStringArray;
i: integer;
begin
SetLength(Addresses, 2);
try
Addresses[0] := TAddress.Create(
'146 Bill Johnson Rd NE Milledgeville GA 31061',
33.143526, -83.240354, 0);
Addresses[1] := TAddress.Create(
'222 Blake Cir Milledgeville GA 31061',
33.177852, -83.263535, 0);
OptimalPosition := True;
Result := Route4MeManager.Route.AddAddresses(
RouteId, Addresses, OptimalPosition, ErrorString);
WriteLn('');
if (Length(Result) > 0) then
begin
WriteLn('AddRouteDestinations executed successfully');
SetLength(AddressIds, Length(Result));
for i := 0 to Length(Result) - 1 do
AddressIds[i] := IntToStr(Result[i]);
WriteLn(Format('Destination IDs: %s', [String.Join(' ', AddressIds)]));
end
else
WriteLn(Format('AddRouteDestinations error: "%s"', [errorString]));
finally
for i := Length(Addresses) - 1 downto 0 do
FreeAndNil(Addresses[i]);
end;
end;
end.
|
unit LIB.Raytrace.Geometry;
interface //#################################################################### ■
uses LUX, LUX.D1, LUX.D3, LUX.Matrix.L4,
LUX.Raytrace, LUX.Raytrace.Geometry,
LIB.Raytrace;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMyGeometry
TMyGeometry = class( TRayGeometry )
private
protected
_Radius :Single;
///// アクセス
function GetLocalAABB :TSingleArea3D; override;
///// メソッド
procedure _RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea ); override;
public
constructor Create; override;
destructor Destroy; override;
///// プロパティ
property Radius :Single read _Radius write _Radius;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses System.SysUtils, System.Math;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMyGeometry
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
/////////////////////////////////////////////////////////////////////// アクセス
function TMyGeometry.GetLocalAABB :TSingleArea3D;
begin
Result := TSingleArea3D.Create( -_Radius, -_Radius, -_Radius,
+_Radius, +_Radius, +_Radius );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// メソッド
procedure TMyGeometry._RayCast( var LocalRay_:TRayRay; var LocalHit_:TRayHit; const Len_:TSingleArea );
var
A, B, C, D, D2, T0, T1 :Single;
begin
with LocalRay_.Ray do
begin
A := Vec.Siz2;
B := DotProduct( Pos, Vec );
C := Pos.Siz2 - Pow2( _Radius );
end;
D := Pow2( B ) - A * C;
if D > 0 then
begin
D2 := Roo2( D );
T1 := ( -B + D2 ) / A;
if T1 > 0 then
begin
T0 := ( -B - D2 ) / A;
with LocalRay_ do
begin
if T0 > 0 then Len := T0
else Len := T1;
end;
with LocalHit_ do
begin
Obj := Self;
Nor := LocalHit_.Pos.Unitor;
end;
end;
end;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TMyGeometry.Create;
begin
inherited;
Radius := 1;
end;
destructor TMyGeometry.Destroy;
begin
inherited;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■ |
(************************************************************************)
unit utils;
(*======================================================================*)
interface
(*======================================================================*)
uses crt, dos;
(*======================================================================*)
(******** global const, type, vars are declared here *******************)
(*======================================================================*)
var
x1, y1, x2, y2 : byte;
gsingleBorder : boolean;
(*======================================================================*)
function IsMono:boolean;
function process0:char;
function SpecFive : string;
Function ConvertString(astring : string): single;
function RemoveBlanks( astring: string): string;
function LoCase(ch: char):char;
function DosFile( fname: string; abyte:byte):boolean;
function MinDouble( val1, val2: double): double;
function MaxDouble( val1, val2: double): double;
function HalfAdjust(r : real; width, decimals : integer) : string;
function rounded(r : real; width, decimals : integer) : string;
function RoundToNearest(dvar :integer) : integer;
(************************************************************************)
procedure norm_video;
procedure rev_video;
procedure HideCursor;
procedure RestoreCursor;
procedure Flush_Kb_Buffer;
procedure DrawBorder( px1, py1, px2, py2:byte; single:boolean);
procedure sleep( ms: word );
procedure capitalize( var buffer: string);
procedure LowerCase( var buffer: string);
procedure UpperCase( var buffer: string);
procedure WidowPane;
procedure DeskTop;
procedure draw_screen;
(*======================================================================*)
implementation
(*======================================================================*)
function IsMono:boolean;
begin
if ((mem[$0040:$0010] and $30) = $30) then IsMono:=true
else begin
IsMono:=false;
end;
end;
(************************************************************************)
(* returns char from keyboard buffer *)
(* if none available returns NULL *)
function process0:char;
var
inchar:char;
begin
if (keypressed) then begin
inchar:=readkey;
if (inchar=#0) then inchar:=readkey;
end
else inchar:= chr(0); (* return NULL char *)
process0:= inchar;
end;
(*************************************************************************)
function SpecFive: string;
(** Writes the string below to destination WP document ****)
var
string1 : string;
string2 : string;
begin
string1 := 'The submitted sample displayed significant variation';
string2 := ' in individual specimen test values';
SpecFive := string1+string2;
end;
Function ConvertString(astring : string): single;
(****************************************************************)
(******* Converts string to its numeric representation *******)
(****************************************************************)
var strvalue: single;
code: integer;
begin
val(astring,strvalue,code);
if code <> 0 then
WriteLn('Error at position: ', code);
ConvertString := strvalue;
end;
(****************************************************************)
function removeBlanks( astring: string): string;
var i: byte;
begin
while ( pos( ' ',astring) <>0 ) do begin
i:=pos( ' ', astring );
delete( astring, i, 1 );
end;
removeBlanks:= astring;
end;
(***********************************************************************)
function LoCase(ch: char):char;
begin
if ch in ['A'..'Z'] then locase:= chr( ord(ch) + 32)
else locase:= ch;
end;
(***************************************************************************)
(* searches for dosfile given fname *)
function DosFile( fname: string; abyte:byte):boolean;
var
sr : searchrec;
i : byte;
begin
for i:=1 to length( fname) do fname[i]:=upcase( fname[i]);
findfirst( fname, abyte, sr);
if (doserror=0) then DosFile:=true
else if (doserror=18) then DosFile:=false
else if (doserror=3) then DosFile:=false;
end;
(*************************************************************************)
procedure norm_video;
begin
textcolor( LIGHTGRAY); textbackground(BLACK);
end;
(************************************************************************)
procedure rev_video;
begin
textcolor(BLACK); textbackground(LIGHTGRAY);
end;
(************************************************************************)
procedure HideCursor;
var
regs: registers;
begin
with regs do begin
ah := $01;
ch := $20;
cl := $00;
end;
intr($10, regs );
end;
(************************************************************************)
procedure RestoreCursor;
var
reg:registers;
mono_system:boolean;
begin
reg.Ah:= $01;
if mono_system then begin
reg.Ch:= $0c;
reg.Cl:= $0d;
end
else begin
reg.Ch:= $06;
reg.Cl:=$07;
end;
intr($10,reg);
end;
(************************************************************************)
(* removes keys from the buffer that are waiting to be read *)
procedure flush_kb_buffer;
var
ch:char;
begin
while (keypressed) do ch:=readkey;
end;
(************************************************************************)
procedure drawBorder( px1,py1,px2,py2:byte; single:boolean);
const
boxchar:array[1..2,1..6] of char=((#218,#196,#191,#179,#192,#217),
(#201,#205,#187,#186,#200,#188));
var
b,i : byte;
begin
x1:= px1; x2:= px2;
y1:= py1; y2:= py2;
gSingleBorder:= single;
if single=TRUE then b:=1 (* sets border index *)
else if single=FALSE then b:=2;
TextColor(white);
gotoxy(x1,y1);
write(boxchar[b,1]); (* draws upper left corner *)
for i:=1 to ((x2-x1)-1) do begin
gotoxy(x1+ i ,y1);
write(boxchar[b,2]); (* draw the top *)
end;
gotoxy(x2,y1); (* draw uper right corner *)
write(boxchar[b,3]);
for i:=(y1+1) to (y2 - 1) do begin (* draw sides *)
gotoxy(x1,i);
write(boxchar[b,4]);
gotoxy(x2,i);
write(boxchar[b,4]);
end;
gotoxy(x1,y2);
write(boxchar[b,5]); (* draws lower left corner *)
for i:= 1 to ((x2-x1) -1) do begin
gotoxy(x1+i,y2);
write(boxchar[b,2]); (* draws bottom *)
end;
gotoxy(x2,y2);
write(boxchar[b,6]); TextColor(14);
end;
(************************************************************************)
procedure sleep( ms: word );
var x, y: byte;
begin
x:=wherex; y:=wherey;
writeln;
write('Wait... (', ms div 1000, ' Seconds)');
delay( ms);
gotoxy( 1, wherey);
clreol; (* clear last message line *)
gotoxy( x, y);
end;
(************************************************************************)
procedure capitalize( var buffer: string);
var
i: byte;
begin
for i:=1 to length(buffer) do buffer[i]:=upcase( buffer[i] );
end;
(************************************************************************)
procedure lowerCase( var buffer: string);
var
i: byte;
begin
for i:=1 to length(buffer) do buffer[i]:=locase( buffer[i] );
end;
(************************************************************************)
procedure UpperCase( var buffer: string);
var
i: byte;
begin
for i:=1 to length(buffer) do buffer[i]:=upcase( buffer[i] );
end;
(************************************************************************)
procedure WidowPane;
begin
window( x1+1, y1+1, x2-1, y2-1 );
end;
(***************************************************************************)
procedure DeskTop;
begin
window( 1, 1, 80, 25 );
clrscr;
x1:=2; y1:=1; x2:=79; y2:=25; gSingleBorder:=TRUE;
drawBorder( x1, y1, x2, y2, gSingleBorder);
gotoxy( 70, y2);
write( 'ESC-Exit');
window( x1+1, y1+1, x2-1, y2-1 );
end;
(*************************************************************************)
procedure draw_screen;
begin
clrscr;
gotoxy( 22, 13);
write('Press ESCape key to quit program...');
end;
(***************************************************************************)
function MinDouble( val1, val2: double): double;
begin
if (val1 < val2) then MinDouble:= val1
else MinDouble:= val2;
end;
(***************************************************************************)
function MaxDouble( val1, val2: double): double;
begin
if (val1 > val2) then MaxDouble:= val1
else MaxDouble:= val2;
end;
(***************************************************************************)
function HalfAdjust(r : real; width, decimals : integer) : string;
{ always round up on "5" }
var
temp : string;
half : real;
begin
case decimals of
0 : half := 0.5;
1 : half := 0.05;
2 : half := 0.005;
3 : half := 0.0005;
4 : half := 0.00005;
5 : half := 0.000005;
6 : half := 0.0000005;
7 : half := 0.00000005;
8 : half := 0.000000005;
9 : half := 0.0000000005;
10 : half := 0.00000000005;
11 : half := 0.000000000005;
else half := 0.0;
end;
if r<0 then
r := r-half
else
r := r+half;
str(r:0:11,temp);
if decimals=0 then
dec(temp[0],12)
else
dec(temp[0],11-decimals);
dec(width,length(temp));
if width>0 then begin
move(temp[1],temp[succ(width)],length(temp));
inc(temp[0],width);
fillchar(temp[1],width,' ')
end;
HalfAdjust := temp
end; {HalfAdjust}
(***************************************************************************)
function rounded(r : real; width, decimals : integer) : string;
{ round on "5" to an even value }
var
temp : string;
point : integer;
i : integer;
label 1;
begin
str(r:0:11,temp);
insert('0',temp,1);
point := length(temp)-11;
delete(temp,point,1);
if temp[point+decimals]='5' then
if odd(ord(temp[point+decimals-1])) then
for i := pred(point) downto 1 do
if temp[i]='9' then
temp[i] := '0'
else
begin
inc(temp[i]);
{break}
goto 1
end;
1: insert('.',temp,point);
if temp[1]='0' then
delete(temp,1,1);
if decimals=0 then
dec(temp[0],12)
else
dec(temp[0],11-decimals);
dec(width,length(temp));
if width>0 then begin
move(temp[1],temp[succ(width)],length(temp));
inc(temp[0],width);
fillchar(temp[1],width,' ')
end;
rounded := temp
end; {rounded}
function RoundToNearest(dvar : integer) : integer;
begin
Case dvar of
0..200 : RoundToNearest:=10;
200..999 : RoundToNearest:=25;
1000..4999 : RoundToNearest:=50;
5000..32000 : RoundToNearest:=100;
end;
end;
(*======================================================================*)
end. (* Unit *)
(************************************************************************)
|
{
$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 10/26/2004 9:55:58 PM JPMugaas
Updated refs.
Rev 1.3 7/31/2004 6:55:06 AM JPMugaas
New properties.
Rev 1.2 4/19/2004 5:06:12 PM JPMugaas
Class rework Kudzu wanted.
Rev 1.1 10/19/2003 3:36:20 PM DSiders
Added localization comments.
Rev 1.0 10/1/2003 12:55:22 AM JPMugaas
New FTP list parsers.
}
unit IdFTPListParseStercomUnixEnt;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase, IdFTPListTypes;
type
TIdSterCommEntUxFTPListItem = class(TIdOwnerFTPListItem)
protected
FFlagsProt : String;
FProtIndicator : String;
public
property FlagsProt : String read FFlagsProt write FFlagsProt;
property ProtIndicator : String read FProtIndicator write FProtIndicator;
end;
TIdFTPLPSterComEntBase = class(TIdFTPListBaseHeader)
protected
class function IsFooter(const AData : String): Boolean; override;
end;
TIdFTPLPSterCommEntUx = class(TIdFTPLPSterComEntBase)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
TIdSterCommEntUxNSFTPListItem = class(TIdOwnerFTPListItem);
TIdFTPLPSterCommEntUxNS = class(TIdFTPLPSterComEntBase)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class procedure StripPlus(var VString : String);
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
TIdSterCommEntUxRootFTPListItem = class(TIdMinimalFTPListItem);
TIdFTPLPSterCommEntUxRoot = class(TIdFTPLPSterComEntBase)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function IsFooter(const AData : String): Boolean; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
const
STIRCOMUNIX = 'CONNECT:Enterprise for UNIX'; {do not localize}
STIRCOMUNIXNS = STIRCOMUNIX + '$$'; {do not localize} //dir with $$ parameter
STIRCOMUNIXROOT = STIRCOMUNIX + ' ROOT'; {do not localize} //root dir for mailboxes
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseStercomUnixEnt"'*)
implementation
uses
IdGlobal, IdFTPCommon, IdGlobalProtocols,
SysUtils;
{ TIdFTPLPSterCommEntUx }
class function TIdFTPLPSterCommEntUx.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
var
LBuf : String;
function IsSterPrefix(const AStr : String) : Boolean;
begin
Result := False;
if Length(AStr) = 13 then
begin
if IsValidSterCommFlags(Copy(AStr, 1, 10)) then begin
Result := IsValidSterCommProt(Copy(AStr, 11, 3));
end;
end;
end;
begin
{
Expect a pattern such as this:
These are from the The Jakarta Project test cases CVS code. Only
the string constants from a test case are used.
-C--E-----FTP B QUA1I1 18128 41 Aug 12 13:56 QUADTEST
-C--E-----FTP A QUA1I1 18128 41 Aug 12 13:56 QUADTEST2
From:
http://www.mail-archive.com/commons-user@jakarta.apache.org/msg03809.html
Person noted this was from a "CONNECT:Enterprise for UNIX 1.3.01 Secure FTP"
The first few letters (ARTE, AR) are flags associated with each file.
The two sets of numbers represent batch IDs and file sizes.
-ARTE-----TCP A cbeodm 22159 629629 Aug 06 05:47 PSEUDOFILENAME
-ARTE-----TCP A cbeodm 4915 1031030 Aug 06 09:12 PSEUDOFILENAME
-ARTE-----TCP A cbeodm 16941 321321 Aug 06 12:41 PSEUDOFILENAME
-ARTE-----TCP A cbeodm 7872 3010007 Aug 07 02:31 PSEUDOFILENAME
-ARTE-----TCP A cbeodm 2737 564564 Aug 07 05:54 PSEUDOFILENAME
-ARTE-----TCP A cbeodm 14879 991991 Aug 07 08:57 PSEUDOFILENAME
-ARTE-----TCP A cbeodm 5183 332332 Aug 07 12:37 PSEUDOFILENAME
-AR-------TCP A cbeodm 5252 2767765 Aug 08 01:49 PSEUDOFILENAME
-AR-------TCP A cbeodm 15502 537537 Aug 08 05:44 PSEUDOFILENAME
-AR-------TCP A cbeodm 13444 1428427 Aug 08 09:01 PSEUDOFILENAME
-SR--M------- A steve 1 369 Sep 02 13:47 <<ACTIVITY LOG>>
}
Result := False;
if AListing.Count > 0 then
begin
LBuf := AListing[0];
Result := IsSterPrefix(Fetch(LBuf));
if Result then begin
Result := IsValidSterCommProt(Fetch(LBuf));
end;
end;
end;
class function TIdFTPLPSterCommEntUx.GetIdent: String;
begin
Result := STIRCOMUNIX;
end;
class function TIdFTPLPSterCommEntUx.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdSterCommEntUxFTPListItem.Create(AOwner);
end;
class function TIdFTPLPSterCommEntUx.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var
LBuf, LTmp : String;
wYear, wMonth, wDay, wHour, wMin, wSec : Word;
LI : TIdSterCommEntUxFTPListItem;
begin
LI := AItem as TIdSterCommEntUxFTPListItem;
DecodeDate(Now, wYear, wMonth, wDay);
wHour := 0;
wMin := 0;
wSec := 0;
LBuf := AItem.Data;
//flags and protocol
LBuf := TrimLeft(LBuf);
LI.FlagsProt := Fetch(LBuf);
//protocol indicator
LBuf := TrimLeft(LBuf);
LI.ProtIndicator := Fetch(LBuf);
// owner
LI.OwnerName := Fetch(LBuf);
//file size
repeat
LBuf := TrimLeft(LBuf);
LTmp := Fetch(LBuf);
if LBuf <> '' then
begin
if IsNumeric(LBuf[1]) then begin
//we found the month
Break;
end;
LI.Size := IndyStrToInt(LTmp, 0);
end;
until False;
//month
wMonth := StrToMonth(LTmp);
//day
LBuf := TrimLeft(LBuf);
LTmp := Fetch(LBuf);
wDay := IndyStrToInt(LTmp, wDay);
//year or time
LBuf := TrimLeft(LBuf);
LTmp := Fetch(LBuf);
if IndyPos(':', LTmp) > 0 then {do not localize}
begin
//year is missing - just get the time
wYear := AddMissingYear(wDay, wMonth);
wHour := IndyStrToInt(Fetch(LTmp, ':'), 0); {do not localize}
wMin := IndyStrToInt(Fetch(LTmp, ':'), 0); {do not localize}
end else
begin
wYear := IndyStrToInt(LTmp, wYear);
end;
LI.FileName := LBuf;
LI.ModifiedDate := EncodeDate(wYear, wMonth, wDay);
LI.ModifiedDate := LI.ModifiedDate + EncodeTime(wHour, wMin, wSec, 0);
Result := True;
end;
{ TIdFTPLPSterCommEntUxNS }
class function TIdFTPLPSterCommEntUxNS.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
var
LBuf, LBuf2 : String;
{
The list format is this:
solution 00003444 00910368 <c3957010.zip.001> 030924-1636 A R TCP BIN
solution 00000439 02688275 <C3959009.zip> 030925-0940 A RT TCP BIN
solution 00003603 00124000 <POST1202.P1182069.L>+ 030925-1548 A RT TCP BIN
solution 00003604 00265440 <POST1202.P1182069.O>+ 030925-1548 A RT TCP BIN
solution 00003605 00030960 <POST1202.P1182069.S>+ 030925-1548 A RT TCP BIN
solution 00003606 00007341 <POST1202.P1182069.R>+ 030925-1548 A RT TCP ASC
solution 00002755 06669222 <3963338.fix.000> 030926-0811 A R TCP BIN
solution 00003048 00007341 <POST1202.P1182069.R>+ 030926-0832 A RT TCP ASC
solution 00002137 00427516 <c3957010.zip.002> 030926-1001 A RT TCP BIN
solution 00002372 00007612 <C3964415.zip> 030926-1038 A RT TCP BIN
solution 00003043 06669222 <3963338.fix.001> 030926-1236 A RT TCP BIN
solution 00001079 57267791 <c3958462.zip> 030926-1301 A RT TCP BIN
solution 00003188 06669222 <c3963338.zip> 030926-1312 A R TCP BIN
solution 00002172 120072022 <c3967287.zi> 030929-1059 A RT TCP BIN
Total Number of batches listed: 14
}
function IsValidDate(const ADate : String) : Boolean;
var
LLBuf, LDate : String;
LDay, LMonth, LHour, LMin : Word;
begin
LLBuf := ADate;
LDate := Fetch(LLBuf, '-'); {do not localize}
LMonth := IndyStrToInt(Copy(LDate, 3, 2), 0);
Result := (LMonth > 0) and (LMonth < 13);
if not Result then begin
Exit;
end;
LDay := IndyStrToInt(Copy(LDate, 5, 2), 0);
Result := (LDay > 0) and (LDay < 32);
if not Result then begin
Exit;
end;
LHour := IndyStrToInt(Copy(LLBuf, 1, 2), 0);
Result := (LHour > 0) and (LHour < 25);
if not Result then begin
Exit;
end;
LMin := IndyStrToInt(Copy(LLBuf, 3, 2), 0);
Result := (LMin < 60);
end;
begin
Result := False;
if AListing.Count > 0 then
begin
if IsFooter(AListing[0]) then
begin
Result := True;
Exit;
end;
if IndyPos('>', AListing[0]) > 0 then {do not localize}
begin
LBuf := AListing[0];
Fetch(LBuf, '>'); {do not localize}
StripPlus(LBuf);
LBuf := TrimLeft(LBuf);
if IsValidDate(Fetch(LBuf)) then
begin
LBuf2 := RightStr(LBuf, 7);
if IsValidSterCommProt(Copy(LBuf2, 1, 3)) then
begin
if IsValidSterCommData(Copy(LBuf2, 5, 3)) then
begin
LBuf := Copy(LBuf, 1, Length(LBuf)-7);
Result := IsValidSterCommFlags(LBuf);
end;
end;
end;
end;
end;
end;
class function TIdFTPLPSterCommEntUxNS.GetIdent: String;
begin
Result := STIRCOMUNIXNS;
end;
class function TIdFTPLPSterCommEntUxNS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdSterCommEntUxNSFTPListItem.Create(AOwner);
end;
class function TIdFTPLPSterCommEntUxNS.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var
LBuf : String;
LYear, LMonth, LDay : Word;
LHour, LMin : Word;
LI : TIdSterCommEntUxNSFTPListItem;
begin
{
The format is like this:
ACME 00000020 00000152 <test batch> 990926-1431 CD FTP ASC
ACME 00000019 00000152 <test batch> 990926-1435 CD FTP ASC
ACME 00000014 00000606 <cmuadded locally> 990929-1306 A R TCP BIN
ACME 00000013 00000606 <orders> 990929-1308 A R TCP EBC
ACME 00000004 00000606 <orders> 990929-1309 A R TCP ASC
Total Number of batches listed: 5
Note that this was taken from:
"Connect:Enterprise® UNIX Remote User’s Guide Version 2.1 " Copyright
1999, 2002, 2003 Sterling Commerce, Inc.
}
LI := AItem as TIdSterCommEntUxNSFTPListItem;
// owner
LBuf := AItem.Data;
LI.OwnerName := Fetch(LBuf);
//8 digit batch - skip
LBuf := TrimLeft(LBuf);
Fetch(LBuf);
//size
LBuf := TrimLeft(LBuf);
LI.Size := IndyStrToInt64(Fetch(LBuf), 0);
//filename
Fetch(LBuf, '<'); {do not localize}
LI.FileName := Fetch(LBuf, '>'); {do not localize}
StripPlus(LBuf);
//date
LBuf := TrimLeft(LBuf);
//since we aren't going to do anything else after the date,
//we should process as a string;
//Date format: 990926-1431
LBuf := Copy(LBuf, 1, 11);
LYear := IndyStrToInt(Copy(LBuf, 1, 2), 0);
LYear := Y2Year(LYear);
LMonth := IndyStrToInt(Copy(LBuf, 3, 2), 0);
LDay := IndyStrToInt(Copy(LBuf, 5, 2), 0);
// got the date
StripPlus(LBuf);
Fetch(LBuf, '-'); {do not localize}
LI.ModifiedDate := EncodeDate(LYear, LMonth, LDay);
LHour := IndyStrToInt(Copy(LBuf, 1, 2), 0);
LMin := IndyStrToInt(Copy(LBuf, 3, 2), 0);
LI.ModifiedDate := LI.ModifiedDate + EncodeTime(LHour, LMin, 0, 0);
Result := True;
end;
class procedure TIdFTPLPSterCommEntUxNS.StripPlus(var VString: String);
begin
if TextStartsWith(VString, '+') then begin {do not localize}
IdDelete(VString, 1, 1);
end;
end;
{ TIdFTPLPSterCommEntUxRoot }
class function TIdFTPLPSterCommEntUxRoot.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
var
LBuf : String;
begin
Result := False;
if AListing.Count > 0 then
begin
if IsFooter(AListing[0]) then begin
Result := True;
Exit;
end;
//The line may be something like this:
//d - - - - - - - steve
//123456789012345678901234567890
// 1 2 3
//do not check for the "-" in case its something we don't know
//about. Checking for "d" should be okay as a mailbox listed here
//is probably like a dir
LBuf := AListing[0];
if (Length(LBuf) >= 26) and
(LBuf[1] = 'd') and {do not localize}
(Copy(LBuf, 2, 3) = ' ') and {do not localize}
(LBuf[5] <> ' ') and {do not localize}
(Copy(LBuf, 6, 3) = ' ') and {do not localize}
(LBuf[9] <> ' ') and {do not localize}
(Copy(LBuf, 10, 3) = ' ') and {do not localize}
(LBuf[13] <> ' ') and {do not localize}
(Copy(LBuf, 14, 2) = ' ') and {do not localize}
(LBuf[16] <> ' ') and {do not localize}
(Copy(LBuf, 17, 2) = ' ') and {do not localize}
(LBuf[19] <> ' ') and {do not localize}
(Copy(LBuf, 20, 2) = ' ') and {do not localize}
(LBuf[22] <> ' ') and {do not localize}
(Copy(LBuf, 23, 2) = ' ') and {do not localize}
(LBuf[25] <> ' ') and {do not localize}
(LBuf[26] = ' ') then {do not localize}
begin
Result := True;
end;
end;
end;
class function TIdFTPLPSterCommEntUxRoot.GetIdent: String;
begin
Result := STIRCOMUNIXROOT;
end;
class function TIdFTPLPSterCommEntUxRoot.IsFooter(const AData: String): Boolean;
begin
Result := TextStartsWith(AData, 'Total number of Mailboxes = '); {do not localize}
end;
class function TIdFTPLPSterCommEntUxRoot.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdSterCommEntUxRootFTPListItem.Create(AOwner);
end;
class function TIdFTPLPSterCommEntUxRoot.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
begin
AItem.FileName := Copy(AItem.Data, 27, MaxInt);
//mailboxes are just subdirs
AItem.ItemType := ditDirectory;
Result := True;
end;
{ TIdFTPLPSterComEntBase }
class function TIdFTPLPSterComEntBase.IsFooter(const AData: String): Boolean;
var
LData : String;
begin
LData := UpperCase(AData);
Result := (IndyPos('TOTAL NUMBER OF ', LData) > 0) and {do not localize}
(IndyPos(' BATCH', LData) > 0) and {do not localize}
(IndyPos('LISTED:', LData) > 0); {do not localize}
end;
initialization
RegisterFTPListParser(TIdFTPLPSterCommEntUx);
RegisterFTPListParser(TIdFTPLPSterCommEntUxNS);
RegisterFTPListParser(TIdFTPLPSterCommEntUxRoot);
finalization
UnRegisterFTPListParser(TIdFTPLPSterCommEntUx);
UnRegisterFTPListParser(TIdFTPLPSterCommEntUxNS);
UnRegisterFTPListParser(TIdFTPLPSterCommEntUxRoot);
end.
|
//
// opus.h header binding for the Free Pascal Compiler aka FPC
//
// Binaries and demos available at http://www.djmaster.com/
//
(* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited
Written by Jean-Marc Valin and Koen Vos *)
(*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
(**
* @file opus.h
* @brief Opus reference implementation API
*)
unit opus;
{$mode objfpc}{$H+}
interface
uses
ctypes;
const
LIB_OPUS = 'libopus-0.dll';
// #ifndef OPUS_H
// #define OPUS_H
{$include opus_types.inc}
{$include opus_defines.inc}
// #ifdef __cplusplus
// extern "C" {
// #endif
(**
* @mainpage Opus
*
* The Opus codec is designed for interactive speech and audio transmission over the Internet.
* It is designed by the IETF Codec Working Group and incorporates technology from
* Skype's SILK codec and Xiph.Org's CELT codec.
*
* The Opus codec is designed to handle a wide range of interactive audio applications,
* including Voice over IP, videoconferencing, in-game chat, and even remote live music
* performances. It can scale from low bit-rate narrowband speech to very high quality
* stereo music. Its main features are:
* @li Sampling rates from 8 to 48 kHz
* @li Bit-rates from 6 kb/s to 510 kb/s
* @li Support for both constant bit-rate (CBR) and variable bit-rate (VBR)
* @li Audio bandwidth from narrowband to full-band
* @li Support for speech and music
* @li Support for mono and stereo
* @li Support for multichannel (up to 255 channels)
* @li Frame sizes from 2.5 ms to 60 ms
* @li Good loss robustness and packet loss concealment (PLC)
* @li Floating point and fixed-point implementation
*
* Documentation sections:
* @li @ref opus_encoder
* @li @ref opus_decoder
* @li @ref opus_repacketizer
* @li @ref opus_multistream
* @li @ref opus_libinfo
* @li @ref opus_custom
*)
(** @defgroup opus_encoder Opus Encoder
* @{
*
* @brief This page describes the process and functions used to encode Opus.
*
* Since Opus is a stateful codec, the encoding process starts with creating an encoder
* state. This can be done with:
*
* @code
* int error;
* OpusEncoder *enc;
* enc = opus_encoder_create(Fs, channels, application, &error);
* @endcode
*
* From this point, @c enc can be used for encoding an audio stream. An encoder state
* @b must @b not be used for more than one stream at the same time. Similarly, the encoder
* state @b must @b not be re-initialized for each frame.
*
* While opus_encoder_create() allocates memory for the state, it's also possible
* to initialize pre-allocated memory:
*
* @code
* int size;
* int error;
* OpusEncoder *enc;
* size = opus_encoder_get_size(channels);
* enc = malloc(size);
* error = opus_encoder_init(enc, Fs, channels, application);
* @endcode
*
* where opus_encoder_get_size() returns the required size for the encoder state. Note that
* future versions of this code may change the size, so no assuptions should be made about it.
*
* The encoder state is always continuous in memory and only a shallow copy is sufficient
* to copy it (e.g. memcpy())
*
* It is possible to change some of the encoder's settings using the opus_encoder_ctl()
* interface. All these settings already default to the recommended value, so they should
* only be changed when necessary. The most common settings one may want to change are:
*
* @code
* opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate));
* opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complexity));
* opus_encoder_ctl(enc, OPUS_SET_SIGNAL(signal_type));
* @endcode
*
* where
*
* @arg bitrate is in bits per second (b/s)
* @arg complexity is a value from 1 to 10, where 1 is the lowest complexity and 10 is the highest
* @arg signal_type is either OPUS_AUTO (default), OPUS_SIGNAL_VOICE, or OPUS_SIGNAL_MUSIC
*
* See @ref opus_encoderctls and @ref opus_genericctls for a complete list of parameters that can be set or queried. Most parameters can be set or changed at any time during a stream.
*
* To encode a frame, opus_encode() or opus_encode_float() must be called with exactly one frame (2.5, 5, 10, 20, 40 or 60 ms) of audio data:
* @code
* len = opus_encode(enc, audio_frame, frame_size, packet, max_packet);
* @endcode
*
* where
* <ul>
* <li>audio_frame is the audio data in opus_int16 (or float for opus_encode_float())</li>
* <li>frame_size is the duration of the frame in samples (per channel)</li>
* <li>packet is the byte array to which the compressed data is written</li>
* <li>max_packet is the maximum number of bytes that can be written in the packet (4000 bytes is recommended).
* Do not use max_packet to control VBR target bitrate, instead use the #OPUS_SET_BITRATE CTL.</li>
* </ul>
*
* opus_encode() and opus_encode_float() return the number of bytes actually written to the packet.
* The return value <b>can be negative</b>, which indicates that an error has occurred. If the return value
* is 2 bytes or less, then the packet does not need to be transmitted (DTX).
*
* Once the encoder state if no longer needed, it can be destroyed with
*
* @code
* opus_encoder_destroy(enc);
* @endcode
*
* If the encoder was created with opus_encoder_init() rather than opus_encoder_create(),
* then no action is required aside from potentially freeing the memory that was manually
* allocated for it (calling free(enc) for the example above)
*
*)
(** Opus encoder state.
* This contains the complete state of an Opus encoder.
* It is position independent and can be freely copied.
* @see opus_encoder_create,opus_encoder_init
*)
type
POpusEncoder = ^OpusEncoder;
OpusEncoder = record
end;
(** Gets the size of an <code>OpusEncoder</code> structure.
* @param[in] channels <tt>int</tt>: Number of channels.
* This must be 1 or 2.
* @returns The size in bytes.
*)
function opus_encoder_get_size(channels: cint): cint; cdecl; external LIB_OPUS;
(**
*)
(** Allocates and initializes an encoder state.
* There are three coding modes:
*
* @ref OPUS_APPLICATION_VOIP gives best quality at a given bitrate for voice
* signals. It enhances the input signal by high-pass filtering and
* emphasizing formants and harmonics. Optionally it includes in-band
* forward error correction to protect against packet loss. Use this
* mode for typical VoIP applications. Because of the enhancement,
* even at high bitrates the output may sound different from the input.
*
* @ref OPUS_APPLICATION_AUDIO gives best quality at a given bitrate for most
* non-voice signals like music. Use this mode for music and mixed
* (music/voice) content, broadcast, and applications requiring less
* than 15 ms of coding delay.
*
* @ref OPUS_APPLICATION_RESTRICTED_LOWDELAY configures low-delay mode that
* disables the speech-optimized mode in exchange for slightly reduced delay.
* This mode can only be set on an newly initialized or freshly reset encoder
* because it changes the codec delay.
*
* This is useful when the caller knows that the speech-optimized modes will not be needed (use with caution).
* @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz)
* This must be one of 8000, 12000, 16000,
* 24000, or 48000.
* @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal
* @param [in] application <tt>int</tt>: Coding mode (@ref OPUS_APPLICATION_VOIP/@ref OPUS_APPLICATION_AUDIO/@ref OPUS_APPLICATION_RESTRICTED_LOWDELAY)
* @param [out] error <tt>int*</tt>: @ref opus_errorcodes
* @note Regardless of the sampling rate and number channels selected, the Opus encoder
* can switch to a lower audio bandwidth or number of channels if the bitrate
* selected is too low. This also means that it is safe to always use 48 kHz stereo input
* and let the encoder optimize the encoding.
*)
function opus_encoder_create(Fs: opus_int32; channels: cint; application: cint; error: pcint): POpusEncoder; cdecl; external LIB_OPUS;
(** Initializes a previously allocated encoder state
* The memory pointed to by st must be at least the size returned by opus_encoder_get_size().
* This is intended for applications which use their own allocator instead of malloc.
* @see opus_encoder_create(),opus_encoder_get_size()
* To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.
* @param [in] st <tt>OpusEncoder*</tt>: Encoder state
* @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz)
* This must be one of 8000, 12000, 16000,
* 24000, or 48000.
* @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal
* @param [in] application <tt>int</tt>: Coding mode (OPUS_APPLICATION_VOIP/OPUS_APPLICATION_AUDIO/OPUS_APPLICATION_RESTRICTED_LOWDELAY)
* @retval #OPUS_OK Success or @ref opus_errorcodes
*)
function opus_encoder_init(st: POpusEncoder; Fs: opus_int32; channels: cint; application: cint): cint; cdecl; external LIB_OPUS;
(** Encodes an Opus frame.
* @param [in] st <tt>OpusEncoder*</tt>: Encoder state
* @param [in] pcm <tt>opus_int16*</tt>: Input signal (interleaved if 2 channels). length is frame_size*channels*sizeof(opus_int16)
* @param [in] frame_size <tt>int</tt>: Number of samples per channel in the
* input signal.
* This must be an Opus frame size for
* the encoder's sampling rate.
* For example, at 48 kHz the permitted
* values are 120, 240, 480, 960, 1920,
* and 2880.
* Passing in a duration of less than
* 10 ms (480 samples at 48 kHz) will
* prevent the encoder from using the LPC
* or hybrid modes.
* @param [out] data <tt>unsigned char*</tt>: Output payload.
* This must contain storage for at
* least \a max_data_bytes.
* @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated
* memory for the output
* payload. This may be
* used to impose an upper limit on
* the instant bitrate, but should
* not be used as the only bitrate
* control. Use #OPUS_SET_BITRATE to
* control the bitrate.
* @returns The length of the encoded packet (in bytes) on success or a
* negative error code (see @ref opus_errorcodes) on failure.
*)
function opus_encode(st: POpusEncoder; const pcm: Popus_int16; frame_size: cint; data: pcuchar; max_data_bytes: opus_int32): opus_int32; cdecl; external LIB_OPUS;
(** Encodes an Opus frame from floating point input.
* @param [in] st <tt>OpusEncoder*</tt>: Encoder state
* @param [in] pcm <tt>float*</tt>: Input in float format (interleaved if 2 channels), with a normal range of +/-1.0.
* Samples with a range beyond +/-1.0 are supported but will
* be clipped by decoders using the integer API and should
* only be used if it is known that the far end supports
* extended dynamic range.
* length is frame_size*channels*sizeof(float)
* @param [in] frame_size <tt>int</tt>: Number of samples per channel in the
* input signal.
* This must be an Opus frame size for
* the encoder's sampling rate.
* For example, at 48 kHz the permitted
* values are 120, 240, 480, 960, 1920,
* and 2880.
* Passing in a duration of less than
* 10 ms (480 samples at 48 kHz) will
* prevent the encoder from using the LPC
* or hybrid modes.
* @param [out] data <tt>unsigned char*</tt>: Output payload.
* This must contain storage for at
* least \a max_data_bytes.
* @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated
* memory for the output
* payload. This may be
* used to impose an upper limit on
* the instant bitrate, but should
* not be used as the only bitrate
* control. Use #OPUS_SET_BITRATE to
* control the bitrate.
* @returns The length of the encoded packet (in bytes) on success or a
* negative error code (see @ref opus_errorcodes) on failure.
*)
function opus_encode_float(st: POpusEncoder; const pcm: pcfloat; frame_size: cint; data: pcuchar; max_data_bytes: opus_int32): opus_int32; cdecl; external LIB_OPUS;
(** Frees an <code>OpusEncoder</code> allocated by opus_encoder_create().
* @param[in] st <tt>OpusEncoder*</tt>: State to be freed.
*)
procedure opus_encoder_destroy(st: POpusEncoder); cdecl; external LIB_OPUS;
(** Perform a CTL function on an Opus encoder.
*
* Generally the request and subsequent arguments are generated
* by a convenience macro.
* @param st <tt>OpusEncoder*</tt>: Encoder state.
* @param request This and all remaining parameters should be replaced by one
* of the convenience macros in @ref opus_genericctls or
* @ref opus_encoderctls.
* @see opus_genericctls
* @see opus_encoderctls
*)
function opus_encoder_ctl(st: POpusEncoder; request: cint; args: array of const): cint; cdecl; external LIB_OPUS;
(**@}*)
(** @defgroup opus_decoder Opus Decoder
* @{
*
* @brief This page describes the process and functions used to decode Opus.
*
* The decoding process also starts with creating a decoder
* state. This can be done with:
* @code
* int error;
* OpusDecoder *dec;
* dec = opus_decoder_create(Fs, channels, &error);
* @endcode
* where
* @li Fs is the sampling rate and must be 8000, 12000, 16000, 24000, or 48000
* @li channels is the number of channels (1 or 2)
* @li error will hold the error code in case of failure (or #OPUS_OK on success)
* @li the return value is a newly created decoder state to be used for decoding
*
* While opus_decoder_create() allocates memory for the state, it's also possible
* to initialize pre-allocated memory:
* @code
* int size;
* int error;
* OpusDecoder *dec;
* size = opus_decoder_get_size(channels);
* dec = malloc(size);
* error = opus_decoder_init(dec, Fs, channels);
* @endcode
* where opus_decoder_get_size() returns the required size for the decoder state. Note that
* future versions of this code may change the size, so no assuptions should be made about it.
*
* The decoder state is always continuous in memory and only a shallow copy is sufficient
* to copy it (e.g. memcpy())
*
* To decode a frame, opus_decode() or opus_decode_float() must be called with a packet of compressed audio data:
* @code
* frame_size = opus_decode(dec, packet, len, decoded, max_size, 0);
* @endcode
* where
*
* @li packet is the byte array containing the compressed data
* @li len is the exact number of bytes contained in the packet
* @li decoded is the decoded audio data in opus_int16 (or float for opus_decode_float())
* @li max_size is the max duration of the frame in samples (per channel) that can fit into the decoded_frame array
*
* opus_decode() and opus_decode_float() return the number of samples (per channel) decoded from the packet.
* If that value is negative, then an error has occurred. This can occur if the packet is corrupted or if the audio
* buffer is too small to hold the decoded audio.
*
* Opus is a stateful codec with overlapping blocks and as a result Opus
* packets are not coded independently of each other. Packets must be
* passed into the decoder serially and in the correct order for a correct
* decode. Lost packets can be replaced with loss concealment by calling
* the decoder with a null pointer and zero length for the missing packet.
*
* A single codec state may only be accessed from a single thread at
* a time and any required locking must be performed by the caller. Separate
* streams must be decoded with separate decoder states and can be decoded
* in parallel unless the library was compiled with NONTHREADSAFE_PSEUDOSTACK
* defined.
*
*)
(** Opus decoder state.
* This contains the complete state of an Opus decoder.
* It is position independent and can be freely copied.
* @see opus_decoder_create,opus_decoder_init
*)
type
POpusDecoder = ^OpusDecoder;
OpusDecoder = record
end;
(** Gets the size of an <code>OpusDecoder</code> structure.
* @param [in] channels <tt>int</tt>: Number of channels.
* This must be 1 or 2.
* @returns The size in bytes.
*)
function opus_decoder_get_size(channels: cint): cint; cdecl; external LIB_OPUS;
(** Allocates and initializes a decoder state.
* @param [in] Fs <tt>opus_int32</tt>: Sample rate to decode at (Hz).
* This must be one of 8000, 12000, 16000,
* 24000, or 48000.
* @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode
* @param [out] error <tt>int*</tt>: #OPUS_OK Success or @ref opus_errorcodes
*
* Internally Opus stores data at 48000 Hz, so that should be the default
* value for Fs. However, the decoder can efficiently decode to buffers
* at 8, 12, 16, and 24 kHz so if for some reason the caller cannot use
* data at the full sample rate, or knows the compressed data doesn't
* use the full frequency range, it can request decoding at a reduced
* rate. Likewise, the decoder is capable of filling in either mono or
* interleaved stereo pcm buffers, at the caller's request.
*)
function opus_decoder_create(Fs: opus_int32; channels: cint; error: pcint): POpusDecoder; cdecl; external LIB_OPUS;
(** Initializes a previously allocated decoder state.
* The state must be at least the size returned by opus_decoder_get_size().
* This is intended for applications which use their own allocator instead of malloc. @see opus_decoder_create,opus_decoder_get_size
* To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.
* @param [in] st <tt>OpusDecoder*</tt>: Decoder state.
* @param [in] Fs <tt>opus_int32</tt>: Sampling rate to decode to (Hz).
* This must be one of 8000, 12000, 16000,
* 24000, or 48000.
* @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode
* @retval #OPUS_OK Success or @ref opus_errorcodes
*)
function opus_decoder_init(st: POpusDecoder; Fs: opus_int32; channels: cint): cint; cdecl; external LIB_OPUS;
(** Decode an Opus packet.
* @param [in] st <tt>OpusDecoder*</tt>: Decoder state
* @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss
* @param [in] len <tt>opus_int32</tt>: Number of bytes in payload*
* @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length
* is frame_size*channels*sizeof(opus_int16)
* @param [in] frame_size Number of samples per channel of available space in \a pcm.
* If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will
* not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1),
* then frame_size needs to be exactly the duration of audio that is missing, otherwise the
* decoder will not be in the optimal state to decode the next incoming packet. For the PLC and
* FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms.
* @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be
* decoded. If no such data is available, the frame is decoded as if it were lost.
* @returns Number of decoded samples or @ref opus_errorcodes
*)
function opus_decode(st: POpusDecoder; const data: pcuchar; len: opus_int32; pcm: Popus_int16; frame_size: cint; decode_fec: cint): cint; cdecl; external LIB_OPUS;
(** Decode an Opus packet with floating point output.
* @param [in] st <tt>OpusDecoder*</tt>: Decoder state
* @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss
* @param [in] len <tt>opus_int32</tt>: Number of bytes in payload
* @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length
* is frame_size*channels*sizeof(float)
* @param [in] frame_size Number of samples per channel of available space in \a pcm.
* If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will
* not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1),
* then frame_size needs to be exactly the duration of audio that is missing, otherwise the
* decoder will not be in the optimal state to decode the next incoming packet. For the PLC and
* FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms.
* @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be
* decoded. If no such data is available the frame is decoded as if it were lost.
* @returns Number of decoded samples or @ref opus_errorcodes
*)
function opus_decode_float(st: POpusDecoder; const data: pcuchar; len: opus_int32; pcm: pcfloat; frame_size: cint; decode_fec: cint): cint; cdecl; external LIB_OPUS;
(** Perform a CTL function on an Opus decoder.
*
* Generally the request and subsequent arguments are generated
* by a convenience macro.
* @param st <tt>OpusDecoder*</tt>: Decoder state.
* @param request This and all remaining parameters should be replaced by one
* of the convenience macros in @ref opus_genericctls or
* @ref opus_decoderctls.
* @see opus_genericctls
* @see opus_decoderctls
*)
function opus_decoder_ctl(st: POpusDecoder; request: cint; args: array of const): cint; cdecl; external LIB_OPUS;
(** Frees an <code>OpusDecoder</code> allocated by opus_decoder_create().
* @param[in] st <tt>OpusDecoder*</tt>: State to be freed.
*)
procedure opus_decoder_destroy(st: POpusDecoder); cdecl; external LIB_OPUS;
(** Parse an opus packet into one or more frames.
* Opus_decode will perform this operation internally so most applications do
* not need to use this function.
* This function does not copy the frames, the returned pointers are pointers into
* the input packet.
* @param [in] data <tt>char*</tt>: Opus packet to be parsed
* @param [in] len <tt>opus_int32</tt>: size of data
* @param [out] out_toc <tt>char*</tt>: TOC pointer
* @param [out] frames <tt>char*[48]</tt> encapsulated frames
* @param [out] size <tt>opus_int16[48]</tt> sizes of the encapsulated frames
* @param [out] payload_offset <tt>int*</tt>: returns the position of the payload within the packet (in bytes)
* @returns number of frames
*)
function opus_packet_parse(const data: pcuchar; len: opus_int32; out_toc: pcuchar; const frames: array of pcuchar; size: array of opus_int16; payload_offset: pcint): cint; cdecl; external LIB_OPUS;
(** Gets the bandwidth of an Opus packet.
* @param [in] data <tt>char*</tt>: Opus packet
* @retval OPUS_BANDWIDTH_NARROWBAND Narrowband (4kHz bandpass)
* @retval OPUS_BANDWIDTH_MEDIUMBAND Mediumband (6kHz bandpass)
* @retval OPUS_BANDWIDTH_WIDEBAND Wideband (8kHz bandpass)
* @retval OPUS_BANDWIDTH_SUPERWIDEBAND Superwideband (12kHz bandpass)
* @retval OPUS_BANDWIDTH_FULLBAND Fullband (20kHz bandpass)
* @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
*)
function opus_packet_get_bandwidth(const data: pcuchar): cint; cdecl; external LIB_OPUS;
(** Gets the number of samples per frame from an Opus packet.
* @param [in] data <tt>char*</tt>: Opus packet.
* This must contain at least one byte of
* data.
* @param [in] Fs <tt>opus_int32</tt>: Sampling rate in Hz.
* This must be a multiple of 400, or
* inaccurate results will be returned.
* @returns Number of samples per frame.
*)
function opus_packet_get_samples_per_frame(const data: pcuchar; Fs: opus_int32): cint; cdecl; external LIB_OPUS;
(** Gets the number of channels from an Opus packet.
* @param [in] data <tt>char*</tt>: Opus packet
* @returns Number of channels
* @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
*)
function opus_packet_get_nb_channels(const data: pcuchar): cint; cdecl; external LIB_OPUS;
(** Gets the number of frames in an Opus packet.
* @param [in] packet <tt>char*</tt>: Opus packet
* @param [in] len <tt>opus_int32</tt>: Length of packet
* @returns Number of frames
* @retval OPUS_BAD_ARG Insufficient data was passed to the function
* @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
*)
function opus_packet_get_nb_frames(const packet: array of cuchar; len: opus_int32): cint; cdecl; external LIB_OPUS;
(** Gets the number of samples of an Opus packet.
* @param [in] packet <tt>char*</tt>: Opus packet
* @param [in] len <tt>opus_int32</tt>: Length of packet
* @param [in] Fs <tt>opus_int32</tt>: Sampling rate in Hz.
* This must be a multiple of 400, or
* inaccurate results will be returned.
* @returns Number of samples
* @retval OPUS_BAD_ARG Insufficient data was passed to the function
* @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
*)
function opus_packet_get_nb_samples(const packet: array of cuchar; len: opus_int32; Fs: opus_int32): cint; cdecl; external LIB_OPUS;
(** Gets the number of samples of an Opus packet.
* @param [in] dec <tt>OpusDecoder*</tt>: Decoder state
* @param [in] packet <tt>char*</tt>: Opus packet
* @param [in] len <tt>opus_int32</tt>: Length of packet
* @returns Number of samples
* @retval OPUS_BAD_ARG Insufficient data was passed to the function
* @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
*)
function opus_decoder_get_nb_samples(const dec: POpusDecoder; const packet: array of cuchar; len: opus_int32): cint; cdecl; external LIB_OPUS;
(** Applies soft-clipping to bring a float signal within the [-1,1] range. If
* the signal is already in that range, nothing is done. If there are values
* outside of [-1,1], then the signal is clipped as smoothly as possible to
* both fit in the range and avoid creating excessive distortion in the
* process.
* @param [in,out] pcm <tt>float*</tt>: Input PCM and modified PCM
* @param [in] frame_size <tt>int</tt> Number of samples per channel to process
* @param [in] channels <tt>int</tt>: Number of channels
* @param [in,out] softclip_mem <tt>float*</tt>: State memory for the soft clipping process (one float per channel, initialized to zero)
*)
procedure opus_pcm_soft_clip(pcm: pcfloat; frame_size: cint; channels: cint; softclip_mem: pcfloat); cdecl; external LIB_OPUS;
(**@}*)
(** @defgroup opus_repacketizer Repacketizer
* @{
*
* The repacketizer can be used to merge multiple Opus packets into a single
* packet or alternatively to split Opus packets that have previously been
* merged. Splitting valid Opus packets is always guaranteed to succeed,
* whereas merging valid packets only succeeds if all frames have the same
* mode, bandwidth, and frame size, and when the total duration of the merged
* packet is no more than 120 ms. The 120 ms limit comes from the
* specification and limits decoder memory requirements at a point where
* framing overhead becomes negligible.
*
* The repacketizer currently only operates on elementary Opus
* streams. It will not manipualte multistream packets successfully, except in
* the degenerate case where they consist of data from a single stream.
*
* The repacketizing process starts with creating a repacketizer state, either
* by calling opus_repacketizer_create() or by allocating the memory yourself,
* e.g.,
* @code
* rp: POpusRepacketizer;
* rp = (OpusRepacketizer* )malloc(opus_repacketizer_get_size());
* if (rp != NULL)
* opus_repacketizer_init(rp);
* @endcode
*
* Then the application should submit packets with opus_repacketizer_cat(),
* extract new packets with opus_repacketizer_out() or
* opus_repacketizer_out_range(), and then reset the state for the next set of
* input packets via opus_repacketizer_init().
*
* For example, to split a sequence of packets into individual frames:
* @code
* data: pcuchar;
* int len;
* while (get_next_packet(&data, &len))
* {
* unsigned char out[1276];
* opus_int32 out_len;
* int nb_frames;
* int err;
* int i;
* err = opus_repacketizer_cat(rp, data, len);
* if (err != OPUS_OK)
* {
* release_packet(data);
* return err;
* }
* nb_frames = opus_repacketizer_get_nb_frames(rp);
* for (i = 0; i < nb_frames; i++)
* {
* out_len = opus_repacketizer_out_range(rp, i, i+1, out, sizeof(out));
* if (out_len < 0)
* {
* release_packet(data);
* return (int)out_len;
* }
* output_next_packet(out, out_len);
* }
* opus_repacketizer_init(rp);
* release_packet(data);
* }
* @endcode
*
* Alternatively, to combine a sequence of frames into packets that each
* contain up to <code>TARGET_DURATION_MS</code> milliseconds of data:
* @code
* // The maximum number of packets with duration TARGET_DURATION_MS occurs
* // when the frame size is 2.5 ms, for a total of (TARGET_DURATION_MS*2/5)
* // packets.
* data: pcuchar[(TARGET_DURATION_MS*2/5)+1];
* len: opus_int32[(TARGET_DURATION_MS*2/5)+1];
* int nb_packets;
* unsigned char out[1277*(TARGET_DURATION_MS*2/2)];
* opus_int32 out_len;
* int prev_toc;
* nb_packets = 0;
* while (get_next_packet(data+nb_packets, len+nb_packets))
* {
* int nb_frames;
* int err;
* nb_frames = opus_packet_get_nb_frames(data[nb_packets], len[nb_packets]);
* if (nb_frames < 1)
* {
* release_packets(data, nb_packets+1);
* return nb_frames;
* }
* nb_frames += opus_repacketizer_get_nb_frames(rp);
* // If adding the next packet would exceed our target, or it has an
* // incompatible TOC sequence, output the packets we already have before
* // submitting it.
* // N.B., The nb_packets > 0 check ensures we've submitted at least one
* // packet since the last call to opus_repacketizer_init(). Otherwise a
* // single packet longer than TARGET_DURATION_MS would cause us to try to
* // output an (invalid) empty packet. It also ensures that prev_toc has
* // been set to a valid value. Additionally, len[nb_packets] > 0 is
* // guaranteed by the call to opus_packet_get_nb_frames() above, so the
* // reference to data[nb_packets][0] should be valid.
* if (nb_packets > 0 && (
* ((prev_toc & 0xFC) != (data[nb_packets][0] & 0xFC)) ||
* opus_packet_get_samples_per_frame(data[nb_packets], 48000)*nb_frames >
* TARGET_DURATION_MS*48))
* {
* out_len = opus_repacketizer_out(rp, out, sizeof(out));
* if (out_len < 0)
* {
* release_packets(data, nb_packets+1);
* return (int)out_len;
* }
* output_next_packet(out, out_len);
* opus_repacketizer_init(rp);
* release_packets(data, nb_packets);
* data[0] = data[nb_packets];
* len[0] = len[nb_packets];
* nb_packets = 0;
* }
* err = opus_repacketizer_cat(rp, data[nb_packets], len[nb_packets]);
* if (err != OPUS_OK)
* {
* release_packets(data, nb_packets+1);
* return err;
* }
* prev_toc = data[nb_packets][0];
* nb_packets++;
* }
* // Output the final, partial packet.
* if (nb_packets > 0)
* {
* out_len = opus_repacketizer_out(rp, out, sizeof(out));
* release_packets(data, nb_packets);
* if (out_len < 0)
* return (int)out_len;
* output_next_packet(out, out_len);
* }
* @endcode
*
* An alternate way of merging packets is to simply call opus_repacketizer_cat()
* unconditionally until it fails. At that point, the merged packet can be
* obtained with opus_repacketizer_out() and the input packet for which
* opus_repacketizer_cat() needs to be re-added to a newly reinitialized
* repacketizer state.
*)
type
POpusRepacketizer = ^OpusRepacketizer;
OpusRepacketizer = record
end;
(** Gets the size of an <code>OpusRepacketizer</code> structure.
* @returns The size in bytes.
*)
function opus_repacketizer_get_size(): cint; cdecl; external LIB_OPUS;
(** (Re)initializes a previously allocated repacketizer state.
* The state must be at least the size returned by opus_repacketizer_get_size().
* This can be used for applications which use their own allocator instead of
* malloc().
* It must also be called to reset the queue of packets waiting to be
* repacketized, which is necessary if the maximum packet duration of 120 ms
* is reached or if you wish to submit packets with a different Opus
* configuration (coding mode, audio bandwidth, frame size, or channel count).
* Failure to do so will prevent a new packet from being added with
* opus_repacketizer_cat().
* @see opus_repacketizer_create
* @see opus_repacketizer_get_size
* @see opus_repacketizer_cat
* @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to
* (re)initialize.
* @returns A pointer to the same repacketizer state that was passed in.
*)
function opus_repacketizer_init(rp: POpusRepacketizer): POpusRepacketizer; cdecl; external LIB_OPUS;
(** Allocates memory and initializes the new repacketizer with
* opus_repacketizer_init().
*)
function opus_repacketizer_create(): POpusRepacketizer; cdecl; external LIB_OPUS;
(** Frees an <code>OpusRepacketizer</code> allocated by
* opus_repacketizer_create().
* @param[in] rp <tt>OpusRepacketizer*</tt>: State to be freed.
*)
procedure opus_repacketizer_destroy(rp: POpusRepacketizer); cdecl; external LIB_OPUS;
(** Add a packet to the current repacketizer state.
* This packet must match the configuration of any packets already submitted
* for repacketization since the last call to opus_repacketizer_init().
* This means that it must have the same coding mode, audio bandwidth, frame
* size, and channel count.
* This can be checked in advance by examining the top 6 bits of the first
* byte of the packet, and ensuring they match the top 6 bits of the first
* byte of any previously submitted packet.
* The total duration of audio in the repacketizer state also must not exceed
* 120 ms, the maximum duration of a single packet, after adding this packet.
*
* The contents of the current repacketizer state can be extracted into new
* packets using opus_repacketizer_out() or opus_repacketizer_out_range().
*
* In order to add a packet with a different configuration or to add more
* audio beyond 120 ms, you must clear the repacketizer state by calling
* opus_repacketizer_init().
* If a packet is too large to add to the current repacketizer state, no part
* of it is added, even if it contains multiple frames, some of which might
* fit.
* If you wish to be able to add parts of such packets, you should first use
* another repacketizer to split the packet into pieces and add them
* individually.
* @see opus_repacketizer_out_range
* @see opus_repacketizer_out
* @see opus_repacketizer_init
* @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to which to
* add the packet.
* @param[in] data <tt>const unsigned char*</tt>: The packet data.
* The application must ensure
* this pointer remains valid
* until the next call to
* opus_repacketizer_init() or
* opus_repacketizer_destroy().
* @param len <tt>opus_int32</tt>: The number of bytes in the packet data.
* @returns An error code indicating whether or not the operation succeeded.
* @retval #OPUS_OK The packet's contents have been added to the repacketizer
* state.
* @retval #OPUS_INVALID_PACKET The packet did not have a valid TOC sequence,
* the packet's TOC sequence was not compatible
* with previously submitted packets (because
* the coding mode, audio bandwidth, frame size,
* or channel count did not match), or adding
* this packet would increase the total amount of
* audio stored in the repacketizer state to more
* than 120 ms.
*)
function opus_repacketizer_cat(rp: POpusRepacketizer; const data: pcuchar; len: opus_int32): cint; cdecl; external LIB_OPUS;
(** Construct a new packet from data previously submitted to the repacketizer
* state via opus_repacketizer_cat().
* @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to
* construct the new packet.
* @param begin <tt>int</tt>: The index of the first frame in the current
* repacketizer state to include in the output.
* @param end <tt>int</tt>: One past the index of the last frame in the
* current repacketizer state to include in the
* output.
* @param[out] data <tt>const unsigned char*</tt>: The buffer in which to
* store the output packet.
* @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in
* the output buffer. In order to guarantee
* success, this should be at least
* <code>1276</code> for a single frame,
* or for multiple frames,
* <code>1277*(end-begin)</code>.
* However, <code>1*(end-begin)</code> plus
* the size of all packet data submitted to
* the repacketizer since the last call to
* opus_repacketizer_init() or
* opus_repacketizer_create() is also
* sufficient, and possibly much smaller.
* @returns The total size of the output packet on success, or an error code
* on failure.
* @retval #OPUS_BAD_ARG <code>[begin,end)</code> was an invalid range of
* frames (begin < 0, begin >= end, or end >
* opus_repacketizer_get_nb_frames()).
* @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the
* complete output packet.
*)
function opus_repacketizer_out_range(rp: POpusRepacketizer; begin_: cint; end_: cint; data: pcuchar; maxlen: opus_int32): opus_int32; cdecl; external LIB_OPUS;
(** Return the total number of frames contained in packet data submitted to
* the repacketizer state so far via opus_repacketizer_cat() since the last
* call to opus_repacketizer_init() or opus_repacketizer_create().
* This defines the valid range of packets that can be extracted with
* opus_repacketizer_out_range() or opus_repacketizer_out().
* @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state containing the
* frames.
* @returns The total number of frames contained in the packet data submitted
* to the repacketizer state.
*)
function opus_repacketizer_get_nb_frames(rp: POpusRepacketizer): cint; cdecl; external LIB_OPUS;
(** Construct a new packet from data previously submitted to the repacketizer
* state via opus_repacketizer_cat().
* This is a convenience routine that returns all the data submitted so far
* in a single packet.
* It is equivalent to calling
* @code
* opus_repacketizer_out_range(rp, 0, opus_repacketizer_get_nb_frames(rp),
* data, maxlen)
* @endcode
* @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to
* construct the new packet.
* @param[out] data <tt>const unsigned char*</tt>: The buffer in which to
* store the output packet.
* @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in
* the output buffer. In order to guarantee
* success, this should be at least
* <code>1277*opus_repacketizer_get_nb_frames(rp)</code>.
* However,
* <code>1*opus_repacketizer_get_nb_frames(rp)</code>
* plus the size of all packet data
* submitted to the repacketizer since the
* last call to opus_repacketizer_init() or
* opus_repacketizer_create() is also
* sufficient, and possibly much smaller.
* @returns The total size of the output packet on success, or an error code
* on failure.
* @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the
* complete output packet.
*)
function opus_repacketizer_out(rp: POpusRepacketizer; data: pcuchar; maxlen: opus_int32): opus_int32; cdecl; external LIB_OPUS;
(** Pads a given Opus packet to a larger size (possibly changing the TOC sequence).
* @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the
* packet to pad.
* @param len <tt>opus_int32</tt>: The size of the packet.
* This must be at least 1.
* @param new_len <tt>opus_int32</tt>: The desired size of the packet after padding.
* This must be at least as large as len.
* @returns an error code
* @retval #OPUS_OK \a on success.
* @retval #OPUS_BAD_ARG \a len was less than 1 or new_len was less than len.
* @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet.
*)
function opus_packet_pad(data: pcuchar; len: opus_int32; new_len: opus_int32): cint; cdecl; external LIB_OPUS;
(** Remove all padding from a given Opus packet and rewrite the TOC sequence to
* minimize space usage.
* @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the
* packet to strip.
* @param len <tt>opus_int32</tt>: The size of the packet.
* This must be at least 1.
* @returns The new size of the output packet on success, or an error code
* on failure.
* @retval #OPUS_BAD_ARG \a len was less than 1.
* @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet.
*)
function opus_packet_unpad(data: pcuchar; len: opus_int32): opus_int32; cdecl; external LIB_OPUS;
(** Pads a given Opus multi-stream packet to a larger size (possibly changing the TOC sequence).
* @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the
* packet to pad.
* @param len <tt>opus_int32</tt>: The size of the packet.
* This must be at least 1.
* @param new_len <tt>opus_int32</tt>: The desired size of the packet after padding.
* This must be at least 1.
* @param nb_streams <tt>opus_int32</tt>: The number of streams (not channels) in the packet.
* This must be at least as large as len.
* @returns an error code
* @retval #OPUS_OK \a on success.
* @retval #OPUS_BAD_ARG \a len was less than 1.
* @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet.
*)
function opus_multistream_packet_pad(data: pcuchar; len: opus_int32; new_len: opus_int32; nb_streams: cint): cint; cdecl; external LIB_OPUS;
(** Remove all padding from a given Opus multi-stream packet and rewrite the TOC sequence to
* minimize space usage.
* @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the
* packet to strip.
* @param len <tt>opus_int32</tt>: The size of the packet.
* This must be at least 1.
* @param nb_streams <tt>opus_int32</tt>: The number of streams (not channels) in the packet.
* This must be at least 1.
* @returns The new size of the output packet on success, or an error code
* on failure.
* @retval #OPUS_BAD_ARG \a len was less than 1 or new_len was less than len.
* @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet.
*)
function opus_multistream_packet_unpad(data: pcuchar; len: opus_int32; nb_streams: cint): opus_int32; cdecl; external LIB_OPUS;
(**@}*)
// #ifdef __cplusplus
// }
// #endif
// #endif (* OPUS_H *)
implementation
end.
|
unit fmuPrintOperations;
interface
uses
// VCL
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ComCtrls, ExtCtrls,
// This
untPages, untDriver, Spin;
type
{ TfmPrintOperations }
TfmPrintOperations = class(TPage)
grpFeed: TGroupBox;
lblStringQuantity: TLabel;
btnFeedDocument: TButton;
chbUseReceiptRibbon2: TCheckBox;
chbUseJournalRibbon2: TCheckBox;
btnContinuePrint: TButton;
seStringQuantity: TSpinEdit;
grpContinuePrint: TGroupBox;
grpTechTest: TGroupBox;
lblPeriod: TLabel;
btnStartTechTest: TButton;
btnStopTechTest: TButton;
sePeriod: TSpinEdit;
chkUseSlipDocument: TCheckBox;
grpCutCheck: TGroupBox;
lblCutType: TLabel;
cbCutType: TComboBox;
btnCutCheck: TButton;
procedure btnFeedDocumentClick(Sender: TObject);
procedure btnContinuePrintClick(Sender: TObject);
procedure btnStartTechTestClick(Sender: TObject);
procedure btnStopTechTestClick(Sender: TObject);
procedure btnCutCheckClick(Sender: TObject);
end;
implementation
{$R *.DFM}
{ TfmPrintOperations }
procedure TfmPrintOperations.btnFeedDocumentClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.UseReceiptRibbon := chbUseReceiptRibbon2.Checked;
Driver.UseJournalRibbon := chbUseJournalRibbon2.Checked;
Driver.UseSlipDocument := chkUseSlipDocument.Checked;
Driver.StringQuantity := seStringQuantity.Value;
Driver.FeedDocument;
finally
EnableButtons(True);
end;
end;
procedure TfmPrintOperations.btnContinuePrintClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.ContinuePrint;
finally
EnableButtons(True);
end;
end;
procedure TfmPrintOperations.btnStartTechTestClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.RunningPeriod := sePeriod.Value;
Driver.Test;
finally
EnableButtons(True);
end;
end;
procedure TfmPrintOperations.btnStopTechTestClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.InterruptTest;
finally
EnableButtons(True);
end;
end;
procedure TfmPrintOperations.btnCutCheckClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.CutType := cbCutType.ItemIndex = 1;
Driver.CutCheck;
finally
EnableButtons(True);
end;
end;
end.
|
unit streaming_class_lib;
(*
This unit makes work with Delphi streaming system much easier.
TStreamingClass is defined which should be base class instead of TComponent,
in case you want to easily save its contents to file/stream/string or
load them back. It defines easiest child/parent relation needed for streaming
system to work, that is: Parent is same as owner, children are owner's components.
*)
interface
uses Classes,sysutils,typInfo;
type
TStreamingClassSaveFormat=Integer;
TStreamConvertFunc = procedure (input,output: TStream);
TStreamingFormatEntry = record
ident: TStreamingClassSaveFormat;
signature: AnsiString;
name: string;
Filter: string;
convertToBinary: TStreamConvertFunc;
convertFromBinary: TStreamConvertFunc;
end;
PStreamingFormatEntry = ^TStreamingFormatEntry;
TstreamingClass=class(TComponent)
protected
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
function GetChildOwner: TComponent; override;
//converts other load formats to binary, if needed
class function GetStreamFormat(stream: TStream): PStreamingFormatEntry;
public
saveFormat: TStreamingClassSaveFormat;
//these constructors are easiest to use, but you should already know what class
//you're expecting to get.
//If you don't know which class you're loading, use class functions LoadComponent,
//and cast them accordingly.
constructor LoadFromStream(stream: TStream); virtual;//yup, it must be constructor,
constructor LoadFromFile(filename: string); virtual; //not a function or class function
constructor LoadFromString(const text: string);
class function LoadComponentFromStream(stream: TStream): TComponent;
class function LoadComponentFromString(const text: string): TComponent;
class function LoadComponentFromFile(const FileName: string): TComponent;
procedure Clear; virtual;
procedure SetDefaultProperties;
procedure Assign(source: TPersistent); override;
constructor Clone(source: TStreamingClass; owner: TComponent=nil);
class function CloneComponent(source: TStreamingClass; aowner: TComponent=nil): TComponent;
procedure SaveToStream(stream: TStream); virtual;
procedure SaveToFile(const filename: string); virtual;
function SaveToString: string;
function IsEqual(what: TStreamingClass): boolean; virtual;
function EqualsByAnyOtherName(what: TStreamingClass): boolean; virtual;
function FindOwner: TComponent; //finds ultimate owner
end;
EStreamingClassError = class (Exception);
TStreamingClassClass=class of TStreamingClass;
TSaveToFileProc = procedure (const filename: string) of object;
procedure SafeSaveToFile(saveProc: TSaveToFileProc; const filename: string);
procedure RegisterStreamingFormat(aFormatIdent: TStreamingClassSaveFormat;
aSignature: AnsiString; aName, aFilter: String;
aConvertToBinaryFunc, aConvertFromBinaryFunc: TStreamConvertFunc);
function GetStreamingFormatsCount: Integer;
function GetStreamingFormatEntry(ident: TStreamingClassSaveFormat):
PStreamingFormatEntry;
const sfBin = 0;
sfASCII = 1;
implementation
uses SyncObjs, Contnrs;
var gCriticalSection: TCriticalSection;
//TFiler operations are not thread-safe unfortunately
//it changes DecimalSeparator in the middle of operation
//It is possible to set DecimalSeparator to '.' at the beginning of your program
//and not to change it ever, using thread-safe routines with FormatSettings,
//then you can load/save several StreamingClasses simultaneously
gFormatList: TList;
resourcestring
BinaryFormatFilter = 'Binary file|*.dat';
AsciiFormatFilter = 'Text file|*.bin';
(*
General procedures
*)
function GetStreamingFormatsCount: Integer;
begin
Result:=gFormatList.Count;
end;
function GetStreamingFormatEntry(ident: TStreamingClassSaveFormat): PStreamingFormatEntry;
var i: Integer;
begin
for i:=0 to gFormatList.Count-1 do begin
Result:=gFormatList[i];
if Result.ident=ident then Exit;
end;
Result:=nil;
end;
procedure RegisterStreamingFormat(aFormatIdent: TStreamingClassSaveFormat;
aSignature: AnsiString; aName, aFilter: String;
aConvertToBinaryFunc, aConvertFromBinaryFunc: TStreamConvertFunc);
var Entry: PStreamingFormatEntry;
begin
Entry:=GetStreamingFormatEntry(aFormatIdent);
if Assigned(Entry) then
Raise EStreamingClassError.CreateFmt('Streaming format %d already registered',[aFormatIdent]);
New(Entry);
with Entry^ do begin
ident:=aFormatIdent;
signature:=aSignature;
name:=aName;
Filter:=aFilter;
convertToBinary:=aConvertToBinaryFunc;
convertFromBinary:=aConvertFromBinaryFunc;
end;
gFormatList.Add(Entry);
end;
function NameToSaveFormat(const Ident: string; var Int: Longint): Boolean;
var i: Integer;
entry: PStreamingFormatEntry;
begin
for i := 0 to gFormatList.Count-1 do begin
entry:=gFormatList[i];
if SameText(entry^.name,Ident) then begin
Result:=true;
Int:=entry^.ident;
Exit;
end;
end;
Result:=false;
end;
function SaveFormatToName(Int: LongInt; var Ident: string): Boolean;
var i: Integer;
entry: PStreamingFormatEntry;
begin
for i := 0 to gFormatList.Count-1 do begin
entry:=gFormatList[i];
if entry^.ident=Int then begin
Result:=true;
Ident:=entry^.name;
Exit;
end;
end;
Result:=false;
end;
//if file exists already, we rename it to .BAK at first, if successful,
//we delete it. In this fashion, any failure during saving document
//won't destroy it completely, we'll at least have original version
procedure SafeSaveToFile(saveProc: TSaveToFileProc; const filename: string);
var backupName: string;
begin
if FileExists(filename) then begin
BackupName := ChangeFileExt(FileName, '.BAK');
if not RenameFile(FileName,BackupName) then
Raise Exception.Create('couldn''t create BAK file, save procedure canceled');
//OK, backup is ready
try
saveProc(filename);
if not DeleteFile(BackUpName) then
Raise Exception.Create('couldn''t delete BAK file after saving');
except
if FileExists(FileName) then
DeleteFile(FileName);
RenameFile(BackupName,FileName);
//may be unsuccessful, then user will have to rename BAK file by hand
raise; //whatever exception stopped us from proper saving
end;
end
else
saveProc(fileName);
end;
//silly problem with DecimalSeparator
procedure ThreadSafeWriteComponent(stream: TStream; component: TComponent);
begin
gCriticalSection.Acquire;
try
stream.WriteComponent(component);
finally
gCriticalSection.Release;
end;
end;
function ThreadSafeReadComponent(stream: TStream; component: TComponent): TComponent;
begin
gCriticalSection.Acquire;
try
Result:=stream.ReadComponent(component);
finally
gCriticalSection.Release;
end;
end;
(*
TStreamingClass
*)
function TstreamingClass.GetChildOwner: TComponent;
begin
Result := self;
end;
procedure TstreamingClass.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
i : Integer;
begin
inherited;
for i := 0 to ComponentCount-1 do
if not (csSubComponent in Components[i].ComponentStyle) then
Proc( Components[i] );
end;
procedure TStreamingClass.SaveToStream(stream: TStream);
var
BinStream: TMemoryStream;
entry: PStreamingFormatEntry;
begin
entry:=GetStreamingFormatEntry(saveFormat);
if not Assigned(entry) then
Raise Exception.CreateFmt('Streaming format %d not registered',[saveFormat]);
if not Assigned(entry.convertFromBinary) then
ThreadSafeWriteComponent(stream,Self)
else begin
BinStream:=TMemoryStream.Create;
try
ThreadSafeWriteComponent(BinStream,self);
BinStream.Seek(0, soFromBeginning);
entry.convertFromBinary(BinStream,stream);
finally
BinStream.Free;
end;
end;
end;
procedure TstreamingClass.SaveToFile(const filename: string);
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(filename,fmCreate);
try
SaveToStream(FileStream);
finally
FileStream.Free;
end;
end;
function TstreamingClass.SaveToString: string;
var StrStream: TStringStream;
begin
StrStream:=TStringStream.Create(Result);
try
SaveToStream(StrStream);
finally
StrStream.Free;
end;
end;
class function TStreamingClass.GetStreamFormat(stream: Tstream): PStreamingFormatEntry;
var i: Integer;
s: AnsiString;
begin
for i:=0 to gFormatList.Count-1 do begin
Result:=gFormatList[i];
SetLength(s,Length(Result.signature));
stream.Read(s[1],Length(Result.signature));
stream.Seek(0,soFromBeginning);
if AnsiCompareText(s,Result.signature)=0 then Exit;
end;
Result:=nil;
end;
constructor TStreamingClass.LoadFromStream(stream: TStream);
var BinStream: TMemoryStream;
streamFormat: PStreamingFormatEntry;
begin
Create(nil);
streamFormat:=GetStreamFormat(stream);
if not Assigned(streamFormat) then
Raise EStreamingClassError.Create('Load from stream: unknown format of data');
if not Assigned(streamFormat.convertToBinary) then
ThreadSafeReadComponent(stream,self)
else begin
BinStream:=TMemoryStream.Create;
try
streamFormat.convertToBinary(stream,binStream);
binStream.Seek(0,soFromBeginning);
ThreadSafeReadComponent(BinStream,self);
finally
binStream.Free;
end;
end;
end;
constructor TstreamingClass.LoadFromFile(filename: string);
var fileStream: TFileStream;
begin
Create(nil);
fileStream:=TFileStream.Create(filename,fmOpenRead);
try
LoadFromStream(fileStream);
finally
fileStream.Free;
end;
end;
constructor TstreamingClass.LoadFromString(const text: string);
var StrStream: TStringStream;
begin
Create(nil);
StrStream:=TStringStream.Create(text);
try
LoadFromStream(strStream);
finally
StrStream.Free;
end;
end;
class function TStreamingClass.LoadComponentFromStream(stream: TStream): TComponent;
var BinStream: TMemoryStream;
StreamFormat: PStreamingFormatEntry;
begin
streamFormat:=GetStreamFormat(stream);
if not Assigned(streamFormat) then
Raise EStreamingClassError.Create('Load component from stream: unknown format of data');
if not Assigned(streamFormat.convertToBinary) then
Result:=ThreadSafeReadComponent(stream,nil)
else begin
BinStream:=TMemoryStream.Create;
try
streamFormat.convertToBinary(stream,binStream);
binStream.Seek(0,soFromBeginning);
Result:=ThreadSafeReadComponent(BinStream,nil);
finally
binStream.Free;
end;
end;
end;
class function TStreamingClass.LoadComponentFromFile(const FileName: string): TComponent;
var FileStream: TFileStream;
begin
FileStream := TFileStream.Create(filename, fmOpenRead );
try
Result:=LoadComponentFromStream(FileStream);
finally
FileStream.Free;
end;
end;
class function TStreamingClass.LoadComponentFromString(const text: string): TComponent;
var StrStream: TStringStream;
begin
StrStream:=TStringStream.Create(text);
try
Result:=LoadComponentFromStream(StrStream);
finally
StrStream.Free;
end;
end;
class function TStreamingClass.CloneComponent(source: TStreamingClass; aowner: TComponent=nil): TComponent;
var BinStream: TMemoryStream;
begin
BinStream:=TMemoryStream.Create;
try
ThreadSafeWriteComponent(BinStream,source);
BinStream.Seek(0,soFromBeginning);
Result:=ThreadSafeReadComponent(BinStream,aowner);
finally
BinStream.Free;
end;
end;
procedure TStreamingClass.Assign(source: TPersistent);
var b: TMemoryStream;
begin
if source is TStreamingClass then begin
b:=TMemoryStream.Create;
try
ThreadSafeWriteComponent(b,TComponent(source));
b.Seek(0,soBeginning);
Clear;
ThreadSafeReadComponent(b,self);
finally
b.Free;
end;
end
else inherited Assign(source);
end;
constructor TStreamingClass.Clone(source: TStreamingClass; owner: TComponent=nil);
begin
Create(Owner);
self.Assign(source);
end;
function TStreamingClass.IsEqual(what: TStreamingClass): boolean;
var bin1,bin2: TMemoryStream;
begin
bin1:=TMemoryStream.Create;
try
ThreadSafeWriteComponent(bin1,self);
bin1.Seek(0,soFromBeginning);
bin2:=TMemoryStream.Create;
try
ThreadSafeWriteComponent(bin2,what);
bin2.Seek(0,soFromBeginning);
if bin1.Size<>bin2.Size then Result:=false
else Result:=Comparemem(bin1.Memory,bin2.Memory,bin1.Size);
finally
bin2.Free;
end;
finally
bin1.Free;
end;
end;
function TStreamingClass.EqualsByAnyOtherName(what: TStreamingClass): boolean;
var our_class: TStreamingClassClass;
t: TStreamingClass;
begin
// we don't want to temporary change any object, so we'll have little workaround
// not very fast procedure, if you know that temporary change of name won't harm,
// better do it and call IsEqual
if ClassType=what.ClassType then begin
our_class:=TStreamingClassClass(ClassType);
t:=our_class.Clone(what);
t.Name:=Name;
Result:=IsEqual(t);
t.Free;
end
else Result:=false;
end;
function TStreamingClass.FindOwner: TComponent;
var tmp: TComponent;
begin
tmp:=self;
repeat
Result:=tmp;
tmp:=tmp.Owner;
until tmp=nil;
end;
procedure TStreamingClass.SetDefaultProperties;
//from book "Delphi in a nutshell" by Ray Lischner
const
tkOrdinal=[tkEnumeration, tkInteger, tkChar, tkSet, tkWChar];
noDefault = Low(Integer);
var
PropList: PPropList;
Count, I: Integer;
begin
Count:= GetPropList(PTypeInfo(self.ClassInfo),tkOrdinal,nil);
GetMem(PropList,Count*SizeOf(PPropInfo));
try
GetPropList(PTypeInfo(self.ClassInfo),tkOrdinal,PropList);
for i:=0 to Count-1 do
if PropList[i].Default<>NoDefault then
SetOrdProp(self,PropList[i],PropList[i].Default)
finally
FreeMem(PropList);
end;
end;
procedure TStreamingClass.Clear;
var i: Integer;
begin
//pretty generic approach: all properties are set to default values,
//nested components supporting 'clear' are cleared recursively.
SetDefaultProperties;
for i:=0 to ComponentCount-1 do
if Components[i] is TStreamingClass then
TStreamingClass(Components[i]).Clear;
end;
procedure InitializeStreamingClassLib;
//we've got a lot of headache because classes unit hides signature for binary files
//we know it's 'TPF0' but who knows, maybe it changes sometimes...
//problem is, it's not in any standart as gzip header is.
var w: TWriter;
stream: TStringStream;
sig: AnsiString;
begin
gCriticalSection:=TCriticalSection.Create;
gFormatList:=TList.Create;
RegisterIntegerConsts(TypeInfo(TStreamingClassSaveFormat),NameToSaveFormat,SaveFormatToName);
//we won't use try/finally here, absolute sure it'll handle 4 bytes all right
stream:=TStringStream.Create(sig);
w:=TWriter.Create(stream,4);
w.WriteSignature;
w.Free;
RegisterStreamingFormat(sfBin,AnsiString(stream.DataString),'sfBin',BinaryFormatFilter,nil,nil); //nil corresponds to no transformation at all
RegisterStreamingFormat(sfASCII,'object','sfAscii',AsciiFormatFilter, ObjectTextToBinary,ObjectBinaryToText);
stream.Free;
end;
procedure FinalizeStreamingClassLib;
var i: Integer;
begin
for i:=0 to gFormatList.Count-1 do
Dispose(gFormatList[i]);
FreeAndNil(gFormatList);
FreeAndNil(gCriticalSection);
end;
initialization
InitializeStreamingClassLib;
finalization
FinalizeStreamingClassLib;
end.
|
unit NullableBasicTypesUnit;
interface
uses
SysUtils, Math, Types;
type
NullableObject = record
strict private
FValue: TObject;
FIsNull: boolean;
function GetValue: TObject;
public
constructor Create(PValue: TObject);
class operator Implicit(A: NullableObject): TObject;
class operator Implicit(PValue: TObject): NullableObject;
class operator Equal(A, B: NullableObject): boolean;
class operator NotEqual(A, B: NullableObject): boolean;
class function Null: NullableObject; static;
procedure Free;
property Value: TObject read GetValue;
property IsNull: boolean read FIsNull;
function IsNotNull: boolean;
end;
NullableInteger = record
strict private
FValue: integer;
FIsNull: boolean;
function GetValue: integer;
private
function LessThen(Another: NullableInteger): boolean;
function GreaterThen(Another: NullableInteger): boolean;
function LessThenOrEqual(Another: NullableInteger): boolean;
function GreaterThenOrEqual(Another: NullableInteger): boolean;
public
constructor Create(PValue: integer);
class operator Implicit(A: NullableInteger): integer;
class operator Implicit(PValue: integer): NullableInteger;
class operator Equal(A, B: NullableInteger): boolean;
class operator NotEqual(A, B: NullableInteger): boolean;
class operator LessThan(A, B: NullableInteger): boolean;
class operator GreaterThan(A, B: NullableInteger): boolean;
class operator LessThanOrEqual(A, B: NullableInteger): boolean;
class operator GreaterThanOrEqual(A, B: NullableInteger): boolean;
class function Null: NullableInteger; static;
function Compare(Other: NullableInteger): integer;
function ToString(): String;
property Value: integer read GetValue;
property IsNull: boolean read FIsNull;
function IsNotNull: boolean;
end;
NullableDouble = record
strict private
const
NullStr = 'Null';
var
FValue: double;
FIsNull: boolean;
function GetValue: double;
function LessThen(Another: NullableDouble): boolean;
function GreaterThen(Another: NullableDouble): boolean;
function LessThenOrEqual(Another: NullableDouble): boolean;
function GreaterThenOrEqual(Another: NullableDouble): boolean;
public
constructor Create(PValue: double);
class function NullIfNaN(Value: double): NullableDouble; static;
function Equals(OtherValue: NullableDouble; Epsilon: double): boolean;
class operator Implicit(A: NullableDouble): double;
class operator Implicit(PValue: double): NullableDouble;
class operator Equal(A, B: NullableDouble): boolean;
class operator NotEqual(A, B: NullableDouble): boolean;
class operator LessThan(A, B: NullableDouble): boolean;
class operator GreaterThan(A, B: NullableDouble): boolean;
class operator LessThanOrEqual(A, B: NullableDouble): boolean;
class operator GreaterThanOrEqual(A, B: NullableDouble): boolean;
function Compare(Other: NullableDouble): integer;
class function Null: NullableDouble; static;
function ToString(): String; overload;
class function FromString(PValue: String): NullableDouble; static;
property Value: double read GetValue;
property IsNull: boolean read FIsNull;
function IsNotNull: boolean;
function IfNull(DefaultValue: double): double;
end;
NullableDoubleArray = array of NullableDouble;
NullableString = record
private
FValue: String;
FIsNull: boolean;
function GetValue: String;
public
constructor Create(PValue: String);
class operator Implicit(A: NullableString): String;
class operator Implicit(PValue: String): NullableString;
class operator Equal(A, B: NullableString): boolean;
class operator NotEqual(A, B: NullableString): boolean;
function Compare(Other: NullableString): integer;
class function Null: NullableString; static;
function ToString(): String;
property Value: String read GetValue;
property IsNull: boolean read FIsNull;
function IsNotNull: boolean;
function IfNull(DefaultValue: string): string;
end;
NullableBoolean = record
strict private
FValue: boolean;
FIsNull: boolean;
function GetValue: boolean;
public
constructor Create(PValue: boolean);
function ToString(): String;
class operator Implicit(A: NullableBoolean): boolean;
class operator Implicit(PValue: boolean): NullableBoolean;
class operator Equal(A, B: NullableBoolean): boolean;
class operator NotEqual(A, B: NullableBoolean): boolean;
class function Null: NullableBoolean; static;
property Value: boolean read GetValue;
property IsNull: boolean read FIsNull;
function IsNotNull: boolean;
end;
implementation
{ NullableInteger }
function NullableInteger.Compare(Other: NullableInteger): integer;
begin
if (IsNull and Other.IsNotNull) then
Result := LessThanValue
else
if (IsNotNull and Other.IsNull) then
Result := GreaterThanValue
else
if (Self = Other) then
Result := EqualsValue
else
if (Self < Other) then
Result := LessThanValue
else
Result := GreaterThanValue;
end;
constructor NullableInteger.Create(PValue: integer);
begin
FValue := PValue;
FIsNull := False;
end;
class operator NullableInteger.Equal(A, B: NullableInteger): boolean;
begin
if (A.IsNull <> B.IsNull) then
begin
Result := False;
end
else
if (A.IsNull = B.IsNull) and (A.IsNull) then
begin
Result := True;
end
else
if (A.IsNull = B.IsNull) and (not A.IsNull) then
begin
Result := (A.Value = B.Value);
end
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
function NullableInteger.GetValue: integer;
begin
if (FIsNull) then
raise Exception.Create('Невозможно получить значение - оно равно Null')
else
Result := FValue;
end;
class operator NullableInteger.GreaterThan(A, B: NullableInteger): boolean;
begin
Result := A.GreaterThen(B);
end;
class operator NullableInteger.GreaterThanOrEqual(A,
B: NullableInteger): boolean;
begin
Result := A.GreaterThenOrEqual(B);
end;
function NullableInteger.GreaterThen(Another: NullableInteger): boolean;
begin
if ((Self.IsNull) and (not Another.IsNull)) or
((not Self.IsNull) and (Another.IsNull)) then
raise Exception.Create('Нельзя сравнивать число с Null');
if (Self.IsNull) and (Another.IsNull) then
Result := False
else
if (not Self.IsNull) and (not Another.IsNull) then
Result := (Self.Value > Another.Value)
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
function NullableInteger.GreaterThenOrEqual(Another: NullableInteger): boolean;
begin
if ((Self.IsNull) and (not Another.IsNull)) or
((not Self.IsNull) and (Another.IsNull)) then
raise Exception.Create('Нельзя сравнивать число с Null');
if (Self.IsNull) and (Another.IsNull) then
Result := False
else
if (not Self.IsNull) and (not Another.IsNull) then
Result := (Self.Value >= Another.Value)
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
class operator NullableInteger.Implicit(A: NullableInteger): integer;
begin
Result := A.Value;
end;
class operator NullableInteger.Implicit(PValue: integer): NullableInteger;
begin
Result := NullableInteger.Create(PValue);
end;
class operator NullableInteger.LessThan(A, B: NullableInteger): boolean;
begin
Result := A.LessThen(B);
end;
class operator NullableInteger.LessThanOrEqual(A, B: NullableInteger): boolean;
begin
Result := A.LessThenOrEqual(B);
end;
function NullableInteger.LessThen(Another: NullableInteger): boolean;
begin
if (Self.IsNull) and (not Another.IsNull) then
raise Exception.Create('Нельзя сравнивать число ' + Another.ToString() + ' с Null');
if (not Self.IsNull) and (Another.IsNull) then
raise Exception.Create('Нельзя сравнивать число ' + Self.ToString() + ' с Null');
if (Self.IsNull) and (Another.IsNull) then
Result := False
else
if (not Self.IsNull) and (not Another.IsNull) then
Result := (Self.Value < Another.Value)
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
function NullableInteger.LessThenOrEqual(Another: NullableInteger): boolean;
begin
if (Self.IsNull) and (not Another.IsNull) then
raise Exception.Create('Нельзя сравнивать число ' + Another.ToString() + ' с Null');
if (not Self.IsNull) and (Another.IsNull) then
raise Exception.Create('Нельзя сравнивать число ' + Self.ToString() + ' с Null');
if (Self.IsNull) and (Another.IsNull) then
Result := False
else
if (not Self.IsNull) and (not Another.IsNull) then
Result := (Self.Value <= Another.Value)
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
class operator NullableInteger.NotEqual(A, B: NullableInteger): boolean;
begin
Result := not (A = B);
end;
class function NullableInteger.Null: NullableInteger;
begin
Result.FIsNull := True;
end;
function NullableInteger.ToString: String;
begin
if FIsNull then
Result := 'Null'
else
Result := IntToStr(FValue);
end;
function NullableInteger.IsNotNull: boolean;
begin
Result := not IsNull;
end;
{ NullableDouble }
function NullableDouble.Compare(Other: NullableDouble): integer;
begin
if (IsNull and Other.IsNotNull) then
Result := LessThanValue
else
if (IsNotNull and Other.IsNull) then
Result := GreaterThanValue
else
if (Self = Other) then
Result := EqualsValue
else
if (Self < Other) then
Result := LessThanValue
else
Result := GreaterThanValue;
end;
constructor NullableDouble.Create(PValue: double);
begin
FValue := PValue;
FIsNull := False;
end;
class operator NullableDouble.Equal(A, B: NullableDouble): boolean;
var
Epsilon: double;
begin
// пока точность "зашита"
Epsilon := 0.0001;
if (A.IsNull <> B.IsNull) then
begin
Result := False;
end
else
if (A.IsNull = B.IsNull) and (A.IsNull) then
begin
Result := True;
end
else
if (A.IsNull = B.IsNull) and (not A.IsNull) then
begin
Result := SameValue(A.Value, B.Value, Epsilon);
end
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
function NullableDouble.Equals(OtherValue: NullableDouble; Epsilon: double): boolean;
begin
if Self.IsNull and OtherValue.IsNull then
Result := True
else
if ((not Self.IsNull) and (OtherValue.IsNull)) or
((Self.IsNull) and (not OtherValue.IsNull)) then
Result := False
else
Result := SameValue(Self.Value, OtherValue.Value, Epsilon);
end;
class function NullableDouble.FromString(PValue: String): NullableDouble;
begin
if (PValue = EmptyStr) or (PValue = NullStr)
then Result := NullableDouble.Null
else Result := StrToFloat(PValue);
end;
function NullableDouble.GetValue: double;
begin
if (FIsNull) then
raise Exception.Create('Невозможно получить значение - оно равно Null')
else
Result := FValue;
end;
class operator NullableDouble.GreaterThan(A, B: NullableDouble): boolean;
begin
Result := A.GreaterThen(B);
end;
class operator NullableDouble.GreaterThanOrEqual(A, B: NullableDouble): boolean;
begin
Result := A.GreaterThenOrEqual(B);
end;
function NullableDouble.GreaterThen(Another: NullableDouble): boolean;
var
cv: TValueRelationship;
begin
if ((Self.IsNull) and (not Another.IsNull)) or
((not Self.IsNull) and (Another.IsNull)) then
raise Exception.Create('Нельзя сравнивать число с Null');
if (Self.IsNull) and (Another.IsNull) then
Result := False
else
if (not Self.IsNull) and (not Another.IsNull) then
begin
cv := CompareValue(Self.Value, Another.Value);
Result := (cv = GreaterThanValue);
end
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
function NullableDouble.GreaterThenOrEqual(Another: NullableDouble): boolean;
var
cv: TValueRelationship;
begin
if ((Self.IsNull) and (not Another.IsNull)) or
((not Self.IsNull) and (Another.IsNull)) then
raise Exception.Create('Нельзя сравнивать число с Null');
if (Self.IsNull) and (Another.IsNull) then
Result := False
else
if (not Self.IsNull) and (not Another.IsNull) then
begin
cv := CompareValue(Self.Value, Another.Value);
Result := (cv = GreaterThanValue) or (cv = EqualsValue);
end
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
class operator NullableDouble.Implicit(A: NullableDouble): double;
begin
Result := A.Value;
end;
function NullableDouble.IfNull(DefaultValue: double): double;
begin
if Self.IsNull then
Result := DefaultValue
else
Result := Self.Value;
end;
class operator NullableDouble.Implicit(PValue: double): NullableDouble;
begin
Result := NullableDouble.Create(PValue);
end;
class operator NullableDouble.LessThan(A, B: NullableDouble): boolean;
begin
Result := A.LessThen(B);
end;
class operator NullableDouble.LessThanOrEqual(A, B: NullableDouble): boolean;
begin
Result := A.LessThenOrEqual(B);
end;
function NullableDouble.LessThen(Another: NullableDouble): boolean;
var
cv: TValueRelationship;
begin
if ((Self.IsNull) and (not Another.IsNull)) or
((not Self.IsNull) and (Another.IsNull)) then
raise Exception.Create('Нельзя сравнивать число с Null');
if (Self.IsNull) and (Another.IsNull) then
Result := False
else
if (not Self.IsNull) and (not Another.IsNull) then
begin
cv := CompareValue(Self.Value, Another.Value);
Result := (cv = LessThanValue);
end
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
function NullableDouble.LessThenOrEqual(Another: NullableDouble): boolean;
var
cv: TValueRelationship;
begin
if ((Self.IsNull) and (not Another.IsNull)) or
((not Self.IsNull) and (Another.IsNull)) then
raise Exception.Create('Нельзя сравнивать число с Null');
if (Self.IsNull) and (Another.IsNull) then
Result := False
else
if (not Self.IsNull) and (not Another.IsNull) then
begin
cv := CompareValue(Self.Value, Another.Value);
Result := (cv = LessThanValue) or (cv = EqualsValue);
end
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
class operator NullableDouble.NotEqual(A, B: NullableDouble): boolean;
begin
Result := not (A = B);
end;
class function NullableDouble.Null: NullableDouble;
begin
Result.FIsNull := True;
end;
class function NullableDouble.NullIfNaN(Value: double): NullableDouble;
begin
if Math.IsNAN(Value) then
Result := NullableDouble.Null
else
Result := NullableDouble.Create(Value);
end;
function NullableDouble.ToString: String;
begin
if FIsNull then
Result := NullStr
else
Result := FloatToStr(FValue);
end;
function NullableDouble.IsNotNull: boolean;
begin
Result := not IsNull;
end;
{ NullableString }
function NullableString.Compare(Other: NullableString): integer;
begin
if (IsNull and Other.IsNotNull) then
Result := LessThanValue
else
if (IsNotNull and Other.IsNull) then
Result := GreaterThanValue
else
if (Self = Other) then
Result := EqualsValue
else
Result := String.Compare(Self.Value, Other.Value);
end;
constructor NullableString.Create(PValue: String);
begin
FValue := PValue;
FIsNull := False;
end;
class operator NullableString.Equal(A, B: NullableString): boolean;
begin
if (A.IsNull <> B.IsNull) then
Result := False
else
if (A.IsNull = B.IsNull) and (A.IsNull) then
Result := True
else
if (A.IsNull = B.IsNull) and (not A.IsNull) then
Result := (A.Value = B.Value)
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
function NullableString.GetValue: String;
begin
if (FIsNull) then
raise Exception.Create('Невозможно получить значение - оно равно Null')
else
Result := FValue;
end;
function NullableString.IsNotNull: boolean;
begin
Result := not IsNull;
end;
class operator NullableString.Implicit(A: NullableString): String;
begin
Result := A.Value;
end;
function NullableString.IfNull(DefaultValue: string): string;
begin
if Self.IsNull then
Result := DefaultValue
else
Result := Self.Value;
end;
class operator NullableString.Implicit(PValue: String): NullableString;
begin
Result := NullableString.Create(PValue);
end;
class operator NullableString.NotEqual(A, B: NullableString): boolean;
begin
Result := not (A = B);
end;
class function NullableString.Null: NullableString;
begin
Result.FIsNull := True;
end;
function NullableString.ToString: String;
begin
if (FIsNull) then
Result := 'Null'
else
Result := FValue;
end;
{ NullableBoolean }
constructor NullableBoolean.Create(PValue: boolean);
begin
FValue := PValue;
FIsNull := False;
end;
class operator NullableBoolean.Equal(A, B: NullableBoolean): boolean;
begin
if (A.IsNull <> B.IsNull) then
begin
Result := False;
end
else
if (A.IsNull = B.IsNull) and (A.IsNull) then
begin
Result := True;
end
else
if (A.IsNull = B.IsNull) and (not A.IsNull) then
begin
Result := (A.Value = B.Value);
end
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
function NullableBoolean.GetValue: boolean;
begin
if (FIsNull) then
raise Exception.Create('Невозможно получить значение - оно равно Null')
else
Result := FValue;
end;
class operator NullableBoolean.Implicit(A: NullableBoolean): boolean;
begin
Result := A.Value;
end;
class operator NullableBoolean.Implicit(PValue: boolean): NullableBoolean;
begin
Result := NullableBoolean.Create(PValue);
end;
class operator NullableBoolean.NotEqual(A, B: NullableBoolean): boolean;
begin
Result := not (A = B);
end;
class function NullableBoolean.Null: NullableBoolean;
begin
Result.FIsNull := True;
end;
function NullableBoolean.ToString: String;
begin
if (FIsNull) then
Result := 'Null'
else
if (FValue) then
Result := 'True'
else
if (not FValue) then
Result := 'False'
else
raise Exception.Create('Невозможно получить строковое представление NullableBoolean');
end;
function NullableBoolean.IsNotNull: boolean;
begin
Result := not IsNull;
end;
{ NullableObject }
constructor NullableObject.Create(PValue: TObject);
begin
FValue := PValue;
FIsNull := False;
end;
class operator NullableObject.Equal(A, B: NullableObject): boolean;
begin
if (A.IsNull <> B.IsNull) then
Result := False
else
if (A.IsNull = B.IsNull) and (A.IsNull) then
Result := True
else
if (A.IsNull = B.IsNull) and (not A.IsNull) then
Result := (A.Value.Equals(B.Value))
else
raise Exception.Create('Непредвиденный вариант сравнения');
end;
procedure NullableObject.Free;
begin
FreeAndNil(FValue);
end;
function NullableObject.GetValue: TObject;
begin
if (FIsNull) then
raise Exception.Create('Невозможно получить значение - оно равно Null')
else
Result := FValue;
end;
class operator NullableObject.Implicit(A: NullableObject): TObject;
begin
Result := A.Value;
end;
class operator NullableObject.Implicit(PValue: TObject): NullableObject;
begin
Result := NullableObject.Create(PValue);
end;
function NullableObject.IsNotNull: boolean;
begin
Result := not IsNull;
end;
class operator NullableObject.NotEqual(A, B: NullableObject): boolean;
begin
Result := not (A = B);
end;
class function NullableObject.Null: NullableObject;
begin
Result.FIsNull := True;
Result.FValue := nil;
end;
end.
|
unit Common;
interface
{$I defines.inc}
uses Classes, Forms, Controls , Graphics,SysUtils, Windows, Variants, RxStrUtils, DB;
type
TShowFont = class(TControl)
public
property Font;
end;
var
DebugMode:Boolean = true;
// gServerName:String;
// gSysDbaPassword:String;
// gServerProtocol:integer;
// gLogonUserName,
// gLogonUserPassword,
// gLogonDataBase: String;
gFR_FORMS_PATH : String;
OPERATION_DATE : TDateTime;
// gRoundPrecision:integer;
// gEnterToTab : boolean = true;
gCustActive:TColor; //Подключен
gCustInactive:TColor; //Отключен
gCustInactiveDebt:TColor; //Отключен и долг
gCustPPAct:TColor; //Повторно подключался
function LogEvent(const AUnit, ADescr, ANonice:String):boolean;
procedure SetGlobalConst;
function GetExePath: string;
procedure DatasetToFile(Dataset: TDataset; FileName: string);
procedure DatasetFromFile(Dataset: TDataset; FileName: string);
function AdvSelectDirectory(const Caption: string; const Root: WideString;
var Directory: string; EditBox: Boolean = False; ShowFiles: Boolean = False;
AllowCreateDirs: Boolean = True): Boolean;
procedure ComressStream( aSource, aTarget : TStream);
procedure DecompressStream(aSource, aTarget: TStream);
// получаем версию файла
function GetFileVersion(const FileName: TFileName; var Major, Minor, Release, Build: Integer): Boolean;
// Возвращает системный каталог, по умолчанию
function GetSpecialFolderPath(folder : integer=2) : string;
// Возвращает путь ко времменой папке
function GetTempDir: String;
implementation
uses
DateUtils, IniFiles, ClipBrd, ShlObj, ActiveX, Zlib, ZlibConst, AtrStrUtils, SHFolder;
function GetTempDir: String;
var
Buf: array[0..1023] of Char;
begin
SetString(Result, Buf, GetTempPath(Sizeof(Buf)-1, Buf));
end;
{
Возвращает системный каталог, по умолчанию
0: [Current User]\My Documents
1: All Users\Application Data
2: [User Specific]\Application Data
3: Program Files
4: All Users\Documents
}
function GetSpecialFolderPath(folder : integer=2) : string;
const
SHGFP_TYPE_CURRENT = 0;
var
path: array [0..MAX_PATH] of char;
specialFolder : integer;
begin
specialFolder := CSIDL_PERSONAL;
case folder of
//[Current User]\My Documents
0: specialFolder := CSIDL_PERSONAL;
//All Users\Application Data
1: specialFolder := CSIDL_COMMON_APPDATA;
//[User Specific]\Application Data
2: specialFolder := CSIDL_LOCAL_APPDATA;
//Program Files
3: specialFolder := CSIDL_PROGRAM_FILES;
//All Users\Documents
4: specialFolder := CSIDL_COMMON_DOCUMENTS;
end;
if SUCCEEDED(SHGetFolderPath(0,specialFolder,0,SHGFP_TYPE_CURRENT,@path[0])) then
Result := path
else
Result := '';
end;
function GetFileVersion(const FileName: TFileName; var Major, Minor,
Release, Build: Integer): Boolean;
var
InfoSize, Wnd: DWORD;
VerBuf: Pointer;
FI: PVSFixedFileInfo;
VerSize: DWORD;
begin
Result:= False;
InfoSize:= GetFileVersionInfoSize(PChar(FileName), Wnd);
if InfoSize <> 0 then begin
GetMem(VerBuf, InfoSize);
try
if GetFileVersionInfo(PChar(FileName), Wnd, InfoSize, VerBuf) then
if VerQueryValue(VerBuf, '\', Pointer(FI), VerSize) then begin
Major:= FI.dwFileVersionMS shr 16;
Minor:= FI.dwFileVersionMS and $FFFF;
Release:= FI.dwFileVersionLS shr 16;
Build:= FI.dwFileVersionLS and $FFFF;
Result:= True;
end;
finally
FreeMem(VerBuf);
end;
end;
end;
procedure ComressStream( aSource, aTarget : TStream);
var
comprStream : TCompressionStream;
begin
// compression level : (clNone, clFastest, clDefault, clMax)
comprStream := TCompressionStream.Create( clMax, aTarget );
try
comprStream.CopyFrom( aSource, aSource.Size );
comprStream.CompressionRate;
finally
comprStream.FreeAndNil;
End;
End;
procedure DecompressStream(aSource, aTarget: TStream);
var decompStream : TDecompressionStream;
nRead : Integer;
buffer : array[0..1023] of Char;
begin
decompStream := TDecompressionStream.Create( aSource );
try
repeat
nRead:=decompStream.Read( buffer, 1024 );
aTarget.Write( buffer, nRead );
Until nRead = 0;
finally
decompStream.FreeAndNil;
End;
End;
procedure SetGlobalConst;
begin
DecimalSeparator := ',';
DateSeparator := '.';
ShortDateFormat := 'dd.mm.yyyy';
ShortTimeFormat := 'hh:mm:ss';
end;
function GetExePath: string;
begin
Result := ExtractFilePath(Application.ExeName);
end;
function FBdateToDate(const aFBDAte:String):TDateTime;
var
y,m,d : Integer;
s: string;
begin
//TODO:Дату из строки в TDate
result := 0;
if pos('-',aFBDate) = 0 then exit;
y := StrToInt(copy(aFBDate,0,pos('-',aFBDate)-1));
s := copy(aFBDate,pos('-',aFBDate)+1, 100);
m := StrToInt(copy(s,0,pos('-',s)-1));
s := copy(s,pos('-',s)+1, 100);
d := StrToInt(s);
result := EncodeDate(y,m,d);
end;
//Log Event in Database
//If AEvent_Id<0 then insert mode, else Update mode
//Return True if ok
function LogEvent(const AUnit, ADescr, ANonice:String):boolean;
var
f: TextFile;
begin
Result := False;
if not DebugMode then exit;
AssignFile(f, LogFileName);
if (not FileExists(LogFileName)) then
Rewrite(f) //create
else
Append(f);
if ioresult = 0 then
begin
Writeln(f, format('%10s: %s :%s :%s', [DateTimeToStr(now), AUnit, ADescr, ANonice]));
Flush(f);
CloseFile(f);
Result := True;
end;
end;
procedure DatasetToFile(Dataset: TDataset; FileName: string);
var
body : TStrings;
bkmark: TBookmark;
i : Integer;
s : string;
begin
body := TStringList.Create;
try
with DataSet do begin
DisableControls;
bkmark := GetBookmark;
First;
while (not EOF) do begin
s:='';
for i := 0 to FieldCount - 1 do
if not Fields[i].IsNull
then s:=s+Fields[i].FieldName+':'+Fields[i].AsString+#9;
body.Add(s);
Next;
end;
GotoBookmark(bkmark);
EnableControls;
end;
body.SaveToFile(FileName);
finally
FreeAndNil(body);
end;
end;
procedure DatasetFromFile(Dataset: TDataset; FileName: string);
var
body : TStrings;
i,j,p : Integer;
s,v : string;
l : TStringArray;
begin
body := TStringList.Create;
try
body.LoadFromFile(FileName);
DataSet.DisableControls;
if not DataSet.Active
then DataSet.Open
else while not DataSet.eof do DataSet.Delete;
s := '';
for i:=0 to (body.Count-1) do begin
s := body[i];
l:=explode(#9,s);
if Length(l)>0
then begin
DataSet.append;
for j := 0 to Length(l) - 1 do begin
if l[j] = '' then Continue;
p := Pos(':',l[j]);
s := Copy(l[j],0,p-1);
v := Copy(l[j],p+1,Length(l[j])-p);
DataSet.FieldByName(s).AsString := v;
end;
DataSet.post;
end;
end;
DataSet.First;
DataSet.EnableControls;
finally
FreeAndNil(body);
end;
end;
{
This code shows the SelectDirectory dialog with additional expansions:
- an edit box, where the user can type the path name,
- also files can appear in the list,
- a button to create new directories.
Dieser Code zeigt den SelectDirectory-Dialog mit zusatzlichen Erweiterungen:
- eine Edit-Box, wo der Benutzer den Verzeichnisnamen eingeben kann,
- auch Dateien konnen in der Liste angezeigt werden,
- eine Schaltflache zum Erstellen neuer Verzeichnisse.
}
function AdvSelectDirectory(const Caption: string; const Root: WideString;
var Directory: string; EditBox: Boolean = False; ShowFiles: Boolean = False;
AllowCreateDirs: Boolean = True): Boolean;
// callback function that is called when the dialog has been initialized
//or a new directory has been selected
// Callback-Funktion, die aufgerufen wird, wenn der Dialog initialisiert oder
//ein neues Verzeichnis selektiert wurde
function SelectDirCB(Wnd: HWND; uMsg: UINT; lParam, lpData: lParam): Integer;
stdcall;
//var
//PathName: array[0..MAX_PATH] of Char;
begin
case uMsg of
BFFM_INITIALIZED: SendMessage(Wnd, BFFM_SETSELECTION, Ord(True), Integer(lpData));
// include the following comment into your code if you want to react on the
//event that is called when a new directory has been selected
// binde den folgenden Kommentar in deinen Code ein, wenn du auf das Ereignis
//reagieren willst, das aufgerufen wird, wenn ein neues Verzeichnis selektiert wurde
{BFFM_SELCHANGED:
begin
SHGetPathFromIDList(PItemIDList(lParam), @PathName);
// the directory "PathName" has been selected
// das Verzeichnis "PathName" wurde selektiert
end;}
end;
Result := 0;
end;
var
WindowList: Pointer;
BrowseInfo: TBrowseInfo;
Buffer: PChar;
RootItemIDList, ItemIDList: PItemIDList;
ShellMalloc: IMalloc;
IDesktopFolder: IShellFolder;
Eaten, Flags: LongWord;
const
// necessary for some of the additional expansions
// notwendig fur einige der zusatzlichen Erweiterungen
BIF_USENEWUI = $0040;
BIF_NOCREATEDIRS = $0200;
begin
Result := False;
if not DirectoryExists(Directory) then
Directory := '';
FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then
begin
Buffer := ShellMalloc.Alloc(MAX_PATH);
try
RootItemIDList := nil;
if Root <> '' then
begin
SHGetDesktopFolder(IDesktopFolder);
IDesktopFolder.ParseDisplayName(Application.Handle, nil,
POleStr(Root), Eaten, RootItemIDList, Flags);
end;
OleInitialize(nil);
with BrowseInfo do
begin
hwndOwner := Application.Handle;
pidlRoot := RootItemIDList;
pszDisplayName := Buffer;
lpszTitle := PChar(Caption);
// defines how the dialog will appear:
// legt fest, wie der Dialog erscheint:
ulFlags := BIF_RETURNONLYFSDIRS or BIF_USENEWUI or
BIF_EDITBOX * Ord(EditBox) or BIF_BROWSEINCLUDEFILES * Ord(ShowFiles) or
BIF_NOCREATEDIRS * Ord(not AllowCreateDirs);
lpfn := @SelectDirCB;
if Directory <> '' then
lParam := Integer(PChar(Directory));
end;
WindowList := DisableTaskWindows(0);
try
ItemIDList := ShBrowseForFolder(BrowseInfo);
finally
EnableTaskWindows(WindowList);
end;
Result := ItemIDList <> nil;
if Result then
begin
ShGetPathFromIDList(ItemIDList, Buffer);
ShellMalloc.Free(ItemIDList);
Directory := Buffer;
end;
finally
ShellMalloc.Free(Buffer);
end;
end;
end;
{
TVersionInfo = class(TComponent)
private
FVersionInfo : Pointer;
FFileName : String;
FLangCharSet : String;
function GetCompanyName : String;
function GetFileDescription : String;
function GetFileVersion : String;
function GetInternalName : String;
function GetLegalCopyright : String;
function GetOriginalFilename : String;
function GetProductName : String;
function GetProductVersion : String;
procedure Init;
procedure SetFileName(const Value : String);
procedure Clear;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
function GetValue(const ValueName : String; var Buffer : Pointer) : Boolean;
function GetLocalValue(const ValueName : String) : String;
property CompanyName : String read GetCompanyName;
property FileDescription : String read GetFileDescription;
property FileVersion : String read GetFileVersion;
property InternalName : String read GetInternalName;
property LegalCopyright : String read GetLegalCopyright;
property OriginalFilename : String read GetOriginalFilename;
property ProductName : String read GetProductName;
property ProductVersion : String read GetProductVersion;
property LangCharSet : String read FLangCharSet;
published
property FileName : String read FFileName write SetFileName;
end;
procedure Register;
implementation
constructor TVersionInfo.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FVersionInfo := nil;
FFileName := Application.ExeName;
end;
destructor TVersionInfo.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TVersionInfo.Clear;
begin
if FVersionInfo <> nil then FreeMem(FVersionInfo);
FVersionInfo := nil;
end;
procedure TVersionInfo.SetFileName(const Value : String);
begin
Clear;
FFileName := Value;
end;
procedure TVersionInfo.Init;
type T = array [0..1] of WORD;
var Size, Fake : DWORD;
P : ^T;
begin
if FVersionInfo <> nil then exit;
Size := GetFileVersionInfoSize(PChar(FFileName), Fake);
if Size = 0 then raise Exception.Create('Error in detecting VersionInfo size!');
GetMem(FVersionInfo, Size);
try
if not GetFileVersionInfo(PChar(FFileName), 0, Size, FVersionInfo) then
raise Exception.Create('Error in detecting VersionInfo!');
except
FreeMem(FVersionInfo);
FVersionInfo := nil;
raise;
end;
GetValue('\VarFileInfo\Translation', Pointer(P));
FLangCharSet := Format('%.4x%.4x', [P^[0], P^[1]]);
end;
function TVersionInfo.GetValue(const ValueName : String; var Buffer : Pointer) : Boolean;
var Size : UINT;
begin
Init;
Result := VerQueryValue(FVersionInfo, PChar(ValueName), Buffer, Size);
end;
function TVersionInfo.GetLocalValue(const ValueName : String) : String;
var P : Pointer;
begin
Init;
if GetValue('\StringFileInfo\' + FLangCharSet + '\' + ValueName, P) then Result := StrPas(P)
else Result := '';
end;
function TVersionInfo.GetCompanyName : String;
begin
Result := GetLocalValue('CompanyName');
end;
function TVersionInfo.GetFileDescription : String;
begin
Result := GetLocalValue('FileDescription');
end;
function TVersionInfo.GetFileVersion : String;
begin
Result := GetLocalValue('FileVersion');
end;
function TVersionInfo.GetInternalName : String;
begin
Result := GetLocalValue('InternalName');
end;
function TVersionInfo.GetLegalCopyright : String;
begin
Result := GetLocalValue('LegalCopyright');
end;
function TVersionInfo.GetOriginalFilename : String;
begin
Result := GetLocalValue('OriginalFilename');
end;
function TVersionInfo.GetProductName : String;
begin
Result := GetLocalValue('ProductName');
end;
function TVersionInfo.GetProductVersion : String;
begin
Result := GetLocalValue('ProductVersion');
end;
}
initialization
//Colors
gCustActive := clWindowText; //Подключен
gCustInactive := clTeal; //Отключен
gCustInactiveDebt := clMaroon; //Отключен и долг
gCustPPAct := clBlue; //Повторно подключался за последний месяц
OPERATION_DATE := NOW;
DebugMode := FALSE;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls
;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
// function's type definition
// 1. example: simply decorating with ShowMessage(...)
TMyFunc_Ref = reference to procedure();
// 2. example: passing a parameter
TMyFunc_Ref1 = reference to procedure(aValue : String; aMemo : TMemo);
//functions to be decorated
// 1. example: simply decorating with ShowMessage(...)
procedure sayHello();
// 2. example: passing a parameter
procedure sayHello1(aValue : String; aMemo : TMemo);
// anonymous method is defined as Result of the function
// --> the function returned is the decorated original function
// (--> can be decoreated n times)
// 1. example
function sayHello_Decorator_Who(aMyFunc_Ref : TMyFunc_Ref):TMyFunc_Ref;
function sayHello_Decorator_When(aMyFunc_Ref : TMyFunc_Ref):TMyFunc_Ref;
// 2. example
function sayHello_Decorator1(aMyFunc_Ref : TMyFunc_Ref1):TMyFunc_Ref1;
function sayHello_Decorator2(aMyFunc_Ref : TMyFunc_Ref1):TMyFunc_Ref1;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.Clear;
end;
// 1. example: simply decorating with ShowMessage(...)
procedure TForm1.Button1Click(Sender: TObject);
var
aFunc : TMyFunc_Ref;
begin
Memo1.Clear;
// sayHello();
aFunc := nil;
aFunc := sayHello_Decorator_Who(sayHello);
// aFunc();
aFunc := sayHello_Decorator_When(aFunc);
// calling the double decorated procedure
aFunc();
end;
procedure sayHello();
begin
ShowMessage('hello');
end;
function sayHello_Decorator_Who(aMyFunc_Ref : TMyFunc_Ref):TMyFunc_Ref;
begin
Result := procedure()
begin
aMyFunc_Ref();
showMessage('in decorator added at this beginning:'+sLinebreak+' ''out there''');
end;
end;
function sayHello_Decorator_When(aMyFunc_Ref : TMyFunc_Ref):TMyFunc_Ref;
begin
Result := procedure()
begin
aMyFunc_Ref();
showMessage('in decorator added at the end:'+sLinebreak+' ''at this beautiful time of this day''');
end;
end;
// 2. example: passing a parameter
procedure TForm1.Button2Click(Sender: TObject);
var
aFunc : TMyFunc_Ref1;
begin
Memo1.Clear;
sayHello1('calling the procedure itself', Memo1);
Memo1.Lines.Add('------------');
aFunc := nil;
aFunc := sayHello_Decorator1(sayHello1);
// aFunc('1 --> ');
aFunc := sayHello_Decorator2(aFunc);
// calling the double decorated procedure
aFunc('Hello', Memo1);
end;
procedure sayHello1(aValue : String; aMemo : TMemo);
begin
if ( Assigned(aMemo) ) then
begin
aMemo.Lines.add(sLineBreak);
aMemo.Lines.add(aValue);
aMemo.Lines.add(sLineBreak);
end
else
ShowMessage('no graphical component for output:'+sLineBreak+aValue);
end;
function sayHello_Decorator1(aMyFunc_Ref : TMyFunc_Ref1):TMyFunc_Ref1;
begin
Result := procedure(aValue : String = ''; aMemo : TMemo = nil)
begin
if ( Assigned(aMemo) ) then
begin
aMemo.Lines.Add(' --> logging: in decorator added at the beginning');
aMemo.Lines.Add(' --> calling the decorated procedure with ''at this beautiful time of the day''');
end;
aMyFunc_Ref(aValue + ' ''at this beautiful time of the day''', aMemo);
if ( Assigned(aMemo) ) then
begin
aMemo.Lines.Add(' --> logging: in decorator added at the beginning');
aMemo.Lines.Add(' --> after calling the procedure');
end;
end;
end;
function sayHello_Decorator2(aMyFunc_Ref : TMyFunc_Ref1):TMyFunc_Ref1;
begin
Result := procedure(aValue : String = ''; aMemo : TMemo = nil)
begin
if ( Assigned(aMemo) ) then
begin
aMemo.Lines.Add(' --> logging: in decorator added at the end');
aMemo.Lines.Add(' --> calling the decorated procedure with ''out there''');
end;
aMyFunc_Ref(aValue + ' ''out there''', aMemo);
if ( Assigned(aMemo) ) then
begin
aMemo.Lines.Add(' --> logging: in decorator added at the end');
aMemo.Lines.Add(' --> after calling the procedure');
end;
end;
end;
end.
|
{ Date Created: 5/25/00 5:01:02 PM }
unit InfoDRFTCODETable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoDRFTCODERecord = record
PCode: String[10];
PDescription: String[30];
PNextDraftNumber: String[6];
End;
TInfoDRFTCODEBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoDRFTCODERecord
end;
TEIInfoDRFTCODE = (InfoDRFTCODEPrimaryKey);
TInfoDRFTCODETable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFNextDraftNumber: TStringField;
FDFTemplate: TBlobField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPNextDraftNumber(const Value: String);
function GetPNextDraftNumber:String;
procedure SetEnumIndex(Value: TEIInfoDRFTCODE);
function GetEnumIndex: TEIInfoDRFTCODE;
protected
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoDRFTCODERecord;
procedure StoreDataBuffer(ABuffer:TInfoDRFTCODERecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFNextDraftNumber: TStringField read FDFNextDraftNumber;
property DFTemplate: TBlobField read FDFTemplate;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PNextDraftNumber: String read GetPNextDraftNumber write SetPNextDraftNumber;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoDRFTCODE read GetEnumIndex write SetEnumIndex;
end; { TInfoDRFTCODETable }
procedure Register;
implementation
procedure TInfoDRFTCODETable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFNextDraftNumber := CreateField( 'NextDraftNumber' ) as TStringField;
FDFTemplate := CreateField( 'Template' ) as TBlobField;
end; { TInfoDRFTCODETable.CreateFields }
procedure TInfoDRFTCODETable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoDRFTCODETable.SetActive }
procedure TInfoDRFTCODETable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoDRFTCODETable.Validate }
procedure TInfoDRFTCODETable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoDRFTCODETable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoDRFTCODETable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoDRFTCODETable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoDRFTCODETable.SetPNextDraftNumber(const Value: String);
begin
DFNextDraftNumber.Value := Value;
end;
function TInfoDRFTCODETable.GetPNextDraftNumber:String;
begin
result := DFNextDraftNumber.Value;
end;
procedure TInfoDRFTCODETable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 10, N');
Add('Description, String, 30, N');
Add('NextDraftNumber, String, 6, N');
Add('Template, Memo, 0, N');
end;
end;
procedure TInfoDRFTCODETable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoDRFTCODETable.SetEnumIndex(Value: TEIInfoDRFTCODE);
begin
case Value of
InfoDRFTCODEPrimaryKey : IndexName := '';
end;
end;
function TInfoDRFTCODETable.GetDataBuffer:TInfoDRFTCODERecord;
var buf: TInfoDRFTCODERecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PNextDraftNumber := DFNextDraftNumber.Value;
result := buf;
end;
procedure TInfoDRFTCODETable.StoreDataBuffer(ABuffer:TInfoDRFTCODERecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFNextDraftNumber.Value := ABuffer.PNextDraftNumber;
end;
function TInfoDRFTCODETable.GetEnumIndex: TEIInfoDRFTCODE;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoDRFTCODEPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoDRFTCODETable, TInfoDRFTCODEBuffer ] );
end; { Register }
function TInfoDRFTCODEBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
3 : result := @Data.PNextDraftNumber;
end;
end;
end. { InfoDRFTCODETable }
|
unit App;
{ Based on 006_cartoon_sun.cpp example from oglplus (http://oglplus.org/) }
{$INCLUDE 'Sample.inc'}
interface
uses
System.Classes,
Neslib.Ooogles,
Neslib.FastMath,
Sample.App;
type
TCartoonSunApp = class(TApplication)
private
FProgram: TGLProgram;
FVerts: TGLBuffer;
FUniTime: TGLUniform;
FUniSunPos: TGLUniform;
public
procedure Initialize; override;
procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override;
procedure Shutdown; override;
procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override;
end;
implementation
uses
{$INCLUDE 'OpenGL.inc'}
System.UITypes;
{ TCartoonSunApp }
procedure TCartoonSunApp.Initialize;
const
RECTANGLE_VERTS: array [0..3] of TVector2 = (
(X: -1; Y: -1),
(X: -1; Y: 1),
(X: 1; Y: -1),
(X: 1; Y: 1));
var
VertexShader, FragmentShader: TGLShader;
VertAttr: TGLVertexAttrib;
Uniform: TGLUniform;
begin
VertexShader.New(TGLShaderType.Vertex,
'attribute vec2 Position;'#10+
'varying vec2 vertPos;'#10+
'void main(void)'#10+
'{'#10+
' gl_Position = vec4(Position, 0.0, 1.0);'#10+
' vertPos = gl_Position.xy;'#10+
'}');
VertexShader.Compile;
FragmentShader.New(TGLShaderType.Fragment,
'precision mediump float;'#10+
'uniform float Time;'#10+
'uniform vec2 SunPos;'#10+
'uniform vec3 Sun1, Sun2, Sky1, Sky2;'#10+
'varying vec2 vertPos;'#10+
'void main(void)'#10+
'{'#10+
' vec2 v = vertPos - SunPos;'#10+
' float l = length(v);'#10+
' float a = (sin(l) + atan(v.y, v.x)) / 3.1415;'#10+
' if (l < 0.1)'#10+
' {'#10+
' gl_FragColor = vec4(Sun1, 1.0);'#10+
' }'#10+
' else if (floor(mod(18.0 * (Time * 0.1 + 1.0 + a), 2.0)) == 0.0)'#10+
' {'#10+
' gl_FragColor = vec4(mix(Sun1, Sun2, l), 1.0);'#10+
' }'#10+
' else'#10+
' {'#10+
' gl_FragColor = vec4(mix(Sky1, Sky2, l), 1.0);'#10+
' }'#10+
'}');
FragmentShader.Compile;
FProgram.New(VertexShader, FragmentShader);
FProgram.Link;
VertexShader.Delete;
FragmentShader.Delete;
FProgram.Use;
{ Positions }
FVerts.New(TGLBufferType.Vertex);
FVerts.Bind;
FVerts.Data(RECTANGLE_VERTS);
VertAttr.Init(FProgram, 'Position');
VertAttr.SetConfig<TVector2>;
VertAttr.Enable;
{ Uniforms }
FUniTime.Init(FProgram, 'Time');
FUniSunPos.Init(FProgram, 'SunPos');
Uniform.Init(FProgram, 'Sun1');
Uniform.SetValue(Vector3(0.95, 0.85, 0.60));
Uniform.Init(FProgram, 'Sun2');
Uniform.SetValue(Vector3(0.90, 0.80, 0.20));
Uniform.Init(FProgram, 'Sky1');
Uniform.SetValue(Vector3(0.90, 0.80, 0.50));
Uniform.Init(FProgram, 'Sky2');
Uniform.SetValue(Vector3(0.80, 0.60, 0.40));
gl.Disable(TGLCapability.DepthTest);
end;
procedure TCartoonSunApp.KeyDown(const AKey: Integer; const AShift: TShiftState);
begin
{ Terminate app when Esc key is pressed }
if (AKey = vkEscape) then
Terminate;
end;
procedure TCartoonSunApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double);
var
Angle, S, C: Single;
begin
{ Clear the color buffer }
gl.Clear([TGLClear.Color]);
{ Use the program }
FProgram.Use;
{ Update uniforms }
FUniTime.SetValue(ATotalTimeSec);
Angle := ATotalTimeSec * Pi * 0.1;
FastSinCos(Angle, S, C);
FUniSunPos.SetValue(-C, S);
{ Draw the rectangle }
gl.DrawArrays(TGLPrimitiveType.TriangleStrip, 4);
end;
procedure TCartoonSunApp.Shutdown;
begin
{ Release resources }
FVerts.Delete;
FProgram.Delete;
end;
end.
|
unit TestUnmarshalAddressBookContactUnit;
interface
uses
TestFramework, SysUtils,
TestBaseJsonUnmarshalUnit,
System.Generics.Collections,
IAddressBookContactProviderUnit;
type
TTestUnmarshalAddressBookContact = class(TTestBaseJsonUnmarshal)
private
procedure CheckEquals(Etalon: IAddressBookContactProvider; TestName: String); overload;
published
procedure DefaultAddressBookContact();
procedure FullAddressBookContact();
procedure RealAddressBookContact();
procedure AddressBookContactFindResponse;
end;
implementation
{ TTestOptimizationParametersToJson }
uses
Classes, System.JSON,
DefaultAddressBookContactProviderUnit, FullAddressBookContactProviderUnit,
AddressBookContactUnit, MarshalUnMarshalUnit,
RealAddressBookContactProviderUnit, AddressBookContactFindResponseUnit;
procedure TTestUnmarshalAddressBookContact.AddressBookContactFindResponse;
const
s = '{"results":[[6601883,"Some address3916589616287113937","John6129484611666145821"],' +
'[7681272,"100 Ogle St, Johnstown, PA 15905, USA",""]],"total":142,"fields":["address_id","first_name","address_1"]}';
var
Response: TAddressBookContactFindResponse;
JsonValue: TJSONValue;
begin
JsonValue := TJSONObject.ParseJSONValue(s);
try
Response := TMarshalUnMarshal.FromJson(
TAddressBookContactFindResponse, JsonValue) as TAddressBookContactFindResponse;
try
CheckNotNull(Response);
CheckEquals(142, Response.Total);
CheckEquals(3, Length(Response.Fields));
CheckEquals('address_id', Response.Fields[0]);
CheckEquals('first_name', Response.Fields[1]);
CheckEquals('address_1', Response.Fields[2]);
CheckEquals(2, Length(Response.Results));
CheckEquals(3, Length(Response.Results[0]));
CheckEquals('6601883', Response.Results[0][0]);
CheckEquals('Some address3916589616287113937', Response.Results[0][1]);
CheckEquals('John6129484611666145821', Response.Results[0][2]);
CheckEquals(3, Length(Response.Results[1]));
CheckEquals('7681272', Response.Results[1][0]);
CheckEquals('100 Ogle St, Johnstown, PA 15905, USA', Response.Results[1][1]);
CheckEquals('', Response.Results[1][2]);
finally
FreeAndNil(Response);
end;
finally
FreeAndNil(JsonValue);
end;
end;
procedure TTestUnmarshalAddressBookContact.CheckEquals(
Etalon: IAddressBookContactProvider; TestName: String);
var
ActualList: TStringList;
Actual: TAddressBookContact;
JsonFilename: String;
AddressBookContact: TAddressBookContact;
JsonValue: TJSONValue;
begin
JsonFilename := EtalonFilename(TestName);
ActualList := TStringList.Create;
try
ActualList.LoadFromFile(JsonFilename);
JsonValue := TJSONObject.ParseJSONValue(ActualList.Text);
try
AddressBookContact := Etalon.AddressBookContact;
Actual := TMarshalUnMarshal.FromJson(
AddressBookContact.ClassType, JsonValue) as TAddressBookContact;
try
CheckTrue(AddressBookContact.Equals(Actual));
finally
FreeAndNil(Actual);
FreeAndNil(AddressBookContact);
end;
finally
FreeAndNil(JsonValue);
end;
finally
FreeAndNil(ActualList);
end;
Etalon := nil;
end;
procedure TTestUnmarshalAddressBookContact.DefaultAddressBookContact;
begin
CheckEquals(
TDefaultAddressBookContactProvider.Create,
'AddressBookContactToJson\DefaultAddressBookContact');
end;
procedure TTestUnmarshalAddressBookContact.FullAddressBookContact;
begin
CheckEquals(
TFullAddressBookContactProvider.Create,
'AddressBookContactToJson\FullAddressBookContact');
end;
procedure TTestUnmarshalAddressBookContact.RealAddressBookContact;
begin
CheckEquals(
TRealAddressBookContactProvider.Create,
'AddressBookContactToJson\RealAddressBookContact');
end;
initialization
// Register any test cases with the test runner
RegisterTest('JSON\Unmarshal\', TTestUnmarshalAddressBookContact.Suite);
end.
|
unit constants;
{$ifdef fpc}
{$mode delphi}
{$endif}
interface
uses Classes, Graphics;
{*******************************************************************
* Main data structures
*******************************************************************}
type
{ Base data structures for components }
PTCElement = ^TCElement;
TCElement = object
Pos: TPoint;
Next, Previous: PTCElement;
end;
{ Data structures for components }
TCDataString = array[0..50] of Char;
TCComponentOrientation = (coEast = 0, coNorth = 1, coWest = 2, coSouth = 3);
PTCComponent = ^TCComponent;
TCComponent = object(TCElement)
Name: TCDataString;
TypeID: TCDataString;
Orientation: TCComponentOrientation;
end;
{ Data structures for wires }
PTCWire = ^TCWire;
TCWire = object(TCElement)
PtTo: TPoint;
end;
{ Data structures for text }
PTCText = ^TCText;
TCText = object(TCElement)
BottomRight: TPoint;
Text: shortstring;
end;
{ Data structures for polyline }
PTCPolyline = ^TCPolyline;
TCPolyline = object(TCElement)
NPoints: Word;
Width: Word;
Color: TColor;
PenStyle: TPenStyle;
PenEndCap: TPenEndCap;
PenJoinStyle: TPenJoinStyle;
Points: array[0..255] of TPoint;
end;
{ Data structures for embedded raster images }
PTCRasterImage = ^TCRasterImage;
TCRasterImage = object(TCElement)
Proportion: Single; // in percentage, standard=1.0
Angle: Single; // In radians
ImageData: TPicture;
end;
{ Data structures for tools }
TCTool = (
// Circuits tools
toolArrow = 0, toolComponent, toolWire, toolText,
// 2D CAD tools
toolPolyline, toolRasterImage, toolEllipse,
toolRectangle
);
{*******************************************************************
* Element verification constants
*******************************************************************}
const
ELEMENT_DOES_NOT_MATCH = 0;
ELEMENT_MATCHES = 1;
ELEMENT_START_POINT = 2;
ELEMENT_END_POINT = 3;
{*******************************************************************
* General use data structures
*******************************************************************}
type
{ Used by tcutils.SeparateString }
T10Strings = array[0..9] of shortstring;
{ Used by CalculateCoordinate }
TFloatPoint = record
X, Y: Double;
end;
{*******************************************************************
* Drawing code commands
*******************************************************************}
const
STR_DRAWINGCODE_LINE = 'LINE';
STR_DRAWINGCODE_TEXT = 'TEXT';
STR_DRAWINGCODE_ARC = 'ARC';
STR_DRAWINGCODE_TRIANGLE = 'TRIANGLE';
STR_DRAWINGCODE_IC = 'IC';
STR_DRAWINGCODE_IC_TEXT_LEFT_1 = 'IC_TEXT_LEFT_1';
STR_DRAWINGCODE_IC_TEXT_LEFT_2 = 'IC_TEXT_LEFT_2';
STR_DRAWINGCODE_IC_TEXT_RIGHT_1 = 'IC_TEXT_RIGHT_1';
STR_DRAWINGCODE_IC_TEXT_RIGHT_2 = 'IC_TEXT_RIGHT_2';
{*******************************************************************
* Database field names
*******************************************************************}
const
STR_DB_COMPONENTS_FILE = 'components.dat';
STR_DB_COMPONENTS_TABLE = 'Components';
STR_DB_COMPONENTS_ID = 'ID';
STR_DB_COMPONENTS_NAMEEN = 'NAMEEN';
STR_DB_COMPONENTS_NAMEPT = 'NAMEPT';
STR_DB_COMPONENTS_DRAWINGCODE = 'DRAWINGCODE';
STR_DB_COMPONENTS_HEIGHT = 'HEIGHT';
STR_DB_COMPONENTS_WIDTH = 'WIDTH';
STR_DB_COMPONENTS_PINS = 'PINS';
{*******************************************************************
* StatusBar panel identifiers
*******************************************************************}
const
ID_STATUS_MOUSEPOS = 0;
{*******************************************************************
* General User Interface constants
*******************************************************************}
const
INT_SHEET_DEFAULT_GRID_SPACING = 10;
INT_SHEET_MAX_WIDTH = 1000;
INT_SHEET_MAX_HEIGHT = 1000;
INT_SHEET_DEFAULT_WIDTH = 500;
INT_SHEET_DEFAULT_HEIGHT = 500;
INT_TOOLSNOTEBOOK_ARROW = 0;
INT_TOOLSNOTEBOOK_COMPONENTS = 1;
INT_TOOLSNOTEBOOK_WIRE = 2;
INT_TOOLSNOTEBOOK_TEXT = 3;
INT_TOOLSNOTEBOOK_POLYLINE = 4;
INT_TOOLSNOTEBOOK_RASTERIMAGE= 5;
var
INT_SHEET_GRID_SPACING: Cardinal = INT_SHEET_DEFAULT_GRID_SPACING;
INT_SHEET_GRID_HALFSPACING: Cardinal = INT_SHEET_DEFAULT_GRID_SPACING div 2;
{*******************************************************************
* Strings not to be translated
*******************************************************************}
const
szAppTitle = 'Turbo Circuits and Vectors';
lpSeparator = '-';
lpComma = ',';
lpSpace = ' ';
lpEnglish = 'English';
lpPortugues = 'Português';
{$ifdef GoboLinux}
DefaultDirectory = '/Programs/TurboVectors/0.1/';
{$else}
DefaultDirectory = '/usr/share/turbovectors/';
{$endif}
BundleResourcesDirectory = '/Contents/Resources/';
SectionUnix = 'Unix';
IdentMyDirectory = 'MyDirectory';
implementation
end.
|
unit uRelResumoMensal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uModeloRel, DB, ZConnection, ACBrBase, ACBrEnterTab, frxClass,
frxDBSet, ZAbstractRODataset, ZDataset, frxExportPDF, StdCtrls, Mask,
JvExMask, JvToolEdit, ExtCtrls, JvExControls, JvNavigationPane, Buttons, DateUtils;
type
TfrmRelResumoMensal = class(TfrmModeloRel)
JvNavPanelHeader1: TJvNavPanelHeader;
Bevel1: TBevel;
Bevel2: TBevel;
Label3: TLabel;
Label1: TLabel;
Label2: TLabel;
d02: TJvDateEdit;
d01: TJvDateEdit;
ckLucro: TCheckBox;
frxPDFExport1: TfrxPDFExport;
qrRelatorio: TZReadOnlyQuery;
frxRelatorio: TfrxReport;
frxDBRelatorio: TfrxDBDataset;
ACBrEnterTab1: TACBrEnterTab;
qrRelatorionome_empresa: TStringField;
qrRelatoriosite_empresa: TStringField;
qrRelatoriotelefone_empresa: TStringField;
qrRelatorioendereco_empresa: TStringField;
qrRelatoriocomplemento_empresa: TStringField;
qrRelatorioid: TLargeintField;
qrRelatoriotipo_conta: TIntegerField;
qrRelatorionome_conta: TStringField;
qrRelatoriotipo: TSmallintField;
qrRelatoriodata: TDateField;
qrRelatorionumero: TLargeintField;
qrRelatorioFavorecido: TStringField;
qrRelatoriohistorico: TStringField;
qrRelatoriovalor: TFloatField;
qrRelatoriocredito: TFloatField;
qrRelatoriodebito: TFloatField;
qrRelatoriosaldo: TFloatField;
qrRelatoriocidade_empresa: TStringField;
qrRelatoriouf_empresa: TStringField;
qrRelatoriocep_empresa: TStringField;
ckUnir: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
procedure frxRelatorioGetValue(const VarName: String;
var Value: Variant);
procedure d01Change(Sender: TObject);
private
{ Private declarations }
procedure Relatorio;
public
{ Public declarations }
end;
var
frmRelResumoMensal: TfrmRelResumoMensal;
implementation
uses
funcoes, udmPrincipal;
{$R *.dfm}
procedure TfrmRelResumoMensal.FormCreate(Sender: TObject);
begin
inherited;
d01.Date := StartOfTheMonth(dmPrincipal.SoData);
d02.Date := EndOfTheMonth(dmPrincipal.SoData);
end;
procedure TfrmRelResumoMensal.Relatorio;
begin
try
if (d01.Date = 0) and (d02.Date = 0) then
begin
Application.MessageBox('A data é obrigatória!', 'Atenção', MB_ICONERROR);
Exit;
end;
qrRelatorio.Close;
qrRelatorio.SQL.Clear;
qrRelatorio.SQL.Add('select');
qrRelatorio.SQL.Add('e.fantasia as nome_empresa, e.site as site_empresa, e.telefone as telefone_empresa,');
qrRelatorio.SQL.Add('concat(e.logradouro,", ",e.numero) as endereco_empresa,');
qrRelatorio.SQL.Add('e.complemento as complemento_empresa,');
qrRelatorio.SQL.Add('e.cidade as cidade_empresa, e.uf as uf_empresa, e.cep as cep_empresa,');
qrRelatorio.SQL.Add('cc.id, cco.tipo_conta,cco.nome_conta, cc.tipo, cc.data, cc.numero, cf.fantasia as Favorecido,');
qrRelatorio.SQL.Add('cc.historico, cc.valor,sum(cast(if(cc.tipo in(0,2),cc.valor,NULL)as DECIMAL(10,2))) as credito, sum(cast(if(cc.tipo in(1,3),cc.valor,NULL)as DECIMAL(10,2))) as debito,');
qrRelatorio.SQL.Add('@saldo:=@saldo+if(cc.tipo in(0,2),cc.valor,-cc.valor)saldo');
qrRelatorio.SQL.Add(' from mov_contacorrente as cc');
qrRelatorio.SQL.Add(' left join clientes_fornecedores cf on cc.cliente_codigo=cf.codigo and cc.cliente_filial=cf.filial');
qrRelatorio.SQL.Add(' left join conta_corrente cco on cco.codigo=cc.cc_codigo');
qrRelatorio.SQL.Add(' left join empresas e on cc.empresa_codigo=e.codigo');
qrRelatorio.SQL.Add('where');
qrRelatorio.SQL.Add('cc.tipo in (0,1)');
qrRelatorio.SQL.Add('and isnull(cc.data_exc)');
//Se o componente estiver marcado, desconsiderará as contas de Lucro
if ckLucro.Checked = True then
qrRelatorio.SQL.Add('and cco.tipo_conta not in (5,8)');
// Se o componente estiver marcado, então o relatório unirá todas as empresas
if ckUnir.Checked = False then
begin
qrRelatorio.SQL.add('and cc.empresa_codigo=:EmpresaLogada');
qrRelatorio.ParamByName('EmpresaLogada').AsInteger := dmPrincipal.empresa_login;
end;
if (d01.Date <> 0) and (d02.Date = 0) then
begin
qrRelatorio.SQL.add('and cc.data=:data1');
qrRelatorio.ParamByName('data1').AsDate := d01.Date;
end
else if (d01.Date > 0) and (d02.Date > 0) then
begin
qrRelatorio.SQL.add('and cc.data between :data1 and :data2');
qrRelatorio.ParamByName('data1').AsDate := d01.Date;
qrRelatorio.ParamByName('data2').AsDate := d02.Date;
end;
qrRelatorio.Open;
if qrRelatorio.IsEmpty then
begin
Application.MessageBox('Não há dados para esse relatório!', 'Atenção', MB_ICONERROR);
Exit;
end
else
begin
frxRelatorio.ShowReport;
end;
finally
qrRelatorio.Close;
end
end;
procedure TfrmRelResumoMensal.btnImprimirClick(Sender: TObject);
begin
inherited;
Relatorio;
end;
procedure TfrmRelResumoMensal.frxRelatorioGetValue(const VarName: String;
var Value: Variant);
var
s: string;
begin
inherited;
if (d01.Date <> 0) and (d02.Date = 0) then
s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date))
else if (d01.Date > 0) and (d02.Date > 0) then
s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date), ' Até ', formatdatetime('dd/mm/yyyy', d02.Date));
if CompareText(VarName, 'periodo') = 0 then
Value := s;
end;
procedure TfrmRelResumoMensal.d01Change(Sender: TObject);
begin
inherited;
d02.date := EndOfTheMonth(d01.Date);
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clNntpFileHandler;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
{$IFDEF DELPHI7}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF}
uses
{$IFNDEF DELPHIXE2}
Classes, Windows, SysUtils, SyncObjs,
{$ELSE}
System.Classes, Winapi.Windows, System.SysUtils, System.SyncObjs,
{$ENDIF}
clNntpServer;
type
TclNntpFileHandler = class(TComponent)
private
FServer: TclNntpServer;
FRootDir: string;
FAccessor: TCriticalSection;
FCounter: Integer;
procedure SetServer(const Value: TclNntpServer);
procedure SetRootDir(const Value: string);
procedure SetCounter(const Value: Integer);
function GetGroupPath(const AGroupName: string): string;
function CreateArticleItem(const AFileName: string): TclNntpArticleItem;
procedure CollectArticles(Articles: TclNntpArticleList; const APath: string; ADate: TDateTime; AGMT: Boolean);
function GenerateArticleName(ArticleNo: Integer; const AMessageID: string): string;
procedure DoGetGroupInfo(Sender: TObject; AConnection: TclNntpCommandConnection;
AGroup: TclNewsGroupItem; var ArticleCount, ALastArticle, AFirstArticle: Integer);
procedure DoGetArticles(Sender: TObject; AConnection: TclNntpCommandConnection;
AGroup: TclNewsGroupItem; ADate: TDateTime; AGMT: Boolean; const ADistributions: string; Articles: TclNntpArticleList);
procedure DoGetArticleSource(Sender: TObject; AConnection: TclNntpCommandConnection;
AGroup: TclNewsGroupItem; var ArticleNo: Integer; var AMessageID: string; ArticleSource: TStrings; var Success: Boolean);
procedure DoArticleReceived(Sender: TObject; AConnection: TclNntpCommandConnection;
AGroup: TclNewsGroupItem; const AMessageID: string; ArticleSource: TStrings; var Success: Boolean);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure CleanEventHandlers; virtual;
procedure InitEventHandlers; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Server: TclNntpServer read FServer write SetServer;
property RootDir: string read FRootDir write SetRootDir;
property Counter: Integer read FCounter write SetCounter default 0;
end;
var
cMaxTryCount: Integer = 1000;
implementation
uses
clUtils, clEncoder;
{ TclNntpFileHandler }
procedure TclNntpFileHandler.CleanEventHandlers;
begin
Server.OnGetGroupInfo := nil;
Server.OnGetArticles := nil;
Server.OnGetArticleSource := nil;
Server.OnArticleReceived := nil;
end;
procedure TclNntpFileHandler.CollectArticles(Articles: TclNntpArticleList; const APath: string; ADate: TDateTime; AGMT: Boolean);
var
searchRec: TSearchRec;
fileDate: TDateTime;
item: TclNntpArticleItem;
begin
if {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindFirst(AddTrailingBackSlash(APath) + '*.MSG', 0, searchRec) = 0 then
begin
repeat
fileDate := ConvertFileTimeToDateTime(searchRec.FindData.ftLastWriteTime);
if AGMT then
begin
fileDate := LocalTimeToGlobalTime(fileDate);
end;
if (fileDate >= ADate) then
begin
item := CreateArticleItem(searchRec.Name);
if (item <> nil) then
begin
articles.Add(item);
end;
end;
until ({$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindNext(searchRec) <> 0);
{$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(searchRec);
end;
end;
constructor TclNntpFileHandler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAccessor := TCriticalSection.Create();
end;
function TclNntpFileHandler.CreateArticleItem(const AFileName: string): TclNntpArticleItem;
var
articleNo: Integer;
messageID: string;
begin
Result := nil;
if (WordCount(AFileName, ['_', '.']) <> 3) then Exit;
articleNo := StrToIntDef(ExtractWord(1, AFileName, ['_', '.']), 0);
messageID := TclEncoder.Decode(ExtractWord(2, AFileName, ['_', '.']), cmBase64);
if ((articleNo < 1) or (messageID = '')) then Exit;
Result := TclNntpArticleItem.Create(articleNo, messageID);
end;
destructor TclNntpFileHandler.Destroy;
begin
FAccessor.Free();
inherited Destroy();
end;
procedure TclNntpFileHandler.DoArticleReceived(Sender: TObject; AConnection: TclNntpCommandConnection; AGroup: TclNewsGroupItem;
const AMessageID: string; ArticleSource: TStrings; var Success: Boolean);
var
i: Integer;
path, msgFileName: string;
begin
Success := False;
path := AddTrailingBackSlash(GetGroupPath(AGroup.Name));
FAccessor.Enter();
try
i := 0;
while (True) do
begin
Inc(FCounter);
msgFileName := path + GenerateArticleName(FCounter, AMessageID);
try
if (not FileExists(msgFileName)) then
begin
TclStringsUtils.SaveStrings(ArticleSource, msgFileName, '');
Success := True;
Break;
end;
except
on EStreamError do;
end;
Inc(i);
if (i > cMaxTryCount) then
begin
raise Exception.Create('Cannot save new message');
end;
end;
finally
FAccessor.Leave();
end;
end;
procedure TclNntpFileHandler.DoGetArticles(Sender: TObject; AConnection: TclNntpCommandConnection; AGroup: TclNewsGroupItem;
ADate: TDateTime; AGMT: Boolean; const ADistributions: string; Articles: TclNntpArticleList);
var
path: string;
begin
path := GetGroupPath(AGroup.Name);
CollectArticles(Articles, path, ADate, AGMT);
end;
procedure TclNntpFileHandler.DoGetArticleSource(Sender: TObject; AConnection: TclNntpCommandConnection; AGroup: TclNewsGroupItem;
var ArticleNo: Integer; var AMessageID: string; ArticleSource: TStrings; var Success: Boolean);
var
path, fileName: string;
articles: TclNntpArticleList;
article: TclNntpArticleItem;
begin
path := GetGroupPath(AGroup.Name);
articles := nil;
try
articles := TclNntpArticleList.Create();
CollectArticles(articles, path, 0, False);
article := nil;
if (ArticleNo > 0) then
begin
article := articles.FindArticle(ArticleNo);
end else
if (AMessageID <> '') then
begin
article := articles.FindArticle(AMessageID);
end;
if (article = nil) then
begin
Success := False;
Exit;
end;
ArticleNo := article.ArticleNo;
AMessageID := article.MessageID;
fileName := AddTrailingBackSlash(path) + GenerateArticleName(ArticleNo, AMessageID);
TclStringsUtils.LoadStrings(fileName, ArticleSource, '');
Success := True;
finally
articles.Free();
end;
end;
procedure TclNntpFileHandler.DoGetGroupInfo(Sender: TObject; AConnection: TclNntpCommandConnection; AGroup: TclNewsGroupItem;
var ArticleCount, ALastArticle, AFirstArticle: Integer);
var
path: string;
articles: TclNntpArticleList;
begin
path := GetGroupPath(AGroup.Name);
articles := TclNntpArticleList.Create();
try
CollectArticles(articles, path, 0, False);
ArticleCount := articles.Count;
AFirstArticle := 0;
ALastArticle := 0;
if (articles.Count > 0) then
begin
AFirstArticle := articles[0].ArticleNo;
ALastArticle := articles[articles.Count - 1].ArticleNo;
end;
finally
articles.Free();
end;
end;
function TclNntpFileHandler.GenerateArticleName(ArticleNo: Integer; const AMessageID: string): string;
begin
Result := Format('%.7d', [ArticleNo]) + '_' + TclEncoder.EncodeToString(AMessageID, cmBase64) + '.MSG';
end;
function TclNntpFileHandler.GetGroupPath(const AGroupName: string): string;
begin
Result := AddTrailingBackSlash(RootDir);
Result := Result + StringReplace(AGroupName, '.', '_', [rfReplaceAll]);
Result := AddTrailingBackSlash(Result);
FAccessor.Enter();
try
if (not DirectoryExists(Result)) then
begin
ForceFileDirectories(Result);
end;
finally
FAccessor.Leave();
end;
end;
procedure TclNntpFileHandler.InitEventHandlers;
begin
Server.OnGetGroupInfo := DoGetGroupInfo;
Server.OnGetArticles := DoGetArticles;
Server.OnGetArticleSource := DoGetArticleSource;
Server.OnArticleReceived := DoArticleReceived;
end;
procedure TclNntpFileHandler.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation <> opRemove) then Exit;
if (AComponent = FServer) then
begin
CleanEventHandlers();
FServer := nil;
end;
end;
procedure TclNntpFileHandler.SetCounter(const Value: Integer);
begin
FAccessor.Enter();
try
FCounter := Value;
finally
FAccessor.Leave();
end;
end;
procedure TclNntpFileHandler.SetRootDir(const Value: string);
begin
FAccessor.Enter();
try
FRootDir := Value;
finally
FAccessor.Leave();
end;
end;
procedure TclNntpFileHandler.SetServer(const Value: TclNntpServer);
begin
if (FServer <> Value) then
begin
if (FServer <> nil) then
begin
FServer.RemoveFreeNotification(Self);
CleanEventHandlers();
end;
FServer := Value;
if (FServer <> nil) then
begin
FServer.FreeNotification(Self);
InitEventHandlers();
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ Zlot programistów Delphi }
{ RTTI w Delph }
{ Sylwester Wojnar }
{ }
{ Mszczonów 2019 }
{*******************************************************}
unit demortti.vehicles;
interface
uses
demortti.db;
type
TColor = (Grean, Red, Yellow, Silver, Gold, Black);
TVehicleType = (Car, Truck, Bus);
TVehicle = class
private
FId: Integer;
FVin: String;
FBrand: String;
FColor: TColor;
FKind: TVehicleType;
FNew: Boolean;
public
[DBField(1, TDataType.AutoInc)]
property Id: Integer read FId write FId;
[DBField(0, TDataType.Varchar, 32)]
property Brand: String read FBrand write FBrand;
[DBField(0, TDataType.Varchar, 17)]
property Vin: String read FVin write FVin;
[DBField(0, TDataType.Varchar, 8)]
property Color: TColor read FColor write FColor;
[DBField(0, TDataType.Varchar, 8)]
property Kind: TVehicleType read FKind write FKind;
property New: Boolean read FNew write FNew;
end;
TCustomer = class
private
FName: String;
FId: Integer;
FVehicles: TArray<TVehicle>;
public
property Id: Integer read FId write FId;
property Name: String read FName write FName;
property Vehicles: TArray<TVehicle> read FVehicles write FVehicles;
end;
implementation
end.
|
unit ResearchCenter;
interface
uses
Protocol, WorkCenterBlock, Kernel, Collection, Classes, CacheAgent,
BackupInterfaces, Accounts, Inventions;
type
TCollection = Collection.TCollection;
const
tidURL_SpecialMailMessages = 'Visual/Voyager/Mail/SpecialMessages/';
tidMailMsgURL_NoMoneyRes = tidURL_SpecialMailMessages + 'MsgNoMoneyForResearch.asp';
type
TMetaResearchCenter =
class( TMetaWorkCenter )
public
constructor Create( anId : string;
aCapacities : array of TFluidValue;
aInventionKind : string;
aBlockClass : CBlock );
destructor Destroy; override;
private
fInventionKind : string;
fInventions : TCollection;
fStandalone : boolean;
private
function GetMinimalWorkForce( kind : TPeopleKind ) : TFluidValue;
public
property InventionKind : string read fInventionKind;
property MinimalWorkForce[kind : TPeopleKind] : TFluidValue read GetMinimalWorkForce;
property Standalone : boolean read fStandalone write fStandalone;
public
procedure RegisterInvention(Invention : TInvention);
procedure RegisterInventions(Inventions : array of TInvention);
private
function GetInventionCount : integer;
function GetInvention( index : integer ) : TInvention;
public
property InventionCount : integer read GetInventionCount;
property Inventions[index : integer] : TInvention read GetInvention;
public
function FindInvention(id : string) : TInvention;
end;
TDevelopingResearch =
class
public
constructor Create( anInv : TInvention; aPrior : byte );
private
fInvention : TInvention;
fPriority : byte;
end;
TResearchCenter =
class( TFinanciatedWorkCenter )
public
constructor Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); override;
destructor Destroy; override;
public
procedure Stop; override;
private
procedure StartResearch;
procedure InsertResearch(DevRes : TDevelopingResearch);
function CanResearch(InventionId : TInventionNumId) : boolean;
published
procedure ResearchInvention(Invention : TInvention; Priority : integer);
procedure RestoreResearch(InventionId : string; Priority : integer);
procedure QueueResearch(InventionId : string; Priority : integer);
procedure CancelResearch(InventionId : string);
procedure RDOQueueResearch(InventionId : widestring; Priority : integer);
procedure RDOCancelResearch(InventionId : widestring);
function RDOGetInvProps(InventionId : widestring) : olevariant;
function RDOGetInvPropsByLang(InventionId, lang : widestring) : olevariant;
function RDOGetInvDesc(InventionId : widestring) : olevariant;
function RDOGetInvDescEx(InventionId, LangId : widestring) : olevariant;
protected
fCurrResearch : TDevelopingResearch;
fProgress : single;
fDirCoverage : word;
fDevResearches : TCollection;
fWFError : single;
fCompanyDirection : TCompanyDirection;
protected
function Evaluate : TEvaluationResult; override;
function GetVisualClassId : TVisualClassId; override;
function GetUpgradeCost : TMoney; override;
function GetActualMaxUpgrade : integer; override;
public
procedure AutoConnect( loaded : boolean ); override;
published
function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override;
public
procedure BlockLoaded; override;
procedure StoreToCache ( Cache : TObjectCache ); override;
procedure LoadFromBackup( Reader : IBackupReader ); override;
procedure StoreToBackup ( Writer : IBackupWriter ); override;
private
function GetResearch( index : integer ) : TDevelopingResearch;
function GetResearchById( InventionId : TInventionNumId ) : TDevelopingResearch;
public
property Researches[index : integer] : TDevelopingResearch read GetResearch;
property ResearchById[InventionId : TInventionNumId] : TDevelopingResearch read GetResearchById;
private
procedure CheckResearches;
protected
function RenderCloneMenu(lang : string) : string; override;
end;
const
PeopleToStrength : array[TPeopleKind] of single = (60, 30, 6);
StandaloneHQPeopleToStrength : array[TPeopleKind] of single = (200, 100, 50);
const
WorkforceOpenRatio = 1;
WorkforceCloseRatio = 1;
BasicWorkforce = 0.1;
procedure RegisterBackup;
implementation
uses
ClassStorage, SysUtils, MathUtils, Population, SimHints, BasicAccounts, Logs,
Languages, ModelServerCache, CloneOptions;
const
WFErrorDelta = 0.1;
// TMetaResearchCenter
constructor TMetaResearchCenter.Create( anId : string; aCapacities : array of TFluidValue; aInventionKind : string; aBlockClass : CBlock );
begin
inherited Create( anId, aCapacities, accIdx_ResearchCenter_Supplies, accIdx_None, accIdx_ResearchCenter_Salaries, aBlockClass );
fInventionKind := aInventionKind;
fInventions := TCollection.Create(0, rkUse);
MaxUpgrade := StrToInt(TheGlobalConfigHandler.GetConfigParm('MaxRCenterUpgrade', '20'));
end;
destructor TMetaResearchCenter.Destroy;
begin
fInventions.Free;
inherited;
end;
function TMetaResearchCenter.GetMinimalWorkForce( kind : TPeopleKind ) : TFluidValue;
begin
result := BasicWorkForce*Capacity[kind];
end;
procedure TMetaResearchCenter.RegisterInvention(Invention : TInvention);
begin
fInventions.Insert(Invention);
if fInventionKind <> ''
then fInventionKind := Invention.Kind;
end;
procedure TMetaResearchCenter.RegisterInventions(Inventions : array of TInvention);
var
i : integer;
begin
for i := low(Inventions) to high(Inventions) do
RegisterInvention( Inventions[i] );
end;
function TMetaResearchCenter.GetInventionCount : integer;
begin
result := fInventions.Count;
end;
function TMetaResearchCenter.GetInvention( index : integer ) : TInvention;
begin
result := TInvention(fInventions[index]);
end;
function TMetaResearchCenter.FindInvention(id : string) : TInvention;
var
i : integer;
begin
i := pred(fInventions.Count);
while (i >= 0) and (Inventions[i].Id <> id) do
dec(i);
if i >= 0
then result := Inventions[i]
else result := nil;
end;
// TDevelopingResearch
constructor TDevelopingResearch.Create( anInv : TInvention; aPrior : byte );
begin
inherited Create;
fInvention := anInv;
fPriority := aPrior;
end;
// TResearchCenter
constructor TResearchCenter.Create( aMetaBlock : TMetaBlock; aFacility : TFacility );
begin
inherited;
fDevResearches := TCollection.Create( 0, rkBelonguer );
end;
destructor TResearchCenter.Destroy;
begin
fDevResearches.Free;
inherited;
end;
procedure TResearchCenter.Stop;
begin
inherited;
fDirCoverage := 0;
end;
procedure TResearchCenter.StartResearch;
var
WorldLocator : IWorldLocator;
URL : string;
resName : string;
lang : string;
reason : string;
begin
try
Facility.Lock;
try
fCurrResearch.Free;
if fDevResearches.Count > 0
then
begin
fCurrResearch := TDevelopingResearch(fDevResearches.AtExtract(0));
if not fCurrResearch.fInvention.Enabled(Facility.Company)
then StartResearch
else
begin
// This is to avoid the start of a research if you don't have the money
if Facility.Company.Owner.Budget < (fCurrResearch.fInvention.Price + fCurrResearch.fInvention.GetFeePrice(Facility.Company))
then
begin
if Facility.Company.Owner.Budget > fCurrResearch.fInvention.Price
then
reason := 'license'
else
reason := 'research';
Facility.UpdateCache(true);
Facility.StatusChanged(fchStructure);
WorldLocator := Facility.Town.WorldLocator;
lang := Facility.Company.Owner.Language;
resName := fCurrResearch.fInvention.Name_MLS.Values[lang];
URL := WorldLocator.GetWorldURL + '/' + lang + '/' + tidMailMsgURL_NoMoneyRes + '?Company=' + Facility.Company.Name + '&InvName='+ resName + '&TycName=' + Facility.Company.Owner.Name + '&Reason=' + reason;
WorldLocator.SendEmail('mailer@Global' + WorldLocator.GetWorldName + '.net', Facility.Company.Owner.Name + '@' + WorldLocator.GetWorldName + '.net', 'No Money for ' + resName + '!', URL); //TheModelServer.TheWorld.SendNoMoneyForResearchMsg(Facility.Company.Owner.Name, Facility.Company.Name, fCurrResearch.fInvention.Name, Facility.Company.Owner.Language);
fCurrResearch := nil;
end;
end;
end
else fCurrResearch := nil;
finally
fProgress := 0;
Facility.Unlock;
end;
except
end;
end;
procedure TResearchCenter.InsertResearch( DevRes : TDevelopingResearch );
var
i : integer;
cnt : integer;
begin
Facility.Lock;
try
cnt := fDevResearches.Count;
i := 0;
while (i < cnt) and (Researches[i].fPriority <= DevRes.fPriority) do
inc(i);
fDevResearches.AtInsert(i, DevRes);
finally
Facility.Unlock;
end;
end;
function TResearchCenter.CanResearch(InventionId : TInventionNumId) : boolean;
begin
Facility.Lock;
try
result := (ResearchById[InventionId] = nil) and ((fCurrResearch = nil) or (fCurrResearch.fInvention.NumId <> InventionId));
finally
Facility.Unlock;
end;
end;
procedure TResearchCenter.ResearchInvention(Invention : TInvention; Priority : integer);
begin
InsertResearch(TDevelopingResearch.Create(Invention, Priority));
if fCurrResearch = nil
then StartResearch;
end;
procedure TResearchCenter.RestoreResearch(InventionId : string; Priority : integer);
var
Inv : TInvention;
begin
Inv := GetInventionById(InventionId);
if Inv <> nil
then
if fCurrResearch = nil
then fCurrResearch := TDevelopingResearch.Create(Inv, Priority)
else InsertResearch(TDevelopingResearch.Create(Inv, Priority));
end;
procedure TResearchCenter.QueueResearch(InventionId : string; Priority : integer );
var
Inv : TInvention;
begin
try
Inv := GetInventionById(InventionId);
if (Inv <> nil) and CanResearch(Inv.NumId) and not Facility.Company.HasInvention[Inv.NumId] and Inv.Enabled(Facility.Company)
then
if Inv.Time > 0
then
begin
ResearchInvention(Inv, Priority);
Facility.UpdateCache(true);
end
else
if Facility.Budget >= Inv.Price + Inv.GetFeePrice(Facility.Company)
then
begin
BlockGenMoney(-Inv.Price, accIdx_ResearchCenter_Research);
Facility.Company.DeclareInvention(Inv);
Facility.UpdateCache(true);
Facility.StatusChanged(fchStructure);
end;
except
end;
end;
procedure TResearchCenter.CancelResearch(InventionId : string);
var
Inv : TInvention;
Dev : TDevelopingResearch;
begin
try
Inv := GetInventionById(InventionId);
if Inv <> nil
then
begin
if (fCurrResearch <> nil) and (fCurrResearch.fInvention.NumId = Inv.NumId)
then
begin
// Return the money spent upto now
BlockGenMoney((fProgress/100)*Inv.Price, accIdx_ResearchCenter_Research); // accIdx_Compensations
StartResearch;
end
else
begin
Dev := ResearchById[Inv.NumId];
if Dev <> nil
then
begin
Facility.Lock;
try
fDevResearches.Delete(Dev)
finally
Facility.Unlock;
end
end
else
if Facility.Company.RetireInvention(Inv)
then CheckResearches;
end;
Facility.UpdateCache(false);
Facility.StatusChanged(fchStructure);
end;
except
end;
end;
procedure TResearchCenter.RDOQueueResearch(InventionId : widestring; Priority : integer);
begin
Logs.Log( tidLog_Survival, TimeToStr(Now) + ' Queue Research: ' + InventionId + ', ' + IntToStr(Priority) );
try
if Facility.CheckOpAuthenticity
then QueueResearch(InventionId, Priority);
Logs.Log( tidLog_Survival, 'OK!');
except
Logs.Log( tidLog_Survival, 'Error!');
end;
end;
procedure TResearchCenter.RDOCancelResearch(InventionId : widestring);
begin
Logs.Log( tidLog_Survival, TimeToStr(Now) + ' Cancel Research: ' + InventionId );
try
if Facility.CheckOpAuthenticity
then CancelResearch(InventionId);
Logs.Log( tidLog_Survival, 'OK!');
except
Logs.Log( tidLog_Survival, 'Error!');
end;
end;
function TResearchCenter.RDOGetInvProps(InventionId : widestring) : olevariant;
var
Inv : TInvention;
lid : string;
begin
try
Inv := TMetaResearchCenter(MetaBlock).FindInvention(InventionId);
if Inv <> nil
then
begin
if (Facility.Company <> nil) and (Facility.Company.Owner <> nil)
then lid := Facility.Company.Owner.Language
else lid := langDefault;
result := Inv.GetClientProps(Facility.Company, lid) // >> MLS Alarm!
end
else result := '';
except
result := '';
end;
end;
function TResearchCenter.RDOGetInvPropsByLang(InventionId, lang : widestring) : olevariant;
var
Inv : TInvention;
lid : string;
begin
try
Inv := TMetaResearchCenter(MetaBlock).FindInvention(InventionId);
if Inv <> nil
then
begin
lid := lang;
if Facility.Company <> nil
then result := Inv.GetClientProps(Facility.Company, lid)
else result := '';
end
else result := '';
except
result := '';
end;
end;
function TResearchCenter.RDOGetInvDesc(InventionId : widestring) : olevariant;
var
Inv : TInvention;
begin
try
Inv := TMetaResearchCenter(MetaBlock).FindInvention(InventionId);
if Inv <> nil
then result := Inv.GetFullDesc( langDefault ) // >> MLS Alarm!
else result := '';
except
result := '';
end;
end;
function TResearchCenter.RDOGetInvDescEx(InventionId, LangId : widestring) : olevariant;
var
Inv : TInvention;
begin
try
Inv := TMetaResearchCenter(MetaBlock).FindInvention(InventionId);
if (Inv <> nil) and (LangId <> '')
then result := Inv.GetFullDesc( LangId)
else result := '';
except
result := '';
end;
end;
{
function TResearchCenter.RDOGetInvHist(InventionId : widestring) : olevariant;
var
InvRec : TInventionRecord;
begin
try
if Facility.Company <> nil
then
begin
//InvRec := Facility.Company.FindInventionRecord(InventionId);
if InvRec <> nil
then result := InvRec.Invention.Desc // >> FIX!!
else result := '';
end
else result := '';
except
result := '';
end;
end;
}
function TResearchCenter.Evaluate : TEvaluationResult;
function ComputeDirectionStrength : integer;
var
kind : TPeopleKind;
strength : single;
begin
strength := 0;
for kind := low(kind) to high(kind) do
if TMetaResearchCenter(MetaBlock).Standalone and (Workers[kind].Q > 0)
then strength := strength + StandaloneHQPeopleToStrength[kind]*sqrt(Workers[kind].Q) //sqrt(sqrt(Workers[kind].Q))
else strength := strength + PeopleToStrength[kind]*Workers[kind].Q;
result := round(strength);
end;
procedure AdjustWorkforce;
var
SupDirectionSup : single;
MB : TMetaResearchCenter;
kind : TPeopleKind;
NewStrength : integer;
lastSupport : single;
ugrLevel : byte;
begin
MB := TMetaResearchCenter(MetaBlock);
if fCompanyDirection = nil
then fCompanyDirection := Facility.Company.Directions[MB.InventionKind];
ugrLevel := max(1, UpgradeLevel);
lastSupport := fCompanyDirection.Support;
if not Facility.CriticalTrouble
then
if fCompanyDirection.Demand > 0
then
begin
if (lastSupport >= 1) and (lastSupport < 2)
then fWFError := 0
else fWFError := realmax(-2, realmin(2, fWFError + 1.5 - realmin(2, lastSupport)));
for kind := low(kind) to high(kind) do
if TMetaResearchCenter(MetaBlock).Capacity[kind] > 0
then
begin
if WorkersMax[kind].Q = 0
then WorkersMax[kind].Q := MB.MinimalWorkForce[kind]
else WorkersMax[kind].Q := realmin(ugrLevel*TMetaResearchCenter(MetaBlock).Capacity[kind], realmax(ugrLevel*MB.MinimalWorkForce[kind], WorkersMax[kind].Q + WFErrorDelta*fWFError));
end;
end
else
for kind := low(kind) to high(kind) do
if fCurrResearch <> nil
then WorkersMax[kind].Q := MB.MinimalWorkForce[kind]
else WorkersMax[kind].Q := SmartRound(0.5*MB.MinimalWorkForce[kind]);
if Facility.HasTechnology
then
begin
if Facility.CompanyDir <> nil
then SupDirectionSup := sqrt(realmin(1, Facility.CompanyDir.Support))
else SupDirectionSup := 1;
NewStrength := ComputeDirectionStrength;
fCompanyDirection.Strength := fCompanyDirection.Strength + NewStrength*SupDirectionSup;
fDirCoverage := round(100*fCompanyDirection.Support); //min(100, round(100*CompanyDirection.Support))
end
else
begin
SupDirectionSup := 0;
fDirCoverage := 0;
end;
if SupDirectionSup >= 0.9
then Facility.ClearTrouble(facNeedCompSupport)
else Facility.ReportTrouble(facNeedCompSupport);
end;
procedure StandaloneAdjustWorkforce;
var
MB : TMetaResearchCenter;
kind : TPeopleKind;
ugrLevel : byte;
begin
MB := TMetaResearchCenter(MetaBlock);
if fCompanyDirection = nil
then fCompanyDirection := Facility.Company.Directions[MB.InventionKind];
ugrLevel := max(1, UpgradeLevel);
for kind := low(kind) to high(kind) do
WorkersMax[kind].Q := ugrLevel*sqr(ugrLevel)*MB.Capacity[kind];
if Facility.HasTechnology
then
begin
fCompanyDirection.Strength := fCompanyDirection.Strength + ComputeDirectionStrength;
fDirCoverage := round(100*fCompanyDirection.Support);
end
else fDirCoverage := 0;
end;
var
kind : TPeopleKind;
hourday : single;
dtCorrection : single;
capacity : single;
cnt : integer;
ToPay : TMoney;
extraPrg : double;
begin
result := inherited Evaluate;
if TMetaResearchCenter(MetaBlock).Standalone
then StandaloneAdjustWorkforce
else AdjustWorkForce;
if not Facility.CriticalTrouble
then
if fCurrResearch <> nil
then
begin
capacity := 0;
cnt := 0;
for kind := low(kind) to high(kind) do
if TMetaResearchCenter(MetaBlock).Capacity[kind] > 0
then
begin
capacity := capacity + Workers[kind].Q/WorkersMax[kind].Q;
inc( cnt );
end;
if cnt > 0
then capacity := capacity/cnt
else capacity := 1;
hourday := Facility.Town.WorldLocator.GetHoursADay;
if hourday <> 0
then dtCorrection := realmin(5, 24/hourday)
else dtCorrection := 1;
capacity := dtCorrection*realmin(capacity, fDirCoverage/100);
fProgress := fProgress + capacity*dt; // >> You can pay more than what you are suppose to...
ToPay := fCurrResearch.fInvention.Price*capacity*dt/fCurrResearch.fInvention.Time;
BlockGenMoney( -ToPay, accIdx_ResearchCenter_Research );
if fProgress >= fCurrResearch.fInvention.Time
then
begin
extraPrg := fProgress - fCurrResearch.fInvention.Time;
BlockGenMoney(fCurrResearch.fInvention.Price*extraPrg/fCurrResearch.fInvention.Time, accIdx_ResearchCenter_Research);
Facility.Company.DeclareInvention(fCurrResearch.fInvention);
StartResearch;
ModelServerCache.UnCacheObject(self, noKind, noInfo); // Facility.UpdateCache(false); // >>
Facility.StatusChanged(fchStructure);
end;
end
else
begin
StartResearch;
if fCurrResearch <> nil
then Facility.UpdateCache(true);
end;
end;
function TResearchCenter.GetUpgradeCost : TMoney;
begin
if (Facility <> nil) and (Facility.Company <> nil)
then
begin
if fCompanyDirection = nil
then fCompanyDirection := Facility.Company.Directions[TMetaResearchCenter(MetaBlock).InventionKind];
if fCompanyDirection.Support < 1.5
then
begin
result := inherited GetUpgradeCost;
result := sqr(sqr(UpgradeLevel))*result;
end
else result := -1;
end
else result := inherited GetUpgradeCost;
end;
function TResearchCenter.GetActualMaxUpgrade : integer;
begin
if (Facility <> nil) and (Facility.Company <> nil)
then
begin
if fCompanyDirection = nil
then fCompanyDirection := Facility.Company.Directions[TMetaResearchCenter(MetaBlock).InventionKind];
if (fCompanyDirection.Support < 1.5) and (WorkForceRatioAvg > 0.90)
then result := UpgradeLevel + 1
else result := UpgradeLevel;
end
else result := inherited GetActualMaxUpgrade;
end;
function TResearchCenter.GetVisualClassId : TVisualClassId;
begin
result := min( UpgradeLevel - 1, MetaBlock.VisualStages - 1 );
end;
procedure TResearchCenter.AutoConnect( loaded : boolean );
var
kind : TPeopleKind;
WFInput : TInput;
MB : TMetaResearchCenter;
MinWF : TFluidValue;
begin
inherited;
if not loaded
then
begin
MB := TMetaResearchCenter(MetaBlock);
for kind := low(kind) to high(kind) do
begin
WFInput := InputsByName[PeopleKindPrefix[kind] + tidGate_WorkForceIn];
if WFInput <> nil
then
begin
MinWF := MB.MinimalWorkForce[kind];
WFInput.ActualMaxFluid.Q := MinWF;
WorkersMax[kind].Q := MinWF;
end;
end;
end;
end;
function TResearchCenter.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string;
begin
result := inherited GetStatusText( kind, ToTycoon );
case kind of
sttMain :
if fCurrResearch <> nil
then
result :=
result +
SimHints.GetHintText( mtidResearchMain.Values[ToTycoon.Language], [round(100*fProgress/fCurrResearch.fInvention.Time)] );
{
IntToStr(round(100*fProgress/fCurrResearch.fInvention.Time)) +
'% research completed.';
}
sttSecondary :
begin
if fCurrResearch <> nil
then
result :=
result +
SimHints.GetHintText( mtidResearchSec.Values[ToTycoon.Language], [fCurrResearch.fInvention.Name, FormatMoney(fCurrResearch.fInvention.Price)] );
{
'Researching "' + fCurrResearch.fInvention.Name + '". ' +
'Total cost: ' + IntToStr(round(fCurrResearch.fInvention.Price));
}
result := result + ' ' +
SimHints.GetHintText( mtidCompSupported.Values[ToTycoon.Language], [fDirCoverage] );
// ' Company supported at ' + IntToStr(fDirCoverage) + '%.';
end;
sttHint :
case Facility.AccessLevelOf( ToTycoon ) of
acsFull, acsModerate :
if not Facility.CriticalTrouble
then
if not Facility.HasTechnology
then result := GetHintText(mtidEvalBlockNeedTechnology.Values[ToTycoon.Language], [Facility.MetaFacility.Technology.Name])
else
if Facility.Trouble and facNeedCompSupport <> 0
then result := GetHintText( mtidNeedsCompSupport.Values[ToTycoon.Language], [0] )
else
if fCurrResearch <> nil
then
if 100*fProgress/fCurrResearch.fInvention.Time < 5
then result := GetHintText( mtidGeneralHQResearch.Values[ToTycoon.Language], [0] )
else result := GetHintText( mtidHQResearch.Values[ToTycoon.Language], [ToTycoon.Name] )
else result := GetHintText( mtidHQIdle.Values[ToTycoon.Language], [0] )
else GetHintText(mtidVisitWebSite.Values[ToTycoon.Language], [0]);
end;
end
end;
procedure TResearchCenter.BlockLoaded;
begin
inherited;
fCompanyDirection := Facility.Company.Directions[TMetaResearchCenter(MetaBlock).InventionKind]; // >> Optimizable
end;
procedure TResearchCenter.StoreToCache( Cache : TObjectCache );
var
avlCount : array[0..10] of integer;
devCount : array[0..10] of integer;
hasCount : array[0..10] of integer;
cat : integer;
catStr : string;
maxCat : integer;
Invention : TInvention;
InvRec : TInventionRecord;
MetaRC : TMetaResearchCenter;
i : integer;
iStr : string;
begin
inherited;
FillChar(avlCount, sizeof(avlCount), 0); //avlCount := 0;
FillChar(devCount, sizeof(devCount), 0); //devCount := 0;
FillChar(hasCount, sizeof(hasCount), 0); ///hasCount := 0;
MetaRC := TMetaResearchCenter(MetaBlock);
Cache.WriteString('RsKind', MetaRC.fInventionKind);
maxCat := 0;
for i := 0 to pred(MetaRC.InventionCount) do
begin
Invention := MetaRC.Inventions[i];
cat := Invention.CatPos;
catStr := IntToStr(cat);
maxCat := max(maxCat, cat);
if (fCurrResearch <> nil) and ((Invention = fCurrResearch.fInvention) or (ResearchById[Invention.NumId] <> nil))
then
begin
Invention.StoreToCache(Cache, 'dev' + catStr, devCount[cat]);
inc(devCount[cat]);
end
else
if Facility.Company.HasInvention[Invention.NumId]
then
begin
Invention.StoreToCache(Cache, 'has' + catStr, hasCount[cat]);
InvRec := Facility.Company.FindInventionRecord(Invention);
if InvRec <> nil
then Cache.WriteString('has' + catStr + 'RsCost' + IntToStr(hasCount[cat]), FormatMoney(InvRec.TotalCost - InvRec.Subsidy));
inc(hasCount[cat]);
end
else
begin
Invention.StoreToCache(Cache, 'avl' + catStr, avlCount[cat]);
Cache.WriteBoolean('avl' + catStr + 'RsEnabled' + IntToStr(avlCount[cat]), Invention.Enabled(Facility.Company));
inc(avlCount[cat]);
end;
end;
Cache.WriteInteger('CatCount', maxCat);
for i := 0 to maxCat do
begin
iStr := IntToStr(i);
Cache.WriteInteger('devCount' + iStr, devCount[i]);
Cache.WriteInteger('hasCount' + iStr, hasCount[i]);
Cache.WriteInteger('avlCount' + iStr, avlCount[i]);
end;
end;
procedure TResearchCenter.LoadFromBackup( Reader : IBackupReader );
var
InventionId : string;
i : integer;
theId : string;
prior : integer;
begin
inherited;
fDevResearches := TCollection.Create(0, rkBelonguer);
if Reader.ReadBoolean('IsRes', false)
then
begin
InventionId := Reader.ReadString('curResId', '');
RestoreResearch(InventionId, 0);
for i := 0 to pred(Reader.ReadInteger('rsCount', 0)) do
begin
theId := Reader.ReadString('Id' + IntToStr(i), '');
prior := Reader.ReadByte('Pr' + IntToStr(i), 0);
RestoreResearch(theId, prior);
end;
end;
fProgress := Reader.ReadSingle('Progress', 0);
end;
procedure TResearchCenter.StoreToBackup( Writer : IBackupWriter );
var
i : integer;
aux : string;
begin
inherited;
Writer.WriteBoolean('IsRes', fCurrResearch <> nil);
if fCurrResearch <> nil
then
begin
Writer.WriteString('curResId', fCurrResearch.fInvention.Id);
Writer.WriteInteger('rsCount', fDevResearches.Count);
for i := 0 to pred(fDevResearches.Count) do
with Researches[i] do
begin
aux := 'Id' + IntToStr(i);
Writer.WriteString(aux, fInvention.Id);
aux := 'Pr' + IntToStr(i);
Writer.WriteByte(aux, fPriority);
end;
end;
Writer.WriteSingle('Progress', fProgress);
aux := '';
end;
function TResearchCenter.GetResearch(index : integer) : TDevelopingResearch;
begin
result := TDevelopingResearch(fDevResearches[index]);
end;
function TResearchCenter.GetResearchById( InventionId : TInventionNumId ) : TDevelopingResearch;
var
i : integer;
begin
Facility.Lock;
try
i := pred(fDevResearches.Count);
while (i >= 0) and (Researches[i].fInvention.NumId <> InventionId) do
dec(i);
if i >= 0
then result := Researches[i]
else result := nil;
finally
Facility.Unlock;
end;
end;
procedure TResearchCenter.CheckResearches;
var
i : integer;
begin
Facility.Lock;
try
for i := pred(fDevResearches.Count) downto 0 do
begin
if not Researches[i].fInvention.Enabled(Facility.Company)
then fDevResearches.AtDelete(i);
end;
if (fCurrResearch <> nil) and not fCurrResearch.fInvention.Enabled(Facility.Company)
then
begin
BlockGenMoney((fProgress/100)*fCurrResearch.fInvention.Price, accIdx_ResearchCenter_Research); // accIdx_Compensations
StartResearch;
end;
finally
Facility.Unlock;
end;
end;
function TResearchCenter.RenderCloneMenu(lang : string) : string;
var
aux : string;
begin
aux := mtidResCenterCloneMenu.Values[lang];
result := inherited RenderCloneMenu(lang);
if aux <> ''
then result := result + Format(aux, [cloneOption_Suppliers]); // FIX MLS 'Suppliers|%d|'
end;
// RegisterBackup
procedure RegisterBackup;
begin
BackupInterfaces.RegisterClass( TResearchCenter );
end;
end.
|
unit Resources;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
interface
uses
Windows, Icons;
// Module mapping:
function LoadResourceModule( const FileName : string ) : HMODULE;
procedure FreeResourceModule( ResourceModule : HMODULE );
// Icon resources
type
PGroupIconDirEntry = ^TGroupIconDirEntry;
TGroupIconDirEntry =
packed record
bWidth : byte; // Width, in pixels, of the image
bHeight : byte; // Height, in pixels, of the image
bColorCount : byte; // Number of colors in image (0 if >=8bpp)
bReserved : byte; // Reserved
wPlanes : word; // Color Planes
wBitCount : word; // Bits per pixel
dwBytesInRes : dword; // how many bytes in this resource?
nID : word; // the ID
end;
PGroupIconDir = ^TGroupIconDir;
TGroupIconDir =
packed record
idReserved : word; // Reserved (must be 0)
idType : word; // Resource type (1 for icons)
idCount : word; // How many images?
idEntries : array[0..0] of TGroupIconDirEntry; // The entries for each image
end;
type
PIconGroupList = ^TIconGroupList;
TIconGroupList = array[0..0] of PGroupIconDir;
TIconGroups =
record
Count : integer;
Items : PIconGroupList;
end;
type
PIconResource = pointer; // !!! <- Refine this
type
PIconResourceList = ^TIconResourceList;
TIconResourceList = array[0..0] of PIconResource;
TIconResources =
record
Count : integer;
Items : PIconResourceList;
end;
type
PResNameList = ^TResNameList;
TResNameList = array[0..0] of pchar;
TResNames =
record
Count : integer;
Items : PResNameList;
end;
// Resource loading:
function GroupSize( GroupIcon : PGroupIconDir ) : integer;
function GetIconResourceFromIndx( Module : HMODULE; IconIndx : integer; Size : integer ) : PIconResource;
function GetIconGroupFromIndx( Module : HMODULE; IconIndx : integer ) : PGroupIconDir;
function GetIconGroupFromName( Module : HMODULE; IconName : PAnsiChar ) : PGroupIconDir;
// Resource enumeration:
function GetIconNames( Module : HMODULE; var Names : TResNames ) : integer;
function GetIconGroups( Module : HMODULE; var IconGroups : TIconGroups ) : integer;
function GetIconResources( Module : HMODULE; IconGroup : PGroupIconDir; var IconResources : TIconResources ) : integer;
function GetIconResourceCount( Module : HMODULE ) : integer;
function GetGroupIconCount( Module : HMODULE ) : integer;
function GetLastIconResource( Module : HMODULE ) : integer;
function GetLastGroupIcon( Module : HMODULE ) : integer;
// Icon data
type
TIconData =
record
Group : PGroupIconDir;
Resources : TIconResources;
end;
function GetIconDataFromIndx( Module : HMODULE; IconIndx : integer; var Data : TIconData ) : integer;
function GetIconDataFromName( Module : HMODULE; IconName : PAnsiChar; var Data : TIconData ) : integer;
procedure FreeIconData( var Data : TIconData );
// Shell stuff:
function GetIconHandleFromIndx( Data : TIconData; IconIndx : integer ) : HICON;
function BestIconIndx( IconGroup : PGroupIconDir; Width, Height : integer ) : integer;
function GetSmallIconIndx( IconGroup : PGroupIconDir ) : integer;
function GetLargeIconIndx( IconGroup : PGroupIconDir ) : integer;
// Resource updating:
type
HUPDATE = THandle;
function CreateResources( const FileName : string ) : HUPDATE;
function UpdateResources( const FileName : string ) : HUPDATE;
procedure EndUpdateResources( Module : HUPDATE; Discard : boolean );
function AddIconData( Module : HUPDATE; ResName : PAnsiChar; LastIcon : integer; Data : TIconData ) : integer;
function UpdateIconData( Module : HUPDATE; ResName : PAnsiChar; LastIcon : integer; OldGroup : PGroupIconDir; Data : TIconData ) : integer;
implementation
uses
SysUtils, StrUtils;
// Module mapping:
function LoadResourceModule( const FileName : string ) : HMODULE;
begin
Result := LoadLibraryEx( pchar(FileName), 0, LOAD_LIBRARY_AS_DATAFILE );
if Debugging
then assert( Result <> 0, 'Could not load Module ''' + FileName + ''' in Resources.LoadResourceModule' );
end;
procedure FreeResourceModule( ResourceModule : HMODULE );
begin
if Debugging
then assert( FreeLibrary( ResourceModule ), 'Could not free Module in Resources.FreeResourceModule' )
else FreeLibrary( ResourceModule );
end;
// Resource loading:
function GroupSize( GroupIcon : PGroupIconDir ) : integer;
begin
Result := sizeof( TGroupIconDir ) + pred( GroupIcon.idCount ) * sizeof( TGroupIconDirEntry );
end;
type
PResEnumFromIndxData = ^TResEnumFromIndxData;
TResEnumFromIndxData =
record
ResType : PAnsiChar;
ResName : pchar;
Indx : integer;
Count : integer;
end;
function CallbackFindFromIndx( Module : HMODULE; EnumResType, EnumResName : PAnsiChar; Param : integer ) : boolean; stdcall;
var
EnumFromIndxData : PResEnumFromIndxData absolute Param;
begin
Result := true;
with EnumFromIndxData^ do
if EnumResType = ResType
then
if succ( Indx ) < Count
then inc( Indx )
else
begin
ResName := StrNew( EnumResName );
Result := false;
end;
end;
function GetIconGroupFromIndx( Module : HMODULE; IconIndx : integer ) : PGroupIconDir;
var
EnumFromIndxData : TResEnumFromIndxData;
begin
with EnumFromIndxData do
begin
ResType := RT_GROUP_ICON;
Count := succ( IconIndx );
EnumResourceNames( Module, ResType, @CallbackFindFromIndx, longint(@EnumFromIndxData) );
Result := GetIconGroupFromName( Module, ResName );
end;
end;
function GetIconGroupFromName( Module : HMODULE; IconName : PAnsiChar ) : PGroupIconDir;
var
ResHandle : HRSRC;
GlobalHandle : HGLOBAL;
GroupResource : PGroupIconDir;
begin
Result := nil;
ResHandle := FindResource( Module, IconName, RT_GROUP_ICON );
if ResHandle <> 0
then
begin
GlobalHandle := LoadResource( Module, ResHandle );
if (GlobalHandle <> 0)
then
begin
GroupResource := LockResource( GlobalHandle );
New( Result );
Result^ := GroupResource^;
// Do we need to free GlobalHandle in Win95? There are conflicts in Win32 SDK
end;
end;
end;
function GetIconResourceFromIndx( Module : HMODULE; IconIndx : integer; Size : integer ) : PIconResource;
var
ResHandle : HRSRC;
GlobalHandle : HGLOBAL;
IconResource : PIconResource;
begin
Result := nil;
ResHandle := FindResource( Module, MakeIntResource(IconIndx), RT_ICON );
if ResHandle <> 0
then
begin
GlobalHandle := LoadResource( Module, ResHandle );
if (GlobalHandle <> 0)
then
begin
IconResource := LockResource( GlobalHandle );
GetMem( Result, Size );
Move( IconResource^, Result^, Size );
end;
end;
end;
// Resource enumeration:
type
PResEnumData = ^TResEnumData;
TResEnumData =
record
ResType : PAnsiChar;
Count : integer;
ResNames : PResNameList;
end;
const
ResAllocGranularity = 15;
function CallbackEnumerator( Module : HMODULE; EnumResType, EnumResName : PAnsiChar; Param : integer ) : boolean; stdcall;
var
EnumData : PResEnumData absolute Param;
begin
with EnumData^ do
if EnumResType = ResType
then
begin
if Count mod ResAllocGranularity = 0
then ReallocMem( ResNames, (Count + ResAllocGranularity) * sizeof( ResNames[0] ));
ResNames[Count] := StrNew( EnumResName );
inc( Count );
end;
Result := true;
end;
function GetIconNames( Module : HMODULE; var Names : TResNames ) : integer;
var
EnumData : TResEnumData;
begin
with EnumData do
begin
ResType := RT_GROUP_ICON;
Count := 0;
ResNames := nil;
EnumResourceNames( Module, ResType, @CallbackEnumerator, longint(@EnumData) );
Result := Count;
end;
end;
function GetIconGroups( Module : HMODULE; var IconGroups : TIconGroups ) : integer;
var
Names : TResNames;
i : integer;
begin
with IconGroups do
begin
Count := GetIconNames( Module, Names );
GetMem( Items, Count * sizeof(Items[0]) );
for i := 0 to pred(Count) do
Items[i] := GetIconGroupFromName( Module, Names.Items[i] );
Result := Count;
end;
end;
function GetIconResources( Module : HMODULE; IconGroup : PGroupIconDir; var IconResources : TIconResources ) : integer;
var
i : integer;
begin
with IconGroup^, IconResources do
begin
Count := idCount;
GetMem( Items, Count * sizeof(Items[0]) );
for i := 0 to pred(Count) do
with idEntries[i] do
Items[i] := GetIconResourceFromIndx( Module, nId, dwBytesInRes );
Result := Count;
end;
end;
function GetIconResourceCount( Module : HMODULE ) : integer;
var
EnumFromIndxData : TResEnumFromIndxData;
begin
with EnumFromIndxData do
begin
ResType := RT_ICON;
Count := MaxInt;
EnumResourceNames( Module, ResType, @CallbackFindFromIndx, longint(@EnumFromIndxData) );
Result := Count;
end;
end;
function GetLastIconResource( Module : HMODULE ) : integer;
var
EnumFromIndxData : TResEnumFromIndxData;
begin
with EnumFromIndxData do
begin
ResType := RT_ICON;
Count := MaxInt;
EnumResourceNames( Module, ResType, @CallbackFindFromIndx, longint(@EnumFromIndxData) );
Result := integer( ResName );
end;
end;
function GetGroupIconCount( Module : HMODULE ) : integer;
var
EnumFromIndxData : TResEnumFromIndxData;
begin
with EnumFromIndxData do
begin
ResType := RT_GROUP_ICON;
Count := MaxInt;
EnumResourceNames( Module, ResType, @CallbackFindFromIndx, longint(@EnumFromIndxData) );
Result := Count;
end;
end;
function GetLastGroupIcon( Module : HMODULE ) : integer;
var
EnumFromIndxData : TResEnumFromIndxData;
begin
with EnumFromIndxData do
begin
ResType := RT_GROUP_ICON;
Count := MaxInt;
EnumResourceNames( Module, ResType, @CallbackFindFromIndx, longint(@EnumFromIndxData) );
Result := integer( ResName );
end;
end;
// Icon data
function GetIconDataFromPathIndx( const PathIndx : string; var Data : TIconData ) : integer;
var
Pos : integer;
Indx : integer;
Path : string;
Module : HMODULE;
begin
if PathIndx <> '%1'
then
begin
Pos := BackPos( ',', PathIndx, Length(PathIndx) );
if Pos <> 0
then
begin
try
Indx := StrToInt( RightStr( PathIndx, Length(PathIndx) - Pos ));
except
Indx := 0;
end;
Path := copy( PathIndx, 1, Pos - 1 );
end
else
begin
Indx := 0;
Path := PathIndx;
end;
Module := LoadResourceModule( Path );
Result := GetIconDataFromIndx( Module, Indx, Data );
FreeResourceModule( Module );
end
else
begin
FillChar( Data, sizeof(Data), 0);
Result := 0;
end;
end;
function GetIconDataFromIndx( Module : HMODULE; IconIndx : integer; var Data : TIconData ) : integer;
begin
with Data do
begin
Group := GetIconGroupFromIndx( Module, IconIndx );
Result := GetIconResources( Module, Group, Resources );
end;
end;
function GetIconDataFromName( Module : HMODULE; IconName : PAnsiChar; var Data : TIconData ) : integer;
begin
with Data do
begin
Group := GetIconGroupFromName( Module, IconName );
Result := GetIconResources( Module, Group, Resources );
end;
end;
procedure FreeIconData( var Data : TIconData );
var
i : integer;
begin
with Data, Resources do
begin
FreeMem( Group );
for i := 0 to pred( Count ) do
FreeMem( Items[i] );
FreeMem( Items );
end;
end;
const
IconWin2x = $20000;
IconWin3x = $30000;
function GetIconHandleFromIndx( Data : TIconData; IconIndx : integer ) : HICON;
begin
with Data do
Result := CreateIconFromResourceEx( Resources.Items[IconIndx], Group.idEntries[IconIndx].dwBytesInRes, true, IconWin3x, 0, 0, LR_LOADREALSIZE );
end;
// Resource updating:
function CreateResources( const FileName : string ) : HUPDATE;
begin
Result := BeginUpdateResource( pchar(FileName), true );
end;
function UpdateResources( const FileName : string ) : HUPDATE;
begin
Result := BeginUpdateResource( pchar(FileName), false );
end;
procedure EndUpdateResources( Module : HUPDATE; Discard : boolean );
begin
EndUpdateResource( Module, Discard );
end;
function AddIconData( Module : HUPDATE; ResName : PAnsiChar; LastIcon : integer; Data : TIconData ) : integer;
var
i : integer;
begin
with Data do
begin
with Group^, Resources do
for i := 0 to pred( Count ) do
begin
inc( LastIcon );
UpdateResource( Module, RT_ICON, MakeIntResource(LastIcon), LANG_SYSTEM_DEFAULT, Items[i], idEntries[i].dwBytesInRes );
idEntries[i].nId := LastIcon;
end;
UpdateResource( Module, RT_GROUP_ICON, ResName, LANG_SYSTEM_DEFAULT, Group, GroupSize(Group) );
end;
Result := LastIcon;
end;
function UpdateIconData( Module : HUPDATE; ResName : PAnsiChar; LastIcon : integer; OldGroup : PGroupIconDir; Data : TIconData ) : integer;
var
i : integer;
begin
// Erase old resource
with OldGroup^ do
begin
for i := 0 to pred( idCount ) do
UpdateResource( Module, RT_ICON, MakeIntResource( idEntries[i].nId ), LANG_SYSTEM_DEFAULT, nil, 0 );
UpdateResource( Module, RT_GROUP_ICON, ResName, LANG_SYSTEM_DEFAULT, nil, 0 );
end;
// Add new resource
with Data do
begin
with Group^, Resources do
for i := 0 to pred( Count ) do
begin
inc( LastIcon );
UpdateResource( Module, RT_ICON, MakeIntResource(LastIcon), LANG_SYSTEM_DEFAULT, Items[i], idEntries[i].dwBytesInRes );
idEntries[i].nId := LastIcon;
end;
UpdateResource( Module, RT_GROUP_ICON, ResName, LANG_SYSTEM_DEFAULT, Group, GroupSize(Group) );
end;
Result := LastIcon;
end;
// Shell stuff:
function BestIconIndx( IconGroup : PGroupIconDir; Width, Height : integer ) : integer;
begin
Result := LookupIconIdFromDirectoryEx( pointer(IconGroup), true, Width, Height, LR_DEFAULTCOLOR );
end;
function GetSmallIconIndx( IconGroup : PGroupIconDir ) : integer;
var
Width, Height : integer;
begin
GetSmallIconSize( Width, Height );
Result := LookupIconIdFromDirectoryEx( pointer(IconGroup), true, Width, Height, LR_DEFAULTCOLOR );
end;
function GetLargeIconIndx( IconGroup : PGroupIconDir ) : integer;
var
Width, Height : integer;
begin
GetLargeIconSize( Width, Height );
Result := LookupIconIdFromDirectoryEx( pointer(IconGroup), true, Width, Height, LR_DEFAULTCOLOR );
end;
end.
|
unit UPearsonHash;
interface
type
TPearsonTable = array[Byte] of Byte;
function PearsonHash(var T:TPearsonTable; const s:AnsiString):Byte;
procedure InitPearsonTable(var T:TPearsonTable);
procedure ShufflePearsonTable(var T:TPearsonTable);
procedure TicklePearsonTable(var T:TPearsonTable);
procedure TicklePearsonTable2(var T:TPearsonTable; index:Integer);
procedure CopyPearsonTable(var a,b:TPearsonTable);
implementation
uses Windows;
function rotb_r (x, times : byte) : byte; assembler;
asm
mov al,x
mov cl, times
ror al,cl
end;
function rotb_l (x, times : byte) : byte; assembler;
asm
mov al,x
mov cl,times
rol al,cl
end;
function PearsonHash2(var T:TPearsonTable; s:PByte; len:Integer):Byte;
var
i : Integer;
begin
Result := len mod 256;
for i := 0 to len-1 do
begin
Result := rotb_r(Result, 3);
Result := T[Result xor s^];
Inc(s);
end;
end;
(*
function PearsonHash(var T:TPearsonTable; const s:AnsiString):Byte;
var
i : Integer;
begin
Result := Length(s) mod 256;
for i := 1 to Length(s) do
begin
//Result := rotb_l(Result, 1);
Result := T[Result xor ord(s[i])];
end;
end;
*)
function PearsonHash(var T:TPearsonTable; const s:AnsiString):Byte;
begin
Result := PearsonHash2(T, @s[1], length(s));
end;
procedure InitPearsonTable(var T:TPearsonTable);
var
i : Integer;
begin
for i := low(T) to High(T) do
T[i] := i;
end;
procedure SwapByte(a,b:PByte);
var t: Byte;
begin
t := a^;
a^ := b^;
b^ := t;
end;
procedure ShufflePearsonTable(var T:TPearsonTable);
var
i : Integer;
begin
for i := High(T) downto Low(T)+1 do
begin
SwapByte(@T[i], @T[random(i+1)]);
end
end;
procedure TicklePearsonTable2(var T:TPearsonTable; index:Integer);
var
i : Integer;
begin
repeat
i := random(256);
until index<>i;
SwapByte(@T[i], @T[index]);
end;
procedure TicklePearsonTable(var T:TPearsonTable);
var
i,j : Integer;
begin
i := random(256);
repeat
j := random(256);
until j<>i;
SwapByte(@T[i], @T[j]);
end;
procedure CopyPearsonTable(var a,b:TPearsonTable);
begin
Move(a[0], b[0], sizeof(b));
end;
end.
|
unit define_stockday_sina;
interface
uses
Sysutils;
type
TDealDayDataHeadName_Sina = (
headNone, // 0
headDay, // 1 日期,
headPrice_Open, // 7开盘价,
headPrice_High, // 5最高价,
headPrice_Close, // 4收盘价,
headPrice_Low, // 6最低价,
headDeal_Volume, // 12成交量,
headDeal_Amount, // 13成交金额,
headDeal_WeightFactor
); // 15流通市值);
PRT_DealDayData_HeaderSina = ^TRT_DealDayData_HeaderSina;
TRT_DealDayData_HeaderSina = record
HeadNameIndex : array[TDealDayDataHeadName_Sina] of SmallInt;
end;
const
DealDayDataHeadNames_Sina: array[TDealDayDataHeadName_Sina] of string = (
'',
'日期',
'开盘价',
'最高价',
'收盘价',
'最低价',
'交易量(股)',
'交易金额(元)',
'复权因子'
);
var
DateFormat_Sina: Sysutils.TFormatSettings;(*// =(
CurrencyString: '';
DateSeparator: '-';
TimeSeparator: ':';
ListSeparator: ';';
ShortDateFormat : 'yyyy-mm-dd';
LongDateFormat : 'yyyy-mm-dd';
);//*)
implementation
initialization
FillChar(DateFormat_Sina, SizeOf(DateFormat_Sina), 0);
DateFormat_Sina.DateSeparator := '-';
DateFormat_Sina.TimeSeparator := ':';
DateFormat_Sina.ListSeparator := ';';
DateFormat_Sina.ShortDateFormat := 'yyyy-mm-dd';
DateFormat_Sina.LongDateFormat := 'yyyy-mm-dd';
end.
|
unit uConsultaCEP;
{
Objetivo: Consultar CEP atravez de webservice que retorne no browser um arquivo formato XML.
Para utilizar basta seguir o exemplo abaixo:
var
CEP: TConsultaCEP;
endereco: string;
bairro: string;
cidade: string;
estado: string;
begin
CEP.Cep := 'xxxxx-xxx'; //pode ser passado tbm sem o traço "xxxxxxxx"
if CEP.ConsultaCEP then
begin
endereco := CEP.endereco;
bairro := CRP.bairro;
cidade := CEP.cidade;
estado := CEP.estado;
end;
end;
************************
existe tbm uma propriedade Resposta, que contem a resposta da consulta.
para utilizar
ShowMessage(CEP.Resposta);
************************
a classe tbm tem um forma de retornar os valores,
sendo setada a propriedade FormatoRetorno para
msDefault = retorna exatamente igual foi recebido do browser
msUpper = da um UpperCase no retorno
msUpperClear = alem de dar um UpperCase retira os acentos
msLower = retorna com LowerCase
msDefaultClear = somente retira os acentos.
}
interface
uses
Windows, Forms, Dialogs, Messages, SysUtils, SqlExpr, Classes, xmldom,
XMLIntf, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,
OleCtrls, SHDocVw, msxmldom, XMLDoc, Provider, Xmlxform, Graphics, Menus,
StdCtrls, ExtCtrls, Controls, LibSatwin, LibGeral, LibSenha;
type
TModString = (msDefault, msUpper, msUpperClear, msLower, msDefaultClear);
type
TtpAuthentication = (NoAuthentication, AuthenticationUserName);
type
TConsultaCEP = class(TObject)
constructor Create;
private
fCEP: string;
fBairro: string;
fUF: string;
fCidade: string;
fEndereco: string;
fURL: string;
fSourceXML: string;
FResposta: string;
fFormatoRetorno: TModString;
fAbreviado: Boolean;
fAtivo: Boolean;
fProxyUsername: string;
fProxyServer: string;
fProxyPort: integer;
fProxyPassword: string;
fProxyAuthentication: TtpAuthentication;
procedure SetResposta(const Value: string);
procedure SetSouceXML(const Value: string);
procedure SetURL(const Value: string);
procedure SetCEP(const Value: string);
procedure Limpar;
function FormatarCEP(value: string): string;
function PegarCEP: Boolean; //Busca o CEP na Web
function CarregarDados: Boolean; //Carrega os dados preenchendo as propriedades
function Abreviar(value: string): string;
function RemoverAcento(value: string): string;
public
function ConsultarCEP: Boolean; //Função que será chamada pelo usuario
property CEP: string read fCEP write SetCEP;
property Endereco: string read fEndereco;
property Bairro: string read fBairro;
property Cidade: string read fCidade;
property UF: string read fUF;
property URL: string write SetURL;
property SouceXml: string write SetSouceXML;
property Resposta: string read FResposta;
property FormatoRetorno: TmodString read fFormatoRetorno write fFormatoRetorno;
property Abreviado: Boolean read fAbreviado write fAbreviado;
property Ativo: Boolean read fAtivo write fAtivo;
property ProxyAuthentication: TtpAuthentication read fProxyAuthentication write fProxyAuthentication;
property ProxyServer: string read fProxyServer write fProxyServer;
property ProxyPort: integer read fProxyPort write fProxyPort;
property ProxyUsername: string read fProxyUsername write fProxyUsername;
property ProxyPassword: string read fProxyPassword write fProxyPassword;
end;
implementation
{ TConsultaCep }
function TConsultaCEP.Abreviar(value: string): string;
var
aux: string;
begin
aux := value;
if Pos('RUA', aux) > 0 then
aux := StringReplace(aux, 'RUA', 'R.', [])
else
if Pos('VILA', aux) > 0 then
aux := StringReplace(aux, 'VILA', 'VL', [])
else
if Pos('CAPITAO', aux) > 0 then
aux := StringReplace(aux, 'CAPITAO', 'CAP.:', [])
else
if Pos('COMENDADOR', aux) > 0 then
aux := StringReplace(aux, 'COMENDADOR', 'COM.', [])
else
if Pos('TRAVESSA', aux) > 0 then
aux := StringReplace(aux, 'TRAVESSA', 'TRV.', [])
else
if Pos('BAIRRO', aux) > 0 then
aux := StringReplace(aux, 'BAIRRO', 'B.', [])
else
if Pos('JARDIM', aux) > 0 then
aux := StringReplace(aux, 'JARDIM', 'JD.', [])
else
if Pos('BOSQUE', aux) > 0 then
aux := StringReplace(aux, 'BOSQUE', 'BQ.', [])
else
if Pos('ESTRADA', aux) > 0 then
aux := StringReplace(aux, 'ESTRADA', 'EST.', [])
else
if Pos('RODOVIA', aux) > 0 then
aux := StringReplace(aux, 'RODOVIA', 'ROD.', [])
else
if Pos('PROFESSOR', aux) > 0 then
aux := StringReplace(aux, 'PROFESSOR', 'PROF.', [])
else
if Pos('MINISTRO', aux) > 0 then
aux := StringReplace(aux, 'MINISTRO', 'MIN.', [])
else
if Pos('PARQUE', aux) > 0 then
aux := StringReplace(aux, 'PARQUE', 'PQ.', [])
else
if Pos('PADRE', aux) > 0 then
aux := StringReplace(aux, 'PADRE', 'PDE.', [])
else
if Pos('AVENIDA', aux) > 0 then
aux := StringReplace(aux, 'AVENIDA', 'AV.', [])
else
if Pos('BLOCO', aux) > 0 then
aux := StringReplace(aux, 'BLOCO', 'BL.', [])
else
if Pos('ALAMEDA', aux) > 0 then
aux := StringReplace(aux, 'ALAMEDA', 'AL.', [])
else
if Pos('CONJUNTO', aux) > 0 then
aux := StringReplace(aux, 'CONJUNTO', 'CJ.', [])
else
if Pos('CONDOMINIO', aux) > 0 then
aux := StringReplace(aux, 'CONDOMINIO', 'COND.', [])
else
if Pos('CONDOMÍNIO', aux) > 0 then
aux := StringReplace(aux, 'CONDOMÍNIO', 'COND.', [])
else
if Pos('Condomínio', aux) > 0 then
aux := StringReplace(aux, 'Condomínio', 'Cond.', [])
else
if Pos('Condominio', aux) > 0 then
aux := StringReplace(aux, 'Condominio', 'Cond.', [])
else
if Pos('CHÁCARA', aux) > 0 then
aux := StringReplace(aux, 'CHÁCARA', 'CHÁC.', [])
else
if Pos('Chácara', aux) > 0 then
aux := StringReplace(aux, 'Chácara', 'Chác.', []);
Result := aux;
end;
function TConsultaCEP.CarregarDados: Boolean;
var
nd: string;
XMLDoc: TStringList;
begin
result := False;
try
XMLDoc := TStringList.Create;
XMLDoc.CommaText:= fSourceXML;
{try // Rafael
XMLDoc.CommaText.Active := True;
except
exit;
end;}
//XMLDoc.DocumentElement;
nd := XMLDoc.Values ['resultado'];
if (nd = '1') or (nd = '2') then
begin
nd := XMLDoc.Values['uf'];
case fFormatoRetorno of
msDefault: fUF := nd;
msUpper: fUF := UpperCase(nd);
msUpperClear: fUF := UpperCase(RemoverAcento(nd));
msLower: fUF := LowerCase(nd);
msDefaultClear: fUF := RemoverAcento(nd);
end;
nd := XMLDoc.Values['cidade'];
case fFormatoRetorno of
msDefault: fCidade := RemoverAcento(nd);
msUpper: fCidade := UpperCase(nd);
msUpperClear: fCidade := UpperCase(RemoverAcento(StringReplace(nd, '-', ' ', [rfReplaceAll])));
msLower: fCidade := LowerCase(nd);
msDefaultClear: fCidade := RemoverAcento(nd);
end;
nd := XMLDoc.Values['bairro'];
case fFormatoRetorno of
msDefault: fBairro := nd;
msUpper: fBairro := UpperCase(nd);
msUpperClear: fBairro := UpperCase(RemoverAcento(StringReplace(nd, '-', ' ', [rfReplaceAll])));
//msUpperClear: fBairro := UpperCase(RemoverAcento(nd));
msLower: fBairro := LowerCase(nd);
msDefaultClear: fBairro := RemoverAcento(nd);
end;
nd := XMLDoc.Values['tipo_logradouro'];
case fFormatoRetorno of
msDefault: fEndereco := nd;
msUpper: fEndereco := UpperCase(nd);
msUpperClear: fEndereco := UpperCase(RemoverAcento(nd));
msLower: fEndereco := LowerCase(nd);
msDefaultClear: fEndereco := RemoverAcento(nd);
end;
nd := XMLDoc.Values['logradouro'];
case fFormatoRetorno of
msDefault: fEndereco := fEndereco + ' ' + nd;
msUpper: fEndereco := UpperCase(fEndereco + ' ' + nd);
msUpperClear: fEndereco := UpperCase(RemoverAcento(StringReplace(fEndereco + ' ' + nd, '-', ' ', [rfReplaceAll])));
//msUpperClear: fEndereco := UpperCase(RemoverAcento(fEndereco + ' ' + nd));
msLower: fEndereco := LowerCase(fEndereco + ' ' + nd);
msDefaultClear: fEndereco := RemoverAcento(fEndereco + ' ' + nd);
end;
// nd := XMLDoc.Values ['resultado_txt'];
if fAbreviado then
begin
fEndereco := Abreviar(fEndereco);
fBairro := Abreviar(fBairro);
// fCidade := Abreviar(fCidade);
end;
result := True;
end
else
begin
Limpar;
nd := XMLDoc.Values['resultado_txt'];
fResposta := nd;
end;
finally
DeleteFile(fSourceXML);
//XMLDoc.Active := False;
XMLDoc.Free;
end;
end;
function TConsultaCEP.ConsultarCEP: Boolean;
begin
Result := False;
if fAtivo then
if PegarCEP then
if CarregarDados then
Result := True;
end;
constructor TConsultaCEP.Create;
begin
Limpar;
fAbreviado := True;
fFormatoRetorno := msUpperClear;
end;
function TConsultaCEP.FormatarCEP(Value: string): string;
begin
value := StringReplace(Value, '-', '', [rfReplaceAll]);
result := Copy(value, 1, 5) + '-' + Copy(value, 6, 3)
end;
procedure TConsultaCEP.Limpar;
begin
fFormatoRetorno := msDefault;
fSourceXML := ExtractFilePath(Application.ExeName) + 'webcep.xml';
fCEP := '';
fEndereco := '';
fBairro := '';
fCidade := '';
fUF := '';
fProxyUsername := '';
fProxyServer := '';
fProxyPort := 0;
fProxyPassword := '';
fProxyAuthentication := NoAuthentication;
end;
function TConsultaCEP.PegarCEP: Boolean;
var
List: TStringList;
Http: TIdHTTP;
begin
List := TStringList.Create;
Http := TIdHTTP.Create(Application);
if fProxyServer <> '' then
begin
Http.ProxyParams.BasicAuthentication := True;
Http.ProxyParams.ProxyPort := fProxyPort;
Http.ProxyParams.ProxyServer := fProxyServer;
Http.ProxyParams.ProxyPassword := fProxyPassword;
Http.ProxyParams.ProxyUsername := fProxyUsername;
end;
List.Text:=stringreplace(Http.Get('http://republicavirtual.com.br/web_cep.php?cep='+fCEP+'&formato=query_string'),'&',#13#10,[rfreplaceAll]);
List.Text := StringReplace(List.Text, '%E1', 'á', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '%E2', 'â', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '%E3', 'ã', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '%E9', 'é', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '%E7', 'ç', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '%ED', 'í', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '%F3', 'ó', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '%F4', 'ô', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '%F5', 'õ', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '%FA', 'ú', [rfReplaceAll, rfIgnoreCase]);
List.Text := StringReplace(List.Text, '+', '-', [rfReplaceAll, rfIgnoreCase]);
// List.Add(Http.Get(fURL + fCEP));
try
result := List.Text <> '';
if result then
fSourceXML := List.Text;//(fSourceXML);
finally
List.Free;
end;
//List.Free;
end;
function TConsultaCEP.RemoverAcento(value: string): string;
const
ComAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ';
SemAcento = 'AAEOUAOAEIOUCUAAEOUAOAEIOUCU';
var
x : Integer;
begin
for x := 1 to Length(value) do
if Pos(value[x], ComAcento) <> 0 then
value[x] := SemAcento[Pos(value[x], ComAcento)];
Result := value;
end;
procedure TConsultaCep.SetCEP(const Value: string);
begin
fCEP := FormatarCEP(Value);
end;
procedure TConsultaCEP.SetResposta(const Value: string);
begin
FResposta := Value;
end;
procedure TConsultaCEP.SetSouceXML(const Value: string);
begin
fSourceXML := Value;
end;
procedure TConsultaCEP.SetURL(const Value: string);
begin
fURL := Value;
end;
end.
|
PROGRAM Pseudo(INPUT, OUTPUT);
{ Programm creates file of pseudo-symbols }
TYPE
SignsPlace = SET OF 1 .. 25;
VAR
PseudoLetter: SignsPlace;
Letters: FILE OF SignsPlace;
BEGIN {Pseudo}
ASSIGN(Letters, 'Letters_EN_Bin.txt');
REWRITE(Letters);
PseudoLetter := []; {Blank} {0}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 6, 10, 11, 15, 16, 17, 18, 19, 20, 21, 25]; {A}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 6, 8, 11, 12, 13, 14, 15, 16, 20, 21, 22, 23, 24, 25]; {B}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 16, 21, 22, 23, 24, 25]; {C}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 6, 10, 11, 15, 16, 20, 21, 22, 23, 24, 25]; {D}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 12, 13, 16, 21, 22, 23, 24, 25]; {E}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 16, 21]; {F}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 13, 14, 15, 16, 20, 21, 22, 23, 24, 25]; {G}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 10, 11, 12, 13, 14, 15, 16, 20, 21, 25]; {H}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 8, 13, 18, 21, 22, 23, 24, 25]; {I}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 8, 13, 16, 18, 21, 22, 23]; {J}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 4, 5, 6, 8, 11, 12, 16, 18, 21, 24, 25]; {K}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 6, 11, 16, 21, 22, 23, 24, 25]; {L}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 7, 9, 10, 11, 13, 15, 16, 20, 21, 25]; {M}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 7, 10, 11, 13, 15, 16, 19, 20, 21, 25]; {N}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 10, 11, 15, 16, 20, 21, 22, 23, 24, 25]; {O}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15, 16, 21]; {P}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 6, 9, 11, 14, 16, 17, 18, 19, 25]; {Q}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 6, 9, 11, 12, 13, 14, 16, 19, 21, 25]; {R}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25]; {S}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 8, 13, 18, 23]; {T}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 10, 11, 15, 16, 20, 21, 22, 23, 24, 25]; {U}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 10, 11, 15, 17, 19, 23]; {V}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 8, 10, 11, 13, 15, 17, 18, 19, 23]; {W}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 7, 9, 13, 17, 19, 21, 25]; {X}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 5, 6, 10, 12, 14, 18, 23]; {Y}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 9, 13, 17, 21, 22, 23, 24, 25]; {Z} {26}
WRITE(Letters, PseudoLetter);
PseudoLetter := [17, 18, 19, 22, 23, 24]; {.}
WRITE(Letters, PseudoLetter);
PseudoLetter := [16, 17, 22]; {,}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 7, 8, 9, 12, 13, 14, 23]; {!}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 10, 13, 14, 15, 22, 23, 24]; {?} {30}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; {'}
WRITE(Letters, PseudoLetter);
PseudoLetter := [11, 12, 13, 14, 15]; {-}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 4, 7, 9]; {"}
WRITE(Letters, PseudoLetter);
PseudoLetter := [8, 18]; {:}
WRITE(Letters, PseudoLetter);
PseudoLetter := [8, 18, 19, 24]; {;} {35}
WRITE(Letters, PseudoLetter);
PseudoLetter := [4, 8, 12, 18, 24]; {<}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 8, 14, 18, 22]; {>}
WRITE(Letters, PseudoLetter);
PseudoLetter := [7, 11, 13, 15, 19]; {~}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 7, 8, 9, 10]; {`}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 6, 8, 10, 11, 13, 14, 15, 16, 22, 23, 24, 25]; {@} {40}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 4, 6, 7, 8, 9, 10, 12, 14, 16, 17, 18, 19, 20, 22, 24]; {#}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 3, 4, 5, 6, 8, 11, 12, 13, 14, 15, 18, 20, 21, 22, 23, 24, 25]; //$
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 2, 5, 6, 7, 9, 13, 17, 19, 20, 21, 24, 25]; {%}
WRITE(Letters, PseudoLetter);
PseudoLetter := [3, 7, 9, 11, 15]; {^}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 6, 8, 12, 13, 15, 16, 19, 21, 22, 23, 25]; {&} {45}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 3, 5, 7, 8, 9, 11, 12, 13, 14, 15, 17, 18, 19, 21, 23, 25]; {*}
WRITE(Letters, PseudoLetter);
PseudoLetter := [3, 7, 12, 17, 23]; {(}
WRITE(Letters, PseudoLetter);
PseudoLetter := [3, 9, 14, 19, 23]; {)}
WRITE(Letters, PseudoLetter);
PseudoLetter := [21, 22, 23, 24, 25]; {_}
WRITE(Letters, PseudoLetter);
PseudoLetter := [3, 8, 11, 12, 13, 14, 15, 18, 23]; {+} {50}
WRITE(Letters, PseudoLetter);
PseudoLetter := [6, 7, 8, 9, 10, 16, 17, 18, 19, 20]; {=}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 7, 12, 17, 22, 23, 24]; {[}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 9, 14, 19, 22, 23, 24]; {]}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 7, 11, 12, 17, 22, 23, 24]; //{
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 9, 14, 15, 19, 22, 23, 24]; //} {55}
WRITE(Letters, PseudoLetter);
PseudoLetter := [3, 8, 13, 18, 23]; {|}
WRITE(Letters, PseudoLetter);
PseudoLetter := [5, 9, 13, 17, 21]; {/}
WRITE(Letters, PseudoLetter);
PseudoLetter := [1, 7, 13, 19, 25]; {\}
WRITE(Letters, PseudoLetter);
PseudoLetter := [3, 7, 8, 13, 18, 22, 23, 24]; {1}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 9, 12, 13, 14, 17, 22, 23, 24]; {2} {60}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 9, 12, 13, 14, 19, 22, 23, 24]; {3}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 4, 7, 9, 12, 13, 14, 19, 24]; {4}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 7, 12, 13, 14, 19, 22, 23, 24]; {5}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 7, 12, 13, 14, 17, 19, 22, 23, 24]; {6}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 9, 14, 19, 24]; {7} {65}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 7, 9, 12, 13, 14, 17, 19, 22, 23, 24]; {8}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 7, 9, 12, 13, 14, 19, 22, 23, 24]; {9}
WRITE(Letters, PseudoLetter);
PseudoLetter := [2, 3, 4, 7, 9, 12, 14, 17, 19, 22, 23, 24]; {0}
WRITE(Letters, PseudoLetter)
END. {Pseudo}
|
unit functions;
interface
uses
classes;
function GetImageFiles(const directory: string): TStrings;
function FindFiles(const directory, prefix, extension: string): TStringList; //Build222
function CombinePath(const path: string; const subPath: string): string; overload;
function Minimum(const x, y: double): double; overload;
function Minimum(const x, y: integer): integer; overload;
implementation
uses
SysUtils;
function GetImageFiles(const directory: string): TStrings;
procedure AddFiles(const ext: string);
var
i: integer;
sl: TStrings;
begin
sl := FindFiles(directory, '', ext);
for i := 0 to sl.count-1 do
result.Add(sl[i]);
FreeAndNil(sl);
end;
begin
result := TStringList.Create();
AddFiles('png');
AddFiles('bmp');
AddFiles('jpg');
AddFiles('jpeg');
AddFiles('ico');
AddFiles('emf');
AddFiles('wmf');
end;
//Return a list of files where
// directory is the directory to search (sub-directories are ignored)
// prefix is the first part of the filename to match
// extension is a ; seperated list of file extensions to match
//Note: client is responsible for freeing result of this function
function FindFiles(const directory, prefix, extension: string): TStringList;
procedure FindThisExt(const result: TStrings; const directory, prefix: string; extension: string);
var
SR: TSearchRec;
s: string;
N: integer;
begin
S := directory;
if copy(directory, length(directory), 1) <> PathDelim then
s := s + PathDelim;
s := s + prefix + '*';
if extension = '*' then
extension := '.*'
else if copy(extension, 1, 1) <> '.' then
extension := '.' + extension;
s := s + extension;
N := FindFirst(S, 0, SR);
if (N = 0) then
begin
while (N = 0) do
begin
//Workaround FindFirst()
S := UpperCase(SR.Name);
if (Copy(S, 1, length(UpperCase(prefix))) = UpperCase(prefix)) then
result.Add(SR.Name);
N := FindNext(SR);
end;
end;
FindClose(SR);
end;
var
extensions: TStringList;
i: integer;
begin
result := TStringList.Create;
extensions := TStringList.Create;
try
ExtractStrings([';'], [], PChar(extension), extensions);
for i := 0 to extensions.count-1 do
FindThisExt(result, directory, prefix, extensions[i]);
finally
extensions.Free;
end;
end;
function ExcludeTrailingBackslash(const S: string): string;
begin
Result := S;
if IsPathDelimiter(Result, Length(Result)) then
SetLength(Result, Length(Result)-1);
end;
function CombinePath(const path: string; const subPath: string): string;
begin
result := ExcludeTrailingBackslash(path) + PathDelim + ExcludeTrailingBackslash(subPath);
end;
function Minimum(const x, y: double): double;
begin
if x < y then
result := x
else
result := y;
end;
function Minimum(const x, y: integer): integer;
begin
if x < y then
result := x
else
result := y;
end;
end.
|
unit GX_MacroLibraryNamePrompt;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, GX_BaseForm;
type
TfmMacroLibraryNamePrompt = class(TfmBaseForm)
lblMacroName: TLabel;
edtMacroName: TEdit;
chkDoNotShowAgain: TCheckBox;
btnOK: TButton;
btnCancel: TButton;
lblMacroDesc: TLabel;
mmoMacroDescription: TMemo;
public
class function Execute(AOwner: TComponent; var AMacroName, AMacroDesc: string;
var APromptForName: Boolean): Boolean;
end;
implementation
{$R *.dfm}
{ TTfmMacroLibraryNamePrompt }
class function TfmMacroLibraryNamePrompt.Execute(AOwner: TComponent;
var AMacroName, AMacroDesc: string; var APromptForName: Boolean): Boolean;
var
Form: TfmMacroLibraryNamePrompt;
begin
Form := TfmMacroLibraryNamePrompt.Create(AOwner);
try
Form.edtMacroName.Text := AMacroName;
Form.mmoMacroDescription.Lines.Text := AMacroDesc;
Form.chkDoNotShowAgain.Checked := False;
Result := (Form.ShowModal = mrOk);
if Result then begin
AMacroName := Form.edtMacroName.Text;
AMacroDesc := Form.mmoMacroDescription.Lines.Text;
end;
// The checkbox is always evaluated
APromptForName := not Form.chkDoNotShowAgain.Checked;
finally
FreeAndNil(Form);
end;
end;
end.
|
unit FFSDataBackground;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls,
FFSTypes;
type
TFFSDataBackground = class(TPanel)
private
FFieldsColorScheme: TFieldsColorScheme;
{ Private declarations }
procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange;
procedure SetFieldsColorScheme(const Value: TFieldsColorScheme);
protected
{ Protected declarations }
public
{ Public declarations }
constructor create(AOwner:TComponent);override;
published
{ Published declarations }
property FieldsColorScheme:TFieldsColorScheme read FFieldsColorScheme write SetFieldsColorScheme;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Controls', [TFFSDataBackground]);
end;
{ TFFSDataBackground }
constructor TFFSDataBackground.create(AOwner: TComponent);
begin
inherited;
FFieldsColorScheme := fcsDataBackGround;
BevelOuter := bvNone;
end;
procedure TFFSDataBackground.MsgFFSColorChange(var Msg: TMessage);
begin
color := FFSColor[FFieldsColorScheme];
Broadcast(msg);
end;
procedure TFFSDataBackground.SetFieldsColorScheme(const Value: TFieldsColorScheme);
begin
FFieldsColorScheme := Value;
color := FFSColor[FFieldsColorScheme];
end;
end.
|
unit UToolBarDemo;
interface
{$IFDEF IOS}
{$DEFINE MOBILE}
{$ENDIF}
{$IFDEF ANDROID}
{$DEFINE MOBILE}
{$ENDIF}
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, Generics.Collections,
FMX.TMSBitmapContainer, FMX.TMSToolBar, FMX.Objects, FMX.StdCtrls, IOUtils, UIConsts;
type
TTMSFMXPaintElement = class(TPersistent)
private
FColor: TAlphaColor;
public
property Color: TAlphaColor read FColor write FColor;
end;
TTMSFMXLineElement = class(TTMSFMXPaintElement)
private
FWidth: Integer;
FPoints: TList<TPointF>;
public
constructor Create;
property Width: Integer read FWidth write FWidth;
property Points: TList<TPointF> read FPoints write FPoints;
end;
TTMSFMXTextElement = class(TTMSFMXPaintElement)
private
FFontSize: Integer;
FFontName: String;
FPos: TPointF;
FText: String;
public
property FontName: String read FFontName write FFontName;
property FontSize: Integer read FFontSize write FFontSize;
property Pos: TPointF read FPos write FPos;
property Text: String read FText write FText;
end;
TForm88 = class(TForm)
TMSFMXToolBar1: TTMSFMXToolBar;
PaintBox1: TPaintBox;
TMSFMXBitmapContainer1: TTMSFMXBitmapContainer;
TMSFMXToolBarButton1: TTMSFMXToolBarButton;
TMSFMXToolBarButton2: TTMSFMXToolBarButton;
TMSFMXToolBarColorPicker1: TTMSFMXToolBarColorPicker;
TMSFMXToolBarFontSizePicker1: TTMSFMXToolBarFontSizePicker;
TMSFMXToolBarSeparator1: TTMSFMXToolBarSeparator;
TMSFMXToolBarButton3: TTMSFMXToolBarButton;
TMSFMXToolBarSeparator2: TTMSFMXToolBarSeparator;
TMSFMXToolBarFontNamePicker1: TTMSFMXToolBarFontNamePicker;
TMSFMXToolBarFontSizePicker2: TTMSFMXToolBarFontSizePicker;
TMSFMXToolBarButton4: TTMSFMXToolBarButton;
procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
procedure PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure TMSFMXToolBarButton2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
procedure TMSFMXToolBarColorPicker1ColorSelected(Sender: TObject;
AColor: TAlphaColor);
procedure TMSFMXToolBarFontSizePicker1FontSizeSelected(Sender: TObject;
AFontSize: Integer);
procedure TMSFMXToolBarButton1Click(Sender: TObject);
procedure TMSFMXToolBarButton3Click(Sender: TObject);
procedure TMSFMXToolBarColorPicker1Click(Sender: TObject);
procedure TMSFMXToolBarButton4Click(Sender: TObject);
private
{ Private declarations }
FStartPainting: Boolean;
FActiveLineElement: TTMSFMXLineElement;
FActiveTextElement: TTMSFMXTextElement;
FPaintCol: TObjectList<TTMSFMXPaintElement>;
FActiveColor: TAlphaColor;
FActiveThickness: Integer;
public
{ Public declarations }
end;
var
Form88: TForm88;
implementation
{$R *.fmx}
procedure TForm88.FormCreate(Sender: TObject);
var
I: Integer;
begin
{$IFDEF MOBILE}
TMSFMXToolBar1.State := esLarge;
{$ENDIF}
FActiveColor := claRed;
FActiveThickness := 3;
TMSFMXToolBarColorPicker1.SelectedColor := claRed;
FPaintCol := TObjectList<TTMSFMXPaintElement>.Create;
TMSFMXToolBarFontSizePicker1.ListBox.Clear;
for I := 1 to 20 do
TMSFMXToolBarFontSizePicker1.ListBox.Items.Insert(I, inttostr(I));
TMSFMXToolBarFontSizePicker1.SelectedItemIndex := FActiveThickness - 1;
{$IFDEF MACOS}
TMSFMXToolBarFontNamePicker1.SelectedFontName := 'Helvetica';
{$ENDIF}
{$IFDEF ANDROID}
TMSFMXToolBarFontNamePicker1.SelectedFontName := 'Roboto';
{$ENDIF}
{$IFDEF MSWINDOWS}
TMSFMXToolBarFontNamePicker1.SelectedFontName := 'Tahoma';
{$ENDIF}
TMSFMXToolBarFontSizePicker2.SelectedFontSize := 18;
end;
procedure TForm88.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
if TMSFMXToolBarButton4.DownState then
Exit;
FStartPainting := True;
FActiveLineElement := TTMSFMXLineElement.Create;
if TMSFMXToolBarButton3.DownState then
FActiveLineElement.Color := claWhite
else
FActiveLineElement.Color := FActiveColor;
FActiveLineElement.Width := FActiveThickness;
FActiveLineElement.Points.Add(PointF(X, Y));
FPaintCol.Add(FActiveLineElement);
PaintBox1.Repaint;
end;
procedure TForm88.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
begin
if FStartPainting and Assigned(FActiveLineElement) then
begin
FActiveLineElement.Points.Add(PointF(X, Y));
PaintBox1.Repaint;
end;
end;
procedure TForm88.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var
str: String;
begin
if TMSFMXToolBarButton4.DownState then
begin
TMSFMXToolBarButton4.DownState := False;
FActiveTextElement := TTMSFMXTextElement.Create;
FActiveTextElement.Color := TMSFMXToolBarColorPicker1.SelectedColor;
FActiveTextElement.FontName := TMSFMXToolBarFontNamePicker1.SelectedFontName;
FActiveTextElement.Pos := PointF(X, Y);
FActiveTextElement.FontSize := TMSFMXToolBarFontSizePicker2.SelectedFontSize;
str := 'Hello World !';
{$IFNDEF ANDROID}
InputQuery('Please enter text', '', str);
{$ENDIF}
FActiveTextElement.Text := str;
FPaintCol.Add(FActiveTextElement);
end;
if Assigned(FActiveLineElement) then
FActiveLineElement.Points.Add(PointF(X, Y));
FStartPainting := False;
PaintBox1.Repaint;
FActiveLineElement := nil;
FActiveTextElement := nil;
end;
procedure TForm88.PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
var
I: Integer;
el: TTMSFMXPaintElement;
ln: TTMSFMXLineElement;
txt: TTMSFMXTextElement;
K: Integer;
tw, th: Single;
st: TCanvasSaveState;
begin
st := Canvas.SaveState;
Canvas.Fill.Color := claWhite;
Canvas.FillRect(PaintBox1.BoundsRect, 0, 0, AllCorners, 1);
if Assigned(FPaintCol) then
begin
for I := 0 to FPaintCol.Count - 1 do
begin
el := FPaintCol[I];
if el is TTMSFMXLineElement then
begin
ln := (el as TTMSFMXLineElement);
{$IF compilerversion > 26}
Canvas.Stroke.Kind := TBrushKind.Solid;
Canvas.Fill.Kind := TBrushKind.Solid;
Canvas.StrokeCap := TStrokeCap.Round;
{$ELSE}
Canvas.Stroke.Kind := TBrushKind.bkSolid;
Canvas.Fill.Kind := TBrushKind.bkSolid;
Canvas.StrokeCap := TStrokeCap.scRound;
{$ENDIF}
Canvas.Stroke.Color := ln.Color;
Canvas.Fill.Color := ln.Color;
Canvas.Stroke.Thickness := ln.Width;
{$IFDEF MSWINDOWS}
{$ENDIF}
if (el as TTMSFMXLineElement).Points.Count > 1 then
begin
for K := 0 to ln.Points.Count - 2 do
Canvas.DrawLine(ln.Points[K], ln.Points[K + 1], 1);
end
else
Canvas.FillEllipse(RectF(ln.Points[0].X - ln.Width / 2, ln.Points[0].Y - ln.Width / 2, ln.Points[0].X + ln.Width / 2, ln.Points[0].Y + ln.Width / 2), 1);
end
else if el is TTMSFMXTextElement then
begin
txt := el as TTMSFMXTextElement;
{$IF compilerversion > 26}
Canvas.Fill.Kind := TBrushKind.Solid;
{$ELSE}
Canvas.Fill.Kind := TBrushKind.bkSolid;
{$ENDIF}
Canvas.Font.Family := txt.FontName;
Canvas.Fill.Color := txt.Color;
Canvas.Font.Size := txt.FontSize;
tw := Canvas.TextWidth(txt.Text);
th := Canvas.TextHeight(txt.Text);
{$IF compilerversion > 26}
Canvas.FillText(RectF(txt.Pos.X, txt.Pos.Y, txt.Pos.X + tw, txt.Pos.Y + th), txt.Text, False, 1, [], TTextAlign.Leading, TTextAlign.Leading);
{$ELSE}
Canvas.FillText(RectF(txt.Pos.X, txt.Pos.Y, txt.Pos.X + tw, txt.Pos.Y + th), txt.Text, False, 1, [], TTextAlign.taLeading, TTextAlign.taLeading);
{$ENDIF}
end;
end;
end;
Canvas.RestoreState(st);
end;
procedure TForm88.TMSFMXToolBarButton1Click(Sender: TObject);
begin
FPaintCol.Clear;
PaintBox1.Repaint;
end;
procedure TForm88.TMSFMXToolBarButton2Click(Sender: TObject);
{$IFNDEF MOBILE}
var
sd: TSaveDialog;
str: String;
bmp: TBitmap;
{$ENDIF}
begin
{$IFDEF MOBILE}
ShowMessage('ToolBar Button event handling: Drawing saved');
{$ELSE}
sd := TSaveDialog.Create(Self);
sd.Filter := 'Portable Network Graphics (*.png)|*.png';
try
if sd.Execute then
begin
str := sd.FileName;
if not UpperCase(str).Contains('.PNG') then
str := str + '.png';
bmp := nil;
try
bmp := PaintBox1.MakeScreenshot;
if Assigned(bmp) then
begin
bmp.SaveToFile(str);
end;
finally
if Assigned(bmp) then
bmp.Free;
end;
end;
finally
sd.Free;
end;
{$ENDIF}
end;
procedure TForm88.TMSFMXToolBarButton3Click(Sender: TObject);
begin
TMSFMXToolBarButton3.DownState := not TMSFMXToolBarButton3.DownState;
TMSFMXToolBarButton4.DownState := False;
end;
procedure TForm88.TMSFMXToolBarButton4Click(Sender: TObject);
begin
TMSFMXToolBarButton4.DownState := not TMSFMXToolBarButton4.DownState;
TMSFMXToolBarButton3.DownState := False;
end;
procedure TForm88.TMSFMXToolBarColorPicker1Click(Sender: TObject);
begin
TMSFMXToolBarButton3.DownState := False;
end;
procedure TForm88.TMSFMXToolBarColorPicker1ColorSelected(Sender: TObject;
AColor: TAlphaColor);
begin
FActiveColor := AColor;
end;
procedure TForm88.TMSFMXToolBarFontSizePicker1FontSizeSelected(Sender: TObject;
AFontSize: Integer);
begin
FActiveThickness := AFontSize;
end;
{ TTMSFMXLineElement }
constructor TTMSFMXLineElement.Create;
begin
FPoints := TList<TPointF>.Create;
end;
end.
|
unit CCOW_const;
interface
const
// Note: set the 'CCOW' suffix to the suffix this app should look for in the context.
// Eg. Patient.ID.MRN.GeneralHospital, Patient.ID.MRN.VendorAppName, etc.
// This string is used during startup (to check for an existing context),
// during a commit event (to check the new context), etc.
//The VistA Domain
CCOW_LOGON_ID = 'user.id.logon.vistalogon'; //CCOW
//The VistA Token
CCOW_LOGON_TOKEN = 'user.id.logon.vistatoken'; //CCOW
//The VistA user Name
CCOW_LOGON_NAME = 'user.id.logon.vistaname'; //CCOW
// The VistA Vpid
CCOW_LOGON_VPID = 'user.id.logon.vpid';
// The generic name
CCOW_USER_NAME = 'user.co.name';
implementation
end.
|
unit csIdIOHandlerAdapter;
// Модуль: "w:\common\components\rtl\Garant\cs\csIdIOHandlerAdapter.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TcsIdIOHandlerAdapter" MUID: (538DB527006C)
{$Include w:\common\components\rtl\Garant\cs\CsDefine.inc}
interface
{$If NOT Defined(Nemesis)}
uses
l3IntfUses
, csIdIOHandlerAbstractAdapter
, IdIOHandler
, Classes
;
type
TcsIdIOHandlerAdapter = class(TcsIdIOHandlerAbstractAdapter)
private
f_IOHandler: TIdIOHandler;
protected
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aIOHandler: TIdIOHandler); reintroduce;
procedure WriteBufferFlush; override;
function ReadChar: AnsiChar; override;
function ReadCardinal: Cardinal; override;
function ReadDateTime: TDateTime; override;
function ReadLn: AnsiString; override;
function ReadInt64: Int64; override;
procedure ReadStream(aStream: TStream;
aSize: Int64 = -1); override;
function ReadInteger: Integer; override;
function ReadSmallInt: SmallInt; override;
procedure WriteLn(const aString: AnsiString); override;
procedure WriteCardinal(aValue: Cardinal); override;
procedure WriteInt64(aValue: Int64); override;
procedure WriteStream(aStream: TStream;
aByteCount: Int64 = 0); override;
procedure WriteChar(aValue: AnsiChar); override;
procedure WriteSmallInt(aValue: SmallInt); override;
procedure WriteInteger(aValue: Integer); override;
procedure WriteDateTime(aValue: TDateTime); override;
function Connected: Boolean; override;
procedure WriteFile(const aFile: AnsiString); override;
procedure WriteBufferOpen(AThreshhold: Integer); override;
procedure WriteBufferClose; override;
procedure WriteBufferClear; override;
function WaitForReadData(aTimeout: Integer): Boolean; override;
procedure InputBufferClear; override;
procedure WriteLargeStr(const aString: AnsiString); override;
function ReadLargeStr: AnsiString; override;
function ReadStreamWithCRCCheck(aStream: TStream;
CalcCRCFromBegin: Boolean = True;
ReadOffset: Int64 = 0;
ReadSize: Int64 = -1): Boolean; override;
procedure WriteStreamWithCRCCheck(aStream: TStream;
KeepPosition: Boolean = False); override;
function ReadBoolean: Boolean; override;
procedure WriteBoolean(aValue: Boolean); override;
end;//TcsIdIOHandlerAdapter
{$IfEnd} // NOT Defined(Nemesis)
implementation
{$If NOT Defined(Nemesis)}
uses
l3ImplUses
, IdGlobal
, l3Base
, l3Memory
, SysUtils
, l3CRCUtils
//#UC START# *538DB527006Cimpl_uses*
//#UC END# *538DB527006Cimpl_uses*
;
constructor TcsIdIOHandlerAdapter.Create(aIOHandler: TIdIOHandler);
//#UC START# *538DB5610283_538DB527006C_var*
//#UC END# *538DB5610283_538DB527006C_var*
begin
//#UC START# *538DB5610283_538DB527006C_impl*
inherited Create;
f_IOHandler := aIOHandler;
f_IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;
f_IOHandler.DefAnsiEncoding := IndyTextEncoding_UTF8;
//#UC END# *538DB5610283_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.Create
procedure TcsIdIOHandlerAdapter.WriteBufferFlush;
//#UC START# *538DB5C7002E_538DB527006C_var*
//#UC END# *538DB5C7002E_538DB527006C_var*
begin
//#UC START# *538DB5C7002E_538DB527006C_impl*
f_IOHandler.WriteBufferFlush;
//#UC END# *538DB5C7002E_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteBufferFlush
function TcsIdIOHandlerAdapter.ReadChar: AnsiChar;
//#UC START# *538DB5E90386_538DB527006C_var*
//#UC END# *538DB5E90386_538DB527006C_var*
begin
//#UC START# *538DB5E90386_538DB527006C_impl*
Result := f_IOHandler.ReadChar;
//#UC END# *538DB5E90386_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadChar
function TcsIdIOHandlerAdapter.ReadCardinal: Cardinal;
//#UC START# *538DB61100CA_538DB527006C_var*
//#UC END# *538DB61100CA_538DB527006C_var*
begin
//#UC START# *538DB61100CA_538DB527006C_impl*
Result := f_IOHandler.ReadUInt32;
//#UC END# *538DB61100CA_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadCardinal
function TcsIdIOHandlerAdapter.ReadDateTime: TDateTime;
//#UC START# *538DB62D02C7_538DB527006C_var*
var
l_Bytes: TIdBytes;
//#UC END# *538DB62D02C7_538DB527006C_var*
begin
//#UC START# *538DB62D02C7_538DB527006C_impl*
f_IOHandler.ReadBytes(l_Bytes, SizeOf(TDateTime));
Result := PDateTime(@l_Bytes[0])^;
//#UC END# *538DB62D02C7_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadDateTime
function TcsIdIOHandlerAdapter.ReadLn: AnsiString;
//#UC START# *538DB6520024_538DB527006C_var*
//#UC END# *538DB6520024_538DB527006C_var*
begin
//#UC START# *538DB6520024_538DB527006C_impl*
Result := f_IOHandler.ReadLn;
//#UC END# *538DB6520024_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadLn
function TcsIdIOHandlerAdapter.ReadInt64: Int64;
//#UC START# *538DB66D02EB_538DB527006C_var*
//#UC END# *538DB66D02EB_538DB527006C_var*
begin
//#UC START# *538DB66D02EB_538DB527006C_impl*
Result := f_IOHandler.ReadInt64;
//#UC END# *538DB66D02EB_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadInt64
procedure TcsIdIOHandlerAdapter.ReadStream(aStream: TStream;
aSize: Int64 = -1);
//#UC START# *538DB69000E7_538DB527006C_var*
//#UC END# *538DB69000E7_538DB527006C_var*
begin
//#UC START# *538DB69000E7_538DB527006C_impl*
f_IOHandler.ReadStream(aStream, aSize);
//#UC END# *538DB69000E7_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadStream
function TcsIdIOHandlerAdapter.ReadInteger: Integer;
//#UC START# *538DB78C01B0_538DB527006C_var*
//#UC END# *538DB78C01B0_538DB527006C_var*
begin
//#UC START# *538DB78C01B0_538DB527006C_impl*
Result := f_IOHandler.ReadInt32;
//#UC END# *538DB78C01B0_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadInteger
function TcsIdIOHandlerAdapter.ReadSmallInt: SmallInt;
//#UC START# *538DB7A4016D_538DB527006C_var*
//#UC END# *538DB7A4016D_538DB527006C_var*
begin
//#UC START# *538DB7A4016D_538DB527006C_impl*
Result := f_IOHandler.ReadSmallInt;
//#UC END# *538DB7A4016D_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadSmallInt
procedure TcsIdIOHandlerAdapter.WriteLn(const aString: AnsiString);
//#UC START# *538DB7E00144_538DB527006C_var*
//#UC END# *538DB7E00144_538DB527006C_var*
begin
//#UC START# *538DB7E00144_538DB527006C_impl*
f_IOHandler.WriteLn(aString);
//#UC END# *538DB7E00144_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteLn
procedure TcsIdIOHandlerAdapter.WriteCardinal(aValue: Cardinal);
//#UC START# *538DB804015E_538DB527006C_var*
//#UC END# *538DB804015E_538DB527006C_var*
begin
//#UC START# *538DB804015E_538DB527006C_impl*
f_IOHandler.Write(aValue);
//#UC END# *538DB804015E_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteCardinal
procedure TcsIdIOHandlerAdapter.WriteInt64(aValue: Int64);
//#UC START# *538DB83B021B_538DB527006C_var*
//#UC END# *538DB83B021B_538DB527006C_var*
begin
//#UC START# *538DB83B021B_538DB527006C_impl*
f_IOHandler.Write(aValue);
//#UC END# *538DB83B021B_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteInt64
procedure TcsIdIOHandlerAdapter.WriteStream(aStream: TStream;
aByteCount: Int64 = 0);
//#UC START# *538DB86700DB_538DB527006C_var*
//#UC END# *538DB86700DB_538DB527006C_var*
begin
//#UC START# *538DB86700DB_538DB527006C_impl*
f_IOHandler.Write(aStream, aByteCount, True);
//#UC END# *538DB86700DB_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteStream
procedure TcsIdIOHandlerAdapter.WriteChar(aValue: AnsiChar);
//#UC START# *538DB8970317_538DB527006C_var*
//#UC END# *538DB8970317_538DB527006C_var*
begin
//#UC START# *538DB8970317_538DB527006C_impl*
f_IOHandler.Write(aValue);
//#UC END# *538DB8970317_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteChar
procedure TcsIdIOHandlerAdapter.WriteSmallInt(aValue: SmallInt);
//#UC START# *538DB8BA00D1_538DB527006C_var*
//#UC END# *538DB8BA00D1_538DB527006C_var*
begin
//#UC START# *538DB8BA00D1_538DB527006C_impl*
f_IOHandler.Write(aValue);
//#UC END# *538DB8BA00D1_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteSmallInt
procedure TcsIdIOHandlerAdapter.WriteInteger(aValue: Integer);
//#UC START# *538DB8DF029E_538DB527006C_var*
//#UC END# *538DB8DF029E_538DB527006C_var*
begin
//#UC START# *538DB8DF029E_538DB527006C_impl*
f_IOHandler.Write(aValue);
//#UC END# *538DB8DF029E_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteInteger
procedure TcsIdIOHandlerAdapter.WriteDateTime(aValue: TDateTime);
//#UC START# *538DB9070097_538DB527006C_var*
var
l_Bytes: TIdBytes;
//#UC END# *538DB9070097_538DB527006C_var*
begin
//#UC START# *538DB9070097_538DB527006C_impl*
SetLength(l_Bytes, SizeOf(aValue));
try
l3Move(aValue, l_Bytes[0], SizeOf(aValue));
f_IOHandler.Write(l_Bytes);
finally
l_Bytes := nil;
end;//try..finally
//#UC END# *538DB9070097_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteDateTime
function TcsIdIOHandlerAdapter.Connected: Boolean;
//#UC START# *538DB93002B5_538DB527006C_var*
//#UC END# *538DB93002B5_538DB527006C_var*
begin
//#UC START# *538DB93002B5_538DB527006C_impl*
Result := f_IOHandler.Connected;
//#UC END# *538DB93002B5_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.Connected
procedure TcsIdIOHandlerAdapter.WriteFile(const aFile: AnsiString);
//#UC START# *538DB9810192_538DB527006C_var*
//#UC END# *538DB9810192_538DB527006C_var*
begin
//#UC START# *538DB9810192_538DB527006C_impl*
f_IOHandler.WriteFile(aFile, false);
//#UC END# *538DB9810192_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteFile
procedure TcsIdIOHandlerAdapter.WriteBufferOpen(AThreshhold: Integer);
//#UC START# *538DB9C40271_538DB527006C_var*
//#UC END# *538DB9C40271_538DB527006C_var*
begin
//#UC START# *538DB9C40271_538DB527006C_impl*
f_IOHandler.WriteBufferOpen(AThreshhold);
//#UC END# *538DB9C40271_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteBufferOpen
procedure TcsIdIOHandlerAdapter.WriteBufferClose;
//#UC START# *538DB9F30058_538DB527006C_var*
//#UC END# *538DB9F30058_538DB527006C_var*
begin
//#UC START# *538DB9F30058_538DB527006C_impl*
f_IOHandler.WriteBufferClose;
//#UC END# *538DB9F30058_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteBufferClose
procedure TcsIdIOHandlerAdapter.WriteBufferClear;
//#UC START# *538DBA0B009F_538DB527006C_var*
//#UC END# *538DBA0B009F_538DB527006C_var*
begin
//#UC START# *538DBA0B009F_538DB527006C_impl*
f_IOHandler.WriteBufferClear;
//#UC END# *538DBA0B009F_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteBufferClear
function TcsIdIOHandlerAdapter.WaitForReadData(aTimeout: Integer): Boolean;
//#UC START# *54536C8F036B_538DB527006C_var*
//#UC END# *54536C8F036B_538DB527006C_var*
begin
//#UC START# *54536C8F036B_538DB527006C_impl*
Result := (f_IOHandler.InputBuffer.Size > 0) or f_IOHandler.Readable(aTimeOut);
//#UC END# *54536C8F036B_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WaitForReadData
procedure TcsIdIOHandlerAdapter.InputBufferClear;
//#UC START# *5476EDF200B5_538DB527006C_var*
//#UC END# *5476EDF200B5_538DB527006C_var*
begin
//#UC START# *5476EDF200B5_538DB527006C_impl*
if Assigned(f_IOHandler.InputBuffer) then
f_IOHandler.InputBuffer.Clear;
//#UC END# *5476EDF200B5_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.InputBufferClear
procedure TcsIdIOHandlerAdapter.WriteLargeStr(const aString: AnsiString);
//#UC START# *54F5C07302CC_538DB527006C_var*
var
l_Stream: TStream;
//#UC END# *54F5C07302CC_538DB527006C_var*
begin
//#UC START# *54F5C07302CC_538DB527006C_impl*
WriteCardinal(Length(aString));
if Length(aString) > 0 then
begin
l_Stream := Tl3ConstMemoryStream.Create(@AString[1], Length(aString)*SizeOf(aString[1]));
try
WriteStream(l_Stream);
finally
FreeAndNil(l_Stream);
end;
end;
//#UC END# *54F5C07302CC_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteLargeStr
function TcsIdIOHandlerAdapter.ReadLargeStr: AnsiString;
//#UC START# *54F5C09C0302_538DB527006C_var*
var
l_Stream: TStream;
l_Size: Integer;
//#UC END# *54F5C09C0302_538DB527006C_var*
begin
//#UC START# *54F5C09C0302_538DB527006C_impl*
l_Size := ReadCardinal;
SetLength(Result, l_Size);
if Length(Result) > 0 then
begin
l_Stream := Tl3ConstMemoryStream.Create(@Result[1], Length(Result)*SizeOf(Result[1]));
try
ReadStream(l_Stream);
finally
FreeAndNil(l_Stream);
end;
end;
//#UC END# *54F5C09C0302_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadLargeStr
function TcsIdIOHandlerAdapter.ReadStreamWithCRCCheck(aStream: TStream;
CalcCRCFromBegin: Boolean = True;
ReadOffset: Int64 = 0;
ReadSize: Int64 = -1): Boolean;
//#UC START# *580F367C0052_538DB527006C_var*
var
l_SizeToRead: Int64;
l_CalcCRCFromBegin: Byte;
l_LocalCRC: Cardinal;
l_BufferLength: Integer;
l_Buffer: TIdBytes;
l_Readed: Int64;
l_CheckCRC: Cardinal;
//#UC END# *580F367C0052_538DB527006C_var*
begin
//#UC START# *580F367C0052_538DB527006C_impl*
Result := False;
f_IOHandler.Write(ReadOffset);
f_IOHandler.Write(ReadSize);
WriteBufferFlush;
l_SizeToRead := f_IOHandler.ReadInt64;
if l_SizeToRead = 0 then
Exit;
if CalcCRCFromBegin then
l_CalcCRCFromBegin := 1
else
l_CalcCRCFromBegin := 0;
f_IOHandler.Write(l_CalcCRCFromBegin);
WriteBufferFlush;
if CalcCRCFromBegin then
l_LocalCRC := l3CalcCRC32(aStream, 0, ReadOffset)
else
l_LocalCRC := l3CalcCRC32(aStream, ReadOffset, 0);
l_BufferLength := f_IOHandler.ReadInt32;
SetLength(l_Buffer, l_BufferLength);
try
while l_SizeToRead > 0 do
begin
f_IOHandler.ReadBytes(l_Buffer, l_BufferLength, False);
l3AccumulateBufferCRC32(l_LocalCRC, @l_Buffer[0], l_BufferLength);
aStream.WriteBuffer(l_Buffer[0], l_BufferLength);
l_SizeToRead := l_SizeToRead - l_BufferLength;
if l_BufferLength > l_SizeToRead then
l_BufferLength := l_SizeToRead;
end;
finally
SetLength(l_Buffer, 0);
end;
l_CheckCRC := f_IOHandler.ReadInt32;
Result := l_CheckCRC = l_LocalCRC;
//#UC END# *580F367C0052_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadStreamWithCRCCheck
procedure TcsIdIOHandlerAdapter.WriteStreamWithCRCCheck(aStream: TStream;
KeepPosition: Boolean = False);
//#UC START# *580F36A802FA_538DB527006C_var*
var
l_Offset: Int64;
l_Size: Int64;
l_SizeToWrite: Int64;
l_CalcCRCFromBegin: Byte;
l_LocalCRC: Cardinal;
l_Buffer: TIdBytes;
l_OldPosition: Int64;
l_Readed: Int64;
l_BufferLength: Integer;
//#UC END# *580F36A802FA_538DB527006C_var*
begin
//#UC START# *580F36A802FA_538DB527006C_impl*
l_OldPosition := aStream.Position;
try
l_Offset := f_IOHandler.ReadInt64;
l_Size := f_IOHandler.ReadInt64;
if l_Size = -1 then
l_Size := aStream.Size - l_Offset;
l_SizeToWrite := aStream.Size - l_Offset;
if l_SizeToWrite < 0 then
l_SizeToWrite := 0;
if l_SizeToWrite > l_Size then
l_SizeToWrite := l_Size;
f_IOHandler.Write(l_SizeToWrite);
WriteBufferFlush;
if l_SizeToWrite = 0 then
Exit;
l_CalcCRCFromBegin := f_IOHandler.ReadByte;
if l_CalcCRCFromBegin = 1 then
l_LocalCRC := l3CalcCRC32(aStream, 0, l_Offset)
else
l_LocalCRC := l3CalcCRC32(aStream, l_Offset, 0);
l_BufferLength := f_IOHandler.SendBufferSize;
f_IOHandler.Write(l_BufferLength);
WriteBufferFlush;
SetLength(l_Buffer, l_BufferLength);
try
while l_SizeToWrite > 0 do
begin
l_Readed := aStream.Read(l_Buffer[0], l_BufferLength);
Assert(l_Readed = l_SizeToWrite);
l3AccumulateBufferCRC32(l_LocalCRC, @l_Buffer[0], l_BufferLength);
f_IOHandler.Write(l_Buffer, l_BufferLength);
l_SizeToWrite := l_SizeToWrite - l_Readed;
if l_BufferLength > l_SizeToWrite then
l_BufferLength := l_SizeToWrite;
end;
finally
SetLength(l_Buffer, 0);
end;
f_IOHandler.Write(l_LocalCRC);
WriteBufferFlush;
finally
if KeepPosition then
aStream.Seek(l_OldPosition, soBeginning);
end;
//#UC END# *580F36A802FA_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteStreamWithCRCCheck
function TcsIdIOHandlerAdapter.ReadBoolean: Boolean;
//#UC START# *58172754028B_538DB527006C_var*
//#UC END# *58172754028B_538DB527006C_var*
begin
//#UC START# *58172754028B_538DB527006C_impl*
Result := f_IOHandler.ReadByte = 1;
//#UC END# *58172754028B_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.ReadBoolean
procedure TcsIdIOHandlerAdapter.WriteBoolean(aValue: Boolean);
//#UC START# *581727750209_538DB527006C_var*
const
cMap: array [Boolean] of Byte = (0, 1);
//#UC END# *581727750209_538DB527006C_var*
begin
//#UC START# *581727750209_538DB527006C_impl*
f_IOHandler.Write(cMap[aValue]);
//#UC END# *581727750209_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.WriteBoolean
procedure TcsIdIOHandlerAdapter.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_538DB527006C_var*
//#UC END# *479731C50290_538DB527006C_var*
begin
//#UC START# *479731C50290_538DB527006C_impl*
f_IOHandler := nil;
inherited;
//#UC END# *479731C50290_538DB527006C_impl*
end;//TcsIdIOHandlerAdapter.Cleanup
{$IfEnd} // NOT Defined(Nemesis)
end.
|
unit apiSMS;
{ DEFINE TEST_SMS}
interface
uses SysUtils, Classes, DateUtils, Types, Windows, vcl.dialogs,
httpsend, SynaUtil, DB, FIBQuery, pFIBQuery,
System.Generics.Collections, JsonDataObjects;
const
// Константы для отправки SMS по SMTP
API_URL: String = 'http://a4on.tv/sms/sms/';
type
TCountry = (cRU, cBY, cUA);
TSMS = record
a4ID: Integer;
smsID: Integer;
phone: string;
Text: string;
date: TDateTime;
status: Integer;
end;
TSMSList = TList<TSMS>;
TSMSapi = class
private
fA4ON_USER: string;
fA4ON_KEY: string;
fError: String;
fHTTP: THTTPSend;
fBalance: Integer;
fCountry: TCountry;
function GetBalance: Integer;
function BalanceFromA4on: Integer;
function CorrectPhone(const phone: string): string;
function POST2A4ON(const action: string; soData: JsonDataObjects.TJSONObject): string;
public
property ErrorText: string read fError;
property Balance: Integer read GetBalance;
// Отправить список смс и вернуть кол-во отправленных смс
function SMSCount(const Text: string): Integer;
function SendList(list: TSMSList): Integer;
function SendAll(var ErrorText: String): Integer;
function CheckAll: Integer;
function StatusList(list: TSMSList): Integer;
constructor Create(const user: string; const key: string; const country: string = 'RU');
destructor Destroy; override;
end;
implementation
uses SynCrypto, ZLibExGZ, RegularExpressions, DM, AtrStrUtils;
constructor TSMSapi.Create(const user: string; const key: string; const country: string = 'RU');
begin
fA4ON_USER := user;
fA4ON_KEY := key;
if AnsiUpperCase(country) = 'BY'
then fCountry := cBY
else if AnsiUpperCase(country) = 'UA'
then fCountry := cUA
else fCountry := cRU;
fHTTP := THTTPSend.Create;
// Получим баланс сразу
fBalance := BalanceFromA4on();
end;
destructor TSMSapi.Destroy;
begin
FreeAndNil(fHTTP);
inherited Destroy;
end;
function TSMSapi.POST2A4ON(const action: string; soData: JsonDataObjects.TJSONObject): string;
var
strmData: TStringStream;
s: UTF8String;
begin
fError := '';
soData['login'] := fA4ON_USER;
soData['password'] := fA4ON_KEY;
s := soData.ToString;
soData['hash'] := MD5(s);
strmData := TStringStream.Create(soData.ToString, TEncoding.UTF8);
try
// strmData.WriteString();
fHTTP.TargetHost := 'a4on.tv';
fHTTP.Protocol := '1.1';
fHTTP.MimeType := 'application/x-www-form-urlencoded';
// fHTTP.Headers.Add('Accept-Encoding: gzip,deflate');
fHTTP.Document.LoadFromStream(strmData);
{$IFDEF TEST_SMS}
fHTTP.Document.SaveToFile('b:\' + action + '.request.JDO.js'); // for debug
{$ENDIF}
fHTTP.HTTPMethod('post', API_URL + action + '/');
strmData.Clear;
HeadersToList(fHTTP.Headers);
if Trim(fHTTP.Headers.Values['Content-Encoding']) = 'gzip'
then begin
GZDecompressStream(fHTTP.Document, strmData);
Result := strmData.DataString;
end
else begin
strmData.LoadFromStream(fHTTP.Document);
{$IFDEF TEST_SMS}
fHTTP.Document.SaveToFile('b:\' + action + '.Answer.js'); // for debug
{$ENDIF}
Result := strmData.DataString;
end;
finally strmData.Free;
end
end;
function TSMSapi.BalanceFromA4on: Integer;
var
Str: string;
Obj: JsonDataObjects.TJSONObject;
begin
Result := 0;
Obj := JsonDataObjects.TJSONObject.Create;
try Str := POST2A4ON('balance', Obj);
finally Obj.Free;
end;
Obj := TJSONObject.Parse(Str) as TJSONObject;
try
if Obj.IndexOf('sms_count') >= 0
then begin
Result := Obj['sms_count'];
end
else begin
if Obj.IndexOf('error') >= 0
then fError := Obj['error'];
if Obj.IndexOf('text') >= 0
then fError := fError + ':' + Obj['text'];
end
finally Obj.Free;
end;
end;
function TSMSapi.GetBalance: Integer;
begin
Result := fBalance;
end;
function TSMSapi.CorrectPhone(const phone: string): string;
const
pfRU: string = '^79[0-9]{9}$';
pfBY: string = '^375(24|25|29|33|44)[1-9]{1}[0-9]{6}$';
pfUA: string = '^380(50|63|66|67|68|91|92|93|94|95|96|97|98|99)[0-9]{7}$';
function CorrectBY(const p: string): string;
const
prefix: string = '375';
var
l: Integer;
s: string;
begin
Result := '';
l := Length(p);
case l of
12: if Copy(p, 1, 3) = prefix then Result := p;
9: Result := prefix + p; // 297346934
else begin
if l >= 11
then begin
// 80297349634
s := Copy(p, 1, 2);
if s = '80'
then Result := prefix + Copy(p, 3, 9);
end;
end;
end;
if not TRegEx.IsMatch(Result, pfBY)
then Result := '';
end;
function CorrectUA(const p: string): string;
const
prefix: string = '380';
begin
Result := p;
if not TRegEx.IsMatch(Result, pfUA)
then Result := '';
end;
function CorrectRU(const p: string): string;
const
prefix: string = '7';
var
l: Integer;
begin
Result := '';
l := Length(p);
case l of
11: if Copy(p, 1, 1) = '8' then Result := prefix + Copy(p, 2, 10);
10: Result := prefix + p; // 297346934
end;
if not TRegEx.IsMatch(Result, pfRU)
then Result := '';
end;
var
s: string;
tp: string;
begin
Result := '';
tp := DigitsOnly(phone);
case fCountry of
cRU: s := pfRU;
cBY: s := pfBY;
cUA: s := pfUA;
end;
if not TRegEx.IsMatch(tp, s)
then begin
s := tp;
case fCountry of
cRU: Result := CorrectRU(s);
cBY: Result := CorrectBY(s);
cUA: Result := CorrectUA(s);
end;
end
else Result := tp;
end;
function TSMSapi.SMSCount(const Text: string): Integer;
begin
Result := 1;
// public function abtSMScount($text) {
// /* Считаем Приблизительное количество SMS в сообщении
// SMS CYR ENG
// 1 70 160
// 2 134 306
// 3 201 459
// 4 268 612
// */
// $len = mb_strlen($text, 'UTF-8');
// $cnt = 0;
// if (preg_match('/[А-Я\^\{\}\[\]\|\\\~]/i',$text)) {
// if ($len<=70) $cnt = 1;
// elseif (($len>70) and ($len < 134)) $cnt = 2;
// elseif (($len>=134) and ($len < 201)) $cnt = 3;
// elseif (($len>=201) and ($len < 268)) $cnt = 4;
// elseif (($len>=268) and ($len < 335)) $cnt = 5;
// else $cnt = 6;
// }
// else {
// if ($len <= 160) $cnt = 1;
// elseif (($len>=160) and ($len < 306)) $cnt = 2;
// elseif (($len>=134) and ($len < 459)) $cnt = 3;
// elseif (($len>=201) and ($len < 612)) $cnt = 4;
// elseif (($len>=268) and ($len < 765)) $cnt = 5;
// else $cnt = 6;
// }
// return $cnt;
// }
end;
function TSMSapi.SendList(list: TSMSList): Integer;
var
sms: TSMS;
Str: string;
i, j: Integer;
a4ID: Integer;
Obj, ChildObj: JsonDataObjects.TJSONObject;
begin
Result := 0;
if not Assigned(list)
then Exit;
if list.Count = 0
then Exit;
Obj := JsonDataObjects.TJSONObject.Create;
for i := 0 to list.Count - 1 do begin
Str := CorrectPhone(list[i].phone);
if Str <> ''
then begin
// если корректный номер - то продолжим
ChildObj := Obj.A['messages'].AddObject;
ChildObj['a4id'] := list[i].a4ID;
ChildObj['phone'] := Str;
ChildObj['text'] := list[i].Text;
if list[i].date <> 0
then ChildObj['date'] := FormatDateTime('YYYY-mm-dd', list[i].date) + 'T' + FormatDateTime('hh:nn:00+00:00',
list[i].date);
end
else begin
sms := list[i];
sms.status := -6; // не верный номер
list[i] := sms;
end;
end;
if Obj.Count > 0
then begin
try
Str := POST2A4ON('send', Obj);
finally
Obj.Free;
end;
Obj := TJSONObject.Parse(Str) as TJSONObject;
try
if Obj.IndexOf('sms_count') = 0
then fBalance := Obj['sms_count'];
// Если массив с заданным именем найден
if Obj.IndexOf('messages') >= 0
then begin
// Получили массив по имени
for i := 0 to Obj['messages'].Count - 1 do begin
a4ID := Obj['messages'].Items[i]['a4id'];
for j := 0 to list.Count - 1 do
if a4ID = list[j].a4ID
then begin
sms := list[j];
sms.smsID := Obj['messages'].Items[i]['smsId'];
sms.status := Obj['messages'].Items[i]['state'];
sms.Text := Obj['messages'].Items[i]['text'];
list[j] := sms;
end;
end;
Result := Obj['messages'].Count;
end;
finally
Obj.Free;
end;
end
else Obj.Free;
end;
function TSMSapi.SendAll(var ErrorText: String): Integer;
var
i: Integer;
rSMS: TpFIBQuery;
uSMS: TpFIBQuery;
SMSList: TSMSList;
sms: TSMS;
// trR : TpFIBTransaction;
// trW : TpFIBTransaction;
begin
Result := 0;
ErrorText := '';
rSMS := TpFIBQuery.Create(nil);
uSMS := TpFIBQuery.Create(nil);
SMSList := TSMSList.Create;
try
rSMS.DataBase := dmMain.dbTV;
rSMS.Transaction := dmMain.trReadQ;
rSMS.SQL.Add('select m.reciver as PHONE, M.Mes_Text, m.Mes_Id ');
rSMS.SQL.Add(' from messages m ');
rSMS.SQL.Add(' where m.mes_result = 0 and m.Mes_Type = ''SMS'' ');
rSMS.SQL.Add(' order by m.mes_prior desc ');
rSMS.Transaction.StartTransaction;
rSMS.ExecQuery;
while not rSMS.EOF do begin
sms.a4ID := rSMS.fn('Mes_Id').AsInteger;
sms.phone := rSMS.fn('PHONE').AsString;
sms.Text := rSMS.fn('Mes_Text').AsString;
SMSList.Add(sms);
rSMS.NEXT;
end;
rSMS.Transaction.Commit;
if SMSList.Count > 0
then begin
// если есть что отправлять
SendList(SMSList);
uSMS.DataBase := dmMain.dbTV;
uSMS.Transaction := dmMain.trWriteQ;
uSMS.SQL.Text := ' update Messages set Mes_Result = :Mes_Result, ext_id = :ext_id where Mes_Id = :Mes_Id ';
for i := 0 to SMSList.Count - 1 do begin
uSMS.Transaction.StartTransaction;
uSMS.ParamByName('Mes_Id').AsInteger := SMSList[i].a4ID;
uSMS.ParamByName('Mes_Result').AsInteger := SMSList[i].status;
uSMS.ParamByName('ext_id').AsInteger := SMSList[i].smsID;
uSMS.ExecQuery;
uSMS.Transaction.Commit;
end;
end;
finally
SMSList.Free;
rSMS.Free;
uSMS.Free;
end;
end;
function TSMSapi.StatusList(list: TSMSList): Integer;
var
sms: TSMS;
Str: string;
i, j: Integer;
a4ID: Integer;
Obj, ChildObj: JsonDataObjects.TJSONObject;
begin
Result := 0;
if not Assigned(list)
then Exit;
if list.Count = 0
then Exit;
Obj := JsonDataObjects.TJSONObject.Create;
for i := 0 to list.Count - 1 do begin
// если корректный номер - то продолжим
ChildObj := Obj.A['messages'].AddObject;
ChildObj['a4id'] := list[i].a4ID;
ChildObj['smsId'] := list[i].smsID;
end;
if Obj.Count > 0
then begin
try
Str := POST2A4ON('status', Obj);
finally
Obj.Free;
end;
Obj := TJSONObject.Parse(Str) as TJSONObject;
try
if Obj.IndexOf('sms_count') = 0
then fBalance := Obj['sms_count'];
// Если массив с заданным именем найден
if Obj.IndexOf('messages') >= 0
then begin
// Получили массив по имени
for i := 0 to Obj['messages'].Count - 1 do begin
a4ID := Obj['messages'].Items[i]['a4id'];
for j := 0 to list.Count - 1 do
if a4ID = list[j].a4ID
then begin
sms := list[j];
sms.status := Obj['messages'].Items[i]['state'];
list[j] := sms;
end;
end;
Result := Obj['messages'].Count;
end;
finally
Obj.Free;
end;
end
else Obj.Free;
end;
function TSMSapi.CheckAll: Integer;
var
SMSList: TSMSList;
sms: TSMS;
i: Integer;
rSMS: TpFIBQuery;
uSMS: TpFIBQuery;
begin
Result := 0;
SMSList := TSMSList.Create;
rSMS := TpFIBQuery.Create(nil);
uSMS := TpFIBQuery.Create(nil);
try
rSMS.DataBase := dmMain.dbTV;
rSMS.Transaction := dmMain.trReadQ;
rSMS.SQL.Add('select Mes_Id, ext_id from messages m where m.mes_result = 1 and (not ext_id is NULL) and m.Mes_Type = ''SMS'' ');
rSMS.Transaction.StartTransaction;
rSMS.ExecQuery;
while not rSMS.EOF do begin
sms.a4ID := rSMS.fn('Mes_Id').AsInteger;
sms.smsID := rSMS.fn('ext_id').AsInteger;
SMSList.Add(sms);
rSMS.NEXT;
end;
rSMS.Transaction.Commit;
if SMSList.Count > 0
then begin
// если есть что отправлять
StatusList(SMSList);
uSMS.DataBase := dmMain.dbTV;
uSMS.Transaction := dmMain.trWriteQ;
uSMS.SQL.Text := ' update Messages set Mes_Result = :Mes_Result where Mes_Id = :Mes_Id ';
for i := 0 to SMSList.Count - 1 do begin
// 18, 19 - в очереди на сервере отправки смс
if not (SMSList[i].status in [0,1,18,19]) then begin
uSMS.Transaction.StartTransaction;
uSMS.ParamByName('Mes_Id').AsInteger := SMSList[i].a4ID;
uSMS.ParamByName('Mes_Result').AsInteger := SMSList[i].status;
// uSMS.ParamByName('ext_id').AsInteger := SMSList[i].smsID;
uSMS.ExecQuery;
uSMS.Transaction.Commit;
end;
end;
Result := SMSList.Count;
end;
finally
SMSList.Free;
rSMS.Free;
uSMS.Free;
end;
end;
end.
|
//Exercicio 32: Escreva um algoritmo que receba do usuário 4 números inteiros e, informe se há ou não um deles no
//intervalo entre 1 e 25, outro de 26 a 50, outro de 51 a 75, e um último de 76 a 100.
{ Solução em Portugol.
Algoritmo Exercicio 32;
Var
N1,N2,N3,N4: inteiro;
Inicio
exiba("Programa que diz se números estão em certos intervalos.");
exiba("Digite o primeiro número: ");
leia(N1);
exiba("Digite o segundo número: ");
leia(N2);
exiba("Digite o terceiro número: ");
leia(N3);
exiba("Digite o quarto número: ");
leia(N4);
se(((N1 >= 1) e (N1 <= 25)) ou ((N2 >= 1) e (N2 <= 25)) ou ((N3 >= 1) e (N3 <= 25)) ou ((N4 >= 1) e (N4 <= 25)))
então exiba("Um dos números está no intervalo 1-25.");
senão exiba("Nenhum dos números está no intervalo 1-25.");
fimse;
se(((N1 >= 26) e (N1 <= 50)) ou ((N2 >= 26) e (N2 <= 50)) ou ((N3 >= 26) e (N3 <= 50)) ou ((N4 >= 26) e (N4 <= 50)))
então exiba("Um dos números está no intervalo 26-50.");
senão exiba("Nenhum dos números está no intervalo 26-50.");
fimse;
se(((N1 >= 51) e (N1 <= 75)) ou ((N2 >= 51) e (N2 <= 75)) ou ((N3 >= 51) e (N3 <= 75)) ou ((N4 >= 51) e (N4 <= 75)))
então exiba("Um dos números está no intervalo 51-75.");
senão exiba("Nenhum dos números está no intervalo 51-75.");
fimse;
se(((N1 >= 76) e (N1 <= 100)) ou ((N2 >= 76) e (N2 <= 100)) ou ((N3 >= 76) e (N3 <= 100)) ou ((N4 >= 76) e (N4 <= 100)))
então exiba("Um dos números está no intervalo 76-100.");
senão exiba("Nenhum dos números está no intervalo 76-100.");
fimse;
Fim.
}
// Solução em Pascal
Program Exercicio32;
uses crt;
const
const1 = 1;
var
N1,N2,N3,N4: integer;
begin
clrscr;
writeln('Programa que diz se números estão em certos intervalos.');
writeln('Digite o primeiro número: ');
readln(N1);
writeln('Digite o segundo número: ');
readln(N2);
writeln('Digite o terceiro número: ');
readln(N3);
writeln('Digite o quarto número: ');
readln(N4);
if(((N1 >= 1) and (N1 <= 25)) or ((N2 >= 1) and (N2 <= 25)) or ((N3 >= 1) and (N3 <= 25)) or ((N4 >= 1) and (N4 <= 25)))
then writeln('Um dos números está no intervalo 1-25.')
else writeln('Nenhum dos números está no intervalo 1-25.');
if(((N1 >= 26) and (N1 <= 50)) or ((N2 >= 26) and (N2 <= 50)) or ((N3 >= 26) and (N3 <= 50)) or ((N4 >= 26) and (N4 <= 50)))
then writeln('Um dos números está no intervalo 26-50.')
else writeln('Nenhum dos números está no intervalo 26-50.');
if(((N1 >= 51) and (N1 <= 75)) or ((N2 >= 51) and (N2 <= 75)) or ((N3 >= 51) and (N3 <= 75)) or ((N4 >= 51) and (N4 <= 75)))
then writeln('Um dos números está no intervalo 51-75.')
else writeln('Nenhum dos números está no intervalo 51-75.');
if(((N1 >= 76) and (N1 <= 100)) or ((N2 >= 76) and (N2 <= 100)) or ((N3 >= 76) and (N3 <= 100)) or ((N4 >= 76) and (N4 <= 100)))
then writeln('Um dos números está no intervalo 76-100.')
else writeln('Nenhum dos números está no intervalo 76-100.');
repeat until keypressed;
end. |
unit vcmToolbarMenuRes;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "VCM"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/gui/Garant/VCM/implementation/vcmToolbarMenuRes.pas"
// Начат: 10.03.2010 13:40
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::VCM::vcmL10nImpl::vcmToolbarMenuRes
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc}
interface
{$If not defined(NoVCM)}
uses
l3Interfaces,
afwInterfaces,
l3StringIDEx
;
type
TvcmGlyphSize = (
vcm_gsAutomatic
, vcm_gs16x16
, vcm_gs24x24
, vcm_gs32x32
);//TvcmGlyphSize
var
{ Локализуемые строки vcmIconSize }
str_vcmgsAutomatic : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmgsAutomatic'; rValue : 'Автоматически');
{ 'Автоматически' }
str_vcmgs16x16 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmgs16x16'; rValue : 'Маленькие');
{ 'Маленькие' }
str_vcmgs24x24 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmgs24x24'; rValue : 'Средние');
{ 'Средние' }
str_vcmgs32x32 : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmgs32x32'; rValue : 'Большие');
{ 'Большие' }
const
{ Карта преобразования локализованных строк vcmIconSize }
vcmIconSizeMap : array [TvcmGlyphSize] of Pl3StringIDEx = (
@str_vcmgsAutomatic
, @str_vcmgs16x16
, @str_vcmgs24x24
, @str_vcmgs32x32
);//vcmIconSizeMap
type
vcmIconSizeMapHelper = {final} class
{* Утилитный класс для преобразования значений vcmIconSizeMap }
public
// public methods
class procedure FillStrings(const aStrings: IafwStrings);
{* Заполнение списка строк значениями }
class function DisplayNameToValue(const aDisplayName: Il3CString): TvcmGlyphSize;
{* Преобразование строкового значения к порядковому }
end;//vcmIconSizeMapHelper
{$IfEnd} //not NoVCM
implementation
{$If not defined(NoVCM)}
uses
l3MessageID,
l3String,
SysUtils
;
// start class vcmIconSizeMapHelper
class procedure vcmIconSizeMapHelper.FillStrings(const aStrings: IafwStrings);
var
l_Index: TvcmGlyphSize;
begin
aStrings.Clear;
for l_Index := Low(l_Index) to High(l_Index) do
aStrings.Add(vcmIconSizeMap[l_Index].AsCStr);
end;//vcmIconSizeMapHelper.FillStrings
class function vcmIconSizeMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): TvcmGlyphSize;
var
l_Index: TvcmGlyphSize;
begin
for l_Index := Low(l_Index) to High(l_Index) do
if l3Same(aDisplayName, vcmIconSizeMap[l_Index].AsCStr) then
begin
Result := l_Index;
Exit;
end;//l3Same..
raise Exception.CreateFmt('Display name "%s" not found in map "vcmIconSizeMap"', [l3Str(aDisplayName)]);
end;//vcmIconSizeMapHelper.DisplayNameToValue
{$IfEnd} //not NoVCM
initialization
{$If not defined(NoVCM)}
// Инициализация str_vcmgsAutomatic
str_vcmgsAutomatic.Init;
{$IfEnd} //not NoVCM
{$If not defined(NoVCM)}
// Инициализация str_vcmgs16x16
str_vcmgs16x16.Init;
{$IfEnd} //not NoVCM
{$If not defined(NoVCM)}
// Инициализация str_vcmgs24x24
str_vcmgs24x24.Init;
{$IfEnd} //not NoVCM
{$If not defined(NoVCM)}
// Инициализация str_vcmgs32x32
str_vcmgs32x32.Init;
{$IfEnd} //not NoVCM
end. |
unit EncForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
type
TFormEncode = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
Panel1: TPanel;
BtnLoadPlain: TButton;
BtnSaveEncoded: TButton;
BtnLoadEncoded: TButton;
Splitter1: TSplitter;
procedure BtnSaveEncodedClick(Sender: TObject);
procedure BtnLoadEncodedClick(Sender: TObject);
procedure BtnLoadPlainClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormEncode: TFormEncode;
implementation
{$R *.DFM}
uses
EncodStr;
procedure TFormEncode.BtnSaveEncodedClick(Sender: TObject);
var
EncStr: TEncodedStream;
begin
if SaveDialog1.Execute then
begin
EncStr := TEncodedStream.Create(
SaveDialog1.Filename, fmCreate);
try
Memo1.Lines.SaveToStream (EncStr);
finally
EncStr.Free;
end;
end;
end;
procedure TFormEncode.BtnLoadEncodedClick(Sender: TObject);
var
EncStr: TEncodedStream;
begin
if OpenDialog1.Execute then
begin
EncStr := TEncodedStream.Create(
OpenDialog1.FileName, fmOpenRead);
try
Memo2.Lines.LoadFromStream (EncStr);
finally
EncStr.Free;
end;
end;
end;
procedure TFormEncode.BtnLoadPlainClick(Sender: TObject);
begin
if OpenDialog1.Execute then
Memo1.Lines.LoadFromFile (
OpenDialog1.FileName);
end;
end.
|
unit ConfFile;
interface
Uses Classes, SysUtils, SchObject;
Type
ESchFileError = class(ESchException);
TSchConfFile = class( TSchObject )
private
fValueList,
fNameList : TStrings;
fFile : String;
function GetValue(Index: String): String;
procedure SetValue(Index: String; const Value: String);
function GetBValue(Index: String): Boolean;
function GetIValue(Index: String): Integer;
procedure SetBValue(Index: String; const Value: Boolean);
procedure SetIValue(Index: String; const Value: Integer);
public
constructor Create( AFile : String );
destructor Destroy(); override;
procedure Save();
procedure Load();
property sValue[ Index : String ] : String read GetValue write SetValue;
property iValue[ Index : String ] : Integer read GetIValue write SetIValue;
property bValue[ Index : String ] : Boolean read GetBValue write SetBValue;
property Names : TStrings read fNameList;
property Values : TStrings read fValueList;
end;
implementation
{ TSchConfFile }
function atoi( sVal : String ) : Integer;
var
Err : Integer;
begin
Val( sVal, Result, Err );
if Err <> 0 then Result := 0;
end;
constructor TSchConfFile.Create(AFile: String);
begin
fFile := AFile;
fValueList := TStringList.Create();
fNameList := TStringList.Create();
end;
destructor TSchConfFile.Destroy;
begin
fValueList.Destroy();
fNameList.Destroy();
end;
function TSchConfFile.GetBValue(Index: String): Boolean;
begin
Result := ( GetIValue( Index ) <> 0 );
end;
function TSchConfFile.GetIValue(Index: String): Integer;
begin
Result := atoi( GetValue( Index ) );
end;
function TSchConfFile.GetValue( Index : String ): String;
var
idx : Integer;
begin
idx := fNameList.IndexOf( UpperCase(Index) );
if idx <> -1 then
Result := fValueList.Strings[ idx ] else
Result := '';
end;
procedure TSchConfFile.Load;
var
fTemp : TStrings;
i, x : Integer;
sVal,
sVar : String;
begin
fTemp := TStringList.Create();
try
fTemp.LoadFromFile( fFile );
except
on Exception do begin fTemp.Destroy(); raise ESchFileError.Create( 'File Load Error!' ); end;
end;
if fTemp.Count > 0 then
for i := 0 to fTemp.Count - 1 do
begin
x := Pos( '=', fTemp.Strings[i] );
if x = 0 then Continue;
sVar := UpperCase(Trim(Copy( fTemp.Strings[i], 1, x - 1 )));
sVal := fTemp.Strings[i];
Delete( sVal, 1, x );
fNameList.Add( sVar );
fValueList.Add( sVal );
end;
fTemp.Destroy();
end;
procedure TSchConfFile.Save;
var
fTemp : TStrings;
i : Integer;
begin
fTemp := TStringList.Create();
if fNameList.Count > 0 then
for i := 0 to fNameList.Count - 1 do
fTemp.Add( fNameList.Strings[i] + '=' + fValueList.Strings[i] );
try
fTemp.SaveToFile( fFile );
except
on Exception do begin fTemp.Destroy(); raise ESchFileError.Create( 'File Save Error!' ); end;
end;
fTemp.Destroy();
end;
procedure TSchConfFile.SetBValue(Index: String; const Value: Boolean);
begin
SetIValue( Index, Integer(Value) );
end;
procedure TSchConfFile.SetIValue(Index: String; const Value: Integer);
begin
SetValue( Index, IntToStr(Value) );
end;
procedure TSchConfFile.SetValue(Index: String; const Value: String);
var
idx : Integer;
begin
idx := fNameList.IndexOf( UpperCase(Index) );
if idx <> -1 then
fValueList.Strings[ idx ] := Value else
begin
fNameList.Add( UpperCase(Index) );
fValueList.Add( Value );
end;
end;
end.
|
unit uAreaAggegator;
interface
uses
SysUtils, Classes, uShapes;
type
TAreaAggregator = class(TObject)
public
function SumArea(const aItems: array of IHasArea): Double;
end;
implementation
{ TAreaAggregator }
function TAreaAggregator.SumArea(const aItems: array of IHasArea): Double;
var
I: Integer;
begin
Result := 0;
for I := Low(aItems) to High(aItems) do
begin
Result := Result + aItems[I].Area;
end;
end;
end.
|
program a1test;
(* This program contains 7 test cases to test your implementation. In order
to run this program you must create file 'a1unit.pas' and compile it
to the current directory, or to the C:/work directory. After compiling
you should see a file named 'a1unit.tpu' on the disk.
The program runs 7 labeled tests one by one. You must hit a key 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 a1unit ; { crt }
var Collection1, Collection2: collection;
{ Value: collection_element; }
begin
IdentifyMyself;
writeln;
(* 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;Readkey;
(* 2. Test insertion *)
Writeln('2. INSERTION');
Insert(Collection1, 'chimpanzee');
Insert(Collection1, 'orangutan');
Insert(Collection1, 'gorilla');
Insert(Collection1, 'bonobo');
Insert(Collection1, 'human');
Write ('Collection1 should contain "chimpanzee", "orangutan", "gorilla", ');
Writeln ('"bonobo", and "human" in any order (Size 5)...');
Writeln;
Writeln ('Actual Contents of Collection1:');
Print(Collection1);
Writeln;
Writeln ('Reported size: ', Size(Collection1));
Writeln;Readkey;
(* 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;Readkey;
(* 4. Test deletion *)
Writeln('4. DELETION');
Delete(Collection1, 'chimpanzee');
Delete(Collection1, 'human');
Delete(Collection1, 'hippopotamus');
Writeln ('Collection1 should contain "orangutan", "gorilla", and "bonobo" in any order (Size 3)...');
Writeln;
Writeln ('Actual Contents of Collection1:');
Print(Collection1);
Writeln;
Writeln ('Reported size: ', Size(Collection1));
writeln;Readkey;
writeln( 'Deleting from empty Collection' ) ;
delete(Collection2, 'mandrill') ;
Writeln ('Actual Contents of Collection2:');
print(Collection2) ;
Writeln ('Reported size: ', Size(Collection2));
writeln;Readkey;
(* 5. Join populated with empty collection*)
Writeln('5. JOIN POPULATED WITH EMPTY COLLECTION:');
Join(Collection1, Collection2);
Writeln('Collection1 should be the same as before.');
Writeln;
Writeln ('Actual Contents of Collection1:');
Print(Collection1);
Writeln ('Reported size: ', Size(Collection1));
writeln; readkey;
(* 6. Join to non-empty collection*)
Writeln ('6. JOIN TO NON-EMPTY COLLECTION');
Create_Collection(Collection2);
If Size(Collection2) <> 0 then
writeln('Error in re-creation of Collection2');
Insert(Collection2, 'rhesus monkey');
Insert(Collection2, 'snow monkey');
Join(Collection2, Collection1);
Write ('Collection2 should contain "orangutan", "gorilla", "bonobo", ');
Writeln ('"snow monkey" and "rhesus monkey" in any order (Size 5)...');
Writeln;
Writeln ('Actual Contents of Collection2:');
Print(Collection2);
Writeln;
Writeln ('Reported size: ', Size(Collection2));
Writeln;
Writeln( 'Collection1 should now be undefined.' );
Writeln; readkey;
(* 7. Join empty with populated collection*)
Writeln('7. JOIN EMPTY WITH POPULATED COLLECTION:');
Create_Collection(Collection1);
If Size(Collection1) <> 0 then
writeln('Error in re-creation of Collection1');
Join(Collection1, Collection2);
Writeln('Collection1 should be the same as Collection2 was before.');
Writeln;
Writeln('Actual Contents of Collection1:');
Print(Collection1);
writeln ;
Writeln( 'Reported size: ', Size(Collection1) );
Writeln;
Writeln( 'Collection2 should now be undefined' );
Writeln; readkey;
(* 8. Test Is_Empty *)
Writeln('8. test IS_EMPTY again:');
writeln( 'copying Collection1 to Collection2' ) ;
Collection2 := Collection1 ;
Writeln ('Actual Contents of Collection2:');
Print(Collection2);
Writeln;
Writeln ('Reported size: ', Size(Collection2));
Writeln;
writeln( 'calling "new" and "dispose" on Collection1 - now is undefined' ) ;
new(Collection1) ;
dispose(Collection1) ;
writeln ;
writeln('Collection1 is undefined, and Is_Empty returned ', is_empty(Collection1) ) ;
if Is_Empty(Collection2) then
writeln('Collection2 not empty, but Is_Empty returned TRUE')
else
writeln('Collection2 ok');
writeln;Readkey;
(* 9. Multiple insertions *)
Writeln ('9. Multiple insertions.');
Writeln ('-----------------------');
writeln ;
writeln( 'recreating Collection1 and inserting values -' ) ;
Create_Collection(Collection1);
If Size(Collection1) <> 0 then
writeln('Error in re-creation of Collection1');
Insert(Collection1, 'chimpanzee');
Insert(Collection1, 'orangutan');
Insert(Collection1, 'chimpanzee');
Insert(Collection1, 'bonobo');
Insert(Collection1, 'human');
Insert(Collection1, 'chimpanzee');
Writeln;
Writeln ('Collection1 Reported size: ', Size(Collection1));
print(Collection1);
Writeln;
Writeln ('Collection2 Reported size: ', Size(Collection2));
print(Collection2);
writeln;readkey ;
Writeln ('inserting more values into Collection2 and Collection1 -' ) ;
Insert(Collection2, 'bonobo');
Insert(Collection1, 'chimpanzee');
Insert(Collection2, 'bonobo');
Insert(Collection2, 'bonobo');
Insert(Collection2, 'mandrill');
Writeln;
Writeln ('Collection1 Reported size: ', Size(Collection1));
print(Collection1);
Writeln;
Writeln ('Collection2 Reported size: ', Size(Collection2));
print(Collection2);
writeln;Readkey;
(* 10. Deletions - should be single *)
writeln( '10. Deletions - should be single') ;
Writeln ('--------------------------------');
writeln ;
writeln( 'deleting chimpanzee from Collection1' ) ;
delete(Collection1, 'chimpanzee');
Writeln ('Collection1 Reported size: ', Size(Collection1));
print(Collection1);
Writeln;readkey ;
writeln( 'deleting orangutan from Collection2' ) ;
delete(Collection2, 'orangutan');
Writeln ('Collection2 Reported size: ', Size(Collection2));
print(Collection2);
Writeln;readkey ;
writeln( 'deleting orangutan from Collection1' ) ;
delete(Collection1, 'orangutan');
Writeln ('Collection1 Reported size: ', Size(Collection1));
print(Collection1);
Writeln;readkey ;
writeln( 'deleting bonobo from Collection2' ) ;
delete(Collection2, 'bonobo');
Writeln ('Collection2 Reported size: ', Size(Collection2));
print(Collection2);
writeln; Readkey;
(* 11. Destroy and check for memory leak *)
Writeln('11. MEMCHECK:');
Destroy(Collection2);
Destroy(Collection1);
IF MemCheck then
writeln('Memory check passed')
else
writeln('Memory check failed - possible memory leak');
writeln;readkey;
Writeln('*** DONE ***');
end. |
unit TraincarSprite;
interface
uses
GameTypes, MapSprites, MapTypes, Vehicles, Sounds;
type
ITraincarSprite =
interface(IMapSprite)
function GetGroupId : integer;
function GetSoundTarget : ISoundTarget;
procedure SetSoundTarget(const SoundTarget : ISoundTarget);
function GetIdx : byte;
procedure SetIdx(Idx : byte);
property GroupId : integer read GetGroupId;
property SoundTarget : ISoundTarget read GetSoundTarget write SetSoundTarget;
property Idx : byte read GetIdx write SetIdx;
end;
type
TTraincarSprite =
class(TInterfacedObject, ITraincarSprite)
public
constructor Create(const Traincar : IVehicle; TraincarClass : PTraincarClass; const Manager : IMapSpriteManager);
destructor Destroy; override;
private
fTraincar : IVehicle;
fManager : IMapSpriteManager;
fFrame : integer;
fAngle : TAngle;
fMapX : integer;
fMapY : integer;
fOldMapX : integer;
fOldMapY : integer;
fBlockX : integer;
fBlockY : integer;
fOldBlockX : integer;
fOldBlockY : integer;
fSoundTarget : ISoundTarget;
fLastFrameUpdate : integer;
fIdx : byte;
fZoom : TZoomRes; // last zoom seen
fRotation : TRotation; // last rotation seen
fImages : array[TZoomRes, TRotation] of TSpriteImages;
private
procedure CalcTraincarCoords(trainx, trainy : single; out mapx, mapy, blockx, blocky : integer);
procedure CalcAngle(out angle : TAngle);
procedure UpdateFrame;
private // IMapSprite
function GetId : integer;
function GetFrame : integer;
function GetAngle : TAngle;
function GetMapX : integer;
function GetMapY : integer;
function GetOldMapX : integer;
function GetOldMapY : integer;
procedure AnimationTick;
procedure NewView(const View : IGameView);
function GetBlockX(const View : IGameView) : integer;
function GetBlockY(const View : IGameView) : integer;
function GetOldBlockX(const View : IGameView) : integer;
function GetOldBlockY(const View : IGameView) : integer;
function GetWidth(const View : IGameView) : integer;
function GetHeight(const View : IGameView) : integer;
private // ITraincarSprite
function GetGroupId : integer;
function GetSoundTarget : ISoundTarget;
procedure SetSoundTarget(const SoundTarget : ISoundTarget);
function GetIdx : byte;
procedure SetIdx(Idx : byte);
end;
type
TTraincarSpriteManager =
class(TMapSpritesManager, IMapSpriteManager)
public
constructor Create(Map : TWorldMap; MinAnimInterval : integer; OwnsSprites : boolean; const TraincarsArray : IVehicleArray);
destructor Destroy; override;
private // IMapSpriteManager
function GetSpriteCount : integer; override;
function GetSprite(i : integer) : IMapSprite; override;
procedure SpriteMapPosChanged(const Sprite : IMapSprite); override;
function RegisterSprite(const Sprite : IMapSprite) : integer; override;
procedure UnregisterSprite(const Sprite : IMapSprite); override;
procedure RecacheSoundTargets; override;
private
fTraincarsArray : IVehicleArray;
function GetFullSpriteId(const Sprite : IMapSprite) : integer; override;
procedure TraincarsArrayChanged(TraincarsArray : IVehicleArray; ArrayChange : TArrayChange; const Info);
end;
implementation
uses
SysUtils, LogFile, Windows;
const
cTraincarSpritesTimerInterval = cNoTimerInterval;
const
cBasicU = 16;
const
cXHotSpot = 0;
cYHotSpot = 10;
const
cChangeMapCoordThresh = 0.0001;
constructor TTraincarSprite.Create(const Traincar : IVehicle; TraincarClass : PTraincarClass; const Manager : IMapSpriteManager);
begin
inherited Create;
fTraincar := Traincar;
fManager := Manager;
CalcTraincarCoords(fTraincar.getX, fTraincar.getY, fMapX, fMapY, fBlockX, fBlockY);
CalcAngle(fAngle);
fOldMapX := fMapX;
fOldMapY := fMapY;
fOldBlockX := fBlockX;
fOldBlockY := fBlockY;
if fManager <> nil
then
begin
fManager.RegisterSprite(ITraincarSprite(Self));
fManager.UpdateSpriteRect(ITraincarSprite(Self));
end
else raise Exception.Create('Manager = nil in constructor');
end;
destructor TTraincarSprite.Destroy;
begin
{if fManager <> nil
then fManager.UnregisterSprite(ITraincarSprite(Self))
else raise Exception.Create('Manager = nil in constructor');}
inherited;
end;
procedure TTraincarSprite.CalcTraincarCoords(trainx, trainy : single; out mapx, mapy, blockx, blocky : integer);
var
rndx, rndy : integer;
fracx, fracy : single;
img : TGameImage;
begin
rndx := round(trainx);
rndy := round(trainy);
if abs(trainx - rndx) > cChangeMapCoordThresh
then
begin
mapx := trunc(trainx);
fracx := frac(trainx);
end
else
begin
mapx := rndx;
fracx := 0;
end;
if abs(trainy - rndy) > cChangeMapCoordThresh
then
begin
mapy := trunc(trainy);
fracy := frac(trainy);
end
else
begin
mapy := rndy;
fracy := 0;
end;
blockx := round(2*cBasicU*(1 - fracy + fracx));
blocky := round(cBasicU*((1 - fracy) + (1 - fracx)));
img := fImages[fZoom, fRotation][fAngle];
if img <> nil
then
begin
dec(blockx, img.Width div 2 + cXHotSpot);
dec(blocky, img.Height + cYHotSpot);
end;
end;
procedure TTraincarSprite.CalcAngle(out angle : TAngle);
var
angdegrees : integer;
begin
angdegrees := round(fTraincar.getAngle*180/Pi);
if angdegrees < 0
then angdegrees := 360 + angdegrees;
if (angdegrees < 0) or (angdegrees > 360)
then raise Exception.Create('Invalid angle');
case angdegrees of
0..10:
angle := agE;
11..33:
angle := agENE;
34..55:
angle := agNE;
56..78:
angle := agNNE;
79..100:
angle := agN;
101..123:
angle := agNNW;
124..145:
angle := agNW;
146..168:
angle := agWNW;
169..190:
angle := agW;
191..213:
angle := agWSW;
214..235:
angle := agSW;
236..258:
angle := agSSW;
259..280:
angle := agS;
281..303:
angle := agSSE;
304..325:
angle := agSE;
326..348:
angle := agESE;
else
angle := agE;
end;
end;
procedure TTraincarSprite.UpdateFrame;
var
ElapsedTicks : integer;
CurrentTick : integer;
Img : TGameImage;
begin
Img := fImages[fZoom, fRotation][fAngle];
if (Img <> nil) and (Img.FrameCount > 1)
then
begin
CurrentTick := GetTickCount;
if fFrame >= Img.FrameCount
then
begin
fFrame := 0;
fLastFrameUpdate := CurrentTick;
end;
ElapsedTicks := CurrentTick - fLastFrameUpdate;
if ElapsedTicks >= Img.FrameDelay[fFrame]
then
begin
if fFrame < pred(Img.FrameCount)
then inc(fFrame)
else fFrame := 0;
fLastFrameUpdate := CurrentTick;
end;
end;
end;
function TTraincarSprite.GetId : integer;
begin
Result := fTraincar.getVisualClass;
end;
function TTraincarSprite.GetFrame : integer;
begin
Result := fFrame;
end;
function TTraincarSprite.GetAngle : TAngle;
begin
Result := fAngle;
end;
function TTraincarSprite.GetMapX : integer;
begin
Result := fMapX;
end;
function TTraincarSprite.GetMapY : integer;
begin
Result := fMapY;
end;
function TTraincarSprite.GetOldMapX : integer;
begin
Result := fOldMapX;
end;
function TTraincarSprite.GetOldMapY : integer;
begin
Result := fOldMapY;
end;
procedure TTraincarSprite.AnimationTick;
var
angle : TAngle;
begin
//LogThis('Id = ' + IntToStr(integer(fTraincar)) + ' X = ' + FloatToStr(fTraincar.getX) + ' Y = ' + FloatToStr(fTraincar.getY) + ' Angle = ' + IntToStr(round(fTraincar.getAngle*180/Pi)));
fOldMapX := fMapX;
fOldMapY := fMapY;
fOldBlockX := fBlockX;
fOldBlockY := fBlockY;
CalcTraincarCoords(fTraincar.getX, fTraincar.getY, fMapX, fMapY, fBlockX, fBlockY);
CalcAngle(angle);
if angle <> fAngle
then fAngle := angle;
UpdateFrame;
fManager.UpdateSpriteRect(ITraincarSprite(Self));
end;
procedure TTraincarSprite.NewView(const View : IGameView);
begin
fFrame := 0;
fillchar(fImages[fZoom, fRotation], sizeof(fImages[fZoom, fRotation]), 0);
fZoom := TZoomRes(View.ZoomLevel);
fRotation := View.Rotation;
if fImages[fZoom, fRotation][fAngle] = nil
then fManager.GetSpriteImages(ITraincarSprite(Self), View, fImages[fZoom, fRotation]);
end;
function TTraincarSprite.GetBlockX(const View : IGameView) : integer;
begin
Result := fBlockX*cZoomFactors[TZoomRes(View.ZoomLevel)].m div cZoomFactors[TZoomRes(View.ZoomLevel)].n;
end;
function TTraincarSprite.GetBlockY(const View : IGameView) : integer;
begin
Result := fBlockY*cZoomFactors[TZoomRes(View.ZoomLevel)].m div cZoomFactors[TZoomRes(View.ZoomLevel)].n;
end;
function TTraincarSprite.GetOldBlockX(const View : IGameView) : integer;
begin
Result := fOldBlockX*cZoomFactors[TZoomRes(View.ZoomLevel)].m div cZoomFactors[TZoomRes(View.ZoomLevel)].n;
end;
function TTraincarSprite.GetOldBlockY(const View : IGameView) : integer;
begin
Result := fOldBlockY*cZoomFactors[TZoomRes(View.ZoomLevel)].m div cZoomFactors[TZoomRes(View.ZoomLevel)].n;
end;
function TTraincarSprite.GetWidth(const View : IGameView) : integer;
begin
fZoom := TZoomRes(View.ZoomLevel);
fRotation := View.Rotation;
if fImages[fZoom, fRotation][fAngle] = nil
then fManager.GetSpriteImages(ITraincarSprite(Self), View, fImages[fZoom, fRotation]);
if fImages[fZoom, fRotation][fAngle] <> nil
then Result := fImages[fZoom, fRotation][fAngle].Width
else Result := 0;
end;
function TTraincarSprite.GetHeight(const View : IGameView) : integer;
begin
fZoom := TZoomRes(View.ZoomLevel);
fRotation := View.Rotation;
if fImages[fZoom, fRotation][fAngle] = nil
then fManager.GetSpriteImages(ITraincarSprite(Self), View, fImages[fZoom, fRotation]);
if fImages[fZoom, fRotation][fAngle] <> nil
then Result := fImages[fZoom, fRotation][fAngle].Height
else Result := 0;
end;
function TTraincarSprite.GetGroupId : integer;
begin
Result := fTraincar.getGroupId;
end;
function TTraincarSprite.GetSoundTarget : ISoundTarget;
begin
Result := fSoundTarget;
end;
procedure TTraincarSprite.SetSoundTarget(const SoundTarget : ISoundTarget);
begin
fSoundTarget := SoundTarget;
end;
function TTraincarSprite.GetIdx : byte;
begin
Result := fIdx;
end;
procedure TTraincarSprite.SetIdx(Idx : byte);
begin
fIdx := Idx;
end;
// TTraincarSpriteSoundTarget
type
TTraincarSpriteSoundTarget =
class(TInterfacedObject, ISoundTarget)
public
constructor Create(Owner : TGameFocus; const TraincarSprite : ITraincarSprite; TraincarClass : PTraincarClass);
private
fOwner : TGameFocus;
fTraincarSprite : ITraincarSprite;
fSoundData : TSoundData;
fPan : single;
fVolume : single;
fLastPlayed : dword;
private // ISoundTarget
function GetSoundName : string;
function GetSoundKind : integer;
function GetPriority : integer;
function IsLooped : boolean;
function GetVolume : single;
function GetPan : single;
function ShouldPlayNow : boolean;
function IsCacheable : boolean;
function IsEqualTo(const SoundTarget : ISoundTarget) : boolean;
function GetObject : TObject;
procedure UpdateSoundParameters;
end;
constructor TTraincarSpriteSoundTarget.Create(Owner : TGameFocus; const TraincarSprite : ITraincarSprite; TraincarClass : PTraincarClass);
begin
inherited Create;
fOwner := Owner;
fTraincarSprite := TraincarSprite;
fSoundData := TraincarClass.SoundData;
UpdateSoundParameters;
end;
function TTraincarSpriteSoundTarget.GetSoundName : string;
begin
Result := fSoundData.wavefile;
end;
function TTraincarSpriteSoundTarget.GetSoundKind : integer;
begin
Result := integer(Self);
end;
function TTraincarSpriteSoundTarget.GetPriority : integer;
begin
Result := fSoundData.priority;
end;
function TTraincarSpriteSoundTarget.IsLooped : boolean;
begin
Result := true; //fSoundData.looped;
end;
function TTraincarSpriteSoundTarget.GetVolume : single;
begin
Result := fVolume*fSoundData.atenuation;
end;
function TTraincarSpriteSoundTarget.GetPan : single;
begin
Result := fPan;
end;
function TTraincarSpriteSoundTarget.ShouldPlayNow : boolean;
var
ElapsedTicks : integer;
begin
with fSoundData do
if (not looped and (period <> 0)) or (fLastPlayed = 0)
then
begin
ElapsedTicks := GetTickCount - fLastPlayed;
if ElapsedTicks >= period
then
begin
if random < probability
then Result := true
else Result := false;
fLastPlayed := GetTickCount;
end
else Result := false;
end
else Result := false;
end;
function TTraincarSpriteSoundTarget.IsCacheable : boolean;
begin
Result := false;
end;
function TTraincarSpriteSoundTarget.IsEqualTo(const SoundTarget : ISoundTarget) : boolean;
var
SndTargetObj : TObject;
begin
SndTargetObj := SoundTarget.GetObject;
if SndTargetObj is TTraincarSpriteSoundTarget
then Result := fTraincarSprite = TTraincarSpriteSoundTarget(SndTargetObj).fTraincarSprite
else Result := false;
end;
function TTraincarSpriteSoundTarget.GetObject : TObject;
begin
Result := Self;
end;
procedure TTraincarSpriteSoundTarget.UpdateSoundParameters;
var
screensize : TPoint;
tmppt : TPoint;
x, y : integer;
u : integer;
ci, cj : integer;
Dist : single;
begin
with fOwner, fMap do
begin
fConverter.MapToScreen(fView, fTraincarSprite.MapY, fTraincarSprite.MapX, x, y);
tmppt := fView.ViewPtToScPt(Point(x, y));
x := tmppt.x;
y := tmppt.y;
u := 2 shl fView.ZoomLevel;
x := x + 2*u;
screensize := Point(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
if abs(x - screensize.x/2) > cPanDeadZone
then fPan := cLeftPan + (cRightPan - cLeftPan)*x/screensize.x
else fPan := cCenterPan;
boundvalue(cLeftPan, cRightPan, fPan);
tmppt := fView.ScPtToViewPt(Point(screensize.x div 2, screensize.y div 2));
fConverter.ScreenToMap(fView, tmppt.x, tmppt.y, ci, cj);
Dist := sqrt(sqr(ci - fTraincarSprite.MapY) + sqr(cj - fTraincarSprite.MapX));
if Dist < cMaxHearDist
then fVolume := cMinVol + (1 - Dist/cMaxHearDist)*(cMaxVol - cMinVol)*(1 - abs(fView.ZoomLevel - ord(cBasicZoomRes))*cZoomVolStep)
else fVolume := cMinVol;
boundvalue(cMinVol, cMaxVol, fVolume);
end;
end;
// TTraincarSpriteManager
constructor TTraincarSpriteManager.Create(Map: TWorldMap; MinAnimInterval : integer; OwnsSprites : boolean; const TraincarsArray : IVehicleArray);
begin
inherited Create(Map, MinAnimInterval, OwnsSprites);
fTraincarsArray := TraincarsArray;
fTraincarsArray.RegisterNotificationProc(TraincarsArrayChanged);
end;
destructor TTraincarSpriteManager.Destroy;
begin
fTraincarsArray.UnRegisterNotificationProc(TraincarsArrayChanged);
inherited;
end;
function TTraincarSpriteManager.GetSpriteCount : integer;
begin
Result := fTraincarsArray.getVehicleCount;
end;
function TTraincarSpriteManager.GetSprite(i : integer) : IMapSprite;
begin
Result := IMapSprite(fTraincarsArray.getVehicle(i).getCustomData);
end;
procedure TTraincarSpriteManager.SpriteMapPosChanged(const Sprite : IMapSprite);
var
SoundTarget : ISoundTarget;
Focus : TGameFocus;
i : integer;
begin
for i := 0 to pred(fMap.fFocuses.Count) do
begin
Focus := TGameFocus(fMap.fFocuses[i]);
SoundTarget := ITraincarSprite(Sprite).SoundTarget; // >>
if SoundTarget <> nil
then
begin
SoundTarget.UpdateSoundParameters;
Focus.fSoundManager.UpdateTarget(SoundTarget);
end;
end;
end;
function TTraincarSpriteManager.RegisterSprite(const Sprite : IMapSprite) : integer;
var
SoundTarget : ISoundTarget;
Focus : TGameFocus;
i : integer;
TraincarClass : PTraincarClass;
traincaridx : TTraincarIdx;
begin
traincaridx := fMap.SetTraincar(Sprite.MapY, Sprite.MapX, pointer(Sprite));
ITraincarSprite(Sprite).Idx := traincaridx;
TraincarClass := fMap.fManager.GetTraincarClass(Sprite.Id);
for i := 0 to pred(fMap.fFocuses.Count) do
begin
Focus := TGameFocus(fMap.fFocuses[i]);
if TraincarClass.SoundData.wavefile <> ''
then
begin
SoundTarget := TTraincarSpriteSoundTarget.Create(Focus, ITraincarSprite(Sprite), TraincarClass);
ITraincarSprite(Sprite).SoundTarget := SoundTarget; // >>
Focus.fSoundManager.AddTargets(SoundTarget);
end;
end;
Result := 0; // result doesn't matter here
end;
procedure TTraincarSpriteManager.UnregisterSprite(const Sprite : IMapSprite);
var
SoundTarget : ISoundTarget;
Focus : TGameFocus;
i : integer;
begin
SoundTarget := ITraincarSprite(Sprite).SoundTarget;
if SoundTarget <> nil
then
for i := 0 to pred(fMap.fFocuses.Count) do
begin
Focus := TGameFocus(fMap.fFocuses[i]);
Focus.fSoundManager.RemoveTarget(SoundTarget);
end;
fMap.RemoveTraincar(Sprite.MapY, Sprite.MapX, ITraincarSprite(Sprite).Idx);
end;
procedure TTraincarSpriteManager.RecacheSoundTargets;
var
SoundTarget : ISoundTarget;
Focus : TGameFocus;
i, j : integer;
TraincarClass : PTraincarClass;
Traincar : IVehicle;
TraincarSprite : ITraincarSprite;
begin
for i := 0 to pred(fTraincarsArray.getVehicleCount) do
begin
Traincar := fTraincarsArray.getVehicle(i);
TraincarSprite := ITraincarSprite(Traincar.getCustomData);
if TraincarSprite <> nil
then
begin
TraincarClass := fMap.fManager.GetTraincarClass(TraincarSprite.Id);
for j := 0 to pred(fMap.fFocuses.Count) do
begin
Focus := TGameFocus(fMap.fFocuses[j]);
if TraincarClass.SoundData.wavefile <> ''
then
begin
TraincarSprite.SoundTarget := nil;
SoundTarget := TTraincarSpriteSoundTarget.Create(Focus, TraincarSprite, TraincarClass);
TraincarSprite.SoundTarget := SoundTarget; // >>
Focus.fSoundManager.AddTargets(SoundTarget);
end;
end;
end;
end;
end;
function TTraincarSpriteManager.GetFullSpriteId(const Sprite : IMapSprite) : integer;
begin
Result := idTraincarMask or Sprite.Id;
end;
procedure TTraincarSpriteManager.TraincarsArrayChanged(TraincarsArray : IVehicleArray; ArrayChange : TArrayChange; const Info);
var
i : integer;
Traincar : IVehicle;
TraincarSprite : ITraincarSprite;
traincaridx : TTraincarIdx;
TraincarClass : PTraincarClass;
Vehicle : IVehicle absolute Info;
begin
fTraincarsArray := TraincarsArray;
for i := 0 to pred(fMap.fFocuses.Count) do
TGameFocus(fMap.fFocuses[i]).StartCaching;
try
case ArrayChange of
achUpdate:
for i := 0 to pred(fTraincarsArray.getVehicleCount) do
begin
Traincar := fTraincarsArray.getVehicle(i);
TraincarSprite := ITraincarSprite(Traincar.getCustomData);
if TraincarSprite = nil
then
begin
TraincarClass := fMap.fManager.GetTraincarClass(Traincar.getVisualClass);
TraincarSprite := TTraincarSprite.Create(Traincar, TrainCarClass, Self);
TraincarSprite._AddRef;
Traincar.setCustomData(pointer(TraincarSprite), sizeof(TraincarSprite));
end;
TraincarSprite.AnimationTick;
fMap.RemoveTraincar(TraincarSprite.OldMapY, TraincarSprite.OldMapX, TraincarSprite.Idx);
traincaridx := fMap.SetTraincar(TraincarSprite.MapY, TraincarSprite.MapX, pointer(TraincarSprite));
TraincarSprite.Idx := traincaridx;
end;
achVehicleDeletion:
begin
TraincarSprite := ITraincarSprite(Vehicle.getCustomData);
UnregisterSprite(TraincarSprite);
end;
end;
finally
for i := 0 to pred(fMap.fFocuses.Count) do
TGameFocus(fMap.fFocuses[i]).StopCaching;
end;
end;
end.
|
unit StatusBarUtils;
// Модуль: "w:\common\components\gui\Garant\Nemesis\StatusBarUtils.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "StatusBarUtils" MUID: (505DCE690055)
{$Include w:\common\components\gui\Garant\Nemesis\nscDefine.inc}
interface
{$If Defined(Nemesis)}
uses
l3IntfUses
, nscNewInterfaces
, l3ProtoDataContainer
, l3Memory
, l3Types
, l3Interfaces
, l3Core
, l3Except
, Classes
;
type
TnscStatusBarItemNotificationType = (
sbintVisibleChanged
);//TnscStatusBarItemNotificationType
InscStatusBarItem = interface
['{F1EFAA8A-2134-43CC-AF3F-0B73FB275A89}']
function Get_Visible: Boolean;
function Get_NotificationClients: Pointer;
function Get_ItemDef: InscStatusBarItemDef;
procedure Set_ItemDef(const aValue: InscStatusBarItemDef);
procedure Unsubscribe(const aClient: InscStatusBarItem);
procedure SendNotificationToClients(aNotificationType: TnscStatusBarItemNotificationType);
procedure Subscribe(const aClient: InscStatusBarItem);
procedure Notify(const aSender: InscStatusBarItem;
aNotificationType: TnscStatusBarItemNotificationType);
property Visible: Boolean
read Get_Visible;
property NotificationClients: Pointer
read Get_NotificationClients;
{* TnscStatusBarItemsList }
property ItemDef: InscStatusBarItemDef
read Get_ItemDef
write Set_ItemDef;
end;//InscStatusBarItem
_ItemType_ = InscStatusBarItem;
_l3InterfacePtrList_Parent_ = Tl3ProtoDataContainer;
{$Define l3Items_IsProto}
{$Include w:\common\components\rtl\Garant\L3\l3InterfacePtrList.imp.pas}
TnscStatusBarItemsList = class(_l3InterfacePtrList_)
end;//TnscStatusBarItemsList
{$IfEnd} // Defined(Nemesis)
implementation
{$If Defined(Nemesis)}
uses
l3ImplUses
, l3Base
, l3MinMax
, RTLConsts
, SysUtils
//#UC START# *505DCE690055impl_uses*
//#UC END# *505DCE690055impl_uses*
;
type _Instance_R_ = TnscStatusBarItemsList;
{$Include w:\common\components\rtl\Garant\L3\l3InterfacePtrList.imp.pas}
{$IfEnd} // Defined(Nemesis)
end.
|
unit MemoChannel;
{Unit containing TMemoChannel contributed by Avra (Жељко Аврамовић). TMemoChannel was based on TFileChannel.
TMemoChannel can be thread safe!)
}
{
Copyright (C) 2006 Luiz Américo Pereira Câmara
This library is free software; you can redistribute it and/or modify it
under the terms of the FPC modified LGPL licence which can be found at:
http://wiki.lazarus.freepascal.org/FPC_modified_LGPL.
}
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
interface
uses
{$ifndef fpc}fpccompat,{$endif} Classes, SysUtils, StdCtrls, Forms, Math, MultiLog, strutils;
const
MEMO_MINIMAL_NUMBER_OF_TOTAL_LINES = 200;
MEMO_MINIMAL_NUMBER_OF_LINES_TO_DELETE_AT_ONCE = 100; // must be lower or equal to MEMO_MINIMAL_NUMBER_OF_TOTAL_LINES
type
TLogMsgData = record
Text: string;
end;
PLogMsgData = ^TLogMsgData;
TMemoChannelOption = (fcoShowHeader, fcoShowPrefixMethod, fcoShowFilterDynamic_forWhichPurposesLogIsEffective, fcoShowTime, fcoUnlimitedBuffer, fcoRotaryBuffer);
TMemoChannelOptions = set of TMemoChannelOption;
{ TMemoChannel }
TMemoChannel = class(TLogChannel)
private
FrecMsg: TrecLogMessage;
FoMemo: TMemo;
FiRelativeIdent: Integer;
FiBaseIdent: Integer;
FbShowHeader: Boolean;
FbUnlimitedBuffer: Boolean;
FbRotaryBuffer: Boolean;
FsTimeFormat: String;
FiLogLinesLimit: Integer;
FoWrapper: TLogChannelWrapper;
procedure SetLogLinesLimit(AValue: Integer);
procedure UpdateIdentation;
{ Put log msg into queue that will be processed from the main thread - ie the application's main UI thread - after all other messages,
ie the function returns immediately (asynchronous call), do not wait for the result, removing
the possibility of a inter-messages deadlock in a window's queue. }
procedure Write(const AMsg: string);
procedure WriteStringsOfMsgDataStream();
procedure WriteComponentOfMsgDataStream();
public
constructor Create(AMemo: TMemo; AChannelOptions: TMemoChannelOptions = [fcoShowHeader, fcoShowTime] );
destructor Destroy; override;
procedure SetShowTime(const AValue: Boolean); override;
{ Called from main thread, after all other messages have been processed to allow thread safe TMemo access. }
procedure WriteAsyncQueue(Data: PtrInt);
procedure Deliver(const AMsg: TrecLogMessage); override;
procedure Init; override;
procedure Clear; override;
property ShowHeader: boolean read FbShowHeader write FbShowHeader;
property LogLinesLimit: integer read FiLogLinesLimit write SetLogLinesLimit;
property TimeFormat: String read FsTimeFormat write FsTimeFormat;
end;
implementation
uses
LazLoggerBase;
{ TMemoChannel }
constructor TMemoChannel.Create(AMemo: TMemo; AChannelOptions: TMemoChannelOptions);
begin
FoMemo:= AMemo;
FoWrapper:= TLogChannelWrapper.Create(nil);
FoWrapper.Channel:= Self;
AMemo.FreeNotification(FoWrapper);
FbShowPrefixMethod:= fcoShowPrefixMethod in AChannelOptions; //can be disabled with ShowPrefixMethod property
FbShowTime:= fcoShowTime in AChannelOptions;
FbShow_DynamicFilter_forWhatReasonsToLogActually:= fcoShowFilterDynamic_forWhichPurposesLogIsEffective in AChannelOptions;
FbShowHeader:= fcoShowHeader in AChannelOptions;
FbRotaryBuffer:= fcoRotaryBuffer in AChannelOptions;
FbUnlimitedBuffer:= fcoUnlimitedBuffer in AChannelOptions;
Active:= True;
FiLogLinesLimit:= MEMO_MINIMAL_NUMBER_OF_TOTAL_LINES;
FsTimeFormat:= 'hh:nn:ss:zzz';
end;
destructor TMemoChannel.Destroy;
begin
FoWrapper.Destroy;
inherited Destroy;
end;
procedure TMemoChannel.Write(const AMsg: string);
var
LogMsgToSend: PLogMsgData;
begin
New(LogMsgToSend);
LogMsgToSend^.Text := AMsg;
Application.QueueAsyncCall(@WriteAsyncQueue, PtrInt(LogMsgToSend)); // put log msg into queue that will be processed from the main thread after all other messages
end;
procedure TMemoChannel.WriteAsyncQueue(Data: PtrInt);
var // called from main thread after all other messages have been processed to allow thread safe TMemo access
ReceivedLogMsg: TLogMsgData;
LineCount: Integer;
begin
ReceivedLogMsg := PLogMsgData(Data)^;
try
if (FoMemo <> nil) and (not Application.Terminated) then begin
if FoMemo.Lines.Count > LogLinesLimit then begin
// FILO rotating bufferised memo
if FbRotaryBuffer then begin
FoMemo.Lines.BeginUpdate;
try // less flickering compared to deleting first line for each newly added line
for LineCount := 1 to Max(LoglinesLimit div 10, MEMO_MINIMAL_NUMBER_OF_LINES_TO_DELETE_AT_ONCE) do
FoMemo.Lines.Delete(0);
finally
FoMemo.Lines.EndUpdate;
end;
end
else
if not FbUnlimitedBuffer then
Clear; // clear whole bufferised memo when limit is reached
end;
FoMemo.Append(ReceivedLogMsg.Text);
end;
finally
Dispose(PLogMsgData(Data));
end;
end;
procedure TMemoChannel.UpdateIdentation;
var
S: string;
begin
S := '';
if FbShowTime then
S := FormatDateTime(FsTimeFormat, Time);
FiBaseIdent := Length(S) + 3;
end;
procedure TMemoChannel.SetShowTime(const AValue: Boolean);
begin
inherited SetShowTime(AValue);
UpdateIdentation;
end;
procedure TMemoChannel.SetLogLinesLimit(AValue: Integer);
begin
FiLogLinesLimit := Max(Abs(AValue), MEMO_MINIMAL_NUMBER_OF_TOTAL_LINES);
end;
procedure TMemoChannel.WriteStringsOfMsgDataStream();
var
i: integer;
{$If defined(DEBUG)}sDebug: string;{$EndIf}
begin
if FrecMsg.pData.Size = 0 then Exit; // pre-condition
with TStringList.Create do begin
try
FrecMsg.pData.Position:=0;
LoadFromStream(FrecMsg.pData);
for i:= 0 to Count - 1 do begin
{$If defined(DEBUG)}
sDebug:= Strings[i];
{$EndIf}
if (Trim(Strings[i])<>'') then
Write(Space(FiRelativeIdent+FiBaseIdent) + Strings[i]);
end;
finally
Destroy;
end;
end;
end;
procedure TMemoChannel.WriteComponentOfMsgDataStream();
var
TextStream: TStringStream;
begin
TextStream := TStringStream.Create('');
FrecMsg.pData.Seek(0, soFromBeginning);
ObjectBinaryToText(FrecMsg.pData, TextStream);
write(TextStream.DataString); //todo: better handling of format
TextStream.Destroy;
end;
procedure TMemoChannel.Deliver(const AMsg: TrecLogMessage);
var
sWholeMsg: string;
begin
FrecMsg:= AMsg;
sWholeMsg:= '';
//Exit method identation must be set before
if (FrecMsg.iMethUsed = methExitMethod) and (FiRelativeIdent >= 2) then
Dec(FiRelativeIdent, 2);
try
if FbShowTime then
sWholeMsg:= FormatDateTime(FsTimeFormat, FrecMsg.dtMsgTime) + ' ';
sWholeMsg:= sWholeMsg + Space(FiRelativeIdent);
//FbShowPrefixMethod can serve as qualifier for each current msg, allowing further thematic extractions
if FbShowPrefixMethod then
sWholeMsg:= sWholeMsg + (ctsLogPrefixesMethod[FrecMsg.iMethUsed] + ': ');
//write second qualifier explaining for which tracking purposes Msg are Logged
if FbShow_DynamicFilter_forWhatReasonsToLogActually then
sWholeMsg:= sWholeMsg + TLogChannelUtils.SetofToString(AMsg.setFilterDynamic);
sWholeMsg:= sWholeMsg + FrecMsg.sMsgText;
write(sWholeMsg);
//if there's a TStream to write...
if FrecMsg.pData <> nil then begin
case FrecMsg.iMethUsed of
methTStrings, methCallStack, methHeapInfo, methException, methMemory: WriteStringsOfMsgDataStream();
methObject: WriteComponentOfMsgDataStream();
end;
end;
finally
//Update enter method identation
if (FrecMsg.iMethUsed = methEnterMethod) then
Inc(FiRelativeIdent, 2);
end;
end;
procedure TMemoChannel.Init;
var
sBufferLimitedStr: string;
begin
if FbRotaryBuffer or not FbUnlimitedBuffer then
sBufferLimitedStr:= ' (buffer limited to ' + IntToStr(LogLinesLimit) + ' lines - simplier CPU use on the client side with IPC )'
else
sBufferLimitedStr:= '';
if FbShowHeader then
Write('=== Log Session Started at ' + DateTimeToStr(Now) + ' by ' + ApplicationName + sBufferLimitedStr + ' ===');
UpdateIdentation;
end;
procedure TMemoChannel.Clear;
begin
FoMemo.Lines.Clear;
if FbRotaryBuffer or not FbUnlimitedBuffer then
Write(' (cleared buffer always limited to ' + IntToStr(LogLinesLimit) + ' lines - simplier CPU use on the client side with IPC )');
end;
end.
|
unit UDatePicker;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSNativeUILabel,
FMX.TMSNativeUIButton, FMX.TMSNativeUIBaseControl, FMX.TMSNativeUIDatePicker,
FMX.TMSNativeUISwitch;
type
TForm935 = class(TForm)
TMSFMXNativeUIDatePicker1: TTMSFMXNativeUIDatePicker;
TMSFMXNativeUIButton1: TTMSFMXNativeUIButton;
TMSFMXNativeUILabel1: TTMSFMXNativeUILabel;
TMSFMXNativeUISwitch1: TTMSFMXNativeUISwitch;
TMSFMXNativeUILabel2: TTMSFMXNativeUILabel;
procedure FormCreate(Sender: TObject);
procedure TMSFMXNativeUIButton1Click(Sender: TObject);
procedure TMSFMXNativeUIDatePicker1ValueChanged(ASender: TObject;
ADateTime: TDateTime);
procedure TMSFMXNativeUISwitch1ValueChanged(ASender: TObject;
AValue: Boolean);
private
{ Private declarations }
public
{ Public declarations }
procedure UpdateLabel;
end;
var
Form935: TForm935;
implementation
{$R *.fmx}
procedure TForm935.FormCreate(Sender: TObject);
begin
UpdateLabel;
end;
procedure TForm935.TMSFMXNativeUIButton1Click(Sender: TObject);
begin
TMSFMXNativeUIDatePicker1.DateTime := Now;
UpdateLabel;
end;
procedure TForm935.TMSFMXNativeUIDatePicker1ValueChanged(ASender: TObject;
ADateTime: TDateTime);
begin
UpdateLabel;
end;
procedure TForm935.TMSFMXNativeUISwitch1ValueChanged(ASender: TObject;
AValue: Boolean);
begin
if AValue then
TMSFMXNativeUIDatePicker1.Mode := dpmDatePickerModeDateAndTime
else
TMSFMXNativeUIDatePicker1.Mode := dpmDatePickerModeDate;
UpdateLabel;
end;
procedure TForm935.UpdateLabel;
begin
if TMSFMXNativeUISwitch1.Value then
TMSFMXNativeUILabel1.Text := DateTimeToStr(TMSFMXNativeUIDatePicker1.DateTime)
else
TMSFMXNativeUILabel1.Text := DateToStr(TMSFMXNativeUIDatePicker1.DateTime);
end;
end.
|
unit TransparentPanelU;
interface
uses
System.Classes, System.Types, System.Sysutils, Winapi.Windows, Winapi.Messages, Vcl.ExtCtrls, Vcl.Controls, VCL.Forms;
const
ERROwnerNotForm = 'The owner is not a TForm';
type
TFormNotOwner = class(Exception);
TTransparentPanel = class(TPanel)
private
FOwner: TForm;
IsDown: boolean;
a, b: Integer;
protected
procedure WMEraseBkGnd(var Msg: TWMEraseBkGnd); message WM_ERASEBKGND;
procedure CreateParams(var Params: TCreateParams); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{ TTransparentPanel }
constructor TTransparentPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if (AOwner is TForm) then
FOwner := (AOwner as TForm)
else if (AOwner.Owner is TForm) then
FOwner := (AOwner.Owner as TForm)
else if (AOwner.Owner.Owner is TForm) then
FOwner := (AOwner.Owner.Owner as TForm)
else
raise TFormNotOwner.Create(ERROwnerNotForm);
IsDown := false;
a := 0;
b := 0;
end;
procedure TTransparentPanel.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.ExStyle := Params.ExStyle or WS_EX_TRANSPARENT;
end;
procedure TTransparentPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
IsDown := True;
a := X;
b := Y;
end;
inherited;
end;
procedure TTransparentPanel.MouseMove(Shift: TShiftState; X, Y: Integer);
var
P: TPoint;
begin
if IsDown then
if (abs(X - a) > 5) or (abs(Y - b) > 5) then
begin
P := Point(X, Y);
P := FOwner.ClientToScreen(P);
MoveWindow(FOwner.Handle, P.X - a, P.Y - b, FOwner.Width, FOwner.Height, True);
end;
inherited;
end;
procedure TTransparentPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
IsDown := false;
inherited;
end;
procedure TTransparentPanel.WMEraseBkGnd(var Msg: TWMEraseBkGnd);
begin
SetBkMode(Msg.DC, TRANSPARENT);
Msg.result := 1;
end;
end.
|
{ *************************************************************************** }
{ }
{ This file is part of the XPde project }
{ }
{ Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> }
{ }
{ This program is free software; you can redistribute it and/or }
{ modify it under the terms of the GNU General Public }
{ License as published by the Free Software Foundation; either }
{ version 2 of the License, or (at your option) any later version. }
{ }
{ This program is distributed in the hope that it will be useful, }
{ but WITHOUT ANY WARRANTY; without even the implied warranty of }
{ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU }
{ General Public License for more details. }
{ }
{ You should have received a copy of the GNU General Public License }
{ along with this program; see the file COPYING. If not, write to }
{ the Free Software Foundation, Inc., 59 Temple Place - Suite 330, }
{ Boston, MA 02111-1307, USA. }
{ }
{ *************************************************************************** }
unit uGraphics;
interface
uses Classes, QGraphics, Types, QExtCtrls, QControls;
//Draw a 3D Rectangle y several styles
procedure Draw3DRect(const Canvas:TCanvas; Rect: TRect; const style: TBorderStyle);
//Draw a 3D Rectangle y several styles
procedure R3D(canvas:TCanvas;r:TRect;flat:boolean=false;raised:boolean=true;fill:boolean=true);
//Draw source1 over source2 and produces target
//Source1 can contain an alpha channel that will be merged with source2
procedure AlphaBitmap(source1,source2,target:TBitmap;dens:longint);
//Merge two bitmaps
procedure MergeBitmaps(source1,source2,target:TBitmap;dens:longint);
//Creates a selected bitmap
procedure SelectedBitmap(source1,source2,target:TBitmap;dens:longint);
//Copies binary save a bitmap, even with alpha channel
procedure bitblt(source:TBitmap;target:TBitmap;const x,y,w,h:integer);
//Creates a masked bitmap, should be deprecated
procedure MaskedBitmap(orig:TBitmap;result:TBitmap);
function rgbtocolor(r,g,b:byte):TColor;
procedure resizeBitmap(original, target: TBitmap; const width,height: integer; const border:integer=3);
implementation
function rgbtocolor(r,g,b:byte):TColor;
begin
result:=b shl 16;
result:=result+(g shl 8);
result:=result+r;
end;
// Draw a 3D Rectangle in several styles
procedure Draw3DRect(const Canvas:TCanvas; Rect: TRect; const style: TBorderStyle);
const
cColor: array [0..3] of Integer = (clBtnShadow, clBtnHighlight, clShadow, clMidLight);
begin
{ TODO : Add more drawing styles }
Frame3D(Canvas, Rect, cColor[0], cColor[1], 1);
Frame3D(Canvas, Rect, cColor[2], cColor[3], 1);
end;
procedure R3D(canvas:TCanvas;r:TRect;flat:boolean=false;raised:boolean=true;fill:boolean=true);
begin
with canvas do begin
if not flat then begin
pen.mode:=pmCopy;
if raised then begin
//Top Left
pen.color:=clBtnFace;
moveto(r.left,r.top);
lineto(r.right-2,r.top);
moveto(r.left,r.top);
lineto(r.left,r.bottom-2);
//Bottom Right
pen.color:=clGray;
moveto(r.right-1,r.top);
lineto(r.right-1,r.bottom);
moveto(r.left,r.bottom-1);
lineto(r.right,r.bottom-1);
//Top Left 2
pen.color:=clWhite;
moveto(r.left+1,r.top+1);
lineto(r.right-2,r.top+1);
moveto(r.left+1,r.top+1);
lineto(r.Left+1,r.bottom-2);
//Bottom Right 2
pen.color:=clBtnShadow;
moveto(r.right-2,r.top+1);
lineto(r.right-2,r.bottom-1);
moveto(r.left+1,r.bottom-2);
lineto(r.right-1,r.bottom-2);
end
else begin
//Top Left
pen.color:=clBtnShadow;
moveto(r.left,r.top);
lineto(r.right-1,r.top);
moveto(r.left,r.top);
lineto(r.left,r.bottom-1);
//Bottom Right
pen.color:=clWhite;
moveto(r.right-1,r.top+1);
lineto(r.right-1,r.bottom);
moveto(r.left+1,r.bottom-1);
lineto(r.right,r.bottom-1);
//Top Left 2
pen.color:=clGray;
moveto(r.left+1,r.top+1);
lineto(r.right-2,r.top+1);
moveto(r.left+1,r.top+1);
lineto(r.Left+1,r.bottom-2);
//Bottom Right 2
pen.color:=clBtnFace;
moveto(r.right-2,r.top+1);
lineto(r.right-2,r.bottom-1);
moveto(r.left+1,r.bottom-2);
lineto(r.right-1,r.bottom-2);
end;
if fill then begin
brush.Style:=bsSolid;
inflaterect(r,-2,-2);
fillrect(r);
end;
end
else begin
pen.mode:=pmCopy;
if raised then begin
//Top Left
pen.color:=clWhite;
moveto(r.left,r.top);
lineto(r.right-1,r.top);
moveto(r.left,r.top);
lineto(r.left,r.bottom-1);
//Bottom Right
pen.color:=clBtnShadow;
moveto(r.right-1,r.top);
lineto(r.right-1,r.bottom);
moveto(r.left,r.bottom-1);
lineto(r.right,r.bottom-1);
end
else begin
//Top Left
pen.color:=clBtnShadow;
moveto(r.left,r.top);
lineto(r.right-1,r.top);
moveto(r.left,r.top);
lineto(r.left,r.bottom-1);
//Bottom Right
pen.color:=clWhite;
moveto(r.right-1,r.top);
lineto(r.right-1,r.bottom);
moveto(r.left,r.bottom-1);
lineto(r.right,r.bottom-1);
end;
if fill then begin
brush.Style:=bsSolid;
inflaterect(r,-1,-1);
fillrect(r);
end;
end;
end;
end;
// Copies a bitmap
procedure bitblt(source:TBitmap;target:TBitmap;const x,y,w,h:integer);
var
spoints: pointer;
tpoints: pointer;
t,l: integer;
begin
for t:=y to (y+h)-1 do begin
spoints:=source.ScanLine[t];
tpoints:=target.scanline[t-y];
inc(PChar(spoints),x*4);
for l:=x to (x+w)-1 do begin
integer(tpoints^):=integer(spoints^);
inc(PChar(tpoints),4);
inc(PChar(spoints),4);
end;
end;
end;
//Merge 2 bitmaps with transparencies
procedure MergeBitmaps(source1,source2,target:TBitmap;dens:longint);
var
aEBX, aESI, aEDI, aESP, aEDX, Dens1, Dens2: Longint;
i: longint;
ptz: pointer;
ptt: pointer;
ptf: pointer;
w:longint;
bmz:TBitmap;
bmf:TBitmap;
bmt:TBitmap;
fina:integer;
const
Maxize = (1294967280 Div SizeOf(TPoint));
MaxPixelCount = 32768;
Mask0101 = $00FF00FF;
Mask1010 = $FF00FF00;
begin
bmz:=TBitmap.create;
bmf:=TBitmap.create;
bmt:=TBitmap.create;
bmz.PixelFormat:=pf32bit;
bmf.PixelFormat:=pf32bit;
bmt.PixelFormat:=pf32bit;
bmz.width:=source1.width;
bmz.height:=source1.height;
bmf.width:=source1.width;
bmf.height:=source1.height;
bmt.width:=source1.width;
bmt.height:=source1.height;
bmF.Canvas.brush.color:=clFuchsia;
bmF.Canvas.Draw(0, 0, source1);
bmT.Canvas.Draw(0, 0, source2);
bmZ.Canvas.Draw(0, 0, bmF);
w:=bmz.width;
for i := 0 to bmz.height - 1 do begin
Ptz := bmz.Scanline[i];
Ptt := bmt.Scanline[i];
Ptf := bmf.Scanline[i];
asm
MOV aEBX, EBX
MOV aEDI, EDI
MOV aESI, ESI
MOV aESP, ESP
MOV aEDX, EDX
MOV EBX, Dens
MOV Dens1, EBX
NEG BL
ADD BL, $20
MOV Dens2, EBX
CMP Dens1, 0
JZ @Final
MOV EDI, ptz
MOV ESI, ptt
MOV ECX, ptf
MOV EAX, w
lea EAX, [EAX+EAX*2+3]
ADD EAX,w
AND EAX, $FFFFFFFC
ADD EAX, EDI
MOV FinA, EAX
MOV EDX,EDI
MOV ESP,ESI
MOV ECX,ECX
@LOOPA:
MOV EAX, [EDX]
MOV EDI, [ESP]
MOV EBX, EAX
AND EAX, Mask1010
AND EBX, Mask0101
SHR EAX, 5
IMUL EAX, Dens2
IMUL EBX, Dens2
MOV ESI, EDI
AND EDI, Mask1010
AND ESI, Mask0101
SHR EDI, 5
IMUL EDI, Dens1
IMUL ESI, Dens1
ADD EAX, EDI
ADD EBX, ESI
AND EAX, Mask1010
SHR EBX, 5
AND EBX, Mask0101
OR EAX, EBX
MOV [ECX], EAX
ADD EDX, 4
ADD ESP, 4
ADD ECX, 4
CMP EDX, FinA
JNE @LOOPA
@final:
MOV EBX, aEBX
MOV EDI, aEDI
MOV ESI, aESI
MOV ESP, aESP
MOV EDX, aEDX
end;
end;
target.assign(bmf);
bmz.free;
bmf.free;
bmt.free;
end;
//Applies the alpha channel of a bitmap
procedure AlphaBitmap(source1,source2,target:TBitmap;dens:longint);
var
aEBX, aESI, aEDI, aESP, aEDX, Dens1, Dens2: Longint;
i: longint;
ptz: pointer;
ptt: pointer;
ptf: pointer;
w:longint;
bmz:TBitmap;
bmf:TBitmap;
bmt:TBitmap;
fina:integer;
const
Maxize = (1294967280 Div SizeOf(TPoint));
MaxPixelCount = 32768;
Mask0101 = $00FF00FF;
Mask1010 = $FF00FF00;
begin
bmF:=source1;
bmt:=source2;
bmZ:=bmf;
w:=bmz.width;
for i := 0 to bmz.height - 1 do begin
Ptz := bmz.Scanline[i];
Ptt := bmt.Scanline[i];
Ptf := bmf.Scanline[i];
asm
MOV aEBX, EBX
MOV aEDI, EDI
MOV aESI, ESI
MOV aESP, ESP
MOV aEDX, EDX
MOV EBX, Dens
MOV Dens1, EBX
NEG BL
ADD BL, $20
MOV Dens2, EBX
MOV EDI, ptz
MOV ESI, ptt
MOV ECX, ptf
MOV EAX, w
lea EAX, [EAX+EAX*2+3]
ADD EAX,w
AND EAX, $FFFFFFFC
ADD EAX, EDI
MOV FinA, EAX
MOV EDX,EDI
MOV ESP,ESI
MOV ECX,ECX
@LOOPA:
MOV EAX, [EDX]
SHR EAX, 24
MOV EBX, EAX
ADD EBX, dens
CMP EBX, $20
JNG @p
MOV EBX, $20
@p:
MOV Dens1, EBX
NEG BL
ADD BL, $20
MOV Dens2, EBX
CMP Dens1, 0
JZ @sig
MOV EAX, [EDX]
MOV EDI, [ESP]
CMP EAX, $FFFFFFFF
JZ @mask
@again:
MOV EBX, EAX
AND EAX, Mask1010
AND EBX, Mask0101
SHR EAX, 5
IMUL EAX, Dens2
IMUL EBX, Dens2
MOV ESI, EDI
AND EDI, Mask1010
AND ESI, Mask0101
SHR EDI, 5
IMUL EDI, Dens1
IMUL ESI, Dens1
ADD EAX, EDI
ADD EBX, ESI
AND EAX, Mask1010
SHR EBX, 5
AND EBX, Mask0101
OR EAX, EBX
MOV [ECX], EAX
@sig:
ADD EDX, 4
ADD ESP, 4
ADD ECX, 4
CMP EDX, FinA
JNE @LOOPA
JE @final
@mask:
MOV EAX, EDI
MOV [ECX], EAX
jmp @sig
@final:
MOV EBX, aEBX
MOV EDI, aEDI
MOV ESI, aESI
MOV ESP, aESP
MOV EDX, aEDX
end;
end;
target.assign(bmf);
end;
//Creates the selected bitmap
procedure SelectedBitmap(source1,source2,target:TBitmap;dens:longint);
var
aEBX, aESI, aEDI, aESP, aEDX, Dens1, Dens2, Dens3: Longint;
i: longint;
ptz: pointer;
ptt: pointer;
ptf: pointer;
w:longint;
bmz:TBitmap;
bmf:TBitmap;
bmt:TBitmap;
fina:integer;
const
Maxize = (1294967280 Div SizeOf(TPoint));
MaxPixelCount = 32768;
Mask0101 = $00FF00FF;
Mask1010 = $FF00FF00;
begin
bmz:=TBitmap.create;
bmf:=TBitmap.create;
bmt:=TBitmap.create;
bmz.PixelFormat:=pf32bit;
bmf.PixelFormat:=pf32bit;
bmt.PixelFormat:=pf32bit;
bmz.width:=source1.width;
bmz.height:=source1.height;
bmf.width:=source1.width;
bmf.height:=source1.height;
bmt.width:=source1.width;
bmt.height:=source1.height;
bmF.Assign(source1);
bmt.assign(source2);
bmZ.assign(bmf);
w:=bmz.width;
for i := 0 to bmz.height - 1 do begin
Ptz := bmz.Scanline[i];
Ptt := bmt.Scanline[i];
Ptf := bmf.Scanline[i];
asm
MOV aEBX, EBX
MOV aEDI, EDI
MOV aESI, ESI
MOV aESP, ESP
MOV aEDX, EDX
MOV EBX, Dens
MOV Dens1, EBX
NEG BL
ADD BL, $20
MOV Dens2, EBX
// CMP Dens1, 0
// JZ @Final
MOV EDI, ptz
MOV ESI, ptt
MOV ECX, ptf
MOV EAX, w
lea EAX, [EAX+EAX*2+3]
ADD EAX,w
AND EAX, $FFFFFFFC
ADD EAX, EDI
MOV FinA, EAX
MOV EDX,EDI
MOV ESP,ESI
MOV ECX,ECX
@LOOPA:
MOV EAX, [EDX]
SHR EAX, 24
MOV EBX, EAX
ADD EBX, dens
CMP EBX, $20
JNG @p
MOV EBX, $20
@p:
MOV Dens1, EBX
NEG BL
ADD BL, $20
MOV Dens2, EBX
CMP Dens1, 0
JZ @sig
MOV EAX, [EDX]
SHR EAX, 24
SHL EAX, 24
MOV Dens3, EAX
MOV EAX, [EDX]
MOV EDI, [ESP]
CMP EAX, $FFFFFFFF
JZ @mask
@again:
MOV EBX, EAX
AND EAX, Mask1010
AND EBX, Mask0101
SHR EAX, 5
IMUL EAX, Dens2
IMUL EBX, Dens2
MOV ESI, EDI
AND EDI, Mask1010
AND ESI, Mask0101
SHR EDI, 5
IMUL EDI, Dens1
IMUL ESI, Dens1
ADD EAX, EDI
ADD EBX, ESI
AND EAX, Mask1010
SHR EBX, 5
AND EBX, Mask0101
OR EAX, EBX
SHL EAX ,8
SHR EAX ,8
OR EAX, Dens3
MOV [ECX], EAX
@sig:
ADD EDX, 4
ADD ESP, 4
ADD ECX, 4
CMP EDX, FinA
JNE @LOOPA
JE @final
@mask:
// MOV EAX, EDI
// MOV [ECX], EAX
jmp @sig
@final:
MOV EBX, aEBX
MOV EDI, aEDI
MOV ESI, aESI
MOV ESP, aESP
MOV EDX, aEDX
end;
end;
target.assign(bmf);
bmz.free;
bmf.free;
bmt.free;
end;
procedure MaskedBitmap(orig:TBitmap;result:TBitmap);
var
mask:TBitmap;
source: TBitmap;
begin
mask:=TBitmap.create;
source:=TBitmap.create;
try
source.width:=orig.width;
source.height:=orig.height;
result.width:=orig.width;
result.height:=orig.height;
source.Canvas.brush.color:=clFuchsia;
source.Canvas.draw(0,0,orig);
source.transparent:=true;
mask.width:=source.width;
mask.height:=source.height;
mask.Canvas.brush.color:=clHighLight;
mask.Canvas.pen.color:=clHighLight;
mask.Canvas.fillrect(rect(0,0,source.width,source.height));
MergeBitmaps(source,mask,result,14);
finally
source.free;
mask.free;
end;
end;
procedure resizeBitmap(original, target: TBitmap; const width,height: integer; const border:integer=3);
var
rRect: TRect;
rTop: TRect;
rLeft: TRect;
rRight: TRect;
rBottom: TRect;
procedure stretchCopy(destCanvas: TCanvas; dest: TRect; sourceCanvas: TCanvas; source:TRect);
var
temp: TBitmap;
begin
temp:=TBitmap.create;
try
temp.width:=source.Right-source.Left;
temp.height:=source.Bottom-source.Top;
temp.Canvas.CopyRect(rect(0,0,temp.width,temp.height),sourcecanvas,source);
destCanvas.StretchDraw(dest,temp);
finally
temp.free;
end;
end;
begin
target.width:=width;
target.height:=height;
target.Canvas.Rectangle(0,0,width,height);
rRect:=Rect(0,0,width,height);
if (border<>0) then begin
rTop:=rRect;
rTop.Bottom:=border;
rRight:=rRect;
rRight.Left:=rRight.Right-border;
rBottom:=rRect;
rBottom.top:=rBottom.bottom-border;
target.Canvas.CopyRect(rect(0,0,border,border),original.canvas,rect(0,0,border,border));
target.Canvas.CopyRect(rect(width-border,0,width,border),original.canvas,rect(original.width-border,0,original.width,border));
target.Canvas.CopyRect(rect(0,height-border,border,height),original.canvas,rect(0,original.height-border,border,original.height));
target.Canvas.CopyRect(rect(width-border,height-border,width,height),original.canvas,rect(original.width-border,original.height-border,original.width,original.height));
rLeft:=rRect;
rLeft.top:=border;
rLeft.right:=border;
rLeft.bottom:=height-border;
stretchCopy(target.canvas,rLeft,original.canvas,rect(0,border,border,original.height-border));
rRight:=rRect;
rRight.top:=border;
rRight.left:=width-border;
rRight.bottom:=height-border;
stretchCopy(target.canvas,rRight,original.canvas,rect(original.width-border,border,original.width,original.height-border));
rTop:=rRect;
rTop.bottom:=border;
rTop.left:=border;
rTop.right:=width-border;
stretchCopy(target.canvas,rTop,original.canvas,rect(border,0,original.width-border,border));
rBottom:=rRect;
rBottom.top:=height-border;
rBottom.left:=border;
rBottom.right:=width-border;
stretchCopy(target.canvas,rBottom,original.canvas,rect(border,original.height-border,original.width-border,original.height));
end;
rRect.left:=border;
rRect.top:=border;
rRect.right:=width-border;
rRect.bottom:=height-border;
stretchCopy(target.canvas,rRect,original.canvas,rect(border,border,original.width-border,original.height-border));
end;
end.
|
unit GX_eSelectionEditorExpert;
interface
uses
Classes, ToolsAPI, GX_EditorExpert;
type
TNoSelectionMode = (nsmSelectLine, nsmSelectIdent, nsmError);
TSelectionEditorExpert = class(TEditorExpert)
private
function BlockSelectionToLineEndType(SouceEditor: IOTASourceEditor;const Selection: string): Integer;
procedure InternalExecute;
protected
// Return True to let the changed lines get copied back into the editor
function ProcessSelected(Lines: TStrings): Boolean; virtual; abstract;
function GetNoSelectionMode: TNoSelectionMode; virtual;
public
procedure Execute(Sender: TObject); override;
end;
implementation
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
SysUtils, GX_OtaUtils;
{ TSelectionEditorExpert }
// WARNING: This is a hack.
// GxOtaReplaceSelection has a problem with appending an
// unwanted CRLF for multiline selections to the line end
// The clean solution is just to call
// GxOtaReplaceSelection(Editor, 0, CodeList.Text);
// and have the problem solved elsewhere, but this is hard...
// We don't remove the CRLF if the block ends in the first column,
// because then we delete a necessary CRLF.
function TSelectionEditorExpert.BlockSelectionToLineEndType(SouceEditor: IOTASourceEditor;
const Selection: string): Integer;
var
View: IOTAEditView;
CharPos: TOTACharPos;
EditPos: TOTAEditPos;
begin
Result := 0;
View := GxOtaGetTopMostEditView(SouceEditor);
Assert(Assigned(View));
CharPos.Line := View.Block.EndingRow;
CharPos.CharIndex := View.Block.EndingColumn;
View.ConvertPos(False, EditPos, CharPos);
// TODO 3 -cIssue -oAnyone: Why is a 2 necessary for this column check (tested in Delphi 6)
if (Length(Selection) > 1) and (EditPos.Col > 2) then
begin
if Copy(Selection, Length(Selection) - 1, 2) = #13#10 then
Result := 2
else if Selection[Length(Selection)] = #10 then
Result := 1;
end;
end;
procedure TSelectionEditorExpert.Execute(Sender: TObject);
begin
InternalExecute;
end;
function TSelectionEditorExpert.GetNoSelectionMode: TNoSelectionMode;
begin
Result := nsmSelectLine;
end;
procedure TSelectionEditorExpert.InternalExecute;
resourcestring
NoSelectionError = 'Please select some text first.';
var
SourceEditor: IOTASourceEditor;
CodeList: TStrings;
LineEndType: Integer;
begin
{$IFOPT D+} SendDebug('Executing TSelectionEditorExpert'); {$ENDIF}
CodeList := TStringList.Create;
try
if not GxOtaTryGetCurrentSourceEditor(SourceEditor) then
Exit;
CodeList.Text := GxOtaGetCurrentSelection;
if CodeList.Count = 0 then
begin
case GetNoSelectionMode of
nsmSelectLine: GxOtaSelectCurrentLine(SourceEditor, False);
nsmSelectIdent: GxOtaSelectCurrentIdent(SourceEditor, False);
else // nsmError:
raise Exception.Create(NoSelectionError);
end;
CodeList.Text := GxOtaGetCurrentSelection;
end;
if CodeList.Count = 0 then
Exit;
if ProcessSelected(CodeList) then
begin
{$IFOPT D+}SendDebug('Calling GxOtaReplaceSelection');{$ENDIF}
if CodeList.Count = 1 then
GxOtaReplaceSelection(SourceEditor, 0, TrimRight(CodeList.Text))
else
begin
LineEndType := BlockSelectionToLineEndType(SourceEditor, CodeList.Text);
if LineEndType = 2 then
GxOtaReplaceSelection(SourceEditor, 0, Copy(CodeList.Text, 1,
Length(CodeList.Text) - 2))
else if LineEndType = 1 then
GxOtaReplaceSelection(SourceEditor, 0, Copy(CodeList.Text, 1,
Length(CodeList.Text) - 1))
else
GxOtaReplaceSelection(SourceEditor, 0, CodeList.Text);
end;
end;
finally
FreeAndNil(CodeList);
end;
end;
end.
|
unit FFSLENDGRPTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TFFSLENDGRPRecord = record
PName: String[4];
PLender1: String[240];
PLender2: String[240];
PLender3: String[240];
PLender4: String[240];
PSearchable: Boolean;
PDescription: String[40];
End;
TFFSLENDGRPBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TFFSLENDGRPRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIFFSLENDGRP = (FFSLENDGRPPrimaryKey);
TFFSLENDGRPTable = class( TDBISAMTableAU )
private
FDFName: TStringField;
FDFLender1: TStringField;
FDFLender2: TStringField;
FDFLender3: TStringField;
FDFLender4: TStringField;
FDFSearchable: TBooleanField;
FDFDescription: TStringField;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPLender1(const Value: String);
function GetPLender1:String;
procedure SetPLender2(const Value: String);
function GetPLender2:String;
procedure SetPLender3(const Value: String);
function GetPLender3:String;
procedure SetPLender4(const Value: String);
function GetPLender4:String;
procedure SetPSearchable(const Value: Boolean);
function GetPSearchable:Boolean;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIFFSLENDGRP);
function GetEnumIndex: TEIFFSLENDGRP;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; override;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TFFSLENDGRPRecord;
procedure StoreDataBuffer(ABuffer:TFFSLENDGRPRecord);
property DFName: TStringField read FDFName;
property DFLender1: TStringField read FDFLender1;
property DFLender2: TStringField read FDFLender2;
property DFLender3: TStringField read FDFLender3;
property DFLender4: TStringField read FDFLender4;
property DFSearchable: TBooleanField read FDFSearchable;
property DFDescription: TStringField read FDFDescription;
property PName: String read GetPName write SetPName;
property PLender1: String read GetPLender1 write SetPLender1;
property PLender2: String read GetPLender2 write SetPLender2;
property PLender3: String read GetPLender3 write SetPLender3;
property PLender4: String read GetPLender4 write SetPLender4;
property PSearchable: Boolean read GetPSearchable write SetPSearchable;
property PDescription: String read GetPDescription write SetPDescription;
published
property Active write SetActive;
property EnumIndex: TEIFFSLENDGRP read GetEnumIndex write SetEnumIndex;
end; { TFFSLENDGRPTable }
procedure Register;
implementation
function TFFSLENDGRPTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TFFSLENDGRPTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TFFSLENDGRPTable.GenerateNewFieldName }
function TFFSLENDGRPTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TFFSLENDGRPTable.CreateField }
procedure TFFSLENDGRPTable.CreateFields;
begin
FDFName := CreateField( 'Name' ) as TStringField;
FDFLender1 := CreateField( 'Lender1' ) as TStringField;
FDFLender2 := CreateField( 'Lender2' ) as TStringField;
FDFLender3 := CreateField( 'Lender3' ) as TStringField;
FDFLender4 := CreateField( 'Lender4' ) as TStringField;
FDFSearchable := CreateField( 'Searchable' ) as TBooleanField;
FDFDescription := CreateField( 'Description' ) as TStringField;
end; { TFFSLENDGRPTable.CreateFields }
procedure TFFSLENDGRPTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TFFSLENDGRPTable.SetActive }
procedure TFFSLENDGRPTable.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TFFSLENDGRPTable.GetPName:String;
begin
result := DFName.Value;
end;
procedure TFFSLENDGRPTable.SetPLender1(const Value: String);
begin
DFLender1.Value := Value;
end;
function TFFSLENDGRPTable.GetPLender1:String;
begin
result := DFLender1.Value;
end;
procedure TFFSLENDGRPTable.SetPLender2(const Value: String);
begin
DFLender2.Value := Value;
end;
function TFFSLENDGRPTable.GetPLender2:String;
begin
result := DFLender2.Value;
end;
procedure TFFSLENDGRPTable.SetPLender3(const Value: String);
begin
DFLender3.Value := Value;
end;
function TFFSLENDGRPTable.GetPLender3:String;
begin
result := DFLender3.Value;
end;
procedure TFFSLENDGRPTable.SetPLender4(const Value: String);
begin
DFLender4.Value := Value;
end;
function TFFSLENDGRPTable.GetPLender4:String;
begin
result := DFLender4.Value;
end;
procedure TFFSLENDGRPTable.SetPSearchable(const Value: Boolean);
begin
DFSearchable.Value := Value;
end;
function TFFSLENDGRPTable.GetPSearchable:Boolean;
begin
result := DFSearchable.Value;
end;
procedure TFFSLENDGRPTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TFFSLENDGRPTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TFFSLENDGRPTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Name, String, 4, N');
Add('Lender1, String, 240, N');
Add('Lender2, String, 240, N');
Add('Lender3, String, 240, N');
Add('Lender4, String, 240, N');
Add('Searchable, Boolean, 0, N');
Add('Description, String, 40, N');
end;
end;
procedure TFFSLENDGRPTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Name, Y, Y, N, N');
end;
end;
procedure TFFSLENDGRPTable.SetEnumIndex(Value: TEIFFSLENDGRP);
begin
case Value of
FFSLENDGRPPrimaryKey : IndexName := '';
end;
end;
function TFFSLENDGRPTable.GetDataBuffer:TFFSLENDGRPRecord;
var buf: TFFSLENDGRPRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PName := DFName.Value;
buf.PLender1 := DFLender1.Value;
buf.PLender2 := DFLender2.Value;
buf.PLender3 := DFLender3.Value;
buf.PLender4 := DFLender4.Value;
buf.PSearchable := DFSearchable.Value;
buf.PDescription := DFDescription.Value;
result := buf;
end;
procedure TFFSLENDGRPTable.StoreDataBuffer(ABuffer:TFFSLENDGRPRecord);
begin
DFName.Value := ABuffer.PName;
DFLender1.Value := ABuffer.PLender1;
DFLender2.Value := ABuffer.PLender2;
DFLender3.Value := ABuffer.PLender3;
DFLender4.Value := ABuffer.PLender4;
DFSearchable.Value := ABuffer.PSearchable;
DFDescription.Value := ABuffer.PDescription;
end;
function TFFSLENDGRPTable.GetEnumIndex: TEIFFSLENDGRP;
begin
//VG 220318: No checks because there are no other key types defined
Result := FFSLENDGRPPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'FFS Tables', [ TFFSLENDGRPTable, TFFSLENDGRPBuffer ] );
end; { Register }
function TFFSLENDGRPBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..7] of string = ('NAME','LENDER1','LENDER2','LENDER3','LENDER4','SEARCHABLE'
,'DESCRIPTION' );
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 TFFSLENDGRPBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftBoolean;
7 : result := ftString;
end;
end;
function TFFSLENDGRPBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PName;
2 : result := @Data.PLender1;
3 : result := @Data.PLender2;
4 : result := @Data.PLender3;
5 : result := @Data.PLender4;
6 : result := @Data.PSearchable;
7 : result := @Data.PDescription;
end;
end;
end.
|
{******************************************************************************}
{ }
{ SChannel API definitions for Object Pascal }
{ }
{******************************************************************************}
unit SChannel.JwaSChannel;
interface
uses
Windows,
SChannel.JwaBaseTypes, SChannel.JwaWinCrypt;
const
// Protocols
SP_PROT_TLS1_0_SERVER = $00000040;
SP_PROT_TLS1_0_CLIENT = $00000080;
SP_PROT_TLS1_0 = SP_PROT_TLS1_0_SERVER or SP_PROT_TLS1_0_CLIENT;
SP_PROT_TLS1_1_SERVER = $00000100;
SP_PROT_TLS1_1_CLIENT = $00000200;
SP_PROT_TLS1_1 = SP_PROT_TLS1_1_SERVER or SP_PROT_TLS1_1_CLIENT;
SP_PROT_TLS1_2_SERVER = $00000400;
SP_PROT_TLS1_2_CLIENT = $00000800;
SP_PROT_TLS1_2 = SP_PROT_TLS1_2_SERVER or SP_PROT_TLS1_2_CLIENT;
// QueryContextAttributes/QueryCredentialsAttribute extensions
SECPKG_ATTR_REMOTE_CERT_CONTEXT = $53; // returns PCCERT_CONTEXT
SECPKG_ATTR_LOCAL_CERT_CONTEXT = $54; // returns PCCERT_CONTEXT
SECPKG_ATTR_ROOT_STORE = $55; // returns HCERTCONTEXT to the root store
SECPKG_ATTR_SUPPORTED_ALGS = $56; // returns SecPkgCred_SupportedAlgs
SECPKG_ATTR_CIPHER_STRENGTHS = $57; // returns SecPkgCred_CipherStrengths
SECPKG_ATTR_SUPPORTED_PROTOCOLS = $58; // returns SecPkgCred_SupportedProtocols
SECPKG_ATTR_ISSUER_LIST_EX = $59; // returns SecPkgContext_IssuerListInfoEx
SECPKG_ATTR_CONNECTION_INFO = $5a; // returns SecPkgContext_ConnectionInfo
UNISP_NAME = 'Microsoft Unified Security Protocol Provider';
//
//
// ApplyControlToken PkgParams types
//
// These identifiers are the DWORD types
// to be passed into ApplyControlToken
// through a PkgParams buffer.
SCHANNEL_RENEGOTIATE = 0; // renegotiate a connection
SCHANNEL_SHUTDOWN = 1; // gracefully close down a connection
SCHANNEL_ALERT = 2; // build an error message
SCHANNEL_SESSION = 3; // session control
//
// Schannel credentials data structure.
//
SCH_CRED_V1 = $00000001;
SCH_CRED_V2 = $00000002; // for legacy code
SCH_CRED_VERSION = $00000002; // for legacy code
SCH_CRED_V3 = $00000003; // for legacy code
SCHANNEL_CRED_VERSION = $00000004;
type
_SCHANNEL_CRED = record
dwVersion: DWORD; // always SCHANNEL_CRED_VERSION
cCreds: DWORD;
paCred: PCCERT_CONTEXT;
hRootStore: HCERTSTORE;
cMappers: DWORD;
aphMappers: Pointer; //struct _HMAPPER;
cSupportedAlgs: DWORD;
palgSupportedAlgs: ^ALG_ID;
grbitEnabledProtocols: DWORD;
dwMinimumCipherStrength: DWORD;
dwMaximumCipherStrength: DWORD;
dwSessionLifespan: DWORD;
dwFlags: DWORD;
dwCredFormat: DWORD;
end;
SCHANNEL_CRED = _SCHANNEL_CRED;
PSCHANNEL_CRED = ^SCHANNEL_CRED;
type
SecPkgContext_IssuerListInfoEx = record
aIssuers: PCERT_NAME_BLOB;
cIssuers: Cardinal;
end;
const
SCH_CRED_NO_SYSTEM_MAPPER = $00000002;
SCH_CRED_NO_SERVERNAME_CHECK = $00000004;
SCH_CRED_MANUAL_CRED_VALIDATION = $00000008;
SCH_CRED_NO_DEFAULT_CREDS = $00000010;
SCH_CRED_AUTO_CRED_VALIDATION = $00000020;
SCH_CRED_USE_DEFAULT_CREDS = $00000040;
SCH_CRED_DISABLE_RECONNECTS = $00000080;
SCH_CRED_REVOCATION_CHECK_END_CERT = $00000100;
SCH_CRED_REVOCATION_CHECK_CHAIN = $00000200;
SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = $00000400;
SCH_CRED_IGNORE_NO_REVOCATION_CHECK = $00000800;
SCH_CRED_IGNORE_REVOCATION_OFFLINE = $00001000;
SCH_CRED_RESTRICTED_ROOTS = $00002000;
SCH_CRED_REVOCATION_CHECK_CACHE_ONLY = $00004000;
SCH_CRED_CACHE_ONLY_URL_RETRIEVAL = $00008000;
SCH_CRED_MEMORY_STORE_CERT = $00010000;
SCH_CRED_CACHE_ONLY_URL_RETRIEVAL_ON_CREATE = $00020000;
SCH_SEND_ROOT_CERT = $00040000;
// Constants for SSL_EXTRA_CERT_CHAIN_POLICY_PARA.fdwChecks field
SECURITY_FLAG_IGNORE_REVOCATION = $00000080; // Ignore errors associated with a revoked certificate.
SECURITY_FLAG_IGNORE_UNKNOWN_CA = $00000100; // Ignore errors associated with an unknown certification authority.
SECURITY_FLAG_IGNORE_WRONG_USAGE = $00000200; // Ignore errors associated with the use of a certificate.
SECURITY_FLAG_IGNORE_CERT_CN_INVALID = $00001000; // Ignore errors associated with a certificate that contains a common name that is not valid.
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = $00002000; // Ignore errors associated with an expired certificate.
implementation
end. |
unit CurrencyConverter;
interface
uses
system.Generics.Collections,SysUtils;
{$IF DEFINED(ANDROID) OR DEFINED(IOS) OR DEFINED(LINUX)}
const
StrStartIteration = {$IFNDEF LINUX} 0 {$ELSE}1{$ENDIF};
type
AnsiString = string;
type
AnsiChar = Char;
{$ELSE}
const
StrStartIteration = 1;
{$ENDIF}
type
TCurrencyConverter = class
ratio: double;
symbol: AnsiString;
availableCurrency: TObjectDictionary<AnsiString, double>;
function calculate(value: double): double;
constructor Create();
destructor destroy(); override;
procedure updateCurrencyRatio(symbol: AnsiString; ratio: double);
procedure setCurrency(_symbol: AnsiString);
end;
implementation
procedure TCurrencyConverter.setCurrency(_symbol: AnsiString);
begin
try
ratio := availableCurrency[_symbol];
symbol := _symbol;
except on E : Exception do
begin
ratio := 1.0;
symbol := 'USD';
end;
end;
end;
function TCurrencyConverter.calculate(value: double): double;
begin
Result := value * ratio;
end;
procedure TCurrencyConverter.updateCurrencyRatio(symbol: AnsiString;
ratio: double);
begin
availableCurrency.AddOrSetValue(symbol, ratio);
end;
constructor TCurrencyConverter.Create();
begin
availableCurrency := TObjectDictionary<AnsiString, double>.Create();
if availableCurrency.Count=0 then begin
availableCurrency.TryAdd('EUR', 0.89);
availableCurrency.TryAdd('USD', 1.0);
availableCurrency.TryAdd('GBP', 0.78);
availableCurrency.TryAdd('CAD', 1.35);
availableCurrency.TryAdd('PLN', 3.85);
availableCurrency.TryAdd('INR', 69.07);
availableCurrency.TryAdd('JPY', 109.31);
availableCurrency.TryAdd('BGN', 1.75);
availableCurrency.TryAdd('CZK', 23.03);
availableCurrency.TryAdd('DKK', 6.68);
availableCurrency.TryAdd('HUF', 290.75);
availableCurrency.TryAdd('RON', 4.26);
availableCurrency.TryAdd('SEK', 9.63);
availableCurrency.TryAdd('CHF', 1.01);
availableCurrency.TryAdd('ISK', 122.87);
availableCurrency.TryAdd('NOK', 8.76);
availableCurrency.TryAdd('HRK', 6.63);
availableCurrency.TryAdd('RUB', 64.81);
availableCurrency.TryAdd('TRY', 6.06);
availableCurrency.TryAdd('AUD', 1.45);
availableCurrency.TryAdd('BRL', 3.99);
availableCurrency.TryAdd('CNY', 6.88);
availableCurrency.TryAdd('HKD', 7.85);
availableCurrency.TryAdd('IDR', 14460.00);
availableCurrency.TryAdd('ILS', 3.57);
availableCurrency.TryAdd('INR', 70.36);
availableCurrency.TryAdd('KRW', 1190.48);
availableCurrency.TryAdd('MXN', 19.20);
availableCurrency.TryAdd('MYR', 4.18);
availableCurrency.TryAdd('NZD', 1.53);
availableCurrency.TryAdd('PHP', 52.39);
availableCurrency.TryAdd('SGD', 1.37);
availableCurrency.TryAdd('THB', 31.59);
availableCurrency.TryAdd('ZAR', 14.27);
end;
ratio := 1.0;
symbol := 'USD';
end;
destructor TCurrencyConverter.destroy;
begin
availableCurrency.Free;
end;
end.
|
program Verkauf2 (input, output);
{ Rabattgewaehrung: zweite Version }
const
GRUNDPREIS = 200.00 {EUR};
var
Anzahl : integer;
Preis : real;
begin
writeln ('Bitte die Anzahl bestellter Teile ',
'eingeben:');
readln (Anzahl);
if Anzahl <= 0 then
writeln ('falsche Eingabe')
else
{ es liegt eine Bestellung vor }
begin
Preis := Anzahl * GRUNDPREIS;
if Anzahl > 50 then
{ grosser Rabatt kann gewaehrt werden }
Preis := Preis * 0.8
else
if Anzahl > 10 then
{ kleiner Rabatt kann gewaehrt werden }
Preis := Preis * 0.9;
writeln ('Der Preis betraegt ', Preis, ' EUR')
end
end. { Verkauf2 }
|
unit FeatureError;
interface
uses
FeatureErrorIntf, Error;
type
TFeatureError = class(TError, IFeatureError)
private
FLine: Integer;
FSugestedAction: string;
function GetLine: Integer;
function GetSugestedAction: string;
procedure SetLine(const Value: Integer);
procedure SetSugestedAction(const Value: string);
public
class function NewError(const AMessage: string; const ALine: Integer; const ASugestedAction: string): IFeatureError;
property Line: Integer read GetLine write SetLine;
property SugestedAction: string read GetSugestedAction write SetSugestedAction;
end;
implementation
function TFeatureError.GetLine: Integer;
begin
Result := FLine;
end;
function TFeatureError.GetSugestedAction: string;
begin
Result := FSugestedAction;
end;
class function TFeatureError.NewError(const AMessage: string; const ALine: Integer; const ASugestedAction: string): IFeatureError;
begin
Result := Self.Create;
Result.Message := AMessage;
Result.Line := ALine;
Result.SugestedAction := ASugestedAction;
end;
procedure TFeatureError.SetLine(const Value: Integer);
begin
FLine := Value;
end;
procedure TFeatureError.SetSugestedAction(const Value: string);
begin
FSugestedAction := Value;
end;
end.
|
unit fmuTable;
interface
uses
// VCL
ComCtrls, StdCtrls, Controls, Classes, SysUtils, ExtCtrls, Buttons, Graphics,
// This
untPages, untUtil, untDriver, Spin;
type
{ TfmTable }
TfmTable = class(TPage)
Memo: TMemo;
edtValue: TEdit;
lblValue: TLabel;
lblRowNumber: TLabel;
lblTableNumber: TLabel;
lblFieldNumber: TLabel;
btnGetTableStruct: TBitBtn;
btnGetFieldStruct: TBitBtn;
btnReadTable: TBitBtn;
btnWriteTable: TBitBtn;
btnInitTable: TBitBtn;
seTableNumber: TSpinEdit;
seRowNumber: TSpinEdit;
seFieldNumber: TSpinEdit;
btnShowTablesDlg: TButton;
procedure btnGetTableStructClick(Sender: TObject);
procedure btnGetFieldStructClick(Sender: TObject);
procedure btnReadTableClick(Sender: TObject);
procedure btnWriteTableClick(Sender: TObject);
procedure btnInitTableClick(Sender: TObject);
procedure btnShowTablesDlgClick(Sender: TObject);
end;
implementation
{$R *.DFM}
{ TfmTable }
procedure TfmTable.btnGetTableStructClick(Sender: TObject);
begin
Memo.Clear;
EnableButtons(False);
try
Driver.TableNumber := seTableNumber.Value;
if Driver.GetTableStruct=0 then
begin
Memo.Lines.Add('Название таблицы: ' + Driver.TableName);
Memo.Lines.Add('Кол-во рядов: ' + IntToStr(Driver.RowNumber));
Memo.Lines.Add('Кол-во полей: ' + IntToStr(Driver.FieldNumber));
end;
finally
EnableButtons(True);
end;
end;
procedure TfmTable.btnGetFieldStructClick(Sender: TObject);
begin
Memo.Clear;
EnableButtons(False);
try
Driver.TableNumber := seTableNumber.Value;
Driver.FieldNumber := seFieldNumber.Value;
if Driver.GetFieldStruct = 0 then
begin
Memo.Lines.Add('Название поля: ' + Driver.FieldName);
if Driver.FieldType then Memo.Lines.Add(' Тип поля: строка')
else Memo.Lines.Add('Тип поля: число');
Memo.Lines.Add('Размер поля: '+IntToStr(Driver.FieldSize));
if not Driver.FieldType then
begin
Memo.Lines.Add('Мин. значение: '+IntToStr(Driver.MINValueOfField));
Memo.Lines.Add('Макс. значение: '+IntToStr(Driver.MaxValueOfField));
end;
end;
finally
EnableButtons(True);
end;
end;
procedure TfmTable.btnReadTableClick(Sender: TObject);
begin
Memo.Clear;
EnableButtons(False);
try
Driver.TableNumber := seTableNumber.Value;
Driver.FieldNumber := seFieldNumber.Value;
Driver.RowNumber := seRowNumber.Value;
if Driver.ReadTable = 0 then
begin
Memo.Lines.Add('Название поля: '+Driver.FieldName);
if Driver.FieldType then Memo.Lines.Add(' Тип поля: строка')
else Memo.Lines.Add('Тип поля: число');
Memo.Lines.Add('Размер поля: '+IntToStr(Driver.FieldSize));
if not Driver.FieldType then
begin
Memo.Lines.Add('Мини. значение: '+IntToStr(Driver.MINValueOfField));
Memo.Lines.Add('Макс. значение: '+IntToStr(Driver.MaxValueOfField));
edtValue.Text := IntToStr(Driver.ValueOfFieldInteger);
end
else
begin
edtValue.Text := Driver.ValueOfFieldString;
end;
end;
finally
EnableButtons(True);
end;
end;
procedure TfmTable.btnWriteTableClick(Sender: TObject);
begin
Memo.Clear;
EnableButtons(False);
try
Driver.TableNumber := seTableNumber.Value;
Driver.FieldNumber := seFieldNumber.Value;
Driver.RowNumber := seRowNumber.Value;
Driver.ValueOfFieldString := edtValue.Text;
if Driver.WriteTable = 0 then
begin
Memo.Lines.Add('Структура поля:');
Memo.Lines.Add(' Название поля: ' + Driver.FieldName);
if Driver.FieldType then Memo.Lines.Add(' Тип поля: строка')
else Memo.Lines.Add(' Тип поля: число');
Memo.Lines.Add(' Размер поля: '+IntToStr(Driver.FieldSize));
if not Driver.FieldType then
begin
Memo.Lines.Add(' Мини. значение: '+IntToStr(Driver.MINValueOfField));
Memo.Lines.Add(' Макс. значение: '+IntToStr(Driver.MaxValueOfField));
edtValue.Text := IntToStr(Driver.ValueOfFieldInteger);
end else
edtValue.Text := Driver.ValueOfFieldString;
end;
finally
EnableButtons(True);
end;
end;
procedure TfmTable.btnInitTableClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.InitTable;
finally
EnableButtons(True);
end;
end;
procedure TfmTable.btnShowTablesDlgClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.ParentWnd := Handle;
Driver.ShowTablesDlg;
finally
EnableButtons(True);
end;
end;
end.
|
unit CleanArch_EmbrConf.Core.Repository.Interfaces;
interface
uses
Json,
CleanArch_EmbrConf.Core.Entity.Interfaces;
type
iParkingLotRepository = interface
function getParkingLot(Code : String) : iParkingLot;
function getParkingLotJSON(Code : String) : TJSONArray;
function saveParkedCar(Value : iParkedCar) : iParkingLotRepository;
end;
implementation
end.
|
unit AndroidApi.ProgressDialog;
interface
uses
Androidapi.JNI.App,
Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes,
Androidapi.JNIBridge;
type
JProgressDialog = interface;//android.app.ProgressDialog
JProgressDialogClass = interface(JAlertDialogClass)
['{670F662E-8777-4C53-92DD-CD78B2C6FE21}']
{ Property Methods }
function _GetSTYLE_SPINNER: Integer;
function _GetSTYLE_HORIZONTAL: Integer;
{ Methods }
function init(P1: JContext): JProgressDialog; cdecl; overload;
function init(P1: JContext; P2: Integer): JProgressDialog; cdecl; overload;
function show(P1: JContext; P2: JCharSequence; P3: JCharSequence): JProgressDialog; cdecl; overload;
function show(P1: JContext; P2: JCharSequence; P3: JCharSequence; P4: Boolean): JProgressDialog; cdecl; overload;
function show(P1: JContext; P2: JCharSequence; P3: JCharSequence; P4: Boolean; P5: Boolean): JProgressDialog; cdecl; overload;
function show(P1: JContext; P2: JCharSequence; P3: JCharSequence; P4: Boolean; P5: Boolean; P6: JDialogInterface_OnCancelListener): JProgressDialog; cdecl; overload;
{ Properties }
property STYLE_SPINNER: Integer read _GetSTYLE_SPINNER;
property STYLE_HORIZONTAL: Integer read _GetSTYLE_HORIZONTAL;
end;
[JavaSignature('android/app/ProgressDialog')]
JProgressDialog = interface(JAlertDialog)
['{2CED09DE-2C56-464A-90B4-F9193B45B37D}']
{ Methods }
procedure onStart; cdecl;
procedure setProgress(P1: Integer); cdecl;
procedure setSecondaryProgress(P1: Integer); cdecl;
function getProgress: Integer; cdecl;
function getSecondaryProgress: Integer; cdecl;
function getMax: Integer; cdecl;
procedure setMax(P1: Integer); cdecl;
procedure incrementProgressBy(P1: Integer); cdecl;
procedure incrementSecondaryProgressBy(P1: Integer); cdecl;
procedure setProgressDrawable(P1: JDrawable); cdecl;
procedure setIndeterminateDrawable(P1: JDrawable); cdecl;
procedure setIndeterminate(P1: Boolean); cdecl;
function isIndeterminate: Boolean; cdecl;
procedure setMessage(P1: JCharSequence); cdecl;
procedure setProgressStyle(P1: Integer); cdecl;
procedure setProgressNumberFormat(P1: JString); cdecl;
end;
TJProgressDialog = class(TJavaGenericImport<JProgressDialogClass, JProgressDialog>) end;
implementation
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.