text stringlengths 14 6.51M |
|---|
unit GLDTorusParamsFrame;
interface
uses
Classes, Controls, Forms, ComCtrls, StdCtrls, GL, GLDTypes, GLDSystem,
GLDTorus, GLDNameAndColorFrame, GLDUpDown;
type
TGLDTorusParamsFrame = class(TFrame)
NameAndColor: TGLDNameAndColorFrame;
GB_Params: TGroupBox;
L_Radius1: TLabel;
L_Radius2: TLabel;
L_Segments: TLabel;
L_Sides: TLabel;
L_StartAngle1: TLabel;
L_SweepAngle1: TLabel;
L_StartAngle2: TLabel;
L_SweepAngle2: TLabel;
E_Radius1: TEdit;
E_Radius2: TEdit;
E_Segments: TEdit;
E_Sides: TEdit;
E_StartAngle1: TEdit;
E_SweepAngle1: TEdit;
E_StartAngle2: TEdit;
E_SweepAngle2: TEdit;
UD_Radius1: TGLDUpDown;
UD_Radius2: TGLDUpDown;
UD_Segments: TUpDown;
UD_Sides: TUpDown;
UD_StartAngle1: TGLDUpDown;
UD_SweepAngle1: TGLDUpDown;
UD_StartAngle2: TGLDUpDown;
UD_SweepAngle2: TGLDUpDown;
procedure ParamsChangeUD(Sender: TObject);
procedure SegmentsChangeUD(Sender: TObject; Button: TUDBtnType);
procedure EditEnter(Sender: TObject);
private
FDrawer: TGLDDrawer;
procedure SetDrawer(Value: TGLDDrawer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function HaveTorus: GLboolean;
function GetParams: TGLDTorusParams;
procedure SetParams(const Name: string; const Color: TGLDColor3ub;
const Radius1, Radius2: GLfloat; const Segments, Sides: GLushort;
const StartAngle1, SweepAngle1, StartAngle2, SweepAngle2: GLfloat);
procedure SetParamsFrom(Torus: TGLDTorus);
procedure ApplyParams;
property Drawer: TGLDDrawer read FDrawer write SetDrawer;
end;
implementation
{$R *.dfm}
uses
SysUtils, GLDConst, GLDX;
constructor TGLDTorusParamsFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDrawer := nil;
end;
destructor TGLDTorusParamsFrame.Destroy;
begin
if Assigned(FDrawer) then
if FDrawer.IOFrame = Self then
FDrawer.IOFrame := nil;
inherited Destroy;
end;
function TGLDTorusParamsFrame.HaveTorus: GLboolean;
begin
Result := False;
if Assigned(FDrawer) and
Assigned(FDrawer.EditedObject) and
(FDrawer.EditedObject is TGLDTorus) then
Result := True;
end;
function TGLDTorusParamsFrame.GetParams: TGLDTorusParams;
begin
if HaveTorus then
with TGLDTorus(FDrawer.EditedObject) do
begin
Result.Position := Position.Vector3f;
Result.Rotation := Rotation.Params;
end else
begin
Result.Position := GLD_VECTOR3F_ZERO;
Result.Rotation := GLD_ROTATION3D_ZERO;
end;
Result.Color := NameAndColor.ColorParam;
Result.Radius1 := UD_Radius1.Position;
Result.Radius2 := UD_Radius2.Position;
Result.Segments := UD_Segments.Position;
Result.Sides := UD_Sides.Position;
Result.StartAngle1 := UD_StartAngle1.Position;
Result.SweepAngle1 := UD_SweepAngle1.Position;
Result.StartAngle2 := UD_StartAngle2.Position;
Result.SweepAngle2 := UD_SweepAngle2.Position;
end;
procedure TGLDTorusParamsFrame.SetParams(const Name: string; const Color: TGLDColor3ub;
const Radius1, Radius2: GLfloat; const Segments, Sides: GLushort;
const StartAngle1, SweepAngle1, StartAngle2, SweepAngle2: GLfloat);
begin
NameAndColor.NameParam := Name;
NameAndColor.ColorParam := Color;
UD_Radius1.Position := Radius1;
UD_Radius2.Position := Radius2;
UD_Segments.Position := Segments;
UD_Sides.Position := Sides;
UD_StartAngle1.Position := StartAngle1;
UD_SweepAngle1.Position := SweepAngle1;
UD_StartAngle2.Position := StartAngle2;
UD_SweepAngle2.Position := SweepAngle2;
end;
procedure TGLDTorusParamsFrame.SetParamsFrom(Torus: TGLDTorus);
begin
if not Assigned(Torus) then Exit;
with Torus do
SetParams(Name, Color.Color3ub, Radius1, Radius2, Segments, Sides,
StartAngle1, SweepAngle1, StartAngle2, SweepAngle2);
end;
procedure TGLDTorusParamsFrame.ParamsChangeUD(Sender: TObject);
begin
if HaveTorus then
with TGLDTorus(FDrawer.EditedObject) do
if Sender = UD_Radius1 then
Radius1 := UD_Radius1.Position else
if Sender = UD_Radius2 then
Radius2 := UD_Radius2.Position else
if Sender = UD_StartAngle1 then
StartAngle1 := UD_StartAngle1.Position else
if Sender = UD_SweepAngle1 then
SweepAngle1 := UD_SweepAngle1.Position else
if Sender = UD_StartAngle2 then
StartAngle2 := UD_StartAngle2.Position else
if Sender = UD_SweepAngle2 then
SweepAngle2 := UD_SweepAngle2.Position;
end;
procedure TGLDTorusParamsFrame.SegmentsChangeUD(Sender: TObject; Button: TUDBtnType);
begin
if HaveTorus then
with TGLDTorus(FDrawer.EditedObject) do
if Sender = UD_Segments then
Segments := UD_Segments.Position else
if Sender = UD_Sides then
Sides := UD_Sides.Position;
end;
procedure TGLDTorusParamsFrame.EditEnter(Sender: TObject);
begin
ApplyParams;
end;
procedure TGLDTorusParamsFrame.ApplyParams;
begin
if HaveTorus then
TGLDTorus(FDrawer.EditedObject).Params := GetParams;
end;
procedure TGLDTorusParamsFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDTorusParamsFrame.SetDrawer(Value: TGLDDrawer);
begin
FDrawer := Value;
NameAndColor.Drawer := FDrawer;
end;
procedure Register;
begin
//RegisterComponents('GLDraw', [TGLDTorusParamsFrame]);
end;
end.
|
unit uExplorerShelfProvider;
interface
uses
System.SysUtils,
System.StrUtils,
Vcl.Graphics,
Dmitry.Utils.ShellIcons,
Dmitry.PathProviders,
Dmitry.PathProviders.MyComputer,
uConstants,
uMemory,
uTranslate,
uPhotoShelf,
uExplorerPathProvider;
type
TShelfItem = class(TPathItem)
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
public
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
end;
type
TShelfProvider = class(TExplorerPathProvider)
public
function GetTranslateID: string; override;
function Supports(Item: TPathItem): Boolean; override;
function Supports(Path: string): Boolean; override;
function CreateFromPath(Path: string): TPathItem; override;
function InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; override;
end;
implementation
{ TShelfItem }
constructor TShelfItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
FCanHaveChildren := False;
FDisplayName := TA('Photo shelf', 'PhotoShelf');
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
function TShelfItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TShelfItem.InternalCreateNewInstance: TPathItem;
begin
Result := TShelfItem.Create;
end;
function TShelfItem.InternalGetParent: TPathItem;
begin
Result := THomeItem.Create;
end;
function TShelfItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
begin
F(FImage);
FindIcon(HInstance, 'SHELF', ImageSize, 32, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
{ TShelfProvider }
function TShelfProvider.CreateFromPath(Path: string): TPathItem;
begin
Result := nil;
if StartsText(cShelfPath, AnsiLowerCase(Path)) then
Result := TShelfItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
end;
function TShelfProvider.Supports(Item: TPathItem): Boolean;
begin
Result := Item is TShelfItem;
Result := Result or Supports(Item.Path);
end;
function TShelfProvider.GetTranslateID: string;
begin
Result := 'PhotoShelf';
end;
function TShelfProvider.InternalFillChildList(Sender: TObject; Item: TPathItem;
List: TPathItemCollection; Options, ImageSize, PacketSize: Integer;
CallBack: TLoadListCallBack): Boolean;
var
Cancel: Boolean;
SI: TShelfItem;
begin
inherited;
Result := True;
Cancel := False;
if Options and PATH_LOAD_ONLY_FILE_SYSTEM > 0 then
Exit;
if Item is THomeItem then
begin
if PhotoShelf.Count > 0 then
begin
SI := TShelfItem.CreateFromPath(cShelfPath, Options, ImageSize);
List.Add(SI);
end;
end;
if Item is TShelfItem then
begin
//do nothing, all logic is inside ExplorerThread unit
end;
if Assigned(CallBack) then
CallBack(Sender, Item, List, Cancel);
end;
function TShelfProvider.Supports(Path: string): Boolean;
begin
Result := StartsText(cShelfPath, AnsiLowerCase(Path));
Result := Result or (Pos(cImagesSearchPath, AnsiLowerCase(Path)) > 0);
Result := Result or (Pos(cFilesSearchPath, AnsiLowerCase(Path)) > 0);
end;
end.
|
unit Chapter05._01_Solution2;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
AI.ListNode;
// 206. Reverse Linked List
// https://leetcode.com/problems/reverse-linked-list/description/
// 时间复杂度: O(n)
// 空间复杂度: O(1)
type
TSolution = class(TObject)
public
function reverseList(head: TListNode): TListNode;
end;
implementation
{ TSolution }
function TSolution.reverseList(head: TListNode): TListNode;
var
ret: TListNode;
begin
if (head = nil) or (head.Next = nil) then
begin
Result := head;
Exit;
end;
ret := reverseList(head.Next);
// head->next 此刻指向 head 后面的链表的尾节点
// head->next->next = head 把 head 节点放在了尾部
head.Next.Next := head;
head.Next := nil;
Result := ret;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation;
type
TForm1 = class(TForm)
NoPluralLabel: TLabel;
NoPluralLabel0: TLabel;
NoPluralLabel1: TLabel;
NoPluralLabel2: TLabel;
HomeLabel: TLabel;
HomeLabel0: TLabel;
HomeLabel1: TLabel;
HomeLabel2: TLabel;
PluralLabel: TLabel;
PluralLabel0: TLabel;
PluralLabel1: TLabel;
PluralLabel2: TLabel;
MultiPluralLabel: TLabel;
MultiPluralLabel1: TLabel;
MultiPluralLabel2: TLabel;
MultiPluralLabel3: TLabel;
MultiPluralLabel4: TLabel;
LanguageButton: TButton;
procedure FormCreate(Sender: TObject);
procedure LanguageButtonClick(Sender: TObject);
private
procedure UpdateStrings;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
NtBase,
NtPattern,
NtResource,
FMX.NtLanguageDlg,
FMX.NtTranslator;
procedure TForm1.UpdateStrings;
procedure ProcessNoPlural(count: Integer; lab: TLabel);
begin
// On most languages this does not work except when count is 1
// Do not use code like this!
lab.Text := Format(_T('%d file'), [count]);
if TMultiPattern.IsSingleFormLanguage or (count = 1) or ((count = 0) and TMultiPattern.IsZeroLikeOne) then
lab.TextSettings.FontColor := TAlphaColorRec.DarkGreen
else
lab.TextSettings.FontColor := TAlphaColorRec.Crimson;
end;
procedure ProcessHomeBrewed(count: Integer; lab: TLabel);
begin
// This works on some Western languages (those that use similar plural rules as English)
// but would fail for example in French.
// Do not use code like this!
if count = 1 then
lab.Text := Format(_T('%d file'), [count])
else
lab.Text := Format(_T('%d files'), [count]);
if not TMultiPattern.IsSingleFormLanguage and (count = 0) and TMultiPattern.IsZeroLikeOne then
lab.TextSettings.FontColor := TAlphaColorRec.Crimson
else
lab.TextSettings.FontColor := TAlphaColorRec.DarkGreen
end;
// The following two samples handle plural forms correctly. Use this kind of code in your applications.
procedure ProcessPluralAware(count: Integer; lab: TLabel);
begin
// This works on every count and language (expecting SFiles translated correctly with right patterns)
// This message contains two patterns: one and other.
// Localized strings will contain the patterns used by the target languages:
// - German is like English: one and other
// - Polish: one, paucal, other
// - Japanese: other
lab.Text := TMultiPattern.Format(_T('{plural, one {%d file} other {%d files}}', 'FilesPlural'), count, [count]);
lab.TextSettings.FontColor := TAlphaColorRec.DarkGreen;
end;
procedure ProcessMultiPlural(completed, total: Integer; lab: TLabel);
begin
// This message contains two pluralized parameters. Contains three parts and seven patterns:
// - Pattern 0 is the top level pattern without pluralized parameters.
// - Patterns 1-3 are zero, one and other for completed parameter.
// These contain additional second placeholder (%s or %1:s) for the rest of the message
// - Patterns 4-6 are zero, one and other for total parameter.
//
// On runtime part 3 is firstly created by choosing the right pattern and injecting total there.
// Then part 2 is created by choosing the right pattern and injecting completed and part 3 there.
// Finally part 1 is created by injecting part 2 there resulting the final string.
lab.Text := TMultiPattern.Format(_T('I have completed {plural, zero {none} one {one} other {%d}} {plural, zero {out of none steps} one {out of one step} other {out of %d steps}}', 'MessagePlural'), [completed, total]);
lab.TextSettings.FontColor := TAlphaColorRec.DarkGreen;
end;
begin
ProcessNoPlural(0, NoPluralLabel0);
ProcessNoPlural(1, NoPluralLabel1);
ProcessNoPlural(2, NoPluralLabel2);
ProcessHomeBrewed(0, HomeLabel0);
ProcessHomeBrewed(1, HomeLabel1);
ProcessHomeBrewed(2, HomeLabel2);
ProcessPluralAware(0, PluralLabel0);
ProcessPluralAware(1, PluralLabel1);
ProcessPluralAware(2, PluralLabel2);
ProcessMultiPlural(0, 1, MultiPluralLabel1);
ProcessMultiPlural(1, 1, MultiPluralLabel2);
ProcessMultiPlural(1, 3, MultiPluralLabel3);
ProcessMultiPlural(2, 3, MultiPluralLabel4);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
NtResources._T('English', 'en');
NtResources._T('Finnish', 'fi');
NtResources._T('German', 'de');
NtResources._T('French', 'fr');
NtResources._T('Japanese', 'ja');
_T(Self);
UpdateStrings;
end;
procedure TForm1.LanguageButtonClick(Sender: TObject);
begin
if TNtLanguageDialog.Select then
UpdateStrings;
end;
end.
|
{ ****************************************************************************** }
{ * Status IO writen by QQ 600585@qq.com * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit DoStatusIO;
{$INCLUDE zDefine.inc}
interface
uses
{$IFNDEF FPC}
{$IF Defined(WIN32) or Defined(WIN64)}
Windows,
{$ELSEIF not Defined(Linux)}
FMX.Types,
{$IFEND}
{$IFEND FPC}
SysUtils, Classes, SyncObjs,
{$IFDEF FPC}
FPCGenericStructlist, fgl,
{$ELSE FPC}
System.Generics.Collections,
{$ENDIF FPC}
PascalStrings, UPascalStrings, UnicodeMixedLib, CoreClasses;
type
{$IFDEF FPC}
TDoStatusProc = procedure(Text_: SystemString; const ID: Integer) is nested;
{$ELSE FPC}
TDoStatusProc = reference to procedure(Text_: SystemString; const ID: Integer);
{$ENDIF FPC}
TDoStatusMethod = procedure(Text_: SystemString; const ID: Integer) of object;
TDoStatusCall = procedure(Text_: SystemString; const ID: Integer);
procedure AddDoStatusHook(TokenObj: TCoreClassObject; CallProc: TDoStatusMethod);
procedure AddDoStatusHookM(TokenObj: TCoreClassObject; CallProc: TDoStatusMethod);
procedure AddDoStatusHookC(TokenObj: TCoreClassObject; CallProc: TDoStatusCall);
procedure AddDoStatusHookP(TokenObj: TCoreClassObject; CallProc: TDoStatusProc);
procedure DeleteDoStatusHook(TokenObj: TCoreClassObject);
procedure RemoveDoStatusHook(TokenObj: TCoreClassObject);
procedure DisableStatus;
procedure EnabledStatus;
procedure DoStatus(Text_: SystemString; const ID: Integer); overload;
procedure DoStatus(const v: Pointer; siz, width: NativeInt); overload;
procedure DoStatus(prefix: SystemString; v: Pointer; siz, width: NativeInt); overload;
procedure DoStatus(const v: TCoreClassStrings); overload;
procedure DoStatus(const v: Int64); overload;
procedure DoStatus(const v: Integer); overload;
procedure DoStatus(const v: Single); overload;
procedure DoStatus(const v: Double); overload;
procedure DoStatus(const v: Pointer); overload;
procedure DoStatus(const v: SystemString; const Args: array of const); overload;
procedure DoError(v: SystemString; const Args: array of const); overload;
procedure DoStatus(const v: SystemString); overload;
procedure DoStatus(const v: TPascalString); overload;
procedure DoStatus(const v: TUPascalString); overload;
procedure DoStatus(const v: TMD5); overload;
procedure DoStatus; overload;
procedure DoStatusNoLn(const v: TPascalString); overload;
procedure DoStatusNoLn(const v: SystemString; const Args: array of const); overload;
procedure DoStatusNoLn; overload;
function StrInfo(s: TPascalString): string; overload;
function StrInfo(s: TUPascalString): string; overload;
function BytesInfo(s: TBytes): string; overload;
var
LastDoStatus: SystemString;
IDEOutput: Boolean;
ConsoleOutput: Boolean;
OnDoStatusHook: TDoStatusCall;
StatusThreadID: Boolean;
implementation
procedure bufHashToString(hash: Pointer; Size: NativeInt; var output: TPascalString);
const
HexArr: array [0 .. 15] of SystemChar = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
var
i: Integer;
begin
output.Len := Size * 2;
for i := 0 to Size - 1 do
begin
output.buff[i * 2] := HexArr[(PByte(nativeUInt(hash) + i)^ shr 4) and $0F];
output.buff[i * 2 + 1] := HexArr[PByte(nativeUInt(hash) + i)^ and $0F];
end;
end;
procedure DoStatus(Text_: SystemString; const ID: Integer);
begin
try
OnDoStatusHook(Text_, ID);
except
end;
end;
procedure DoStatus(const v: Pointer; siz, width: NativeInt);
var
s: TPascalString;
i: Integer;
n: SystemString;
begin
bufHashToString(v, siz, s);
n := '';
for i := 1 to s.Len div 2 do
begin
if n <> '' then
n := n + #32 + s[i * 2 - 1] + s[i * 2]
else
n := s[i * 2 - 1] + s[i * 2];
if i mod (width div 2) = 0 then
begin
DoStatus(n);
n := '';
end;
end;
if n <> '' then
DoStatus(n);
end;
procedure DoStatus(prefix: SystemString; v: Pointer; siz, width: NativeInt);
var
s: TPascalString;
i: Integer;
n: SystemString;
begin
bufHashToString(v, siz, s);
n := '';
for i := 1 to s.Len div 2 do
begin
if n <> '' then
n := n + #32 + s[i * 2 - 1] + s[i * 2]
else
n := s[i * 2 - 1] + s[i * 2];
if i mod (width div 2) = 0 then
begin
DoStatus(prefix + n);
n := '';
end;
end;
if n <> '' then
DoStatus(prefix + n);
end;
procedure DoStatus(const v: TCoreClassStrings);
var
i: Integer;
o: TCoreClassObject;
begin
for i := 0 to v.Count - 1 do
begin
o := v.Objects[i];
if o <> nil then
DoStatus('%s<%s>', [v[i], o.ClassName])
else
DoStatus(v[i]);
end;
end;
procedure DoStatus(const v: Int64);
begin
DoStatus(IntToStr(v));
end;
procedure DoStatus(const v: Integer);
begin
DoStatus(IntToStr(v));
end;
procedure DoStatus(const v: Single);
begin
DoStatus(FloatToStr(v));
end;
procedure DoStatus(const v: Double);
begin
DoStatus(FloatToStr(v));
end;
procedure DoStatus(const v: Pointer);
begin
DoStatus(Format('0x%p', [v]));
end;
procedure DoStatus(const v: SystemString; const Args: array of const);
begin
DoStatus(Format(v, Args));
end;
procedure DoError(v: SystemString; const Args: array of const);
begin
DoStatus(Format(v, Args), 2);
end;
procedure DoStatus(const v: SystemString);
begin
DoStatus(v, 0);
end;
procedure DoStatus(const v: TPascalString);
begin
DoStatus(v.Text, 0);
end;
procedure DoStatus(const v: TUPascalString);
begin
DoStatus(v.Text, 0);
end;
procedure DoStatus(const v: TMD5);
begin
DoStatus(umlMD5ToString(v).Text);
end;
type
TStatusProcStruct = record
TokenObj: TCoreClassObject;
OnStatusM: TDoStatusMethod;
OnStatusC: TDoStatusCall;
OnStatusP: TDoStatusProc;
end;
PStatusProcStruct = ^TStatusProcStruct;
TStatusStruct = record
s: SystemString;
th: TCoreClassThread;
TriggerTime: TTimeTick;
ID: Integer;
end;
PStatusStruct = ^TStatusStruct;
TStatusNoLnStruct = record
s: TPascalString;
th: TCoreClassThread;
TriggerTime: TTimeTick;
end;
PStatusNoLnStruct = ^TStatusNoLnStruct;
TStatusProcList = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<PStatusProcStruct>;
TStatusStructList = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<PStatusStruct>;
TStatusNoLnStructList = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<PStatusNoLnStruct>;
var
StatusActive: Boolean;
HookStatusProcs: TStatusProcList;
StatusStructList: TStatusStructList;
StatusCritical: TCriticalSection;
StatusNoLnStructList: TStatusNoLnStructList;
Hooked_OnCheckThreadSynchronize: TCheckThreadSynchronize;
function GetOrCreateStatusNoLnData_(th_: TCoreClassThread): PStatusNoLnStruct;
var
tk: TTimeTick;
i: Integer;
begin
tk := GetTimeTick();
Result := nil;
i := 0;
while i < StatusNoLnStructList.Count do
begin
if StatusNoLnStructList[i]^.th = th_ then
begin
Result := StatusNoLnStructList[i];
Result^.TriggerTime := tk;
if i > 0 then
StatusNoLnStructList.Exchange(i, 0);
inc(i);
end
else if tk - StatusNoLnStructList[i]^.TriggerTime > C_Tick_Minute then
begin
Dispose(StatusNoLnStructList[i]);
StatusNoLnStructList.Delete(i);
end
else
inc(i);
end;
if Result = nil then
begin
new(Result);
Result^.s := '';
Result^.th := th_;
Result^.TriggerTime := tk;
StatusNoLnStructList.Add(Result);
end;
end;
function GetOrCreateStatusNoLnData(): PStatusNoLnStruct;
begin
Result := GetOrCreateStatusNoLnData_(TCoreClassThread.CurrentThread);
end;
procedure DoStatusNoLn(const v: TPascalString);
var
L, i: Integer;
StatusNoLnData: PStatusNoLnStruct;
pSS: PStatusStruct;
begin
StatusCritical.Acquire;
StatusNoLnData := GetOrCreateStatusNoLnData();
try
L := v.Len;
i := 1;
while i <= L do
begin
if CharIn(v[i], [#13, #10]) then
begin
if StatusNoLnData^.s.Len > 0 then
begin
new(pSS);
pSS^.s := StatusNoLnData^.s.Text;
pSS^.th := TCoreClassThread.CurrentThread;
pSS^.TriggerTime := GetTimeTick;
pSS^.ID := 0;
StatusStructList.Add(pSS);
StatusNoLnData^.s := '';
end;
repeat
inc(i);
until (i > L) or (not CharIn(v[i], [#13, #10]));
end
else
begin
StatusNoLnData^.s.Append(v[i]);
inc(i);
end;
end;
finally
StatusCritical.Release;
end;
end;
procedure DoStatusNoLn(const v: SystemString; const Args: array of const);
begin
DoStatusNoLn(Format(v, Args));
end;
procedure DoStatusNoLn;
var
StatusNoLnData: PStatusNoLnStruct;
s: SystemString;
begin
StatusCritical.Acquire;
StatusNoLnData := GetOrCreateStatusNoLnData();
s := StatusNoLnData^.s;
StatusNoLnData^.s := '';
StatusCritical.Release;
if Length(s) > 0 then
DoStatus(s);
end;
function StrInfo(s: TPascalString): string;
begin
Result := BytesInfo(s.Bytes);
end;
function StrInfo(s: TUPascalString): string;
begin
Result := BytesInfo(s.Bytes);
end;
function BytesInfo(s: TBytes): string;
begin
Result := umlStringOf(s);
end;
procedure _InternalOutput(const Text_: U_String; const ID: Integer);
var
i: Integer;
p: PStatusProcStruct;
n: U_String;
begin
if Text_.Exists(#10) then
begin
n := Text_.DeleteChar(#13);
_InternalOutput(umlGetFirstStr_Discontinuity(n, #10), ID);
n := umlDeleteFirstStr_Discontinuity(n, #10);
_InternalOutput(n, ID);
exit;
end;
if (StatusActive) and (HookStatusProcs.Count > 0) then
begin
LastDoStatus := Text_;
for i := HookStatusProcs.Count - 1 downto 0 do
begin
p := HookStatusProcs[i];
try
if Assigned(p^.OnStatusM) then
p^.OnStatusM(Text_, ID);
if Assigned(p^.OnStatusC) then
p^.OnStatusC(Text_, ID);
if Assigned(p^.OnStatusP) then
p^.OnStatusP(Text_, ID);
except
end;
end;
end;
{$IFNDEF FPC}
if (StatusActive) and ((IDEOutput) or (ID = 2)) and (DebugHook <> 0) then
begin
{$IF Defined(WIN32) or Defined(WIN64)}
OutputDebugString(PWideChar('"' + Text_ + '"'));
{$ELSEIF not Defined(Linux)}
FMX.Types.Log.d('"' + Text_ + '"');
{$IFEND}
end;
{$IFEND FPC}
if (StatusActive) and ((ConsoleOutput) or (ID = 2)) and (IsConsole) then
Writeln(Text_.Text);
end;
procedure CheckDoStatus(th: TCoreClassThread);
var
i: Integer;
pSS: PStatusStruct;
begin
if StatusCritical = nil then
exit;
if (th = nil) or (th.ThreadID <> MainThreadID) then
exit;
StatusCritical.Acquire;
try
if StatusStructList.Count > 0 then
begin
for i := 0 to StatusStructList.Count - 1 do
begin
pSS := StatusStructList[i];
_InternalOutput(pSS^.s, pSS^.ID);
pSS^.s := '';
Dispose(pSS);
end;
StatusStructList.Clear;
end;
finally
StatusCritical.Release;
end;
end;
procedure DoStatus;
begin
CheckDoStatus(TCoreClassThread.CurrentThread);
end;
procedure InternalDoStatus(Text_: SystemString; const ID: Integer);
var
th: TCoreClassThread;
pSS: PStatusStruct;
begin
th := TCoreClassThread.CurrentThread;
if (th = nil) or (th.ThreadID <> MainThreadID) then
begin
new(pSS);
if StatusThreadID then
pSS^.s := '[' + IntToStr(th.ThreadID) + '] ' + Text_
else
pSS^.s := Text_;
pSS^.th := th;
pSS^.TriggerTime := GetTimeTick();
pSS^.ID := ID;
StatusCritical.Acquire;
StatusStructList.Add(pSS);
StatusCritical.Release;
exit;
end;
CheckDoStatus(th);
_InternalOutput(Text_, ID);
end;
procedure AddDoStatusHook(TokenObj: TCoreClassObject; CallProc: TDoStatusMethod);
begin
AddDoStatusHookM(TokenObj, CallProc);
end;
procedure AddDoStatusHookM(TokenObj: TCoreClassObject; CallProc: TDoStatusMethod);
var
p: PStatusProcStruct;
begin
new(p);
p^.TokenObj := TokenObj;
p^.OnStatusM := CallProc;
p^.OnStatusC := nil;
p^.OnStatusP := nil;
HookStatusProcs.Add(p);
end;
procedure AddDoStatusHookC(TokenObj: TCoreClassObject; CallProc: TDoStatusCall);
var
p: PStatusProcStruct;
begin
new(p);
p^.TokenObj := TokenObj;
p^.OnStatusM := nil;
p^.OnStatusC := CallProc;
p^.OnStatusP := nil;
HookStatusProcs.Add(p);
end;
procedure AddDoStatusHookP(TokenObj: TCoreClassObject; CallProc: TDoStatusProc);
var
p: PStatusProcStruct;
begin
new(p);
p^.TokenObj := TokenObj;
p^.OnStatusM := nil;
p^.OnStatusC := nil;
p^.OnStatusP := CallProc;
HookStatusProcs.Add(p);
end;
procedure DeleteDoStatusHook(TokenObj: TCoreClassObject);
var
i: Integer;
p: PStatusProcStruct;
begin
i := 0;
while i < HookStatusProcs.Count do
begin
p := HookStatusProcs[i];
if p^.TokenObj = TokenObj then
begin
Dispose(p);
HookStatusProcs.Delete(i);
end
else
inc(i);
end;
end;
procedure RemoveDoStatusHook(TokenObj: TCoreClassObject);
begin
DeleteDoStatusHook(TokenObj);
end;
procedure DisableStatus;
begin
StatusActive := False;
end;
procedure EnabledStatus;
begin
StatusActive := True;
end;
procedure DoCheckThreadSynchronize;
begin
DoStatus();
if Assigned(Hooked_OnCheckThreadSynchronize) then
Hooked_OnCheckThreadSynchronize();
end;
procedure _DoInit;
begin
HookStatusProcs := TStatusProcList.Create;
StatusStructList := TStatusStructList.Create;
StatusCritical := TCriticalSection.Create;
StatusNoLnStructList := TStatusNoLnStructList.Create;
StatusActive := True;
LastDoStatus := '';
IDEOutput := False;
ConsoleOutput := True;
OnDoStatusHook := {$IFDEF FPC}@{$ENDIF FPC}InternalDoStatus;
StatusThreadID := True;
Hooked_OnCheckThreadSynchronize := CoreClasses.OnCheckThreadSynchronize;
CoreClasses.OnCheckThreadSynchronize := {$IFDEF FPC}@{$ENDIF FPC}DoCheckThreadSynchronize;
end;
procedure _DoFree;
var
i: Integer;
pSS: PStatusStruct;
begin
for i := 0 to HookStatusProcs.Count - 1 do
Dispose(PStatusProcStruct(HookStatusProcs[i]));
DisposeObject(HookStatusProcs);
for i := 0 to StatusStructList.Count - 1 do
begin
pSS := StatusStructList[i];
pSS^.s := '';
Dispose(pSS);
end;
DisposeObject(StatusStructList);
for i := 0 to StatusNoLnStructList.Count - 1 do
Dispose(StatusNoLnStructList[i]);
DisposeObject(StatusNoLnStructList);
DisposeObject(StatusCritical);
StatusActive := True;
StatusCritical := nil;
end;
initialization
_DoInit;
finalization
_DoFree;
end.
|
unit Chapter10._02_Solution1;
{$mode objfpc}{$H+}
{$ModeSwitch advancedrecords}
interface
uses
Classes,
SysUtils,
Math,
DeepStar.Utils;
/// 435. Non-overlapping Intervals
/// https://leetcode.com/problems/non-overlapping-intervals/description/
/// 动态规划
/// 时间复杂度: O(n^2)
/// 空间复杂度: O(n)
type
TInterval = record
Start: integer;
End_: integer;
constructor Create(newStart: integer; newEnd: integer);
class function Comparer(constref Left, Right: TInterval): integer; static;
end;
TArr_TInterval = array of TInterval;
TSolution = class(TObject)
public
function EraseOverlapIntervals(intervals: TArr_TInterval): integer;
end;
procedure Main;
implementation
procedure Main;
var
intervals: TArr_TInterval;
begin
with TSolution.Create do
begin
intervals := [
TInterval.Create(1, 2),
TInterval.Create(2, 3),
TInterval.Create(3, 4),
TInterval.Create(1, 3)];
WriteLn(EraseOverlapIntervals(intervals));
intervals := [
TInterval.Create(1, 2),
TInterval.Create(1, 2),
TInterval.Create(1, 2)];
WriteLn(EraseOverlapIntervals(intervals));
intervals := [
TInterval.Create(1, 2),
TInterval.Create(2, 3)];
WriteLn(EraseOverlapIntervals(intervals));
Free;
end;
end;
{ TInterval }
constructor TInterval.Create(newStart: integer; newEnd: integer);
begin
Start := newStart;
End_ := newEnd;
end;
class function TInterval.Comparer(constref Left, Right: TInterval): integer;
begin
if Left.Start <> Right.Start then
begin
Result := Left.Start - Right.Start;
Exit;
end;
Result := Left.Start - Right.Start;
end;
{ TSolution }
function TSolution.EraseOverlapIntervals(intervals: TArr_TInterval): integer;
type
TArrayUtils_TInterval = specialize TArrayUtils<TInterval>;
TCmp = TArrayUtils_TInterval.TCmp_T;
TCmpFunc = TArrayUtils_TInterval.TComparisonFunc_T;
var
cmp: TCmpFunc;
memo: TArr_int;
res, i, j: integer;
begin
if Length(intervals) = 0 then
Exit(0);
cmp := TCmpFunc(@TInterval.Comparer);
TArrayUtils_TInterval.Sort(intervals, TCmp.Construct(cmp));
// memo[i]表示以intervals[i]为结尾的区间能构成的最长不重叠区间序列
SetLength(memo, Length(intervals));
TArrayUtils_int.FillArray(memo, 1);
for i := 1 to High(intervals) do
// memo[i]
for j := 0 to i - 1 do
if intervals[i].Start >= intervals[j].End_ then
memo[i] := Max(memo[i], 1 + memo[j]);
res := 0;
for i := 0 to High(memo) do
res := Max(res, memo[i]);
Result := Length(intervals) - res;
end;
end.
|
unit ufrmDialogTipePembayaran;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls,
StdCtrls, uRetnoUnit, uModTipePembayaran, ufraFooterDialog3Button,
System.Actions, Vcl.ActnList;
type
TfrmDialogTipePembayaran = class(TfrmMasterDialog)
lbl1: TLabel;
lbl2: TLabel;
edtKodeTipePembayaran: TEdit;
edtTipePembayaran: TEdit;
procedure actDeleteExecute(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
private
FModTipePembayaran: TModTipePembayaran;
function GetModTipePembayaran: TModTipePembayaran;
procedure SimpanData;
function ValidateData: boolean;
property ModTipePembayaran: TModTipePembayaran read GetModTipePembayaran write
FModTipePembayaran;
public
procedure LoadData(aID: string);
end;
var
frmDialogTipePembayaran: TfrmDialogTipePembayaran;
implementation
uses uDMClient, uAppUtils, uConstanta;
{$R *.dfm}
procedure TfrmDialogTipePembayaran.actDeleteExecute(Sender: TObject);
begin
inherited;
if not TAppUtils.Confirm('Yakin menghapus?') then exit;
if ModTipePembayaran.ID <> '' then
begin
try
DMClient.CrudClient.DeleteFromDB(ModTipePembayaran);
TAppUtils.Information('Berhasil Hapus');
except
TAppUtils.Error('Gagal Hapus Data');
raise
end;
end;
end;
procedure TfrmDialogTipePembayaran.actSaveExecute(Sender: TObject);
begin
inherited;
if not ValidateData then exit;
SimpanData;
end;
function TfrmDialogTipePembayaran.GetModTipePembayaran: TModTipePembayaran;
begin
if not assigned(FModTipePembayaran) then
FModTipePembayaran := TModTipePembayaran.Create;
Result := FModTipePembayaran;
end;
procedure TfrmDialogTipePembayaran.LoadData(aID: string);
begin
FModTipePembayaran := DMClient.CrudClient.Retrieve(
TModTipePembayaran.ClassName,aID) as TModTipePembayaran;
edtKodeTipePembayaran.Text := ModTipePembayaran.TPBYR_CODE;
edtTipePembayaran.Text := ModTipePembayaran.TPBYR_NAME;
end;
procedure TfrmDialogTipePembayaran.SimpanData;
begin
ModTipePembayaran.TPBYR_CODE := edtKodeTipePembayaran.Text;
ModTipePembayaran.TPBYR_NAME := edtTipePembayaran.Text;
try
DMClient.CrudClient.SaveToDB(ModTipePembayaran);
TAppUtils.Information(CONF_ADD_SUCCESSFULLY);
except
TAppUtils.Error('Gagal Simpan Data');
raise
end;
end;
function TfrmDialogTipePembayaran.ValidateData: boolean;
begin
Result := False;
if edtKodeTipePembayaran.Text ='' then
begin TAppUtils.Warning('Kode Tidak Boleh Kosong');
exit;
end;
if edtTipePembayaran.Text ='' then
begin TAppUtils.Warning('Nama Tidak Boleh Kosong');
exit;
end;
Result := True;
// TODO -cMM: TfrmDialogTipePembayaran.ValidateData default body inserted
end;
end.
|
PROGRAM DAG (Input,Output, Recipes, OutRecipes);
{****************************************************************************
Program Author: Scott Janousek Due: Wed May 12, 1993
Student ID: 4361106 Section: 1 MWF 10:10
Program Assignment 5 Instructor: Cris Pedgregal
Program Desciption: To implement a DAG (Directed Acyclic Graph). A data
------------------ structure in which there are no cycles (paths from
any node back to itself). This the program will: (1) Build such a DAG
from given information about the vertex and edges values contained in
a specified file. (2) Sort the Nodes based on a KeyField using Two Sorts.
(3) Implement a Toplogical Sort on the DAG. (5) Save all this information
to a Output file.
A DAG is represented as : G (C1, C2, C3, C4, C5) where you can only
traverse into the next node, if there is edge present. This type of graph
is useful to represent the ordering of logical steps in a sequence.
Input: The InFile contained the Recipes (-Recipes.dat-)
----- which contains the:
- Vertices : or Recipe Nodes ("Ingredients")
- Edges : or Logical Steps for making a Recipe
Output: The OutFile containing (-OutRecipes.dat-):
------ - (A) Quick & Selection Sort - Sorts the Nodes Alphabetically
- (B) ToplogicalSort - Sorts the Logical Steps for Recipes according
to Graphical representation of the Recipe.
Data Structues: Implementation of a DAG (Graph) and a Stack for Top Sort.
--------------
Assumptions: (1) The InputFile (-Recipes.dat-) is entirely correct.
-----------
****************************************************************************}
CONST
MaxVertices = 30; {* Maximum Vertices in the Graph *}
MaxStack = 26; {* Maximum Flow Value Value for Stack *}
MaxLength = 30; {* Maximum Length of Recipe String *}
RecipeEnd = 'REND'; {* Recipe Begin *}
LastRecipe = 'FEND'; {* Recipe End *}
Blank = ' '; {* 30 spaces *}
Separator = '----------------------------------------'; {* For OutRecipes *}
TYPE
StringLength = 1..MaxLength; {* String Length *}
StringType = packed array [StringLength] of char; {* Vertex String *}
VertexType = StringType; {* Vertices Info *}
EdgeValueType = Boolean; {* Edge Values *}
Sorts = (Quick, Selec); {* Types of Sort *}
IndexType = 0 .. MaxVertices; {* IndexType *}
IndexArrayType = ARRAY [1..MaxVertices] of IndexType; {* IndexArrayType *}
{************************* Graph Type **************************************}
VertexListType = RECORD
NumVertices : Integer;
VertexList : ARRAY [1 .. MaxVertices] OF VertexType
END; (* VertexListType *)
MatrixType = ARRAY [1 .. MaxVertices, 1 .. MaxVertices]
OF EdgeValueType;
GraphType = RECORD
Vertices : VertexListType;
Edges : MatrixType
END; {* GraphType *}
{************************* Graph Type **************************************}
{************************* Stack Type **************************************}
StackElementType = VertexType;
StackType = RECORD
Elements : ARRAY [1 .. MaxStack] OF StackElementType;
Top : 0 .. MaxStack
END; (* StackType *)
{************************* Stack Type **************************************}
VAR
Graph : GraphType; {* The DAG Graph for the program *}
Stack : StackType; {* Stack for use in Topological Sort *}
RStep : StringType; {* Recipe Step *}
Recipes, {* File for Reading Vertices and Edges *}
OUTRecipes : Text; {* File for Writing Quick/Top Sort Results *}
Comparisons : Integer; {* Comparision Variable for Sorts *}
Quit : Boolean; {* Quit Program Flag *}
{***************** Create Graph ***************************}
PROCEDURE CreateGraph
(VAR Graph : GraphType);
{* Create empty graph. *}
BEGIN {** of CreateGraph **}
Graph.Vertices.NumVertices := 0
END; {** of CreateGraph **}
{***************** Add Vertex *****************************}
PROCEDURE AddVertex
(VAR Graph : GraphType;
Vertex : VertexType);
{* Add Vertex to Graph. *}
VAR
Index : Integer;
BEGIN {** of AddVertex **}
WITH Graph.Vertices DO
BEGIN
{* Put Vertex in Vertices array. *}
NumVertices := NumVertices + 1;
VertexList [NumVertices] := Vertex;
{* Initialize Edges to dummy value. *}
FOR Index := 1 TO NumVertices DO
BEGIN
Graph.Edges[NumVertices, Index] := False;
Graph.Edges[Index, NumVertices] := False
END {* FOR *}
END {* WITH *}
END; {** of AddVertex **}
{***************** Vertex Index *****************************}
FUNCTION VertexIndex
(VAR Graph : GraphType;
Vertex : VertexType) : Integer;
{* Returns index of Vertex in Graph.Vertices. Assumes that
Vertex is in the array. Graph is passed as a VAR parameter
because of its size, but is not changed by this function. *}
VAR Index : Integer;
BEGIN {** of VertexIndex **}
Index := 1;
{* Loop Invariant: Vertex is not in VertexList[1] *}
{* VertexList[Index - 1]. *}
WHILE Graph.Vertices.VertexList [Index] <> Vertex DO
Index := Index + 1;
VertexIndex := Index;
END; {** of VertexIndex **}
{******************* Weight of Graph ************************}
FUNCTION Weight
(VAR Graph : GraphType;
FromVertex : VertexType;
ToVertex : VertexType) : EdgeValueType;
{* Returns weight of edge between FromVertex and ToVertex. *}
BEGIN {** of Weight **}
Weight := Graph.Edges [VertexIndex (Graph, FromVertex),
VertexIndex (Graph, ToVertex)]
END; {** of Weight **}
{******************* Edge Exists ****************************}
FUNCTION EdgeExists
(VAR Graph : GraphType;
FromVertex : VertexType;
ToVertex : VertexType) : Boolean;
{* Determines if edge exists between FromVertex and ToVertex. *}
BEGIN {** of EdgeExists **}
EdgeExists := Graph.Edges [VertexIndex (Graph, FromVertex),
VertexIndex (Graph, ToVertex)] <> False
END; {** of EdgeExists **}
{******************* Add an Edge *****************************}
PROCEDURE AddEdge
(VAR Graph : GraphType;
FromVertex : VertexType;
ToVertex : VertexType;
Weight : EdgeValueType);
{* Add an edge in graph between FromVertex and ToVertex. *}
BEGIN {** of AddEdge **}
{* Set the slot in Edges array to True. *}
Graph.Edges [VertexIndex (Graph, FromVertex),
VertexIndex (Graph, ToVertex)] := Weight
END; {** of AddEdge **}
{******************* Get Adjaceny List **********************}
PROCEDURE GetAdjacentList
(VAR Graph : GraphType;
Vertex : VertexType;
VAR AdjList : VertexListType);
{* Create a list of vertices that Vertex is adjacent to.
Graph is passed as a VAR parameter because of its
size, but is not changed by this function. *}
VAR
FromIndex : Integer;
ToIndex : Integer;
BEGIN {** of GetAdjacentList **}
{* Find index associated with Vertex in Graph. *}
FromIndex := VertexIndex (Graph, Vertex);
WITH AdjList DO
BEGIN
NumVertices := 0;
{* Put all vertices that are adjacent into AdjList. *}
FOR ToIndex := 1 TO Graph.Vertices.NumVertices DO
IF Graph.Edges [FromIndex, ToIndex] <> False THEN
BEGIN
NumVertices := AdjList.NumVertices + 1;
VertexList [NumVertices] :=
Graph.Vertices.VertexList [ToIndex]
END {* IF *}
END {* WITH *}
END; {** of GetAdjacentList **}
{***********************************************************}
VAR {* GLOBAL *}
Visited : ARRAY [1 .. MaxVertices] OF Boolean;
{* indicates which vertices have already been visited *}
{******************* Initalize Marks ***********************}
PROCEDURE InitMarks
(VAR Graph : GraphType);
{* Initialize all marks to False. *}
VAR Index : Integer;
BEGIN {* of InitMarks *}
FOR Index := 1 TO Graph.Vertices.NumVertices DO
Visited [Index] := False
END; {* of InitMarks *}
{******************* Mark Vertex ****************************}
PROCEDURE MarkVertex
(VAR Graph : GraphType;
Vertex : VertexType);
BEGIN {* of MarkVertex *}
Visited [VertexIndex (Graph, Vertex)] := True
END; {* of MarkVertex *}
{******************* UnMark Vertex **************************}
PROCEDURE UnmarkVertex
(VAR Graph : GraphType;
Vertex : VertexType);
BEGIN {* UnmarkVertex *}
Visited [VertexIndex (Graph, Vertex)] := False
END; {* UnmarkVertex *}
{****************** Vertex Marked ***************************}
FUNCTION VertexMarked
(VAR Graph : GraphType;
Vertex : VertexType) : Boolean;
BEGIN (* of VertexMarked *)
VertexMarked := (Visited [VertexIndex (Graph, Vertex)] = True)
END; (* of VertexMarked *)
{****************** Create Stack ****************************}
PROCEDURE CreateStack
(VAR Stack : StackType);
{* Initializes Stack to empty state. *}
BEGIN {* of CreateStack *}
Stack.Top := 0
END; {* of CreateStack *}
{****************** Destroy Stack ***************************}
PROCEDURE DestroyStack
(VAR Stack : StackType);
{* Destroys all elements in stack, leaving Stack empty. *}
BEGIN {* of DestroyStack *}
Stack.Top := 0
END; {* of DestroyStack *}
{****************** Empty Stack ****************************}
FUNCTION EmptyStack
(Stack : StackType) : Boolean;
{* Returns True if Stack is empty; returns False otherwise. *}
BEGIN {* of EmptyStack *}
EmptyStack := Stack.Top = 0
END; {* of EmptyStack *}
{****************** Full Stack *****************************}
FUNCTION FullStack
(Stack : StackType) : Boolean;
{* Returns True if Stack is full; returns False otherwise. *}
BEGIN {* of FullStack *}
FullStack := Stack.Top = MaxStack
END; {* of FullStack *}
{****************** Push Element ****************************}
PROCEDURE Push
(VAR Stack : StackType;
NewElement : StackElementType);
{* Adds NewElement to the top of Stack. Assumes that the
stack is not full. *}
BEGIN {* of Push *}
Stack.Top := Stack.Top + 1;
Stack.Elements[Stack.Top] := NewElement
END; {* of Push *}
{****************** Pop Element *****************************}
PROCEDURE Pop
(VAR Stack : StackType;
VAR PoppedElement : StackElementType);
{* Removes the top element from Stack and returns its
value in PoppedElement. Assumes that the stack is
not empty. *}
BEGIN {* of Pop *}
PoppedElement := Stack.Elements[Stack.Top];
Stack.Top := Stack.Top - 1
END; {* of Pop *}
{******************* Swap for the Sorting Implementations ******************}
PROCEDURE Swap
(VAR Element1, Element2 : Integer);
{* Swap the values of Element1 and Element 2. *}
VAR Temp : IndexType;
BEGIN {* Swap *}
Temp := Element1;
Element1 := Element2;
Element2 := Temp
END; {* Swap *}
{****************** Sorting Routines (Quick and Selection) *****************}
PROCEDURE SortingAlgorithms
(Graph : GraphType);
VAR Index : IndexArrayType;
FirstV, NumV : Integer;
SortType : Sorts;
{**************** Initalize the Index *******************}
PROCEDURE InitalizeIndex
(VAR Index : IndexArrayType;
NumV : integer);
{* Sets the Index Array in Sequence before the Sorts *}
VAR Count : integer;
BEGIN {*** Of InitalizeIndex ***}
Comparisons := 0;
FOR Count := 1 to NumV DO
Index [Count] := Count;
END; {*** of InitalizeIndex ***}
{******************** Selection Sort ************************}
PROCEDURE SelectionSort
(Graph : GraphType;
VAR Index : IndexArrayType);
{* Sorts List elements in order of increasing value. *}
VAR
Current : IndexType;
Smallest : IndexType;
{**************** Nested Function Mindex **************}
FUNCTION Mindex
(Index : IndexArrayType;
StartIndex : IndexType;
EndIndex : IndexType) : IndexType;
{* Mindex = index of smallest element in the subarray *}
{* Index [StartIndex] .. Index [EndIndex]. *}
VAR
Min : IndexType; {* index of smallest element so far *}
I : IndexType; {* loop control variable *}
BEGIN (* Mindex *)
Min := StartIndex;
{* Loop Invariant: Index [Min] is the smallest element *}
{* in Index [StartIndex] .. Index [I - 1]. *}
FOR I := StartIndex + 1 TO EndIndex DO
BEGIN {** of Switch **}
Comparisons := Comparisons + 1; {* Num of Comparisons *}
WITH Graph.Vertices DO
IF VertexList [Index [I]] < VertexList [Index [Min]]
THEN Min := I;
END; {** of Switch **}
Mindex := Min;
END; (* Mindex *)
{**********************************************************}
BEGIN {*** of SelectionSort ***}
SortType := Selec; {* Set to Selection Sort *}
WITH Graph DO
BEGIN
Current := 1; {* index of first unsorted element *}
{* Loop Invariant: 1 <= Current <= Length AND the *}
{* values in Index [1] .. Index [Current - 1] are sorted *}
{* and are less than or equal to the unsorted values *}
{* in Index [Current] .. Index [Length]. *}
WHILE Current < Vertices.NumVertices DO
BEGIN
{* Find the smallest element in the unsorted part. *}
Smallest := Mindex (Index, Current, Graph.Vertices.NumVertices);
{* Swap the Current element and the smallest *}
{* element in the unsorted part of the array. *}
Swap (Index [Current], Index [Smallest]);
{* Shrink the unsorted part of the array. *}
Current := Current + 1
END {* WHILE *}
END {* WITH *}
END; {*** of SelectionSort ***}
{********************** The Quick Sort Routine *****************************}
PROCEDURE QuickSort
(Graph : GraphType;
VAR Index : IndexArrayType;
First : Integer;
Last : Integer);
VAR SplitPoint : IndexType;
{******************* Nested Procedure Split ******************}
PROCEDURE Split
(VAR Index : IndexArrayType;
First : Integer;
Last : Integer;
VAR SplitPoint : IndexType);
{* Choose SplitVal and rearrange Info so that: *}
{* Info[First]..Info[SplitPoint - 1] <= SplitVal and *}
{* Info[SplitPoint + 1]..Info[Last] > SplitVal. *}
VAR
SplitVal : VertexType; {* value on which to split *}
SaveFirst : IndexType; {* original value of First *}
BEGIN {** of Split **}
Comparisons := Comparisons + 1; {* Num of Comparisons *}
{* SplitVal is chosen from the First array slot. *}
SplitVal := Graph.Vertices.VertexList [Index [First]];
{* Set up for split loop. *}
SaveFirst := First;
First := First + 1;
{* Loop invariant: elements to the left of First are *}
{* less than or equal to SplitVal; elements to the *}
{* right of Last are greater than SplitVal. *}
REPEAT
Comparisons := Comparisons + 1; {* Num of Comparisons *}
{* Move First to the right until element > SplitVal. *}
WHILE (First < Last)
AND (Graph.Vertices.VertexList [Index [First]] <= SplitVal) DO
BEGIN
Comparisons := Comparisons + 1; {* Num of Comparisons *}
First := First + 1;
END;
{* Check end condition. *}
IF (First = Last)
AND (Graph.Vertices.VertexList [Index [First]] <= SplitVal)
THEN BEGIN
First := First + 1;
Comparisons := Comparisons + 1; {* Num of Comparisons *}
END;
{* Move Last to the left until element <= SplitVal. *}
WHILE (First <= Last)
AND (Graph.Vertices.VertexList [Index [Last]] > SplitVal) DO
BEGIN
Last := Last - 1;
Comparisons := Comparisons + 1; {* Num of Comparisons *}
END;
{* If First and Last are on the wrong side of the *}
{* split point, then swap them; update First and *}
{* Last to set up to continue splitting. *}
IF First < Last
THEN
BEGIN
Swap (Index [First], Index [Last]); {* Swap Content Values *}
First := First + 1;
Last := Last - 1;
Comparisons := Comparisons + 1; {* Num of Comparisons *}
END {* IF *}
UNTIL First > Last;
{* Set SplitPoint to place where the halves meet. *}
SplitPoint := Last;
{* Swap SplitVal with element at SplitPoint. *}
Swap (Index [SaveFirst], Index [SplitPoint])
END; {** of Split **}
{*************** Quick Sort Main Routine ********************}
BEGIN {*** of QuickSort ***}
IF First < Last {* General case *}
THEN
BEGIN
SortType := Quick; {* Set Sort to Quick *}
Comparisons := Comparisons + 1; {* Num of Comparisons *}
{* Procedure Split choses the splitting value and *}
{* rearranges the array so that: *}
{* Info[First]..Info[SplitPoint - 1] <= SplitVal *}
{* Info[SplitPoint] = SplitVal *}
{* Info[SplitPoint + 1]..Info[Last] > SplitVal *}
Split (Index, First, Last, SplitPoint) ;
{* Sort the left "half." *}
QuickSort (Graph, Index, First, SplitPoint - 1);
{* Sort the right "half." *}
QuickSort (Graph, Index, SplitPoint + 1, Last)
END {* IF First < Last *}
{* ELSE Base Case : Do nothing. *}
END; {*** of QuickSort ***}
{*************** Write Sorted Graph List ********************}
PROCEDURE WriteSortedGraphList
(TypeofSort : Sorts; NumRSteps : Integer);
VAR Sort : Integer;
BEGIN {** of WriteSortedGraphList **}
writeln (OutRecipes);
write (OutRecipes, 'Alphabetical Sort ');
CASE TypeofSort OF
Quick : Writeln (OutRecipes, '-(using QuickSort)-');
Selec : Writeln (OutRecipes, '-(using SelectionSort)-');
END;
writeln (OutRecipes, Separator);
FOR Sort := 1 TO NumRSteps DO
writeln (OutRecipes, Graph.Vertices.VertexList [Index [Sort]]);
writeln (OutRecipes);
writeln (OutRecipes, 'Number of Comparisons = ', Comparisons:1);
writeln (OutRecipes);
END; {** of WriteSortedGraphList **}
{************************************************************}
BEGIN {**** of SortingAlgorithms ****}
FirstV := 1; {* Set First and Last *}
NumV := Graph.Vertices.NumVertices;
InitalizeIndex (Index, NumV); {* Initalize Index for Sort *}
QuickSort (Graph, Index, FirstV, NumV); {* Perform the QuickSort *}
WriteSortedGraphList (SortType, NumV); {* Write the Sorted List *}
Comparisons := 0; {* Re-Initalize Comparisons *}
SelectionSort (Graph, Index); {* Perform SelectionSort *}
WriteSortedGraphList (SortType,NumV); {* Write the Sorted List *}
END; {**** of SortingAlgorithm ****}
{***************** Read the Recipe from File *******************************}
PROCEDURE ReadRecipesfromFile
(VAR Graph : GraphType);
{* This Procedure reads all the information about a Recipe from a given
file, Recipes.Dat. This includes the Recipe Steps (Nodes of DAG), and
the sequence of their execution (Edges of DAG). Termination conditions
for the file processing include checking for FEND (File End) AND REND
(Recipe End), and also Blanks (30 spaces). The program does not provide
error checking in reading the file. In otherwords, the file should be
correct in its input format. *}
{*************** Read in the Nodes **************}
PROCEDURE ReadRecipeNodes
(VAR Graph : GraphType;
VAR RecipeFile : Text);
{* This Procedure reads in the Recipe Nodes (Steps) *}
BEGIN {*** of Read a Recipe Nodes from File **}
REPEAT {* Read the Recipe *}
Readln (Recipes, RStep); {* Read the Nodes (Steps) *}
IF NOT (RStep = Blank)
AND NOT (RStep = RecipeEnd) THEN
AddVertex (Graph, RStep); {* Add Vertex (Step) *}
UNTIL (RStep = Blank) OR (RStep = RecipeEnd);
END; {*** of Read a Recipe Nodes ***}
{**************** Read the Recipe Edges *******************}
PROCEDURE ReadRecipeEdges
(VAR Graph : GraphType;
VAR RecipeFile : Text);
{* This Procedure reads in the Logical Sequence of Recipe Steps (Edges),
if there are any to add to the DAG. *}
VAR FirstStep, {* Step1 for Recipe *}
MoreSteps : VertexType; {* Step2 (or more) Steps *}
{************** Initalize the Edges ******************}
PROCEDURE InitalizeEdges
(VAR Step1, Step2 : VertexType);
BEGIN {*** of InitalizeEdges ***}
Step1 := Blank; {* Set First Step to Blank *}
Step2 := Blank; {* Set 2nd Step to Blank *}
END; {*** of InitalizeEdges ***}
{*****************************************************}
BEGIN {*** of Read Recipe Step Edges ***}
InitalizeEdges (FirstStep, MoreSteps); {* Initalize Edges *}
REPEAT
Readln (Recipes, FirstStep); {* Get the First Edge *}
Readln (Recipes, MoreSteps); {* Get the Second Edge *}
IF NOT (FirstStep = RecipeEnd) AND NOT (MoreSteps = RecipeEnd) THEN
AddEdge (Graph, FirstStep, MoreSteps, TRUE); {* Add the Edges *}
REPEAT
Readln (Recipes, MoreSteps); {* Get Another Edge *}
IF NOT (MoreSteps = Blank) AND NOT (MoreSteps = RecipeEnd) AND
NOT (MoreSteps = LastRecipe) THEN
AddEdge (Graph, FirstStep, MoreSteps, TRUE); {* Add the Edges *}
UNTIL (MoreSteps = RecipeEnd)
OR (MoreSteps = LastRecipe) OR (MoreSteps = Blank);
UNTIL (FirstStep = RecipeEnd) OR (MoreSteps = RecipeEnd) OR
(MoreSteps = LastRecipe);
IF (MoreSteps = LastRecipe) THEN Quit := TRUE; {* Quit program Flag *}
END; {*** of Read Recipe Step Edges ***}
{***************************************************************************}
BEGIN {**** of Read the Recipe from File ****}
CreateGraph (Graph); {* Create the DAG *}
ReadRecipeNodes (Graph, Recipes); {* Read all the Nodes (Recipes) *}
SortingAlgorithms (Graph); {* Perform the Two Sorts on Nodes *}
IF NOT (RStep = RecipeEnd) THEN
ReadRecipeEdges (Graph, Recipes); {* Read in Edges for Recipe *}
END; {**** of Read the Recipe from File ****}
{***************************************************************************}
PROCEDURE TheTopSort
(Graph : GraphType);
{* The Topological Sort Algorithm. This graph operation allows a method *}
{* to traverse one possible order the Recipes can follow. *}
VAR Stack : StackType;
V : VertexType;
Num : integer;
RNode : VertexType;
{*********** Write the Nodes to File **************}
PROCEDURE WriteTopSort
(VAR RecipeOutFile : Text;
RNode : VertexType);
BEGIN
writeln (OutRecipes, RNode); {* Writes node to OUT File *}
END;
{******************* Depth First Traveral ***************************}
PROCEDURE TopologicalSort
(Graph : GraphType;
FirstV : VertexType;
VAR Stack : StackType);
VAR
AdjacentList : VertexListType;
V : VertexType;
index : Integer;
BEGIN {*** of Topological Sort ***}
MarkVertex (Graph, FirstV); {* Mark each Visited *}
GetAdjacentList (Graph, FirstV, AdjacentList); {* Index into Adj List *}
FOR index := 1 to AdjacentList.NumVertices DO {* Get All Vertices *}
BEGIN {** For Loop **}
V := AdjacentList.VertexList [index]; {* Set Vertex *}
IF NOT (VertexMarked (Graph, V)) THEN {* If Not Vertex Visited *}
TopologicalSort (Graph, V, Stack); {* Do the Top Sort *}
END; {** For Loop **}
IF NOT FullStack (Stack) THEN Push (Stack, V); {* Push Vertex on Stack *}
END; {*** of Topological Sort ***}
{**************** Toplogical Sort Main Routine ************************}
BEGIN {**** of Top Sort ****}
InitMarks (Graph); {* Initialize All the DAG Marks *}
CreateStack (Stack); {* Create the Stack for TopSort *}
FOR Num := 1 TO Graph.Vertices.NumVertices DO
IF NOT (VertexMarked (Graph, Graph.Vertices.VertexList [Num]))
THEN TopologicalSort (Graph, Graph.Vertices.VertexList [Num], Stack);
writeln (OutRecipes, '-Topological Sort-');
writeln (OutRecipes, Separator);
WHILE NOT (EmptyStack (Stack)) DO {* While Stack is not Empty *}
BEGIN {** While **}
Pop (Stack, RNode); {* Pop the Node off Stack *}
WriteTopSort (OUTRecipes, RNode); {* Call the Write Procedure *}
END; {** While **}
DestroyStack (Stack); {* Destroy the Stack *}
END; {**** of Top Sort ****}
{***************************************************************************}
BEGIN {***** of Main Program *****}
{***************************}
Quit := FALSE; {* Quit Flag for Program *}
writeln (chr(27), '[2J'); {* Clear the Screen *}
writeln ('Welcome to the Graph Program.'); writeln;
Reset (Recipes); {* Reset the Recipes File *}
Rewrite (OutRecipes); {* Create OUTRecipes File *}
writeln ('--- Files Open =*=');
WHILE NOT Quit DO {* While not FEND *}
BEGIN {***** of Run the Program *****}
ReadRecipesfromFile (Graph); {* Read Recipe Data *}
TheTopSort (Graph); {* Perform Topological Sort *}
END; {***** of Run the Program *****}
Close (Recipes); {* Close the IN Recipe File *}
Close (OutRecipes); {* Close the OUT Recipe File *}
writeln ('--- Files Closed =*=');
writeln ('--- TYPE OutRecipe to View Output =*=');
writeln; writeln('Thank you for using this program.');
writeln('Goodbye.'); writeln;
readln;
END. {***** of Main Program *****}
{***************************}
|
/// <summary> 稀疏图 - 邻接表 </summary>
unit DSA.Graph.SparseWeightedGraph;
interface
uses
Classes,
SysUtils,
Rtti,
DSA.List_Stack_Queue.ArrayList,
DSA.List_Stack_Queue.LinkedList,
DSA.Interfaces.DataStructure,
DSA.Graph.Edge;
type
TSparseWeightedGraph<T> = class(TWeightGraph<T>)
private type
TEdge_T = TEdge<T>;
TEdgeType = TLinkedList<TEdge_T>;
TGraphType = TArrayList<TEdgeType>;
TArray_Edge = TArray<TEdge_T>;
var
__vertex: integer; // 节点数
__edge: integer; // 边数
__directed: boolean; // 是否为有向图
__graphData: TGraphType; // 图的具体数据
public
constructor Create(n: integer; directed: boolean);
destructor Destroy; override;
/// <summary> 向图中添加一个边 </summary>
procedure AddEdge(v, w: integer; weight: T); override;
/// <summary> 验证图中是否有从v到w的边 </summary>
function HasEdge(v, w: integer): boolean; override;
/// <summary> 返回节点个数 </summary>
function Vertex: integer; override;
/// <summary> 返回边的个数 </summary>
function Edge: integer; override;
/// <summary> 返回图中一个顶点的所有邻边 </summary>
function AdjIterator(v: integer): TArray_Edge; override;
procedure Show; override;
end;
procedure Main;
implementation
uses
DSA.Graph.DenseWeightedGraph,
DSA.Utils;
type
TDenseWeightedGraph_dbl = TDenseWeightedGraph<double>;
TSparseWeightedGraph_dbl = TSparseWeightedGraph<double>;
TWeightGraph_dbl = TWeightGraph<double>;
TReadGraphWeight_dbl = TReadGraphWeight<double>;
procedure Main;
var
g: TWeightGraph_dbl;
FileName: string;
begin
FileName := WEIGHT_GRAPH_FILE_NAME_1;
g := TDenseWeightedGraph_dbl.Create(8, false);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + FileName);
WriteLn('test G1 in Sparse Weighted Graph:');
g.Show;
TDSAUtils.DrawLine;
g := TSparseWeightedGraph_dbl.Create(8, false);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + FileName);
WriteLn('test G1 in Sparse Weighted Graph:');
g.Show;
end;
{ TSparseWeightedGraph<T> }
constructor TSparseWeightedGraph<T>.Create(n: integer; directed: boolean);
var
i: integer;
begin
Assert(n > 0);
__vertex := n;
__edge := 0;
__directed := directed;
__graphData := TGraphType.Create(n);
for i := 0 to n - 1 do
__graphData.AddLast(TEdgeType.Create);
end;
procedure TSparseWeightedGraph<T>.AddEdge(v, w: integer; weight: T);
begin
Assert((v >= 0) and (v < __vertex));
Assert((w >= 0) and (w < __vertex));
__graphData[v].AddLast(TEdge_T.Create(v, w, weight));
if (v <> w) and (__directed = false) then
__graphData[w].AddLast(TEdge_T.Create(w, v, weight));
Inc(__edge);
end;
function TSparseWeightedGraph<T>.AdjIterator(v: integer): TArray_Edge;
var
i: integer;
ret: TArray_Edge;
begin
for i := 0 to __graphData[v].GetSize - 1 do
begin
SetLength(ret, i + 1);
ret[i] := __graphData[v][i];
end;
Result := ret;
end;
destructor TSparseWeightedGraph<T>.Destroy;
var
i: integer;
begin
for i := 0 to Pred(__graphData.GetSize) do
begin
__graphData[i].Free;
end;
FreeAndNil(__graphData);
inherited Destroy;
end;
function TSparseWeightedGraph<T>.Edge: integer;
begin
Result := __edge;
end;
function TSparseWeightedGraph<T>.HasEdge(v, w: integer): boolean;
var
i: integer;
begin
Assert((v >= 0) and (v < __vertex));
Assert((w >= 0) and (w < __vertex));
for i := 0 to __graphData[v].GetSize - 1 do
begin
if (__graphData[v].Get(i).OtherVertex(v) = w) then
begin
Result := True;
Exit;
end;
end;
Result := false;
end;
procedure TSparseWeightedGraph<T>.Show;
var
v: integer;
e: TEdge_T;
value: TValue;
begin
for v := 0 to __graphData.GetSize - 1 do
begin
write('Vertex ', v, ' : ', #9);
for e in AdjIterator(v) do
begin
value := TValue.From<T>(e.weight);
write('( to:', e.VertexB, ' wt:', value.ToString, ')'#9);
end;
WriteLn;
end;
end;
function TSparseWeightedGraph<T>.Vertex: integer;
begin
Result := __vertex;
end;
end.
|
unit Odontologia.Vistas.Home;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Odontologia.Vista.Estilos;
type
TPagHome = class(TForm)
pnlMain: TPanel;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PagHome: TPagHome;
implementation
{$R *.dfm}
procedure TPagHome.FormCreate(Sender: TObject);
begin
pnlMain.color := COLOR_BACKGROUND;
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// 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 ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
unit fTextStats;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uMultiLanguage, fEditor, SynEdit, ComCtrls, StdCtrls,
SynEditHighlighter, JclFileUtils, Clipbrd, uCommon, uSafeRegistry,
SynEditTypes;
type
TfmTextStats = class(TForm)
lvStats: TListView;
btnClose: TButton;
btnCopy: TButton;
procedure btnCopyClick(Sender: TObject);
private
fEditor: TfmEditor;
fStrings: TStrings;
procedure AddItem(ACaption, Value: string);
procedure DoStats;
procedure LoadSettings;
procedure SaveSettings;
public
constructor Create(AOwner: TComponent; Editor: TfmEditor); reintroduce;
destructor Destroy; override;
end;
procedure CreateTextStatsDialog(Editor: TfmEditor);
implementation
{$R *.dfm}
uses
fMain;
////////////////////////////////////////////////////////////////////////////////////////////
// Static functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure CreateTextStatsDialog(Editor: TfmEditor);
begin
with TfmTextStats.Create(fmMain, Editor) do
try
ShowModal;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmTextStats.LoadSettings;
begin
with TSafeRegistry.Create do
try
if OpenKey(CONTEXT_REG_KEY+Name, TRUE) then begin
ReadListViewWidths(lvStats);
end;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmTextStats.SaveSettings;
begin
with TSafeRegistry.Create do
try
if OpenKey(CONTEXT_REG_KEY+Name, TRUE) then begin
WriteListViewWidths(lvStats);
end;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmTextStats.AddItem(ACaption, Value: string);
begin
with lvStats.Items.Add do begin
Caption:=ACaption;
SubItems.Add(Value);
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmTextStats.DoStats;
var
i, ii: integer;
s: string;
len: integer;
CharCount: integer;
NonSpaceCharCount: integer;
NonEmptyLines: integer;
CommentedCharCount: integer;
dt: TDateTime;
function DoCountCommentedChars: integer;
var
HL: TSynCustomHighlighter;
X, Y: integer;
token: string;
attr: TSynHighlighterAttributes;
len: integer;
begin
result:=0;
HL:=fEditor.memo.Highlighter;
if Assigned(HL) and (HL<>fmMain.hlTxt) then begin
for Y:=0 to fStrings.Count-1 do begin
X:=0;
while (X<Length(fStrings[Y])) do begin
if fEditor.memo.GetHighlighterAttriAtRowCol(BufferCoord(X+1, Y+1), token, attr) then begin
len:=Length(token);
if (attr=HL.CommentAttribute) then begin
inc(result, len);
inc(X, len);
end;
inc(X, len);
end else
BREAK;
end;
end;
end;
end;
begin
NonEmptyLines:=0;
CharCount:=0;
NonSpaceCharCount:=0;
for i:=0 to fStrings.Count-1 do begin
s:=fStrings[i];
len:=Length(s);
if (Length(Trim(s))>0) then
inc(NonEmptyLines);
inc(CharCount, len);
for ii:=1 to len do
if (s[ii]>#32) then
inc(NonSpaceCharCount);
end;
CommentedCharCount:=DoCountCommentedChars;
if not fEditor.NewFile then begin
AddItem(mlStr(ML_STATS_FILENAME, 'File name'), fEditor.FileName);
if GetFileCreation(fEditor.FileName, dt) then
AddItem(mlStr(ML_STATS_CREATED, 'Created'), DateTimeToStr(dt));
if GetFileLastWrite(fEditor.FileName, dt) then
AddItem(mlStr(ML_STATS_MODIFIED, 'Modified'), DateTimeToStr(dt));
end;
AddItem(mlStr(ML_STATS_LINES, 'Lines'), IntToStr(fStrings.Count));
AddItem(mlStr(ML_STATS_NONEMPTY_LINES, 'Non-empty lines'), IntToStr(NonEmptyLines));
AddItem(mlStr(ML_STATS_CHARS, 'Characters'), IntToStr(CharCount));
AddItem(mlStr(ML_STATS_CHARS_WITHOUT_BLANKS, 'Characters without blanks'), IntToStr(NonSpaceCharCount));
AddItem(mlStr(ML_STATS_COMMENTED_CHARS, 'Commented char count'), IntToStr(CommentedCharCount));
if (CharCount>0) then
AddItem(mlStr(ML_STATS_COMMENTED_CHARS_PERCENT, 'Commented char count percent'), FormatFloat('0.#', CommentedCharCount/CharCount*100));
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Buttons
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmTextStats.btnCopyClick(Sender: TObject);
var
buff: PChar;
str: TStringList;
i: integer;
Item: TListItem;
begin
str:=TStringList.Create;
for i:=0 to lvStats.Items.Count-1 do begin
Item:=lvStats.Items[i];
str.Add(Format('%s'#09'%s', [Item.Caption, Item.SubItems[0]]));
end;
if (str.Count>0) then begin
buff:=str.GetText;
Clipboard.SetTextBuf(buff);
StrDispose(buff);
end;
str.Free;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Static functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TfmTextStats.Create(AOwner: TComponent; Editor: TfmEditor);
begin
fEditor:=Editor;
fStrings:=Editor.memo.Lines;
inherited Create(AOwner);
lvStats.DoubleBuffered:=TRUE;
LoadSettings;
mlApplyLanguageToForm(SELF, Name);
Screen.Cursor:=crHourGlass;
try
DoStats;
finally
Screen.Cursor:=crDefault;
end;
end;
//------------------------------------------------------------------------------------------
destructor TfmTextStats.Destroy;
begin
SaveSettings;
inherited;
end;
//------------------------------------------------------------------------------------------
end.
|
unit DSA.Tree.RBTree;
interface
uses
System.SysUtils,
System.Rtti,
DSA.List_Stack_Queue.ArrayList,
DSA.Interfaces.DataStructure,
DSA.Interfaces.Comparer,
DSA.Utils;
type
TRBTree<K, V> = class
private type
TNode = class
public
key: K;
Value: V;
Left, Right: TNode;
Color: Boolean;
constructor Create(newkey: K; newValue: V);
end;
TPtrV = TPtr_V<V>;
TArrayList_K = TArrayList<K>;
const
RED = True;
BLACK = False;
var
__root: TNode;
__size: integer;
__comparer: IComparer<K>;
/// <summary>
/// 向以node为根的红黑树中插入元素(key, value),递归算法.
/// 返回插入新节点后红黑树的根
/// </summary>
function __add(node: TNode; key: K; Value: V): TNode;
function __getNode(node: TNode; key: K): TNode;
function __isRBTree(node: TNode; const blackCount: integer;
count: integer): Boolean;
function __remove(node: TNode; key: K): TNode;
function __minimum(node: TNode): TNode;
procedure __inOrder(node: TNode; list: TArrayList_K);
/// <summary> 判断节点node的颜色 </summary>
function __isRed(node: TNode): Boolean;
/// <summary> 颜色翻转 </summary>
procedure __flipColors(node: TNode);
/// <summary>
/// 对节点y进行向右旋转操作,返回旋转后新的根节点x
/// </summary>
/// <remarks>
/// <code>
/// 右旋转操作:
/// <para> node x </para>
/// <para> / \ 右旋转 / \ </para>
/// <para> x T2 -------> y node </para>
/// <para> / \ / \ </para>
/// <para> y T1 T1 T2 </para>
/// </code>
/// </remarks>
function __rightRotate(node: TNode): TNode;
/// <summary>
/// 向左旋转
/// </summary>
/// /// <remarks>
/// <code>
/// 左旋转操作:
/// <para> node x </para>
/// <para> / \ 左旋转 / \ </para>
/// <para> T1 x ---------> node T3 </para>
/// <para> / \ / \ </para>
/// <para> T2 T3 T1 T2 </para>
/// </code>
/// </remarks>
function __leftRotate(node: TNode): TNode;
public
constructor Create();
function Contains(key: K): Boolean;
/// <summary> 判断该二叉树是否是一棵二分搜索树 </summary>
function IsBST: Boolean;
function Get(key: K): TPtrV;
function GetSize: integer;
function IsEmpty: Boolean;
function IsRBTree: Boolean;
function Remove(key: K): TPtrV;
procedure Add(key: K; Value: V);
procedure Set_(key: K; newValue: V);
function KeySets: TArrayList_K;
end;
procedure Main;
implementation
type
TRBTree_str_int = TRBTree<string, integer>;
procedure Main;
var
words: TArrayList_str;
rbt: TRBTree_str_int;
i: integer;
begin
words := TArrayList_str.Create();
if TDsaUtils.ReadFile(FILE_PATH + A_File_Name, words) then
begin
Writeln('Total words: ', words.GetSize);
end;
rbt := TRBTree_str_int.Create;
for i := 0 to words.GetSize - 1 do
begin
if rbt.Contains(words[i]) then
rbt.Set_(words[i], rbt.Get(words[i]).PValue^ + 1)
else
rbt.Add(words[i], 1);
end;
Writeln('Total different words: ', rbt.GetSize);
TDsaUtils.DrawLine;
Writeln('Frequency of pride: ', rbt.Get('pride').PValue^);
Writeln('Frequency of prejudice: ', rbt.Get('prejudice').PValue^);
Writeln('IsBST: ', rbt.IsBST);
Writeln('IsRBTree: ', rbt.IsRBTree);
end;
{ TRBTree<K, V>.TNode }
constructor TRBTree<K, V>.TNode.Create(newkey: K; newValue: V);
begin
Self.key := newkey;
Self.Value := newValue;
Left := nil;
Right := nil;
Color := RED;
end;
{ TRBTree<K, V> }
procedure TRBTree<K, V>.Add(key: K; Value: V);
begin
__root := __add(__root, key, Value);
__root.Color := BLACK; // 最终根节点为黑色节点
end;
function TRBTree<K, V>.Contains(key: K): Boolean;
begin
Result := __getNode(__root, key) <> nil;
end;
constructor TRBTree<K, V>.Create;
begin
inherited;
__comparer := TComparer<K>.Default;
end;
procedure TRBTree<K, V>.__flipColors(node: TNode);
begin
node.Color := RED;
node.Left.Color := BLACK;
node.Right.Color := BLACK;
end;
function TRBTree<K, V>.Get(key: K): TPtrV;
var
node: TNode;
begin
node := __getNode(__root, key);
if node = nil then
Result.PValue := nil
else
Result.PValue := @node.Value;
end;
function TRBTree<K, V>.GetSize: integer;
begin
Result := __size;
end;
function TRBTree<K, V>.IsBST: Boolean;
var
list: TArrayList_K;
i: integer;
bool: Boolean;
begin
bool := True;
list := TArrayList_K.Create();
__inOrder(__root, list);
for i := 1 to list.GetSize - 1 do
if __comparer.Compare(list.Get(i - 1), list.Get(i)) > 0 then
bool := False
else
bool := True;
Result := bool;
end;
function TRBTree<K, V>.IsEmpty: Boolean;
begin
Result := __size = 0;
end;
function TRBTree<K, V>.IsRBTree: Boolean;
var
cur: TNode;
blackCount: integer;
begin
// 1、红黑树所有的节点都有颜色(红或黑)
// 2、红黑树的根结点是黑色的
// 3、红黑树的两个红色节点不能相连
// 4、红黑树的每一条链的黑节点的个数相同
// 5、所有空的节点都是黑色的
if __root = nil then
begin
Result := True;
Exit;
end;
if __isRed(__root) then // 违反 2.红黑树的根结点是黑色的
begin
Result := False;
Exit;
end;
// 统计单一链上黑色结点的个数 , 这里以最左边的那一条链统计
blackCount := 0;
cur := __root;
while cur <> nil do
begin
if cur.Color = BLACK then
inc(blackCount);
cur := cur.Left;
end;
// 验证性质 4.每条链上的黑色结点都相等”,验证性质 3.红色结点不能相连
Result := __isRBTree(__root, blackCount, 0)
end;
function TRBTree<K, V>.KeySets: TArrayList_K;
var
list: TArrayList_K;
begin
list := TArrayList_K.Create;
__inOrder(__root, list);
Result := list;
end;
function TRBTree<K, V>.Remove(key: K): TPtrV;
var
node: TNode;
begin
node := __getNode(__root, key);
if node = nil then
begin
Result.PValue := nil;
Exit;
end;
__root := __remove(__root, key);
Result.PValue := @node.Value;
end;
procedure TRBTree<K, V>.Set_(key: K; newValue: V);
var
node: TNode;
Value: TValue;
s: string;
begin
node := __getNode(__root, key);
if node = nil then
begin
TValue.Make(@key, TypeInfo(K), Value);
s := Value.ToString;
raise Exception.Create(s + ' doesn''t exist!');
end
else
node.Value := newValue;
end;
function TRBTree<K, V>.__add(node: TNode; key: K; Value: V): TNode;
var
bool: integer;
begin
if node = nil then
begin
inc(__size);
Result := TNode.Create(key, Value);
Exit;
end;
bool := __comparer.Compare(key, node.key);
if bool < 0 then
node.Left := __add(node.Left, key, Value)
else if bool > 0 then
node.Right := __add(node.Right, key, Value)
else
node.Value := Value;
if __isRed(node.Right) and not(__isRed(node.Left)) then
node := __leftRotate(node);
if (__isRed(node.Left)) and __isRed(node.Left.Left) then
node := __rightRotate(node);
if __isRed(node.Left) and __isRed(node.Right) then
__flipColors(node);
Result := node;
end;
function TRBTree<K, V>.__getNode(node: TNode; key: K): TNode;
var
bool: integer;
begin
if node = nil then
Exit(nil);
bool := __comparer.Compare(key, node.key);
if bool < 0 then
Result := __getNode(node.Left, key)
else if bool > 0 then
Result := __getNode(node.Right, key)
else
Result := node;
end;
procedure TRBTree<K, V>.__inOrder(node: TNode; list: TArrayList_K);
begin
if node = nil then
Exit;
__inOrder(node.Left, list);
list.AddLast(node.key);
__inOrder(node.Right, list);
end;
function TRBTree<K, V>.__isRBTree(node: TNode; const blackCount: integer;
count: integer): Boolean;
begin
if node = nil then
begin
if count = blackCount then
Result := True
else
Result := False;
Exit;
end;
if (node.Color = BLACK) then
inc(count);
//违反性质 3.红色结点不能相连
if (node.Left <> nil) and (__isRed(node) and __isRed(node.Left)) then
begin
Result := False;
Exit;
end;
if (node.Right <> nil) and (__isRed(node) and __isRed(node.Right)) then
begin
Result := False;
Exit;
end;
Result := __isRBTree(node.Left, blackCount, count) and
__isRBTree(node.Right, blackCount, count);
end;
function TRBTree<K, V>.__isRed(node: TNode): Boolean;
begin
if node = nil then
begin
Result := BLACK;
Exit;
end;
Result := node.Color;
end;
function TRBTree<K, V>.__leftRotate(node: TNode): TNode;
var
x: TNode;
begin
x := node.Right;
// 左旋转
node.Right := x.Left;
x.Left := node;
x.Color := node.Color;
node.Color := RED;
Result := x;
end;
function TRBTree<K, V>.__minimum(node: TNode): TNode;
begin
if node.Left = nil then
begin
Result := node;
Exit;
end;
Result := __minimum(node.Left);
end;
function TRBTree<K, V>.__remove(node: TNode; key: K): TNode;
var
leftNode, rightNode, succesorNode, minNode, retNode: TNode;
bool: integer;
begin
leftNode := nil;
rightNode := nil;
succesorNode := nil;
if node = nil then
begin
Result := nil;
Exit;
end;
bool := __comparer.Compare(key, node.key);
if bool < 0 then
begin
node.Left := __remove(node.Left, key);
retNode := node;
end
else if bool > 0 then
begin
node.Right := __remove(node.Right, key);
retNode := node;
end
else // e = node.e
begin
if node.Left = nil then
begin
rightNode := node.Right;
FreeAndNil(node);
Dec(__size);
retNode := rightNode;
end
else if node.Right = nil then
begin
leftNode := node.Left;
FreeAndNil(node);
Dec(__size);
retNode := leftNode;
end
else
begin
// 待删除节点左右子树均不空的情况
// 找到比待删除节点大的最小节点,即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
minNode := __minimum(node.Right);
succesorNode := TNode.Create(minNode.key, minNode.Value);
succesorNode.Right := __remove(node.Right, succesorNode.key);
succesorNode.Left := node.Left;
FreeAndNil(node);
retNode := succesorNode;
end;
end;
// todo: 2019-08-29 删除代没有完成.
Result := retNode;
end;
function TRBTree<K, V>.__rightRotate(node: TNode): TNode;
var
x: TNode;
begin
x := node.Left;
// 右旋转
node.Left := x.Right;
x.Right := node;
x.Color := node.Color;
node.Color := RED;
Result := x;
end;
end.
|
{******************************************************************************}
{ }
{ Project JEDI Code Library (JCL) extension }
{ }
{ The contents of this file are subject to the Mozilla Public License Version }
{ 1.0 (the "License"); you may not use this file except in compliance with the }
{ License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, }
{ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for }
{ the specific language governing rights and limitations under the License. }
{ }
{ The Original Code is JclDebugResult.pas. }
{ }
{ The Initial Developer of the Original Code is documented in the accompanying }
{ help file JCL.chm. Portions created by these individuals are Copyright (C) }
{ of these individuals. }
{ }
{ Last modified: March 17, 2002 }
{ }
{******************************************************************************}
unit JclDebugIdeResult;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ImgList;
type
TJclDebugResultForm = class(TForm)
OkBtn: TButton;
ResultListView: TListView;
ImageList1: TImageList;
procedure FormResize(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
procedure CopyReportToClipboard;
public
{ Public declarations }
end;
var
JclDebugResultForm: TJclDebugResultForm;
implementation
{$R *.dfm}
uses
ClipBrd, Math,
JclStrings;
procedure ListViewToStrings(ListView: TListView; Strings: TStrings;
SelectedOnly: Boolean = False; Headers: Boolean = True);
var
R, C: Integer;
ColWidths: array of Word;
S: string;
procedure AddLine;
begin
Strings.Add(TrimRight(S));
end;
function MakeCellStr(const Text: String; Index: Integer): String;
begin
with ListView.Columns[Index] do
if Alignment = taLeftJustify then
Result := StrPadRight(Text, ColWidths[Index] + 1)
else
Result := StrPadLeft(Text, ColWidths[Index]) + ' ';
end;
begin
with ListView do
begin
SetLength(ColWidths, Columns.Count);
if Headers then
for C := 0 to Columns.Count - 1 do
ColWidths[C] := Length(Trim(Columns[C].Caption));
for R := 0 to Items.Count - 1 do
if not SelectedOnly or Items[R].Selected then
begin
ColWidths[0] := Max(ColWidths[0], Length(Trim(Items[R].Caption)));
for C := 0 to Items[R].SubItems.Count - 1 do
ColWidths[C + 1] := Max(ColWidths[C + 1], Length(Trim(Items[R].SubItems[C])));
end;
Strings.BeginUpdate;
try
if Headers then
with Columns do
begin
S := '';
for C := 0 to Count - 1 do
S := S + MakeCellStr(Items[C].Caption, C);
AddLine;
S := '';
for C := 0 to Count - 1 do
S := S + StringOfChar('-', ColWidths[C]) + ' ';
AddLine;
end;
for R := 0 to Items.Count - 1 do
if not SelectedOnly or Items[R].Selected then
with Items[R] do
begin
S := MakeCellStr(Caption, 0);
for C := 0 to Min(SubItems.Count, Columns.Count - 1) - 1 do
S := S + MakeCellStr(SubItems[C], C + 1);
AddLine;
end;
finally
Strings.EndUpdate;
end;
end;
end;
{ TJclDebugResultForm }
procedure TJclDebugResultForm.CopyReportToClipboard;
var
SL: TStringList;
begin
SL := TStringList.Create;
try
ListViewToStrings(ResultListView, SL);
Clipboard.AsText := SL.Text;
finally
SL.Free;
end;
end;
procedure TJclDebugResultForm.FormResize(Sender: TObject);
begin
OkBtn.Left := ClientWidth div 2 - OkBtn.Width div 2;
end;
procedure TJclDebugResultForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Key = Ord('C')) then
begin
CopyReportToClipboard;
MessageBeep(MB_OK);
end;
end;
end.
|
unit MVVM.Attributes;
interface
uses
MVVM.Types,
MVVM.Interfaces.Architectural;
type
// Attributes
EInstanceType = (itSingleton, itNewInstance);
TMVVMCustomAttribute = class(TCustomAttribute)
end;
// [ViewForViewModel('EDITOR_USUARIOS', IMyViewModel1, 'WindowsDesktop']
View_For_ViewModel = class(TMVVMCustomAttribute)
strict private
FViewAlias: string;
FVMInterface: TGUID;
FPlatform: string;
public
constructor Create(const AViewALias: string; AVMInterfaceID: TGUID; const APlatform: String);
property ViewAlias: String read FViewAlias;
property VMInterface: TGUID read FVMInterface;
property Platform: String read FPlatform;
end;
// [ViewModel_Implements(ICSVFile_ViewModel, AsSingleton)]
ViewModel_Implements = class(TMVVMCustomAttribute)
strict private
FVMInterface: TGUID;
FInstanceType: EInstanceType;
public
constructor Create(AVMInterfaceID: TGUID; const AInstanceType: EInstanceType = EInstanceType.itNewInstance);
property VMInterface: TGUID read FVMInterface;
property InstanceType: EInstanceType read FInstanceType;
end;
// Commands
// - Action Member
ActionMember = class(TMVVMCustomAttribute)
private
FName: String;
FCaption: String;
FMemberType: EActionMemberType;
public
constructor Create(const AName: String; const AMemberType: EActionMemberType; const ACaption: String = ''); overload;
constructor Create(const AName: String; const AMemberType: EActionMemberType); overload;
constructor Create(const AMemberType: EActionMemberType; const ACaption: String = ''); overload;
property Name: String read FName;
property Caption: String read FCaption;
property MemberType: EActionMemberType read FMemberType;
end;
// - Standard command
Command = class(TMVVMCustomAttribute)
private
FExecuteName: String;
FCanExecuteName: String;
FParamsName: String;
public
constructor Create(const AExecuteName: string; const ACanExecuteName: String = ''); overload;
constructor Create(const AExecuteName, ACanExecuteName: String; const AParamsName: string); overload;
property ExecuteName: String read FExecuteName;
property CanExecuteName: String read FCanExecuteName;
property ParamsName: String read FParamsName;
end;
implementation
{ ViewForVM }
constructor View_For_ViewModel.Create(const AViewALias: string; AVMInterfaceID: TGUID; const APlatform: String);
begin
FVMInterface := AVMInterfaceID;
FViewAlias := AViewALias;
FPlatform := APlatform;
end;
{ ViewModel_Implements }
constructor ViewModel_Implements.Create(AVMInterfaceID: TGUID; const AInstanceType: EInstanceType);
begin
FVMInterface := AVMInterfaceID;
FInstanceType := AInstanceType;
end;
{ ActionMember }
constructor ActionMember.Create(const AName: String; const AMemberType: EActionMemberType);
begin
FName := AName;
FCaption:= '';
FMemberType := AMemberType;
end;
constructor ActionMember.Create(const AName: String; const AMemberType: EActionMemberType; const ACaption: String = '');
begin
FName := AName;
FCaption:= ACaption;
FMemberType := AMemberType;
end;
constructor ActionMember.Create(const AMemberType: EActionMemberType; const ACaption: String);
begin
FName := '';
FCaption:= ACaption;
FMemberType := AMemberType;
end;
{ Command }
constructor Command.Create(const AExecuteName, ACanExecuteName, AParamsName: string);
begin
FExecuteName := AExecuteName;
FCanExecuteName:= ACanExecuteName;
FParamsName:= AParamsName;
end;
constructor Command.Create(const AExecuteName, ACanExecuteName: String);
begin
FExecuteName := AExecuteName;
FCanExecuteName:= ACanExecuteName;
FParamsName:= '';
end;
end.
|
// Sorting demo
program Sort;
const
DataLength = 60;
type
TNumber = Integer;
TData = array [1..DataLength] of TNumber;
PData = ^TData;
procedure Swap(var x, y: TNumber);
var
buf: TNumber;
begin
buf := x;
x := y;
y := buf;
end;
function Partition(var data: TData; len: Integer): Integer;
var
pivot: TNumber;
pivotIndex, i: Integer;
begin
pivot := data[len];
pivotIndex := 1;
for i := 1 to len do
if data[i] < pivot then
begin
Swap(data[pivotIndex], data[i]);
Inc(pivotIndex);
end; // if
Swap(data[len], data[pivotIndex]);
Result := pivotIndex;
end;
procedure QuickSort(var data: TData; len: Integer);
var
pivotIndex: Integer;
dataShiftedPtr: PData;
begin
if len > 1 then
begin
pivotIndex := Partition(data, len);
dataShiftedPtr := PData(@data[pivotIndex + 1]);
QuickSort(data, pivotIndex - 1 );
QuickSort(dataShiftedPtr^, len - pivotIndex);
end; // if
end;
procedure BubbleSort(var data: TData; len: Integer);
var
changed: Boolean;
i: Integer;
begin
repeat
changed := FALSE;
for i := 1 to len - 1 do
if data[i + 1] < data[i] then
begin
Swap(data[i + 1], data[i]);
changed := TRUE;
end;
until not changed;
end;
procedure SelectionSort(var data: TData; len: Integer);
var
i, j, extrIndex: Integer;
extr: TNumber;
begin
for i := 1 to len do
begin
extr := data[i];
extrIndex := i;
for j := i + 1 to len do
if data[j] < extr then
begin
extr := data[j];
extrIndex := j;
end;
Swap(data[i], data[extrIndex]);
end; // for
end;
var
RandomData: TData;
i: Integer;
Method: Char;
begin
WriteLn;
WriteLn('Sorting demo');
WriteLn;
WriteLn('Initial array: ');
WriteLn;
Randomize;
for i := 1 to DataLength do
begin
RandomData[i] := Round((Random - 0.5) * 1000000);
Write(RandomData[i]);
if i mod 4 <> 0 then Write(#9) else WriteLn;
end;
WriteLn;
WriteLn;
Write('Select method (Q - quick, B - bubble, S - selection): '); Read(Method);
WriteLn(Method);
WriteLn;
case Method of
'Q', 'q':
begin
WriteLn('Quick sorting');
QuickSort(RandomData, DataLength);
end;
'B', 'b':
begin
WriteLn('Bubble sorting');
BubbleSort(RandomData, DataLength);
end;
'S', 's':
begin
WriteLn('Selection sorting');
SelectionSort(RandomData, DataLength);
end
else
WriteLn('Sorting method is not selected.');
ReadLn;
Halt;
end;
WriteLn;
WriteLn('Sorted array: ');
WriteLn;
for i := 1 to DataLength do
begin
Write(RandomData[i]);
if i mod 4 <> 0 then Write(#9) else WriteLn;
end;
WriteLn;
WriteLn;
WriteLn('Done.');
ReadLn;
end.
|
namespace RemObjects.Elements.System;
interface
uses
java.util;
type
Tuple1<T1> = public class
public
constructor(aItem1: T1);
property Item1: T1; readonly;
method hashCode: Integer; override;
method &equals(arg1: Object): Boolean; override;
end;
Tuple2<T1, T2> = public class
public
constructor(aItem1: T1; aItem2: T2);
property Item1: T1; readonly;
property Item2: T2; readonly;
method hashCode: Integer; override;
method &equals(arg1: Object): Boolean; override;
end;
Tuple3<T1, T2, T3> = public class
public
constructor(aItem1: T1; aItem2: T2; aItem3: T3);
property Item1: T1; readonly;
property Item2: T2; readonly;
property Item3: T3; readonly;
method hashCode: Integer; override;
method &equals(arg1: Object): Boolean; override;
end;
Tuple4<T1, T2, T3, T4> = public class
public
constructor(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4);
property Item1: T1; readonly;
property Item2: T2; readonly;
property Item3: T3; readonly;
property Item4: T4; readonly;
method hashCode: Integer; override;
method &equals(arg1: Object): Boolean; override;
end;
Tuple5<T1, T2, T3, T4, T5> = public class
public
constructor(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5);
property Item1: T1; readonly;
property Item2: T2; readonly;
property Item3: T3; readonly;
property Item4: T4; readonly;
property Item5: T5; readonly;
method hashCode: Integer; override;
method &equals(arg1: Object): Boolean; override;
end;
Tuple6<T1, T2, T3, T4, T5, T6> = public class
public
constructor(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6);
property Item1: T1; readonly;
property Item2: T2; readonly;
property Item3: T3; readonly;
property Item4: T4; readonly;
property Item5: T5; readonly;
property Item6: T6; readonly;
method hashCode: Integer; override;
method &equals(arg1: Object): Boolean; override;
end;
Tuple7<T1, T2, T3, T4, T5, T6, T7> = public class
public
constructor(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6; aItem7: T7);
property Item1: T1; readonly;
property Item2: T2; readonly;
property Item3: T3; readonly;
property Item4: T4; readonly;
property Item5: T5; readonly;
property Item6: T6; readonly;
property Item7: T7; readonly;
method hashCode: Integer; override;
method &equals(arg1: Object): Boolean; override;
end;
Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> = public class
public
constructor(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6; aItem7: T7; aItem8: T8);
property Item1: T1; readonly;
property Item2: T2; readonly;
property Item3: T3; readonly;
property Item4: T4; readonly;
property Item5: T5; readonly;
property Item6: T6; readonly;
property Item7: T7; readonly;
property Item8: T8; readonly;
method hashCode: Integer; override;
method &equals(arg1: Object): Boolean; override;
end;
Tuple = public static class
assembly
class method R3(i: Integer): Integer;
public
class method &New<T1>(aItem1: T1): Tuple1<T1>;
class method &New<T1, T2>(aItem1: T1; aItem2: T2): Tuple2<T1, T2>;
class method &New<T1, T2, T3>(aItem1: T1; aItem2: T2; aItem3: T3): Tuple3<T1, T2, T3>;
class method &New<T1, T2, T3, T4>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4): Tuple4<T1, T2, T3, T4>;
class method &New<T1, T2, T3, T4, T5>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5): Tuple5<T1, T2, T3, T4, T5>;
class method &New<T1, T2, T3, T4, T5, T6>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6): Tuple6<T1, T2, T3, T4, T5, T6>;
class method &New<T1, T2, T3, T4, T5, T6, T7>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6; aItem7: T7): Tuple7<T1, T2, T3, T4, T5, T6, T7>;
class method &New<T1, T2, T3, T4, T5, T6, T7, T8>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6; aItem7: T7; aItem8: T8): Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>;
end;
implementation
constructor Tuple1<T1>(aItem1: T1);
begin
Item1 := aItem1;
end;
method Tuple1<T1>.hashCode: Integer;
begin
if Item1 = nil then exit 0;
exit Item1.hashCode;
end;
method Tuple1<T1>.&equals(arg1: Object): Boolean;
begin
var lTuple := Tuple1(arg1);
exit assigned(lTuple) and (lTuple.Item1 = Item1);
end;
constructor Tuple2<T1, T2>(aItem1: T1; aItem2: T2);
begin
Item1 := aItem1;
Item2 := aItem2;
end;
method Tuple2<T1, T2>.hashCode: Integer;
begin
result := 0;
if Item1 <> nil then result := Tuple.R3(result) xor Item1.hashCode;
if Item2 <> nil then result := Tuple.R3(result) xor Item2.hashCode;
end;
method Tuple2<T1, T2>.&equals(arg1: Object): Boolean;
begin
var lTuple := Tuple2(arg1);
exit assigned(lTuple) and (lTuple.Item1 = Item1) and (lTuple.Item2 = Item2);
end;
constructor Tuple3<T1, T2, T3>(aItem1: T1; aItem2: T2; aItem3: T3);
begin
Item1 := aItem1;
Item2 := aItem2;
Item3 := aItem3;
end;
method Tuple3<T1, T2, T3>.hashCode: Integer;
begin
result := 0;
if Item1 <> nil then result := Tuple.R3(result) xor Item1.hashCode;
if Item2 <> nil then result := Tuple.R3(result) xor Item2.hashCode;
if Item3 <> nil then result := Tuple.R3(result) xor Item3.hashCode;
end;
method Tuple3<T1, T2, T3>.&equals(arg1: Object): Boolean;
begin
var lTuple := Tuple3(arg1);
exit assigned(lTuple) and (lTuple.Item1 = Item1) and (lTuple.Item2 = Item2) and (lTuple.Item3 = Item3);
end;
constructor Tuple4<T1, T2, T3, T4>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4);
begin
Item1 := aItem1;
Item2 := aItem2;
Item3 := aItem3;
Item4 := aItem4;
end;
method Tuple4<T1, T2, T3, T4>.hashCode: Integer;
begin
result := 0;
if Item1 <> nil then result := Tuple.R3(result) xor Item1.hashCode;
if Item2 <> nil then result := Tuple.R3(result) xor Item2.hashCode;
if Item3 <> nil then result := Tuple.R3(result) xor Item3.hashCode;
if Item4 <> nil then result := Tuple.R3(result) xor Item4.hashCode;
end;
method Tuple4<T1, T2, T3, T4>.&equals(arg1: Object): Boolean;
begin
var lTuple := Tuple4(arg1);
exit assigned(lTuple) and (lTuple.Item1 = Item1) and (lTuple.Item2 = Item2) and (lTuple.Item3 = Item3) and (lTuple.Item4 = Item4);
end;
constructor Tuple5<T1, T2, T3, T4, T5>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5);
begin
Item1 := aItem1;
Item2 := aItem2;
Item3 := aItem3;
Item4 := aItem4;
Item5 := aItem5;
end;
method Tuple5<T1, T2, T3, T4, T5>.hashCode: Integer;
begin
result := 0;
if Item1 <> nil then result := Tuple.R3(result) xor Item1.hashCode;
if Item2 <> nil then result := Tuple.R3(result) xor Item2.hashCode;
if Item3 <> nil then result := Tuple.R3(result) xor Item3.hashCode;
if Item4 <> nil then result := Tuple.R3(result) xor Item4.hashCode;
if Item5 <> nil then result := Tuple.R3(result) xor Item5.hashCode;
end;
method Tuple5<T1, T2, T3, T4, T5>.&equals(arg1: Object): Boolean;
begin
var lTuple := Tuple5(arg1);
exit assigned(lTuple) and (lTuple.Item1 = Item1) and (lTuple.Item2 = Item2) and (lTuple.Item3 = Item3) and (lTuple.Item4 = Item4) and (lTuple.Item5 = Item5);
end;
constructor Tuple6<T1, T2, T3, T4, T5, T6>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6);
begin
Item1 := aItem1;
Item2 := aItem2;
Item3 := aItem3;
Item4 := aItem4;
Item5 := aItem5;
Item6 := aItem6;
end;
method Tuple6<T1, T2, T3, T4, T5, T6>.hashCode: Integer;
begin
result := 0;
if Item1 <> nil then result := Tuple.R3(result) xor Item1.hashCode;
if Item2 <> nil then result := Tuple.R3(result) xor Item2.hashCode;
if Item3 <> nil then result := Tuple.R3(result) xor Item3.hashCode;
if Item4 <> nil then result := Tuple.R3(result) xor Item4.hashCode;
if Item5 <> nil then result := Tuple.R3(result) xor Item5.hashCode;
if Item6 <> nil then result := Tuple.R3(result) xor Item6.hashCode;
end;
method Tuple6<T1, T2, T3, T4, T5, T6>.&equals(arg1: Object): Boolean;
begin
var lTuple := Tuple6(arg1);
exit assigned(lTuple) and (lTuple.Item1 = Item1) and (lTuple.Item2 = Item2) and (lTuple.Item3 = Item3) and (lTuple.Item4 = Item4) and (lTuple.Item5 = Item5)
and (lTuple.Item6 = Item6);
end;
constructor Tuple7<T1, T2, T3, T4, T5, T6, T7>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6; aItem7: T7);
begin
Item1 := aItem1;
Item2 := aItem2;
Item3 := aItem3;
Item4 := aItem4;
Item5 := aItem5;
Item6 := aItem6;
Item7 := aItem7;
end;
method Tuple7<T1, T2, T3, T4, T5, T6, T7>.hashCode: Integer;
begin
result := 0;
if Item1 <> nil then result := Tuple.R3(result) xor Item1.hashCode;
if Item2 <> nil then result := Tuple.R3(result) xor Item2.hashCode;
if Item3 <> nil then result := Tuple.R3(result) xor Item3.hashCode;
if Item4 <> nil then result := Tuple.R3(result) xor Item4.hashCode;
if Item5 <> nil then result := Tuple.R3(result) xor Item5.hashCode;
if Item6 <> nil then result := Tuple.R3(result) xor Item6.hashCode;
if Item7 <> nil then result := Tuple.R3(result) xor Item7.hashCode;
end;
method Tuple7<T1, T2, T3, T4, T5, T6, T7>.&equals(arg1: Object): Boolean;
begin
var lTuple := Tuple7(arg1);
exit assigned(lTuple) and (lTuple.Item1 = Item1) and (lTuple.Item2 = Item2) and (lTuple.Item3 = Item3) and (lTuple.Item4 = Item4) and (lTuple.Item5 = Item5)
and (lTuple.Item6 = Item6) and (lTuple.Item7 = Item7);
end;
constructor Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6; aItem7: T7; aItem8: T8);
begin
Item1 := aItem1;
Item2 := aItem2;
Item3 := aItem3;
Item4 := aItem4;
Item5 := aItem5;
Item6 := aItem6;
Item7 := aItem7;
Item8 := aItem8;
end;
method Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>.hashCode: Integer;
begin
result := 0;
if Item1 <> nil then result := Tuple.R3(result) xor Item1.hashCode;
if Item2 <> nil then result := Tuple.R3(result) xor Item2.hashCode;
if Item3 <> nil then result := Tuple.R3(result) xor Item3.hashCode;
if Item4 <> nil then result := Tuple.R3(result) xor Item4.hashCode;
if Item5 <> nil then result := Tuple.R3(result) xor Item5.hashCode;
if Item6 <> nil then result := Tuple.R3(result) xor Item6.hashCode;
if Item7 <> nil then result := Tuple.R3(result) xor Item7.hashCode;
if Item8 <> nil then result := Tuple.R3(result) xor Item8.hashCode;
end;
method Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>.&equals(arg1: Object): Boolean;
begin
var lTuple := Tuple8(arg1);
exit assigned(lTuple) and (lTuple.Item1 = Item1) and (lTuple.Item2 = Item2) and (lTuple.Item3 = Item3) and (lTuple.Item4 = Item4) and (lTuple.Item5 = Item5)
and (lTuple.Item6 = Item6) and (lTuple.Item7 = Item7) and (lTuple.Item8 = Item8);
end;
class method Tuple.&New<T1>(aItem1: T1): Tuple1<T1>;
begin
exit new Tuple1<T1>(aItem1);
end;
class method Tuple.&New<T1,T2>(aItem1: T1; aItem2: T2): Tuple2<T1, T2>;
begin
exit new Tuple2<T1, T2>(aItem1, aItem2);
end;
class method Tuple.&New<T1,T2,T3>(aItem1: T1; aItem2: T2; aItem3: T3): Tuple3<T1, T2, T3>;
begin
exit new Tuple3<T1, T2, T3>(aItem1, aItem2, aItem3);
end;
class method Tuple.&New<T1,T2,T3,T4>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4): Tuple4<T1, T2, T3, T4>;
begin
exit new Tuple4<T1, T2, T3, T4>(aItem1, aItem2, aItem3, aItem4);
end;
class method Tuple.&New<T1,T2,T3,T4,T5>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5): Tuple5<T1, T2, T3, T4, T5>;
begin
exit new Tuple5<T1, T2, T3, T4, T5>(aItem1, aItem2, aItem3, aItem4, aItem5);
end;
class method Tuple.&New<T1,T2,T3,T4,T5,T6>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6): Tuple6<T1, T2, T3, T4, T5, T6>;
begin
exit new Tuple6<T1, T2, T3, T4, T5,T6>(aItem1, aItem2, aItem3, aItem4, aItem5, aItem6);
end;
class method Tuple.&New<T1,T2,T3,T4,T5,T6,T7>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6; aItem7: T7): Tuple7<T1, T2, T3, T4, T5, T6, T7>;
begin
exit new Tuple7<T1, T2, T3, T4, T5,T6, T7>(aItem1, aItem2, aItem3, aItem4, aItem5, aItem6, aItem7);
end;
class method Tuple.&New<T1,T2,T3,T4,T5,T6,T7,T8>(aItem1: T1; aItem2: T2; aItem3: T3; aItem4: T4; aItem5: T5; aItem6: T6; aItem7: T7; aItem8: T8): Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>;
begin
exit new Tuple8<T1, T2, T3, T4, T5,T6, T7, T8>(aItem1, aItem2, aItem3, aItem4, aItem5, aItem6, aItem7, aItem8);
end;
class method &Tuple.R3(i: Integer): Integer;
begin
exit (i shl 29) or (unsignedShr(i, 3));
end;
end. |
unit PageDocument;
interface
uses
SysUtils, Classes, Forms,
dcfdes,
LrDocument, ThComponentIterator, ThInterfaces, TpInterfaces,
DesignView, PhpPage;
type
TPageDocument = class(TLrDocument)
private
FPublishFolder: string;
FLibFolder: string;
protected
function GetExtension: string; override;
function GetFilter: string; override;
function GetHtmlFilename: string;
function GetJsFilename: string;
function GetPageName: string;
function GetPhpConfigFilename: string;
function GetPhpFilename: string;
function GetPublishFolder: string;
function GetRemoteLibFolder: string;
function GetStyleFilename: string;
function GetSupportFolder: string;
protected
procedure GeneratePageSource;
procedure ListPhpIncludes;
procedure Load;
procedure PageNameChange(inSender: TObject);
procedure PublishConfigs;
procedure PublishHtml;
procedure PublishJavaScript;
procedure PublishLibs;
procedure PublishPhp;
procedure PublishPhpConfig;
procedure PublishStyles(inStyles: TStringList);
procedure PublishStyleSheet;
public
DesignForm: TDesignForm;
Html: TStringList;
OldName: string;
Page: TPhpPage;
PhpIncludes: TStringList;
public
constructor Create(inManager: TLrDocumentManager;
const inPath: string = ''); override;
destructor Destroy; override;
function GenerateHtml: TStringList;
procedure LazyUpdate; override;
procedure Open; override;
procedure Publish;
procedure Save; override;
procedure UpdatePageName(inStrings: TStrings);
procedure ValidateLimitInfos;
public
property HtmlFilename: string read GetHtmlFilename;
property LibFolder: string read FLibFolder write FLibFolder;
property PhpFilename: string read GetPhpFilename;
property PublishFolder: string read GetPublishFolder write FPublishFolder;
property RemoteLibFolder: string read GetRemoteLibFolder;
property SupportFolder: string read GetSupportFolder;
end;
const
//cPageDocumentFileExtension = '.tppage';
cPageDocumentFileExtension = '.tphp';
implementation
uses
LrUtils, ThPathUtils, Config;
{ TPageDocument }
var
singletonPlaceholderForm: TForm;
function PlaceholderForm: TForm;
begin
if singletonPlaceholderForm = nil then
singletonPlaceholderForm := TForm.Create(nil);
Result := singletonPlaceholderForm;
end;
constructor TPageDocument.Create(inManager: TLrDocumentManager;
const inPath: string);
begin
inherited;
//
PhpIncludes := TStringList.Create;
//PhpIncludes.Sorted := true;
//PhpIncludes.Duplicates := dupIgnore;
//
DesignForm := TDesignForm.Create(Application);
DesignForm.Parent := PlaceholderForm;
DesignForm.DCLiteDesigner.OnChange := ChangeEvent;
//
Page := TPhpPage.Create(DesignForm);
GeneratePageSource;
//
ValidateLimitInfos;
end;
destructor TPageDocument.Destroy;
begin
DesignForm.Free;
PhpIncludes.Free;
inherited;
end;
function TPageDocument.GetExtension: string;
begin
Result := cPageDocumentFileExtension;
end;
function TPageDocument.GetFilter: string;
begin
Result := Format('TurboPhp Files (*%s)|*%0:s', [ Extension ]);
end;
procedure TPageDocument.ValidateLimitInfos;
begin
DesignForm.SetLimitInfo(0, DesignForm);
DesignForm.SetLimitInfo(1, Page, [ atSelect, atEdit ]);
end;
function TPageDocument.GetPageName: string;
begin
Result := DisplayName;
end;
procedure TPageDocument.GeneratePageSource;
begin
with Page.PhpSource do
begin
Add('<?php');
Add('');
Add('// Configure');
Add('');
Add('include_once("page.config.php");');
Add('');
Add('// Define page class');
Add('');
Add('class T' + GetPageName + ' extends TTpPage');
Add('{');
Add('}');
Add('');
Add('// Create and display page');
Add('');
Add('$' + GetPageName + ' = new T' + GetPageName + '($tpTemplateFile);');
Add('$' + GetPageName + '->Run();');
Add('');
{
Add('// Initialize application');
Add('');
Add('$app = new TTpApp($tpTemplateFile);');
Add('$app->ParseTemplate();');
Add('');
Add('// Generate output');
Add('');
Add('echo $app->Generate();');
Add('');
Add('// User event functions here');
Add('');
}
Add('?>');
end;
OldName := GetPageName;
end;
procedure TPageDocument.PageNameChange(inSender: TObject);
begin
// if (OldName <> '') then
// OldName := Page.Name;
end;
procedure TPageDocument.UpdatePageName(inStrings: TStrings);
var
i: Integer;
begin
if (OldName <> GetPageName) then
begin
with inStrings do
for i := 0 to Pred(Count) do
begin
Strings[i] := StringReplace(Strings[i], '$' + OldName, '$' + GetPageName, [ rfReplaceAll ]);
Strings[i] := StringReplace(Strings[i], 'T' + OldName, 'T' + GetPageName, [ rfReplaceAll ]);
end;
OldName := GetPageName;
end;
end;
procedure TPageDocument.LazyUpdate;
begin
inherited;
end;
procedure TPageDocument.Open;
begin
inherited;
if not Untitled then
Load;
OldName := GetPageName;
end;
procedure TPageDocument.Load;
begin
FreeAndNil(Page);
DesignForm.LoadFromFile(Path);
FindComponentByClass(Page, TPhpPage, DesignForm);
ValidateLimitInfos;
inherited;
DesignForm.DCLiteDesigner.OnChange := ChangeEvent;
Modified := false;
end;
procedure TPageDocument.Save;
begin
//UpdatePageName;
inherited;
DesignForm.SaveToFile(Path);
end;
function TPageDocument.GetPublishFolder: string;
begin
Result := FPublishFolder;
end;
function TPageDocument.GetSupportFolder: string;
begin
Result := 'support/';
end;
function TPageDocument.GetRemoteLibFolder: string;
begin
Result := ThPathToUrl(ExtractRelativePath(PublishFolder, LibFolder));
end;
function TPageDocument.GetJsFilename: string;
begin
Result := SupportFolder + ChangeFileExt(FileName, '.js')
end;
function TPageDocument.GetStyleFilename: string;
begin
if Page.StyleSheet = nil then
Result := ''
else
Result := SupportFolder + ChangeFileExt(FileName, '.css')
end;
function TPageDocument.GetHtmlFilename: string;
begin
Result := ChangeFileExt(FileName, '.html');
end;
function TPageDocument.GetPhpFilename: string;
begin
Result := Page.PhpFilename;
if Result = '' then
Result := FileName;
Result := ChangeFileExt(Result, '.php');
end;
function TPageDocument.GetPhpConfigFilename: string;
begin
Result := SupportFolder + ChangeFileExt(GetPhpFilename, '.config.php');
end;
procedure TPageDocument.ListPhpIncludes;
var
l: ITpIncludeLister;
begin
PhpIncludes.Clear;
PhpIncludes.Add('TpParser.php');
PhpIncludes.Add('TpLib.php');
if Page.Debug then
PhpIncludes.Add('TpDebug.php');
//
with TThComponentIterator.Create(DesignForm) do
try
while Next do
if IsAs(Component, ITpIncludeLister, l) then
l.ListPhpIncludes(PhpIncludes);
finally
Free;
end;
//
DeDupeStrings(PhpIncludes);
end;
procedure TPageDocument.PublishLibs;
var
s: TStringList;
i: Integer;
procedure PublishFile(const inFilename: string);
begin
if FileExists(LibSourceFolder + inFilename) then
begin
s.LoadFromFile(LibSourceFolder + inFilename);
s.SaveToFile(LibFolder + inFilename);
end;
end;
begin
s := TStringList.Create;
try
NeedFolder(LibFolder);
for i := 0 to Pred(PhpIncludes.Count) do
PublishFile(PhpIncludes[i]);
PublishFile('TpDebug.php');
// PublishFile('TpDb.php');
// PublishFile('TpMySql.php');
finally
s.Free;
end;
end;
function TPageDocument.GenerateHtml: TStringList;
begin
Result := TStringList.Create;
Result.Text := Page.Html;
end;
procedure TPageDocument.PublishHtml;
begin
Page.JsUrl := ThPathToUrl(GetJsFilename);
Page.StyleUrl := ThPathToUrl(GetStyleFilename);
with GenerateHtml do
try
SaveToFile(PublishFolder + SupportFolder + HtmlFilename);
finally
Free;
end;
end;
procedure TPageDocument.PublishJavaScript;
var
j: TStringList;
l: ITpJsWriter;
begin
j := TStringList.Create;
try
with TThComponentIterator.Create(DesignForm) do
try
while Next do
if IsAs(Component, ITpJsWriter, l) then
l.WriteJavaScript(j);
finally
Free;
end;
j.AddStrings(Page.JsSource);
j.SaveToFile(PublishFolder + GetJsFilename);
finally
j.Free;
end;
end;
procedure TPageDocument.PublishStyles(inStyles: TStringList);
var
s: IThStyleSource;
begin
with TThComponentIterator.Create(DesignForm) do
try
while Next do
if IsAs(Component, IThStyleSource, s) then
s.PublishStyles(inStyles);
finally
Free;
end;
end;
procedure TPageDocument.PublishStyleSheet;
var
s: TStringList;
begin
if Page.StyleSheet <> nil then
begin
s := TStringList.Create;
try
Page.StyleSheet.Styles.GenerateStyles(s);
Page.AnchorStyles.GenerateStyles(s, Page.StyleSheet);
PublishStyles(s);
s.SaveToFile(PublishFolder + GetStyleFilename);
finally
s.Free;
end;
end;
end;
procedure TPageDocument.PublishConfigs;
var
w: ITpConfigWriter;
begin
with TThComponentIterator.Create(DesignForm) do
try
while Next do
if IsAs(Component, ITpConfigWriter, w) then
w.WriteConfig(PublishFolder + SupportFolder);
finally
Free;
end;
{
with TThComponentIterator.Create(DesignForm) do
try
while Next(TTpMySql) do
begin
TTpMySql(Component).WriteConfig(inFolder);
end;
finally
Free;
end;
}
end;
procedure TPageDocument.PublishPhpConfig;
const
cLibPath = '$tpLibPath';
cSupportPath = '$tpSupportPath';
cTemplate = '$tpTemplateFile';
var
config: TStringList;
i: Integer;
begin
config := TStringList.Create;
try
config.Add('<?php');
config.Add('');
config.Add(cSupportPath + ' = "' + SupportFolder + '";');
config.Add(cLibPath + ' = "' + RemoteLibFolder + '";');
config.Add(cTemplate + ' = $tpSupportPath . "' + HtmlFilename + '";');
config.Add('');
for i := 0 to Pred(PhpIncludes.Count) do
config.Add('include_once($tpLibPath . "' + PhpIncludes[i] + '");');
config.Add('');
config.Add('?>');
config.SaveToFile(PublishFolder + GetPhpConfigFilename);
finally
config.Free;
end;
end;
procedure TPageDocument.PublishPhp;
begin
Page.PhpSource.Strings[4] := 'include_once("' + GetPhpConfigFilename + '");';
Page.PhpSource.SaveToFile(PublishFolder + GetPhpFilename);
end;
procedure TPageDocument.Publish;
begin
LazyUpdate;
//
NeedFolder(LibFolder);
NeedFolder(PublishFolder);
NeedFolder(PublishFolder + SupportFolder);
//
ListPhpIncludes;
//
PublishConfigs;
PublishHtml;
PublishPhpConfig;
PublishPhp;
PublishLibs;
PublishJavaScript;
PublishStyleSheet;
// PublishImages(PublishFolder + ImagesFolder);
end;
end.
|
unit Odontologia.Modelo.Estado.Cita;
interface
uses
Data.DB,
SimpleDAO,
SimpleInterface,
SimpleQueryRestDW,
Odontologia.Modelo.Estado.Cita.Interfaces,
Odontologia.Modelo.Entidades.Estado.Cita,
Odontologia.Modelo.Conexion.RestDW,
System.SysUtils;
type
TModelEstadoCita = class (TInterfacedOBject, iModelEstadoCita)
private
FEstadoCita : TFESTADO_CITA;
FDAO : iSimpleDao<TFESTADO_CITA>;
FDataSource : TDataSource;
public
constructor Create;
destructor Destroy; override;
class function New : iModelEstadoCita;
function Entidad : TFESTADO_CITA;
function DAO : iSimpleDAO<TFESTADO_CITA>;
function DataSource (aDataSource : TDataSource) : iModelEstadoCita;
end;
implementation
{ TModelEstadoCita }
constructor TModelEstadoCita.Create;
begin
FEstadoCita := TFESTADO_CITA.Create;
FDAO := TSimpleDAO<TFESTADO_CITA>
.New(TSimpleQueryRestDW<TFESTADO_CITA>
.New(ModelConexion.RESTDWDataBase1));
end;
function TModelEstadoCita.DAO: iSimpleDAO<TFESTADO_CITA>;
begin
Result := FDAO;
end;
function TModelEstadoCita.DataSource(aDataSource: TDataSource): iModelEstadoCita;
begin
Result := Self;
FDataSource := aDataSource;
FDAO.DataSource(FDataSource);
end;
destructor TModelEstadoCita.Destroy;
begin
FreeAndNil(FEstadoCita);
inherited;
end;
function TModelEstadoCita.Entidad: TFESTADO_CITA;
begin
Result := FEstadoCita;
end;
class function TModelEstadoCita.New: iModelEstadoCita;
begin
Result := Self.Create;
end;
end.
|
unit uSpMinGrantAdd;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxMemo, cxMaskEdit,
cxDropDownEdit, cxCalendar, cxTextEdit, cxControls, cxContainer, cxEdit,
cxLabel, ibase, ActnList, cxCurrencyEdit,DogLoaderUnit;
type
TfmSpGrantMinAdd = class(TForm)
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
cxLabel3: TcxLabel;
cxLabel4: TcxLabel;
DateEditBeg: TcxDateEdit;
DateEditEnd: TcxDateEdit;
MemoNote: TcxMemo;
OkButton: TcxButton;
CancelButton: TcxButton;
ActionList1: TActionList;
ActionSave: TAction;
ActionExit: TAction;
TextEditMinSum: TcxCurrencyEdit;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure TextEditMinSumKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure TextEditMinSumKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
id_min_sum : variant;
close_record : integer;
DB_handle : TISC_DB_HANDLE;
constructor Create(AOwner:TComponent);reintroduce;
end;
{var
fmSpGrantMinAdd: TfmSpGrantMinAdd; }
implementation
uses DM_SpMinGrant;
{$R *.dfm}
constructor TfmSpGrantMinAdd.Create(AOwner:TComponent);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
Screen.Cursor:=crDefault;
end;
procedure TfmSpGrantMinAdd.OkButtonClick(Sender: TObject);
begin
if (TextEditMinSum.Text = '') then
Begin
ShowMessage('Необхідно заповнити мінимальну суму!');
TextEditMinSum.SetFocus;
Exit;
end;
if (DateEditBeg.Text = '') then
Begin
ShowMessage('Необхідно заповнити дату початку!');
DateEditBeg.SetFocus;
Exit;
end;
if (DateEditEnd.Text = '') then
Begin
ShowMessage('Необхідно заповнити дату кінця!');
DateEditEnd.SetFocus;
Exit;
end;
if (DateEditBeg.Text > DateEditEnd.Text) then
Begin
ShowMessage('Дата початку не може перевищувати дату кінця!');
DateEditEnd.SetFocus;
Exit;
end;
DM.DataSetCheck.Close;
DM.DataSetCheck.SQLs.SelectSQL.Text := 'select * from CS_MIN_SUM_GR s where :date_beg between s.date_beg and s.date_end';
DM.DataSetCheck.ParamByName('date_beg').AsDate := DateEditBeg.Date;
DM.DataSetCheck.Open;
DM.DataSetCheck.FetchAll;
if DM.DataSetCheck.RecordCount>=1 then
begin
if MessageDlg('Увага', 'Існує запис на цей період! Бажаєте закрити старий запис?', mtConfirmation, [mbYes, mbNo]) = mrYes then
begin
close_record := 1;
end else
begin
close_record := 0;
exit;
end;
end;
ModalResult := mrOk;
end;
procedure TfmSpGrantMinAdd.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfmSpGrantMinAdd.TextEditMinSumKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
//
end;
procedure TfmSpGrantMinAdd.TextEditMinSumKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = '-') then Key := Chr(0);
end;
end.
|
//***********************************************************************
//* Проект "Студгородок" *
//* Справочник категорий - добавление источников финансирования *
//* Выполнил: Чернявский А.Э. 2004-2005 г. *
//***********************************************************************
unit uSp_Kat_Pay_Istoch_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxTextEdit, cxLabel,
cxControls, cxContainer, cxEdit, cxGroupBox, cxCurrencyEdit, cxMaskEdit,
cxButtonEdit, uSp_kat_pay_DM, GlobalSPR, DB, FIBDataSet, pFIBDataSet,
ActnList, Math, st_ConstUnit, st_common_funcs, iBase, st_common_types,
st_common_loader, st_Consts_Messages;
type
TCategoryFormAddFin = class(TForm)
cxGroupBox1: TcxGroupBox;
OKButton: TcxButton;
CancelButton: TcxButton;
ReadDataSet: TpFIBDataSet;
Category_ActionList: TActionList;
Add_Action: TAction;
Edit_Action: TAction;
Delete_Action: TAction;
Ok_Action: TAction;
cxLabel7: TcxLabel;
serves_ButtonEdit: TcxButtonEdit;
cxLabel3: TcxLabel;
Smeta_Edit: TcxButtonEdit;
Smeta_Label: TcxLabel;
SummaLabel: TcxLabel;
SummaEdit: TcxCurrencyEdit;
Currency_PDV: TcxCurrencyEdit;
cxLabel1: TcxLabel;
S_SummaEdit: TcxCurrencyEdit;
cxLabel8: TcxLabel;
cxLabel2: TcxLabel;
KEKV_Edit: TcxButtonEdit;
kekv_Label: TcxLabel;
procedure CancelButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure OKButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure PercentEditKeyPress(Sender: TObject; var Key: Char);
procedure Persent_Subs_EditKeyPress(Sender: TObject; var Key: Char);
procedure Smeta_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Smeta_EditPropertiesEditValueChanged(Sender: TObject);
procedure Kekv_EditKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure Ok_ActionExecute(Sender: TObject);
procedure SummaEditEnter(Sender: TObject);
procedure S_SummaEditEnter(Sender: TObject);
procedure serves_ButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Currency_PDVExit(Sender: TObject);
procedure S_SummaEditExit(Sender: TObject);
procedure SummaEditExit(Sender: TObject);
procedure Currency_PDVEnter(Sender: TObject);
procedure KEKV_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure KEKV_EditPropertiesEditValueChanged(Sender: TObject);
procedure serves_ButtonEditKeyPress(Sender: TObject; var Key: Char);
private
Cur_date: string;
PLanguageIndex: byte;
//CURRENT_TIMESTAMP : TDateTime;
procedure FormIniLanguage();
public
id_smeta : int64;
id_kekv : Int64;
is_admin : Boolean;
aHandle : TISC_DB_HANDLE;
id_serves : Int64;
end;
var
CategoryFormAddFin: TCategoryFormAddFin;
const kav = ''''; // это кавычки
implementation
uses uSp_Kat_Pay_Summ_AE, uSp_Kat_Pay_AE;
{$R *.dfm}
procedure TCategoryFormAddFin.FormIniLanguage();
begin
// индекс языка (1-укр, 2 - рус)
PLanguageIndex:= stLanguageIndex;
//названия кнопок
OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex];
CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex];
// смета
cxLabel3.Caption := st_ConstUnit.st_Smeta[PLanguageIndex];
SummaLabel.Caption:= st_ConstUnit.st_SummaSliv[PLanguageIndex];
cxLabel1.Caption:= st_ConstUnit.st_SubSumma[PLanguageIndex];
end;
procedure TCategoryFormAddFin.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TCategoryFormAddFin.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// Action := caFree;
end;
procedure TCategoryFormAddFin.OKButtonClick(Sender: TObject);
begin
if serves_ButtonEdit.Text = '' then
begin
ShowMessage('Неодхідно обрати послугу!');
serves_ButtonEdit.SetFocus;
Exit;
end;
if Smeta_Edit.Text = '' then
begin
ShowMessage(pchar(st_ConstUnit.st_2[PLanguageIndex]));
Smeta_Edit.SetFocus;
exit;
end;
if not IntegerCheck(Smeta_Edit.Text) then
begin
ShowMessage(pchar(st_ConstUnit.st_mess_Code_need[PLanguageIndex]));
Smeta_Label.Clear;
Smeta_Label.Visible:=false;
Smeta_Edit.SetFocus;
exit;
end;
if Currency_PDV.EditValue <> 0 then
begin
ReadDataSet.Close;
ReadDataSet.SQLs.SelectSQL.Text := 'Select * from ST_SERVICE_DETAIL where ID_SERVICE = :id_serves and ST_OPTIONS = 2';
ReadDataSet.ParamByName('id_serves').AsInt64 := id_serves;
ReadDataSet.Open;
If ReadDataSet.RecordCount = 0 then
begin
ShowMessage('У вибраної послуги немає статті для акумуляції ПДВ!');
serves_ButtonEdit.SetFocus;
Exit;
end;
end;
ModalResult := mrOK;
end;
procedure TCategoryFormAddFin.FormShow(Sender: TObject);
begin
ReadDataSet.Close;
ReadDataSet.SelectSQL.Clear;
ReadDataSet.SelectSQL.Text := 'select CUR_DATE from ST_GET_CURRENT_DATE';
ReadDataSet.Open;
Cur_date:= ReadDataSet['CUR_DATE'];
ReadDataSet.Close;
serves_ButtonEdit.SetFocus;
end;
procedure TCategoryFormAddFin.PercentEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then S_SummaEdit.SetFocus;
end;
procedure TCategoryFormAddFin.Persent_Subs_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then Smeta_Edit.SetFocus;
end;
procedure TCategoryFormAddFin.Smeta_EditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
id:variant;
begin
id:=GlobalSPR.GetSmets(self, aHandle, StrToDate(Cur_date), psmRazdSt);
if VarArrayDimCount(id)>0 //- проверка на то что id вариантный массив
then begin
if id[0]<>NULL
then begin
// id[0] -идентификатор сметы
// id[1] -идентификатор раздела
// id[2] -идентификатор статьи
// id[3] -идентификатор группы смет
// id[4] -наименование раздела
// id[5] -наименование статьи
// id[6] -наименование сметы
// id[7] -номер раздела
// id[8] -номер статьи
// id[9] -код сметы
// id[10] -наименование группы смет
id_smeta := id[0];
Smeta_Edit.Text:=vartostr(id[9]);
Smeta_Label.Caption:=vartostr(id[6]);
Smeta_Label.Visible:=true;
end;
end;
end;
procedure TCategoryFormAddFin.Smeta_EditPropertiesEditValueChanged(
Sender: TObject);
begin
if Smeta_Edit.Text = '' then exit;
if not IntegerCheck(Smeta_Edit.Text) then
begin
ShowMessage(pchar(st_ConstUnit.st_NotCorrectCode[PLanguageIndex]));
Smeta_Label.Clear;
Smeta_Label.Visible:=false;
Smeta_Edit.SetFocus;
exit;
end;
ReadDataSet.Close;
ReadDataSet.SelectSQL.Clear;
ReadDataSet.SelectSQL.Text := 'select ID_OBJECT, TITLE_OBJECT from PUB_GET_NAME_BUDG_BY_KOD ( '+Smeta_Edit.Text+','+kav+Cur_date+kav+',' +'1)';
ReadDataSet.Open;
if ReadDataSet['ID_OBJECT']<> null then
begin
id_smeta := ReadDataSet['ID_OBJECT'];
if ReadDataSet['TITLE_OBJECT']<> null then
begin
Smeta_Label.Caption:= ReadDataSet['TITLE_OBJECT'];
Smeta_Label.Visible:=true;
end
else
begin
Smeta_Label.Clear;
Smeta_Label.Visible:=false;
end
end
else
begin
ShowMessage(pchar(st_ConstUnit.st_NotCorrectSmeta[PLanguageIndex]));
Smeta_Label.Clear;
Smeta_Label.Visible:=false;
Smeta_Edit.SetFocus;
ReadDataSet.Close;
exit;
end;
ReadDataSet.Close;
end;
procedure TCategoryFormAddFin.Kekv_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key=#13 then OKButton.SetFocus;
end;
procedure TCategoryFormAddFin.FormCreate(Sender: TObject);
begin
ReadDataSet.Close;
ReadDataSet.SelectSQL.Clear;
ReadDataSet.SelectSQL.Text := 'select CUR_DATE from ST_GET_CURRENT_DATE';
ReadDataSet.Open;
Cur_date:= ReadDataSet['CUR_DATE'];
ReadDataSet.Close;
FormIniLanguage();
end;
procedure TCategoryFormAddFin.Ok_ActionExecute(Sender: TObject);
begin
CategoryFormAddFin.OKButtonClick(Sender);
end;
procedure TCategoryFormAddFin.SummaEditEnter(Sender: TObject);
begin
SummaEdit.Value := RoundTo(SummaEdit.Value, -2);
end;
procedure TCategoryFormAddFin.S_SummaEditEnter(Sender: TObject);
begin
S_SummaEdit.Value := RoundTo(S_SummaEdit.Value, -2);
end;
procedure TCategoryFormAddFin.serves_ButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
aParameter : TstSimpleParams;
res : Variant;
begin
aParameter := TstSimpleParams.Create;
aParameter.Owner := self;
aParameter.Db_Handle := aHandle;
AParameter.Formstyle := fsNormal;
AParameter.WaitPakageOwner := self;
aParameter.is_admin := is_admin;
res := RunFunctionFromPackage(aParameter, 'Studcity\st_services.bpl', 'getServices');
If VarArrayDimCount(res) <>0 then
begin
id_serves := res[0];
serves_ButtonEdit.Text := res[1];
ReadDataSet.Close;
ReadDataSet.SQLs.SelectSQL.Text := 'Select * from ST_SERVICE_DETAIL where id_service = :id_serves and st_options = 2';
ReadDataSet.ParamByName('ID_SERVES').AsInt64 := id_serves;
ReadDataSet.Open;
ReadDataSet.FetchAll;
if ReadDataSet.RecordCount = 0 then
begin
Currency_PDV.Enabled := False;
Currency_PDV.Value := 0;
End
else Currency_PDV.Enabled := True;
ReadDataSet.Close;
end;
aParameter.Free;
end;
procedure TCategoryFormAddFin.Currency_PDVExit(Sender: TObject);
begin
If Currency_PDV.Text = '' then Currency_PDV.EditValue := 0;
end;
procedure TCategoryFormAddFin.S_SummaEditExit(Sender: TObject);
begin
If S_SummaEdit.Text = '' then S_SummaEdit.EditValue := 0;
end;
procedure TCategoryFormAddFin.SummaEditExit(Sender: TObject);
begin
if SummaEdit.Text = '' then SummaEdit.EditValue := 0;
end;
procedure TCategoryFormAddFin.Currency_PDVEnter(Sender: TObject);
begin
if Currency_PDV.EditValue <> 0 then Exit;
Currency_PDV.EditValue := SummaEdit.EditValue / 5;
end;
procedure TCategoryFormAddFin.KEKV_EditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
id:variant;
begin
id := GlobalSPR.GetKEKVSpr(self, aHandle, FSNormal, StrToDate(Cur_date), DEFAULT_ROOT_ID);
if VarArrayDimCount(id)>0 //- проверка на то что id вариантный массив
then begin
if VarArrayDimCount(id) > 0 then
begin
if id[0][0] <> NULL then
begin
// id[0][0] - идентификатор КЕКВа
// id[0][1] - наименование КЕКВа
// id[0][2] - код КЕКВа
ID_KEKV := id[0][0];
Kekv_Edit.Text := id[0][2];
kekv_Label.Caption := id[0][1];
kekv_Label.Visible := True;
end;
end;
end;
end;
procedure TCategoryFormAddFin.KEKV_EditPropertiesEditValueChanged(
Sender: TObject);
begin
if Kekv_Edit.Text= '' then exit;
if not IntegerCheck(Kekv_Edit.Text) then
begin
ShowMessage('Введен неверный код.');
kekv_Label.Clear;
Kekv_Label.Visible:=false;
Kekv_Edit.SetFocus;
exit;
end;
ReadDataSet.Close;
ReadDataSet.SQLs.SelectSQL.Text := 'select ID_KEKV, KEKV_TITLE from PUB_SPR_KEKV_INFO_EX2 ( '+Kekv_Edit.Text+','+kav + Cur_date+kav+')';
ReadDataSet.Open;
If ReadDataSet['ID_KEKV'] <> null then
begin
ID_KEKV := ReadDataSet['ID_KEKV'];
if ReadDataSet['KEKV_TITLE']<> null then
begin
Kekv_Label.Caption:= ReadDataSet['KEKV_TITLE'];
Kekv_Label.Visible:=true;
end
else
begin
Kekv_Label.Clear;
Kekv_Label.Visible:=false;
end
end
else
begin
ShowMessage(st_Consts_Messages.st_warningVvod_Kekv[PLanguageIndex]);
Kekv_Label.Clear;
Kekv_Label.Visible:=false;
Kekv_Edit.SetFocus;
ReadDataSet.close;
exit;
end;
ReadDataSet.close;
end;
procedure TCategoryFormAddFin.serves_ButtonEditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then Smeta_Edit.SetFocus;
end;
end.
|
unit AltaClientes;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Data.DB, Data.Win.ADODB,modulo,
Vcl.Mask, Vcl.DBCtrls;
type
TfAltaClientes = class(TForm)
cmbSalir: TButton;
cmbGrabar: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
afi_clientes: TADOQuery;
clientes: TDataSource;
txtApeNom: TEdit;
txtCorreo: TEdit;
txtTelefono: TEdit;
txtDomicilio: TEdit;
ADO: TADOConnection;
procedure cmbGrabarClick(Sender: TObject);
procedure txtTelefonoKeyPress(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fAltaClientes: TfAltaClientes;
implementation
function validar(ape,tel:String): boolean;
begin
if ape.IsEmpty = true then begin
ShowMessage('Ingrese Apellido y nombre del cliente');
Result := false;
end;
if tel.IsEmpty then begin
ShowMessage('Ingrese Telefono del cliente');
Result := false;
end;
Result:=true;
end;
{$R *.dfm}
procedure TfAltaClientes.cmbGrabarClick(Sender: TObject);
var valor:integer;
resultado:integer;
begin
if validar(txtApeNom.Text ,txtTelefono.Text)=true then begin
//seteo de parametros
ADO.Connected:=true;
afi_clientes.Parameters.ParamByName('prm_ape_nom').Value := String(txtApeNom.Text);
afi_clientes.Parameters.ParamByName('prm_tel').Value := txtTelefono.Text;
afi_clientes.Parameters.ParamByName('prm_domicilio').Value := txtDomicilio.Text;
afi_clientes.Parameters.ParamByName('prm_correo').Value := txtCorreo.Text;
afi_clientes.Parameters.ParamByName('prm_id').Value := Null;
afi_clientes.Parameters.ParamByName('prm_baja').Value := 'N';
valor := Integer(afi_clientes.Parameters.ParamByName('pro_id').Value);
if valor = 1 then
showmessage('Alta de cliente satisfactoria')
else
showmessage('Ocurrio un error al grabar el alta');
ADO.Connected:=false;
end;
end;
procedure TfAltaClientes.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Action = caHide then
begin
Hide;
Exit;
end;
end;
procedure TfAltaClientes.txtTelefonoKeyPress(Sender: TObject; var Key: Char);
begin
if not(Key in ['0'..'9',#8]) then
begin
Key:=#0;
end;
end;
end.
|
namespace com.example.android.wiktionary;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*}
interface
uses
android.util,
org.json,
android.net,
android.text,
android.webkit,
java.util,
java.util.regex;
type
/// <summary>
/// Extended version of SimpleWikiHelper. This version adds methods to
/// pick a random word, and to format generic wiki-style text into HTML.
/// </summary>
ExtendedWikiHelper = public class(SimpleWikiHelper)
private
// HTML style sheet to include with any formatWikiText(String) HTML
// results. It formats nicely for a mobile screen, and hides some content
// boxes to keep things tidy.
const STYLE_SHEET = '<style>h2 {font-size:1.2em;font-weight:normal;} ' +
'a {color:#6688cc;} ol {padding-left:1.5em;} blockquote {margin-left:0em;} ' +
'.interProject, .noprint {display:none;} ' +
'li, blockquote {margin-top:0.5em;margin-bottom:0.5em;}</style>';
// Pattern of section titles we're interested in showing. This trims out
// extra sections that can clutter things up on a mobile screen.
class var sValidSections: Pattern := Pattern.compile('(verb|noun|adjective|pronoun|interjection)', Pattern.CASE_INSENSITIVE); readonly;
// Pattern that can be used to split a returned wiki page into its various
// sections. Doesn't treat children sections differently.
class var sSectionSplit: Pattern := Pattern.compile('^=+(.+?)=+.+?(?=^=)', Pattern.MULTILINE or Pattern.DOTALL); readonly;
// When picking random words in getRandomWord(), we sometimes
// encounter special articles or templates. This pattern ignores any words
// like those, usually because they have ":" or other punctuation.
class var sInvalidWord: Pattern := Pattern.compile('[^A-Za-z0-9 ]'); readonly;
// Uri to use when requesting a random page.
const WIKTIONARY_RANDOM = 'https://en.wiktionary.org/w/api.php?action=query&list=random&format=json';
// Fake section to insert at the bottom of a wiki response before parsing.
// This ensures that sSectionSplit will always catch the last
// section, as it uses section headers in its searching.
const STUB_SECTION = ''#10'=Stub section=';
// Number of times to try finding a random word in getRandomWord().
// These failures are usually when the found word fails the
// sInvalidWord test, or when a network error happens.
const RANDOM_TRIES = 3;
// List of internal formatting rules to apply when parsing wiki text. These
// include indenting various bullets, apply italic and bold styles, and
// adding internal linking.
class var sFormatRules: List<FormatRule> := new ArrayList<FormatRule>(); readonly;
public
// Uri authority to use when creating internal links.
const WIKI_AUTHORITY = 'wiktionary';
// Uri host to use when creating internal links.
const WIKI_LOOKUP_HOST = 'lookup';
// Mime-type to use when showing parsed results in a WebView.
const MIME_TYPE = 'text/html';
// Encoding to use when showing parsed results in a WebView.
const ENCODING = 'utf-8';
public
class constructor;
class method getRandomWord: String;
class method formatWikiText(wikiText: String): String;
end;
/// <summary>
/// Internal class to hold a wiki formatting rule. It's mostly a wrapper to
/// simplify Matcher.replaceAll(String).
/// </summary>
FormatRule nested in ExtendedWikiHelper = private class
private
var mPattern: Pattern;
var mReplaceWith: String;
public
constructor(aPattern: String; replaceWith: String; &flags: Integer);
constructor(aPattern: String; replaceWith: String);
method apply(input: String): String;
end;
implementation
class constructor ExtendedWikiHelper;
begin
// Format header blocks and wrap outside content in ordered list
sFormatRules.add(new FormatRule("^=+(.+?)=+", "</ol><h2>$1</h2><ol>", Pattern.MULTILINE));
// Indent quoted blocks, handle ordered and bullet lists
sFormatRules.add(new FormatRule("^#+\*?:(.+?)$", "<blockquote>$1</blockquote>", Pattern.MULTILINE));
sFormatRules.add(new FormatRule("^#+:?\*(.+?)$", "<ul><li>$1</li></ul>", Pattern.MULTILINE));
sFormatRules.add(new FormatRule("^#+(.+?)$", "<li>$1</li>", Pattern.MULTILINE));
// Add internal links
sFormatRules.add(new FormatRule("\[\[([^:\|\]]+)\]\]", String.format('<a href="%s://%s/$1">$1</a>', WIKI_AUTHORITY, WIKI_LOOKUP_HOST)));
sFormatRules.add(new FormatRule("\[\[([^:\|\]]+)\|([^\]]+)\]\]", String.format('<a href="%s://%s/$1">$2</a>', WIKI_AUTHORITY, WIKI_LOOKUP_HOST)));
// Add bold and italic formatting
sFormatRules.add(new FormatRule("'''(.+?)'''", "<b>$1</b>"));
sFormatRules.add(new FormatRule("([^'])''([^'].*?[^'])''([^'])", "$1<i>$2</i>$3"));
// Remove odd category links and convert remaining links into flat text
sFormatRules.add(new FormatRule("(\{+.+?\}+|\[\[[^:]+:[^\\|\]]+\]\]|" +
"\[http.+?\]|\[\[Category:.+?\]\])", "", Pattern.MULTILINE or Pattern.DOTALL));
sFormatRules.add(new FormatRule("\[\[([^\|\]]+\|)?(.+?)\]\]", "$2", Pattern.MULTILINE));
end;
/// <summary>
/// Query the Wiktionary API to pick a random dictionary word. Will try
/// multiple times to find a valid word before giving up.
/// Throws ApiException If any connection or server error occurs.
/// Throws ParseException If there are problems parsing the response.
/// </summary>
/// <returns>Random dictionary word, or null if no valid word was found.</returns>
class method ExtendedWikiHelper.getRandomWord: String;
begin
// Keep trying a few times until we find a valid word
for tries: Integer := 0 to pred(RANDOM_TRIES) do
begin
// Query the API for a random word
var content: String := getUrlContent(WIKTIONARY_RANDOM);
try
// Drill into the JSON response to find the returned word
var response: JSONObject := new JSONObject(content);
var query: JSONObject := response.JSONObject['query'];
var random: JSONArray := query.JSONArray['random'];
var word: JSONObject := random.JSONObject[0];
var foundWord: String := word.String['title'];
// If we found an actual word, and it wasn't rejected by our invalid
// filter, then accept and return it.
if (foundWord <> nil) and not sInvalidWord.matcher(foundWord).find then
exit foundWord;
except
on e: JSONException do
raise new ParseException('Problem parsing API response', e);
end
end;
// No valid word found in number of tries, so return nil
exit nil
end;
/// <summary>
/// Format the given wiki-style text into formatted HTML content. This will
/// create headers, lists, internal links, and style formatting for any wiki
/// markup found.
/// </summary>
/// <param name="wikiText">The raw text to format, with wiki-markup included.</param>
/// <returns>HTML formatted content, ready for display in WebView.</returns>
class method ExtendedWikiHelper.formatWikiText(wikiText: String): String;
begin
if wikiText = nil then
exit nil;
// Insert a fake last section into the document so our section splitter
// can correctly catch the last section.
wikiText := wikiText.concat(STUB_SECTION);
// Read through all sections, keeping only those matching our filter,
// and only including the first entry for each title.
var foundSections: HashSet<String> := new HashSet<String>;
var builder: StringBuilder := new StringBuilder;
var sectionMatcher: Matcher := sSectionSplit.matcher(wikiText);
while sectionMatcher.find do
begin
var title: String := sectionMatcher.group(1);
if not foundSections.contains(title) and sValidSections.matcher(title).matches then
begin
var sectionContent: String := sectionMatcher.group;
foundSections.&add(title);
builder.append(sectionContent)
end
end;
// Our new wiki text is the selected sections only
wikiText := builder.toString;
// Apply all formatting rules, in order, to the wiki text
for each rule: FormatRule in sFormatRules do
wikiText := rule.apply(wikiText);
// Return the resulting HTML with style sheet, if we have content left
if not TextUtils.isEmpty(wikiText) then
exit STYLE_SHEET + wikiText
else
exit nil
end;
/// <summary>
/// Create a wiki formatting rule.
/// </summary>
/// <param name="pattern">Search string to be compiled into a Pattern.</param>
/// <param name="replaceWith">String to replace any found occurances with.
/// This string can also include back-references into the given pattern.</param>
/// <param name="flags">Any flags to compile the Pattern with.</param>
constructor ExtendedWikiHelper.FormatRule(aPattern: String; replaceWith: String; &flags: Integer);
begin
mPattern := Pattern.compile(aPattern, &flags);
mReplaceWith := replaceWith
end;
/// <summary>
/// Create a wiki formatting rule.
/// </summary>
/// <param name="pattern">Search string to be compiled into a Pattern.</param>
/// <param name="replaceWith">String to replace any found occurances with.
/// This string can also include back-references into the given pattern.</param>
constructor ExtendedWikiHelper.FormatRule(aPattern: String; replaceWith: String);
begin
constructor (aPattern, replaceWith, 0)
end;
/// <summary>
/// Apply this formatting rule to the given input string, and return the
/// resulting new string.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
method ExtendedWikiHelper.FormatRule.apply(input: String): String;
begin
var m: Matcher := mPattern.matcher(input);
exit m.replaceAll(mReplaceWith)
end;
end. |
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1996-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit ComStrs;
interface
resourcestring
sTabFailClear = 'Falha ao limpar controle de aba';
sTabFailDelete = 'Falha ao deletar índice %d da aba';
sTabFailRetrieve = 'Falha ao recuperar a aba no índice %d';
sTabFailGetObject = 'Falha ao inicializar objeto no índice %d ';
sTabFailSet = 'Falha ao ajustar a aba " %s " no índice %d ';
sTabFailSetObject = 'Falha ao ajustar o objeto no índice %d ';
sTabMustBeMultiLine = 'MultiLine deve ser verdadeiro quando TabPosition é tpLeft ou tpRight ';
sInvalidLevel = 'Nível de ítem atribuído inválido';
sInvalidLevelEx = 'Nível inválido (%d) para o item " %s "';
sInvalidIndex = 'Índice inválido';
sInsertError = 'Não é possível introduzir um item';
sInvalidOwner = 'Proprietário Inválido';
sUnableToCreateColumn = 'Não é possível criar nova coluna';
sUnableToCreateItem = 'Não é possível criar novo item';
sRichEditInsertError = 'Erro inserindo linha no RichEdit';
sRichEditLoadFail = 'Falha ao carregar Stream';
sRichEditSaveFail = 'Falha ao salvar Stream';
sTooManyPanels = 'Barra de status não pode ter mais de 64 painéis';
sHKError = 'Erro ao atribuir Hot-Key à %s. %s';
sHKInvalid = 'Hot-Key inválida';dddddddd
sHKInvalidWindow = 'Janela inválida ou Janela filha';
sHKAssigned = 'Hot-Key está atribuída a outra janela';
sUDAssociated = '%s já é associado com %s';
sPageIndexError = '%d é um valor de índice de página inválido. Índice de página deve ser ' +
'entre 0 e %d';
sInvalidComCtl32 = 'Este controle requer COMCTL32.DLL versão 4.70 ou superior';
sDateTimeMax = 'Data excede o valor máximo de %s';
sDateTimeMin = 'Data é menor que o valor mínimo de %s';
sNeedAllowNone = 'Você deve estar em modo de ShowCheckbox para fixar esta data';
sFailSetCalDateTime = 'Falha ao ajustar a data ou a hora do calendário';
sFailSetCalMaxSelRange = 'Falha ao ajustar a escala máxima de seleção';
sFailSetCalMinMaxRange = 'Falha ao ajustar a escala máxima do calendário';
sCalRangeNeedsMultiSelect = 'A escala da data somente pode ser usada no modo multiselect';
sFailsetCalSelRange = 'Falha ao ajustar a escala selecionada do calendário';
implementation
end.
|
unit FreeOTFEExplorerfrmOverwritePrompt;
interface
uses
Classes, Controls, Dialogs, Forms,
ExplorerSettings, Graphics, Messages, SDUForms,
StdCtrls,
SysUtils, Variants, Windows, // Required for TMoveDeletionMethod
ExtCtrls, frmExplorerMain; // Required for TFExplOperation
type
TfrmOverwritePrompt = class (TSDUForm)
Label1: TLabel;
pbOK: TButton;
pbCancel: TButton;
gbMoveDeletionMethod: TRadioGroup;
procedure rbLeaveAloneClick(Sender: TObject);
procedure FormShow(Sender: TObject);
PRIVATE
function GetSelected(): TMoveDeletionMethod;
PUBLIC
procedure EnableDisableControls();
PUBLISHED
property MoveDeletionMethod: TMoveDeletionMethod Read GetSelected;
end;
implementation
{$R *.dfm}
uses
SDUDialogs, SDUGeneral,
SDUi18n;
procedure TfrmOverwritePrompt.EnableDisableControls();
begin
SDUEnableControl(pbOK, (MoveDeletionMethod <> mdmPrompt));
end;
procedure TfrmOverwritePrompt.FormShow(Sender: TObject);
const
DEFAULT_METHOD = mdmDelete;
var
mdm: TMoveDeletionMethod;
idx: Integer;
useIdx: Integer;
begin
// Populate and set move deletion method
gbMoveDeletionMethod.Items.Clear();
idx := -1;
useIdx := -1;
for mdm := low(mdm) to high(mdm) do begin
// Skip the obvious one!
if (mdm = mdmPrompt) then begin
continue;
end;
Inc(idx);
gbMoveDeletionMethod.Items.Add(MoveDeletionMethodTitle(mdm));
if (DEFAULT_METHOD = mdm) then begin
useIdx := idx;
end;
end;
gbMoveDeletionMethod.ItemIndex := useIdx;
EnableDisableControls();
end;
function TfrmOverwritePrompt.GetSelected(): TMoveDeletionMethod;
var
mdm: TMoveDeletionMethod;
begin
// Decode move deletion method
Result := mdmPrompt;
for mdm := low(mdm) to high(mdm) do begin
if (MoveDeletionMethodTitle(mdm) = gbMoveDeletionMethod.Items[gbMoveDeletionMethod.ItemIndex])
then begin
Result := mdm;
break;
end;
end;
end;
procedure TfrmOverwritePrompt.rbLeaveAloneClick(Sender: TObject);
begin
EnableDisableControls();
end;
end.
|
unit cls_appinit;
{$mode objfpc}{$H+}
interface
uses
Forms,
Controls,
fileutil,
Classes,
MainForm,
SysUtils;
type
{ TAppInit }
TAppInit = class
private
public
class function InitializeApp: Boolean;
class function InitializeMainForm(theMainFrm: TFrmMain): Boolean;
end;
implementation
{ TAppInit }
uses
globals,
frm_database,
VD_Conversie,
ps_inifile,
VD_Global,
cls_migrate,
datamodule,
Dialogs;
class function TAppInit.InitializeApp: Boolean;
/// Nested function
function CreateTheDir(aPath: String; aName: String): Boolean;
begin
Result := False;
If Not DirectoryExists(aPath) then
If Not CreateDir(aPath) Then
ShowMessage('Failed to create ' + aName + ' directory !' + sLineBreak +
'Please check permissions')
else
begin
ShowMessage('Created new ' + aName + ' directory');
Result := True
end;
end;
begin
/// Application Initialisation
///---
FmtSettings.DateSeparator := '-';
FmtSettings.ShortDateFormat := 'dd mm yyyy';
FmtSettings.TimeSeparator := ':';
FmtSettings.LongTimeFormat := 'hh:nn';
// De appDataPath is pad naar algemen app data zoals ini files.
// appDataPath moet altijd hetzelfde zijn en niet opgenomen zijn in inifile daar
// zij de lokatie is van de inifile
// Path to database is wat het zegt en kan wel veranderlijk zijn en in inifile
// opgenomen zijn.
// De iniclass plakt automatisch Filename "IniSettings" achter dirPad.
qPathToExeDir := ExtractFilePath(Application.ExeName);
{$IFDEF WINDOWS}
qPathToAppDataDir := pathCombine(pathCombine(GetEnvironmentVariable('localappdata'), cns_WinDataLocation), cns_Apl_SoftwareNm);
CreateTheDir(qPathToAppDataDir, 'Appdata');
If DirectoryExists(qPathToAppDataDir) then
begin
// Niet onder DirectoryExists, kan alsnog niet aanwezig zijn (oude versie bijv)
qPathToIniDir:= pathCombine(qPathToAppDataDir , cns_DataDirIni);
CreateTheDir(qPathToIniDir, 'Inifile');
end;
{$ENDIF}
{$IFDEF LINUX}
qPathToAppDataDir := pathCombine(ExtractFilePath(Application.ExeName ), cns_LinDataLocation);
If Not DirectoryExists(qPathToAppDataDir) then
CreateTheDir(qPathToAppDataDir, 'Appdata');
If DirectoryExists(qPathToAppDataDir) then
begin
// Niet onder DirectoryExists, kan alsnog niet aanwezig zijn (oude versie bijv)
qPathToIniDir:= pathCombine(qPathToAppDataDir , cns_DataDirIni);
CreateTheDir(qPathToIniDir, 'Inifile');
end;
{$ENDIF}
// Om ook componenten de locatie van inifiles mee te geven.
gPathToIniDir := qPathToIniDir;
qIniPropStorage := TPsIniClass.Create(qPathToIniDir);
// Kijk in ini of er alternatieve databasepad is
qPathToDataBaseFile := qIniPropStorage.ReadIniString(cns_Ini_DataBasePath, EmptyStr);
if qPathToDataBaseFile = EmptyStr then
begin
{$IFDEF LINUX}
if qUseStndDataBase then
begin
qPathToDataBaseFile := pathCombine(cns_LinDefDataLocation, cns_DataBaseNm);
qPathToDataBaseDir := cns_LinDefDataLocation;
qIniPropStorage.WriteIniString(cns_Ini_DataBasePath, qPathToDataBaseFile);
end
else
begin
{$ENDIF}
qPathToDataBaseDir := pathCombine(qPathToAppDataDir, cns_DataDirDatabase);
{$IFDEF LINUX}
end;
{$ENDIF}
CreateTheDir(qPathToDataBaseDir, 'DataBase');
If DirectoryExists(qPathToDataBaseDir) then
begin
qPathToDataBaseFile := pathCombine( qPathToDataBaseDir, cns_DataBaseNm);
end;
end
else
begin
/// Is nog niet geinitieerd als qPathToDataBaseFile als bestond
qPathToDataBaseDir := ExtractFileDir(qPathToDataBaseFile);
end;
/// (Moet hier geplaatst worden als niet bestaat)
qPathToRepoDir := qIniPropStorage.ReadIniString(cns_Ini_PathToRepoDir, EmptyStr);
/// Wanneer Repo niet bestaat, onder database dir plaatsen
if qPathToRepoDir = emptyStr then
begin
qPathToRepoDir := pathCombine( qPathToDataBaseDir, cns_DataDirRepo);
/// Gelijk wegschrijven anders komt hij hier opnieuw (zie check hierboven)
qIniPropStorage.WriteIniString(cns_Ini_PathToRepoDir, qPathToRepoDir);
CreateTheDir(qPathToRepoDir, 'Repo Dir');
end
else
begin
If not DirectoryExists(qPathToRepoDir) then
begin
ShowMessage('The directory to the file-Repo, that is set in the program, does not exist' + #13 +
'The repo directory is currently set to:' + #13 + qPathToRepoDir + #13 +
'Please reset the repo file directory in the settings form (inifile settings)');
/// We kunnen hier nog de settings file openen.
/// We kunnen ook een dialog openen die ini waarde wist zodat bij volgende opstart de defaults voor de repo aangemaakt worden
end;
end;
/// Let op:
/// Tot hier zijn paden aangemaakt maar geen files gechecked of gecopieerd.
/// Ook zijn tot hier alle pad strings juist gezet
if not FileExists(qPathToDataBaseFile) then
if MessageDlg('Question', 'There does not seem to be a database file,' + sLineBreak +
' do you want to copy a empty database?' + sLineBreak +
' Be sure not to overwrite an existing database' + sLineBreak +
'When Choosing No please use SETTINS=>DATABASE' + sLineBreak +
' to choose a valid database file' , mtConfirmation,
[mbYes, mbNo],0) = mrYes then
begin
if CopyFile( pathCombine(pathCombine(ExtractFilePath(Application.ExeName ),
cns_DataDirDatabase), cns_DataBaseNm), qPathToDataBaseFile) then
ShowMessage('Copying of the databasefile was succesfull')
else
begin
ShowMessage('Copying of the databasefile was unsuccesfull');
qInd_ProblDataBase := true;
end;
end
else
qInd_ProblDataBase := true;
///---
Result := true;
/// Haal migratiegetal op
/// Is 0 als nog leeg
qCurrAppMigration := qIniPropStorage.ReadIniInteger(cns_Ini_CurrAppMigration);
/// Afhandeling userdatabase
if cns_PrgmPar_UserDb then
begin
qPathToUserDataBaseFile := qIniPropStorage.ReadIniString(cns_Ini_UserDataBasePath, EmptyStr);
if qPathToUserDataBaseFile = EmptyStr then
begin
ShowMessage('No user databasefile defined' + #13 + 'Please define a user database after te program has started');
end;
end;
end;
/// Wordt aangeroepen in de Create van de Main Form
class function TAppInit.InitializeMainForm(theMainFrm: TFrmMain): Boolean;
begin
Result := True;
theMainFrm.Caption := cns_Apl_MainFrmCaption + 'Vrs: ' + cns_Apl_Version + ' - ' + cns_OS;
/// Probeer de MainDataModule te laden
try
// Let op: moet gebeuren na qPathToDb ingevuld is.
if not qInd_ProblDataBase then
begin
MainDataMod := TDatModMain.Create(nil) ;
/// Check of er nog migraties zijn
TAppMigrate.SelectMigration;
/// Open de Queries
MainDataMod.InitTables;
end
else
begin
ShowMessage('Go to the database form in settings to set the right database path');
TfrmDataBase.ShowForm;
theMainFrm.statbrMain.SimpleText := 'Warning: Application is not connected to a database';
end;
Except
ShowMessage('Something went Wrong opening the database');
theMainFrm.statbrMain.SimpleText := 'Warning: Application is not connected to a database';
qInd_ProblDataBase := true;
end;
end;
end.
|
Unit GameIO;
Interface
Uses Crt,TicTac;
Type { Define types for parameters }
CharSet = Set of Char;
MsgStr = String[80];
Procedure DisplayGame(TheGame:Game);
Procedure DrawGrid;
Procedure ReadChar(VAr Ch : Char; Prompt : MsgStr; OKSet : CharSet);
Procedure ReadInt(Var Val : Integer;
Prompt : MsgStr;
Low,High: Integer);
Implementation
Const
BoardX = 10; { Positioning the TicTacToe Grid }
BoardY = 10;
Bar = #186; { Special Characters used for Grid }
Line = #205;
Cross = #206;
Procedure DrawGrid;
{ Purpose Draws full-sized tictactoe Grid,
with smaller numbered one beside it
Pre Screen has been cleared
Post Two grids drawn on screen }
Procedure DrawHorz(X,Y : Integer);
{ Purpose Draws horizontal bar for tictactoe grid
Pre X <= 63, Y <= 23
Post Bar is written to screen }
Begin
GoToXY(X,Y);
Write(Line,Line,Line,Line,Line,Cross);
Write(Line,Line,Line,Line,Line,Cross);
Write(Line,Line,Line,Line,Line);
End; { Procedure DrawHorz }
Procedure DrawVert(X,Y:Integer);
{ Purpose Draws vertical bars for tictactoe grid
Pre X <= 78, Y <= 16
Post Vertical Bar appears on screen(with gaps for crosses) }
Var
J,I:Integer;
Begin
For J := 1 to 3 Do Begin
For I := 0 to 2 Do Begin
GotoXY(X,Y+1);Write(Bar);
End;
Y := Y + 4;
End;
End; { Procedure DrawVert }
Procedure DrawMoves(X,Y: Integer);
{ Purpose Draws 3 x 3 Grid with numbered positions
Pre x <= 77, Y <= 21
Post 3 x 3 Grid Drawn on screen }
Begin
GoToXY(X,Y); Write('1',Bar,'2',Bar,'3');
GoToXY(X,Y+1); Write(Line,Cross,Line,Cross,Line);
GoToXY(X,Y+2); Write('4',Bar,'5',Bar,'6');
GoToXY(X,Y+3); Write(Line,Cross,Line,Cross,Line);
GoToXY(X,Y+4); Write('7',Bar,'8',Bar,'9');
End; { Procedure DrawMoves }
Begin
DrawHorz(BoardX,BoardY);
DrawHorz(BoardX,BoardY+4);
DrawVert(BoardX+5,BoardY-3);
DrawVert(BoardX+11,BoardY-3);
DrawMoves(BoardX+20,BoardY);
End; { Procedure DrawGrid }
Procedure DisplayGame(TheGame:Game);
{ Purpose Draws Status of TicTacToe Game on screen
Pre Grid has already been drawn on screen
Post Contents of each grid location are displayed }
Var
I,Col,Row : Integer;
M : Move;
Begin
For I := 1 to Glim Do Begin
M := GetLoc(TheGame,I);
Col := BoardX +2 +6 * ((I-1)mod 3);
Row := BoardY -2 +4 * ((I-1)div 3);
GoToXY(Col,Row);
Case M Of
Blank : Write(' ');
X : Write('X');
O : Write('O');
End;
End;
End; { Procedure DisplayGame }
Procedure ReadChar(Var Ch : Char;Prompt:MsgStr;OKSet:CharSet);
{ Purpose Prompt for and get one character of a given set
Pre OkSet is not-empty and contains valid uppercase
characters (including digits, punctuation, etc..)
Post ReadChar() returns some character contained in OkSet }
Begin
GoToXY(1,1); ClrEol;
Write(Prompt);
Repeat
Ch := UpCase(ReadKey);
Until Ch in OkSet;
Write(Ch);
End; { Procedure ReadChar }
Procedure ReadInt(Var Val : Integer;
Prompt : MsgStr;
Low,High: Integer);
{ Purpose Prompt for and get an integer value in a given range
Pre Low <= High
Post ReadInt() Returns some value in the range Low..High }
Begin
{$I-}
Repeat
GoToXY(1,1); ClrEol;
Write(Prompt,' (',Low,',',High,'): ');
Readln(Val);
Until (IOResult = 0) and (VAl >= Low) and (Val <= High);
{$I+}
End; { Procedure ReadInt }
End. { Unit GameIO } |
unit EngineClasses;
interface
uses
ExtCtrls, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms, Dialogs, Math, StdCtrls, pngimage, EngineAnimations, EngineUI,
EngineFileInterpreter;
type
TLineAddTrigger = function(const s : string):integer of object;
TDebug = class(TMemo)
published
constructor Create(AOwner:TComponent);override;
public
println : TLineAddTrigger;
end;
TForward = procedure(ASquare : Pointer) of object;
TSquare = class(TImage)
private
FCords: TPoint;
FDebug: TDebug;
FForwardClick: TForward;
FKind: integer;
FColor: integer;
FPreKind: integer;
procedure SetCords(const Value: TPoint);
procedure Click(Sender:TObject);
procedure SetForwardClick(const Value: TForward);
procedure SetKind(const Value: integer);
procedure SetColor(const Value: integer);
procedure SetPreKind(const Value: integer);
published
constructor Create(AOwner : TComponent); override;
property Cords : TPoint read FCords write SetCords;
property PreKind : integer read FPreKind write SetPreKind;
property Kind : integer read FKind write SetKind;
property Color : integer read FColor write SetColor;
property ForwardClick : TForward read FForwardClick write SetForwardClick;
end;
TBoard = array[1..8] of array[1..8] of TSquare;
//Create the pointers to memory of objects to use in TBoardMannager
PDW = ^DWORD;
PSQR = ^TSquare;
TIntArray = array of integer;
TBoardMannager = class //Manager misspelt but will not fix due to amount of references in code.
private
FDebug: TDebug;
Fhorse: TBitmap;
Fpawn: TBitmap;
Fknight: TBitmap;
Fking: TBitmap;
Fqueen: TBitmap;
Fbishop: TBitmap;
FSelected: boolean;
FSelectedSqr: TSquare;
FTurn: integer;
InCheck : boolean;
FWhitePiecesTook: array of integer;
FBlackPiecesTook: array of integer;
FOrientation: Integer;
FAutoDeselect: boolean;
FOutlineColor: TColor;
FBlackColor: TColor;
FWhiteColor: TColor;
FPlayerNameWhite: string;
FPlayerNameBlack: string;
procedure SetDebug(const Value: TDebug);
procedure Setbishop(const Value: TBitmap);
procedure Sethorse(const Value: TBitmap);
procedure Setking(const Value: TBitmap);
procedure Setknight(const Value: TBitmap);
procedure Setpawn(const Value: TBitmap);
procedure Setqueen(const Value: TBitmap);
procedure SetSelected(const Value: boolean);
procedure SetSelectedSqr(const Value: TSquare);
procedure SetTurn(const Value: integer);
function GetBlackPiecesTook(index:integer):integer;
function GetWhitePiecesTook(index:integer):integer;
procedure SetBlackPiecesTook(Index: Integer; Value: Integer);
procedure SetWhitePiecesTook(Index: Integer; Value: Integer);
function Move(ASquare: TSquare; Abm : TBitmap) : integer; //MOVE!!!
procedure TakePiece(ASquare: TSquare; Abm : TBitmap);
procedure SetOrientation(const Value: Integer);
procedure SetAutoDeselect(const Value: boolean);
procedure SetBlackColor(const Value: TColor);
procedure SetOutlineColor(const Value: TColor);
procedure SetWhiteColor(const Value: TColor);
procedure SetPlayerNameBlack(const Value: string);
procedure SetPlayerNameWhite(const Value: string);
published
constructor create(AOwner : TForm);
destructor destroy;
property Debug : TDebug read FDebug write SetDebug;
procedure Click(ASquare : Pointer); //THE ALGORITHM
procedure InitialDraw;
procedure DrawBoard;
property AutoDeselect : boolean read FAutoDeselect write SetAutoDeselect;
property pawn : TBitmap read Fpawn write Setpawn;
property king : TBitmap read Fking write Setking;
property castle : TBitmap read Fknight write Setknight;
property queen : TBitmap read Fqueen write Setqueen;
property bishop : TBitmap read Fbishop write Setbishop;
property horse : TBitmap read Fhorse write Sethorse;
property Selected : boolean read FSelected write SetSelected;
property SelectedSqr : TSquare read FSelectedSqr write SetSelectedSqr;
property Orientation : Integer read FOrientation write SetOrientation;
property Turn : integer read FTurn write SetTurn;
property WhiteColor : TColor read FWhiteColor write SetWhiteColor;
property BlackColor : TColor read FBlackColor write SetBlackColor;
property OutlineColor : TColor read FOutlineColor write SetOutlineColor;
property PlayerNameWhite : string read FPlayerNameWhite write SetPlayerNameWhite;
property PlayerNameBlack : string read FPlayerNameBlack write SetPlayerNameBlack;
function getLastSquareLeft : integer;
function getSquareHeightWidth : integer;
function getBlackTookLength : integer;
function getWhiteTookLength : integer;
procedure Clear;
procedure InvalidMove;
procedure SetSquareTo(Location : TPoint; kind : integer);
public
Board : TBoard;
CastlingPossible : array[1..2] of boolean;
property WhitePiecesTook[Index:integer] : integer read GetWhitePiecesTook write SetWhitePiecesTook;
property BlackPiecesTook[Index:integer] : integer read GetBlackPiecesTook write SetBlackPiecesTook;
function CheckDetect : byte; overload;//Check if the king is currently in check
function CheckDetect(APoint: TPoint; multiplier : integer) : boolean; overload; //Check if the king will be in check at APoint;
end;
TSaveManager = class
private
FrootDir: string;
FLinkedBoard: TBoardMannager;
procedure SetLinkedBoard(const Value: TBoardMannager);
procedure SetrootDir(const Value: string);
published
constructor Create(AOwner:TObject);
property LinkedBoard : TBoardMannager read FLinkedBoard write SetLinkedBoard;
property rootDir : string read FrootDir write SetrootDir;
procedure SaveRequest;
procedure SaveToFile(filepath : string);
procedure SaveToFileOverwrite(filepath : string);
procedure LoadRequest;
procedure LoadFromFile(filepath : string);
end;
//procedure ShowSettingsUI(Sender: TWinControl; Manager : TBoardMannager);
var
imageSize : integer = 32; //Default to 32px
gameWidth, gameHeight : integer;
const
nl = #13#10;
orRight_Left = 1;
orTop_Bottom = 2;
implementation
{ TSquare }
procedure TSquare.Click(Sender: TObject);
begin
ForwardClick(Self);
end;
constructor TSquare.Create(AOwner: TComponent);
begin
inherited;
stretch := True;
Height := floor(gameHeight/8);
Width := height;
if AOwner IS TForm then
parent := TForm(AOwner);
kind := 0;
color := 0;
OnClick := Click;
end;
procedure TSquare.SetColor(const Value: integer);
begin
FColor := Value;
end;
procedure TSquare.SetCords(const Value: TPoint);
begin
FCords := Value;
end;
procedure TSquare.SetForwardClick(const Value: TForward);
begin
FForwardClick := Value;
end;
procedure TSquare.SetKind(const Value: integer);
begin
PreKind := FKind;
FKind := Value;
end;
procedure TSquare.SetPreKind(const Value: integer);
begin
FPreKind := Value;
end;
{ TDebug }
constructor TDebug.Create(AOwner: TComponent);
begin
inherited;
if AOwner IS TForm then
parent := TForm(AOwner);
lines.Clear;
width := floor(gamewidth/2) - floor((gamewidth/8) * 2.25);
height := floor((gameheight/8)*2);
top := gameHeight - height;
println := lines.Add;//This is used to shorten the code (and I am used to c++)
ReadOnly := true;
Enabled := false;
end;
{ TBoardMannager }
function TBoardMannager.CheckDetect: byte;
var
blackCords, whiteCords, searchCords, search : TPoint;
x: Integer;
y: Integer;
i, i2: integer;
multiplier : integer;
bExit : boolean;
//Var used for pawn detect
pawn1, pawn2 : TPoint;
horseLocation : array[1..8] of TPoint;
begin
result := 0;
//Find the kings!
for x := 1 to 8 do
for y := 1 to 8 do
if (Board[x,y].Kind = -6) then
blackCords := Point(x, y)
else if Board[x,y].Kind = 6 then
whiteCords := Point(x, y);
for i := 1 to 2 do // Check both colors
begin
if i = 1 then
begin
searchCords := whiteCords;
multiplier := -1;
end
else
begin
searchCords := blackCords;
multiplier := 1;
end;
//Clear the varibles
bExit := false;
search := searchCords;
//45 Deg up right
while (search.x + 1 < 9) AND (search.y - 1 > 0) AND (NOT bExit) do
begin
inc(search.x);
dec(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or (Board[search.x, search.y].Kind = 3 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := true;
end; // End While (search.x < 9) AND (search.y > 0)
bExit := false;
search := searchCords;
//45 Deg Down Rigth
while (search.x + 1 < 9) AND (search.y + 1 < 9) AND (NOT bExit) do
begin
inc(search.x);
inc(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or (Board[search.x, search.y].Kind = 3 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := true;
end; // End While (search.x + 1 < 9) AND (search.y + 1 < 9)
bExit := false;
search := searchCords;
//45 Deg up left
while (search.x - 1 > 0) AND (search.y - 1 > 0) AND (NOT bExit) do
begin
dec(search.x);
dec(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or (Board[search.x, search.y].Kind = 3 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := true;
end; // End While (search.x < 9) AND (search.y > 0)
bExit := false;
search := searchCords;
while (search.x - 1 > 0 ) AND (search.y + 1 < 9) AND (NOT bExit) do
begin
dec(search.x);
inc(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or (Board[search.x, search.y].Kind = 3 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := true;
end; // End While (search.x < 9) AND (search.y > 0)
bExit := false;
search := searchCords;
while (search.X - 1 > 0) AND (NOT bExit) do
begin
dec(search.x);
if (Board[search.x, search.y].Kind = 5 * multiplier) or (Board[search.x, search.y].Kind = 2 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := true;
end;
bExit := false;
search := searchCords;
while (search.X + 1 < 9) AND (NOT bExit) do
begin
inc(search.x);
if (Board[search.x, search.y].Kind = 5 * multiplier) or (Board[search.x, search.y].Kind = 2 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := true;
end;
bExit := false;
search := searchCords;
while (search.Y - 1 > 0) AND (NOT bExit) do
begin
dec(search.Y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or (Board[search.x, search.y].Kind = 2 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := true;
end;
bExit := false;
search := searchCords;
while (search.Y + 1 < 9) AND (NOT bExit) do
begin
inc(search.Y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or (Board[search.x, search.y].Kind = 2 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := true;
end;
bExit := false;
search := searchCords;
//SPESIFIC BLOCK CHECKS
//Pawns: Only 1 block infront to right or left!
if (search.X > 1) AND (search.X < 8) then //2 to 7
begin
pawn1 := Point(search.X - 1, search.Y + multiplier);
pawn2 := Point(search.X + 1, search.Y + multiplier);
end
else if NOT (search.X < 8) then
begin
pawn1 := Point(search.X - 1, search.Y + multiplier);
pawn2 := pawn1; //Do not check other side as the king is against it
end
else if NOT (search.X > 1) then
begin
pawn2 := Point(search.X + 1, search.Y + multiplier);
pawn1 := Pawn2;
end;
if (board[Pawn1.X, Pawn1.Y].Kind = 1 * multiplier) OR
(board[Pawn2.X, Pawn2.Y].Kind = 1 * multiplier) then
result := i;
//Horses
{
1# 2#
3# 4#
k*
5# 6#
7# 8#
}
horseLocation[1] := point(search.X - 1, search.Y - 2);
horseLocation[2] := point(search.X + 1, search.Y - 2);
horseLocation[3] := point(search.X - 2, search.Y - 1);
horseLocation[4] := point(search.X + 2, search.Y - 1);
horseLocation[5] := point(search.X - 2, search.Y + 1);
horseLocation[6] := point(search.X + 2, search.Y + 1);
horseLocation[7] := point(search.X - 1, search.Y + 2);
horseLocation[8] := point(search.X + 1, search.Y + 2);
for i2 := 1 to 8 do
begin
if (horseLocation[i2].X IN [1..8]) AND (horseLocation[i2].Y IN [1..8]) then
if board[horselocation[i2].x,horselocation[i2].Y].kind = 4 * multiplier then
result := i;
end;
end; // end for check both colors
end;
function TBoardMannager.CheckDetect(APoint: TPoint; multiplier : integer): boolean;
var
searchCords, search : TPoint;
x: Integer;
y: Integer;
i2: integer;
bExit : boolean;
//Var used for pawn detect
pawn1, pawn2 : TPoint;
horseLocation : array[1..8] of TPoint;
const
i = true;
begin
result := false;
searchCords := APoint;
// Clear the varibles
bExit := false;
search := searchCords;
// 45 Deg up right
while (search.x + 1 < 9) AND (search.y - 1 > 0) AND (NOT bExit) do
begin
inc(search.x);
dec(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or
(Board[search.x, search.y].Kind = 3 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := True;
end; // End While (search.x < 9) AND (search.y > 0)
bExit := false;
search := searchCords;
// 45 Deg Down Rigth
while (search.x + 1 < 9) AND (search.y + 1 < 9) AND (NOT bExit) do
begin
inc(search.x);
inc(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or
(Board[search.x, search.y].Kind = 3 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := True;
end; // End While (search.x + 1 < 9) AND (search.y + 1 < 9)
bExit := false;
search := searchCords;
// 45 Deg up left
while (search.x - 1 > 0) AND (search.y - 1 > 0) AND (NOT bExit) do
begin
dec(search.x);
dec(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or
(Board[search.x, search.y].Kind = 3 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := True;
end; // End While (search.x < 9) AND (search.y > 0)
bExit := false;
search := searchCords;
while (search.x - 1 > 0) AND (search.y + 1 < 9) AND (NOT bExit) do
begin
dec(search.x);
inc(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or
(Board[search.x, search.y].Kind = 3 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := True;
end; // End While (search.x < 9) AND (search.y > 0)
bExit := false;
search := searchCords;
while (search.x - 1 > 0) AND (NOT bExit) do
begin
dec(search.x);
if (Board[search.x, search.y].Kind = 5 * multiplier) or
(Board[search.x, search.y].Kind = 2 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := True;
end;
bExit := false;
search := searchCords;
while (search.x + 1 < 9) AND (NOT bExit) do
begin
inc(search.x);
if (Board[search.x, search.y].Kind = 5 * multiplier) or
(Board[search.x, search.y].Kind = 2 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := True;
end;
bExit := false;
search := searchCords;
while (search.y - 1 > 0) AND (NOT bExit) do
begin
dec(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or
(Board[search.x, search.y].Kind = 2 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := True;
end;
bExit := false;
search := searchCords;
while (search.y + 1 < 9) AND (NOT bExit) do
begin
inc(search.y);
if (Board[search.x, search.y].Kind = 5 * multiplier) or
(Board[search.x, search.y].Kind = 2 * multiplier) then
result := i
else if Board[search.x, search.y].Kind <> 0 then
bExit := True;
end;
bExit := false;
search := searchCords;
// SPESIFIC BLOCK CHECKS
// Pawns: Only 1 block infront to right or left!
if (search.x > 1) AND (search.x < 8) then // 2 to 7
begin
pawn1 := Point(search.x - 1, search.y + multiplier);
pawn2 := Point(search.x + 1, search.y + multiplier);
end
else if NOT(search.x < 8) then
begin
pawn1 := Point(search.x - 1, search.y + multiplier);
pawn2 := pawn1; // Do not check other side as the king is against it
end
else if NOT(search.x > 1) then
begin
pawn2 := Point(search.x + 1, search.y + multiplier);
pawn1 := pawn2;
end;
if (Board[pawn1.x, pawn1.y].Kind = 1 * multiplier) OR
(Board[pawn2.x, pawn2.y].Kind = 1 * multiplier) then
result := i;
// Horses
horseLocation[1] := Point(search.x - 1, search.y - 2);
horseLocation[2] := Point(search.x + 1, search.y - 2);
horseLocation[3] := Point(search.x - 2, search.y - 1);
horseLocation[4] := Point(search.x + 2, search.y - 1);
horseLocation[5] := Point(search.x - 2, search.y + 1);
horseLocation[6] := Point(search.x + 2, search.y + 1);
horseLocation[7] := Point(search.x - 1, search.y + 2);
horseLocation[8] := Point(search.x + 1, search.y + 2);
for i2 := 1 to 8 do
begin
if (horseLocation[i2].x IN [1 .. 8]) AND (horseLocation[i2].y IN [1 .. 8])
then
if Board[horseLocation[i2].x,
horseLocation[i2].y].Kind = 4 * multiplier then
result := i;
end;
end;
procedure TBoardMannager.Clear;
var
y, x, i: Integer;
t1, t2 : integer;
begin
t1 := GetTickCount;
selected := false;
//clear the arrays
for I := 0 to getBlackTooklength do
FBlackPiecesTook[i] := 0;
for I := 0 to getWhiteTookLength do
FWhitePiecesTook[i] := 0;
SetLength(fwhitePiecesTook, 1);
SetLength(fblackPiecesTook, 1);
turn := 1;
//Clear the Kinds
for y := 1 to 8 do
for x := 1 to 8 do
with Board[x, y] do
Kind := 0;
t2 := GetTickCount;
Debug.lines.Clear;
Debug.println('Cleared board in: ' + Inttostr(t2 - t1) + ' miliseconds');
end;
procedure TBoardMannager.Click(ASquare: Pointer);
var
Square : TSquare;
sDebugMSG : string;
difInY, difInX:integer;
//var for pawns
difPawnForward, difPawnSide : integer;
bm: TBitmap;
x,y:integer;
pbase, p : PDW;
xMultiplier, yMin, yMax, newKind : integer;
I: Integer; //general use int var
//var for king check
startcheckX, endcheckx, startchecky, endchecky: integer;
possibleCastling : boolean;
presquareKind : integer;
begin
InCheck := false; //Prevents check movement loop
bm := TBitmap.Create;
with bm do
begin
PixelFormat := pf32bit;
height := 1;
width := 1;
end;
Square := TSquare(ASquare);
sDebugMSG := 'Clicked On: X:' + IntToStr(Square.Cords.X) + ' Y:' + IntToStr(Square.Cords.Y);
debug.println(sDebugMSG + nl);
if NOT Selected then
begin
case Square.Color of
1:
debug.println('The block is black');
2:
debug.println('The block is white');
end;
if Square.Kind = 0 then
debug.println('Not Occupied')
else if ((square.Kind >= -6) OR (square.Kind <= -1)) OR (square.Kind IN [1..6]) then
debug.println('Occupation is ' + IntToStr(square.Kind))
else
debug.println('Invalid Occupation (' + IntToStr(square.Kind) + ')');
if ((Square.Kind IN [1 .. 6]) AND (Turn = 1)) then
begin
Selected := True;
SelectedSqr := Square;
debug.println('Piece Selected!');
Turn := 2;
end
else if (((Square.Kind >= -6) AND (Square.Kind < 0)) AND (Turn = 2)) then
begin
Selected := True;
SelectedSqr := Square;
debug.println('Piece Selected');
Turn := 1;
end
else if Square.Kind = 0 then
debug.println('Not Selected')
else
debug.println('Invalid kind it is not your turn! It is turn: ' + inttostr(turn) + nl);
end //End of not selected
else //start of check;
begin
difInY := Square.Cords.Y - SelectedSqr.Cords.Y;
difInX := Square.Cords.X - SelectedSqr.Cords.X;
case SelectedSqr.Color of
1:
bm.Canvas.Pixels[0, 0] := $0;
2:
bm.Canvas.Pixels[0, 0] := $FFFFFF;
end;
//Check what color
case selectedsqr.kind of
-6..-1:
begin
xMultiplier := -1;
yMax := 6;
yMin := 1;
newKind := Selectedsqr.Kind;
end;
1..6:
begin
xMultiplier := 1;
yMax := -1;
yMin := -6;
newKind := Selectedsqr.Kind;
end;
end;
case SelectedSqr.Kind of
1, -1: //Pawns
begin
case Orientation of
orRight_Left:
begin
difPawnForward := difInX;
difPawnSide := difInY;
end;
orTop_Bottom:
begin
difPawnForward := -difInY;
difPawnSide := -difInX;
end;
end;
if difPawnForward = (1 * xMultiplier) then
begin
if (Square.Kind <> 0) AND (difPawnSide = 0) then
begin
invalidmove;
Exit;
end;
if (difPawnSide = 0) then
begin
move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
exit;
end;
if difPawnSide <> 0 then
if (difPawnSide = 1) or (difPawnSide = -1) then
begin
if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
// Get person
takepiece(square, bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTakePawn(square.Cords, selectedsqr.cords, square.kind);
exit;
end
else
begin
invalidmove;
Exit;
end;
end
else
begin
invalidmove;
Exit;
end;
end
else if (difPawnForward = (2*xMultiplier)) AND
(board[square.cords.x, square.cords.y + (1 * xMultiplier)].Kind = 0) AND
((selectedsqr.Cords.Y = 7)or(selectedsqr.Cords.Y = 2)) then
begin
if (difPawnSide = 0) then
begin
move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
exit;
end;
end
else
begin
invalidmove;
Exit;
end;
end;
2, -2: // Catles / Rooks
begin
if (difInY <> 0) and (difInX <> 0) then
begin
invalidmove;
Exit;
end
else if difInY <> 0 then
begin
if difInY < 0 then
for I := Square.Cords.y + 1 to SelectedSqr.Cords.y - 1 do
begin
if Board[Square.Cords.x, I].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end
else if difInY > 0 then
for I := SelectedSqr.Cords.y + 1 to Square.Cords.y - 1 do
begin
if Board[Square.Cords.x, I].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end;
if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
takepiece(square, bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
castlingPossible[turn] := false;
exit;
end
else if Square.Kind = 0 then
begin
move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
castlingPossible[turn] := false;
exit;
end
else
begin
invalidmove;
Exit;
end;
end
else if difInX <> 0 then
begin
if difInX < 0 then
for I := Square.Cords.X + 1 to SelectedSqr.Cords.X - 1 do
begin
if Board[I, square.Cords.y].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end
else if difInX > 0 then
for I := SelectedSqr.Cords.X + 1 to Square.Cords.X - 1 do
begin
if Board[I, square.Cords.y].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end;
if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
takepiece(square,bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
castlingPossible[turn] := false;
exit;
end
else if Square.Kind = 0 then
begin
move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
castlingPossible[turn] := false;
exit;
end
else
begin
invalidmove;
Exit;
end;
end;
end;
//bishops
3, -3:
begin
if difInX > 0 then
begin
if (difInY = difInX) or (difInY = -difInX) then
begin
i := 0;
for x := SelectedSqr.Cords.x + 1 to Square.Cords.x - 1 do
begin
inc(i);
if difInY = difInX then
y := SelectedSqr.Cords.y + i
else
y := SelectedSqr.Cords.y - i;
if Board[x, y].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end;
if Square.Kind = 0 then
begin
move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
exit;
end;
if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
takepiece(square, bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
exit;
end
else
begin
invalidmove;
Exit;
end;
end
else
begin
invalidmove;
Exit;
end;
end
else if difInX < 0 then
begin
if (difInY = difInX) or (difInY = -difInX) then
begin
i := 0;
for x := SelectedSqr.Cords.x - 1 downto Square.Cords.x + 1 do
begin
dec(i);
if difInY = difInX then
y := SelectedSqr.Cords.y + i
else
y := SelectedSqr.Cords.y - i;
if Board[x, y].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end;
if Square.Kind = 0 then
begin
move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
exit;
end;
if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
takepiece(square, bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
exit;
end
else
begin
invalidmove;
Exit;
end;
end
else
begin
invalidmove;
Exit;
end;
end
else
begin
invalidmove;
Exit;
end;
end;
//Horses / Knights
4, -4:
begin
if (((difInX = 2) or (difInX = -2)) and ((difInY = 1) or (difInY = -1)))
or (((difInY = 2) or (difInY = -2)) and ((difInX = 1) or (difInX = -1))) then
begin
if Square.Kind = 0 then
begin
move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
exit;
end
else if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
takepiece(square,bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
exit;
end
else
begin
invalidmove;
Exit;
end;
end
else
begin
invalidmove;
Exit;
end;
end; // End of horse check.
// Queen
5, -5:
begin
if (difInY = difInX) or (difInY = -difInX) then
begin
if difInX > 0 then
begin
i := 0;
for x := SelectedSqr.Cords.x + 1 to Square.Cords.x - 1 do
begin
inc(i);
if difInY = difInX then
y := SelectedSqr.Cords.y + i
else
y := SelectedSqr.Cords.y - i;
if Board[x, y].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end;
if Square.Kind = 0 then
begin
Move(Square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
Exit;
end;
if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
TakePiece(Square, bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
Exit;
end
else
begin
invalidmove;
Exit;
end;
end
else if difInX < 0 then
begin
i := 0;
for x := SelectedSqr.Cords.x - 1 downto Square.Cords.x + 1 do
begin
dec(i);
if difInY = difInX then
y := SelectedSqr.Cords.y + i
else
y := SelectedSqr.Cords.y - i;
if Board[x, y].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end;
if Square.Kind = 0 then
begin
Move(Square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
Exit;
end;
if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
TakePiece(Square, bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
Exit;
end
else
begin
invalidmove;
Exit;
end;
end
else
begin
invalidmove;
Exit;
end;
end
else if (difInY <> 0) and (difinx = 0) then //accros
begin
if difInY < 0 then
for I := Square.Cords.y + 1 to SelectedSqr.Cords.y - 1 do
begin
if Board[Square.Cords.x, I].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end
else if difInY > 0 then
for I := SelectedSqr.Cords.y + 1 to Square.Cords.y - 1 do
begin
if Board[Square.Cords.x, I].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end;
if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
takepiece(square,bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
exit;
end
else if Square.Kind = 0 then
begin
move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
exit;
end
else
begin
invalidmove;
Exit;
end;
end
else if (difInX <> 0) and (difiny = 0) then
begin
if difInX < 0 then
for I := Square.Cords.X + 1 to SelectedSqr.Cords.X - 1 do
begin
if Board[I, square.Cords.y].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end
else if difInX > 0 then
for I := SelectedSqr.Cords.X + 1 to Square.Cords.X - 1 do
begin
if Board[I, square.Cords.y].Kind <> 0 then
begin
invalidmove;
Exit;
end;
end;
if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
takepiece(square,bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
exit;
end
else if Square.Kind = 0 then
begin
move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
exit;
end
else
begin
invalidmove;
Exit;
end;
end
else
begin
invalidmove;
Exit;
end;
end;//End of queen check
//King
6, -6:
begin
if ((difInX < 2) AND (difInX > -2)) AND ((difInY < 2) AND (difInY > -2)) then
begin
startcheckX := square.Cords.X - 1;
if startcheckX < 1 then
startcheckx := 1;
endcheckX := square.Cords.X + 1;
if endcheckX > 8 then
endcheckx := 8;
startcheckY := square.Cords.Y - 1;
if startcheckY < 1 then
startcheckY := 1;
endcheckY := square.Cords.Y + 1;
if endcheckY > 8 then
endcheckY := 8;
for y := startcheckY to endcheckY do
for x := startcheckX to endcheckX do
begin
//Check to see if the king can move
if board[x,y].Kind = selectedsqr.kind * -1 then
begin
Debug.println('Invalid Move - King in range');
beep;
Exit;
end;
end;//end of for loop check
//If not exit!!
if square.Kind = 0 then
begin
Move(square, bm);
PGNPlotPointMove(square.Cords, selectedsqr.Cords, square.kind);
castlingPossible[turn] := false;
exit;
end
else if (Square.Kind >= yMin) AND (Square.Kind <= yMax) then
begin
takepiece(square,bm);
if not ((Square.Kind >= yMin) AND (Square.Kind <= yMax)) then
PGNPlotPointTake(square.Cords, selectedsqr.Cords, square.kind);
castlingPossible[turn] := false;
exit;
end
else
begin
invalidmove;
Exit;
end;
end
else if ((((difInX > 1) or (difinx < -1)) and (Orientation = orTop_Bottom)) and ((square.Kind = 0) AND (castlingpossible[turn]))) then
begin
possibleCastling := false;
///
if ((board[8, square.Cords.y].kind = 2 * xmultiplier)) then
possibleCastling := true;
if square.Cords.X = 7 then
if ((board[8, square.Cords.y].kind = 2 * xmultiplier)) then
possibleCastling := true
else if square.Cords.X = 2 then
if (board[1, square.Cords.y].Kind = 2 * xmultiplier) then
possibleCastling := true;
//
if possibleCastling then
if SelectedSqr.Cords.x < Square.Cords.x then
begin
for i := SelectedSqr.Cords.x + 1 to Square.Cords.x - 1 do
if Board[i, Square.Cords.y].Kind <> 0 then
begin
possibleCastling := false;
end;
end
else
for i := SelectedSqr.Cords.x - 1 downto Square.Cords.x + 1 do
if Board[i, Square.Cords.y].Kind <> 0 then
begin
possibleCastling := false;
end;
if possibleCastling then
begin
if SelectedSqr.Cords.x < Square.Cords.x then //King side
if CheckDetect(Point(SelectedSqr.Cords.x + 2, Square.Cords.y),
xMultiplier * -1) = false then
begin
CastlingPossible[turn] := false;
move(square, bm);
setsquareto(point(8, square.Cords.y), 0);
if board[8, square.Cords.y].Color = 1 then
bm.Canvas.Pixels[0,0] := $0
else
bm.Canvas.Pixels[0,0] := $ffffff;
board[8, square.Cords.y].Picture.Bitmap := bm;
SetSquareTo(point(square.Cords.X - 1, square.Cords.Y), 2 * xMultiplier);
PGNBlankMove(turn);
PGNPrint('O-O ');
if ((numMoves mod 5) = 0) and (square.kind < 0) then
PGNPrint(#13#10);
end;
if SelectedSqr.Cords.x > Square.Cords.x then //Queen side
begin
if CheckDetect(Point(SelectedSqr.Cords.x - 2, Square.Cords.y),
xMultiplier * -1) = false then
begin
CastlingPossible[turn] := false;
move(board[SelectedSqr.Cords.x - 2, Square.Cords.y], bm);
setsquareto(point(1, square.Cords.y), 0);
if board[1, square.Cords.y].Color = 1 then
bm.Canvas.Pixels[0,0] := $0
else
bm.Canvas.Pixels[0,0] := $ffffff;
board[1, square.Cords.y].Picture.Bitmap := bm;
SetSquareTo(point(square.Cords.X + 2, square.Cords.Y), 2 * xMultiplier);
PGNBlankMove(turn);
PGNPrint('O-O-O ');
if ((numMoves mod 5) = 0) and (square.kind < 0) then
PGNPrint(#13#10);
end;
end;
end;
end //end (((difInX > 1) and (Orientation = orTop_Bottom))
else
begin
invalidmove;
Exit;
end;
end; //end king check
end;//End of case for check
end;//End of check
freeAndNil(bm);
end;
constructor TBoardMannager.create(AOwner: TForm);
var
y, x, firstX: Integer;
bm : TBitmap;
t1, t2 : integer;
begin
PGNResetTemp;
PlayerNameWhite := 'White Player';
PlayerNameBlack := 'Black Player';
BlackColor := $1F2635;
WhiteColor := $BED5FF;
OutlineColor := $505050;
AutoDeselect := true;
incheck := false;
selected := false; //boolean keeps track of whether something is selected
firstX := floor(gameWidth/2) - floor((gameWidth/8) * 2.25);
SetLength(fwhitePiecesTook, 1);
SetLength(fblackPiecesTook, 1);
turn := 1;
Debug := TDebug.Create(AOwner);
for y := 1 to 8 do
for x := 1 to 8 do
begin
Board[x, y] := tsquare.Create(AOwner);
with board[x, y] do
begin
top := (y - 1) * Height;
left := (x - 1) * Height + firstX;
Cords := Point(x, y);
ForwardClick := self.Click;
end;
end;
//Create all the bitmaps
pawn := TBitmap.Create;
with pawn do
begin
PixelFormat := pf32bit;
height := imagesize;
width := height;
end;
bishop := TBitmap.Create;
with bishop do
begin
PixelFormat := pf32bit;
height := imagesize;
width := height;
end;
castle := TBitmap.Create;
with castle do
begin
PixelFormat := pf32bit;
height := imagesize;
width := height;
end;
horse := TBitmap.Create;
with horse do
begin
PixelFormat := pf32bit;
height := imagesize;
width := height;
end;
king := TBitmap.Create;
with king do
begin
PixelFormat := pf32bit;
height := imagesize;
width := height;
end;
queen := TBitmap.Create;
with queen do
begin
PixelFormat := pf32bit;
height := imagesize;
width := height;
end;
Orientation := orRight_Left;
debug.println('Chess by Daniel Wykerd 10A3 Parel Vallei');
end;
destructor TBoardMannager.destroy;
var
x, y : integer;
begin
for y := 1 to 8 do
for x := 1 to 8 do
freeandnil(Board[x,y]);
debug.Destroy;
pawn.Destroy;
bishop.Destroy;
castle.Destroy;
horse.Destroy;
king.Destroy;
queen.Destroy;
end;
procedure TBoardMannager.DrawBoard;
var
bm : TBitmap;
x, y : integer;
t1, t2 : integer;
begin
t1 := GetTickCount;
//generate the board
bm := TBitmap.Create;
with bm do
begin
PixelFormat := pf32bit;
height := 1;
width := 1;
end;
for y := 1 to 8 do
for x := 1 to 8 do
begin
with board[x, y] do
begin
if odd(x + y - orientation) then
begin
bm.Canvas.Pixels[0,0] := $000000;
color := 1;
end
else
begin
bm.Canvas.Pixels[0,0] := $ffffff;
//this method ( pixels[] ) is slowwer than using pointers directly but in this
//case only one pixel is changed per block making it easier to code and the time diffirence minimal
color := 2;
end;
picture.Bitmap := bm
end;
end;
bm.Destroy;
t2 := GetTickCount;
debug.println('Generated board in ' + IntToStr(t2 -t1) + ' miliseconds');
end;
function TBoardMannager.GetBlackPiecesTook(index: integer): integer;
begin
result := FBlackPiecesTook[index];
end;
function TBoardMannager.getBlackTookLength: integer;
begin
result := length(FBlackPiecesTook) - 1;
end;
function TBoardMannager.getLastSquareLeft: integer;
begin
result := board[8,1].Left
end;
function TBoardMannager.getSquareHeightWidth: integer;
begin
result := board[1,1].Height;
end;
function TBoardMannager.GetWhitePiecesTook(index: integer): integer;
begin
result := FWhitePiecesTook[index];
end;
function TBoardMannager.getWhiteTookLength: integer;
begin
result := length(FWhitePiecesTook) - 1;
end;
procedure TBoardMannager.InitialDraw;
var
pbase, p : PDW;
y, y1, x, x1, i : integer;
tempbm: TBitmap;
t1, t2 : integer;
begin
drawboard;
PlayerNameWhite := 'White Player';
PlayerNameBlack := 'Black Player';
PGNResetTemp;
castlingPossible[1] := true;
CastlingPossible[2] := true;
t1 := GetTickCount;
if Orientation = orTop_Bottom then
begin
for x := 1 to 8 do // y = x
begin
SetSquareTo(Point(x, 7), 1);
SetSquareTo(Point(x, 2), -1);
end;
for x := 1 to 2 do
begin
SetSquareTo(Point( x * 7 - 6, 8), 2);
SetSquareTo(Point( x * 7 - 6, 1), -2);
SetSquareTo(Point( x * 3,8), 3);
SetSquareTo(Point( x * 3,1), -3);
SetSquareTo(Point( x * 5 - 3, 8), 4);
SetSquareTo(Point( x * 5 - 3, 1), -4);
end;
SetSquareTo(Point(5, 8), 6);
SetSquareTo(Point(5, 1), -6);
SetSquareTo(Point(4, 8), 5);
SetSquareTo(Point(4, 1), -5);
end
else
Begin
for y := 1 to 8 do
begin
SetSquareTo(Point(2, y), 1);
SetSquareTo(Point(7, y), -1);
end;
for y := 1 to 2 do
begin
SetSquareTo(Point(1, y * 7 - 6), 2);
SetSquareTo(Point(8, y * 7 - 6), -2);
SetSquareTo(Point(1, y * 3), 3);
SetSquareTo(Point(8, y * 3), -3);
SetSquareTo(Point(1, y * 5 - 3), 4);
SetSquareTo(Point(8, y * 5 - 3), -4);
end;
SetSquareTo(Point(1, 5), 6);
SetSquareTo(Point(8, 5), -6);
SetSquareTo(Point(1, 4), 5);
SetSquareTo(Point(8, 4), -5);
End;
t2 := GetTickCount;
debug.println('Generated pieces in: ' + IntToStr(t2-t1) + ' miliseconds' + nl)
end;
procedure TBoardMannager.InvalidMove;
begin
Debug.println('Invalid Move'); ;
beep;
if autoDeselect then
begin
selected := false;
//Revert turn
if turn = 1 then
turn := 2
else
turn := 1;
end;
end;
function TBoardMannager.Move(ASquare: TSquare; Abm : TBitmap) : integer;
var
Atempbm: Tbitmap;
pbase, p : PDW;
y,x : integer;
CheckTurn : byte;
reverseSelected, reverseSquare : TSquare;
squarebm : TBitmap;
begin
result := ASquare.kind;
reverseSelected := ASquare;
reverseSquare := SelectedSqr;
squarebm := TBitmap.Create;
with squarebm do
begin
PixelFormat := pf32bit;
Height := imageSize;
Width := Height;
end;
squarebm.Assign(ASquare.Picture.Bitmap);
if Turn = 1 then
CheckTurn := 2
else
CheckTurn := 1;
if asquare.Color <> selectedsqr.color then
begin
Atempbm := TBitmap.Create;
with Atempbm do
begin
PixelFormat := pf32bit;
Height := imageSize;
Width := Height;
end;
Atempbm.Assign(SelectedSqr.picture.Bitmap);
for y := 0 to imageSize - 1 do
for x := 0 to imageSize - 1 do
begin
pbase := Atempbm.ScanLine[y];
p := PDW(DWORD(pbase) + (x shl 2));
case ASquare.Color of
2:
if p^ = $0 then
p^ := $FFFFFF;
1:
if p^ = $FFFFFF then
p^ := $0;
end;
end;
ASquare.picture.Bitmap := Atempbm;
SelectedSqr.picture.Bitmap := Abm;
ASquare.Kind := SelectedSqr.Kind;
SelectedSqr.Kind := 0;
Selected := false;
Debug.println('Moved' + nl);
freeandnil(atempbm);
end
else
begin
ASquare.picture.Bitmap := SelectedSqr.picture.Bitmap;
ASquare.Kind := selectedsqr.Kind;
SelectedSqr.Kind := 0;
SelectedSqr.picture.Bitmap := Abm;
Selected := false;
Debug.println('Moved' + nl);
end;
if CheckDetect = CheckTurn then
begin
if not InCheck then
begin
incheck := true;
Debug.println('Invalid Move - Will cause check!' + nl + 'Reversing Move!');
beep;
SelectedSqr := reverseSelected;
Move(reverseSquare, squarebm);
ASquare.Kind := result;
selectedSqr := reverseSquare; //Reset selectedsqr to allow for PGN Saving!
Turn := CheckTurn;
DropDownMsg('Illegal Move', Debug.parent);
end
else
InCheck := false;
end
else if CheckDetect <> 0 then
DropDownMsg('Check', Debug.parent);
selectedSqr := reverseSquare; //Reset selectedsqr to allow for PGN Saving!
squarebm.Destroy;
end;
procedure TBoardMannager.SetAutoDeselect(const Value: boolean);
begin
FAutoDeselect := Value;
end;
procedure TBoardMannager.Setbishop(const Value: TBitmap);
begin
Fbishop := Value;
end;
procedure TBoardMannager.SetBlackColor(const Value: TColor);
begin
FBlackColor := rgb(GetBValue(value), GetGValue(Value),GetRValue(Value));
end;
procedure TBoardMannager.SetBlackPiecesTook(Index: Integer; Value: Integer);
begin
FBlackPiecesTook[Index] := Value;
end;
procedure TBoardMannager.SetDebug(const Value: TDebug);
begin
FDebug := Value;
end;
procedure TBoardMannager.Sethorse(const Value: TBitmap);
begin
Fhorse := Value;
end;
procedure TBoardMannager.Setking(const Value: TBitmap);
begin
Fking := Value;
end;
procedure TBoardMannager.Setknight(const Value: TBitmap);
begin
Fknight := Value;
end;
procedure TBoardMannager.SetOrientation(const Value: Integer);
begin
FOrientation := Value;
end;
procedure TBoardMannager.SetOutlineColor(const Value: TColor);
begin
FOutlineColor := rgb(GetBValue(value), GetGValue(Value),GetRValue(Value));
end;
procedure TBoardMannager.Setpawn(const Value: TBitmap);
begin
Fpawn := Value;
end;
procedure TBoardMannager.SetPlayerNameBlack(const Value: string);
begin
FPlayerNameBlack := Value;
end;
procedure TBoardMannager.SetPlayerNameWhite(const Value: string);
begin
FPlayerNameWhite := Value;
end;
procedure TBoardMannager.Setqueen(const Value: TBitmap);
begin
Fqueen := Value;
end;
procedure TBoardMannager.SetSelected(const Value: boolean);
begin
FSelected := Value;
end;
procedure TBoardMannager.SetSelectedSqr(const Value: TSquare);
begin
FSelectedSqr := Value;
end;
procedure TBoardMannager.SetSquareTo(Location: TPoint; Kind: integer);
var
tempbm: TBitmap;
x, y: integer;
pbase, p: PDW;
begin
if (Location.x IN [1 .. 8]) AND (Location.y IN [1 .. 8]) then
begin
tempbm := TBitmap.Create;
with tempbm do
begin
PixelFormat := pf32bit;
Height := imageSize;
Width := Height;
end;
case Kind of
1, -1:
tempbm.Assign(pawn);
2, -2:
tempbm.Assign(castle);
3, -3:
tempbm.Assign(bishop);
4, -4:
tempbm.Assign(horse);
5, -5:
tempbm.Assign(queen);
6, -6:
tempbm.Assign(king);
0:
begin
for y := 0 to imageSize - 1 do
for x := 0 to imageSize - 1 do
pbase := tempbm.ScanLine[y];
p := PDW(DWORD(pbase) + (x shl 2));
p^ := $0000FF;
end;
end;
for y := 0 to imageSize - 1 do
for x := 0 to imageSize - 1 do
begin
pbase := tempbm.ScanLine[y];
p := PDW(DWORD(pbase) + (x shl 2));
case p^ of
$0000FF:
if odd(Location.y + Location.x - orientation) then
p^ := $000000
else
p^ := $FFFFFF;
$00FF00:
p^ := outlineColor;
$FF0000:
begin
if Kind > 0 then
p^ := WhiteColor
else
p^ := BlackColor;
end;
end;
end;
if Kind <> 0 then
Board[Location.x, Location.y].picture.Bitmap := tempbm;
Board[Location.x, Location.y].Kind := Kind;
tempbm.Destroy; //Keep memory clean!!
end;
end;
procedure TBoardMannager.SetTurn(const Value: integer);
begin
FTurn := Value;
end;
procedure TBoardMannager.SetWhiteColor(const Value: TColor);
begin
FWhiteColor := rgb(GetBValue(value), GetGValue(Value),GetRValue(Value));
end;
procedure TBoardMannager.SetWhitePiecesTook(Index: Integer; Value: Integer);
begin
FWhitePiecesTook[Index] := Value;
end;
procedure TBoardMannager.TakePiece(ASquare: TSquare; Abm: TBitmap);
var
i, oKind: integer;
begin
okind := selectedsqr.Kind;
i := Move(ASquare, Abm);
if ASquare.Kind = oKind then //only if moved
case i of
1 .. 6:
begin
WhitePiecesTook[ high(FWhitePiecesTook)] := i;
SetLength(FWhitePiecesTook, length(FWhitePiecesTook) + 1);
end;
-6 .. -1:
begin
BlackPiecesTook[ high(FBlackPiecesTook)] := i * -1;
SetLength(FBlackPiecesTook, length(FBlackPiecesTook) + 1);
end;
end;
end;
{ TSaveManager }
constructor TSaveManager.Create(AOwner: TObject);
begin
LinkedBoard := nil;
rootdir := '';
end;
procedure TSaveManager.LoadFromFile(filepath: string);
var
tS : TextFile;
x: Integer;
y: Integer;
i: Integer;
s: string;
t1, t2 : integer;
PGNPath : string;
begin
PGNPath := filepath;
delete(PGNPath, pos('.', PGNPath), 6);
PGNPath := PGNPath + '.PGN';
if FileExists(PGNPath) then
CopyFile(PCHar(PGNPath), PChar(tempPGNFileName), false);
assignFile(tS, filepath);
reset(tS);
readln(tS, s);
with LinkedBoard do
begin
Clear;
drawboard;
t1 := GetTickCount;
turn := strtoint(s);
for y := 1 to 8 do
begin
readln(tS, s);
for x := 1 to 8 do
begin
SetSquareTo(Point(x,y),strtoint(copy(s,1,2)));
delete(s, 1, 2);
end;
end;
readln(tS, s);
SetLength(FWhitePiecesTook, length(S));
for i := 0 to length(s) - 1 do
begin
WhitePiecesTook[i] := strtoint(copy(s, 1, 1));
delete(s, 1, 1);
end;
readln(tS, s);
SetLength(FBlackPiecesTook, length(S));
for i := 0 to length(s) - 1 do
begin
BlackPiecesTook[i] := strtoint(copy(s, 1, 1));
delete(s, 1, 1);
end;
readln(ts, s);
if s = 'TRUE' then
CastlingPossible[1] := true
else
CastlingPossible[1] := false;
readln(ts, s);
if s = 'TRUE' then
CastlingPossible[2] := true
else
CastlingPossible[2] := false;
readln(ts, numMoves);
readln(tS, s);
PlayerNameWhite := s;
readln(tS, s);
PlayerNameBlack := s;
end;
closefile(ts);
t2 := GetTickCount;
LinkedBoard.Debug.println(Format('Loaded from save in: %d milliseconds', [t2-t1]));
end;
procedure TSaveManager.LoadRequest;
var
filename : string;
begin
filename := ChooseLoadDlg(rootDir + '\_LOG.DWCS');
if filename = '' then //Do nothing
else if not fileExists(filename) then
DropDownMsg('Error: File Not Found',LinkedBoard.FDebug.Parent)
else
LoadFromFile(filename);
end;
procedure TSaveManager.SaveRequest;
var
filename, path : string;
begin
filename := requestsavename;
if filename <> '' then
begin
path := rootDir + '\' + filename + '.DWC'; //dwc = Daniel Wykerd Chess
if fileExists(path) then
begin
if OverwriteRequest then
SaveToFileOverwrite(path)
else
DropDownMsg('Did not save!', LinkedBoard.FDebug.parent);
end
else
SaveToFile(path);
end;
end;
procedure TSaveManager.SaveToFile(filepath: string);
var
tS : TextFile;
x: Integer;
y: Integer;
s: Integer;
pgnpath : string;
begin
PGNPath := filepath;
delete(PGNPath, pos('.', PGNPath), 6);
PGNPath := PGNPath + '.PGN';
//create / clear the pgn file
assignfile(tS, PGNPath);
rewrite(ts);
closefile(ts);
CopyFile(PChar(tempPGNFileName), PCHar(PGNPath), false);
assignFile(tS, filepath);
rewrite(tS);
with LinkedBoard do
begin
//Deselect piece
if selected then
begin
selected := false;
if Turn = 1 then
turn := 2
else
turn := 1;
end;
//write turn
writeln(tS, turn);
//write all board kinds
for y := 1 to 8 do
begin
for x := 1 to 8 do
begin
if Board[x, y].Kind >= 0 then
write(tS, FormatFloat('00', Board[x, y].Kind))
else
write(tS, Board[x, y].Kind);
end;
write(tS, #13#10);
end;
//Write pieces took
for s := 0 to getWhiteTookLength do
write(tS ,WhitePiecesTook[s]);
write(tS, #13#10);
for s := 0 to getBlackTookLength do
write(tS, BlackPiecesTook[s]);
write(tS, #13#10);
writeln(ts, CastlingPossible[1]);
writeln(ts, CastlingPossible[2]);
writeln(ts, numMoves);
writeln(tS, PlayerNameWhite);
writeln(tS, PlayerNameBlack);
end;
closefile(tS);
//Add save to save log
assignFile(tS, rootDir + '\_LOG.DWCS');
if not fileExists(rootDir + '\_LOG.DWCS') then
rewrite(tS);
Append(tS);
writeLn(tS, filepath);
closefile(tS);
DropDownMsg('Save Successful',LinkedBoard.FDebug.Parent)
end;
procedure TSaveManager.SaveToFileOverwrite(filepath: string);
var
tS : TextFile;
x: Integer;
y: Integer;
s: Integer;
pgnpath : string;
begin
PGNPath := filepath;
delete(PGNPath, pos('.', PGNPath), 6);
PGNPath := PGNPath + '.PGN';
//create / clear the pgn file
assignfile(tS, PGNPath);
rewrite(ts);
closefile(ts);
CopyFile(PChar(tempPGNFileName), PCHar(PGNPath), false);
assignFile(tS, filepath);
rewrite(tS);
with LinkedBoard do
begin
//Deselect piece
if selected then
begin
selected := false;
if Turn = 1 then
turn := 2
else
turn := 1;
end;
//write turn
writeln(tS, turn);
//write all board kinds
for y := 1 to 8 do
begin
for x := 1 to 8 do
begin
if Board[x, y].Kind >= 0 then
write(tS, FormatFloat('00', Board[x, y].Kind))
else
write(tS, Board[x, y].Kind);
end;
write(tS, #13#10);
end;
//Write pieces took
for s := 0 to getWhiteTookLength do
write(tS ,WhitePiecesTook[s]);
write(tS, #13#10);
for s := 0 to getBlackTookLength do
write(tS, BlackPiecesTook[s]);
write(tS, #13#10);
writeln(ts, CastlingPossible[1]);
writeln(ts, CastlingPossible[2]);
writeln(ts, numMoves);
writeln(tS, PlayerNameWhite);
writeln(tS, PlayerNameBlack);
end;
closefile(tS);
DropDownMsg('Save Successful',LinkedBoard.FDebug.Parent)
end;
procedure TSaveManager.SetLinkedBoard(const Value: TBoardMannager);
begin
FLinkedBoard := Value;
end;
procedure TSaveManager.SetrootDir(const Value: string);
begin
if not DirectoryExists(value) then
CreateDir(value);
FrootDir := Value;
end;
{procedure ShowSettingsUI(Sender: TWinControl; Manager : TBoardMannager);
var
frm : TForm;
lbl : TLabel;
rgn : HRGN;
begin
/// All the changeable settings include ///
/// Orientation ///
/// Piece Colors ~~ OUTLINES / INNER COLORS ///
/// Background Color ///
/// Show Debug ///
/// Auto Deselect ///
/// Assets Pack ///
/// Player Names ///
/// Font NOTE: NOT POSSIBLE YET! ///
/// Save directory ///
/// Animation speed control ///
frm := TForm.CreateNew(Sender, 0);
frm.BorderStyle := bsNone;
frm.ClientWidth := 720;
lbl := TLabel.Create(frm);
lbl.Parent := frm;
lbl.Caption := 'S E T T I N G S';
lbl.Font.Name := 'Arial';
lbl.Font.Size := 18;
lbl.Font.Color := $5D2FFF;
lbl.Font.Style := [fsBold];
frm.Position := poScreenCenter;
rgn := CreateRoundRectRgn(0, // x-coordinate of the region's upper-left corner
0, // y-coordinate of the region's upper-left corner
frm.ClientWidth, // x-coordinate of the region's lower-right corner
frm.ClientHeight, // y-coordinate of the region's lower-right corner
20, // height of ellipse for rounded corners
20); // width of ellipse for rounded corners
SetWindowRgn(frm.Handle, rgn, True);
frm.Color := rgb(168,244,255);
frm.DoubleBuffered := true;
frm.ShowModal;
end; }
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is IdeOpenDlgFavoriteUnit.pas. }
{ }
{ The Initial Developer of the Original Code is documented in the accompanying }
{ help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. }
{ }
{**************************************************************************************************}
{ }
{ Unit owner: Petr Vones }
{ Last modified: June 12, 2002 }
{ }
{**************************************************************************************************}
unit IdeOpenDlgFavoriteUnit;
interface
{$I jcl.inc}
uses
Windows, Messages, Classes, SysUtils, ToolsAPI, OpenDlgFavAdapter, JclOtaUtils;
type
TOpenDialogsFavoriteExpert = class(TJclOTAExpert)
private
FFavOpenDialog: TFavOpenDialog;
procedure DialogClose(Sender: TObject);
procedure DialogShow(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
end;
procedure Register;
implementation
uses
JclIniFiles, JclFileUtils, JclSysInfo;
const
FavoritesSectionName = 'IdeFavoriteFolders';
PictDialogFolderItemName = 'PictureDialogPath';
BorlandImagesPath = 'Borland Shared\Images';
procedure Register;
begin
RegisterPackageWizard(TOpenDialogsFavoriteExpert.Create);
end;
//==================================================================================================
// TOpenDialogsFavoriteExpert
//==================================================================================================
constructor TOpenDialogsFavoriteExpert.Create;
begin
inherited Create;
FFavOpenDialog := InitializeFavOpenDialog;
FFavOpenDialog.DisableHelpButton := True;
FFavOpenDialog.HookDialogs;
FFavOpenDialog.OnClose := DialogClose;
FFavOpenDialog.OnShow := DialogShow;
FFavOpenDialog.PictureDialogLastFolder := JediIniFile.ReadString(FavoritesSectionName,
PictDialogFolderItemName, PathAddSeparator(GetCommonFilesFolder) + BorlandImagesPath);
end;
//--------------------------------------------------------------------------------------------------
destructor TOpenDialogsFavoriteExpert.Destroy;
begin
FFavOpenDialog.UnhookDialogs;
inherited;
end;
//--------------------------------------------------------------------------------------------------
procedure TOpenDialogsFavoriteExpert.DialogClose(Sender: TObject);
begin
IniWriteStrings(JediIniFile, FavoritesSectionName, FFavOpenDialog.FavoriteFolders);
JediIniFile.WriteString(FavoritesSectionName, PictDialogFolderItemName, FFavOpenDialog.PictureDialogLastFolder);
end;
//--------------------------------------------------------------------------------------------------
procedure TOpenDialogsFavoriteExpert.DialogShow(Sender: TObject);
begin
IniReadStrings(JediIniFile, FavoritesSectionName, FFavOpenDialog.FavoriteFolders);
end;
//--------------------------------------------------------------------------------------------------
end.
|
unit uRtAdoFileReader;
interface
uses
Classes,ADODB,Windows,SysUtils,Math, Variants, ActiveX,DateUtils,
uLKJRuntimeFile, uVSConst,uConvertDefine,uRtFileReaderBase;
type
//////////////////////////////////////////////////////////////////////////////
///LKJRuntimeFile的原始文件读写类
//////////////////////////////////////////////////////////////////////////////
TAdoFileReader = class(TRunTimeFileReaderBase)
public
constructor Create();
destructor Destroy();override;
public
{功能:通过思维格式化及ADO文件加载文件信息}
procedure LoadFromFile(orgFile : string;RuntimeFile : TLKJRuntimeFile);override;
private
m_FieldConvert : TFieldConvert;
m_StationFormat : TStationFormat;
m_Query: TADOQuery;
//-------------------------------------------------------------------------
//功能:加载ADO文件
procedure LoadAdoFile(FileName: string);
//功能:转换ADO文件一行为 TLKJCommonRec
function DBRowToLkjRec(PreRec: TLKJCommonRec;Query: TADOQuery):TLKJCommonRec;
//功能:处理特殊数据,如只有事件 但其它列为空的数据
procedure DealSpecailData(PreCommonRec,LKJCommonRec:TLKJCommonRec;Query: TADOQuery);
//功能:处理一般数据
procedure DealNormalData(PreCommonRec,LKJCommonRec:TLKJCommonRec;Query: TADOQuery);
//功能:判断是否为特殊记录
function IsSpecialRow(Query: TADOQuery): Boolean;
//功能:处理均缸数据,确定当前使用的为哪一个均缸
procedure DealWithJgNumber(LkjFile:TLKJRuntimeFile);
//功能:处理车位调整记录
procedure DealWithPosChance(LkjFile:TLKJRuntimeFile);
//格式化下一个站的信息
procedure FormatToStation(LkjFile:TLKJRuntimeFile);
end;
////////////////////////////////////////////////////////////////////////////////
///TOrgToAdofile 功能:把原始文件转换为ADO文件 ,程序执行目录下的“TmpTest.Ado”文件
////////////////////////////////////////////////////////////////////////////////
TOrgToAdofile = class
public
{功能:调用fmtFile.dll及testdll.dll生成TmpTest.Ado}
procedure Execute(const orgFileName:string);
end;
implementation
{ TAdoFileReader }
constructor TAdoFileReader.Create();
begin
inherited Create;
m_FieldConvert := TFieldConvert.Create;
m_StationFormat := TStationFormat.Create;
m_Query := TADOQuery.Create(nil);
end;
destructor TAdoFileReader.Destroy;
begin
m_FieldConvert.Free;
m_StationFormat.Free;
m_Query.Free;
inherited;
end;
procedure TAdoFileReader.LoadFromFile(orgFile: string;
RuntimeFile: TLKJRuntimeFile);
{功能:通过思维格式化及ADO文件加载文件信息}
var
i,tempStation,nStationIndex: Integer;
OrgToAdofile: TOrgToAdofile;
dt,tm : TDateTime;
rec,preRec : TLKJCommonRec;
bJiangji,bDiaoche : boolean;
bInPingdiao : boolean;
begin
OrgToAdofile := TOrgToAdofile.Create;
try
//读取头信息
ReadHead(orgFile,RuntimeFile.HeadInfo);
//生成ADO文件
OrgToAdofile.Execute(orgFile);
//加载ADO数据
LoadAdoFile(ExtractFilePath(ParamStr(0))+'TmpTest.Ado');
//初始化监控数据的日期
dt := DateOf(RuntimeFile.HeadInfo.dtKCDataTime);
//初始化降级、调车的标志
bJiangji := false;
bDiaoche := false;
bInPingdiao := false;
//初始化其它信息
tm := -1;
tempStation := 0;
preRec := nil;
nStationIndex := 1;
//循环翻译数据行信息
for I := 0 to m_Query.RecordCount - 1 do
begin
//生成运行记录行
rec := DBRowToLkjRec(preRec,m_Query);
RuntimeFile.Records.Add(rec);
rec.CommonRec.strCheCi := IntToStr(RuntimeFile.HeadInfo.nTrainNo);
//处理车站序号
if i = 0 then
tempStation := rec.CommonRec.nStation
else begin
preRec := RuntimeFile.Records[RuntimeFile.Records.Count - 1];
if (rec.CommonRec.nStation <>tempStation) then
begin
nStationIndex := nStationIndex + 1;
tempStation := rec.CommonRec.nStation;
end;
end;
rec.CommonRec.nStationIndex := nStationIndex;
//格式化运行记录行的监控状态信息
if rec.CommonRec.nEvent = CommonRec_Event_JKStateChange then
begin
if Pos('降级',rec.CommonRec.strOther) > 0 then
begin
bJiangji := true;
end else begin
bJiangji := false;
end;
if Pos('调车',rec.CommonRec.strOther) > 0 then
begin
bDiaoche := true;
end else begin
bDiaoche := false;
end;
if Pos('平调',rec.CommonRec.strOther) > 0 then
begin
bInPingdiao := true;
end else begin
bInPingdiao := false;
end;
end;
rec.CommonRec.bIsDiaoChe := bDiaoche;
rec.CommonRec.bIsJiangji := bJiangji;
rec.CommonRec.bIsPingdiao := bInPingdiao;
//格式化运行记录行的时间信息(加上日期)
if tm < 0 then
begin
tm := rec.CommonRec.DTEvent;
rec.CommonRec.DTEvent := dt + tm;
end else begin
if (FormatDateTime('HHnnss',rec.CommonRec.DTEvent) < FormatDateTime('HHnnss',tm))
and (rec.CommonRec.DTEvent <> 0) then
begin
dt := dt + 1;
tm := rec.CommonRec.DTEvent;
rec.CommonRec.DTEvent := dt + tm;
end else begin
if rec.CommonRec.DTEvent > 0 then
tm := rec.CommonRec.DTEvent;
rec.CommonRec.DTEvent := dt + tm;
end;
end;
//格式化平调信息
m_Query.Next;
end;
DealWithJgNumber(RuntimeFile);
//格式化车位距离
DealWithPosChance(RuntimeFile);
//格式化当前的交路、数据交路、车站号
m_StationFormat.Execute(RuntimeFile);
FormatToStation(RuntimeFile);
finally
OrgToAdofile.Free;
end;
end;
function TAdoFileReader.DBRowToLkjRec(PreRec: TLKJCommonRec;Query: TADOQuery): TLKJCommonRec;
begin
Result := TLKJCommonRec.Create;
if IsSpecialRow(Query) then
DealSpecailData(PreRec,Result,Query)
else
DealNormalData(PreRec,Result,Query);
end;
procedure TAdoFileReader.DealNormalData(PreCommonRec,LKJCommonRec: TLKJCommonRec;
Query: TADOQuery);
begin
with LKJCommonRec,Query do
begin
CommonRec.nRow := Query.FieldByName('Rec').AsInteger;
CommonRec.nEvent:= m_FieldConvert.GetnEvent(Query.FieldByName('Disp').AsString);
CommonRec.strDisp := Query.FieldByName('Disp').AsString;
CommonRec.strGK := Query.FieldByName('Hand').AsString;
if (FieldByName('T_h').AsString = '') or (FieldByName('T_h').AsInteger > 23)
or (FieldByName('T_m').AsInteger > 59) or (FieldByName('T_s').AsInteger > 59) then
begin
if PreCommonRec <> nil then
CommonRec.DTEvent := TimeOf(PreCommonRec.CommonRec.DTEvent);
end
else
begin
CommonRec.DTEvent :=
EncodeTime(FieldByName('T_h').AsInteger,FieldByName('T_m').AsInteger,FieldByName('T_s').AsInteger,0)
end;
if FieldByName('glb').IsNull and (PreCommonRec <> nil) then
CommonRec.nCoord := PreCommonRec.CommonRec.nCoord
else
CommonRec.nCoord := m_FieldConvert.GetnCoord(FieldByName('glb').AsString);
CommonRec.strXhj := FieldByName('xhj').AsString;
CommonRec.strSignal := FieldByName('Signal').AsString;
if FieldByName('Jl').IsNull and (PreCommonRec <> nil) then
CommonRec.nDistance := PreCommonRec.CommonRec.nDistance
else
CommonRec.nDistance := FieldByName('Jl').AsInteger;
if FieldByName('Gya').IsNull and (PreCommonRec <> nil) then
CommonRec.nLieGuanPressure := PreCommonRec.CommonRec.nLieGuanPressure
else
CommonRec.nLieGuanPressure := FieldByName('Gya').AsInteger;
if FieldByName('GangY').IsNull and (PreCommonRec <> nil) then
CommonRec.nGangPressure := PreCommonRec.CommonRec.nGangPressure
else
CommonRec.nGangPressure := FieldByName('GangY').AsInteger;
if FieldByName('Jg1').IsNull and (PreCommonRec <> nil) then
CommonRec.nJG1Pressure := PreCommonRec.CommonRec.nJG1Pressure
else
CommonRec.nJG1Pressure := FieldByName('Jg1').AsInteger;
if FieldByName('Jg2').IsNull and (PreCommonRec <> nil) then
CommonRec.nJG2Pressure := PreCommonRec.CommonRec.nJG2Pressure
else
CommonRec.nJG2Pressure := FieldByName('Jg2').AsInteger;
if FieldByName('xh_code').IsNull and (PreCommonRec <> nil) then
CommonRec.LampSign := PreCommonRec.CommonRec.LampSign
else
CommonRec.LampSign := m_FieldConvert.ConvertSignal(FieldByName('xh_code').AsInteger);
if FieldByName('xht_code').IsNull and (PreCommonRec <> nil) then
CommonRec.SignType := PreCommonRec.CommonRec.SignType
else
CommonRec.SignType := m_FieldConvert.ConvertSignType(FieldByName('xht_code').AsInteger);
if FieldByName('xhj_no').IsNull and (PreCommonRec <> nil) then
CommonRec.nLampNo := PreCommonRec.CommonRec.nLampNo
else
CommonRec.nLampNo := FieldByName('xhj_no').AsInteger;
if FieldByName('Shoub').IsNull and (PreCommonRec <> nil) then
begin
CommonRec.nShoub := PreCommonRec.CommonRec.nShoub;
CommonRec.WorkZero := PreCommonRec.CommonRec.WorkZero;
CommonRec.WorkDrag := PreCommonRec.CommonRec.WorkDrag;
CommonRec.HandPos := PreCommonRec.CommonRec.HandPos;
end
else
begin
CommonRec.nShoub := FieldByName('Shoub').AsInteger;
CommonRec.WorkZero := m_FieldConvert.ConvertWorkZero(CommonRec.nShoub);
CommonRec.WorkDrag := m_FieldConvert.ConvertWorkDrag(CommonRec.nShoub);
CommonRec.HandPos := m_FieldConvert.ConvertHandPos(CommonRec.nShoub);
end;
if FieldByName('Rota').IsNull and (PreCommonRec <> nil) then
CommonRec.nRotate := PreCommonRec.CommonRec.nRotate
else
CommonRec.nRotate := FieldByName('Rota').AsInteger;
if FieldByName('Speed').IsNull and (PreCommonRec <> nil) then
CommonRec.nSpeed := PreCommonRec.CommonRec.nSpeed
else
CommonRec.nSpeed := FieldByName('Speed').AsInteger;
if FieldByName('S_lmt').IsNull and (PreCommonRec <> nil) then
CommonRec.nLimitSpeed := PreCommonRec.CommonRec.nLimitSpeed
else
CommonRec.nLimitSpeed := FieldByName('S_lmt').AsInteger;
if FieldByName('JKZT').IsNull and (PreCommonRec <> nil) then
CommonRec.JKZT := PreCommonRec.CommonRec.JKZT
else
CommonRec.JKZT := FieldByName('JKZT').AsInteger;
CommonRec.strOther := FieldByName('OTHER').AsString;
CommonRec.Shuoming := FieldByName('Shuoming').AsString;
end;
end;
procedure TAdoFileReader.DealSpecailData(PreCommonRec,LKJCommonRec: TLKJCommonRec;
Query: TADOQuery);
begin
with LKJCommonRec,Query do
begin
CommonRec.nRow := Query.FieldByName('Rec').AsInteger;
CommonRec.nEvent:= m_FieldConvert.GetnEvent(Query.FieldByName('Disp').AsString);
CommonRec.strDisp := Query.FieldByName('Disp').AsString;
CommonRec.strGK := PreCommonRec.CommonRec.strGK;
CommonRec.DTEvent := TimeOf(PreCommonRec.CommonRec.DTEvent);
CommonRec.nCoord := PreCommonRec.CommonRec.nCoord;
CommonRec.strXhj := PreCommonRec.CommonRec.strXhj;
CommonRec.strSignal := PreCommonRec.CommonRec.strSignal;
CommonRec.nDistance := PreCommonRec.CommonRec.nDistance;
CommonRec.nLieGuanPressure := PreCommonRec.CommonRec.nLieGuanPressure;
CommonRec.nGangPressure := PreCommonRec.CommonRec.nGangPressure;
CommonRec.nJG1Pressure := PreCommonRec.CommonRec.nJG1Pressure;
CommonRec.nJG2Pressure := PreCommonRec.CommonRec.nJG2Pressure;
CommonRec.LampSign := PreCommonRec.CommonRec.LampSign;
CommonRec.SignType := PreCommonRec.CommonRec.SignType;
CommonRec.nLampNo := PreCommonRec.CommonRec.nLampNo;
CommonRec.nShoub := PreCommonRec.CommonRec.nShoub;
CommonRec.WorkZero := PreCommonRec.CommonRec.WorkZero;
CommonRec.WorkDrag := PreCommonRec.CommonRec.WorkDrag;
CommonRec.HandPos := PreCommonRec.CommonRec.HandPos;
CommonRec.nRotate := PreCommonRec.CommonRec.nRotate;
CommonRec.nSpeed := PreCommonRec.CommonRec.nSpeed;
CommonRec.nLimitSpeed := PreCommonRec.CommonRec.nLimitSpeed;
CommonRec.JKZT := PreCommonRec.CommonRec.JKZT;
CommonRec.strOther := FieldByName('OTHER').AsString;
CommonRec.Shuoming := FieldByName('Shuoming').AsString;
end;
end;
procedure TAdoFileReader.DealWithJgNumber(LkjFile: TLKJRuntimeFile);
var
i : Integer;
CurrentValue1, CurrentValue2: Integer;
bFit1, bFit2: Boolean;
nIndex: Integer;
begin
nIndex := -1;
for I := 0 to LkjFile.Records.Count - 1 do
begin
LkjFile.Records[i].CommonRec.nValidJG := 0;
CurrentValue1 := LkjFile.Records[i].CommonRec.nJG1Pressure;
CurrentValue2 := LkjFile.Records[i].CommonRec.nJG2Pressure;
if LkjFile.Records[i].CommonRec.nLieGuanPressure >= 500 then
begin
if CurrentValue1 >= LkjFile.Records[i].CommonRec.nLieGuanPressure then
bFit1 := True
else
bFit1 := False;
if CurrentValue2 >= LkjFile.Records[i].CommonRec.nLieGuanPressure then
bFit2 := True
else
bFit2 := False;
if (bFit1 and bFit2) or (not bFit1 and not bFit2) then
begin
if (LkjFile.Records[i - 1].CommonRec.nValidJG <> 0) and (i > 0) then
LkjFile.Records[i].CommonRec.nValidJG := LkjFile.Records[i - 1].CommonRec.nValidJG;
end;
if bFit1 then
begin
if nIndex = -1 then
nIndex := i;
LkjFile.Records[i].CommonRec.nValidJG := 1;
end;
if bFit2 then
begin
if nIndex = -1 then
nIndex := i;
LkjFile.Records[i].CommonRec.nValidJG := 2;
end;
end
else
begin
if i > 0 then
LkjFile.Records[i].CommonRec.nValidJG := LkjFile.Records[i - 1].CommonRec.nValidJG;
end;
end;
if nIndex >= LkjFile.Records.Count - 1 then
Exit;
for I := nIndex downto 0 do
begin
LkjFile.Records[i].CommonRec.nValidJG := LkjFile.Records[i + 1].CommonRec.nValidJG;
end;
end;
procedure TAdoFileReader.DealWithPosChance(LkjFile: TLKJRuntimeFile);
var
i : Integer;
nSignalDistance : Integer;
begin
nSignalDistance := 0;
for i := 0 to LkjFile.Records.Count - 1 do
begin
case LkjFile.Records[i].CommonRec.nEvent of
CommonRec_Event_TrainPosForward :
begin
LkjFile.Records[i].CommonRec.strOther := IntToStr(LkjFile.Records[i].CommonRec.nDistance);
end;
CommonRec_Event_TrainPosBack :
begin
LkjFile.Records[i].CommonRec.strOther :=
IntToStr(nSignalDistance - LkjFile.Records[i].CommonRec.nDistance);
end;
CommonRec_Event_TrainPosReset :
begin
if (LkjFile.Records[i].CommonRec.nDistance < 300)
or (nSignalDistance - LkjFile.Records[i].CommonRec.nDistance < 300) then
begin
if LkjFile.Records[i].CommonRec.nDistance <
nSignalDistance - LkjFile.Records[i].CommonRec.nDistance then
LkjFile.Records[i].CommonRec.strOther := IntToStr(LkjFile.Records[i].CommonRec.nDistance)
else
LkjFile.Records[i].CommonRec.strOther := IntToStr(nSignalDistance - LkjFile.Records[i].CommonRec.nDistance);
end;
end;
CommonRec_Event_SectionSignal :
begin
nSignalDistance := LkjFile.Records[i].CommonRec.nDistance;
end;
CommonRec_Event_InOutStation :
begin
nSignalDistance := LkjFile.Records[i].CommonRec.nDistance;
end;
CommonRec_Event_EnterStation :
begin
nSignalDistance := LkjFile.Records[i].CommonRec.nDistance;
end;
CommonRec_Event_LeaveStation :
begin
nSignalDistance := LkjFile.Records[i].CommonRec.nDistance;
end;
end;
end;
end;
procedure TAdoFileReader.FormatToStation(LkjFile: TLKJRuntimeFile);
var
i : Integer;
recData : TLKJCommonRec;
tempLineID,tempDataLineID,tempStation : Integer;
begin
recData := TLKJCommonRec(lkjFile.Records[lkjFile.Records.Count - 1]);
tempLineID := recData.CommonRec.nJKLineID;
tempDataLineID := recData.CommonRec.nDataLineID;
tempStation := recData.CommonRec.nStation;
for i := lkjFile.Records.Count - 1 downto 0 do
begin
recData := TLKJCommonRec(lkjFile.Records[i]);
if (recData.CommonRec.nJKLineID <> tempLineID)
or (recData.CommonRec.nStation <>tempStation) then
begin
recData.CommonRec.nToStation := tempStation;
recData.CommonRec.nToJKLineID := tempLineID;
recData.CommonRec.nToDataLineID := tempDataLineID;
tempStation := recData.CommonRec.nStation;
tempLineID := recData.CommonRec.nToJKLineID;
tempDataLineID := recData.CommonRec.nToDataLineID;
end;
end;
tempLineID := 0;
tempDataLineID := 0;
tempStation := 0;
for i := lkjFile.Records.Count - 1 downto 0 do
begin
recData := TLKJCommonRec(lkjFile.Records[i]);
if (recData.CommonRec.nToJKLineID > 0)
or (recData.CommonRec.nToStation > 0) then
begin
tempLineID := recData.CommonRec.nToJKLineID;
tempDataLineID := recData.CommonRec.nToDataLineID;
tempStation := recData.CommonRec.nToStation;
end
else begin
recData.CommonRec.nToJKLineID := tempLineID;
recData.CommonRec.nToDataLineID := tempDataLineID;
recData.CommonRec.nToStation := tempStation;
end;
end;
end;
function TAdoFileReader.IsSpecialRow(Query: TADOQuery): Boolean;
begin
if Trim(Query.FieldByName('Disp').AsString) ='揭示查询' then
Result := True
else
Result := False;
end;
procedure TAdoFileReader.LoadAdoFile(FileName: string);
begin
m_Query.Close;
m_Query.LoadFromFile(FileName);
m_Query.Open();
end;
{ TOrgToAdofile }
procedure TOrgToAdofile.Execute(const orgFileName: string);
var
strFormatFile,strDBPath : string;
pcharFormatFile,pcharDBPath,pcharDBName : pchar;
begin
strDBPath := ExtractFilePath(ParamStr(0));
pcharDBName := PChar(strDBPath + 'test.db');
pcharDBPath := pchar(strDBPath);
try
strFormatFile := FmtLkjOrgFile(orgFileName);
pcharFormatFile := PChar(strFormatFile);
Fmttotable(pcharDBName,pcharFormatFile,pcharDBPath, 1);
finally
if FileExists(strFormatFile) then
DeleteFile(PChar(strFormatFile));
end;
end;
end.
|
unit ImportarProdutoOperacao.Controller;
interface
uses ImportarProduto.Controller.interf, Produto.Model.interf,
TESTPRODUTO.Entidade.Model, System.SysUtils;
type
TImportarProdutoOperacaoController = class(TInterfacedObject,
IImportarProdutoOperacaoController)
private
FRegistro: TTESTPRODUTO;
FImportarProdutoController: IImportarProdutoController;
FProdutoModel: IProdutoModel;
FProdutoEncontrado: Boolean;
FCodigoSinapi: string;
FDescricao: string;
FUnidMedida: string;
FOrigemPreco: string;
FPrMedioSinapi: Currency;
procedure atualizarDadosDoProduto;
procedure salvarDadosNovoProduto;
public
constructor Create;
destructor Destroy; override;
class function New: IImportarProdutoOperacaoController;
function importarProdutoController(AValue: IImportarProdutoController)
: IImportarProdutoOperacaoController;
function produtoModel(AValue: IProdutoModel)
: IImportarProdutoOperacaoController;
function produtoSelecionado(AValue: TTESTPRODUTO)
: IImportarProdutoOperacaoController;
function codigoSinapi(AValue: string)
: IImportarProdutoOperacaoController;
function descricao(AValue: string)
: IImportarProdutoOperacaoController;
function unidMedida(AValue: string)
: IImportarProdutoOperacaoController;
function origemPreco(AValue: string)
: IImportarProdutoOperacaoController;
function prMedioSinapi(AValue: Currency)
: IImportarProdutoOperacaoController; overload;
function prMedioSinapi(AValue: string)
: IImportarProdutoOperacaoController; overload;
function &executar: IImportarProdutoController;
end;
implementation
{ TImportarProdutoOperacaoController }
procedure TImportarProdutoOperacaoController.atualizarDadosDoProduto;
begin
FProdutoModel.DAO.Modify(FRegistro);
FRegistro.CODIGO_SINAPI := FCodigoSinapi;
FRegistro.DESCRICAO := FDescricao;
FRegistro.UNIDMEDIDA := FUnidMedida;
FRegistro.ORIGEM_PRECO := FOrigemPreco;
FRegistro.PRMEDIO_SINAPI := FPrMedioSinapi;
FProdutoModel.DAO.Update(FRegistro);
end;
function TImportarProdutoOperacaoController.codigoSinapi(AValue: string)
: IImportarProdutoOperacaoController;
begin
Result := Self;
FCodigoSinapi := AValue;
end;
constructor TImportarProdutoOperacaoController.Create;
begin
end;
function TImportarProdutoOperacaoController.descricao(AValue: string)
: IImportarProdutoOperacaoController;
begin
Result := Self;
FDescricao := AValue;
end;
destructor TImportarProdutoOperacaoController.Destroy;
begin
inherited;
end;
function TImportarProdutoOperacaoController.executar
: IImportarProdutoController;
begin
if FProdutoEncontrado then
atualizarDadosDoProduto
else
salvarDadosNovoProduto;
end;
class function TImportarProdutoOperacaoController.New
: IImportarProdutoOperacaoController;
begin
Result := Self.Create;
end;
function TImportarProdutoOperacaoController.origemPreco(AValue: string)
: IImportarProdutoOperacaoController;
begin
Result := Self;
FOrigemPreco := AValue;
end;
function TImportarProdutoOperacaoController.prMedioSinapi(AValue: string)
: IImportarProdutoOperacaoController;
begin
Result := Self;
FPrMedioSinapi := StrToCurr(AValue);
end;
function TImportarProdutoOperacaoController.prMedioSinapi(AValue: Currency)
: IImportarProdutoOperacaoController;
begin
Result := Self;
FPrMedioSinapi := AValue;
end;
function TImportarProdutoOperacaoController.importarProdutoController
(AValue: IImportarProdutoController): IImportarProdutoOperacaoController;
begin
Result := Self;
FImportarProdutoController := AValue;
end;
function TImportarProdutoOperacaoController.produtoModel(AValue: IProdutoModel)
: IImportarProdutoOperacaoController;
begin
Result := Self;
FProdutoModel := AValue;
end;
function TImportarProdutoOperacaoController.produtoSelecionado
(AValue: TTESTPRODUTO): IImportarProdutoOperacaoController;
begin
Result := Self;
FRegistro := AValue;
FProdutoEncontrado := not(AValue = nil);
end;
procedure TImportarProdutoOperacaoController.salvarDadosNovoProduto;
begin
FProdutoModel.Entidade(TTESTPRODUTO.Create);
FProdutoModel.Entidade.CODIGO_SINAPI := FCodigoSinapi;
FProdutoModel.Entidade.DESCRICAO := FDescricao;
FProdutoModel.Entidade.UNIDMEDIDA := FUnidMedida;
FProdutoModel.Entidade.ORIGEM_PRECO := FOrigemPreco;
FProdutoModel.Entidade.PRMEDIO_SINAPI := FPrMedioSinapi;
FProdutoModel.DAO.Insert(FProdutoModel.Entidade);
end;
function TImportarProdutoOperacaoController.unidMedida(AValue: string)
: IImportarProdutoOperacaoController;
begin
Result := Self;
FUnidMedida := AValue;
end;
end.
|
unit F_FolderSelect;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Vcl.Menus,
Vcl.ComCtrls, Vcl.StdCtrls, Winapi.ShlObj, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, cxShellCommon,
cxControls, cxContainer, cxEdit, cxShellControls, cxShellTreeView, cxButtons;
//------------------------------------------------------------------------------
type
TFormFolderSelect = class(TForm)
bOk: TcxButton;
bCancel: TcxButton;
shtwFolder: TcxShellTreeView;
procedure bOkClick(Sender: TObject);
procedure bCancelClick(Sender: TObject);
public
//! Выбранная папка (путь)
SelectedPath: string;
end;
function UserSelectFolder(): string;
//------------------------------------------------------------------------------
implementation
{$R *.dfm}
//------------------------------------------------------------------------------
procedure TFormFolderSelect.bOkClick(Sender: TObject);
begin
SelectedPath := shtwFolder.Path;
ModalResult := mrOk;
end;
procedure TFormFolderSelect.bCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
//------------------------------------------------------------------------------
function UserSelectFolder(): string;
var
LForm: TFormFolderSelect;
begin
LForm := TFormFolderSelect.Create(nil);
try
LForm.ShowModal;
Result := LForm.SelectedPath;
finally
LForm.Free;
end;
end;
end.
|
(*
Category: SWAG Title: ARCHIVE HANDLING
Original name: 0021.PAS
Description: Arithmetic compression
Author: KAI ROHRBACHER
Date: 08-24-94 13:21
*)
{
Hello Thomas,
On 26.06.94 you wrote in area PASCAL to subject "Arithmetic compression":
TW> But where can we get a discription of this compression method ??
Michael Barnsley, Lyman Hurd, "Fractal Image Compression", AK Peters,
1993
Mark Nelson, "The Data Compression Book", M&T Books, 1991
Ian Witten, Radford Neal, John Cleary, "Arithmetic Coding for Data
Compression", CACM, Vol. 30, No.6, 1987
Below is a small source from the 1st book, translated into Pascal and
adopted to work on the uppercase alphabet to demonstrate the basic
principles.
For a simple explanation, the program uses the letters of the input
string to "drive" the starting point through the real interval 0.0 ..
1.0
By this process, every possible input string stops at a unique point,
that is: a point (better: a small interval section) represents the
whole string. To _decode_ it, you have to reverse the process: you
start at the given end point and apply the reverse transformation,
noting which intervals you are touching at your voyage throughout the
computation.
Due to the restricted arithmetic resolution of any computer language,
the max. length of a string will be restricted, too (try it out with
TYPE REAL=EXTENDED, for example); this happens when the value
"underflows" the computers precision. }
PROGRAM arithmeticCompression;
USES CRT;
CONST charSet:STRING='ABCDEFGHIJKLMNOPQRSTUVWXYZ ';
size=27; {=Length(charSet)}
p:ARRAY[1..size] OF REAL= (* found empirically *)
(
6.1858296469E-02,
1.1055412402E-02,
2.6991022453E-02,
2.6030374520E-02,
9.2418577127E-02,
2.1864028512E-02,
1.4977615842E-02,
2.8410764564E-02,
5.5247871050E-02,
1.3985123226E-03,
3.8001321554E-03,
3.2593032914E-02,
2.1919756707E-02,
5.2434924064E-02,
5.7837905257E-02,
2.0364674693E-02,
1.0031075103E-03,
4.9730779744E-02,
4.8056280170E-02,
7.2072478498E-02,
2.0948493879E-02,
8.2477728625E-03,
1.0299101184E-02,
4.7873173243E-03,
1.3613601926E-02,
2.7067980437E-03,
2.3933136781E-01
);
VAR psum:ARRAY[1..size] OF REAL;
FUNCTION Encode(CONST s:STRING):REAL;
VAR i,po:INTEGER;
offset,len:REAL;
BEGIN
offset:=0.0;
len:=1.0;
FOR i:=1 TO Length(s) DO
BEGIN
po:=POS(s[i],charSet);
IF po<>0
THEN BEGIN
offset:=offset+len*psum[po];
len:=len*p[po]
END
ELSE BEGIN
WRITELN('only input chars ',charSet,' allowed!');
Halt(1)
END;
END;
Encode:=offset+len/2;
END;
FUNCTION Decode(x:REAL; n:BYTE):STRING;
VAR i,j:INTEGER;
s:STRING;
BEGIN
IF (x<0.0) OR (x>1.0)
THEN BEGIN
WRITELN('must lie in the range [0..1]');
Halt(1)
END;
FOR i:=1 TO n DO
BEGIN
j:=size;
WHILE x<psum[j] DO DEC(j);
s[i]:=charSet[j];
x:=x-psum[j];
x:=x/p[j];
END;
s[0]:=CHR(n);
Decode:=s
END;
CONST
inp='ARITHMETIC';
VAR
r:REAL;
i,j:INTEGER;
BEGIN
FOR i:=1 TO size DO
BEGIN
psum[i]:=0.0;
FOR j:=1 TO i-1 DO
psum[i]:=psum[i]+p[j];
END;
ClrScr;
WRITELN('encoding string : ',inp);
r:=Encode(inp);
WRITELN('string is encoded by ',r);
WRITELN('decoding of r gives: ',Decode(r,Length(inp)));
END.
|
unit Dbackdrp;
{-------------------------------------------------------------------}
{ Unit: Dbackdrp.pas }
{ Project: EPA SWMM }
{ Version: 5.0 }
{ Date: 3/29/05 (5.0.005) }
{ Author: L. Rossman }
{ }
{ Dialog form unit that allows the user to select an image to use }
{ as a backdrop picture for the study area map. }
{-------------------------------------------------------------------}
interface
uses
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, Math, Uglobals, Uproject, Uutils;
type
TBackdropFileForm = class(TForm)
Label1: TLabel;
ImageFileEdit: TEdit;
ImageFileBtn: TBitBtn;
Label2: TLabel;
WorldFileEdit: TEdit;
WorldFileBtn: TBitBtn;
OKBtn: TButton;
CancelBtn: TButton;
HelpBtn: TButton;
ScaleMapCheckBox: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure ImageFileBtnClick(Sender: TObject);
procedure WorldFileBtnClick(Sender: TObject);
procedure OKBtnClick(Sender: TObject);
procedure WorldFileEditChange(Sender: TObject);
procedure HelpBtnClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
XtopLeft : Extended; // top left X coordinate
YtopLeft : Extended; // top left Y coordinate
XbotRight : Extended; // bottom right X coordinate
YbotRight : Extended; // bottom right Y coordinate
Xwpp : Extended; // world X distance per pixel
Ywpp : Extended; // world Y distance per pixel
Pwidth : Integer; // image width in pixels
Pheight : Integer; // image height in pixels
Scaling : Integer; // type of image scaling to use
FileDir : String; // name of image file directory
function ReadImageFile(const Fname: String): Boolean;
function ReadWorldFile(const Fname: String): Boolean;
procedure ScaleBackdrop;
procedure ScaleMapToBackdrop;
function SetScaling: Boolean;
public
{ Public declarations }
function GetBackdropFileName: String;
procedure GetBackdropCoords(var LowerLeft, UpperRight: TExtendedPoint);
end;
var
BackdropFileForm: TBackdropFileForm;
implementation
{$R *.dfm}
uses
Fmain, Fmap, Ucoords;
const
TXT_FILE_DLG_TITLE = 'Select a World File';
TXT_FILE_DLG_FILTER = 'World files (*.*w)|*.*w|All files|*.*';
MSG_NO_IMAGE_FILE = 'Cannot find image file ';
MSG_BAD_IMAGE_FILE = 'Cannot read image file ';
MSG_NO_WORLD_FILE = 'Cannot find world file ';
MSG_BAD_WORLD_FILE = 'Invalid world file ';
MSG_NO_OVERLAP =
'The position of the backdrop image falls outside the map''s boundaries.' + #10 +
'Should the backdrop image be shifted and re-scaled to fit within the map?';
SCALE_TO_NOTHING = 0;
SCALE_TO_WINDOW = 1;
SCALE_TO_MAP = 2;
SCALE_TO_BACKDROP = 3;
procedure TBackdropFileForm.FormCreate(Sender: TObject);
//-----------------------------------------------------------------------------
// Form's OnCreate handler.
//-----------------------------------------------------------------------------
begin
Uglobals.SetFont(self);
Scaling := SCALE_TO_WINDOW;
FileDir := ProjectDir;
end;
procedure TBackdropFileForm.ImageFileBtnClick(Sender: TObject);
//-----------------------------------------------------------------------------
// OnClick handler for the ImageFileBtn BitButton. Uses the MainForm's
// OpenPictureDialog to select a backdrop image file.
//-----------------------------------------------------------------------------
begin
with MainForm.OpenPictureDialog do
begin
InitialDir := FileDir;
if Execute then
begin
ImageFileEdit.Text := Filename;
FileDir := ExtractFileDir(Filename);
end;
end;
end;
procedure TBackdropFileForm.WorldFileBtnClick(Sender: TObject);
//-----------------------------------------------------------------------------
// OnClick handler for the WorldFileBtn BitButton. Uses the MainForm's
// OpenTextFileDialog to select a World file for the backdrop image.
//-----------------------------------------------------------------------------
begin
with MainForm.OpenTextFileDialog do
begin
Title := TXT_FILE_DLG_TITLE;
Filter := TXT_FILE_DLG_FILTER;
Filename := '*.*w';
InitialDir := FileDir;
if Execute then
begin
WorldFileEdit.Text := Filename;
FileDir := ExtractFileDir(Filename);
end;
end;
end;
procedure TBackdropFileForm.WorldFileEditChange(Sender: TObject);
//-----------------------------------------------------------------------------
// OnChange handler for the WorldFileEdit edit box. Enables the Scale Map
// to Backdrop CheckBox if a World file is specified.
//-----------------------------------------------------------------------------
begin
ScaleMapCheckBox.Enabled := (Length(Trim(WorldFileEdit.Text)) > 0);
end;
procedure TBackdropFileForm.OKBtnClick(Sender: TObject);
//-----------------------------------------------------------------------------
// OnClick handler for the OKBtn. Processes the entries made in the form.
//-----------------------------------------------------------------------------
begin
if not ReadImageFile(ImageFileEdit.Text)
then ImageFileEdit.SetFocus
else if not ReadWorldFile(WorldFileEdit.Text)
then WorldFileEdit.SetFocus
else begin
if not SetScaling then Exit;
Hide;
ModalResult := mrOK;
end;
end;
function TBackdropFileForm.GetBackdropFileName: String;
//-----------------------------------------------------------------------------
// Public function that returns the name of the backdrop image file.
// Called from the MainForm when processing the View >> Backdrop >>
// Load menu selection.
//-----------------------------------------------------------------------------
begin
Result := ImageFileEdit.Text;
end;
function TBackdropFileForm.ReadImageFile(const Fname: String): Boolean;
//-----------------------------------------------------------------------------
// Determines pixel width and height of backdrop image file.
//-----------------------------------------------------------------------------
var
Picture: TPicture;
begin
XtopLeft := 0.0;
YtopLeft := 0.0;
XbotRight := 0.0;
YbotRight := 0.0;
Xwpp := MapForm.Map.Window.WPPx;
Ywpp := MapForm.Map.Window.WPPy;
Result := False;
if not FileExists(Fname) then
begin
MessageDlg(MSG_NO_IMAGE_FILE + Fname, mtWarning, [mbOK], 0);
Exit;
end;
Picture := TPicture.Create;
try
Picture.LoadFromFile(Fname);
Pwidth := Picture.Width;
Pheight := Picture.Height;
Result := True;
finally
Picture.Free;
end;
if Result = False
then MessageDlg(MSG_BAD_IMAGE_FILE + Fname, mtWarning, [mbOK], 0);
end;
function TBackdropFileForm.ReadWorldFile(const Fname: String): Boolean;
//-----------------------------------------------------------------------------
// Reads the contents of a "world" file for the backdrop image.
//-----------------------------------------------------------------------------
var
F: TextFile;
S: String;
I: Integer;
X: array[0..5] of Extended;
begin
// Check that world file exists
I := 0;
Result := True;
if Length(Trim(Fname)) = 0 then Exit;
Result := False;
if not FileExists(Fname) then
begin
MessageDlg(MSG_NO_WORLD_FILE + Fname, mtWarning, [mbOK], 0);
Exit;
end;
// Try to open the file
AssignFile(F, Fname);
try
Reset(F);
// Read 6 lines of data from the file
while not Eof(F) and (I < 6) do
begin
Readln(F, S);
if Uutils.GetExtended(S, X[I]) then Inc(I);
end;
finally
CloseFile(F);
end;
// Check for valid data
if (I < 6) or (X[0] = 0.0) or (X[3] = 0.0) then
begin
MessageDlg(MSG_BAD_WORLD_FILE + Fname, mtWarning, [mbOK], 0);
Exit;
end;
// Save each data value
Xwpp := X[0]; // world x per pixel
Ywpp := -X[3]; // world y per pixel
XtopLeft := X[4]; // world x of top left
YtopLeft := X[5]; // world y of top left
XbotRight := XtopLeft + Xwpp*Pwidth;
YbotRight := YtopLeft - Ywpp*Pheight;
Result := True;
end;
procedure TBackdropFileForm.GetBackdropCoords(var LowerLeft, UpperRight:
TExtendedPoint);
//-----------------------------------------------------------------------------
// Determines coordinates of lower left and upper right corners of the
// backdrop image.
//-----------------------------------------------------------------------------
begin
case Scaling of
SCALE_TO_WINDOW: ScaleBackdrop;
SCALE_TO_MAP: ScaleBackdrop;
SCALE_TO_BACKDROP: ScaleMapToBackdrop;
end;
LowerLeft.X := XtopLeft;
LowerLeft.Y := YbotRight;
UpperRight.X := XbotRight;
UpperRight.Y := YtopLeft;
end;
function TBackdropFileForm.SetScaling: Boolean;
//-----------------------------------------------------------------------------
// Determines how the backdrop image and the study area map should be
// scaled relative to one another.
//-----------------------------------------------------------------------------
begin
// Default is to scale backdrop to map window extent
Result := True;
Scaling := SCALE_TO_WINDOW;
// Check if world coordinates were supplied for backdrop image
if XtopLeft <> XbotRight then
begin
// Default is no scaling
Scaling := SCALE_TO_NOTHING;
// Scale map to backdrop if check box checked
if ScaleMapCheckBox.Checked then Scaling := SCALE_TO_BACKDROP
else begin
// Check if there is no overlap between map and backdrop
with MapForm.Map.Dimensions do
begin
if (XtopLeft > UpperRight.X)
or (XbotRight < LowerLeft.X)
or (YtopLeft < LowerLeft.Y)
or (YbotRight > UpperRight.Y) then
// See if user wants to scale backdrop to map
case MessageDlg(MSG_NO_OVERLAP, mtConfirmation,
[mbYes, mbNo, mbCancel], 0) of
mrYES: Scaling := SCALE_TO_MAP;
mrCANCEL: Result := False;
end;
end;
end;
end;
end;
procedure TBackdropFileForm.ScaleMapToBackdrop;
//-----------------------------------------------------------------------------
// Scales the study area map so that it fits within the backdrop image.
//-----------------------------------------------------------------------------
var
LL2 : TExtendedPoint; // Lower left corner coords.
UR2 : TExtendedPoint; // Upper right corner coords.
begin
with MapForm.Map do
begin
// Determine lower left and upper right coords. of backdrop
LL2.X := XtopLeft;
LL2.Y := YbotRight;
UR2.X := LL2.X + Pwidth * Xwpp;
UR2.Y := LL2.Y + Pheight * Ywpp;
// Transform object coords. & map dimensions to those of backdrop
with Dimensions do
begin
Ucoords.TransformCoords(LowerLeft, UpperRight, LL2, UR2);
LowerLeft := LL2;
UpperRight := UR2;
end;
// Rescale the map
Rescale;
end;
end;
procedure TBackdropFileForm.ScaleBackdrop;
//-----------------------------------------------------------------------------
// Scales the backdrop image to fit either within the display window
// or within the extents of the study area map.
//-----------------------------------------------------------------------------
var
Wback : Extended;
Hback : Extended;
W : Extended;
H : Extended;
R : Extended;
Rx : Extended;
Ry : Extended;
begin
with MapForm.Map do
begin
// Compute backdrop width & height in world coords.
Wback := Pwidth * WPPx0;
Hback := Pheight * WPPy0;
// If scaling to window, compute width & height of window
if Scaling = SCALE_TO_WINDOW then
begin
W := Window.Pwidth * WPPx0;
H := Window.Pheight * WPPy0;
end
// Otherwise find width & height of map
else with Dimensions do
begin
W := UpperRight.X - LowerLeft.X;
H := UpperRight.Y - LowerLeft.Y;
end;
// Expand picture, if necessary, to fill display extent without distortion
Rx := W / Wback;
Ry := H / Hback;
R := Min(Rx, Ry);
if R > 1.0 then
begin
Wback := R * Wback;
Hback := R * Hback;
end;
// Reduce picture if it's wider or taller than display extent
if Wback > W then
begin
R := W / Wback;
Wback := R * Wback;
Hback := R * Hback;
end;
if Hback > H then
begin
R := H / Hback;
Wback := R * Wback;
Hback := R * Hback;
end;
// Save corner coords. of centered backdrop image
XtopLeft := ZoomState[0].Xcenter - Wback/2.0;
YtopLeft := ZoomState[0].Ycenter + Hback/2.0;
XbotRight := XtopLeft + Wback;
YbotRight := YtopLeft - Hback;
// Re-dimension map to include backdrop image's extent
with Dimensions do
begin
LowerLeft.X := Min(LowerLeft.X, XtopLeft);
LowerLeft.Y := Min(LowerLeft.Y, YbotRight);
UpperRight.X := Max(UpperRight.X, XbotRight);
UpperRight.Y := Max(UpperRight.Y, YtopLeft);
end;
Rescale;
end;
end;
procedure TBackdropFileForm.HelpBtnClick(Sender: TObject);
begin
Application.HelpCommand(HELP_CONTEXT, 212970);
end;
procedure TBackdropFileForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F1 then HelpBtnClick(Sender);
end;
end.
|
unit Magento.ExtensionAttributes;
interface
uses
Magento.Interfaces, System.JSON, System.Generics.Collections;
type
TMagentoExtensionAttributes = class (TInterfacedObject, iMagentoExtensionAttributes)
private
FParent : iMagentoEntidadeProduto;
FJSON : TJSONObject;
FCategoryLink : iMagentoCategory_Links;
public
constructor Create(Parent : iMagentoEntidadeProduto);
destructor Destroy; override;
class function New(Parent : iMagentoEntidadeProduto) : iMagentoExtensionAttributes;
function Category_Links : iMagentoCategory_Links; overload;
function Category_Links(value : TJSONArray) : iMagentoExtensionAttributes; overload;
function Category_Links(value : TDictionary<Integer, String>) : iMagentoExtensionAttributes; overload;
function Stock_item :iMagentoStock_Item; overload;
function Stock_item(value : TJSONObject) : iMagentoExtensionAttributes; overload;
function &End : iMagentoEntidadeProduto;
end;
implementation
{ TMagentoExtensionAttributes }
uses Magento.Factory, System.SysUtils;
function TMagentoExtensionAttributes.Category_Links: iMagentoCategory_Links;
begin
Result := TMagentoFactory.New.Category_Links(Self);
end;
function TMagentoExtensionAttributes.&End: iMagentoEntidadeProduto;
begin
FParent.Extension_attributes(FJSON);
Result := FParent;
end;
function TMagentoExtensionAttributes.Category_Links(
value: TJSONArray): iMagentoExtensionAttributes;
begin
Result := Self;
FJSON.AddPair('category_Links',value);
end;
function TMagentoExtensionAttributes.Category_Links(
value: TDictionary<Integer, String>): iMagentoExtensionAttributes;
var
Key : Integer;
lJSONArray : TJSONArray;
lJSON : TJSONObject;
begin
Result := Self;
value.Add(3,'0');
lJSONArray := TJSONArray.Create;
for Key in Value.Keys do
begin
lJSON := TJSONObject.Create;
lJSON.AddPair('position',TJSONNumber.Create(StrToInt(Value.Items[key])));
lJSON.AddPair('category_id',IntToStr(key));
lJSONArray.Add(lJSON);
end;
FJSON.AddPair('category_Links',lJSONArray);
end;
constructor TMagentoExtensionAttributes.Create(Parent : iMagentoEntidadeProduto);
begin
FParent := Parent;
FJSON := TJSONObject.Create;
end;
destructor TMagentoExtensionAttributes.Destroy;
begin
// FJSON.DisposeOf;
inherited;
end;
class function TMagentoExtensionAttributes.New(Parent : iMagentoEntidadeProduto) : iMagentoExtensionAttributes;
begin
Result := self.Create(Parent);
end;
function TMagentoExtensionAttributes.Stock_item(
value: TJSONObject): iMagentoExtensionAttributes;
begin
Result := Self;
FJSON.AddPair('stock_item', value);
end;
function TMagentoExtensionAttributes.Stock_item: iMagentoStock_Item;
begin
Result := TMagentoFactory.New.Stock_Item(Self);
end;
end.
|
unit EstoqueFactory.View;
interface
uses EstoqueFactory.View.interf, Base.View.interf, Tipos.Controller.interf;
type
TEstoqueFactoryView = class(TInterfacedObject, IEstoqueFactoryView)
private
public
constructor Create;
destructor Destroy; override;
class function New: IEstoqueFactoryView;
function exibirTelaBusca(AValue: TTelaBusca): IBaseLocalizarView;
function exibirTelaListagem(AValue: TTelaListagem): IBasePesquisaView;
function exibirTelaCadastro(AValue: TTelaCadastro): IBaseCadastroView;
function exibirTelaImportacao(AValue: TTelaImportacao): IBaseImportarView;
end;
implementation
{ TEstoqueFactoryView }
uses EST0001P.View, EST0001C.View, EST0001I.View, EST0002P.View, EST0002C.View,
EST0001L.View,
EST0003P.View, EST0003I.View;
constructor TEstoqueFactoryView.Create;
begin
end;
destructor TEstoqueFactoryView.Destroy;
begin
inherited;
end;
function TEstoqueFactoryView.exibirTelaBusca(AValue: TTelaBusca)
: IBaseLocalizarView;
begin
case AValue of
tbProduto:
Result := TFEST0001LView.New;
end;
end;
function TEstoqueFactoryView.exibirTelaCadastro(AValue: TTelaCadastro)
: IBaseCadastroView;
begin
case AValue of
tcProduto:
Result := TFEST0001CView.New;
tcOrcamento:
Result := TFEST0002CView.New;
end;
end;
function TEstoqueFactoryView.exibirTelaImportacao(AValue: TTelaImportacao)
: IBaseImportarView;
begin
case AValue of
tiProduto:
Result := TFEST0001IView.New;
tiCotacao:
Result := TFEST0003IView.New;
end;
end;
function TEstoqueFactoryView.exibirTelaListagem(AValue: TTelaListagem)
: IBasePesquisaView;
begin
case AValue of
tlProduto:
Result := TFEST0001PView.New;
tlOrcamento:
Result := TFEST0002PView.New;
tlCotacao:
Result := TFEST0003PView.New;
end;
end;
class function TEstoqueFactoryView.New: IEstoqueFactoryView;
begin
Result := Self.Create;
end;
end.
|
(*
Copyright (c) 2016 Darian Miller
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice
appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE
LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other
dealings in this Software without prior written authorization of the copyright holder.
As of January 2016, latest version available online at:
https://github.com/darianmiller/dxLib_Tests
*)
unit dxLib_Test_JSONObjectAssign;
interface
{$I '..\Dependencies\dxLib\Source\dxLib.inc'}
uses
TestFramework,
dxLib_JSONObjects;
type
TMyEnum = (myEnum1, myEnum2);
TMyEnumSet = set of TMyEnum;
TExample1 = class(TdxJSONObject)
private
fFirstProp:String;
published
property FirstProp:String read fFirstProp write fFirstProp;
end;
//version 2 of TExampleProp1...should be compatible to always update Server to new version ahead of Client.
//but dataloss occurs if updating Client ahead of Server
TExample2 = class(TdxJSONObject)
private
fFirstProp:String;
fNewProp:String;
published
property FirstProp:String read fFirstProp write fFirstProp;
property NewProp:String read fNewProp write fNewProp;
end;
TExampleString = class(TdxJSONObject)
private
fAString:String;
fAInteger:String;
fAInt64:String;
fABoolean:String;
fADouble:String;
fACurrency:String;
fAMyEnum:String;
fAMyEmumSet:String;
fAVariant:String;
fAClass:String;
published
property AString:String read fAString write fAString;
property AInteger:String read fAInteger write fAInteger;
property AInt64:String read fAInt64 write fAInt64;
property ABoolean:String read fABoolean write fABoolean;
property ADouble:String read fADouble write fADouble;
property ACurrency:String read fACurrency write fACurrency;
property AMyEnum:String read fAMyEnum write fAMyEnum;
property AMyEmumSet:String read fAMyEmumSet write fAMyEmumSet;
property AVariant:String read fAVariant write fAVariant;
property AClass:String read fAClass write fAClass;
end;
TExampleTypes = class(TdxJSONObject)
private
fAString:String;
fAInteger:Integer;
fAInt64:Int64;
fABoolean:Boolean;
fADouble:Double;
fACurrency:Currency;
fAMyEnum:TMyEnum;
fAMyEmumSet:TMyEnumSet;
fAVariant:Variant;
fAClass:TExample1;
public
constructor Create(); override;
destructor Destroy(); override;
procedure PopulateProperties();
published
property AString:String read fAString write fAString;
property AInteger:Integer read fAInteger write fAInteger;
property AInt64:Int64 read fAInt64 write fAInt64;
property ABoolean:Boolean read fABoolean write fABoolean;
property ADouble:Double read fADouble write fADouble;
property ACurrency:Currency read fACurrency write fACurrency;
property AMyEnum:TMyEnum read fAMyEnum write fAMyEnum;
property AMyEmumSet:TMyEnumSet read fAMyEmumSet write fAMyEmumSet;
property AVariant:Variant read fAVariant write fAVariant;
property AClass:TExample1 read fAClass write fAClass;
end;
TestTdxJSONObjectAssign = class(TTestCase)
published
procedure TestSameClassSingleProperty();
procedure TestBackwardsCompatibility();
procedure TestDataLossForwardCompatibility();
procedure TestTypeClash();
procedure TestNullAssign();
end;
implementation
uses
dxLib_JSONUtils,
dxLib_Strings;
procedure TestTdxJSONObjectAssign.TestSameClassSingleProperty();
var
vFirst, vSecond:TExample1;
begin
vFirst := TExample1.Create;
vSecond := TExample1.Create;
try
vFirst.FirstProp := '1';
vSecond.Assign(vFirst);
CheckEqualsString(vFirst.AsJSON, vSecond.AsJSON);
finally
vFirst.Free();
vSecond.Free();
end;
end;
procedure TestTdxJSONObjectAssign.TestBackwardsCompatibility();
var
vClient:TExample1;
vServer:TExample2;
begin
vClient := TExample1.Create;
vServer := TExample2.Create;
try
vClient.FirstProp := '1';
vServer.FirstProp := 'n/a';
vServer.NewProp := 'ignored';
//common action - client sends data to server
vServer.AsJSON := vClient.AsJSON;
CheckEqualsString(vServer.FirstProp, vClient.FirstProp);
CheckEqualsString(vServer.NewProp, ''); //when assigned, current values are reset so this should be 0
finally
vClient.Free();
vServer.Free();
end;
end;
procedure TestTdxJSONObjectAssign.TestDataLossForwardCompatibility();
var
vClientV2:TExample2;
vServerV1:TExample1;
begin
vClientV2 := TExample2.Create;
vServerV1 := TExample1.Create;
try
vClientV2.FirstProp := '1';
vClientV2.NewProp := 'data';
vServerV1.FirstProp := '2';
//common action - client sends data to server
vServerV1.AsJSON := vClientV2.AsJSON;
//existing properties are updated
CheckEqualsString(vServerV1.FirstProp, vClientV2.FirstProp);
//but note data loss, vClientV2.NewProp has no where to go
finally
vClientV2.Free();
vServerV1.Free();
end;
end;
procedure TestTdxJSONObjectAssign.TestTypeClash();
var
aStrings:TExampleString;
aExpected:TExampleString;
aTypes:TExampleTypes;
v1,v2:String;
begin
aStrings := TExampleString.Create;
aTypes := TExampleTypes.Create;
aExpected := TExampleString.Create;
try
aTypes.PopulateProperties();
//classes have same property names, but all strings being assigned..typically not a problem in Delphi client/server coding
//This is more of a problem if receiving JSON from non-delphi sources and your
//data type is incorrectly defined within your Delphi class as data-loss may occur
aStrings.AsJSON := aTypes.AsJSON;
//Not all types are converted...more effort needed to better support mis-matched object property types..
aExpected.AString := aTypes.AString;
aExpected.AInteger := '1';
aExpected.AInt64 := '2';
aExpected.AMyEnum := 'myEnum2';
aExpected.AMyEmumSet := 'myEnum1,myEnum2';
aExpected.AVariant := 'testing';
v1 := aStrings.AsJSON;
v2 := aExpected.AsJSON;
CheckEqualsString(v2, v1);
finally
aExpected.Free();
aStrings.Free();
aTypes.Free();
end;
end;
procedure TestTdxJSONObjectAssign.TestNullAssign();
var
aTypes:TExampleTypes;
begin
aTypes := TExampleTypes.Create();
try
aTypes.PopulateProperties;
aTypes.AsJSON := '{"AString":null,'
+ '"AInteger":null,'
+ '"AInt64":null,'
+ '"ABoolean":null,'
+ '"ADouble":null,'
+ '"ACurrency":null,'
+ '"AMyEnum":null,'
+ '"AMyEmumSet":null,'
+ '"AVariant":null,'
+ '"AClass":null}';
//If delphi doesn't support this option, it defaults to a sorted property list
{$IFDEF DX_Supports_Sorted_GetPropList}
//In later versions of Delphi the list of properties will be left-alone...remains as-sorted by the developer
CheckEqualsString('{"AString":"null","AInteger":0,"AInt64":0,"ABoolean":false,"ADouble":0,"ACurrency":0.00,"AMyEnum":"myEnum1","AMyEmumSet":"","AVariant":"null","AClass":{"FirstProp":""}}',
aTypes.AsJSON);
{$ELSE}
//older versions of Delphi auto-sort the property list alphabetically
CheckEqualsString('{"ABoolean":false,"AClass":{"FirstProp":""},"ACurrency":0.00,"ADouble":0,"AInt64":0,"AInteger":0,"AMyEmumSet":"","AMyEnum":"myEnum1","AString":"null","AVariant":"null"}',
aTypes.AsJSON);
{$ENDIF}
finally
aTypes.Free();
end;
end;
constructor TExampleTypes.Create;
begin
inherited;
fAClass := TExample1.Create();
end;
destructor TExampleTypes.Destroy;
begin
fAClass.Free();
inherited;
end;
procedure TExampleTypes.PopulateProperties();
begin
AString := 'a';
AInteger := 1;
AInt64 := 2;
ABoolean := True;
ADouble := 2.2;
ACurrency := 233.00;
AMyEnum := myEnum2;
AMyEmumSet := [myEnum1,myEnum2];
AVariant := 'testing';
AClass.FirstProp := 'one';
end;
initialization
RegisterTest(TestTdxJSONObjectAssign.Suite);
end.
|
unit UGraphGroup;
interface
uses SysUtils;
Type
TNodeGroup = class;
TNode = class
Name:string;
Pheromon:array of Double;
Group:TNodeGroup;
NextNode:array of TNode;
Constructor Create(NameNode:string; KolTypePheromon:Byte);
Destructor Destroy;
end;
TNodeGroup = class
Name:string;
NomGroup:Longword;
Node:array of TNode;
Procedure GenerateNode(XNat,XKon,ShagX:Double; KolTypePheromon:Byte);
Constructor Create(NameGroup:string; NomGroupGraph:Longword);
Destructor Destroy;
end;
TGraphGroup = Class
Name:string;
KolTypePheromon:Byte;
Group:Array of TNodeGroup;
Procedure LoadGraphInTxtFile(var Graph:TGraphGroup; NameFile:string);
Procedure AddGroup(NameGroup:string);
Constructor Create(NameGraph:string; KolTypePheromonGraph:Byte);
Destructor Destroy;
end;
implementation
Procedure TGraphGroup.LoadGraphInTxtFile(var Graph:TGraphGroup; NameFile:string);
var
f:textfile;
st:string;
NameGraph:string;
NameGroup:string;
KolTypePheromonGraph:Byte;
XNat,XKon,ShagX:Double;
begin
AssignFile(f,NameFile);
reset(f);
if not EOF(f) then
begin
Readln(f,NameGraph);
Readln(f,st);
KolTypePheromonGraph:=StrToInt(st);
Graph:=TGraphGroup.Create(NameGraph,KolTypePheromonGraph);
while not EOF(f) do
begin
Readln(f,NameGroup);
Graph.AddGroup(NameGroup);
Readln(f,st);
XNat:=StrToFloat(Copy(st,1,pos(';',st)-1));
Delete(st,1,pos(';',st));
XKon:=StrToFloat(Copy(st,1,pos(';',st)-1));
Delete(st,1,pos(';',st));
ShagX:=StrToFloat(Copy(st,1,pos(';',st)-1));
end;
end;
CloseFile(f);
end;
Procedure TGraphGroup.AddGroup(NameGroup:string);
var
KolGroup:Longword;
begin
KolGroup:=Length(Group);
SetLength(Group,KolGroup+1);
Group[KolGroup]:=TNodeGroup.Create(NameGroup,KolGroup);
end;
Procedure TNodeGroup.GenerateNode(XNat,XKon,ShagX:Double;KolTypePheromon:Byte);
var
CurrentX:Double;
KolNode:Longword;
begin
CurrentX:=XNat;
KolNode:=0;
while CurrentX<XKon do
begin
Inc(KolNode);
SetLength(Node,KolNode);
Node[KolNode-1]:=TNode.Create(FloatToStr(CurrentX),KolTypePheromon);
Node[KolNode-1].Group:=self;
CurrentX:=CurrentX+ShagX;
end;
end;
Constructor TGraphGroup.Create(NameGraph:string; KolTypePheromonGraph:Byte);
begin
Name:=NameGraph;
KolTypePheromon:=KolTypePheromonGraph;
SetLength(Group,0);
end;
Destructor TGraphGroup.Destroy;
var
NomGroup:Longword;
begin
NomGroup:=0;
while NomGroup<Length(Group) do
begin
Group[NomGroup].Destroy;
inc(NomGroup);
end;
SetLength(Group,0);
end;
Constructor TNodeGroup.Create(NameGroup:string; NomGroupGraph:Longword);
begin
Name:=NameGroup;
NomGroup:=NomGroupGraph;
SetLength(Node,0);
end;
Destructor TNodeGroup.Destroy;
var
NomNode:Longword;
begin
NomNode:=0;
while NomNode<length(Node) do
begin
Node[NomNode].Destroy;
inc(NomNode);
end;
SetLength(Node,0);
end;
Constructor TNode.Create(NameNode:string; KolTypePheromon:Byte);
begin
Name:=NameNode;
SetLength(Pheromon,KolTypePheromon);
setLength(NextNode,0);
Group:=nil;
end;
Destructor TNode.Destroy;
begin
SetLength(Pheromon,0);
setLength(NextNode,0);
Group:=nil;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.IDE.IconCache;
interface
uses
System.Types,
Spring.Collections,
SVGInterfaces,
Vcl.Graphics,
Vcl.Imaging.pngimage,
DPM.Core.Package.Interfaces,
DPM.Core.Types;
type
//This is a wrapper around either an svg or a png.
IPackageIconImage = interface
['{E5617EA7-DEA6-41CF-BC40-64DF7705C6D6}']
procedure PaintTo(const ACanvas : TCanvas; const bounds : TRect);
function ToGraphic : TGraphic;
end;
//In memory cache for package icons.
//TODO : back this with a disk cache, this will be more important to avoid http requests.
type
TDPMIconCache = class
private
FIcons : IDictionary<string, IPackageIconImage>;
FLock : TObject;
protected
public
constructor Create;
destructor Destroy; override;
function Query(const id : string) : boolean;
function Request(const id : string) : IPackageIconImage;
procedure Cache(const id : string; const value : IPackageIconImage);
end;
TPackageIconImage = class(TInterfacedObject, IPackageIconImage)
private
FSVG : ISVG;
FPng : TPngImage;
FKind : TPackageIconKind;
protected
procedure PaintTo(const ACanvas : TCanvas; const bounds : TRect);
function ToGraphic : TGraphic;
public
constructor Create(const icon : IPackageIcon); overload;
constructor Create(const icon : ISVG); overload;
constructor Create(const icon : TPngImage); overload;
destructor Destroy; override;
end;
implementation
uses
System.Classes,
System.SysUtils,
SVGGraphic;
{ TDPMIconCache }
procedure TDPMIconCache.Cache(const id : string; const value : IPackageIconImage);
begin
MonitorEnter(FLock);
try
FIcons[LowerCase(Id)] := value;
finally
MonitorExit(FLock);
end;
end;
constructor TDPMIconCache.Create;
var
ResStream : TResourceStream;
missingImg : ISVG;
begin
inherited;
FIcons := TCollections.CreateDictionary < string, IPackageIconImage > ;
FLock := TObject.Create;
missingImg := GlobalSVGFactory.NewSvg;
resStream := TResourceStream.Create(hInstance, 'DPM_ICON_MISSING_SVG', RT_RCDATA);
try
missingImg := GlobalSVGFactory.NewSvg;
missingImg.LoadFromStream(ResStream);
finally
ResStream.Free;
end;
missingImg.Opacity := 0.333;
FIcons['missing_icon'] := TPackageIconImage.Create(missingImg);
end;
destructor TDPMIconCache.Destroy;
begin
MonitorEnter(FLock);
try
FIcons.Clear;
finally
MonitorExit(FLock);
end;
FLock.Free;
inherited;
end;
function TDPMIconCache.Query(const id : string) : boolean;
begin
MonitorEnter(FLock);
try
result := FIcons.ContainsKey(LowerCase(id));
if not result then
FIcons[LowerCase(Id)] := nil;
finally
MonitorExit(FLock);
end;
end;
function TDPMIconCache.Request(const id : string) : IPackageIconImage;
begin
result := nil;
if id = '' then
exit;
MonitorEnter(FLock);
try
if FIcons.ContainsKey(LowerCase(id)) then
result := FIcons[LowerCase(Id)];
finally
MonitorExit(FLock);
end;
end;
{ TPackageIconImage }
constructor TPackageIconImage.Create(const icon : IPackageIcon);
begin
FKind := icon.Kind;
FPng := nil;
case icon.Kind of
ikSvg :
begin
FSVG := GlobalSVGFactory.NewSvg;
FSVG.LoadFromStream(icon.Stream);
end;
ikPng :
begin
FPng := TPngImage.Create;
icon.stream.Position := 0;
FPng.LoadFromStream(icon.stream);
end;
end;
end;
constructor TPackageIconImage.Create(const icon : ISVG);
begin
FSVG := icon;
FKind := TPackageIconKind.ikSvg;
end;
destructor TPackageIconImage.Destroy;
begin
if FPng <> nil then
FPng.Free;
inherited;
end;
procedure TPackageIconImage.PaintTo(const ACanvas : TCanvas; const bounds : TRect);
begin
case FKind of
ikSvg : FSVG.PaintTo(ACanvas.Handle, TRectF.Create(bounds));
ikPng : FPng.Draw(ACanvas, bounds);
end;
end;
function TPackageIconImage.ToGraphic : TGraphic;
var
svgGraphic : TSVGGraphic;
clonedSVG : ISVG;
clonedPng : TPngImage;
begin
result := nil;
case FKind of
ikSvg :
begin
clonedSVG := GlobalSVGFactory.NewSvg;
clonedSVG.Source := FSVG.Source;
svgGraphic := TSVGGraphic.Create;
svgGraphic.AssignSVG(clonedSVG);
exit(svgGraphic);
end;
ikPng :
begin
clonedPng := TPngImage.Create;
clonedPng.Assign(FPng);
exit(clonedPng);
end;
end;
end;
constructor TPackageIconImage.Create(const icon : TPngImage);
begin
FPng := TPngImage.Create;
FPng.Assign(icon);
FKind := TPackageIconKind.ikPng;
end;
end.
|
unit MensagensUtils;
interface
uses
Dialogs, Forms, Graphics, StdCtrls, Windows, SysUtils, Controls, uFrmConfirm;
function Confirma(mensagem: string): Boolean;
procedure Informacao(mensagem: string);
procedure Erro(mensagem: string);
procedure Atencao(mensagem: string);
function MessageDlgCustom(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; ToCaptions: array of string; customFont: TFont) : integer;
procedure ModifyDialog(var frm: TForm; ToCaptions : array of string; customFont : TFont = nil);
implementation
uses uFrmInformation, uFrmError, uFrmWarning;
function Confirma(mensagem: string): Boolean;
var
f: TFrmConfirm;
begin
Result := False;
f := TFrmConfirm.Create(nil);
try
f.Mensagem := mensagem;
case f.ShowModal of
mrYes: Result := True;
mrNo: Result := False;
end;
finally
f.Free;
end;
end;
procedure Informacao(mensagem: string);
var
f: TFrmInformation;
begin
f := TFrmInformation.Create(nil);
try
f.Mensagem := mensagem;
f.ShowModal;
finally
f.Free;
end;
end;
procedure Erro(mensagem: string);
var
f: TFrmError;
begin
f := TFrmError.Create(nil);
try
f.Mensagem := mensagem;
f.ShowModal;
finally
f.Free;
end;
end;
procedure Atencao(mensagem: string);
var
f: TFrmWarning;
begin
f := TFrmWarning.Create(nil);
try
f.Mensagem := mensagem;
f.ShowModal;
finally
f.Free;
end;
end;
function GetTextWidth(s: string; fnt: TFont; HWND: THandle): integer;
var
canvas: TCanvas;
begin
canvas := TCanvas.Create;
try
canvas.Handle := GetWindowDC(HWND);
canvas.Font := fnt;
Result := canvas.TextWidth(s);
finally
ReleaseDC(HWND,canvas.Handle);
FreeAndNil(canvas);
end;
end;
function MessageDlgCustom(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; ToCaptions: array of string; customFont: TFont): integer;
var
dialog : TForm;
begin
try
dialog := CreateMessageDialog(Msg, DlgType, Buttons);
dialog.Position := poScreenCenter;
ModifyDialog(dialog,ToCaptions,customFont);
Result := dialog.ShowModal;
finally
dialog.Release;
end;
end;
procedure ModifyDialog(var frm: TForm; ToCaptions: array of string; customFont: TFont);
const
c_BtnMargin = 20;
var
i,oldButtonWidth,newButtonWidth,btnCnt : integer;
begin
oldButtonWidth := 0;
newButtonWidth := 0;
btnCnt := 0;
for i := 0 to frm.ComponentCount - 1 do begin
//if they asked for a custom font, assign it here
if customFont <> nil then begin
if frm.Components[i] is TLabel then begin
TLabel(frm.Components[i]).Font := customFont;
end;
if frm.Components[i] is TButton then begin
TButton(frm.Components[i]).Font := customFont;
end;
end;
if frm.Components[i] is TButton then begin
//check buttons for a match with a "from" (default) string
//if found, replace with a "to" (custom) string
Inc(btnCnt);
//record the button width *before* we changed the caption
oldButtonWidth := oldButtonWidth + TButton(frm.Components[i]).Width;
//change the caption
TButton(frm.Components[i]).Caption := ToCaptions[btnCnt - 1];
//auto-size the button for the new caption
TButton(frm.Components[i]).Width :=
GetTextWidth(TButton(frm.Components[i]).Caption,
TButton(frm.Components[i]).Font,frm.Handle) + c_BtnMargin;
//the first button can stay where it is.
//all other buttons need to slide over to the right of the one b4.
if (1 < btnCnt) and (0 < i) then
begin
TButton(frm.Components[i]).Left :=
TButton(frm.Components[i-1]).Left +
TButton(frm.Components[i-1]).Width + c_BtnMargin;
end;
//record the button width *after* changing the caption
newButtonWidth := newButtonWidth + TButton(frm.Components[i]).Width;
end; //if TButton
end; //for i
//whatever we changed the buttons by, widen / shrink the form accordingly
frm.Width := Round(frm.Width + (newButtonWidth - oldButtonWidth) + (c_BtnMargin * btnCnt));
end;
end.
|
unit
xStreamUnit;
interface
{$WARNINGS OFF}
uses
Windows;
const
soFromBeginning = 0;
soFromCurrent = 1;
soFromEnd = 2;
type
Int64Rec = packed record
case Integer of
0: (Lo, Hi: Cardinal);
1: (Cardinals: array [0..1] of Cardinal);
2: (Words: array [0..3] of Word);
3: (Bytes: array [0..7] of Byte);
end;
TNotifyEvent = procedure(Sender: TObject) of object;
TSeekOrigin = (soBeginning, soCurrent, soEnd);
TStream = class(TObject)
private
function GetPosition: Int64;
procedure SetPosition(const Pos: Int64);
procedure SetSize64(const NewSize: Int64);
protected
function GetSize: Int64; virtual;
procedure SetSize(NewSize: Longint); overload; virtual;
procedure SetSize(const NewSize: Int64); overload; virtual;
public
function Read(var Buffer; Count: Longint): Longint; virtual; abstract;
function Write(const Buffer; Count: Longint): Longint; virtual; abstract;
function Seek(Offset: Longint; Origin: Word): Longint; overload; virtual;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; overload; virtual;
procedure ReadBuffer(var Buffer; Count: Longint);
procedure WriteBuffer(const Buffer; Count: Longint);
function CopyFrom(Source: TStream; Count: Int64): Int64;
property Position: Int64 read GetPosition write SetPosition;
property Size: Int64 read GetSize write SetSize64;
end;
IStreamPersist = interface
['{B8CD12A3-267A-11D4-83DA-00C04F60B2DD}']
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
end;
{ THandleStream class }
THandleStream = class(TStream)
protected
FHandle: Integer;
procedure SetSize(NewSize: Longint); override;
procedure SetSize(const NewSize: Int64); override;
public
constructor Create(AHandle: Integer);
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
property Handle: Integer read FHandle;
end;
{ TFileStream class }
TFileStream = class(THandleStream)
public
constructor Create(const FileName: widestring; Mode: Word); overload;
constructor Create(const FileName: widestring; Mode: Word; Rights: Cardinal); overload;
destructor Destroy; override;
end;
{ TCustomMemoryStream abstract class }
TCustomMemoryStream = class(TStream)
private
FMemory: Pointer;
FSize, FPosition: Longint;
protected
procedure SetPointer(Ptr: Pointer; Size: Longint);
public
function Read(var Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
procedure SaveToStream(Stream: TStream);
procedure SaveToFile(const FileName: widestring);
property Memory: Pointer read FMemory;
end;
{ TMemoryStream }
TMemoryStream = class(TCustomMemoryStream)
private
FCapacity: Longint;
procedure SetCapacity(NewCapacity: Longint);
protected
function Realloc(var NewCapacity: Longint): Pointer; virtual;
property Capacity: Longint read FCapacity write SetCapacity;
public
destructor Destroy; override;
procedure Clear;
procedure LoadFromStream(Stream: TStream);
procedure LoadFromFile(const FileName: widestring);
procedure SetSize(NewSize: Longint); override;
function Write(const Buffer; Count: Longint): Longint; override;
end;
function FileSeek(Handle, Offset, Origin: Integer): Integer; overload;
function FileSeek(Handle: Integer; const Offset: Int64; Origin: Integer): Int64; overload;
function FileCreate(const FileName: widestring): Integer; overload;
function FileCreate(const FileName: widestring; Rights: Integer): Integer; overload;
procedure StrToStream(S: TStream; const SS: WideString);
function StreamToStr(S: TStream): WideString;
implementation
const
fmCreate = $FFFF;
fmOpenRead = $0000;
fmOpenWrite = $0001;
fmOpenReadWrite = $0002;
fmShareCompat = $0000;
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
fmShareDenyRead = $0030;
fmShareDenyNone = $0040;
function StreamToStr(S: TStream): WideString;
var
SizeStr: integer;
begin
S.Position := 0;
SizeStr := S.Size;
SetLength(Result, SizeStr div 2);
S.Read(Result[1], SizeStr);
end;
procedure StrToStream(S: TStream; const SS: WideString);
var
SizeStr: integer;
begin
S.Position := 0;
SizeStr := Length(SS);
S.Write(SS[1], SizeStr * 2);
end;
function TStream.GetPosition: Int64;
begin
Result := Seek(0, soCurrent);
end;
procedure TStream.SetPosition(const Pos: Int64);
begin
Seek(Pos, soBeginning);
end;
function TStream.GetSize: Int64;
var
Pos: Int64;
begin
Pos := Seek(0, soCurrent);
Result := Seek(0, soEnd);
Seek(Pos, soBeginning);
end;
procedure TStream.SetSize(NewSize: Longint);
begin
// default = do nothing (read-only streams, etc)
// descendents should implement this method to call the Int64 sibling
end;
procedure TStream.SetSize64(const NewSize: Int64);
begin
SetSize(NewSize);
end;
procedure TStream.SetSize(const NewSize: Int64);
begin
SetSize(Longint(NewSize));
end;
function TStream.Seek(Offset: Longint; Origin: Word): Longint;
type
TSeek64 = function (const Offset: Int64; Origin: TSeekOrigin): Int64 of object;
var
Impl: TSeek64;
Base: TSeek64;
ClassTStream: TClass;
begin
Impl := Seek;
ClassTStream := Self.ClassType;
while (ClassTStream <> nil) and (ClassTStream <> TStream) do
ClassTStream := ClassTStream.ClassParent;
Base := TStream(@ClassTStream).Seek;
Result := Seek(Int64(Offset), TSeekOrigin(Origin));
end;
function TStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
Result := Seek(Longint(Offset), Ord(Origin));
end;
procedure TStream.ReadBuffer(var Buffer; Count: Longint);
begin
Read(Buffer, Count);
end;
procedure TStream.WriteBuffer(const Buffer; Count: Longint);
begin
Write(Buffer, Count);
end;
function TStream.CopyFrom(Source: TStream; Count: Int64): Int64;
const
MaxBufSize = $F000;
var
BufSize, N: Integer;
Buffer: PChar;
begin
if Count = 0 then
begin
Source.Position := 0;
Count := Source.Size;
end;
Result := Count;
if Count > MaxBufSize then BufSize := MaxBufSize else BufSize := Count;
GetMem(Buffer, BufSize);
try
while Count <> 0 do
begin
if Count > BufSize then N := BufSize else N := Count;
Source.ReadBuffer(Buffer^, N);
WriteBuffer(Buffer^, N);
Dec(Count, N);
end;
finally
FreeMem(Buffer, BufSize);
end;
end;
{ THandleStream }
function FileRead(Handle: Integer; var Buffer; Count: LongWord): Integer;
begin
if not ReadFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then
Result := -1;
end;
function FileWrite(Handle: Integer; const Buffer; Count: LongWord): Integer;
begin
if not WriteFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then
Result := -1;
end;
constructor THandleStream.Create(AHandle: Integer);
begin
inherited Create;
FHandle := AHandle;
end;
function THandleStream.Read(var Buffer; Count: Longint): Longint;
begin
Result := FileRead(FHandle, Buffer, Count);
if Result = -1 then Result := 0;
end;
function THandleStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := FileWrite(FHandle, Buffer, Count);
if Result = -1 then Result := 0;
end;
function FileSeek(Handle, Offset, Origin: Integer): Integer;
begin
Result := SetFilePointer(THandle(Handle), Offset, nil, Origin);
end;
function FileSeek(Handle: Integer; const Offset: Int64; Origin: Integer): Int64;
begin
Result := Offset;
Int64Rec(Result).Lo := SetFilePointer(THandle(Handle), Int64Rec(Result).Lo,
@Int64Rec(Result).Hi, Origin);
end;
function THandleStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
Result := FileSeek(FHandle, Offset, Ord(Origin));
end;
procedure THandleStream.SetSize(NewSize: Longint);
begin
SetSize(Int64(NewSize));
end;
function Win32Check(RetVal: BOOL): BOOL;
begin
Result := RetVal;
end;
procedure THandleStream.SetSize(const NewSize: Int64);
begin
Seek(NewSize, soBeginning);
Win32Check(SetEndOfFile(FHandle));
end;
{ TFileStream }
constructor TFileStream.Create(const FileName: widestring; Mode: Word);
begin
Create(Filename, Mode, 0);
end;
function FileCreate(const FileName: widestring): Integer;
begin
Result := Integer(CreateFileW(PWChar(FileName), GENERIC_READ or GENERIC_WRITE,
0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0));
end;
function FileCreate(const FileName: widestring; Rights: Integer): Integer;
begin
Result := FileCreate(FileName);
end;
function FileOpen(const FileName: widestring; Mode: LongWord): Integer;
const
AccessMode: array[0..2] of LongWord = (
GENERIC_READ,
GENERIC_WRITE,
GENERIC_READ or GENERIC_WRITE);
ShareMode: array[0..4] of LongWord = (
0,
0,
FILE_SHARE_READ,
FILE_SHARE_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE);
begin
Result := -1;
if ((Mode and 3) <= fmOpenReadWrite) and
((Mode and $F0) <= fmShareDenyNone) then
Result := Integer(CreateFileW(PWChar(FileName), AccessMode[Mode and 3],
ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0));
end;
constructor TFileStream.Create(const FileName: widestring; Mode: Word; Rights: Cardinal);
begin
if Mode = fmCreate then
begin
inherited Create(FileCreate(FileName, Rights));
end
else
begin
inherited Create(FileOpen(FileName, Mode));
end;
end;
procedure FileClose(Handle: Integer);
begin
CloseHandle(THandle(Handle));
end;
destructor TFileStream.Destroy;
begin
if FHandle >= 0 then FileClose(FHandle);
inherited Destroy;
end;
{ TCustomMemoryStream }
procedure TCustomMemoryStream.SetPointer(Ptr: Pointer; Size: Longint);
begin
FMemory := Ptr;
FSize := Size;
end;
function TCustomMemoryStream.Read(var Buffer; Count: Longint): Longint;
begin
if (FPosition >= 0) and (Count >= 0) then
begin
Result := FSize - FPosition;
if Result > 0 then
begin
if Result > Count then Result := Count;
Move(Pointer(Longint(FMemory) + FPosition)^, Buffer, Result);
Inc(FPosition, Result);
Exit;
end;
end;
Result := 0;
end;
function TCustomMemoryStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
case Origin of
soFromBeginning: FPosition := Offset;
soFromCurrent: Inc(FPosition, Offset);
soFromEnd: FPosition := FSize + Offset;
end;
Result := FPosition;
end;
procedure TCustomMemoryStream.SaveToStream(Stream: TStream);
begin
if FSize <> 0 then Stream.WriteBuffer(FMemory^, FSize);
end;
procedure TCustomMemoryStream.SaveToFile(const FileName: widestring);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
{ TMemoryStream }
const
MemoryDelta = $2000; { Must be a power of 2 }
destructor TMemoryStream.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TMemoryStream.Clear;
begin
SetCapacity(0);
FSize := 0;
FPosition := 0;
end;
procedure TMemoryStream.LoadFromStream(Stream: TStream);
var
Count: Longint;
begin
Stream.Position := 0;
Count := Stream.Size;
SetSize(Count);
if Count <> 0 then Stream.ReadBuffer(FMemory^, Count);
end;
procedure TMemoryStream.LoadFromFile(const FileName: widestring);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TMemoryStream.SetCapacity(NewCapacity: Longint);
begin
SetPointer(Realloc(NewCapacity), FSize);
FCapacity := NewCapacity;
end;
procedure TMemoryStream.SetSize(NewSize: Longint);
var
OldPosition: Longint;
begin
OldPosition := FPosition;
SetCapacity(NewSize);
FSize := NewSize;
if OldPosition > NewSize then Seek(0, soFromEnd);
end;
function TMemoryStream.Realloc(var NewCapacity: Longint): Pointer;
begin
if (NewCapacity > 0) and (NewCapacity <> FSize) then
NewCapacity := (NewCapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1);
Result := Memory;
if NewCapacity <> FCapacity then
begin
if NewCapacity = 0 then
begin
GlobalFreePtr(Memory);
Result := nil;
end else
begin
if Capacity = 0 then
Result := GlobalAllocPtr(HeapAllocFlags, NewCapacity)
else
Result := GlobalReallocPtr(Memory, NewCapacity, HeapAllocFlags);
end;
end;
end;
function TMemoryStream.Write(const Buffer; Count: Longint): Longint;
var
Pos: Longint;
begin
if (FPosition >= 0) and (Count >= 0) then
begin
Pos := FPosition + Count;
if Pos > 0 then
begin
if Pos > FSize then
begin
if Pos > FCapacity then
SetCapacity(Pos);
FSize := Pos;
end;
System.Move(Buffer, Pointer(Longint(FMemory) + FPosition)^, Count);
FPosition := Pos;
Result := Count;
Exit;
end;
end;
Result := 0;
end;
end.
|
Unit UNewHolidayParams;
Interface
Uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxCalendar, cxDropDownEdit, cxCalc, cxControls,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, Buttons,
uFControl, uLabeledFControl, uCharControl, uIntControl, uSpravControl,
FIBDatabase, pFIBDatabase, Ibase, pFibQuery, cxLookAndFeelPainters,
cxButtons, ExtCtrls, ActnList, pFibStoredProc, uBoolControl, cxRadioGroup,
cxCheckBox, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, DB, cxDBData, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGridCustomView, cxGrid, cxClasses,
RxMemDS;
Type
TfrmNewHolidayParams = Class(TForm)
WorkDatabase: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
ActionList1: TActionList;
Action1: TAction;
Action2: TAction;
Panel1: TPanel;
Label3: TLabel;
HolidayPeriod: TqFSpravControl;
Label11: TLabel;
WorkDogValue: TqFCharControl;
Label9: TLabel;
PostValue: TqFCharControl;
Label10: TLabel;
IsPostMainValue: TqFBoolControl;
Panel2: TPanel;
OkButton: TBitBtn;
CancelButton: TBitBtn;
Panel3: TPanel;
Label5: TLabel;
Label6: TLabel;
HolidayDayCount: TqFIntControl;
Label7: TLabel;
TotalDayCount: TqFIntControl;
Panel4: TPanel;
Label2: TLabel;
StartDate: TcxDateEdit;
Label8: TLabel;
DateEndForCalc: TcxDateEdit;
Label4: TLabel;
cxButton1: TcxButton;
cxButton2: TcxButton;
PeriodArrayButton: TcxButton;
Panel5: TPanel;
NotFixedTypeHoliday: TcxRadioButton;
Label12: TLabel;
FixedTypeHoliday: TcxRadioButton;
Label1: TLabel;
HolidayType: TqFSpravControl;
Panel6: TPanel;
PeriodsPanel: TPanel;
StyleRepository: TcxStyleRepository;
stBackground: TcxStyle;
stContent: TcxStyle;
stContentEven: TcxStyle;
stContentOdd: TcxStyle;
stFilterBox: TcxStyle;
stFooter: TcxStyle;
stGroup: TcxStyle;
stGroupByBox: TcxStyle;
stHeader: TcxStyle;
stInactive: TcxStyle;
stIncSearch: TcxStyle;
stIndicator: TcxStyle;
stPreview: TcxStyle;
stSelection: TcxStyle;
stHotTrack: TcxStyle;
ContentError: TcxStyle;
qizzStyle: TcxGridTableViewStyleSheet;
ItemsGrid: TcxGrid;
PeopleView: TcxGridDBTableView;
PeopleViewDBColumn2: TcxGridDBColumn;
PeopleViewDBColumn4: TcxGridDBColumn;
PeopleViewDBColumn3: TcxGridDBColumn;
cxGridLevel5: TcxGridLevel;
PeopleViewDBColumn1: TcxGridDBColumn;
PeopleViewDBColumn5: TcxGridDBColumn;
PeriodsDataSet: TRxMemoryData;
PeriodsDataSetdate_beg: TDateTimeField;
PeriodsDataSetdate_end: TDateTimeField;
PeriodsDataSetorder_count: TIntegerField;
PeriodsDataSethol_count: TIntegerField;
PeriodsDataSetsum_count: TIntegerField;
PeriodsDataSource: TDataSource;
Panel7: TPanel;
AddPeriodButton: TcxButton;
cxButton3: TcxButton;
cxButton4: TcxButton;
DayCount: TcxTextEdit;
Procedure OkButtonClick(Sender: TObject);
Procedure CancelButtonClick(Sender: TObject);
Procedure HolidayTypeOpenSprav(Sender: TObject; Var Value: Variant;
Var DisplayText: String);
Procedure HolidayPeriodOpenSprav(Sender: TObject; Var Value: Variant;
Var DisplayText: String);
Procedure cxButton1Click(Sender: TObject);
Procedure cxButton2Click(Sender: TObject);
Procedure DateEndForCalcPropertiesChange(Sender: TObject);
Procedure NotFixedTypeHolidayClick(Sender: TObject);
Procedure FixedTypeHolidayClick(Sender: TObject);
Procedure FormClose(Sender: TObject; Var Action: TCloseAction);
Procedure DateEndForCalcExit(Sender: TObject);
Procedure PeriodArrayButtonClick(Sender: TObject);
Procedure AddPeriodButtonClick(Sender: TObject);
Procedure cxButton3Click(Sender: TObject);
Procedure cxButton4Click(Sender: TObject);
Procedure DayCountExit(Sender: TObject);
Procedure HolidayTypeChange(Sender: TObject);
Procedure HolidayPeriodChange(Sender: TObject);
private
{ Private declarations }
cid_pcard: int64;
cshow_plan_holidays: Integer;
UpdateFlag: integer;
IdGroupHoliday: Variant;
IdGroupHolidayPeriod: Variant;
Function CheckCrossPeriods(Ds: TDataSet; date_beg, date_end: TDateTime): Boolean;
public
{ Public declarations }
out_id_work_dog_moving: Variant;
auto_fill_not_post_main_values: Integer;
id_post: Variant;
is_post_main: Variant;
max_day_count: Integer;
loc_is_insert: Boolean;
id_annual_holiday: Integer;
id_annual_holiday_val: String;
Constructor Create(AOwner: TComponent;
DB_Handle: TISC_DB_HANDLE;
id_type_holiday: integer;
id_holiday_period: variant;
date_start: TdateTime;
end_date: TdateTime;
day_count: integer;
ipcard: int64;
can_edit_holiday: Boolean;
show_plan_holidays: Integer;
id_work_dog_moving: variant;
id_post_in: variant;
is_post_main_in: variant;
show_radio_buttons: Boolean;
is_insert: boolean = false); reintroduce;
End;
Implementation
Uses uUnivSprav, qFTools, FIBQuery, BaseTypes, DateUtils, UpKernelUnit;
{$R *.dfm}
Procedure TfrmNewHolidayParams.OkButtonClick(Sender: TObject);
Begin
If (HolidayPeriod.Value = null) And FixedTypeHoliday.Checked And (Not loc_is_insert)
Then
Begin
agShowMessage('Треба вибрати період, за який надається відпустка!');
exit;
End;
If (HolidayType.Value = null) And FixedTypeHoliday.Checked
Then
Begin
agShowMessage('Треба вибрати тип відпустки!');
exit;
End;
If DayCount.EditValue = null
Then
Begin
agShowMessage('Треба ввести кількість днів відпустки!');
exit;
End;
ModalResult := mrYes;
End;
Procedure TfrmNewHolidayParams.CancelButtonClick(Sender: TObject);
Begin
ModalResult := mrNo;
End;
Procedure TfrmNewHolidayParams.HolidayTypeOpenSprav(Sender: TObject;
Var Value: Variant; Var DisplayText: String);
Var
Params: TUnivParams;
OutPut: TRxMemoryData;
Begin
Params.FormCaption := 'Довідник типів відпусток';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
If cshow_plan_holidays = -1
Then
Params.TableName := 'HL_SP_TYPE_HOLIDAY_SEL';
If cshow_plan_holidays = 0
Then
Params.TableName := 'HL_SP_TYPE_NPHOLIDAY_SEL';
If cshow_plan_holidays = 1
Then
Params.TableName := 'HL_SP_TYPE_PHOLIDAY_SEL';
If Not (VarIsNull(IdGroupHolidayPeriod)) Then
Params.TableName := Params.TableName + ' WHERE ID_GROUP_HOLIDAY = ' + VarToStr(IdGroupHolidayPeriod);
Params.Fields := 'FULL_NAME,CHECK_PLAN_WITH_FACT,ID_TYPE_HOLIDAY,ID_GROUP_HOLIDAY';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE_HOLIDAY';
Params.ReturnFields := 'FULL_NAME,CHECK_PLAN_WITH_FACT,ID_TYPE_HOLIDAY,ID_GROUP_HOLIDAY';
Params.DBHandle := Integer(WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
If GetUnivSprav(Params, OutPut)
Then
Begin
value := output['ID_TYPE_HOLIDAY'];
DisplayText := VarToStr(output['FULL_NAME']);
HolidayPeriod.Value := null;
HolidayPeriod.Clear;
IdGroupHoliday := output['ID_GROUP_HOLIDAY'];
End;
End;
Constructor TfrmNewHolidayParams.Create(AOwner: TComponent;
DB_Handle: TISC_DB_HANDLE;
id_type_holiday: integer;
id_holiday_period: variant;
date_start: TdateTime;
end_date: TdateTime;
day_count: integer;
ipcard: int64;
can_edit_holiday: Boolean;
show_plan_holidays: Integer;
id_work_dog_moving: variant;
id_post_in: variant;
is_post_main_in: variant;
show_radio_buttons: Boolean;
is_insert: boolean = false);
Var
GetInfo: TpFibQuery;
GetInfoStoredProc: TpFibStoredProc;
Begin
Inherited Create(Aowner);
self.loc_is_insert := is_insert;
UpdateFlag := 0;
auto_fill_not_post_main_values := 0;
IdGroupHoliday := null;
IdGroupHolidayPeriod := null;
cid_pcard := ipcard;
WorkDatabase.Handle := DB_Handle;
ReadTransaction.StartTransaction;
cshow_plan_holidays := show_plan_holidays;
GetInfo := TpFibQuery.Create(self);
GetInfo.Database := WorkDatabase;
GetInfo.Transaction := ReadTransaction;
GetInfo.Close;
GetInfo.SQL.Text := 'SELECT ID_ANNUAL_HOLIDAY FROM UP_SYS_INI_CONSTS';
GetInfo.ExecQuery;
If GetInfo.RecordCount > 0
Then
Begin
id_annual_holiday := GetInfo.FieldByName('ID_ANNUAL_HOLIDAY').Value;
End;
GetInfo.Close;
If Not VarIsNull(id_annual_holiday) Then
Begin
GetInfo.SQL.Text := 'SELECT FULL_NAME FROM HL_SP_TYPE_HOLIDAY WHERE ID_TYPE_HOLIDAY=' +
IntToStr(id_annual_holiday);
GetInfo.ExecQuery;
If GetInfo.RecordCount > 0
Then
id_annual_holiday_val := GetInfo.FieldByName('FULL_NAME').Value;
End;
GetInfo.Close;
If (id_type_holiday <> -1)
Then
Begin
GetInfo.SQL.Text := 'SELECT * FROM HL_SP_TYPE_HOLIDAY WHERE ID_TYPE_HOLIDAY=' + IntToStr(id_type_holiday);
GetInfo.ExecQuery;
If GetInfo.RecordCount > 0
Then
Begin
HolidayType.Value := id_type_holiday;
HolidayType.DisplayText := GetInfo.FieldByName('FULL_NAME').Value;
IdGroupHoliday := GetInfo.FieldByName('ID_GROUP_HOLIDAY').Value;
If GetInfo.FieldByName('CHECK_PLAN_WITH_FACT').Value = 1
Then
Begin
HolidayPeriod.Value := null;
HolidayPeriod.Clear;
End;
End;
Self.Height := Self.Height - PeriodsPanel.Height;
End
Else
Begin
If is_insert
Then
Begin
AutoLoadFromRegistry(self, Nil);
Label3.Visible := False;
Label9.Visible := False;
Label10.Visible := False;
Label11.Visible := False;
HolidayPeriod.Visible := False;
WorkDogValue.Visible := False;
PostValue.Visible := False;
IsPostMainValue.Visible := False;
Panel1.Visible := False;
Self.Height := Self.Height - Panel1.Height;
Self.Height := Self.Height - PeriodsPanel.Height;
PeriodArrayButton.Visible := True;
End;
End;
//Получаем количество праздничных дней между двумя датами
StartDate.Date := date_start;
GetInfoStoredProc := TpFibStoredProc.Create(self);
GetInfoStoredProc.Database := WorkDatabase;
GetInfoStoredProc.Transaction := ReadTransaction;
GetInfoStoredProc.StoredProcName := 'HOLIDAYS_BETWEEN_2_DATES_EX';
GetInfoStoredProc.Prepare;
GetInfoStoredProc.ParamByName('ID_TYPE_HOLIDAY').Value := HolidayType.Value;
GetInfoStoredProc.ParamByName('DATE1').Value := StartDate.Date;
GetInfoStoredProc.ParamByName('DATE2').Value := end_date;
GetInfoStoredProc.ExecProc;
HolidayDayCount.Value := GetInfoStoredProc.ParamByName('HCOUNT').Value;
GetInfoStoredProc.Close;
GetInfoStoredProc.Free;
DayCount.EditValue := Day_Count;
DateEndForCalc.Date := end_date;
TotalDayCount.Value := DaysBetween(StartDate.Date, DateEndForCalc.Date) + 1;
If (id_holiday_period <> null)
Then
Begin
self.out_id_work_dog_moving := id_work_dog_moving;
self.id_post := id_post_in;
self.is_post_main := is_post_main_in;
IsPostMainValue.Value := is_post_main;
GetInfoStoredProc := TpFibStoredProc.Create(self);
GetInfoStoredProc.Database := WorkDatabase;
GetInfoStoredProc.Transaction := ReadTransaction;
GetInfoStoredProc.StoredProcName := 'UP_KER_GET_POST_INFO';
GetInfoStoredProc.Prepare;
GetInfoStoredProc.ParamByName('ID_POST').Value := id_post;
GetInfoStoredProc.ExecProc;
PostValue.Value := GetInfoStoredProc.ParamByName('NAME_POST').Value;
GetInfoStoredProc.Close;
If out_id_work_dog_moving <> null
Then
Begin
GetInfoStoredProc.StoredProcName := 'UP_KER_GET_RMOVING_INFO';
GetInfoStoredProc.Prepare;
GetInfoStoredProc.ParamByName('ID_WORK_DOG_MOVING').asInt64 := out_id_work_dog_moving;
GetInfoStoredProc.ExecProc;
WorkDogValue.Value := GetInfoStoredProc.ParamByName('STR_VALUE').Value;
GetInfoStoredProc.Close;
End;
HolidayPeriod.Clear;
HolidayPeriod.Value := id_holiday_period;
GetInfoStoredProc.StoredProcName := 'UP_KER_GET_HOLIDAY_PERIOD_INFO';
GetInfoStoredProc.Prepare;
GetInfoStoredProc.ParamByName('ID_HOLIDAY_PERIOD').asInt64 := id_holiday_period;
GetInfoStoredProc.ExecProc;
HolidayPeriod.DisplayText := GetInfoStoredProc.ParamByName('PERIOD_STR').Value;
IdGroupHolidayPeriod := GetInfoStoredProc.ParamByName('ID_GROUP_HOLIDAY').Value;
GetInfoStoredProc.Close;
GetInfoStoredProc.Free;
End;
GetInfo.Free;
//HolidayType.Blocked := not can_edit_holiday;
UpdateFlag := 1;
If NotFixedTypeHoliday.Checked Then
Begin
HolidayType.Enabled := False;
If can_edit_holiday = false Then
Begin
HolidayType.Value := id_annual_holiday;
HolidayType.DisplayText := id_annual_holiday_val;
HolidayType.Enabled := False;
End;
End;
//NotFixedTypeHoliday.Enabled:=show_radio_buttons;
//FixedTypeHoliday.Enabled :=show_radio_buttons;
//Label12.Enabled :=show_radio_buttons;
If Not show_radio_buttons
Then
Begin
NotFixedTypeHoliday.Visible := show_radio_buttons;
FixedTypeHoliday.Visible := show_radio_buttons;
End;
End;
Procedure TfrmNewHolidayParams.HolidayPeriodOpenSprav(Sender: TObject;
Var Value: Variant; Var DisplayText: String);
Var
Params: TUnivParams;
OutPut: TRxMemoryData;
Begin
Screen.Cursor := crHourGlass;
Params.FormCaption := 'За який період надається планова відпустка?';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'HL_DT_PHOLIDAY_SEL_BY_PCARD(' + IntToStr(cid_pcard) + ')';
If Not (VarIsNull(IdGroupHoliday)) Then
Params.TableName := Params.TableName + ' WHERE ID_GROUP_HOLIDAY = ' + VarToStr(IdGroupHoliday);
Params.Fields :=
'PERIOD_STR,WORK_POST_STR,ID_HOLIDAY_PERIOD,ID_WORK_DOG_MOVING,PERIOD_BEG,PERIOD_END,ID_POST,IS_POST_MAIN,NAME_POST,ID_GROUP_HOLIDAY';
Params.FieldsName := 'Період,~*Посада';
Params.KeyField := 'ID_HOLIDAY_PERIOD';
Params.ReturnFields :=
'WORK_POST_STR,PERIOD_STR,ID_HOLIDAY_PERIOD,ID_WORK_DOG_MOVING,PERIOD_BEG,PERIOD_END,ID_POST,IS_POST_MAIN,NAME_POST,ID_GROUP_HOLIDAY';
Params.DBHandle := Integer(WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
Screen.Cursor := crDefault;
If GetUnivSprav(Params, OutPut)
Then
Begin
WorkDogValue.Value := VarToStr(output['WORK_POST_STR']);
value := output['ID_HOLIDAY_PERIOD'];
id_post := output['ID_POST'];
is_post_main := output['IS_POST_MAIN'];
IsPostMainValue.Value := output['IS_POST_MAIN'];
PostValue.Value := output['NAME_POST'];
out_id_work_dog_moving := output['ID_WORK_DOG_MOVING'];
DisplayText := VarToStr(output['PERIOD_STR']);
IdGroupHolidayPeriod := output['ID_GROUP_HOLIDAY'];
End;
End;
Procedure TfrmNewHolidayParams.cxButton1Click(Sender: TObject);
Var
GetInfoStoredProc: TpFibStoredProc;
Begin
//Необходимо получить количество дней между двумя датами
TotalDayCount.Value := DaysBetween(StartDate.Date, DateEndForCalc.Date) + 1;
//Получаем количество праздничных дней между двумя датами
GetInfoStoredProc := TpFibStoredProc.Create(self);
GetInfoStoredProc.Database := WorkDatabase;
GetInfoStoredProc.Transaction := ReadTransaction;
GetInfoStoredProc.StoredProcName := 'HOLIDAYS_BETWEEN_2_DATES_EX';
GetInfoStoredProc.Prepare;
GetInfoStoredProc.ParamByName('ID_TYPE_HOLIDAY').Value := HolidayType.Value;
GetInfoStoredProc.ParamByName('DATE1').Value := StartDate.Date;
GetInfoStoredProc.ParamByName('DATE2').Value := DateEndForCalc.Date;
GetInfoStoredProc.ExecProc;
HolidayDayCount.Value := GetInfoStoredProc.ParamByName('HCOUNT').Value;
GetInfoStoredProc.Close;
GetInfoStoredProc.Free;
DayCount.EditValue := TotalDayCount.Value - HolidayDayCount.Value;
End;
Procedure TfrmNewHolidayParams.cxButton2Click(Sender: TObject);
Var
Params: TUnivParams;
OutPut: TRxMemoryData;
Begin
If PeriodArrayButton.Caption = '>>'
Then
Begin
If PeriodsDataSet.Active
Then
Begin
If PeriodsDataSet.RecordCount > 0
Then
Begin
If PeriodsDataSet.FieldByName('order_count').Value > 0
Then
Begin
Params.FormCaption := 'Святкові дні за період ' + PeriodsDataSet.fieldbyname('date_beg').asstring +
'-' + PeriodsDataSet.fieldbyname('date_end').asstring;
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'HOLIDAYS_BETWEEN_2_DATES_EX2(' + '''' +
PeriodsDataSet.fieldbyname('date_beg').asstring + '''' + ',' + '''' +
PeriodsDataSet.fieldbyname('date_end').asstring + '''' + ')';
Params.Fields := 'HDATE';
Params.FieldsName := 'Свято';
Params.KeyField := 'HDATE';
Params.ReturnFields := 'HDATE';
Params.DBHandle := Integer(WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
GetUnivSprav(Params, OutPut);
End
Else
agShowMessage('Немає жодного святкового дня!');
End;
End;
End
Else
Begin
If (HolidayDayCount.Value > 0)
Then
Begin
Params.FormCaption := 'Святкові дні за період ' + DateToStr(StartDate.Date) + '-' +
DateToStr(DateEndForCalc.Date);
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'HOLIDAYS_BETWEEN_2_DATES_EX2(' + '''' + DateToStr(StartDate.Date) + '''' + ',' + ''''
+ DateToStr(DateEndForCalc.Date) + '''' + ')';
Params.Fields := 'HDATE';
Params.FieldsName := 'Свято';
Params.KeyField := 'HDATE';
Params.ReturnFields := 'HDATE';
Params.DBHandle := Integer(WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
GetUnivSprav(Params, OutPut)
End
Else
agShowMessage('Немає жодного святкового дня!');
End;
End;
Procedure TfrmNewHolidayParams.DateEndForCalcPropertiesChange(
Sender: TObject);
Begin
If UpdateFlag = 1
Then
cxButton1Click(self);
End;
Procedure TfrmNewHolidayParams.NotFixedTypeHolidayClick(Sender: TObject);
Begin
If NotFixedTypeHoliday.Checked Then
Begin
HolidayType.Value := id_annual_holiday;
HolidayType.DisplayText := id_annual_holiday_val;
HolidayType.Enabled := False;
End;
End;
Procedure TfrmNewHolidayParams.FixedTypeHolidayClick(Sender: TObject);
Begin
HolidayType.Enabled := True;
End;
Procedure TfrmNewHolidayParams.FormClose(Sender: TObject;
Var Action: TCloseAction);
Begin
AutoSaveIntoRegistry(self, Nil);
End;
Procedure TfrmNewHolidayParams.DateEndForCalcExit(Sender: TObject);
Begin
If UpdateFlag = 1
Then
cxButton1Click(self);
End;
Procedure TfrmNewHolidayParams.PeriodArrayButtonClick(Sender: TObject);
Begin
If (PeriodArrayButton.Caption = '<<')
Then
Begin
If Not PeriodsDataSet.Active
Then
PeriodsDataSet.Active := True;
PeriodArrayButton.Caption := '>>';
PeriodsPanel.Visible := True;
AddPeriodButton.Visible := True;
Self.Height := Self.Height + PeriodsPanel.Height;
Panel3.Visible := False;
Self.Height := Self.Height - Panel3.Height;
Panel2.Top := Self.Height - Panel2.Height;
End
Else
Begin
PeriodArrayButton.Caption := '<<';
PeriodsPanel.Visible := false;
AddPeriodButton.Visible := false;
Self.Height := Self.Height - PeriodsPanel.Height;
Panel3.Visible := true;
Self.Height := Self.Height + Panel3.Height;
Panel2.Top := Self.Height - Panel2.Height;
End;
End;
Procedure TfrmNewHolidayParams.AddPeriodButtonClick(Sender: TObject);
Begin
If PeriodsDataSet.Active
Then
Begin
cxButton1Click(Self);
If Not CheckCrossPeriods(PeriodsDataSet, StartDate.Date, DateEndForCalc.Date)
Then
Begin
PeriodsDataSet.Insert;
PeriodsDataSet.FieldByName('date_beg').Value := StartDate.Date;
PeriodsDataSet.FieldByName('date_end').Value := DateEndForCalc.Date;
PeriodsDataSet.FieldByName('order_count').Value := DayCount.EditValue;
PeriodsDataSet.FieldByName('hol_count').Value := HolidayDayCount.Value;
PeriodsDataSet.FieldByName('sum_count').Value := TotalDayCount.Value;
PeriodsDataSet.Post;
End;
End;
End;
Procedure TfrmNewHolidayParams.cxButton3Click(Sender: TObject);
Begin
If PeriodsDataSet.Active
Then
If PeriodsDataSet.RecordCount > 0
Then
PeriodsDataSet.Delete;
End;
Function TfrmNewHolidayParams.CheckCrossPeriods(Ds: TDataSet; date_beg,
date_end: TDateTime): Boolean;
Var
Res: Boolean;
Begin
Res := false;
Res := DS.Locate('date_beg;date_end', VarArrayOf([Date_beg, date_end]), []);
If Not Res
Then
Begin
Ds.First;
While Not ds.Eof Do
Begin
If (Ds['date_beg'] <= date_end)
And (Ds['date_end'] >= date_beg)
Then
Begin
Res := True;
Break;
End;
ds.Next;
End;
End;
Result := Res;
End;
Procedure TfrmNewHolidayParams.cxButton4Click(Sender: TObject);
Var
Calc_date_end: TpFibStoredProc;
Begin
//Получаем количество праздничных дней между двумя датами
Calc_date_end := TpFibStoredProc.Create(self);
Calc_date_end.Database := WorkDatabase;
Calc_date_end.Transaction := ReadTransaction;
Calc_date_end.StoredProcName := 'HL_GET_HOLIDAY_TERMS_INFO';
Calc_date_end.Prepare;
Calc_date_end.ParamByName('ID_TYPE_HOLIDAY_IN').Value := HolidayType.Value;
If Not VarIsNull(DayCount.EditValue) Then
Calc_date_end.ParamByName('CNT').Value := DayCount.EditValue
Else
Calc_date_end.ParamByName('CNT').Value := 0;
Calc_date_end.ParamByName('HOLIDAY_BEG').Value := StartDate.Date;
Calc_date_end.ExecProc;
DateEndForCalc.Date := Calc_date_end.ParamByName('REAL_HOLIDAY_END').Value;
Calc_date_end.Close;
Calc_date_end.Free;
End;
Procedure TfrmNewHolidayParams.DayCountExit(Sender: TObject);
Begin
cxButton4Click(self);
End;
Procedure TfrmNewHolidayParams.HolidayTypeChange(Sender: TObject);
Begin
If VarIsNull(HolidayType.Value) Then
IdGroupHoliday := Null;
End;
Procedure TfrmNewHolidayParams.HolidayPeriodChange(Sender: TObject);
Begin
If VarIsNull(HolidayPeriod.Value) Then
IdGroupHolidayPeriod := null;
End;
End.
|
unit UnitPasswordKeeper;
interface
uses
System.Types,
Winapi.Windows,
System.Classes,
System.SyncObjs,
Dmitry.CRC32,
UnitDBDeclare,
uDBBaseTypes,
uMemory,
uFormInterfaces,
uSessionPasswords;
type
TPasswordKeeper = class(TObject)
private
PasswordList: TList;
OKList: TArInteger;
FSync: TCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure AddPassword(PasswordRecord: TPasswordRecord);
procedure RemoveRecordsByPasswordCRC(CRC: Cardinal);
function PasswordOKForRecords(Password: string): TList;
function GetActiveFiles(Sender: TObject): TList;
procedure AddCryptFileToListProc(Sender: TObject; Rec: TPasswordRecord);
function Count: Integer;
function GetPasswords: TArCardinal;
procedure TryGetPasswordFromUser(PasswordCRC: Cardinal);
procedure PasswordOKForFiles(PasswordCRC: Cardinal; FileList : TStrings);
function GetAvaliableCryptFileList(Sender: TObject): TArInteger;
procedure AddToOKList(PasswordCRC: Cardinal);
end;
implementation
{ TPasswordKeeper }
procedure TPasswordKeeper.AddCryptFileToListProc(Sender: TObject; Rec: TPasswordRecord);
begin
AddPassword(Rec);
end;
procedure TPasswordKeeper.AddPassword(PasswordRecord: TPasswordRecord);
begin
FSync.Enter;
try
PasswordList.Add(PasswordRecord);
finally
FSync.Leave;
end;
end;
procedure TPasswordKeeper.AddToOKList(PasswordCRC: Cardinal);
var
I: Integer;
P: TPasswordRecord;
begin
FSync.Enter;
try
for I := PasswordList.Count - 1 downto 0 do
begin
P := TPasswordRecord(PasswordList[I]);
if (P.CRC = PasswordCRC) then
begin
SetLength(OKList, Length(OKList) + 1);
OKList[Length(OKList) - 1] := P.ID;
end;
end;
finally
FSync.Leave;
end;
end;
function TPasswordKeeper.Count: Integer;
begin
Result := PasswordList.Count;
end;
constructor TPasswordKeeper.Create;
begin
inherited;
FSync:= TCriticalSection.Create;
SetLength(OKList, 0);
PasswordList := TList.Create;
end;
destructor TPasswordKeeper.Destroy;
begin
FreeList(PasswordList);
F(FSync);
end;
function TPasswordKeeper.GetActiveFiles(Sender : TObject): TList;
var
I: Integer;
P, Cp: TPasswordRecord;
begin
FSync.Enter;
try
Result := TList.Create;
for I := PasswordList.Count - 1 downto 0 do
begin
P := TPasswordRecord(PasswordList[I]);
Cp := TPasswordRecord.Create;
Cp.CRC := P.CRC;
Cp.FileName := P.FileName;
Cp.ID := P.ID;
Result.Add(Cp);
end;
finally
FSync.Leave;
end;
end;
function TPasswordKeeper.GetAvaliableCryptFileList(Sender: TObject): TArInteger;
begin
FSync.Enter;
try
Result := Copy(OKList);
finally
FSync.Leave;
end;
end;
function TPasswordKeeper.GetPasswords: TArCardinal;
var
I: Integer;
P: TPasswordRecord;
Res: TArCardinal;
function FileCRCExists(CRC: Cardinal): Boolean;
var
J: Integer;
begin
Result := False;
for J := 0 to Length(Res) - 1 do
if Res[J] = CRC then
begin
Result := True;
Break;
end;
end;
begin
FSync.Enter;
try
SetLength(Res, 0);
for I := PasswordList.Count - 1 downto 0 do
begin
P := TPasswordRecord(PasswordList[I]);
if not FileCRCExists(P.CRC) then
begin
SetLength(Res, Length(Res) + 1);
Res[Length(Res) - 1] := P.CRC;
end;
end;
Result := Res;
finally
FSync.Leave;
end;
end;
procedure TPasswordKeeper.PasswordOKForFiles(PasswordCRC: Cardinal; FileList : TStrings);
var
I: Integer;
P: TPasswordRecord;
begin
FSync.Enter;
try
FileList.Clear;
for I := PasswordList.Count - 1 downto 0 do
begin
P := TPasswordRecord(PasswordList[I]);
if P.CRC = PasswordCRC then
FileList.Add(P.FileName);
end;
finally
FSync.Leave;
end;
end;
function TPasswordKeeper.PasswordOKForRecords(Password: string): TList;
var
CRC: Cardinal;
I: Integer;
P, Cp: TPasswordRecord;
begin
FSync.Enter;
try
Result := TList.Create;
CalcStringCRC32(Password, CRC);
for I := PasswordList.Count - 1 downto 0 do
begin
P := TPasswordRecord(PasswordList[I]);
if P.CRC = CRC then
begin
Cp := TPasswordRecord.Create;
Cp.CRC := P.CRC;
Cp.FileName := P.FileName;
Cp.ID := P.ID;
Result.Add(Cp);
end;
end;
finally
FSync.Leave;
end;
end;
procedure TPasswordKeeper.RemoveRecordsByPasswordCRC(CRC: Cardinal);
var
I: Integer;
P: TPasswordRecord;
begin
FSync.Enter;
try
for I := PasswordList.Count - 1 downto 0 do
begin
P := TPasswordRecord(PasswordList[I]);
if P.CRC = CRC then
begin
P.Free;
PasswordList.Remove(P);
end;
end;
finally
FSync.Leave;
end;
end;
procedure TPasswordKeeper.TryGetPasswordFromUser(PasswordCRC: Cardinal);
var
FileList: TStrings;
FileOkList: TList;
Password: string;
Skip: Boolean;
I: Integer;
P: TPasswordRecord;
begin
FileList := TStringList.Create;
try
PasswordOKForFiles(PasswordCRC, FileList);
if FileList.Count > 0 then
begin
Skip := False;
Password := RequestPasswordForm.ForManyFiles(FileList, PasswordCRC, Skip);
if Password <> '' then
begin
SessionPasswords.AddForSession(Password);
// moving from password list to OKpassword list FILES
FileOkList := PasswordOKForRecords(Password);
try
for I := 0 to FileOkList.Count - 1 do
begin
P := FileOkList[I];
AddToOKList(P.ID);
end;
finally
FreeList(FileOkList);
end;
RemoveRecordsByPasswordCRC(PasswordCRC);
end;
if Skip then
RemoveRecordsByPasswordCRC(PasswordCRC);
end;
finally
F(FileList);
end;
end;
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons, IniFiles, uFrmInfo, DB, ADODB;
const
DB_INI = 'mrconnection.ini';
type
TFrmMain = class(TForm)
Panel1: TPanel;
EspacamentoInferior: TPanel;
Panel3: TPanel;
btClose: TButton;
cbxDatabase: TComboBox;
Label1: TLabel;
btnUpdate: TSpeedButton;
btnNew: TSpeedButton;
btnSave: TSpeedButton;
btnTestCon: TSpeedButton;
ADOConnect: TADOConnection;
procedure btCloseClick(Sender: TObject);
procedure btnNewClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnUpdateClick(Sender: TObject);
procedure btnTestConClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FrmInfo: TFrmInfo;
fDBFile : TIniFile;
fLocalPath : String;
function OpenIniFile:Boolean;
function CreateIniFile:Boolean;
function SaveConnection:Boolean;
function TestConnection:Boolean;
function GetSection(Section:String):String;
procedure SetSection(Section, Str:String);
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
uses uFileFunctions, Registry, uParamFunctions, uOperationSystem;
{$R *.dfm}
function TFrmMain.TestConnection:Boolean;
var
sResult : String;
sPW, sUser, sDBAlias, sServer : String;
bWinLogin, bLib : Boolean;
begin
Result := False;
//Verifica se tem section
if cbxDatabase.Text = '' then
begin
ShowMessage('Select a connection');
cbxDatabase.SetFocus;
Exit;
end;
sResult := FrmInfo.DecodeStr(GetSection(cbxDatabase.Text));
sServer := ParseParam(sResult, SV_SERVER);
sDBAlias := ParseParam(sResult, SV_DATABASE);
sUser := ParseParam(sResult, SV_USER);
sPW := ParseParam(sResult, SV_PASSWORD);
bWinLogin := (ParseParam(sResult, SV_WIN_LOGIN)[1] in ['Y']);
bLib := (ParseParam(sResult, SV_USE_NETLIB)[1] = 'Y');
if not bWinLogin then
begin
if bLib then
sResult := SetConnectionStr(sUser, sPW, sDBAlias, sServer)
else
sResult := SetConnectionStrNoNETLIB(sUser, sPW, sDBAlias, sServer);
end
else
begin
if bLib then
sResult := SetWinConnectionStr(sDBAlias, sServer)
else
sResult := SetWinConnectionStrNoNETLIB(sDBAlias, sServer);
end;
with ADOConnect do
begin
if Connected then
Close;
ConnectionString := sResult;
Try
Result := True;
Open;
ShowMessage('Connection succeed!');
Close;
except
raise;
Result := False;
Close;
end;
end;
end;
function TFrmMain.SaveConnection:Boolean;
var
Reg : TRegistry;
buildInfo: String;
begin
Result := True;
//Verifica se tem section
if cbxDatabase.Text = '' then
begin
ShowMessage('Select a connection');
Exit;
end;
if not TestConnection then
Exit;
Reg := nil;
Try
Reg := TRegistry.Create;
if ( getOS(buildInfo) = osW7 ) then
Reg.RootKey := HKEY_CURRENT_USER
else
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKey('SOFTWARE\AppleNet', True);
Reg.WriteString('ServerInfo', GetSection(cbxDatabase.Text));
finally
//Fechar o Registry
Reg.CloseKey;
Reg.Free;
end;
end;
function TFrmMain.CreateIniFile:Boolean;
begin
Result := True;
if not FileExists(fLocalPath+DB_INI) then
SaveTextFile(fLocalPath+DB_INI, '');
end;
function TFrmMain.OpenIniFile:Boolean;
var
fIniSection : TStringList;
i : integer;
begin
try
Result := True;
cbxDatabase.Items.Clear;
fIniSection := TStringList.Create;
fDBFile.ReadSections(fIniSection);
for i := 0 to fIniSection.Count -1 do
cbxDatabase.Items.Add(fIniSection[i]);
FreeAndNil(fIniSection);
except
raise;
Result := False;
end;
end;
procedure TFrmMain.btCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFrmMain.SetSection(Section, Str:String);
begin
fDBFile.WriteString(Section, 'STR', Str);
end;
function TFrmMain.GetSection(Section:String):String;
begin
if not fDBFile.SectionExists(Section) then
Exit;
Result := fDBFile.ReadString(Section, 'STR', '');
end;
procedure TFrmMain.btnNewClick(Sender: TObject);
var
sResult,
sSectionName : String;
begin
//New Connection
sSectionName := InputBox('New Database connection', 'Server Name', '');
if sSectionName = '' then
begin
ShowMessage('Server Name not saved!');
Exit;
end;
sResult := FrmInfo.Start('');
if sResult = '' then
begin
ShowMessage('Connection aborted');
Exit;
end;
SetSection(sSectionName, sResult);
OpenIniFile;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
fLocalPath := ExtractFilePath(Application.ExeName);
CreateIniFile;
FrmInfo := TFrmInfo.Create(Self);
fDBFile := TIniFile.Create(fLocalPath+DB_INI);
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
if Assigned(fDBFile) then
FreeAndNil(fDBFile);
if Assigned(FrmInfo) then
FreeAndNil(FrmInfo);
end;
procedure TFrmMain.btnSaveClick(Sender: TObject);
begin
//Save to Register
SaveConnection;
end;
procedure TFrmMain.btnUpdateClick(Sender: TObject);
var
sResult : String;
begin
if cbxDatabase.Text = '' then
begin
ShowMessage('Invalid Server Name!');
Exit;
end;
sResult := FrmInfo.Start(GetSection(cbxDatabase.Text));
SetSection(cbxDatabase.Text, sResult);
end;
procedure TFrmMain.btnTestConClick(Sender: TObject);
begin
TestConnection;
end;
procedure TFrmMain.FormShow(Sender: TObject);
begin
OpenIniFile;
end;
end.
|
Program Math;
{Jesse Anderson
8/26/95
c1e15}
begin
Writeln('4 + 2 = ',4+2);
Writeln('4 - 2 = ',4-2);
Writeln('4 * 2 = ',4*2);
Writeln('4 / 2 = ',4/2);
end. |
unit uAnamnese;
{**********************************************************************
** unit uAnamnese **
** **
** UNIT DESTINADA A MANIPULAR AS INFORMAÇÕES NO CADASTRO DE PACIENTE **
** REFERENTE AS INFORMAÇÕES DENTRO DA ABA DE ANAMNESE **
** **
***********************************************************************}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uCadPacientes, uClassControlePaciente, uClassAnamnese, uFrmMensagem;
type
{ Anamnese }
Anamnese = class
public
class function CarregaObjAnamnese(objAnamnese: TAnamnese; frm: TfrmCadPaciente): TAnamnese;
class procedure InclusaoOuEdicaoAnamnese(frm: TfrmCadPaciente);
end;
implementation
{ Anamnese }
class function Anamnese.CarregaObjAnamnese(objAnamnese: TAnamnese; frm: TfrmCadPaciente): TAnamnese;
begin
objAnamnese.idTblPaciente := StrToInt(frm.edtCodPaciente.Text);
objAnamnese.consumoAcucar := frm.cboxConsAcucar.Text;
objAnamnese.escovacao := frm.cboxEscovacao.Text;
objAnamnese.usoFioDental := frm.cboxFioDental.Text;
objAnamnese.obsAnatomoHisto := frm.memoObsAnatHistPatol.Text;
objAnamnese.habitosViciosos := frm.edtHabitosViciosos.Text;
objAnamnese.antecedentesFamiliares := frm.edtAntecFamiliar.Text;
if frm.rbexSimApreesTratDent.Checked then
begin
objAnamnese.apreensivoTratDentario := 'S';
objAnamnese.porqueApreensivo := frm.edtApreensivoTratamento.Text;
end;
if frm.rbexNaoApreesTratDent.Checked then
objAnamnese.apreensivoTratDentario := 'N';
if frm.rbexSimTratMedico.Checked then
begin
objAnamnese.tratamentoMedico := 'S';
objAnamnese.qualTratMedico := frm.edtTratamentoMedico.Text;
end;
if frm.rbexNaoTratMedico.Checked then
objAnamnese.tratamentoMedico := 'N';
if frm.rbexSimTomaRemedio.Checked then
begin
objAnamnese.tomaMedicamento := 'S';
objAnamnese.tomaQualMedicamento := frm.edtTomaRemedio.Text;
end;
if frm.rbexNaoTomaRemedio.Checked then
objAnamnese.tomaMedicamento := 'N';
if frm.rbexSimAlergiaAnestesia.Checked then
begin
objAnamnese.alergiaAnestesia := 'S';
objAnamnese.alergiaQualAnestesia := frm.edtAlergiaAnestesia.Text;
end;
if frm.rbexNaoAlergiaAnestesia.Checked then
objAnamnese.alergiaAnestesia := 'N';
if frm.rbexSimAlgumaAlergia.Checked then
begin
objAnamnese.algumaAlergia := 'S';
objAnamnese.qualAlergia := frm.edtAlgumaAlergia.Text;
end;
if frm.rbexNaoAlgumaAlergia.Checked then
objAnamnese.algumaAlergia := 'N';
if frm.rbexSimFoiHospitalizado.Checked then
begin
objAnamnese.foiHospitalizado := 'S';
objAnamnese.porqueHospitalizado := frm.edtFoiHospitalizado.Text;
end;
if frm.rbexNaoFoiHospitalizado.Checked then
objAnamnese.foiHospitalizado := 'N';
if frm.rgexSexo.ItemIndex = 0 then
begin
if frm.rbexSimTaGravida.Checked then
begin
objAnamnese.estaGravida := 'S';
objAnamnese.previsaoParto := frm.edtTaGravida.Text;
end;
if frm.rbexNaoTaGravida.Checked then
objAnamnese.estaGravida := 'N';
objAnamnese.teveQuantasGravidez := StrToInt(frm.spedtQtdGravidez.Text);
objAnamnese.quantosFilhos := StrToInt(frm.spedtQtdFilhos.Text);
if frm.rbexSimMenopausa.Checked then
begin
objAnamnese.chegouMenopausa := 'S';
objAnamnese.quandoChegouMenopausa := frm.edtMenopausa.Text;
end;
if frm.rbexNaoMenopausa.Checked then
objAnamnese.chegouMenopausa := 'N';
end;
result := objAnamnese;
end;
class procedure Anamnese.InclusaoOuEdicaoAnamnese(frm: TfrmCadPaciente);
var
objAnamnese : TAnamnese;
objControlePaciente : TControlePaciente;
codIDAnamnese : integer = 0;
begin
objAnamnese := TAnamnese.Create;
objControlePaciente := TControlePaciente.Create;
try
codIDAnamnese := objControlePaciente.InclusaoOuEdicaoAnamnese(CarregaObjAnamnese(objAnamnese,frm));
if codIDAnamnese > 0 then
begin
try
frmMensagem := TfrmMensagem.Create(nil);
frmMensagem.InfoFormMensagem('Cadastro de Anamnese', tiInformacao, 'Cadastro da Anamnese realizado com sucesso!');
finally
FreeAndNil(frmMensagem);
end;
end;
// DesabilitaControles(pcCadPaciente.ActivePage);
estado := teNavegacao;
//EstadoBotoes;
finally
FreeAndNil(objControlePaciente);
FreeAndNil(objAnamnese);
end;
end;
end.
|
Unit Pci;
{ * Pci: *
* *
* Esta Unidad detecta los dispositivos dentro del bus PCI y los *
* coloca en el array pci_devices , el codigo fue extraido de Delhineos *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* *
* 3 / 05 / 2005 : Ultima Revision *
* *
************************************************************************
}
interface
{$I ../../include/head/asm.h}
{$I ../../include/head/printk_.h}
{$I ../../Include/toro/drivers/pci.inc}
{$I ../../include/toro/page.inc}
procedure check_pci_devices;
function pci_device_count (bus : dword) : dword;
function pci_read_dword (bus, device, fonction, regnum : dword) : dword;
procedure scanpci (bus : dword);
var
pci_devices : array[0..MAX_PCI] of t_pci_device;
actual_nb : dword;
nm_pci_dev:dword;
implementation
{$I ../../include/head/ioport.h}
{ * Pci_Init : *
* *
* Procedimiento que se inicializa la tabla de dispostivos que se *
* encuentran sobre el bus pci *
* *
**********************************************************************
}
procedure pci_init;[public , alias :'PCI_INIT'];
var base:^T_Bios32;
found:boolean;
begin
base := pointer($E0000);
found := false;
nm_pci_dev := 0;
while not (found) or (base < pointer($100000)) do
begin
If base^.magic = $5F32335F then
begin
found:=true;
printk('/nIniciando pcibus ... /VOk\n',[]);
check_pci_devices;
exit;
end;
base += 1;
end;
printk('/nIniciando pcibus ... /Rfault\n',[]);
end;
procedure scanpci (bus : dword);
var
bug_tmp : dword;
dev, read : dword;
vendor_id : dword;
device_id : dword;
iobase, i : dword;
ipin, ilin : dword;
func : dword;
main_class, sub_class : dword;
begin
for dev := 0 to 31 do
begin
for func := 0 to 7 do
begin
read := pci_read_dword(bus, dev, func, PCI_CONFIG_VENDOR);
vendor_id := read and $FFFF;
device_id := read div 65536; { device_id := read shr 16 }
if (func = 0) then
bug_tmp := device_id
else if (device_id = bug_tmp) then
break;
if ((vendor_id < $FFFF) and (vendor_id <> 0)) then
begin
read := pci_read_dword(bus, dev, func, PCI_CONFIG_CLASS_REV);
main_class := read div 16777216; { class := read shr 24 }
sub_class := (read div 65536) and $FF;
iobase := 0;
for i := 0 to 5 do
begin
read := pci_read_dword(bus, dev, func, PCI_CONFIG_BASE_ADDR_0 + i);
if (read and 1 = 1) then
begin
iobase := read and $FFFFFFFC;
pci_devices[actual_nb].io[i] := iobase;
end;
end;
read := pci_read_dword(bus, dev, func, PCI_CONFIG_INTR);
ipin := (read div 256) and $FF;
ilin := read and $FF;
with pci_devices[actual_nb] do
begin
bus:= bus;
dev:= dev;
func:= func;
irq := ilin;
vendor_id:= vendor_id;
device_id:= device_id;
main_class:=main_class;
sub_class:= sub_class;
actual_nb := actual_nb + 1;
end;
end;
end;
end;
end;
function pci_read_dword (bus, device, fonction, regnum : dword) : dword;
var
send : dword;
begin
asm
mov eax, $80000000
mov ebx, bus
shl ebx, 16
or eax, ebx
mov ebx, device
shl ebx, 11
or eax, ebx
mov ebx, fonction
shl ebx, 8
or eax, ebx
mov ebx, regnum
shl ebx, 2
or eax, ebx
mov send, eax
end;
enviar_dw(send,PCI_CONF_PORT_INDEX);
pci_read_dword := leer_dw(PCI_CONF_PORT_DATA);
end;
function pci_device_count (bus : dword) : dword;
var
vendor_id : dword;
device_id : dword;
dev, devs : dword;
func, read : dword;
bug_tmp : dword;
begin
devs := 0;
for dev:=0 to (PCI_SLOTS - 1) do
begin
for func:=0 to 7 do
begin
read := pci_read_dword(bus, dev, func, PCI_CONFIG_VENDOR);
vendor_id := read and $FFFF;
device_id := read div 65536;
{ Correction du bug (voir procÚdure scanpci) }
if (func = 0) then
begin
bug_tmp := device_id;
end
else
begin
if (device_id = bug_tmp) then
break;
end;
{ Fin correction du bug }
if ((vendor_id < $FFFF) and (vendor_id <> 0)) then
begin
devs := devs + 1;
end;
end;
end;
pci_device_count := devs;
end;
function pci_lookup (vendorid, deviceid : dword) : p_pci_device; [public, alias : 'PCI_LOOKUP'];
var tmp:dword;
begin
if (nm_pci_dev = 0 ) then exit;
for tmp:= 0 to Max_PCI do
begin
If (pci_devices[tmp].vendor_id=vendorid) and (pci_devices[tmp].device_id=deviceid) then
begin
pci_lookup:=@pci_devices[tmp];
exit
end;
end;
end;
procedure check_pci_devices;
var
devices : array[0..3] of dword;
i : dword;
begin
for i := 0 to 3 do
begin
devices[i] := pci_device_count(i);
nm_pci_dev := nm_pci_dev + devices[i];
end;
actual_nb := 0;
for i:=0 to 3 do
begin
if (devices[i] > 0) then scanpci(i);
end;
end;
end.
|
unit u_sem;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
u_tokens,
u_ast_constructions,
u_ast_blocks,
u_ast_constructions_blocks,
u_ast_expression,
u_ast_expression_blocks;
type
TMashSEM = class
public
imp_lst: TList;
regapi_lst: TList;
ast_lst: TList;
const_lst: TList;
imports: TStringList;
consts: TStringList;
global_vars: TStringList;
classes_lst: TList;
classes_names: TStringList;
virtual_table: TStringList;
max_class_parents: word;
enums: TList;
enums_names: TStringList;
global_nodes: TList;
methods: TList;
class_methods: TList;
methods_names: TStringList;
class_methods_names: TStringList;
constructor Create(_imp_lst, _regapi_lst, _ast_lst, _const_lst: TList);
destructor Destroy; override;
procedure FillLists;
procedure Process;
procedure CheckNode(node: TMashASTBlock; isMethodNodes: boolean; Method: TMashASTB_Method);
function ItCanBeANewVar(v: string): boolean; inline;
function FindMethod(m: string): TMashASTB_Method;
procedure OptCheckNode(node: TMashASTBlock);
procedure OptCheck;
procedure Optimisation;
end;
implementation
constructor TMashSEM.Create(_imp_lst, _regapi_lst, _ast_lst, _const_lst: TList);
begin
inherited Create;
self.imp_lst := _imp_lst;
self.regapi_lst := _regapi_lst;
self.ast_lst := _ast_lst;
self.const_lst := _const_lst;
self.imports := TStringList.Create;
self.consts := TStringList.Create;
self.global_vars := TStringList.Create;
self.classes_lst := TList.Create;
self.classes_names := TStringList.Create;
self.virtual_table := TStringList.Create;
self.max_class_parents := 0;
self.enums := TList.Create;
self.enums_names := TStringList.Create;
self.global_nodes := TList.Create;
self.methods := TList.Create;
self.class_methods := TList.Create;
self.methods_names := TStringList.Create;
self.class_methods_names := TStringList.Create;
end;
destructor TMashSEM.Destroy;
begin
FreeAndNil(self.imports);
FreeAndNil(self.consts);
FreeAndNil(self.global_vars);
FreeAndNil(self.classes_lst);
FreeAndNil(self.classes_names);
FreeAndNil(self.virtual_table);
FreeAndNil(self.enums);
FreeAndNil(self.enums_names);
FreeAndNil(self.global_nodes);
FreeAndNil(self.methods);
FreeAndNil(self.class_methods);
FreeAndNil(self.methods_names);
FreeAndNil(self.class_methods_names);
inherited;
end;
procedure TMashSEM.FillLists;
var
c, j, d, g, f: cardinal;
k: integer;
s: string;
p, p2: pointer;
ok, parent_exist: boolean;
b: boolean;
begin
c := 0;
while c < self.imp_lst.count do
begin
s := TMashASTB_Import(self.imp_lst[c]).method_name;
if self.imports.IndexOf(s) = -1 then
self.imports.add(s)
else
raise Exception.Create(
'Duplicate import ''' + s + ''' declaration.'
);
Inc(c);
end;
c := 0;
while c < self.regapi_lst.count do
begin
s := TMashASTB_RegAPI(self.regapi_lst[c]).method_name;
if self.imports.IndexOf(s) = -1 then
self.imports.add(s)
else
raise Exception.Create(
'Duplicate import ''' + s + ''' declaration.'
);
Inc(c);
end;
c := 0;
while c < self.const_lst.count do
begin
s := TMashASTB_Const(self.const_lst[c]).const_name;
if self.consts.IndexOf(s) = -1 then
self.consts.add(s)
else
raise Exception.Create(
'Duplicate constant ''' + s + ''' declaration.'
);
Inc(c);
end;
c := 0;
while c < self.ast_lst.count do
begin
p := self.ast_lst[c];
j := 0;
while j < TMashAST(p).nodes.count do
begin
p2 := TMashAST(p).nodes[j];
case TMashASTBlock(p2).GetType of
btEnum:
begin
self.enums.add(p2);
s := TMashASTB_Enum(p2).Name;
self.global_vars.add(s);
if self.enums_names.IndexOf(s) = -1 then
self.enums_names.add(s)
else
raise Exception.Create(
'Duplicate enum ''' + s + ''' declaration.'
);
end;
btMethod:
begin
if TMashASTB_Method(p2).is_class_method then
begin
self.class_methods.add(p2);
if self.class_methods_names.IndexOf(TMashASTB_Method(p2).method_name) = -1 then
self.class_methods_names.add(TMashASTB_Method(p2).method_name);
TMashASTB_Method(p2).local_vars.add('this');
end
else
begin
self.methods.add(p2);
if self.methods_names.IndexOf(TMashASTB_Method(p2).method_name) = -1 then
self.methods_names.add(TMashASTB_Method(p2).method_name)
else
raise Exception.Create(
'Duplicate method name ''' + TMashASTB_Method(p2).method_name + ''' at line ' +
IntToStr(TMashASTB_Method(p2).line + 1) + ' at file ''' +
TMashASTB_Method(p2).fp^ + '''.'
);
end;
k := 0;
while k < TMashASTB_Method(p2).params.count do
begin
s := TMashASTB_Param(TMashASTB_Method(p2).params[k]).param.value;
b := TMashASTB_Param(TMashASTB_Method(p2).params[k]).is_enumerable and
(TMashASTB_Method(p2).params.count > 1);
if b then
b := b and ((k + 1) = TMashASTB_Method(p2).params.count)
else
b := true;
if (TMashASTB_Method(p2).local_vars.IndexOf(s) = -1) and b then
TMashASTB_Method(p2).local_vars.add(s)
else
begin
if TMashASTB_Method(p2).is_class_method then
s := TMashASTB_Method(p2).class_name + '::' + TMashASTB_Method(p2).method_name
else
s := TMashASTB_Method(p2).method_name;
raise Exception.Create(
'Invalid method ''' + s + ''' declaration at line ' +
IntToStr(TMashASTB_Method(p2).line + 1) + ' at file ''' +
TMashASTB_Method(p2).fp^ + '''.'
);
end;
Inc(k);
end;
end;
btClass:
begin
self.classes_lst.add(p2);
s := TMashASTB_Class(p2).class_name;
if self.classes_names.IndexOf(s) = -1 then
self.classes_names.add(s)
else
raise Exception.Create(
'Duplicate class ''' + s + ''' declaration.'
);
if self.consts.IndexOf(s) = -1 then
self.consts.add(s)
else
raise Exception.Create(
'Duplicate constant ''' + s + ''' declaration.'
);
end;
else
self.global_nodes.add(p2);
end;
Inc(j);
end;
Inc(c);
end;
// Checking enum's
c := 0;
while c < self.enums.count do
begin
p := self.enums[c];
j := 0;
while j < TMashASTB_Enum(p).Nodes.count do
begin
s := TMashASTB_EnumItem(TMashASTB_Enum(p).Nodes[j]).Name;
if self.consts.IndexOf(s) = -1 then
self.consts.Add(s)
else
raise Exception.Create(
'Duplicate constant ''' + s + ''' declaration.'
);
Inc(j);
end;
Inc(c);
end;
// Checking classes
c := 0;
while c < self.class_methods.count do
begin
p := self.class_methods[c];
s := TMashASTB_Method(p).class_name;
if self.classes_names.IndexOf(s) = -1 then
raise Exception.Create(
'Unknown class ''' + s + ''' in class method ''' +
TMashASTB_Method(p).class_name + '::' + TMashASTB_Method(p).method_name +
''' declaration at line ' + IntToStr(TMashASTB_Method(p).line + 1) +
' at file ''' + TMashASTB_Method(p).fp^ + '''.'
);
Inc(c);
end;
c := 0;
while c < self.classes_lst.count do
begin
p := self.classes_lst[c];
if TMashASTB_Class(p).class_parents.count > self.max_class_parents then
self.max_class_parents := TMashASTB_Class(p).class_parents.count;
j := 0;
while j < self.class_methods.count do
begin
p2 := self.class_methods[j];
if TMashASTB_Method(p2).class_name = TMashASTB_Class(p).class_name then
begin
k := 0;
while k < TMashASTB_Class(p).class_methods.count do
begin
if TMashClassMethodReference(
TMashASTB_Class(p).class_methods[k]
).method_name = TMashASTB_Method(p2).method_name then
raise Exception.Create(
'Duplicate method ''' + TMashASTB_Method(p2).class_name + '::' +
TMashASTB_Method(p2).method_name + ''' declaration at line ' +
IntToStr(TMashASTB_Method(p2).line + 1) + ' at file ''' +
TMashASTB_Method(p2).fp^ + '''.'
);
Inc(k);
end;
TMashASTB_Class(p).class_methods.Add(
TMashClassMethodReference.Create(
TMashASTB_Method(p2).method_name,
TMashASTB_Method(p2)
)
);
end;
Inc(j);
end;
Inc(c);
end;
// Resolving dependens
c := 0;
while c <= self.max_class_parents do
begin
j := 0;
while j < self.classes_lst.count do
begin
p := self.classes_lst[j];
// Checking class by class
if TMashASTB_Class(p).class_parents.count = c then
begin
d := 0;
while d < self.classes_lst.Count do
begin
p2 := self.classes_lst[d];
if (TMashASTB_Class(p2).class_parents.IndexOf(TMashASTB_Class(p).class_name) <> -1) and (p <> p2) then
begin
g := 0;
while g < TMashASTB_Class(p).class_vars.Count do
begin
if TMashASTB_Class(p2).class_vars.IndexOf(TMashASTB_Class(p).class_vars[g]) = -1 then
TMashASTB_Class(p2).class_vars.Add(TMashASTB_Class(p).class_vars[g]);
Inc(g);
end;
g := 0;
while g < TMashASTB_Class(p).class_methods.Count do
begin
b := false;
f := 0;
while f < TMashASTB_Class(p2).class_methods.Count do
begin
if TMashClassMethodReference(TMashASTB_Class(p).class_methods[g]).method_name =
TMashClassMethodReference(TMashASTB_Class(p2).class_methods[f]).method_name then
begin
b := true;
break;
end;
Inc(f);
end;
if not b then
TMashASTB_Class(p2).class_methods.Add(TMashASTB_Class(p).class_methods[g]);
Inc(g);
end;
end;
Inc(d);
end;
end;
Inc(j);
end;
Inc(c);
end;
c := 0;
while c < Self.classes_lst.Count do
begin
p := Self.classes_lst[c];
j := 0;
while j < TMashASTB_Class(p).class_parents.Count do
begin
if Self.classes_names.IndexOf(TMashASTB_Class(p).class_parents[j]) = -1 then
raise Exception.Create(
'Unresolved reference ''' + TMashASTB_Class(p).class_parents[j] +
''' in class ''' + TMashASTB_Class(p).class_name + ''' declaration.'
);
Inc(j);
end;
Inc(c);
end;
// Filling virtual class table
self.virtual_table.Add('type');
c := 0;
while c < self.class_methods_names.count do
begin
self.virtual_table.add(self.class_methods_names[c]);
Inc(c);
end;
c := 0;
while c < self.classes_lst.count do
begin
p := self.classes_lst[c];
j := 0;
while j < TMashASTB_Class(p).class_vars.count do
begin
if self.virtual_table.IndexOf(TMashASTB_Class(p).class_vars[j]) = -1 then
self.virtual_table.add(TMashASTB_Class(p).class_vars[j]);
Inc(j);
end;
Inc(c);
end;
end;
procedure TMashSEM.Process;
var
c, j: cardinal;
m: TMashASTB_Method;
begin
self.FillLists;
c := 0;
while c < self.global_nodes.count do
begin
self.CheckNode(TMashASTBlock(self.global_nodes[c]), false, nil);
Inc(c);
end;
c := 0;
while c < self.methods.count do
begin
m := TMashASTB_Method(self.methods[c]);
j := 0;
while j < m.Nodes.count do
begin
self.CheckNode(TMashASTBlock(m.Nodes[j]), true, m);
Inc(j);
end;
Inc(c);
end;
c := 0;
while c < self.class_methods.count do
begin
m := TMashASTB_Method(self.class_methods[c]);
j := 0;
while j < m.Nodes.count do
begin
self.CheckNode(TMashASTBlock(m.Nodes[j]), true, m);
Inc(j);
end;
Inc(c);
end;
OptCheck;
end;
function TMashSEM.ItCanBeANewVar(v: string): boolean; inline;
begin
Result := (self.consts.IndexOf(v) = -1) and
(self.imports.IndexOf(v) = -1) and
(self.methods_names.IndexOf(v) = -1) and
(self.enums_names.IndexOf(v) = -1) and
(self.global_vars.IndexOf(v) = -1);
end;
procedure TMashSEM.CheckNode(node: TMashASTBlock; isMethodNodes: boolean; Method: TMashASTB_Method);
var
t: TMashToken;
c: cardinal;
begin
case node.GetType of
btExpression: self.CheckNode(
TMashASTExpression(TMashASTB_Expression(node).ast).TreeNode,
isMethodNodes, Method
);
btEOperation:
self.CheckNode(TMashASTE_Operation(node).A, isMethodNodes, Method);
btEOperationLR:
begin
self.CheckNode(TMashASTE_OperationLR(node).L, isMethodNodes, Method);
self.CheckNode(TMashASTE_OperationLR(node).R, isMethodNodes, Method);
end;
btPSimpleObject:
begin
t := TMashASTP_SimpleObject(node).Obj;
if t.info = ttWord then
if ItCanBeANewVar(t.value) then
begin
if isMethodNodes then
begin
if Method.local_vars.IndexOf(t.value) = -1 then
Method.local_vars.add(t.value);
end
else
self.global_vars.add(t.value);
end
end;
btIf:
begin
c := 0;
while c < TMashASTB_If(node).Nodes.count do
begin
self.CheckNode(TMashASTBlock(TMashASTB_If(node).Nodes[c]), isMethodNodes, Method);
Inc(c);
end;
c := 0;
if TMashASTB_If(node).hasElse then
while c < TMashASTB_If(node).ElseNodes.count do
begin
self.CheckNode(TMashASTBlock(TMashASTB_If(node).ElseNodes[c]), isMethodNodes, Method);
Inc(c);
end;
end;
btSwitch:
begin
c := 0;
while c < TMashASTB_Switch(node).Nodes.count do
begin
self.CheckNode(TMashASTBlock(TMashASTB_Switch(node).Nodes[c]), isMethodNodes, Method);
Inc(c);
end;
if TMashASTB_Switch(node).hasElse then
self.CheckNode(TMashASTB_Switch(node).ElseCase, isMethodNodes, Method);
end;
btWhile, btWhilst, btCase, btLaunch:
begin
c := 0;
while c < TMashASTBlockWithNodes(node).Nodes.count do
begin
self.CheckNode(TMashASTBlock(TMashASTBlockWithNodes(node).Nodes[c]), isMethodNodes, Method);
Inc(c);
end;
end;
btForEach:
begin
if ItCanBeANewVar(TMashASTB_ForEach(node).forVar) then
if isMethodNodes then
begin
if Method.local_vars.IndexOf(TMashASTB_ForEach(node).forVar) = -1 then
Method.local_vars.add(TMashASTB_ForEach(node).forVar);
end
else
self.global_vars.add(TMashASTB_ForEach(node).forVar);
c := 0;
while c < TMashASTB_ForEach(node).Nodes.count do
begin
self.CheckNode(TMashASTBlock(TMashASTB_ForEach(node).Nodes[c]), isMethodNodes, Method);
Inc(c);
end;
end;
btAsync:
begin
if ItCanBeANewVar(TMashASTB_Async(node).forVar) then
if isMethodNodes then
begin
if Method.local_vars.IndexOf(TMashASTB_Async(node).forVar) = -1 then
Method.local_vars.add(TMashASTB_Async(node).forVar);
end
else
self.global_vars.add(TMashASTB_Async(node).forVar);
c := 0;
while c < TMashASTB_Async(node).Nodes.count do
begin
self.CheckNode(TMashASTBlock(TMashASTB_Async(node).Nodes[c]), isMethodNodes, Method);
Inc(c);
end;
end;
btTry:
begin
c := 0;
while c < TMashASTB_Try(node).Nodes.count do
begin
self.CheckNode(TMashASTBlock(TMashASTB_Try(node).Nodes[c]), isMethodNodes, Method);
Inc(c);
end;
if TMashASTB_Try(node).hasCatch then
begin
if ItCanBeANewVar(TMashASTB_Try(node).forVar) then
if isMethodNodes then
begin
if Method.local_vars.IndexOf(TMashASTB_Try(node).forVar) = -1 then
Method.local_vars.add(TMashASTB_Try(node).forVar);
end
else
self.global_vars.add(TMashASTB_Try(node).forVar);
c := 0;
while c < TMashASTB_Try(node).NodesCatch.count do
begin
self.CheckNode(TMashASTBlock(TMashASTB_Try(node).NodesCatch[c]), isMethodNodes, Method);
Inc(c);
end;
end;
end;
end;
end;
function TMashSem.FindMethod(m: string): TMashASTB_Method;
var
c: cardinal;
begin
Result := nil;
c := 0;
while c < methods.Count do
begin
if TMashASTB_Method(methods[c]).method_name = m then
begin
Result := TMashASTB_Method(methods[c]);
break;
end;
Inc(c);
end;
end;
procedure TMashSem.OptCheckNode(node: TMashASTBlock);
var
m: TMashASTB_Method;
begin
case node.GetType of
btExpression: OptCheckNode( TMashASTExpression(node).TreeNode );
btEOperation: OptCheckNode( TMashASTE_Operation(node).A );
btEOperationLR:
begin
OptCheckNode( TMashASTE_OperationLR(node).L );
OptCheckNode( TMashASTE_OperationLR(node).R );
end;
btPCall:
begin
if TMashASTP_Call(node).Obj.GetType.
m := FindMethod();
end;
end;
end;
procedure TMashSem.OptCheck;
var
c: cardinal;
m: TMashASTB_Method;
begin
c := 0;
while c < global_nodes.Count do
begin
OptCheckNode( TMashASTBlock(global_nodes[c]) );
Inc(c);
end;
c := 0;
m := FindMethod('main');
if m <> nil then
while c < m.Nodes.Count do
begin
OptCheckNode( TMashASTBlock(m.Nodes[c]) );
Inc(c);
end;
end;
procedure TMashSem.Optimisation;
begin
//
end;
end.
|
unit dmScriptEngine;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Dialogs, lua, plua, LuaWrapper,
pLuaObject, Graphics, ExtCtrls;
type
{ TScriptEngine }
TScriptEngine = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
private
function GetCanvas: TCanvas;
function GetImage: TImage;
{ private declarations }
procedure LoadLibs(LuaWrapper : TLua);
procedure ScriptExceptionHandler( Title: ansistring; Line: Integer; Msg: ansistring;
var handled : Boolean);
public
{ public declarations }
Lua : TLua;
procedure Execute(Source : AnsiString);
property Canvas : TCanvas read GetCanvas;
property Image : TImage read GetImage;
end;
var
ScriptEngine: TScriptEngine;
implementation
uses
MainForm, Turtle;
function lua_Clear(L : Plua_State) : Integer; cdecl;
var
n, c : Integer;
begin
result := 0;
n := lua_gettop(l);
if (n > 0) and (lua_isnumber(l, 1)) then
c := lua_tointeger(l, 1)
else
c := Integer(clWhite);
ScriptEngine.Canvas.Brush.Color := c;
ScriptEngine.Canvas.Pen.Color := c;
ScriptEngine.Canvas.Rectangle(0, 0, ScriptEngine.Image.Width, ScriptEngine.Image.Height);
end;
function lua_print(L : Plua_state) : integer; cdecl;
var
i, n : Integer;
sl : TStringList;
s : AnsiString;
begin
result := 0;
n := lua_gettop(l);
s := '';
sl := TStringList.Create;
try
for i := 1 to n do
s := s + lua_tostring(l, i);
sl.Text := s;
frmMain.memOutput.Lines.AddStrings(sl);
finally
sl.Free;
end;
end;
function lua_HexToInt(L : Plua_state) : integer; cdecl;
var
val : AnsiString;
begin
result := 0;
val := '$' + plua_tostring(l, 1);
lua_pushinteger(l, StrToInt(val));
result := 1;
end;
function lua_SetCanvasSize(L : Plua_state) : integer; cdecl;
var
w, h : integer;
begin
result := 0;
w := lua_tointeger(l, 1);
h := lua_tointeger(l, 2);
ScriptEngine.Image.Width := w;
ScriptEngine.Image.Height := h;
ScriptEngine.Image.Picture.Bitmap.Width := w;
ScriptEngine.Image.Picture.Bitmap.Height := h;
end;
{ TScriptEngine }
procedure TScriptEngine.DataModuleCreate(Sender: TObject);
begin
Lua := TLua.Create(self);
Lua.LibName := 'Script';
Lua.OnLoadLibs := @LoadLibs;
Lua.OnException := @ScriptExceptionHandler;
end;
function TScriptEngine.GetCanvas: TCanvas;
begin
result := frmMain.imgImage.Canvas;
end;
function TScriptEngine.GetImage: TImage;
begin
result := frmMain.imgImage;
end;
procedure TScriptEngine.LoadLibs(LuaWrapper : TLua);
begin
LuaWrapper.RegisterLuaMethod('Clear', @lua_Clear);
LuaWrapper.RegisterLuaMethod('print', @lua_print);
LuaWrapper.RegisterLuaMethod('HexToInt', @lua_HexToInt);
LuaWrapper.RegisterLuaMethod('SetCanvasSize', @lua_SetCanvasSize);
RegisterTurtle(LuaWrapper);
end;
procedure TScriptEngine.ScriptExceptionHandler(Title: ansistring;
Line: Integer; Msg: ansistring; var handled: Boolean);
begin
Handled := true;
frmMain.memOutput.Lines.Add(format('%s (%d): %s', [Title, Line, msg]));
end;
procedure TScriptEngine.Execute(Source: AnsiString);
begin
TurtleCanvas := Canvas;
Lua.LoadScript(Source);
Lua.Execute;
end;
initialization
{$I dmScriptEngine.lrs}
end.
|
unit uDMCloseCount;
interface
uses
SysUtils, Classes, DB, ADODB, uDMInventory;
type
TDMCloseCount = class(TDataModule)
quInvCountItem: TADODataSet;
cmdUpdInventory: TADOCommand;
quModelByBarcode: TADODataSet;
cmdUpdInvCount: TADOCommand;
quInvFrozeItem: TADODataSet;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FSQLConnection: TADOConnection;
FLogError: TStringList;
FDMInventory: TDMInventory;
FIDStore: Integer;
FIDCount: Integer;
FIDUser: Integer;
procedure CloseCycleCount;
procedure ClosePhysicalCount;
procedure CloseLiveCount;
procedure CloseStartUpCount;
procedure UpdateInvCount;
function GetModelByBarcode(ABarcode: String): Integer;
public
procedure CloseInvCount(AIDStore, AIDCount, AIDUser, ACountType: Integer);
property SQLConnection: TADOConnection read FSQLConnection write FSQLConnection;
property LogError: TStringList read FLogError write FLogError;
end;
implementation
uses uSystemConst, uDM;
{$R *.dfm}
{ TDMCloseCount }
procedure TDMCloseCount.DataModuleCreate(Sender: TObject);
begin
FLogError := TStringList.Create;
FDMInventory := TDMInventory.Create(Self);
end;
procedure TDMCloseCount.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(FLogError);
FreeAndNil(FDMInventory);
end;
procedure TDMCloseCount.CloseInvCount(AIDStore, AIDCount, AIDUser,
ACountType: Integer);
begin
FDMInventory.SQLConnection := FSQLConnection;
FIDStore := AIDStore;
FIDCount := AIDCount;
FIDUser := AIDUser;
case ACountType of
INV_COUNT_CYCLE: CloseCycleCount;
INV_COUNT_PHYSICAL: ClosePhysicalCount;
INV_COUNT_LIVE: CloseLiveCount;
INV_COUNT_STARTUP: CloseStartUpCount;
end;
UpdateInvCount;
end;
procedure TDMCloseCount.CloseCycleCount;
var
iIDModel: Integer;
begin
with quInvCountItem do
try
FSQLConnection.BeginTrans;
try
Connection := FSQLConnection;
Parameters.ParamByName('IDCount').Value := FIDCount;
Open;
while not Eof do
begin
iIDModel := GetModelByBarcode(FieldByName('Barcode').AsString);
if iIDModel <> -1 then
FDMInventory.ReplaceInventory(FIDStore, iIDModel, FIDUser,
FieldByName('Qty').AsFloat);
Next;
end;
finally
Close;
end;
FSQLConnection.CommitTrans;
except
on E: Exception do
begin
FLogError.Add('' + E.Message);
FSQLConnection.RollbackTrans;
end;
end;
end;
procedure TDMCloseCount.ClosePhysicalCount;
var
iIDModel: Integer;
begin
try
FSQLConnection.BeginTrans;
with quInvFrozeItem do
try
Connection := FSQLConnection;
Parameters.ParamByName('IDCount').Value := FIDCount;
Open;
while not Eof do
begin
iIDModel := FieldByName('IDModel').AsInteger;
FDMInventory.ZeroInventory(FIDStore, iIDModel, FIDUser);
Next;
end;
finally
Close;
end;
with quInvCountItem do
try
Connection := FSQLConnection;
Parameters.ParamByName('IDCount').Value := FIDCount;
Open;
while not Eof do
begin
iIDModel := GetModelByBarcode(FieldByName('Barcode').AsString);
if iIDModel <> -1 then
FDMInventory.AddInventory(FIDStore, iIDModel, FIDUser,
FieldByName('Qty').AsFloat);
Next;
end;
finally
Close;
end;
FSQLConnection.CommitTrans;
except
on E: Exception do
begin
FLogError.Add('' + E.Message);
FSQLConnection.RollbackTrans;
end;
end;
end;
procedure TDMCloseCount.CloseLiveCount;
begin
with cmdUpdInvCount do
try
Connection := FSQLConnection;
Parameters.ParamByName('IDCount').Value := FIDCount;
Parameters.ParamByName('EndDate').Value := Now;
Execute;
except
on E: Exception do
FLogError.Add('' + E.Message);
end;
end;
procedure TDMCloseCount.CloseStartUpCount;
begin
//Look in catalog
with cmdUpdInvCount do
try
Connection := FSQLConnection;
Parameters.ParamByName('IDCount').Value := FIDCount;
Parameters.ParamByName('EndDate').Value := Now;
Execute;
except
on E: Exception do
FLogError.Add('' + E.Message);
end;
end;
procedure TDMCloseCount.UpdateInvCount;
begin
with cmdUpdInvCount do
try
Connection := FSQLConnection;
Parameters.ParamByName('IDCount').Value := FIDCount;
Parameters.ParamByName('EndDate').Value := Now;
Execute;
except
on E: Exception do
FLogError.Add('' + E.Message);
end;
end;
function TDMCloseCount.GetModelByBarcode(ABarcode: String): Integer;
begin
Result := -1;
with quModelByBarcode do
try
Connection := FSQLConnection;
Parameters.ParamByName('Barcode').Value := ABarcode;
Open;
if Recordset.RecordCount > 0 then
Result := FieldByName('IDModel').AsInteger;
finally
Close;
end;
end;
end.
|
unit PE.Types.Relocations;
interface
uses
{$IFDEF DEBUG}
System.SysUtils,
{$ENDIF}
Generics.Collections,
PE.Common,
gRBTree;
{$I 'PE.Types.Relocations.inc'} // Include constants.
type
{ TBaseRelocationBlock }
TBaseRelocationBlock = packed record
// The image base plus the page RVA is added to each offset
// to create the VA where the base relocation must be applied.
PageRVA: UInt32;
// The total number of bytes in the base relocation block, including the
// Page RVA and Block Size fields and the Type/Offset fields that follow.
BlockSize: UInt32;
// Get count of relocation elements (entries).
function Count: integer; {$IFNDEF DEBUG} inline; {$ENDIF}
// Check if this block's size:0 or rva:0.
function IsEmpty: Boolean; inline;
end;
{ TBaseRelocationEntry }
TBaseRelocationEntry = packed record
raw: uint16;
function GetOffset: uint16;
function GetType: byte;
end;
{ TReloc }
TReloc = packed record
RVA: uint64; // relocatable rva
&Type: integer; // see 5.6.2. Base Relocation Types (IMAGE_REL_BASED_...)
end;
PReloc = ^TReloc;
{ TRelocs }
TRelocTree = TRBTree<TReloc>;
TRelocs = class
private
FItems: TRelocTree;
// Find relocation. Result is pointer to relocation otherwise it's nil.
function FindReloc(RVA: TRVA): PReloc; overload;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Count: integer;
function Find(RVA: TRVA; out Reloc: TReloc): Boolean;
// Add non-existing item, or update existing item.
procedure Put(const Value: TReloc); overload;
procedure Put(RVA: TRVA; &Type: integer); overload;
// Result is True if reloc was found and removed.
function Remove(RVA: TRVA): Boolean;
property Items: TRelocTree read FItems;
end;
implementation
uses
PE.Utils;
{ TBaseRelocationBlock }
function TBaseRelocationBlock.Count: integer;
begin
{$IFDEF DEBUG}
if BlockSize < SizeOf(TBaseRelocationBlock) then
raise Exception.Create('Relocation block is too small.');
{$ENDIF}
result := (BlockSize - SizeOf(TBaseRelocationBlock)) div SizeOf(TBaseRelocationEntry);
end;
function TBaseRelocationBlock.IsEmpty: Boolean;
begin
result := (PageRVA = 0) or (BlockSize = 0);
end;
{ TBaseRelocationEntry }
function TBaseRelocationEntry.GetOffset: uint16;
begin
result := raw and $0FFF;
end;
function TBaseRelocationEntry.GetType: byte;
begin
result := raw shr 12;
end;
{ TRelocs }
procedure TRelocs.Put(const Value: TReloc);
var
p: PReloc;
begin
p := FindReloc(Value.RVA);
// If item exists, modify it.
if p <> nil then
// This will modify type, rva will stay same.
// If we'll modify rva, tree will be corrupted.
p^ := Value
else
// If not yet exists, add it.
FItems.Add(Value);
end;
function TRelocs.Remove(RVA: TRVA): Boolean;
var
r: TReloc;
begin
r.RVA := RVA;
r.&Type := 0; // don't care
result := FItems.Remove(r);
end;
procedure TRelocs.Clear;
begin
FItems.Clear;
end;
function TRelocs.Count: integer;
begin
result := FItems.Count;
end;
function RelocTreeCompLessFunc(const A, B: TReloc): Boolean;
begin
result := A.RVA < B.RVA;
end;
constructor TRelocs.Create;
begin
// oranke modified
FItems := TRelocTree.Create(RelocTreeCompLessFunc);
{
FItems := TRelocTree.Create(
function(const A, B: TReloc): Boolean
begin
result := A.RVA < B.RVA;
end);
}
end;
destructor TRelocs.Destroy;
begin
FItems.Free;
inherited;
end;
function TRelocs.Find(RVA: TRVA; out Reloc: TReloc): Boolean;
var
r: TReloc;
p: TRelocTree.TRBNodePtr;
begin
r.RVA := RVA;
r.&Type := 0; // don't care
p := FItems.Find(r);
if p = nil then
Exit(False);
Reloc := p^.K;
Exit(True);
end;
function TRelocs.FindReloc(RVA: TRVA): PReloc;
var
r: TReloc;
p: TRelocTree.TRBNodePtr;
begin
r.RVA := RVA;
r.&Type := 0; // don't care
p := FItems.Find(r);
if p = nil then
Exit(nil);
Exit(@p^.K);
end;
procedure TRelocs.Put(RVA: TRVA; &Type: integer);
var
r: TReloc;
begin
r.RVA := RVA;
r.&Type := &Type;
Put(r);
end;
end.
|
unit Odontologia.Modelo.Ciudad;
interface
uses
Data.DB,
SimpleDAO,
SimpleInterface,
SimpleQueryRestDW,
System.SysUtils,
Odontologia.Modelo.Ciudad.Interfaces,
Odontologia.Modelo.Entidades.Ciudad,
Odontologia.Modelo.Conexion.RestDW,
Odontologia.Modelo.Departamento,
Odontologia.Modelo.Departamento.Interfaces;
type
TModelCiudad = class(TInterfacedOBject, iModelCiudad)
private
FEntidad : TDciudad;
FDAO : iSimpleDao<TDciudad>;
FDataSource : TDataSource;
FDepartamento : iModelDepartamento;
public
constructor Create;
destructor Destroy; override;
class function New : iModelCiudad;
function Entidad : TDciudad; overload;
function Entidad(aEntidad: TDciudad) : iModelCiudad; overload;
function DAO : iSimpleDao<TDciudad>;
function DataSource(aDataSource: TDataSource) : iModelCiudad;
function Departamento : iModelDepartamento;
end;
implementation
{ TModelCiudad }
constructor TModelCiudad.Create;
begin
FEntidad := TDciudad.Create;
FDAO := TSimpleDAO<TDciudad>
.New(TSimpleQueryRestDW<TDciudad>
.New(ModelConexion.RESTDWDataBase1));
FDepartamento := TModelDepartamento.New;
end;
function TModelCiudad.DAO: iSimpleDao<TDciudad>;
begin
Result := FDAO;
end;
function TModelCiudad.DataSource(aDataSource: TDataSource): iModelCiudad;
begin
Result := Self;
FDataSource := aDataSource;
FDAO.DataSource(FDataSource);
end;
destructor TModelCiudad.Destroy;
begin
FreeAndNil(FEntidad);
inherited;
end;
function TModelCiudad.Entidad(aEntidad: TDciudad): iModelCiudad;
begin
Result := Self;
FEntidad := aEntidad;
end;
function TModelCiudad.Departamento: iModelDepartamento;
begin
Result := FDepartamento;
end;
function TModelCiudad.Entidad: TDciudad;
begin
Result := FEntidad;
end;
class function TModelCiudad.New: iModelCiudad;
begin
Result := Self.Create;
end;
end.
|
unit uDep;
interface
uses
Windows;
type
DepEnforcement = (
// DEP is completely disabled.
DEP_DISABLED,
// DEP is permanently enforced.
DEP_ENABLED,
// DEP with support for ATL7 thunking is permanently enforced.
DEP_ENABLED_ATL7_COMPAT
);
function SetCurrentProcessDEP(enforcement: DepEnforcement): Boolean;
implementation
const
PROCESS_DEP_ENABLE:DWORD = $00000001;
PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION:DWORD = $00000002;
MEM_EXECUTE_OPTION_ENABLE:DWORD = 1;
MEM_EXECUTE_OPTION_DISABLE:DWORD = 2;
MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION:DWORD = 4;
MEM_EXECUTE_OPTION_PERMANENT:DWORD = 8;
type
PROCESS_INFORMATION_CLASS = (ProcessExecuteFlags = $22);
FnSetProcessDEPPolicy = function(dwFlags: DWORD): Boolean; stdcall;
FnNtSetInformationProcess = function(
ProcessHandle: THANDLE;
ProcessInformationClass: PROCESS_INFORMATION_CLASS;
ProcessInformation: Pointer;
ProcessInformationLength: LongWord): HResult;stdcall;
function SetCurrentProcessDEP(enforcement: DepEnforcement): Boolean;
var
SetProcessDEPPolicy: FnSetProcessDEPPolicy;
NtSetInformationProcess: FnNtSetInformationProcess;
hk: HMODULE;
dep_flags: DWORD;
hr: HRESULT;
begin
Result := False;
hk := GetModuleHandle('Kernel32.dll');
if hk <> INVALID_HANDLE_VALUE then begin
@SetProcessDEPPolicy := GetProcAddress(hK, 'SetProcessDEPPolicy');
if @SetProcessDEPPolicy <> nil then begin
case enforcement of
DEP_DISABLED: dep_flags := 0;
DEP_ENABLED: dep_flags := PROCESS_DEP_ENABLE or
PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
DEP_ENABLED_ATL7_COMPAT: dep_flags := PROCESS_DEP_ENABLE;
else Exit;
end;
Result := SetProcessDEPPolicy(dep_flags);
end;
end;
if Result = True then Exit;
hk := GetModuleHandle('ntdll.dll');
if hk <> INVALID_HANDLE_VALUE then begin
@NtSetInformationProcess := GetProcAddress(hK, 'NtSetInformationProcess');
if @NtSetInformationProcess <> nil then begin
case enforcement of
DEP_DISABLED: dep_flags := MEM_EXECUTE_OPTION_DISABLE;
DEP_ENABLED: dep_flags := MEM_EXECUTE_OPTION_PERMANENT or
MEM_EXECUTE_OPTION_ENABLE;
DEP_ENABLED_ATL7_COMPAT: dep_flags := MEM_EXECUTE_OPTION_PERMANENT or
MEM_EXECUTE_OPTION_ENABLE or
MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION;
else Exit;
end;
hr := NtSetInformationProcess(GetCurrentProcess(),
ProcessExecuteFlags,
@dep_flags,
sizeof(dep_flags));
if hr = S_OK then Result := True
else Result := False;
end;
end;
end;
initialization
SetCurrentProcessDEP(DEP_DISABLED);
end. |
{Faça um programa em Pascal que leia um inteiro positivo n, e escreva a soma dos n primeiros termos da série abaixo:
S = 1000/1 - 997/2 + 994/3 ...
Imprima a saída com duas casas decimais.}
program serieS;
var
sinal: integer;
n, denominador, numerador, soma:real;
begin
read(n);
numerador:= 1000;
denominador:= 1;
soma:= 0;
sinal := 1;
while n >= 1 do begin
soma:= soma + (sinal * (numerador / denominador));
numerador:= numerador - 3;
denominador:= denominador + 1;
sinal := sinal * (-1);
n:= n - 1;
end;
writeln(soma:4:2);
end. |
{
"name": "[NEW] far away with gas",
"version":"1.0",
"creator":"Viroo",
"planets": [
{
"name": "Von Ryth",
"mass": 50000,
"position_x": 26000,
"position_y": 36100,
"velocity_x": -86.02473449707031,
"velocity_y": 61.95686340332031,
"required_thrust_to_move": 0,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 788943552,
"radius": 1858,
"heightRange": 0,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 50,
"metalDensity": 0,
"metalClusters": 0,
"metalSpotLimit": -1,
"biomeScale": 100.00000013739177,
"biome": "gas",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Amugaba",
"mass": 35000,
"position_x": 45700,
"position_y": 35000,
"velocity_x": -92.30024719238281,
"velocity_y": -50.431922912597656,
"required_thrust_to_move": 0,
"starting_planet": true,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 1017574272,
"radius": 760,
"heightRange": 0,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 50,
"metalDensity": 75,
"metalClusters": 100,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "metal",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Tech Foundry",
"mass": 5000,
"position_x": -31700,
"position_y": -8500,
"velocity_x": 31.966848373413086,
"velocity_y": -119.217529296875,
"required_thrust_to_move": 3,
"starting_planet": false,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 237092640,
"radius": 250,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 43,
"metalClusters": 43,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "moon",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Sweeney",
"mass": 10000,
"position_x": -25400,
"position_y": 28400,
"velocity_x": -85.38690185546875,
"velocity_y": -76.3671646118164,
"required_thrust_to_move": 0,
"starting_planet": true,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 673616384,
"radius": 574,
"heightRange": 35,
"waterHeight": 34,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 63,
"metalClusters": 70,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "earth",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Sadukar",
"mass": 10000,
"position_x": 12700,
"position_y": -23000,
"velocity_x": 120.76446533203125,
"velocity_y": 66.68299102783203,
"required_thrust_to_move": 0,
"starting_planet": true,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 1358283008,
"radius": 666,
"heightRange": 35,
"waterHeight": 34,
"waterDepth": 100,
"temperature": 80,
"metalDensity": 58.999996185302734,
"metalClusters": 58.999996185302734,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "tropical",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
},
{
"name": "Ka",
"mass": 10000,
"position_x": 50000,
"position_y": -3800,
"velocity_x": 7.5672383308410645,
"velocity_y": 99.56898498535156,
"required_thrust_to_move": 0,
"starting_planet": true,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 1464967296,
"radius": 534,
"heightRange": 35,
"waterHeight": 33,
"waterDepth": 100,
"temperature": 100,
"metalDensity": 75,
"metalClusters": 75,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "lava",
"symmetryType": "none",
"symmetricalMetal": false,
"symmetricalStarts": false,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
}
]
} |
unit UDWindowCursor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeWindowCursorDlg = class(TForm)
pnlWindowCursors: TPanel;
lblCursors: TLabel;
lblWindowArea: TLabel;
lblCursorTypes: TLabel;
sboxCursorShapes: TScrollBox;
imgDefault: TImage;
shpSelection: TShape;
imgMagnify: TImage;
imgHelp: TImage;
imgAppStart: TImage;
imgWait: TImage;
imgNo: TImage;
imgSizeNS: TImage;
imgSizeWE: TImage;
imgSizeNESW: TImage;
imgSizeNWSE: TImage;
imgSizeAll: TImage;
imgUpArrow: TImage;
imgIBeam: TImage;
imgCross: TImage;
imgArrow: TImage;
lbWindowArea: TListBox;
cbCursorTypes: TComboBox;
btnOk: TButton;
btnCancel: TButton;
btnClear: TButton;
imgZoomIn: TImage;
imgReportSection: TImage;
imgHand: TImage;
imgGrabHand: TImage;
imgBackground: TImage;
procedure lbWindowAreaClick(Sender: TObject);
procedure imgCursorClick(Sender: TObject);
procedure cbCursorTypesChange(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure UpdateWindowCursor;
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
rDetailArea : TCrWindowCursor;
rDetailAreaField : TCrWindowCursor;
rGraph : TCrWindowCursor;
rGroupArea : TCrWindowCursor;
rGroupAreaField : TCrWindowCursor;
rHyperLink : TCrWindowCursor;
rOnDemandSubreport : TCrWindowCursor;
end;
var
CrpeWindowCursorDlg: TCrpeWindowCursorDlg;
bWindowCursor : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.FormCreate(Sender: TObject);
begin
bWindowCursor := True;
LoadFormPos(Self);
btnOk.Tag := 1;
btnCancel.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.FormShow(Sender: TObject);
begin
{Store current VCL Settings}
rDetailArea := Cr.WindowCursor.DetailArea;
rDetailAreaField := Cr.WindowCursor.DetailAreaField;
rGraph := Cr.WindowCursor.Graph;
rGroupArea := Cr.WindowCursor.GroupArea;
rGroupAreaField := Cr.WindowCursor.GroupAreaField;
rHyperLink := Cr.WindowCursor.HyperLink;
rOnDemandSubreport := Cr.WindowCursor.OnDemandSubreport;
UpdateWindowCursor;
end;
{------------------------------------------------------------------------------}
{ UpdateWindowCursor }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.UpdateWindowCursor;
begin
lbWindowArea.ItemIndex := 0;
lbWindowAreaClick(Self);
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TScrollBox then
TScrollBox(Components[i]).Enabled := OnOff;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbWindowAreaClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.lbWindowAreaClick(Sender: TObject);
begin
case lbWindowArea.ItemIndex of
0: cbCursorTypes.ItemIndex := Ord(Cr.WindowCursor.DetailArea);
1: cbCursorTypes.ItemIndex := Ord(Cr.WindowCursor.DetailAreaField);
2: cbCursorTypes.ItemIndex := Ord(Cr.WindowCursor.Graph);
3: cbCursorTypes.ItemIndex := Ord(Cr.WindowCursor.GroupArea);
4: cbCursorTypes.ItemIndex := Ord(Cr.WindowCursor.GroupAreaField);
5: cbCursorTypes.ItemIndex := Ord(Cr.WindowCursor.HyperLink);
6: cbCursorTypes.ItemIndex := Ord(Cr.WindowCursor.OnDemandSubreport);
end;
shpSelection.Left := 2 + (cbCursorTypes.ItemIndex * 32) - sboxCursorShapes.HorzScrollBar.Position;
sboxCursorShapes.HorzScrollBar.Position := (shpSelection.Left - 2) + sboxCursorShapes.HorzScrollBar.Position;
end;
{------------------------------------------------------------------------------}
{ cbCursorTypesChange }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.cbCursorTypesChange(Sender: TObject);
begin
case lbWindowArea.ItemIndex of
0: Cr.WindowCursor.DetailArea := TCrWindowCursor(cbCursorTypes.ItemIndex);
1: Cr.WindowCursor.DetailAreaField := TCrWindowCursor(cbCursorTypes.ItemIndex);
2: Cr.WindowCursor.Graph := TCrWindowCursor(cbCursorTypes.ItemIndex);
3: Cr.WindowCursor.GroupArea := TCrWindowCursor(cbCursorTypes.ItemIndex);
4: Cr.WindowCursor.GroupAreaField := TCrWindowCursor(cbCursorTypes.ItemIndex);
5: Cr.WindowCursor.HyperLink := TCrWindowCursor(cbCursorTypes.ItemIndex);
6: Cr.WindowCursor.OnDemandSubreport := TCrWindowCursor(cbCursorTypes.ItemIndex);
end;
shpSelection.Left := 2 + (cbCursorTypes.ItemIndex * 32) - sboxCursorShapes.HorzScrollBar.Position;
sboxCursorShapes.HorzScrollBar.Position := (shpSelection.Left - 2) + sboxCursorShapes.HorzScrollBar.Position;
end;
{------------------------------------------------------------------------------}
{ imgCursorClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.imgCursorClick(Sender: TObject);
begin
cbCursorTypes.ItemIndex := TImage(Sender).Tag;
shpSelection.Left := TImage(Sender).Left - 2;
case lbWindowArea.ItemIndex of
0: Cr.WindowCursor.DetailArea := TCrWindowCursor(cbCursorTypes.ItemIndex);
1: Cr.WindowCursor.DetailAreaField := TCrWindowCursor(cbCursorTypes.ItemIndex);
2: Cr.WindowCursor.Graph := TCrWindowCursor(cbCursorTypes.ItemIndex);
3: Cr.WindowCursor.GroupArea := TCrWindowCursor(cbCursorTypes.ItemIndex);
4: Cr.WindowCursor.GroupAreaField := TCrWindowCursor(cbCursorTypes.ItemIndex);
5: Cr.WindowCursor.HyperLink := TCrWindowCursor(cbCursorTypes.ItemIndex);
6: Cr.WindowCursor.OnDemandSubreport := TCrWindowCursor(cbCursorTypes.ItemIndex);
end;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.btnClearClick(Sender: TObject);
begin
Cr.WindowCursor.Clear;
lbWindowArea.ItemIndex := 0;
lbWindowAreaClick(Self);
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeWindowCursorDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ModalResult = mrCancel then
begin
{Restore Settings}
Cr.WindowCursor.DetailArea := rDetailArea;
Cr.WindowCursor.DetailAreaField := rDetailAreaField;
Cr.WindowCursor.Graph := rGraph;
Cr.WindowCursor.GroupArea := rGroupArea;
Cr.WindowCursor.GroupAreaField := rGroupAreaField;
Cr.WindowCursor.HyperLink := rHyperLink;
Cr.WindowCursor.OnDemandSubreport := rOnDemandSubreport;
end;
bWindowCursor := False;
Release;
end;
end.
|
unit TpInput;
interface
uses
Windows, SysUtils, Classes, Controls, Graphics, Types,
ThWebControl, ThTag, ThInput,
TpControls;
type
TTpInput = class(TThCustomInput)
private
FOnInput: TTpEvent;
FOnGenerate: TTpEvent;
protected
procedure Tag(inTag: TThTag); override;
published
//property AccessKey;
property Align;
property AutoComplete;
property AutoSize;
property Enabled;
//property JavaScript;
property MaxLength;
//property OnBeforeGenerate;
property OnInput: TTpEvent read FOnInput write FOnInput;
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
property Password;
property Size;
property Style;
property StyleClass;
//property TabIndex;
property Text;
end;
implementation
procedure TTpInput.Tag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Add(tpClass, 'TTpInput');
Add('tpName', Name);
Add('tpOnSubmit', OnInput);
Add('tpOnGenerate', OnGenerate);
end;
end;
end.
|
unit unBancoController;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, unControllerBase, unBanco, unModelBase, SQLDB;
type
{ TBancoValidator }
TBancoValidator = class(TInterfacedObject, IModelValidator)
procedure Validate(AModel: TModelBase; out isValid: boolean;
out errors: TStringList);
end;
{ TBancoController }
TBancoController = class(TAbstractController)
private
FFilterCodigo: integer;
FFilterNome: string;
procedure SetFilterCodigo(AValue: integer);
procedure SetFilterNome(AValue: string);
protected
function GetTableName: string; override;
function GetInsertFieldList: TStringList; override;
procedure SetInsertFieldValues(AModel: TModelBase; AQuery: TSQLQuery); override;
procedure SetUpdateFieldValues(AModel: TModelBase; AQuery: TSQLQuery); override;
function PopulateModel(AQuery: TSQLQuery): TModelBase; override;
function GetDefaultOrder: string; override;
function GetValidator: IModelValidator; override;
procedure SetFilterParamsValues(AQuery: TSQLQuery); override;
function GetFilterExpression: string; override;
public
property FilterNome: string read FFilterNome write SetFilterNome;
property FilterCodigo: integer read FFilterCodigo write SetFilterCodigo;
end;
const PARAM_FILTER_CODIGO = 'codigoBanco';
const PARAM_FILTER_NOME = 'nomeBanco';
implementation
{ TBancoValidator }
procedure TBancoValidator.Validate(AModel: TModelBase; out isValid: boolean;
out errors: TStringList);
begin
errors.Clear;
with AModel as TBanco do
begin
if (trim(NomeBanco) = string.Empty) then
begin
errors.Add('O nome do banco é obrigatório!');
end;
if (CodigoBanco <= 0) then
begin
errors.Add('O código do banco é obrigatório!');
end;
end;
isValid := errors.Count = 0;
end;
{ TBancoController }
procedure TBancoController.SetFilterCodigo(AValue: integer);
begin
if FFilterCodigo=AValue then Exit;
FFilterCodigo:=AValue;
end;
procedure TBancoController.SetFilterNome(AValue: string);
begin
if FFilterNome=AValue then Exit;
FFilterNome:=AValue;
end;
function TBancoController.GetTableName: string;
begin
Result := 'banco';
end;
function TBancoController.GetInsertFieldList: TStringList;
var
ret: TStringList;
begin
ret := TStringList.Create;
ret.Add('codigoBanco');
ret.Add('nomeBanco');
ret.Add('observacao');
Result := ret;
end;
procedure TBancoController.SetInsertFieldValues(AModel: TModelBase; AQuery: TSQLQuery);
begin
with AModel as TBanco do
begin
Aquery.ParamByName('codigoBanco').AsInteger := CodigoBanco;
AQuery.ParamByName('nomeBanco').AsString := NomeBanco;
AQuery.ParamByName('observacao').AsString:= Observacao;
end;
end;
procedure TBancoController.SetUpdateFieldValues(AModel: TModelBase; AQuery: TSQLQuery);
begin
with AModel as TBanco do
begin
Aquery.ParamByName('codigoBanco').AsInteger := CodigoBanco;
AQuery.ParamByName('nomeBanco').AsString := NomeBanco;
AQuery.ParamByName('observacao').AsString:= Observacao;
end;
end;
function TBancoController.PopulateModel(AQuery: TSQLQuery): TModelBase;
var
ret: TBanco;
begin
ret := TBanco.Create;
ret.NomeBanco := AQuery.FieldByName('nomeBanco').AsString;
ret.CodigoBanco := AQuery.FieldByName('codigoBanco').AsInteger;
ret.Observacao:= AQuery.FieldByName('observacao').AsString;
Result := ret;
end;
function TBancoController.GetDefaultOrder: string;
begin
Result := 'nomeBanco ASC';
end;
function TBancoController.GetValidator: IModelValidator;
begin
Result := TBancoValidator.Create;
end;
procedure TBancoController.SetFilterParamsValues(AQuery: TSQLQuery);
begin
if ( FFilterCodigo > 0 ) then
begin
AQuery.ParamByName(PARAM_FILTER_CODIGO).AsInteger:= FFilterCodigo;
end;
if ( FFilterNome <> String.Empty ) then
begin
AQuery.ParamByName(PARAM_FILTER_NOME).AsString:= '%'+FFilterNome+'%';
end;
end;
function TBancoController.GetFilterExpression: string;
var
sSql : string;
begin
sSql := 'WHERE 1 = 1 ';
if ( FFilterCodigo > 0 ) then
begin
sSql := sSql + ' AND codigoBanco = :'+ PARAM_FILTER_CODIGO;
end;
if ( FFilterNome <> String.Empty ) then
begin
sSql := sSql + ' AND UPPER(nomeBanco) like UPPER(:'+ PARAM_FILTER_NOME+')';
end;
Result := sSql;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFContextMenuHandler;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefContextMenuHandlerOwn = class(TCefBaseRefCountedOwn, ICefContextMenuHandler)
protected
procedure OnBeforeContextMenu(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); virtual;
function RunContextMenu(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel; const callback: ICefRunContextMenuCallback): Boolean; virtual;
function OnContextMenuCommand(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags): Boolean; virtual;
procedure OnContextMenuDismissed(const browser: ICefBrowser; const frame: ICefFrame); virtual;
public
constructor Create; virtual;
end;
TCustomContextMenuHandler = class(TCefContextMenuHandlerOwn)
protected
FEvent: IChromiumEvents;
procedure OnBeforeContextMenu(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); override;
function RunContextMenu(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel; const callback: ICefRunContextMenuCallback): Boolean; override;
function OnContextMenuCommand(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags): Boolean; override;
procedure OnContextMenuDismissed(const browser: ICefBrowser; const frame: ICefFrame); override;
public
constructor Create(const events: IChromiumEvents); reintroduce; virtual;
destructor Destroy; override;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFBrowser, uCEFFrame, uCEFContextMenuParams,
uCEFMenuModel, uCEFRunContextMenuCallback;
procedure cef_context_menu_handler_on_before_context_menu(self: PCefContextMenuHandler;
browser: PCefBrowser; frame: PCefFrame; params: PCefContextMenuParams;
model: PCefMenuModel); stdcall;
begin
with TCefContextMenuHandlerOwn(CefGetObject(self)) do
OnBeforeContextMenu(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame),
TCefContextMenuParamsRef.UnWrap(params), TCefMenuModelRef.UnWrap(model));
end;
function cef_context_menu_handler_run_context_menu(self: PCefContextMenuHandler;
browser: PCefBrowser; frame: PCefFrame; params: PCefContextMenuParams;
model: PCefMenuModel; callback: PCefRunContextMenuCallback): Integer; stdcall;
begin
with TCefContextMenuHandlerOwn(CefGetObject(self)) do
Result := Ord(RunContextMenu(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame),
TCefContextMenuParamsRef.UnWrap(params), TCefMenuModelRef.UnWrap(model),
TCefRunContextMenuCallbackRef.UnWrap(callback)));
end;
function cef_context_menu_handler_on_context_menu_command(self: PCefContextMenuHandler;
browser: PCefBrowser; frame: PCefFrame; params: PCefContextMenuParams;
command_id: Integer; event_flags: Integer): Integer; stdcall;
begin
with TCefContextMenuHandlerOwn(CefGetObject(self)) do
Result := Ord(OnContextMenuCommand(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame),
TCefContextMenuParamsRef.UnWrap(params), command_id, TCefEventFlags(Pointer(@event_flags)^)));
end;
procedure cef_context_menu_handler_on_context_menu_dismissed(self: PCefContextMenuHandler;
browser: PCefBrowser; frame: PCefFrame); stdcall;
begin
with TCefContextMenuHandlerOwn(CefGetObject(self)) do
OnContextMenuDismissed(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame));
end;
constructor TCefContextMenuHandlerOwn.Create;
begin
inherited CreateData(SizeOf(TCefContextMenuHandler));
with PCefContextMenuHandler(FData)^ do
begin
on_before_context_menu := cef_context_menu_handler_on_before_context_menu;
run_context_menu := cef_context_menu_handler_run_context_menu;
on_context_menu_command := cef_context_menu_handler_on_context_menu_command;
on_context_menu_dismissed := cef_context_menu_handler_on_context_menu_dismissed;
end;
end;
procedure TCefContextMenuHandlerOwn.OnBeforeContextMenu(
const browser: ICefBrowser; const frame: ICefFrame;
const params: ICefContextMenuParams; const model: ICefMenuModel);
begin
end;
function TCefContextMenuHandlerOwn.OnContextMenuCommand(
const browser: ICefBrowser; const frame: ICefFrame;
const params: ICefContextMenuParams; commandId: Integer;
eventFlags: TCefEventFlags): Boolean;
begin
Result := False;
end;
procedure TCefContextMenuHandlerOwn.OnContextMenuDismissed(
const browser: ICefBrowser; const frame: ICefFrame);
begin
end;
function TCefContextMenuHandlerOwn.RunContextMenu(const browser: ICefBrowser;
const frame: ICefFrame; const params: ICefContextMenuParams;
const model: ICefMenuModel;
const callback: ICefRunContextMenuCallback): Boolean;
begin
Result := False;
end;
// TCustomContextMenuHandler
constructor TCustomContextMenuHandler.Create(const events: IChromiumEvents);
begin
inherited Create;
FEvent := events;
end;
destructor TCustomContextMenuHandler.Destroy;
begin
FEvent := nil;
inherited Destroy;
end;
procedure TCustomContextMenuHandler.OnBeforeContextMenu(const browser : ICefBrowser;
const frame : ICefFrame;
const params : ICefContextMenuParams;
const model : ICefMenuModel);
begin
if (FEvent <> nil) then FEvent.doOnBeforeContextMenu(browser, frame, params, model);
end;
function TCustomContextMenuHandler.RunContextMenu(const browser : ICefBrowser;
const frame : ICefFrame;
const params : ICefContextMenuParams;
const model : ICefMenuModel;
const callback : ICefRunContextMenuCallback): Boolean;
begin
if (FEvent <> nil) then
Result := FEvent.doRunContextMenu(browser, frame, params, model, callback)
else
Result := inherited RunContextMenu(browser, frame, params, model, callback);
end;
function TCustomContextMenuHandler.OnContextMenuCommand(const browser : ICefBrowser;
const frame : ICefFrame;
const params : ICefContextMenuParams;
commandId : Integer;
eventFlags : TCefEventFlags): Boolean;
begin
if (FEvent <> nil) then
Result := FEvent.doOnContextMenuCommand(browser, frame, params, commandId, eventFlags)
else
Result := inherited OnContextMenuCommand(browser, frame, params, commandId, eventFlags);
end;
procedure TCustomContextMenuHandler.OnContextMenuDismissed(const browser: ICefBrowser; const frame: ICefFrame);
begin
if (FEvent <> nil) then FEvent.doOnContextMenuDismissed(browser, frame);
end;
end.
|
unit ufrmModal;
interface
uses
Classes, Controls, Forms,
DynamicSkinForm, uCEFChromium,
uframeChrome, uCEFInterfaces, uCEFTypes, SysUtils;
type
TfrmModal = class(TForm)
frameChrome1: TframeChrome;
DSF: TspDynamicSkinForm;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure frameChrome1Chromium1TitleChange(Sender: TObject;
const browser: ICefBrowser; const title: ustring);
private
{ Private declarations }
FUrl: string;
FInstance: TfrmModal;
protected
public
{ Public declarations }
constructor Create(Caption: string; Url: string; width, height: Integer); overload;
end;
var
frmModal: TfrmModal;
implementation
{$R *.dfm}
{ TfrmModel }
constructor TfrmModal.Create(Caption: string;Url: string; width, height: Integer);
begin
inherited Create(Application);
Self.Caption := Trim(Caption);
Self.width := width;
Self.height := height;
Self.FUrl := Url;
end;
procedure TfrmModal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmModal.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := frameChrome1.FCanClose;
if not(frameChrome1.FClosing) then
begin
frameChrome1.FClosing := True;
Visible := False;
frameChrome1.Chromium1.CloseBrowser(True);
end;
end;
procedure TfrmModal.FormShow(Sender: TObject);
begin
frameChrome1.setInfo(Self, Self.FUrl);
if fsModal in self.FormState then
Self.FormStyle := fsNormal;
end;
procedure TfrmModal.frameChrome1Chromium1TitleChange(Sender: TObject;
const browser: ICefBrowser; const title: ustring);
var
tmpTitle: string;
begin
if Self.Caption <> '' then
Exit;
tmpTitle := Trim(title);
if (tmpTitle <> '') and (tmpTitle <> 'about:blank') then
Self.Caption := tmpTitle;
end;
end.
|
(* Stack ADT 1 19.04.2017 *)
(* ---------- *)
(* implementing the stack as abstract data type - version 1 *)
(* ========================================================= *)
UNIT StackADT1;
INTERFACE
CONST
max = 100;
TYPE
Stack = Record
data: Array[1..max] OF INTEGER;
top: INTEGER;
END;
PROCEDURE Init(VAR s: Stack);
PROCEDURE Push(VAR s: Stack; e: INTEGER);
PROCEDURE Pop(VAR s: Stack; VAR e: INTEGER);
(* Copying of an adress is faster than copying the actual stack
Although not nice implementation, its faster with big structures *)
FUNCTION Empty(VAR s: Stack): BOOLEAN;
IMPLEMENTATION
PROCEDURE Init(VAR s: Stack);
BEGIN
s.top := 0;
END;
PROCEDURE Push(VAR s: Stack; e: INTEGER);
BEGIN
IF s.top = max THEN BEGIN
WriteLn('Stack overflow');
END
ELSE BEGIN
s.top := s.top + 1;
s.data[s.top] := e;
END;
END;
PROCEDURE Pop(VAR s: Stack; VAR e: INTEGER);
BEGIN
IF s.top = 0 THEN BEGIN
WriteLn('Stack underflow');
END
ELSE BEGIN
e := s.data[s.top];
s.top := s.top - 1;
END;
END;
FUNCTION Empty(VAR s: Stack): BOOLEAN;
BEGIN
Empty := s.top = 0;
END;
BEGIN
END. (* StackADT1 *)
|
{******
单 元:uPublish.pas
作 者:刘景威
日 期:2007-5-16
说 明:发布单元
更 新:
******}
unit uPublish;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBase, StdCtrls, Buttons, ExtCtrls, ImgList, Quiz, Mask, RzEdit,
RzBtnEdt, ShlObj, ActiveX, RzBckgnd, RzPanel, RzTabs, ComCtrls, ShellAPI;
type
TfrmPublish = class(TfrmBase)
lblPub: TLabel;
bvlPublish: TBevel;
ilImg: TImageList;
pcPub: TRzPageControl;
tsPub: TRzTabSheet;
bvlPath: TBevel;
bvlSp: TBevel;
lblPath: TLabel;
lblFile: TLabel;
lblFolder: TLabel;
RzSeparator1: TRzSeparator;
RzSeparator2: TRzSeparator;
RzSeparator3: TRzSeparator;
rbWeb: TRadioButton;
rbLms: TRadioButton;
rbWord: TRadioButton;
rbExcel: TRadioButton;
pnlImg: TRzPanel;
imgWeb: TImage;
imgLms: TImage;
imgWord: TImage;
imgExcel: TImage;
edtFile: TEdit;
beFolder: TRzButtonEdit;
tsRst: TRzTabSheet;
bvlFinish: TBevel;
imgQuiz: TImage;
imgRst: TImage;
imgArrow: TImage;
Bevel2: TBevel;
pnlRst: TRzPanel;
lblOpenFile: TLabel;
lblFilePath: TLabel;
lblOpenFolder: TLabel;
lblFolderPath: TLabel;
lblSuccess: TLabel;
RzSeparator4: TRzSeparator;
pnlDis: TPanel;
lblDis: TLabel;
pbDis: TProgressBar;
tmr: TTimer;
pc: TPageControl;
tsLms: TTabSheet;
tsWord: TTabSheet;
lblLms: TLabel;
bvlLms: TBevel;
rb12: TRadioButton;
rb2004: TRadioButton;
bvlWord: TBevel;
lblWord: TLabel;
cbShowAns: TCheckBox;
RzSeparator5: TRzSeparator;
rbExe: TRadioButton;
imgExe: TImage;
tsExe: TTabSheet;
bvlExe: TBevel;
lblExe: TLabel;
cbShowMenu: TCheckBox;
procedure imgWebClick(Sender: TObject);
procedure imgLmsClick(Sender: TObject);
procedure imgWordClick(Sender: TObject);
procedure imgExcelClick(Sender: TObject);
procedure RadioClick(Sender: TObject);
procedure edtFileKeyPress(Sender: TObject; var Key: Char);
procedure beFolderButtonClick(Sender: TObject);
procedure tmrTimer(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure lblFilePathClick(Sender: TObject);
procedure lblFolderPathClick(Sender: TObject);
procedure imgExeClick(Sender: TObject);
private
{ Private declarations }
FPublish: TPublish;
FPubType: TPubType;
protected
procedure LoadData; override;
procedure SaveData; override;
//检查数据
function CheckData: Boolean; override;
public
{ Public declarations }
end;
var
frmPublish: TfrmPublish;
function ShowPublish(APublish: TPublish; APubType: TPubType = ptWeb): Boolean;
implementation
uses uGlobal;
{$R *.dfm}
function ShowPublish(APublish: TPublish; APubType: TPubType): Boolean;
begin
Result := False;
if QuizObj.QuesList.Count = 0 then
begin
MessageBox(Application.MainForm.Handle, PAnsiChar('工程中还没有试题;请先添加试题,然后再发布'), '提示', MB_OK + MB_ICONINFORMATION);
Exit;
end;
frmPublish := TfrmPublish.Create(Application.MainForm);
with frmPublish do
begin
try
pcPub.ActivePageIndex := 0;
pnlDis.Visible := False;
FPublish := APublish;
FPubType := APubType;
LoadData();
Result := ShowModal() = mrOk;
finally
Free;
end;
end;
end;
procedure DisProgress(ACurPos, AMaxPos: Integer); stdcall;
begin
Application.ProcessMessages;
with frmPublish do
begin
if not pnlDis.Visible then pnlDis.Visible := True;
lblDis.Caption := '试题生成中…… ' + FormatFloat('#%', ACurPos * 100 / AMaxPos);
pbDis.Position := Round(ACurPos * 100 / AMaxPos);
pnlDis.Update;
end;
end;
procedure TfrmPublish.LoadData;
begin
case Ord(FPubType) of
0: RadioClick(rbWeb);
1: RadioClick(rbLms);
2: RadioClick(rbWord);
3: RadioClick(rbExcel);
4: RadioClick(rbExe);
end;
with (FPublish) do
begin
if Title <> '' then
edtFile.Text := Title
else edtFile.Text := ChangeFileExt(ExtractFileName(QuizObj.ProjPath), '');
beFolder.Text := Folder;
rb12.Checked := LmsVer = lv12;
rb2004.Checked := LmsVer = lv2004;
cbShowAns.Checked := ShowAnswer;
cbShowMenu.Checked := ShowMenu;
end;
end;
procedure TfrmPublish.SaveData;
begin
with FPublish do
begin
if rbWeb.Checked then PubType := ptWeb;
if rbLms.Checked then PubType := ptLms;
if rbWord.Checked then PubType := ptWord;
if rbExcel.Checked then PubType := ptExcel;
if rbExe.Checked then PubType := ptExe;
Title := edtFile.Text;
Folder := beFolder.Text;
if rb12.Checked then LmsVer := lv12;
if rb2004.Checked then LmsVer := lv2004;
ShowAnswer := cbShowAns.Checked;
ShowMenu := cbShowMenu.Checked;
SaveToReg();
end;
end;
function TfrmPublish.CheckData: Boolean;
begin
Result := False;
if Trim(edtFile.Text) = '' then
begin
MessageBox(Handle, '请设定您要发布的文件名!', '提示', MB_OK + MB_ICONINFORMATION);
edtFile.SetFocus;
Exit;
end;
if not DirectoryExists(beFolder.Text) then
begin
MessageBox(Handle, '输出目录不存在,请设定输出目录!', '提示', MB_OK + MB_ICONINFORMATION);
beFolder.SetFocus;
Exit;
end;
Result := inherited CheckData();
end;
procedure TfrmPublish.RadioClick(Sender: TObject);
var
Tag: Integer;
begin
TRadioButton(Sender).Checked := True;
Tag := TRadioButton(Sender).Tag;
case Tag of
0:
begin
HelpHtml := 'publish_web.html';
ilImg.GetIcon(0, Icon);
end;
1:
begin
HelpHtml := 'publish_lms.html';
ilImg.GetIcon(1, Icon);
end;
2:
begin
HelpHtml := 'publish_word.html';
ilImg.GetIcon(2, Icon);
end;
3:
begin
HelpHtml := 'publish_excel.html';
ilImg.GetIcon(3, Icon);
end;
4:
begin
HelpHtml := 'publish_exe.html';
ilImg.GetIcon(4, Icon);
end;
end;
pc.Visible := Tag in [1..2, 4];
if Tag in [1..2] then
pc.ActivePageIndex := Tag - 1
else pc.ActivePageIndex := Tag - 2;
imgRst.Picture := nil;
ilImg.GetBitmap(Tag + 5, imgRst.Picture.Bitmap);
end;
procedure TfrmPublish.imgWebClick(Sender: TObject);
begin
rbWeb.SetFocus();
end;
procedure TfrmPublish.imgLmsClick(Sender: TObject);
begin
rbLms.SetFocus();
end;
procedure TfrmPublish.imgWordClick(Sender: TObject);
begin
rbWord.SetFocus();
end;
procedure TfrmPublish.imgExcelClick(Sender: TObject);
begin
rbExcel.SetFocus();
end;
procedure TfrmPublish.imgExeClick(Sender: TObject);
begin
rbExe.SetFocus();
end;
procedure TfrmPublish.edtFileKeyPress(Sender: TObject; var Key: Char);
begin
if Key in ['\', '/', ':', '*', '?', '"', '<', '>', '|'] then Key := #0;
end;
procedure TfrmPublish.beFolderButtonClick(Sender: TObject);
var
sDir: string;
begin
if SelectDirectory(Handle, '请选择您想要发布到的文件夹:', beFolder.Text, sDir) then
beFolder.Text := sDir;
end;
procedure TfrmPublish.tmrTimer(Sender: TObject);
begin
tmr.Enabled := False;
pnlDis.Visible := False;
end;
procedure TfrmPublish.btnOKClick(Sender: TObject);
var
sFile: string;
begin
if btnOk.Caption = '发布' then
begin
if not CheckData() then Exit;
SaveData();
case FPublish.PubType of
ptWeb: sFile := FPublish.Folder + FPublish.Title + '.swf';
ptLms: sFile := FPublish.Folder + FPublish.Title + '.zip';
ptWord: sFile := FPublish.Folder + FPublish.Title + '.doc';
ptExcel: sFile := FPublish.Folder + FPublish.Title + '.xls';
ptExe: sFile := FPublish.Folder + FPublish.Title + '.exe';
else
sFile := FPublish.Folder + FPublish.Title + '.swf';
end;
if FileExists(sFile) and (MessageBox(Handle, PAnsiChar('输出文件[' + ExtractFileName(sFile) + ']已存在,要替换吗?'), '提示', MB_YESNO + MB_ICONQUESTION) = ID_NO) then Exit;
pcPub.ActivePage.Enabled := False;
btnOk.Enabled := False;
btnCancel.SetFocus;
pnlDis.Visible := True;
Screen.Cursor := crHourGlass;
FPublish.DisProgress := DisProgress;
FPublish.Handle := Handle;
if FPublish.Execute then
begin
if FPublish.PubType = ptWeb then sFile := FPublish.Folder + FPublish.Title + '.html';
btnOk.Enabled := True;
btnOk.Caption := '上一步';
lblPub.Caption := '完成发布';
btnCancel.Caption := '关闭';
lblFilePath.Caption := sFile;
lblFolderPath.Caption := FPublish.Folder;
pcPub.ActivePageIndex := 1;
lblOpenFolder.Top := lblFilePath.Top + lblFilePath.Height + 7;
end
else btnCancelClick(btnCancel);
Screen.Cursor := crDefault;
end
else
begin
btnOk.Caption := '发布';
btnOk.SetFocus;
pnlDis.Visible := False;
pcPub.ActivePageIndex := 0;
pcPub.ActivePage.Enabled := True;
lblPub.Caption := '试题发布';
btnCancel.Caption := '取消';
end;
end;
procedure TfrmPublish.btnCancelClick(Sender: TObject);
var
sFile: string;
begin
if (pcPub.ActivePageIndex = 0) and not btnOk.Enabled then
begin
FPublish.DoCancel;
Screen.Cursor := crDefault;
pcPub.ActivePage.Enabled := True;
tmr.Enabled := True;
pnlDis.Update;
btnOk.Enabled := True;
Update;
case FPublish.PubType of
ptWeb: sFile := FPublish.Folder + FPublish.Title + '.swf';
ptLms: sFile := FPublish.Folder + FPublish.Title + '.zip';
ptWord: sFile := FPublish.Folder + FPublish.Title + '.doc';
ptExcel: sFile := FPublish.Folder + FPublish.Title + '.xls';
ptExe: sFile := FPublish.Folder + FPublish.Title + '.exe';
else
sFile := FPublish.Folder + FPublish.Title + '.swf';
end;
if (FPublish.PubType = ptWeb) and FileExists(ChangeFileExt(sFile, '.html')) then DeleteFile(ChangeFileExt(sFile, '.html'));
if FileExists(sFile) then DeleteFile(sFile);
end
else inherited;
end;
procedure TfrmPublish.lblFilePathClick(Sender: TObject);
begin
ShellExecute(Handle, 'open', PAnsiChar(lblFilePath.Caption), nil, nil, SW_SHOW);
end;
procedure TfrmPublish.lblFolderPathClick(Sender: TObject);
begin
if FileExists(lblFilePath.Caption) then
WinExec(PAnsiChar('explorer /select, ' + lblFilePath.Caption), SW_SHOW)
else WinExec(PAnsiChar('explorer ' + lblFolderPath.Caption), SW_SHOW)
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Allows choosing a material in a material library
}
unit FLibMaterialPicker;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
System.Math.Vectors,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.StdCtrls,
FMX.Layouts,
FMX.ListBox,
FMX.Objects,
FMX.Media,
FMX.Viewport3D,
FMX.Controls3D,
FMX.Objects3D,
FMX.Types3D,
FMX.MaterialSources,
FMX.Controls.Presentation,
VXS.Material,
FRMaterialPreview;
type
TVXLibMaterialPicker = class(TForm)
Label1: TLabel;
Label2: TLabel;
LBMaterials: TListBox;
BBOK: TButton;
ImageOK: TImage;
BBCancel: TButton;
MPPreview: TRMaterialPreview;
procedure LBMaterialsClick(Sender: TObject);
procedure LBMaterialsDblClick(Sender: TObject);
procedure CBObjectChange(Sender: TObject);
procedure CBBackgroundChange(Sender: TObject);
public
function Execute(var materialName: TVXLibMaterialName;
materialLibrary: TVXAbstractMaterialLibrary): Boolean;
end;
function GLLibMaterialPicker: TVXLibMaterialPicker;
procedure ReleaseLibMaterialPicker;
//=================================================================
implementation
//=================================================================
{$R *.fmx}
var
vLibMaterialPicker: TVXLibMaterialPicker;
function GLLibMaterialPicker: TVXLibMaterialPicker;
begin
if not Assigned(vLibMaterialPicker) then
vLibMaterialPicker := TVXLibMaterialPicker.Create(nil);
Result := vLibMaterialPicker;
end;
procedure ReleaseLibMaterialPicker;
begin
if Assigned(vLibMaterialPicker) then
begin
vLibMaterialPicker.Free;
vLibMaterialPicker := nil;
end;
end;
//-----------------------------------------------------
{ TLibMaterialPicker }
//-----------------------------------------------------
procedure TVXLibMaterialPicker.CBBackgroundChange(Sender: TObject);
begin
//
end;
procedure TVXLibMaterialPicker.CBObjectChange(Sender: TObject);
begin
//
end;
function TVXLibMaterialPicker.Execute(var materialName: TVXLibMaterialName;
materialLibrary: TVXAbstractMaterialLibrary): Boolean;
begin
with LBMaterials do
begin
materialLibrary.SetNamesToTStrings(LBMaterials.Items);
ItemIndex := Items.IndexOf(materialName);
if (ItemIndex < 0) and (Items.Count > 0) then
ItemIndex := 0;
BBOk.Enabled := (Items.Count > 0);
end;
LBMaterialsClick(Self);
Result := (ShowModal = mrOk);
if Result then
begin
with LBMaterials do
if ItemIndex >= 0 then
materialName := Items[ItemIndex]
else
materialName := '';
end;
end;
procedure TVXLibMaterialPicker.LBMaterialsClick(Sender: TObject);
begin
with LBMaterials do
if ItemIndex >= 0 then
MPPreview.LibMaterial := TVXAbstractLibMaterial(Items.Objects[ItemIndex]);
end;
procedure TVXLibMaterialPicker.LBMaterialsDblClick(Sender: TObject);
begin
/// BBOk.Click;
end;
end.
|
unit KanjiDicTests;
// Requires KANJIDIC in the same folder
interface
uses TestFramework;
type
TKanjidicTests = class(TTestCase)
published
procedure KanjidicRead;
procedure KanjidicLoad;
end;
TKanjidicSpeedTests = class(TTestCase)
public
FReader: TKanjidicTests;
procedure SetUp; override;
procedure TearDown; override;
published
procedure KanjidicReadTime;
procedure KanjidicLoadTime;
end;
implementation
uses SysUtils, Classes, Windows, TestingCommon, JWBIO, KanjidicReader, Kanjidic;
procedure TKanjidicTests.KanjidicRead;
var AInput: TStreamDecoder;
ed: TKanjiDicEntry;
ln: string;
begin
AInput := OpenTextFile(CommonDataDir+'\kanjidic');
AInput.Rewind();
while AInput.ReadLn(ln) do begin
ln := Trim(ln);
if ln='' then continue;
if IsKanjidicComment(ln) then
continue;
ParseKanjiDicLine(ln, @ed);
end;
end;
procedure TKanjidicTests.KanjidicLoad;
var Kanjidic: TKanjidic;
begin
Kanjidic := TKanjidic.Create;
Kanjidic.LoadFromFile(CommonDataDir+'\kanjidic');
FreeAndNil(Kanjidic);
end;
const
KANJIDIC_ITER_CNT: integer = 20;
procedure TKanjidicSpeedTests.SetUp;
begin
FReader := TKanjidicTests.Create('');
end;
procedure TKanjidicSpeedTests.TearDown;
begin
FreeAndNil(FReader);
end;
procedure TKanjidicSpeedTests.KanjidicReadTime;
var i: integer;
tm: cardinal;
begin
tm := GetTickCount;
for i := 0 to KANJIDIC_ITER_CNT-1 do
FReader.KanjidicRead();
tm := GetTickCount-tm;
Status('x'+IntToStr(KANJIDIC_ITER_CNT)+' = '+IntToStr(tm)+' ticks.');
end;
procedure TKanjidicSpeedTests.KanjidicLoadTime;
var i: integer;
tm: cardinal;
begin
tm := GetTickCount;
for i := 0 to KANJIDIC_ITER_CNT-1 do
FReader.KanjidicLoad();
tm := GetTickCount-tm;
Status('x'+IntToStr(KANJIDIC_ITER_CNT)+' = '+IntToStr(tm)+' ticks.');
end;
initialization
RegisterTest(TNamedTestSuite.Create('Kanjidic', TKanjiDicTests));
RegisterSpeedTest(TNamedTestSuite.Create('Kanjidic', TKanjidicSpeedTests));
end. |
unit uFrmCatalogSyncData;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParent, siComp, StdCtrls, ExtCtrls, ComCtrls, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
DBClient, ADODB, Provider;
type
TFrmCatalogSyncData = class(TFrmParent)
Panel2: TPanel;
btnClose: TButton;
pgOption: TPageControl;
tsVendor: TTabSheet;
cdsListVendor: TClientDataSet;
dsListVendor: TDataSource;
cdsListVendorIDVendorMR: TIntegerField;
cdsListVendorIDVendor: TIntegerField;
cdsListVendorVendor: TStringField;
grdCatalogVendor: TcxGrid;
grdCatalogVendorDBTableView: TcxGridDBTableView;
grdCatalogVendorLevel: TcxGridLevel;
grdCatalogVendorDBTableViewIDVendorMR: TcxGridDBColumn;
grdCatalogVendorDBTableViewVendor: TcxGridDBColumn;
btnApply: TButton;
grdCatalogVendorDBTableViewIDVendor: TcxGridDBColumn;
procedure btnCloseClick(Sender: TObject);
procedure dsListVendorDataChange(Sender: TObject; Field: TField);
procedure btnApplyClick(Sender: TObject);
private
procedure OpenVendor;
procedure CloseVendor;
procedure RefreshVendor;
procedure PostVendor;
public
function Start : Boolean;
end;
implementation
uses uDMImportExport;
{$R *.dfm}
{ TFrmCatalogSyncData }
function TFrmCatalogSyncData.Start: Boolean;
begin
DMImportExport.ImportConn.Connected := True;
DMImportExport.OpenVendor;
RefreshVendor;
ShowModal;
end;
procedure TFrmCatalogSyncData.btnCloseClick(Sender: TObject);
begin
inherited;
DMImportExport.CloseVendor;
CloseVendor;
Close;
end;
procedure TFrmCatalogSyncData.CloseVendor;
begin
with cdsListVendor do
if Active then
Close;
end;
procedure TFrmCatalogSyncData.OpenVendor;
begin
with cdsListVendor do
if not Active then
Open;
end;
procedure TFrmCatalogSyncData.RefreshVendor;
begin
CloseVendor;
OpenVendor;
end;
procedure TFrmCatalogSyncData.dsListVendorDataChange(Sender: TObject;
Field: TField);
begin
inherited;
btnApply.Enabled := True;
end;
procedure TFrmCatalogSyncData.btnApplyClick(Sender: TObject);
begin
inherited;
if pgOption.ActivePage = tsVendor then
PostVendor;
btnApply.Enabled := False;
end;
procedure TFrmCatalogSyncData.PostVendor;
begin
with cdsListVendor do
if Active then
if (ChangeCount > 0) then
ApplyUpdates(-1);
end;
end.
|
{=====================================================================================
Copyright (C) combit GmbH
--------------------------------------------------------------------------------------
Module : DOM List & Label sample
Descr. : D: Dieses Beispiel demonstriert die dynamische Erzeugung von List & Label
Projekten
US: This example shows the dynamic creation of List & Label projects
======================================================================================}
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Registry, DB, ADODB, L28dom, cmbtll28, LlReport_Types,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error,
FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool,
FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MSAcc, FireDAC.Phys.MSAccDef,
FireDAC.VCLUI.Wait, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, ListLabel28, StrUtils
{$if CompilerVersion >= 28} // XE7
, System.UITypes
{$ENDIF}
;
type
TfrmMain = class(TForm)
btnDesign: TButton;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
BtnPreview: TButton;
CmBxTables: TComboBox;
Label5: TLabel;
LstBxAvFields: TListBox;
LstBxSelFields: TListBox;
Label6: TLabel;
Label7: TLabel;
BtnSelect: TButton;
BtnUnSelect: TButton;
Label8: TLabel;
Label9: TLabel;
dtTitle: TEdit;
dtLogo: TEdit;
btnLogo: TButton;
OpenDialog1: TOpenDialog;
LL: TListLabel28;
FDConnectionNorthwind: TFDConnection;
DataSource1: TDataSource;
FDTable: TFDTable;
procedure FormCreate(Sender: TObject);
procedure CmBxTablesClick(Sender: TObject);
procedure BtnSelectClick(Sender: TObject);
procedure BtnUnSelectClick(Sender: TObject);
procedure btnDesignClick(Sender: TObject);
procedure LstBxAvFieldsDblClick(Sender: TObject);
procedure LstBxSelFieldsDblClick(Sender: TObject);
procedure btnLogoClick(Sender: TObject);
procedure BtnPreviewClick(Sender: TObject);
private
workingPath: String;
TableName: TString;
procedure GetTableFields();
function GenerateLLProject(): integer;
procedure SelectFields();
procedure UnSelectFields();
procedure ChangeTableName(ComboBox: TComboBox);
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
lldomproj: TLlDomProjectList;
implementation
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
Var NWindDatabasePath: String;
Registry: TRegistry;
Error: Boolean;
ErrorMessage: String;
begin
Error := False;
ErrorMessage := 'Unable to find sample database. Make sure List & Label is installed correctly.';
Registry := TRegistry.Create(KEY_READ);
if (Registry.OpenKeyReadOnly('Software\combit\cmbtll')) then
begin
NWindDatabasePath := Registry.ReadString('NWINDPath');
if (FileExists(NWindDatabasePath)) then
begin
try
FDConnectionNorthwind.Connected := False;
FDConnectionNorthwind.Params.Database := NWindDatabasePath;
FDConnectionNorthwind.Connected := True;
Except
on Ecx: Exception do
begin
Error := True;
ErrorMessage := 'Unable to find sample database. Make sure List & Label is installed correctly.' + #13#10#13#10 + Ecx.ClassName + ' error raised, with message: ' + Ecx.Message;
end;
end;
end
else
begin
Error := True;
end;
Registry.CloseKey;
end
else
begin
Error := True;
end;
Registry.Free;
if (Error) then
begin
MessageBox(self.Handle, PWideChar(ErrorMessage), 'List & Label', MB_OK);
end;
//D: Combobox mit Tabellennamen aus der Datasource füllen.
//US:Fill the combobox with table names from the data source
FDConnectionNorthwind.GetTableNames('', '', '',CmBxTables.Items, [osMy, osOther], [tkTable]);
ChangeTableName(CmBxTables);
CmBxTables.ItemIndex := 0;
GetTableFields();
//D: Pfad zum Logo für das Layout
//US: Path for the logo for the layout
dtLogo.Text := workingPath + 'sunshine.gif';
end;
procedure TfrmMain.ChangeTableName(ComboBox: TComboBox);
var
i: integer;
TableNameWithOutBrackets: string;
begin
for i := 0 to ComboBox.Items.Count - 1 do
//D: Entfernen der Klammern im Tabellennamen
//US: Removing the brackets in the table name
if AnsiStartsStr('[', ComboBox.Items[i]) then
begin
TableNameWithOutBrackets:= AnsiMidStr(ComboBox.Items[i],Pos('[', ComboBox.Items[i])+1, Pos(']', ComboBox.Items[i])-2) ;
ComboBox.Items[i] := TableNameWithOutBrackets;
break;
end;
end;
procedure TfrmMain.CmBxTablesClick(Sender: TObject);
begin
LstBxAvFields.Clear();
LstBxSelFields.Clear();
GetTableFields();
end;
procedure TfrmMain.GetTableFields;
begin
FDConnectionNorthwind.GetFieldNames('', '', CmBxTables.Items[CmBxTables.ItemIndex],'', LstBxAvFields.Items);
end;
procedure TfrmMain.BtnPreviewClick(Sender: TObject);
var
nRet: integer;
ErrorBuffer: Array [0 .. 255] of char;
ErrorText: TString;
begin
//D: Tabelle für das Layout festlegen
//US: Determine table for the layout
TableName := CmBxTables.Items[CmBxTables.ItemIndex];
FDTable.Active := false;
FDTable.TableName:= TableName;
FDTable.Active := true;
DataSource1.DataSet:= FDTable;
DataSource1.Enabled:= true;
//D: Eintellungen für die List & Label Komponente setzen
//US: Define properties for the List & Label control
LL.DataController.DataSource:= DataSource1;
with LL.DataController.DetailSources.Add do
begin
Name:= TableName;
DataSource:= DataSource1;
end;
LL.AutoProjectFile := workingPath + 'dynamic.lst';
LL.AutoShowSelectFile := false;
//D: List & Label Projekt anhand Einstellungen erstellen
//US: Create List & Label project based on the settings
nRet := GenerateLLProject();
if nRet <> 0 then
begin
LlGetErrortext(nRet, ErrorBuffer, SizeOf(ErrorBuffer));
ErrorText := IntToStr(nRet) + ' (' + StrPas(ErrorBuffer) + ' )';
MessageDlg(ErrorText, mtInformation, [mbOK], 0);
end
else
//D: Designer aufrufen
//US: Call the designer
LL.AutoDestination := TLlPrintMode.pmPreview;
LL.AutoShowPrintOptions := false;
LL.Print();
LL.DataController.DetailSources.Clear;
end;
procedure TfrmMain.BtnSelectClick(Sender: TObject);
begin
SelectFields();
end;
procedure TfrmMain.BtnUnSelectClick(Sender: TObject);
begin
UnSelectFields();
end;
procedure TfrmMain.btnDesignClick(Sender: TObject);
var
nRet: integer;
ErrorBuffer: Array [0 .. 255] of char;
ErrorText: TString;
begin
//D: Tabelle für das Layout festlegen
//US: Determine table for the layout
TableName := CmBxTables.Items[CmBxTables.ItemIndex];
FDTable.Active := false;
FDTable.TableName := TableName;
FDTable.Active := true;
DataSource1.DataSet:= FDTable;
DataSource1.Enabled:= true;
//D: Eintellungen für die List & Label Komponente setzen
//US: Define properties for the List & Label control
LL.DataController.DataSource:= DataSource1;
with LL.DataController.DetailSources.Add do
begin
Name:= TableName;
DataSource:= DataSource1;
end;
LL.AutoProjectFile := workingPath + 'dynamic.lst';
LL.AutoShowSelectFile := false;
//D: List & Label Projekt anhand Einstellungen erstellen
//US: Create List & Label project based on the settings
nRet := GenerateLLProject();
if nRet <> 0 then
begin
LlGetErrortext(nRet, ErrorBuffer, SizeOf(ErrorBuffer));
ErrorText := IntToStr(nRet) + ' (' + StrPas(ErrorBuffer) + ' )';
MessageDlg(ErrorText, mtInformation, [mbOK], 0);
end
else
//D: Designer aufrufen
//US: Call the designer
LL.Design();
LL.DataController.DetailSources.Clear;
end;
//D: Hinweis: Beim Verwenden der List & Label DOM Klassen ist zu beachten, dass
// die einzelnen Eigenschafts-Werte als Zeichenkette angegeben werden müssen.
// Dies ist notwendig um ein Höchstmaß an Flexibilität zu gewährleisten, da
// somit auch List & Label Formeln erlaubt sind.
//US: Hint: When using List & Label DOM classes please note that the property
// values have to be passed as strings. This is necessary to ensure a maximum
// of flexibility - this way, List & Label formulas can be used as property
// values.
function TfrmMain.GenerateLLProject: integer;
var
llobjText: TLlDOMObjectText;
llobjParagraph: TLlDOMParagraph;
llobjDrawing: TLlDOMObjectDrawing;
container: TLlDOMObjectReportContainer;
table: TLlDOMSubItemTable;
tableLineData: TLlDOMTableLineData;
tableLineHeader: TLlDOMTableLineHeader;
header, tableField: TLlDOMTableFieldText;
i, Height, Width: integer;
fieldWidth: string;
begin
TableName:= StringReplace(TableName, ' ', '_', [rfReplaceAll, rfIgnoreCase]);
//D: Das DOM Objekt an ein List & Label Objekt binden
//US: Bind the DOM object to a List & Label object
lldomproj := TLlDomProjectList.Create(LL);
//D: Ein neues Listen Projekt mit dem Namen 'dynamic.lst' erstellen
//US: Create a new list project called 'dynamic.lst'
result := lldomproj.Open(workingPath + 'dynamic.lst', fmCreate, amReadWrite);
if result <> 0 then
exit;
//D: Eine neue Projektbeschreibung zuweisen
//US: Assign new project description
lldomproj.ProjectParameterList.ItemName['LL.ProjectDescription'].Contents := 'Dynamically Created Project';
//D: Ein leeres Text Objekt erstellen
//US: Create an empty text object
llobjText := TLlDOMObjectText.Create(lldomproj.ObjectList);
//D: Auslesen der Seitenkoordinaten der ersten Seite
//US: Get the coordinates for the first page
Height := StrToInt(lldomproj.Regions[0].Paper.Extent.Vertical);
Width := StrToInt(lldomproj.Regions[0].Paper.Extent.Horizontal);
//D: Setzen von Eigenschaften für das Textobjekt
//US: Set some properties for the text object
llobjText.Position.Define(10000, 10000, Width-65000, 27000);
//D: Hinzufügen eines Paragraphen und Setzen diverser Eigenschaften
//US: Add a paragraph to the text object and set some properties
llobjParagraph := TLlDOMParagraph.Create(llobjText.Paragraphs);
llobjParagraph.Contents := '"' + dtTitle.Text + '"';
llobjParagraph.Font.Bold := 'True';
//D: Hinzufügen eines Grafikobjekts
//US: Add a drawing object
llobjDrawing := TLlDOMObjectDrawing.Create(lldomproj.ObjectList);
llobjDrawing.Source.Fileinfo.Filename := dtLogo.Text;
llobjDrawing.Position.Define(Width - 50000, 10000, Width - (Width - 40000), 27000);
//D: Hinzufügen eines Berichtscontainers und setzen diverser Eigenschaften
//US: Add a report container and set some properties
container := TLlDOMObjectReportContainer.Create(lldomproj.ObjectList);
container.Position.Define(10000, 40000, Width - 20000, Height - 44000);
//D: In dem Berichtscontainer eine Tabelle hinzufügen
//US: Add a table into the report container
table := TLlDOMSubItemTable.Create(container.SubItems);
table.TableID := TableName;
//D: Zebramuster für Tabelle definieren
//US: Define zebra pattern for table
table.LineOptions.Data.ZebraPattern.Style := '1';
table.LineOptions.Data.ZebraPattern.Pattern := '1';
table.LineOptions.Data.ZebraPattern.Color := 'RGB(225,225,225)';
//D: Eine neue Datenzeile hinzufügen mit allen ausgewählten Feldern
//US: Add a new data line including all selected fields
tableLineData := TLlDOMTableLineData.Create(table.Lines.Data);
tableLineHeader := TLlDOMTableLineHeader.Create(table.Lines.Header);
for i := 0 to LstBxSelFields.Items.Count - 1 do
begin
fieldWidth := Format('%f', [StrToInt(container.Position.Width) / LstBxSelFields.Items.Count]);
//D: Kopfzeile definieren
//US: Define head line
header := TLlDOMTableFieldText.Create(tableLineHeader.Fields);
header.Contents := '"' + LstBxSelFields.Items[i] + '"';
header.Filling.Style := '1';
header.Filling.Color := 'RGB(255,153,51)';
header.Font.Bold := 'True';
header.Width := fieldWidth;
//D: Datenzeile definieren
//US: Define data line
tableField := TLlDOMTableFieldText.Create(tableLineData.Fields);
tableField.Contents := TableName + '.' + LstBxSelFields.Items[i];
tableField.Width := fieldWidth;
end;
//D: Projekt Liste als Datei speichern
//US: Save projectlist to file
lldomproj.Save(workingPath + 'dynamic.lst');
//D: Projekt Liste schliessen
//US: Close project list
lldomproj.Close();
lldomproj.Free;
end;
procedure TfrmMain.LstBxAvFieldsDblClick(Sender: TObject);
begin
SelectFields();
end;
procedure TfrmMain.SelectFields;
var
i: integer;
begin
for i := 0 to LstBxAvFields.Items.Count - 1 do
if LstBxAvFields.Selected[i] then
LstBxSelFields.Items.Add(LstBxAvFields.Items[i]);
LstBxAvFields.DeleteSelected;
end;
procedure TfrmMain.UnSelectFields;
var
i: integer;
begin
for i := 0 to LstBxSelFields.Items.Count - 1 do
if LstBxSelFields.Selected[i] then
LstBxAvFields.Items.Add(LstBxSelFields.Items[i]);
LstBxSelFields.DeleteSelected;
end;
procedure TfrmMain.LstBxSelFieldsDblClick(Sender: TObject);
begin
UnSelectFields();
end;
procedure TfrmMain.btnLogoClick(Sender: TObject);
begin
OpenDialog1.InitialDir := ExtractFilePath(Application.ExeName);
if OpenDialog1.Execute then
dtLogo.Text := OpenDialog1.FileName;
end;
end.
|
namespace MetalExample;
interface
uses
rtl,
Foundation,
RemObjects.Elements.RTL;
type
Asset = public class
public
// Loads the Content from aFilename as String
class method loadFile(const aFilename : String) : String;
class method loadFileBytes(const aFilename : String) : Array of Byte;
class method getFullname(const aFilename : String) : String; inline;
class method getUrlfor(const aFilename : String) : Foundation.URL;
end;
implementation
class method Asset.getFullname(const aFilename: String): String;
begin
exit Path.Combine(Bundle.mainBundle.resourcePath, aFilename);
end;
class method Asset.loadFile(const aFilename: String): String;
begin
var lname := getFullname(aFilename);
if lname.FileExists then
exit File.ReadText(lname) else exit nil;
end;
class method Asset.loadFileBytes(const aFilename: String): Array of Byte;
begin
var lname := getFullname(aFilename);
if lname.FileExists then
exit File.ReadBytes(lname) else exit nil;
end;
class method Asset.getUrlfor(const aFilename: String): Foundation.Url;
begin
exit Foundation.URL.fileURLWithPath(getFullname(aFilename));
end;
end. |
unit Kunden;
interface
uses System.SysUtils, System.Variants,
System.Classes, System.Generics.Collections, Sortiment, Hilfsfunktionen;
const
GRENZE_BARGELD = 0.9;
type
TWarenkorb = class
private
FArtikelListe: TList<TArtikel>;
function getArtikelWert(): double;
function getArtikelAnzahl(): integer;
public
constructor create();
property ArtikelListe: TList<TArtikel> read FArtikelListe
write FArtikelListe;
property ArtikelAnzahl: integer read getArtikelAnzahl;
property Wert: double read getArtikelWert;
procedure ArtikelHinzufuegen(Artikel: TArtikel);
// procedure ArtikelEntfernen;
end;
TKunde = class
private
FAlter : integer;
FKundenstatus : TKundenStatus;
FTimerAussetzenCounter: integer;
FBargeld : double;
FSortiment : TSortiment;
FWarenkorb : TWarenkorb;
FDauerAufenthalt : integer;
FDauerWarteschlange : integer;
function WarteschlangenBeurteilen(Warteschlangen
: TList<TWarteschlangenVolumen>): TList<TWarteschlangenVolumen>;
public
constructor create(Alter: integer; Bargeld: double; Sortiment: TSortiment);
property Alter: integer read FAlter write FAlter;
property Kundenstatus: TKundenStatus read FKundenstatus write FKundenstatus;
property TimerAussetzenCounter: integer read FTimerAussetzenCounter
write FTimerAussetzenCounter;
property Bargeld: double read FBargeld write FBargeld;
property Sortiment: TSortiment read FSortiment write FSortiment;
property Warenkorb: TWarenkorb read FWarenkorb write FWarenkorb;
property DauerAufenthalt: integer read FDauerAufenthalt
write FDauerAufenthalt;
property DauerWarteschlange: integer read FDauerWarteschlange
write FDauerWarteschlange;
procedure ArtikelEinpacken();
procedure TimerEvent();
procedure ArtikelEntfernen();
function WarteschlangeWaehlen(Warteschlangen
: TList<TWarteschlangenVolumen>): integer;
function Bezahlen(Betrag: double;
KleingeldParameter: TKleingeldParameter): boolean;
end;
TKundenVerwalter = class
private
FKundenVerwalterStatus : TKundenVerwalterStatus;
FKundenListe : TList<TKunde>;
FKundenFrequenz : integer;
FKundenKapazitaet : integer;
FFlashmobQuote : integer;
FFlashmobTimer : integer;
FSortiment : TSortiment;
FMinAlter : integer;
FMaxAlter : integer;
FMinBargeld : integer;
FMaxBargeld : integer;
FEntfernteKunden : double;
FKuerzesteWartezeit : double;
FLaengsteWartezeit : double;
FWartezeitGesamt : double;
FAufenthaltGesamt : double;
FMaxWartezeitDurchschnitt : double;
FMaxWartezeitStundenDurchschnitt: double;
FWartezeitenNachStunden : TList<double>;
FWartezeitenAktuelleStunde : TList<double>;
FTimerCounter : integer;
procedure AufenthaltMessen();
procedure KassierteKundenEntfernen();
procedure MaxWartezeitDurchschnittAktualisieren();
procedure FlashMobStarten();
procedure FlashMob();
procedure WartezeitenErfassen();
procedure WartezeitenStundenMittelErfassen();
procedure TimerHochsetzen();
function getKundenAnzahl(): integer;
function getEinpackendeKunden(): integer;
function getWartendeKunden(): integer;
function getWartezeitDurchschnitt(): double;
function getAufenthaltDurchschnitt(): double;
function getWartezeitDurchschnittString: string;
public
constructor create(Parameter: TKundenParameter; Sortiment: TSortiment);
property Kundenverwalterstatus: TKundenVerwalterStatus
read FKundenVerwalterStatus write FKundenVerwalterStatus;
property KundenListe: TList<TKunde> read FKundenListe write FKundenListe;
property KundenFrequenz: integer read FKundenFrequenz write FKundenFrequenz;
property KundenKapazitaet: integer read FKundenKapazitaet
write FKundenKapazitaet;
property FlashmobQuote: integer read FFlashmobQuote write FFlashmobQuote;
property FlashMobTimer: integer read FFlashmobTimer write FFlashmobTimer;
property KundenAnzahl: integer read getKundenAnzahl;
property KundenBeimEinpacken: integer read getEinpackendeKunden;
property KundenBeimWarten: integer read getWartendeKunden;
property Sortiment: TSortiment read FSortiment write FSortiment;
property MinAlter: integer read FMinAlter write FMinAlter;
property MaxAlter: integer read FMaxAlter write FMaxAlter;
property MinBargeld: integer read FMinBargeld write FMinBargeld;
property MaxBargeld: integer read FMaxBargeld write FMaxBargeld;
property EntfernteKunden: double read FEntfernteKunden
write FEntfernteKunden;
property WartezeitGesamt: double read FWartezeitGesamt
write FWartezeitGesamt;
property AufenthaltGesamt: double read FAufenthaltGesamt
write FAufenthaltGesamt;
property LaengsteWartezeit: double read FLaengsteWartezeit
write FLaengsteWartezeit;
property KuerzesteWartezeit: double read FKuerzesteWartezeit
write FKuerzesteWartezeit;
property Wartezeitdurchschnitt: double read getWartezeitDurchschnitt;
property WartezeitdurchschnittString: string
read getWartezeitDurchschnittString;
property MaxWartezeitDurchschnitt: double read FMaxWartezeitDurchschnitt
write FMaxWartezeitDurchschnitt;
property MaxWartezeitStundenDurchschnitt: double
read FMaxWartezeitStundenDurchschnitt
write FMaxWartezeitStundenDurchschnitt;
property AufenthaltDurchschnitt: double read getAufenthaltDurchschnitt;
property WarteZeitenNachStunden: TList<double> read FWartezeitenNachStunden
write FWartezeitenNachStunden;
property WartezeitenAktuelleStunde: TList<double>
read FWartezeitenAktuelleStunde write FWartezeitenAktuelleStunde;
property TimerCounter: integer read FTimerCounter write FTimerCounter;
procedure KundeErstellen(); overload;
procedure KundeErstellen(Limit: integer); overload;
procedure TimerEvent(supermarktOffen: boolean);
end;
implementation
{ TWarenkorb }
procedure TWarenkorb.ArtikelHinzufuegen(Artikel: TArtikel);
begin
self.ArtikelListe.Add(Artikel);
end;
constructor TWarenkorb.create;
begin
self.ArtikelListe := TList<TArtikel>.create;
end;
function TWarenkorb.getArtikelAnzahl: integer;
begin
result := self.ArtikelListe.Count;
end;
function TWarenkorb.getArtikelWert: double;
var
Wert : double;
Artikel: integer;
begin
Wert := 0;
for Artikel := 0 to self.ArtikelListe.Count - 1 do
Wert := Wert + ArtikelListe[Artikel].Wert;
result := Wert;
end;
{ TKunde }
procedure TKunde.ArtikelEinpacken();
var
randomArtikelIndex: integer;
begin
randomArtikelIndex := Random(self.Sortiment.ArtikeAnzahl);
if ZufallsBoolean(60) then
begin
self.Warenkorb.ArtikelHinzufuegen(self.Sortiment.WarenListe
[randomArtikelIndex]);
if ZufallsBoolean(7) then
self.Warenkorb.ArtikelListe.Delete(self.Warenkorb.ArtikelAnzahl - 1);
end;
if self.Warenkorb.Wert > (self.Bargeld * GRENZE_BARGELD) then
begin
self.TimerAussetzenCounter := Zufallszahl(5, 15);
self.Kundenstatus := ksZurKasseGehen;
end
else if ZufallsBoolean(4) then
begin
self.TimerAussetzenCounter := Zufallszahl(5, 15);
self.Kundenstatus := ksZurKasseGehen;
end;
end;
procedure TKunde.ArtikelEntfernen;
begin
if self.Warenkorb.ArtikelAnzahl > 0 then
self.Warenkorb.ArtikelListe.Delete(0);
end;
function TKunde.Bezahlen(Betrag: double;
KleingeldParameter: TKleingeldParameter): boolean;
var
kleingeldQuote: integer;
kleinGeldModus: boolean;
begin
kleingeldQuote := Random(100);
kleinGeldModus := ((self.Alter > KleingeldParameter.AlterKleingeldquote) and
(kleingeldQuote < KleingeldParameter.KleingeldZahlerAlt));
if kleinGeldModus or (kleingeldQuote < KleingeldParameter.KleingeldZahlerRest)
then
result := false
else
result := self.Bargeld > Betrag;
end;
constructor TKunde.create(Alter: integer; Bargeld: double;
Sortiment: TSortiment);
begin
self.Alter := Alter;
self.Bargeld := Bargeld;
self.Warenkorb := TWarenkorb.create;
self.Sortiment := Sortiment;
self.Kundenstatus := ksArtikelEinpacken;
self.DauerAufenthalt := 0;
end;
procedure TKunde.TimerEvent;
begin
if self.TimerAussetzenCounter > 0 then
begin
self.TimerAussetzenCounter := self.TimerAussetzenCounter - 1;
Exit;
end;
if self.Kundenstatus = ksArtikelEinpacken then
self.ArtikelEinpacken;
if self.Kundenstatus = ksZurKasseGehen then
self.Kundenstatus := ksBereitZumZahlen;
end;
function TKunde.WarteschlangenBeurteilen(Warteschlangen
: TList<TWarteschlangenVolumen>): TList<TWarteschlangenVolumen>;
var
schaetzMultiplikator : double;
persoenlicherEindruck : TWarteschlangenVolumen;
persoenlicherEindruckListe: TList<TWarteschlangenVolumen>;
I : integer;
begin
schaetzMultiplikator := (100 - Random(20)) / 100;
persoenlicherEindruckListe := TList<TWarteschlangenVolumen>.create;
for I := 0 to Warteschlangen.Count - 1 do
begin
if Warteschlangen[I].SchlangeOffen then
begin
persoenlicherEindruck.ArtikelVolumen := Warteschlangen[I].ArtikelVolumen *
schaetzMultiplikator;
persoenlicherEindruck.SchlangenNummer := Warteschlangen[I]
.SchlangenNummer;
persoenlicherEindruck.SchlangeOffen := Warteschlangen[I].SchlangeOffen;
persoenlicherEindruckListe.Add(persoenlicherEindruck);
end;
end;
result := persoenlicherEindruckListe;
end;
function TKunde.WarteschlangeWaehlen(Warteschlangen
: TList<TWarteschlangenVolumen>): integer;
var
randomQuote : integer;
subjektiveEinschaetzung: TList<TWarteschlangenVolumen>;
begin
randomQuote := Random(100);
subjektiveEinschaetzung := self.WarteschlangenBeurteilen(Warteschlangen);
subjektiveEinschaetzung.Sort;
if subjektiveEinschaetzung.Count = 1 then
begin
result := subjektiveEinschaetzung[0].SchlangenNummer;
Exit;
end;
if subjektiveEinschaetzung[0].ArtikelVolumen <
(subjektiveEinschaetzung[1].ArtikelVolumen * 0.8) then
begin
result := subjektiveEinschaetzung[0].SchlangenNummer;
Exit;
end;
if randomQuote < 40 then
result := subjektiveEinschaetzung[1].SchlangenNummer
else
result := subjektiveEinschaetzung[0].SchlangenNummer;
subjektiveEinschaetzung.Free;
end;
{ TKundenVerwalter }
procedure TKundenVerwalter.AufenthaltMessen;
var
I: integer;
begin
try
if Assigned(self.KundenListe) then
begin
for I := 0 to self.KundenListe.Count - 1 do
begin
self.KundenListe[I].DauerAufenthalt := self.KundenListe[I]
.DauerAufenthalt + 1;
if self.KundenListe[I].Kundenstatus = ksInWarteschlange then
self.KundenListe[I].DauerWarteschlange := self.KundenListe[I]
.DauerWarteschlange + 1;
end;
end;
finally
end;
end;
constructor TKundenVerwalter.create(Parameter: TKundenParameter;
Sortiment: TSortiment);
begin
self.Kundenverwalterstatus := kvNormal;
self.KundenListe := TList<TKunde>.create;
self.WarteZeitenNachStunden := TList<double>.create;
self.WartezeitenAktuelleStunde := TList<double>.create;
self.KundenFrequenz := Parameter.KundenFrequenz;
self.KundenKapazitaet := Parameter.KundenKapazitaet;
self.FlashmobQuote := Parameter.FlashmobQuote;
self.MinAlter := Parameter.MinAlter;
self.MaxAlter := Parameter.MaxAlter;
self.MinBargeld := Parameter.MinBargeld;
self.MaxBargeld := Parameter.MaxBargeld;
self.Sortiment := Sortiment;
self.EntfernteKunden := 0;
self.WartezeitGesamt := 0;
self.LaengsteWartezeit := 0;
self.MaxWartezeitDurchschnitt := 0;
self.MaxWartezeitStundenDurchschnitt := 0;
self.TimerCounter := 0;
end;
procedure TKundenVerwalter.FlashMob;
begin
self.KundeErstellen(self.KundenFrequenz * Zufallszahl(3, 10));
self.FFlashmobTimer := self.FlashMobTimer - 1;
if self.FlashMobTimer = 0 then
self.Kundenverwalterstatus := kvNormal
end;
procedure TKundenVerwalter.FlashMobStarten;
begin
self.FlashMobTimer := Zufallszahl(5, 15);
self.Kundenverwalterstatus := kvFlashMob;
end;
function TKundenVerwalter.getAufenthaltDurchschnitt: double;
begin
if self.EntfernteKunden > 0 then
result := self.AufenthaltGesamt / self.EntfernteKunden
else
result := 0
end;
function TKundenVerwalter.getEinpackendeKunden: integer;
var
Kunden: integer;
I : integer;
begin
Kunden := 0;
for I := 0 to self.KundenAnzahl - 1 do
begin
if self.KundenListe[I].Kundenstatus = ksArtikelEinpacken then
Inc(Kunden);
end;
result := Kunden;
end;
function TKundenVerwalter.getKundenAnzahl: integer;
begin
result := self.KundenListe.Count;
end;
function TKundenVerwalter.getWartendeKunden: integer;
var
Kunden: integer;
I : integer;
begin
Kunden := 0;
for I := 0 to self.KundenAnzahl - 1 do
begin
if (self.KundenListe[I].Kundenstatus = ksInWarteschlange) or
(self.KundenListe[I].Kundenstatus = ksBereitZumZahlen) then
Inc(Kunden);
end;
result := Kunden;
end;
function TKundenVerwalter.getWartezeitDurchschnitt: double;
begin
if self.EntfernteKunden > 0 then
result := self.WartezeitGesamt / self.EntfernteKunden / 2
else
result := 0
end;
function TKundenVerwalter.getWartezeitDurchschnittString: string;
var
minuten : double;
sekunden : double;
minutenstring : string;
sekundenstring: string;
begin
minuten := trunc(self.Wartezeitdurchschnitt);
sekunden := trunc((trunc((self.Wartezeitdurchschnitt - minuten) * 100) /
100) * 60);
if minuten >= 10 then
minutenstring := minuten.ToString()
else
minutenstring := '0' + minuten.ToString();
if sekunden >= 10 then
sekundenstring := sekunden.ToString()
else
sekundenstring := '0' + sekunden.ToString();
result := minutenstring + ':' + sekundenstring + ' Minuten';
end;
procedure TKundenVerwalter.KassierteKundenEntfernen;
var
I: integer;
begin
if Assigned(self.KundenListe) then
try
I := self.KundenListe.Count - 1;
while I >= 0 do
begin
if self.KundenListe[I].Kundenstatus = ksZahlenFertig then
begin
if self.KuerzesteWartezeit > self.KundenListe[I].DauerWarteschlange
then
self.KuerzesteWartezeit := self.KundenListe[I].DauerWarteschlange;
if self.LaengsteWartezeit < self.KundenListe[I].DauerWarteschlange / 2
then
self.LaengsteWartezeit := self.KundenListe[I].DauerWarteschlange / 2;
self.EntfernteKunden := self.EntfernteKunden + 1;
self.WartezeitGesamt := self.WartezeitGesamt + self.KundenListe[I]
.DauerWarteschlange;
self.AufenthaltGesamt := self.AufenthaltGesamt + self.KundenListe[I]
.DauerAufenthalt;
self.KundenListe.Delete(I);
end;
dec(I);
end;
finally
end;
end;
procedure TKundenVerwalter.WartezeitenErfassen();
var
I: integer;
begin
if self.KundenListe.Count > 0 then
begin
for I := 0 to self.KundenListe.Count - 1 do
begin
if self.KundenListe[I].Kundenstatus = ksZahlenFertig then
self.WartezeitenAktuelleStunde.Add
(self.KundenListe[I].DauerWarteschlange.ToDouble)
end;
if self.TimerCounter = 59 then
self.WartezeitenStundenMittelErfassen;
end;
end;
procedure TKundenVerwalter.WartezeitenStundenMittelErfassen;
var
stundenGesamt: double;
stundenMittel: double;
I : integer;
begin
stundenGesamt := 0;
for I := 0 to self.WartezeitenAktuelleStunde.Count - 1 do
stundenGesamt := stundenGesamt + self.WartezeitenAktuelleStunde[I];
if self.WartezeitenAktuelleStunde.Count = 0 then
stundenMittel := 0
else
stundenMittel := stundenGesamt / self.WartezeitenAktuelleStunde.Count / 2;
self.WarteZeitenNachStunden.Add(stundenMittel);
self.WartezeitenAktuelleStunde.Clear;
if stundenMittel > self.MaxWartezeitStundenDurchschnitt then
self.MaxWartezeitStundenDurchschnitt := stundenMittel;
end;
procedure TKundenVerwalter.KundeErstellen();
var
Alter : integer;
Bargeld: integer;
I : integer;
begin
for I := 1 to self.KundenFrequenz - 1 do
begin
if (self.KundenListe.Count < self.KundenKapazitaet) and (ZufallsBoolean(60))
then
begin
Alter := Zufallszahl(self.MinAlter, self.MaxAlter);
Bargeld := Zufallszahl(self.MinBargeld, self.MaxBargeld);
self.KundenListe.Add(TKunde.create(Alter, Bargeld, self.Sortiment));
end;
end;
end;
procedure TKundenVerwalter.KundeErstellen(Limit: integer);
var
Alter : integer;
Bargeld: integer;
I : integer;
begin
for I := 1 to Limit - 1 do
begin
if (self.KundenListe.Count < self.KundenKapazitaet) and (ZufallsBoolean(60))
then
begin
Alter := Zufallszahl(self.MinAlter, self.MaxAlter);
Bargeld := Zufallszahl(self.MinBargeld, self.MaxBargeld);
self.KundenListe.Add(TKunde.create(Alter, Bargeld, self.Sortiment));
end;
end;
end;
procedure TKundenVerwalter.MaxWartezeitDurchschnittAktualisieren;
begin
if self.Wartezeitdurchschnitt > self.MaxWartezeitDurchschnitt then
self.MaxWartezeitDurchschnitt := self.Wartezeitdurchschnitt;
end;
procedure TKundenVerwalter.TimerEvent(supermarktOffen: boolean);
var
I: integer;
begin
if supermarktOffen then
case self.Kundenverwalterstatus of
kvNormal:
begin
self.KundeErstellen;
if ZufallsBoolean(self.FlashmobQuote, 1000) then
self.FlashMobStarten;
end;
kvFlashMob:
self.FlashMob;
end;
self.WartezeitenErfassen;
self.KassierteKundenEntfernen;
self.AufenthaltMessen;
self.MaxWartezeitDurchschnittAktualisieren;
for I := 0 to self.KundenListe.Count - 1 do
begin
self.KundenListe[I].TimerEvent;
end;
self.TimerHochsetzen;
end;
procedure TKundenVerwalter.TimerHochsetzen;
begin
if self.TimerCounter = 59 then
self.TimerCounter := 0
else
self.TimerCounter := self.TimerCounter + 1;
end;
end.
|
unit Pospolite.View.HTML.Document;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
...
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Pospolite.View.Basics, Pospolite.View.HTML.Parser,
Pospolite.View.HTML.Basics, Pospolite.View.Internet,
Pospolite.View.Drawing.Renderer, Pospolite.View.DOM.Document;
type
{ TPLHTMLDocument }
TPLHTMLDocument = class(TInterfacedObject, IPLHTMLDocument)
private
FBody: TPLHTMLObject;
FFile: TPLString;
FHead: TPLHTMLObject;
FIsLocal: TPLBool;
FRoot: TPLHTMLRootObject;
FMimeType: TPLString;
FIsLoading: TPLBool;
function GetContent: TPLString;
function GetMimeType: TPLString;
function GetTitle: TPLString;
procedure SetTitle(AValue: TPLString);
function GetRoot: TPLHTMLObject;
protected
procedure InternalLoad(ASource: TPLString);
procedure InternalLoadOther(AData: TPLString);
public
constructor Create;
destructor Destroy; override;
procedure LoadFromLocalFile(const AFileName: TPLString);
procedure LoadFromURL(const AFileName: TPLString);
procedure LoadFromString(const AText: TPLString);
procedure SaveToLocalFile(const AFileName: TPLString);
procedure Reload;
function IsLoaded: TPLBool; inline;
function querySelector(const AQuery: TPLString; AObject: TPLHTMLObject = nil): TPLHTMLObject; // if AObject = nil, then AObject = Root
function querySelectorAll(const AQuery: TPLString; AObject: TPLHTMLObject = nil): TPLHTMLObjects;
property Title: TPLString read GetTitle write SetTitle;
property Content: TPLString read GetContent;
property MimeType: TPLString read GetMimeType;
property Root: TPLHTMLObject read GetRoot;
property IsLoading: TPLBool read FIsLoading;
property Body: TPLHTMLObject read FBody;
property Head: TPLHTMLObject read FHead;
end;
implementation
{ TPLHTMLDocument }
function TPLHTMLDocument.GetContent: TPLString;
begin
if Assigned(FRoot) then Result := FRoot.ToHTML else Result := '';
end;
function TPLHTMLDocument.GetMimeType: TPLString;
begin
Result := FMimeType;
end;
function TPLHTMLDocument.GetTitle: TPLString;
var
obj: TPLHTMLObject;
begin
obj := querySelector('head > title > internal_text_object');
if Assigned(obj) then Result := obj.Text else Result := '';
end;
procedure TPLHTMLDocument.SetTitle(AValue: TPLString);
var
obj: TPLHTMLObject;
begin
obj := querySelector('head > title > internal_text_object');
if Assigned(obj) then obj.Text := AValue;
end;
function TPLHTMLDocument.GetRoot: TPLHTMLObject;
begin
Result := FRoot;
end;
const
HTML_ERROR_TEMPLATE: TPLString = '<html><head><title>%s</title></head><body><h1>%s</h1><pre>%s</pre></body></html>';
procedure TPLHTMLDocument.InternalLoad(ASource: TPLString);
var
p: TPLHTMLParser;
begin
if not IsLoaded then exit;
if Assigned(FRoot) then FreeAndNil(FRoot);
FRoot := TPLHTMLRootObject.Create(nil);
if not FMimeType.Exists('html') then begin
InternalLoadOther(ASource);
exit;
end;
p := TPLHTMLParser.Create;
try
try
p.Parse(ASource, FRoot);
if p.HasCriticalError then raise Exception.Create(p.Errors.AllInOneString);
except
on e: Exception do begin
FRoot.Children.Clear;
p.Parse(HTML_ERROR_TEMPLATE.Format(['Error', 'Error occured', e.Message]), FRoot);
end;
end;
FBody := querySelector('internal_root_object > html > body');
FHead := querySelector('internal_root_object > html > head');
finally
p.Free;
end;
end;
procedure TPLHTMLDocument.InternalLoadOther(AData: TPLString);
begin
// <> html napisać...
end;
constructor TPLHTMLDocument.Create;
begin
inherited Create;
FFile := '';
FMimeType := 'text/html';
FIsLocal := true;
FRoot := nil;
FIsLoading := false;
FBody := nil;
FHead := nil;
end;
destructor TPLHTMLDocument.Destroy;
begin
if Assigned(FRoot) then FRoot.Free;
inherited Destroy;
end;
procedure TPLHTMLDocument.LoadFromLocalFile(const AFileName: TPLString);
var
sl: TStringList;
t: TPLString;
begin
FIsLoading := true;
FIsLocal := true;
FFile := '';
FRoot := nil;
FBody := nil;
FHead := nil;
FMimeType := LocalMimeType(AFileName);
try
sl := TStringList.Create;
try
sl.LoadFromFile(AFileName);
t := sl.Text;
finally
sl.Free;
end;
except
t := '';
FMimeType := '';
exit;
end;
FFile := AFileName;
InternalLoad(t);
FIsLoading := false;
end;
procedure TPLHTMLDocument.LoadFromURL(const AFileName: TPLString);
var
oc: IPLHTTPClient;
t: TPLString;
begin
FIsLoading := true;
FIsLocal := false;
FFile := '';
FRoot := nil;
FBody := nil;
FHead := nil;
try
oc := OnlineClient;
t := oc.FileGetContents(AFileName);
FMimeType := oc.MimeType.ToLower;
if oc.ResponseStatusCode >= 300 then raise Exception.Create('');
except
t := '';
FMimeType := '';
exit;
end;
FFile := AFileName;
InternalLoad(t);
FIsLoading := false;
end;
procedure TPLHTMLDocument.LoadFromString(const AText: TPLString);
begin
FIsLoading := true;
FIsLocal := true;
FFile := '<string>';
FMimeType := 'text/html';
FRoot := nil;
FBody := nil;
FHead := nil;
InternalLoad(AText);
FIsLoading := false;
end;
procedure TPLHTMLDocument.SaveToLocalFile(const AFileName: TPLString);
var
sl: TStringList;
begin
if FIsLoading then exit;
sl := TStringList.Create;
try
sl.Text := FRoot.ToHTML;
sl.SaveToFile(AFileName);
finally
sl.Free;
end;
end;
procedure TPLHTMLDocument.Reload;
begin
if FFile.IsEmpty or (FFile = '<string>') then exit;
if FIsLocal then LoadFromLocalFile(FFile) else LoadFromURL(FFile);
end;
function TPLHTMLDocument.IsLoaded: TPLBool;
begin
Result := not FFile.IsEmpty and not FMimeType.IsEmpty;
end;
function TPLHTMLDocument.querySelector(const AQuery: TPLString;
AObject: TPLHTMLObject): TPLHTMLObject;
begin
if not Assigned(AObject) then AObject := FRoot;
Result := TPLHTMLDocumentQueries.querySelector(AQuery, AObject);
end;
function TPLHTMLDocument.querySelectorAll(const AQuery: TPLString;
AObject: TPLHTMLObject): TPLHTMLObjects;
begin
if not Assigned(AObject) then AObject := FRoot;
Result := TPLHTMLDocumentQueries.querySelectorAll(AQuery, AObject);
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Spec.MetaData;
interface
uses
System.Classes,
Spring.Collections,
JsonDataObjects,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Spec.Interfaces,
DPM.Core.Spec.Node;
type
TSpecMetaData = class(TSpecNode, ISpecMetaData)
private
FId : string;
FVersion : TPackageVersion;
FDescription : string;
FAuthors : string;
FProjectUrl : string;
FRepositoryUrl : string;
FRepositoryType : string;
FRepositoryBranch : string;
FRepositoryCommit : string;
FReleaseNotes : string;
FLicense : string;
FIcon : string;
FCopyright : string;
FTags : string;
FIsTrial : boolean;
FIsCommercial : boolean;
FReadme : string;
FUIFrameworkType : TDPMUIFrameworkType;
protected
function GetVersion : TPackageVersion;
function GetId : string;
function GetDescription : string;
function GetAuthors : string;
function GetProjectUrl : string;
function GetRepositoryUrl : string;
function GetRepositoryType : string;
function GetRepositoryBranch : string;
function GetRepositoryCommit : string;
function GetReleaseNotes : string;
function GetLicense : string;
function GetIcon : string;
function GetCopyright : string;
function GetTags : string;
function GetIsTrial : boolean;
function GetIsCommercial : boolean;
function GetReadMe : string;
function GetUIFrameworkType: TDPMUIFrameworkType;
procedure SetId(const value : string);
procedure SetDescription(const value : string);
procedure SetAuthors(const value : string);
procedure SetProjectUrl(const value : string);
procedure SetRepositoryUrl(const value : string);
procedure SetRepositoryType(const value : string);
procedure SetRepositoryBranch(const value : string);
procedure SetRepositoryCommit(const value : string);
procedure SetReleaseNotes(const value : string);
procedure SetLicense(const value : string);
procedure SetIcon(const value : string);
procedure SetCopyright(const value : string);
procedure SetTags(const value : string);
procedure SetIsTrial(const value : boolean);
procedure SetIsCommercial(const value : boolean);
procedure SetVersion(const value : TPackageVersion);
procedure SetReadMe(const value : string);
procedure SetUIFrameworkType(const value: TDPMUIFrameworkType);
function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override;
public
constructor Create(const logger : ILogger); override;
end;
implementation
uses
System.SysUtils,
DPM.Core.Packaging.IdValidator;
{ TSpecMetaData }
constructor TSpecMetaData.Create(const logger : ILogger);
begin
inherited Create(logger);
FVersion := TPackageVersion.Empty;
FUIFrameworkType := TDPMUIFrameworkType.None;
end;
function TSpecMetaData.GetAuthors : string;
begin
result := FAuthors;
end;
function TSpecMetaData.GetCopyright : string;
begin
result := FCopyright;
end;
function TSpecMetaData.GetDescription : string;
begin
result := FDescription;
end;
function TSpecMetaData.GetIcon : string;
begin
result := FIcon;
end;
function TSpecMetaData.GetId : string;
begin
result := FId;
end;
function TSpecMetaData.GetIsCommercial : boolean;
begin
result := FIsCommercial;
end;
function TSpecMetaData.GetIsTrial : boolean;
begin
result := FIsTrial;
end;
function TSpecMetaData.GetLicense : string;
begin
result := FLicense;
end;
function TSpecMetaData.GetProjectUrl : string;
begin
result := FProjectUrl;
end;
function TSpecMetaData.GetReadMe: string;
begin
result := FReadme;
end;
function TSpecMetaData.GetReleaseNotes: string;
begin
result := FReleaseNotes;
end;
function TSpecMetaData.GetRepositoryBranch: string;
begin
result := FRepositoryBranch;
end;
function TSpecMetaData.GetRepositoryCommit: string;
begin
result := FRepositoryCommit;
end;
function TSpecMetaData.GetRepositoryType: string;
begin
result := FRepositoryType;
end;
function TSpecMetaData.GetRepositoryUrl: string;
begin
result := FRepositoryUrl;
end;
function TSpecMetaData.GetTags : string;
begin
result := FTags;
end;
function TSpecMetaData.GetUIFrameworkType: TDPMUIFrameworkType;
begin
result := FUIFrameworkType;
end;
function TSpecMetaData.GetVersion : TPackageVersion;
begin
result := FVersion;
end;
function TSpecMetaData.LoadFromJson(const jsonObject : TJsonObject) : Boolean;
var
sVersion : string;
sError : string;
sUI : string;
begin
result := true;
FId := jsonObject.S['id'];
if not TPackageIdValidator.IsValidPackageId(FId) then
begin
Logger.Error('Invalid package Id [' + FId + ']');
result := false;
end;
sVersion := jsonObject.S['version'];
if sVersion = '' then
begin
logger.Error('Required field [version] not found.');
result := false;
end;
if not TPackageVersion.TryParseWithError(sVersion, FVersion, sError) then
begin
logger.Error('Invalid Package Version : ' + sError);
result := false;
end;
FDescription := jsonObject.S['description'];
if FDescription = '' then
begin
logger.Error('Required field [description] not found.');
result := false;
end;
FAuthors := jsonObject.S['authors'];
if FAuthors = '' then
begin
logger.Error('Required field [authors] not found.');
result := false;
end;
FProjectUrl := jsonObject.S['projectUrl'];
FRepositoryUrl := jsonObject.S['repositoryUrl'];
FRepositoryType := jsonObject.S['repositoryType'];
FRepositoryBranch := jsonObject.S['repositoryBranch'];
FRepositoryCommit := jsonObject.S['repositoryCommit'];
FReleaseNotes := jsonObject.S['releaseNotes'];
FLicense := jsonObject.S['license'];
FIcon := jsonObject.S['icon'];
FCopyright := jsonObject.S['copyright'];
FReadme := jsonObject.S['readme'];
FTags := jsonObject.S['tags'];
FIsTrial := jsonObject.B['isTrial'];
FIsCommercial := jsonObject.B['isCommercial'];
sUI := jsonObject.S['uiFramework'];
if sUI <> '' then
FUIFrameworkType := StringToUIFrameworkType(sUI);
end;
procedure TSpecMetaData.SetAuthors(const value : string);
begin
FAuthors := value;
end;
procedure TSpecMetaData.SetCopyright(const value : string);
begin
FCopyright := value;
end;
procedure TSpecMetaData.SetDescription(const value : string);
begin
FDescription := value;
end;
procedure TSpecMetaData.SetIcon(const value : string);
begin
FIcon := value;
end;
procedure TSpecMetaData.SetId(const value : string);
begin
FId := value;
end;
procedure TSpecMetaData.SetIsCommercial(const value : boolean);
begin
FIsCommercial := value;
end;
procedure TSpecMetaData.SetIsTrial(const value : boolean);
begin
FIsTrial := value;
end;
procedure TSpecMetaData.SetLicense(const value : string);
begin
FLicense := value;
end;
procedure TSpecMetaData.SetProjectUrl(const value : string);
begin
FProjectUrl := value;
end;
procedure TSpecMetaData.SetReadMe(const value: string);
begin
FReadme := value;
end;
procedure TSpecMetaData.SetReleaseNotes(const value: string);
begin
FReleaseNotes := value;
end;
procedure TSpecMetaData.SetRepositoryBranch(const value: string);
begin
FRepositoryBranch := value;
end;
procedure TSpecMetaData.SetRepositoryCommit(const value: string);
begin
FRepositoryCommit := value;
end;
procedure TSpecMetaData.SetRepositoryType(const value: string);
begin
FRepositoryType := value;
end;
procedure TSpecMetaData.SetRepositoryUrl(const value: string);
begin
FRepositoryUrl := value;
end;
procedure TSpecMetaData.SetTags(const value : string);
begin
FTags := value;
end;
procedure TSpecMetaData.SetUIFrameworkType(const value: TDPMUIFrameworkType);
begin
FUIFrameworkType := value;
end;
procedure TSpecMetaData.SetVersion(const value : TPackageVersion);
begin
FVersion := value;
end;
end.
|
unit LrObserverList;
interface
uses
SysUtils, Classes;
type
TLrObserverList = class
private
FObservers: array of TNotifyEvent;
protected
function Find(inEvent: TNotifyEvent): Integer;
function GetCount: Integer;
procedure SetCount(const Value: Integer);
property Count: Integer read GetCount write SetCount;
public
procedure Add(inEvent: TNotifyEvent);
procedure Remove(inEvent: TNotifyEvent);
procedure Notify(inSender: TObject);
procedure NotifyExcept(inSender: TObject; inExcept: TObject);
end;
implementation
{ TLrObserverList }
function TLrObserverList.GetCount: Integer;
begin
Result := Length(FObservers);
end;
procedure TLrObserverList.SetCount(const Value: Integer);
begin
SetLength(FObservers, Value);
end;
procedure TLrObserverList.Add(inEvent: TNotifyEvent);
begin
if Find(inEvent) = -1 then
begin
Count := Count + 1;
FObservers[Count - 1] := inEvent;
end;
end;
function LrCompareMethods(const inMethod0, inMethod1: TMethod): Boolean;
begin
Result := CompareMem(@inMethod0, @inMethod1, SizeOf(TMethod));
end;
function TLrObserverList.Find(inEvent: TNotifyEvent): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to Pred(Count) do
begin
//if @FObservers[i] = @inEvent then
//if TMethod(FObservers[i]) = TMethod(inEvent) then
if LrCompareMethods(TMethod(FObservers[i]), TMethod(inEvent)) then
begin
Result := i;
break;
end;
end;
end;
procedure TLrObserverList.Remove(inEvent: TNotifyEvent);
var
i, j: Integer;
begin
i := Find(inEvent);
if (i >= 0) then
begin
for j := i to Pred(Pred(Count)) do
FObservers[j] := FObservers[j + 1];
Count := Count - 1;
end;
end;
procedure TLrObserverList.Notify(inSender: TObject);
var
i: Integer;
e: TNotifyEvent;
begin
for i := 0 to Pred(Count) do
begin
e := FObservers[i];
e(inSender);
end;
end;
procedure TLrObserverList.NotifyExcept(inSender, inExcept: TObject);
var
i: Integer;
e: TNotifyEvent;
begin
for i := 0 to Pred(Count) do
begin
e := FObservers[i];
if TMethod(e).Data <> inExcept then
e(inSender);
end;
end;
end.
|
{
@abstract(provides a component for importing from clipboard and text files)
@author(Aaron Hochwimer <aaron@graphic-edge.co.nz>)
@created(June 27, 2003)
@lastmod(June 29, 2003)
This unit provides the TGEImportFile component. This is a general
purpose importing module to import data from comma, tab, or space separated data
files or from the clipboard.
}
unit geImportFile;
// $Id: geImportFile.pas,v 1.3 2003/09/11 05:25:52 hochwimmera Exp $
interface
uses
Classes, Clipbrd, controls, db, Dialogs, Forms,
Registry,Sysutils, Windows, Variants,
// Third Party
{kbmMemTable,}
// local
frmImport;
const
{clipboard}
sCLIPBOARD = 'clipboard';
{comma separated value file}
sCSV = 'comma separated value ';
{fixed format value file - very similar to SSV}
sFFS = 'fixed format space';
{ignore this column}
sIGNORE = 'Ignore';
{import identifier}
sIMPORT = 'import';
{space separated value file}
sSSV = 'space separated value';
{tab separated value file}
sTSV = 'tab separated value';
type
{Enumeration type providing a list of import file types. Current types include:
ifCSV,ifTSV,ifSSV,ifFixedFormatSpace,ifClipboard}
TImportFileType = (ifCSV,ifTSV,ifSSV,ifFixedFormatSpace,ifClipboard);
{Component to handle importing. Simply connect it to a kbmMemTable - the
destination - called by the Execute method}
TGEImportFile = class(TComponent)
private
fAllDelimiters : boolean;
fAllowFields : TStringList;
fDefaultFileType : TImportFileType;
fDelimiter : string;
{fDestination : TkbmMemTable;}
fEFileName : string;
fFilePath : string;
fGroupDelimiters : boolean;
fHeaderSkip : integer;
fIdentifier : string;
fImporter : TformGEImporter;
fImportFileType : TImportFileType;
fOnAfterImport : TNotifyEvent;
fOnTypeChange : TNotifyEvent;
fReg : TRegIniFile;
fRegPath : string;
fTextFile : TextFile;
{strips a string of its delimiter(s), behaviour varies based on AllDelimiters}
procedure CheckStripDelimiter(var sValue:string);
{obtains the index of the last delimiter in sLine}
procedure GetMaxDelimiters(sLine:string;var id2:integer);
{generates a hint string based on the current ImportFileType}
function GetHint:string;
{get next valid item based on the separator sSEP}
function GetNextItem(sSEP:string;var Sepstring:string):string;
{returns the position of the last instance of Substr in S}
function LastPos(Substr,S: string): integer;
{loads the default ImportFileType from registry}
procedure LoadImportFileType;
{saves current settings such as header rows to skip and also the import file
type}
procedure SaveIdentifierSettings;
{sets the AllDelimiters property and stores in registry}
procedure SetAllDelimiters(bAllDelimiters:boolean);
{sets the current Delimiter string and stores in registry}
procedure SetDelimiter(sDelimiter:string);
{sets the last file path and stores in registry}
procedure SetFilePath(sFilePath:string);
{sets the GroupDelimiters property and stores in registry}
procedure SetGroupdelimiters(bGroupDelimiters:boolean);
{sets the HeaderSkip property and stores in registry}
procedure SetHeaderSkip(iHeaderSkip:integer);
{sets the Identifier property}
procedure SetIdentifier(sIdentifier:string);
{sets the ImportFileType}
procedure SetImportFileType(aFileType:TImportFileType);
{writes a string to the importer form grid}
procedure WriteTableLine(sSep:string;var sLine:string);
protected
{event handler run after a successful import}
procedure DoOnAfterImport;virtual;
{event handler run after an import type change}
procedure DoOnTypeChange;virtual;
{generates a stringlist of allowable fields based on the field definitions
of the destination dataset}
procedure GenerateAllowFields;
{loaded method - should check at some future date for valid published properties}
procedure Loaded;override;
{load the last file path from registry}
procedure LoadFilePath;
{load the headerskip property from registry}
procedure LoadHeaderSkip;
{save the current field selection and delimiter to registry}
procedure SaveRegistrySettings(fsl:TStringList);
{examines contents of clipboard for the column number}
procedure SetImportClipboard(importer:TformGEImporter;var bContinue:boolean;
var sl:TStringList;var clip:TStringList);
{examines the text file for the maximum number of columns. Prompts for
the file name}
procedure SetImportFile(importer:TformGEImporter;var bContinue:boolean;
var sl:TStringList);
public
{Class constructor. Creates Reg property for use in reading and writing to
and from the registry}
constructor Create(aOwner:TComponent);override;
{Class destructor. Cleans up}
destructor Destroy;override;
{Call execute to intitiate an import - returns true if successful}
function Execute:boolean;
{Imports data from clipboard}
procedure ImportDataFromClipboard(clip:TStringList);
{Imports data from text file}
function ImportDataFromFile(iHeader:integer;bPrompt:boolean):boolean;
{Load current settings from registry}
procedure LoadRegistrySettings(fsl:TStringList);
{If AllDelimiters is true importing will remove all instances of Delimiter from
the current line}
property AllDelimiters: boolean read fAllDelimiters write SetAllDelimiters;
{AllowFields is a stringlist detailing the available fields that may be
populated by the import procedure}
property AllowFields : TStringList read fAllowFields write fAllowFields;
{The current delimiter string. May be blank, single quote ('), or double quote (")}
property Delimiter : string read fDelimiter write SetDelimiter;
{Name of the last file that was imported}
property EFileName : string read fEFileName write fEFileName;
{The file path (including name) of the the last file that was imported}
property FilePath : string read fFilePath write SetFilePath;
{Number of header lines to skip in the importing procedure}
property HeaderSkip : integer read fHeaderSkip write SetHeaderSkip;
{Hint string - based on the current ImportFileType}
property Hint : string read GetHint;
{Current Identifier. This may be altered to store unique settings in the registry}
property Identifier : string read fIdentifier write SetIdentifier;
{Importer - a form for the user to set up the various import parameters. It also
provides a visual preview of the data}
property Importer : TformGEImporter read fImporter write fImporter;
{Text file variable use for file based importing}
property ImportTextFile : TextFile read fTextFile write fTextFile;
{Registry variable used for loading and saving settings}
property Reg:TRegIniFile read fReg write fReg;
published
{Default file type}
property DefaultFileType : TImportFileType read fDefaultFileType write
fDefaultFileType;
{Destination dataset - at present a TkbmMemTable but could be expanded in the
future}
{ property Destination : TkbmMemTable read fDestination write fDestination;}
{GroupDelimeters property will ignore separators (e.g. comma in CSV) if they
are within a matching pair of delimiters. Useful if you wish to import a string
containing a comma - e.g. "thats all she said, mate","no way"}
property GroupDelimiters : boolean read fGroupDelimiters write
SetGroupDelimiters;
{ImportFileType - either ifCSV,ifTSV,ifSSV,ifFixedFormatSpace,ifClipboard}
property ImportFileType : TImportFileType read fImportFileType write
SetImportFileType;
{Event handler called after a successful import procedure}
property OnAfterImport : TNotifyEvent read fOnAfterImport write fOnAfterImport;
{Event handler called after a type change}
property OnTypeChange : TNotifyEvent read fOnTypeChange write fOnTypeChange;
{Top level registry path}
property RegPath : string read fRegPath write fRegPath;
end;
procedure Register;
implementation
// ----- TGEImportFile.CheckStripDelimiter -------------------------------------
procedure TGEImportFile.CheckStripDelimiter(var sValue:string);
begin
if (Delimiter <> '') then
begin
if AllDelimiters then
sValue := StringReplace(sValue,Delimiter,'',[rfReplaceAll,rfIgnoreCase])
else
begin
// delete the matching pair around a string
if ((sValue[1]=Delimiter) and (sValue[Length(sValue)]=Delimiter)) then
begin
Delete(sValue,Length(sValue),1);
Delete(sValue,1,1);
end;
end;
end;
end;
// ----- TGEImportFile.GetMaxDelimiters ----------------------------------------
procedure TGEImportFile.GetMaxDelimiters(sLine:string;var id2:integer);
var
sCopy,sSep : string;
iPos : integer;
bContinue : boolean;
begin
bContinue := true;
sCopy := sLine;
if (ImportFileType = ifCSV) then
sSEP := ','
else if (ImportFileType = ifTSV) then
sSEP := #9
else if ( (ImportFileType = ifSSV) or
(ImportFileType = ifFixedFormatSpace)) then
sSEP := ' ';
id2 := 0;
while bContinue do
begin
iPos := Pos(sSEP,sCopy);
if (iPos > 0) then
begin
Inc(id2);
Delete(sCopy,1,iPos);
end else
begin
bContinue := false;
end;
end;
end;
// ----- TGEImportFile.GetHint -------------------------------------------------
function TGEImportFile.GetHint:string;
begin
if (ImportFileType = ifCSV) then
result := 'comma separated value file'
else if (ImportFileType = ifTSV) then
result := 'tab separated value file'
else if (ImportFileType = ifClipboard) then
result := 'clipboard'
else if (ImportFileType = ifSSV) then
result := 'space separated value file'
else if (ImportFileType = ifFixedFormatSpace) then
result := 'fixed format file (space separated value)'
else
result := '';
end;
// ----- TGEImportFile.GetNextItem ---------------------------------------------
function TGEImportFile.GetNextItem(sSEP:string;var SepString:string):string;
var
DelPos,SepPos: integer; // position of 2nd delimiter,separator string
sTest: string; // tempstring to locate DelPos
begin
// for the FixedFormat type start be trimming to left
if (ImportFileType = ifFixedFormatSpace) then
SepString := TrimLeft(SepString);
if (SepString <> '') then
begin
// now eval DelPos if required for delimiters like ".." and '..'
if (GroupDelimiters and (SepString[1]=Delimiter)) then
begin
// strip the first Delimiter using sTest
sTest := Copy(SepString,2,Length(SepString));
// locates second matching delimiter - add one for the missing first one
DelPos := Pos(Delimiter,sTest) + 1;
end else
DelPos := 0;
SepPos := Pos(sSEP,SepString);
if (SepPos > 0) then
begin
// matching delimiter code - i.e. grouping delimiters
if (DelPos > 0) then
begin
result := Copy(SepString,1,DelPos);
Delete(SepString,1,DelPos);
end else
begin
// normal instance
result := Copy(SepString,1,SepPos-1);
Delete(SepString,1,SepPos);
end;
end else
begin
// the last item in the string
result := SepString;
SepString := '';
end;
end else
result := '';
end;
// ----- TGEImportFile.LastPos -------------------------------------------------
function TGEImportFile.LastPos(Substr,S: string): integer;
var
Found: Boolean;
TempS: string;
StrPos, LastStrPos,NumRemoved,SubStrLength: integer;
begin
TempS:=S;
SubStrLength:=Length(Substr);
LastStrPos := 0;
StrPos:=0;
NumRemoved:=0;
Found:=True;
while Found do
begin
LastStrPos:=StrPos;
StrPos:=Pos(Substr,TempS);
if StrPos>0 then
begin
Delete(TempS,StrPos,SubStrLength);
Inc(NumRemoved);
end
else
Found:=False;
end;
if NumRemoved>0 then
Result:=LastStrPos+(NumRemoved-1)*SubStrLength
else
Result:=0;
end;
// ----- TGEImportFile.LoadImportFileType --------------------------------------
procedure TGEImportFile.LoadImportFileType;
var
stype:string;
begin
Reg.OpenKey(RegPath,true);
stype:=LowerCase(Reg.ReadString(sIMPORT,Identifier+'.DefaultFileType',''));
Reg.CloseKey;
if (stype = sCSV) then
ImportFileType := ifCSV
else if (stype = sTSV) then
ImportFileType := ifTSV
else if (stype = sCLIPBOARD) then
ImportFileType := ifClipBoard
else if (sType = sSSV) then
ImportFileType := ifSSV
else if (sType = sFFS) then
ImportFileType := ifFixedFormatSpace
else
ImportFileType := DefaultFileType;
end;
// ----- TGEImportFile.SaveIdentifierSettings ----------------------------------
procedure TGEImportFile.SaveIdentifierSettings;
begin
HeaderSkip := HeaderSkip;
ImportFileType := ImportFileType;
end;
// ----- TGEImportFile.SetAllDelimiters ----------------------------------------
procedure TGEImportFile.SetAllDelimiters(bAllDelimiters:boolean);
begin
if (fAllDelimiters <> bAllDelimiters) then
begin
fAllDelimiters := bAllDelimiters;
Reg.OpenKey(RegPath,true);
Reg.WriteBool(sIMPORT,Identifier+'.alldelimiters',fAllDelimiters);
Reg.CloseKey;
end;
end;
// ----- TGEImportFile.SetDelimiter --------------------------------------------
procedure TGEImportFile.SetDelimiter(sDelimiter:string);
begin
if (fDelimiter <> sDelimiter) then
begin
fDelimiter := sDelimiter;
Reg.OpenKey(RegPath,true);
Reg.WriteString(sIMPORT,Identifier+'.delimiter',fDelimiter);
Reg.CloseKey;
end;
end;
// ----- TGEImportFile.SetFilePath ---------------------------------------------
procedure TGEImportFile.SetFilePath(sFilePath:string);
begin
if (fFilePath <> sFilePath) then
begin
fFilePath := sFilePath;
Reg.OpenKey(RegPath,true);
Reg.WriteString(sIMPORT,Identifier+'.FilePath',sFilePath);
Reg.CloseKey;
end;
end;
// ----- TGEImportFile.SetGroupdelimiters --------------------------------------
procedure TGEImportFile.SetGroupdelimiters(bGroupDelimiters:boolean);
begin
if (fGroupDelimiters <> bGroupDelimiters) then
begin
fGroupDelimiters := bGroupDelimiters;
Reg.OpenKey(RegPath,true);
Reg.WriteBool(sIMPORT,Identifier+'.GroupDelimiters',bGroupDelimiters);
Reg.CloseKey;
end;
end;
// ----- TGEImportFile.SetHeaderSkip -------------------------------------------
procedure TGEImportFile.SetHeaderSkip(iHeaderSkip:integer);
begin
if (fHeaderSkip <> iHeaderSkip) then
begin
fHeaderSkip := iHeaderSkip;
Reg.OpenKey(RegPath,true);
Reg.WriteInteger(sIMPORT,Identifier+'.HeaderSkip',iHeaderSkip);
Reg.CloseKey;
end;
end;
// ----- TGEImportFile.SetIdentifier -------------------------------------------
procedure TGEImportFile.SetIdentifier(sIdentifier:string);
begin
fIdentifier := sIdentifier;
LoadImportFileType;
LoadHeaderSkip;
LoadFilePath;
end;
// ----- TGEImportFile.SetImportFileType ---------------------------------------
procedure TGEImportFile.SetImportFileType(aFileType:TImportFileType);
var
sType :string;
begin
fImportFileType := aFileType;
if (fImportFileType = ifCSV) then
sType := sCSV
else if (fImportFileType = ifTSV) then
sType := STSV
else if (fImportFileType = ifClipboard) then
sType := sCLIPBOARD
else if (fImportFileType = ifSSV) then
sType := sSSV
else if (fImportFileType = ifFixedFormatSpace) then
sTYpe := sFFS;
if (RegPath <> '') then
begin
Reg.OpenKey(RegPath,true);
Reg.WriteString(sIMPORT,Identifier+'.DefaultFileType',sType);
Reg.CloseKey;
end;
end;
// ----- TGEImportFile.WriteTableLine ------------------------------------------
procedure TGEImportFile.WriteTableLine(sSep:string;var sLine:string);
var
j:integer;
sFieldName:string;
begin
{
with Importer.kbmImport do
for j:=0 to FieldDefs.Count-1 do
begin
sFieldName := FieldDefs[j].Name;
FieldByName(sFieldName).AsString := GetNextItem(sSEP,sLine);
end;
}
end;
// ----- TGEImportFile.DoOnAfterImport -----------------------------------------
procedure TGEImportFile.DoOnAfterImport;
begin
if Assigned(fOnAfterImport) then
fOnAfterImport(self);
end;
// ----- TGEImportFile.DoOnTypeChange ------------------------------------------
procedure TGEImportFile.DoOnTypeChange;
begin
if Assigned(fOnTypeChange) then
fOnTypeChange(self);
end;
// ----- TGEImportFile.GenerateAllowFields -------------------------------------
procedure TGEImportFile.GenerateAllowFields;
var
i:integer;
sFieldName:string;
begin
AllowFields.Clear;
{
with Destination do
begin
if (FieldCount > 0) then
begin
for i:=0 to FieldCount-1 do
begin
sFieldName:=Fields[i].FieldName;
// only allow visible and writeable import columns
if ((Fields[i].ReadOnly=false) and (Fields[i].Visible=true)) then
AllowFields.Add(sFieldName);
end;
end;
end;
}
end;
// ----- TGEImportFile.Loaded --------------------------------------------------
procedure TGEImportFile.Loaded;
begin
inherited Loaded;
// additional checks for published properties are required
end;
// ----- TGEImportFile.LoadFilePath --------------------------------------------
procedure TGEImportFile.LoadFilePath;
begin
Reg.OpenKey(RegPath,true);
fFilePath := Reg.ReadString(sIMPORT,Identifier+'.FilePath',
ExtractFilePath(ParamStr(0)));
Reg.CloseKey;
end;
// ----- TGEImportFile.LoadHeaderSkip ------------------------------------------
procedure TGEImportFile.LoadHeaderSkip;
begin
Reg.OpenKey(RegPath,true);
fHeaderSkip := Reg.ReadInteger(sIMPORT,Identifier+'.HeaderSkip',0);
Reg.CloseKey;
end;
// ----- TGEImportFile.SaveRegistrySettings ------------------------------------
procedure TGEImportFile.SaveRegistrySettings(fsl:TStringList);
var
i:integer;
sRegEntry:string;
begin
sRegEntry := '';
for i:=0 to fsl.Count-1 do
begin
sRegEntry := sRegEntry+fsl.STrings[i];
if (i<fsl.Count-1) then
sRegEntry := sRegEntry + ',';
end;
Reg.OpenKey(RegPath,true);
Reg.WriteString(sIMPORT,Identifier+'.FieldSelection',sRegEntry);
Reg.WriteString(sIMPORT,Identifier+'.Delimiter',Delimiter);
Reg.CloseKey;
end;
// ----- TGEImportFile.SetImportClipboard --------------------------------------
procedure TGEImportFile.SetImportClipboard(importer:TformGEImporter;
var bContinue:boolean;var sl:TStringList;var clip:TStringList);
var
i,j,nEntries : integer;
sCaption,sItem,sLine : string;
begin
sCaption := 'Import From Clipboard';
try
clip.Text := ClipBoard.AsText;
except
end;
nEntries := 0;
// search for the biggest number of elements
for i:= 0 to clip.Count-1 do
begin
bContinue := true;
sLine := clip.Strings[i];
j:=0;
while bContinue do
begin
sItem := GetNextItem(#9,sLine);
if (sLine = '') then
begin
if (sItem <> '') then
Inc(j);
if (j>nEntries) then
nEntries := j;
bContinue := false;
end else
Inc(j);
end;
end;
if (clip.Count>0) then
begin
bContinue := true;
for i:=0 to nEntries-1 do
sl.Add('Item'+IntToStr(i));
Importer.Caption := sCaption;
Importer.sBarImport.Panels[1].Text := 'Clipboard';
end else
bContinue := false;
end;
// ----- TGEImportFile.SetImportFile -------------------------------------------
procedure TGEImportFile.SetImportFile(importer:TformGEImporter;var bContinue:boolean;
var sl:TStringList);
var
sBiggestLine,sCaption,sFileName,sItem,sLine : string;
id,id2:integer;
OpenFile : TOpenDialog;
begin
OpenFile := TOpenDialog.Create(nil);
with OpenFile do
begin
Filter := 'Comma Separated Value files (*.csv)|*.csv|'+
'Tab Separated Value files (*.tsv)|*.tsv|'+
'Space Separated Value files (*.txt)|*.txt|'+
'All files|*.*';
// set default file path, initial directory - check it out the validity first.
// Think the default Windows behaviour is to default to "My Documents"
// if the FileName and/or InitialDir haven't been set yet}
if FileExists(fFilePath) then
begin
FileName := fFilePath;
InitialDir := Copy(fFilePath,1,LastPos('/',fFilepath)-1);
// shouldn't happen but ...
end else if DirectoryExists(fFilePath) then
InitialDir := fFilePath;
// set captions, filter indices
if (ImportFileType = ifCSV) then
begin
Title := 'Open Comma Separated Value File';
sCaption := 'Import Comma Separated Value File';
FilterIndex := 1;
end else if (ImportFileType = ifTSV) then
begin
Title := 'Open Tab Separated Value File';
sCaption := 'Import Tab Separated Value File';
FilterIndex := 2;
end else if (ImportFileType = ifSSV) then
begin
Title := 'Open Space Separated Value File';
sCaption := 'Import Space Separated Value File';
FilterIndex := 3;
end else if (ImportFileType = ifFixedFormatSpace) then
begin
Title := 'Open Fixed Format (Space Separated) Value File';
sCaption := 'Import Fixed Format (Space Separated) Value File';
FilterIndex := 4;
end;
if Execute then
begin
sFileName := FileName;
// calculates the maximum size of the file
AssignFile(ImportTextFile,sFileName);
Reset(ImportTextFile);
id := 0;
while not eof(ImportTextFile) do
begin
ReadLn(ImportTextFile,sLine);
GetMaxDelimiters(sLine,id2);
if (id2 > id) then
begin
sBiggestLine := sLine;
id := id2;
end;
end;
Close(ImportTextFile);
bContinue:=true;
while (bContinue) do
begin
if (ImportFileType = ifCSV) then
sItem := GetNextItem(',',sBiggestLine)
else if (ImportFileType = ifTSV) then
sItem := GetNextItem(#9,sBiggestLine)
else if ( (ImportFileType = ifSSV) or
(ImportFileType = ifFixedFormatSpace)) then
sItem := GetNextItem(' ',sBiggestLine);
// don't add a blank value at the end
if (not bContinue) and (sItem = '') then
continue
else begin
if (sItem = '') then
begin
bContinue := false;
continue
end;
sl.Add(sItem);
end;
end;
Importer.Caption := sCaption;
Importer.sBarImport.Panels[1].Text := sFileName;
bContinue := true;
FilePath := FileName;
end else
bContinue := false;
end;
if bContinue then
eFileName := OpenFile.FileName;
OpenFile.Free;
end;
// ----- TGEImportFile.Create --------------------------------------------------
constructor TGEImportFile.Create(aOwner:TComponent);
begin
inherited Create(aOwner);
fReg := TRegIniFile.Create;
fAllowFields := TStringList.Create;
fDefaultFileType := ifCSV;
fIdentifier := 'Untitled';
fAllDelimiters := false;
fGroupDelimiters := false;
end;
// ----- TGEImportFile.Destroy -------------------------------------------------
{Class destructor.}
destructor TGEImportFile.Destroy;
begin
fReg.Free;
fAllowFields.Free;
inherited Destroy;
end;
// ----- TGEImportFile.Execute -------------------------------------------------
function TGEImportFile.Execute:boolean;
var
bEntryFailed,bContinue,bIgnoreAll,bSkipLine : boolean;
currentrecord,i,iIndex,j,k : integer;
sDateFormat,sFieldName,sValue : string;
thevalues : array of variant;
cols,clip,sl,temp : TStringList; // cols = not ignore columns
begin
(*
result := false;
sDateFormat := ShortDateFormat; //preserve this
sl := TStringList.Create;
importer := TformGEImporter.Create(self);
importer.bEditing := false;
// Step 1. Obtain the 'size' of the import data - i.e the number of columns
if (ImportFileType = ifClipboard) then
begin
clip := TStringList.Create;
SetImportClipboard(importer,bContinue,sl,clip);
if (not bContinue) then
clip.Free;
end else
// Importing a text file - CSV,TSV,SSV,Fixed Format
SetImportFile(importer,bContinue,sl);
// terminate if required
if (not bContinue) then
begin
sl.Free;
importer.Release;
exit;
end;
// terminate if there are no valid columns
if (sl.count = 0) then
begin
MessageDlg('Data file does not contain any columns in the specified format!',
mtInformation, [mbOK], 0);
sl.free;
importer.Release;
exit;
end;
// Step 2. - generate a list of assignable field names based on the structure
//of the destination memory table}
GenerateAllowFields;
LoadRegistrySettings(Importer.fsl);
// Step 3 - prepare the importing form
with Importer do
begin
allowsl.Clear;
allowsl.Assign(AllowFields);
SetupFieldDefs(sl); {** assigns fields to data}
SetHeaderSkip(HeaderSkip);
SetDelimiters(Delimiter,AllDelimiters,GroupDelimiters);
end;
// Step 4 - prepare additional importing information
if (ImportFileType = ifClipboard) then
begin
ImportDataFromClipboard(clip);
clip.Free;
end else
// file based - e.g. CSV,TSV,SSV,Fixed Format
ImportDataFromFile(0,false);
sl.Free;
// Step 5. Continue Importing until we are done!
bContinue := true;
while bContinue do
begin
with Importer do
begin
if (ShowModal = mrOK) then
begin
ShortDateFormat := ebDateFormat.Text; {** local date format}
result := true;
Screen.Cursor := crHourGlass;
SaveRegistrySettings(fsl);
SaveIdentifierSettings;
// prepare the destination - empty if required
with (Destination) do
begin
DisableControls;
Edit;
if cbxOverWrite.Checked then
EmptyTable;
Active := true;
Last;
currentrecord := RecNo+1; // have to remember to add one
end;
// prepare source table (in the importer)}
with kbmImport do
begin
Active := true;
First;
DisableControls;
end;
SetLength(thevalues,kbmImport.FieldCount);
//check to ensure we're not ignoring everything}
bIgnoreAll:=true;
CheckAllIgnore(bIgnoreAll,fsl);
if (not bIgnoreAll) then
begin
cols := TSTringList.Create;
{ store the non ignore column indices in cols}
for j:=0 to kbmImport.FieldCount-1 do
begin
if (fsl.Strings[j] = sIGNORE) then
thevalues[j] := sIGNORE
else
cols.Add(IntToStr(j));
end;
for i :=0 to kbmImport.RecordCount-1 do
begin
bSkipLine := false;
if (i < HeaderSkip) then
begin
kbmImport.Delete;
Continue;
end;
for k := 0 to cols.Count-1 do
begin
j := StrToInt(cols.Strings[k]);
// nil values
sValue := Trim(kbmImport.Fields[j].AsString);
if (sValue = '') then
thevalues[j] := null
else
// non-nil values
begin
CheckStripDelimiter(sValue);
thevalues[j] := sValue;
if (thevalues[j] = null) then
bSkipLine:=true;
if bSkipLine then
break;
end; {if sValue = ''}
end; {for k := 0 to cols.Count-1};
if bSkipLine then
begin
kbmImport.Next;
continue;
end;
// write to the destination - could be subroutined - pass "thevalues"
with Destination do
begin
Edit;
Append;
bEntryFailed := false;
// loop over desination fields
for j:=0 to FieldCount-1 do
begin
Edit;
sFieldName := Fields[j].FieldName;
iIndex := fsl.IndexOf(sFieldName);
if ((iIndex = -1) or (thevalues[iIndex] = null)) then
Fields[j].Clear
else
begin
if (Fields[j] is TFloatField) then
begin
try
Fields[j].AsFloat := thevalues[iIndex]
except
bEntryFailed := true;
end;
end else if (Fields[j] is TStringField) then
Fields[j].AsString := thevalues[iIndex]
else if ( (Fields[j] is TIntegerField) or
(Fields[j] is TSmallIntField) or
(Fields[j] is TWordField)) then
begin
try
Fields[j].AsInteger := thevalues[iIndex]
except
bEntryFailed := true;
end;
end else if ( (Fields[j] is TDateField) or
(Fields[j] is TDateTimeField)) then
begin
try
Fields[j].AsDateTime := StrToDateTime(thevalues[iIndex]);
except
bEntryFailed := true;
end;
end else if (Fields[j] is TMemoField) then
begin
// memo -> string conversion
temp := TStringList.Create;
temp.Add(thevalues[iIndex]);
Fields[j].Assign(temp);
temp.Free;
end;
end;
if bEntryFailed then
break;
end; {fieldcount}
if bEntryFailed then
begin
Cancel;
kbmImport.Next;
end else
begin
try
Post;
kbmImport.Delete;
except
Cancel;
kbmImport.Next;
end;
end;
end; // with Destination
end; // for i:=0 to kbmImport.RecordCount}
cols.Free;
kbmImport.EnableControls;
// jump to the start of the imported data
with Destination do
begin
MoveBy(currentrecord - RecNo);
EnableControls;
end;
// records left - failed the importing
if (kbmImport.RecordCount > 0) then
begin
Importer.Caption := 'Errors detected! Displaying rejected records.';
kbmImport.First;
end else
bContinue := false;
end else
bContinue := false;
end else
bContinue := false; //modal cancel
Screen.Cursor := crDefault;
end; // with Importer
end; // while bContinue
Importer.Release;
ShortDateFormat := sDateFormat;
DoOnAfterImport;
*)
end;
// ----- TGEImportFile.ImportDataFromClipboard ---------------------------------
procedure TGEImportFile.ImportDataFromClipboard(clip:TStringList);
const
sDELIMITER = #9;
var
i:integer;
sLine:string;
begin
importer.PrepImportTable;
for i := 0 to clip.Count-1 do
begin
sLine:= clip.Strings[i];
///importer.kbmImport.Append;
WriteTableLine(sDELIMITER,sLine);
///importer.kbmImport.Post;
end;
with importer do
begin
///kbmImport.First;
///kbmImport.EnableControls;
DisplayRecCount;
end;
end;
// ----- TGEImportFile.ImportDataFromFile --------------------------------------
function TGEImportFile.ImportDataFromFile(iHeader:integer;bPrompt:boolean):boolean;
const
sPROMPT = 'Replacing existing data by import?';
var
bCancelled: boolean;
sLine: string;
i: integer;
begin
(*
screen.Cursor := crHourGlass;
result := true;
{ control whether we want a prompt}
if bprompt then
bCancelled := (MessageDlg(sPROMPT,mtConfirmation,[mbOK,mbCancel],0) =mrCancel)
else
bCancelled := false;
if (not bCancelled) then
begin
AssignFile(ImportTextFile,eFileName);
Reset(ImportTextFile);
Importer.PrepImportTable;
{ skips these lines (useful if the file has a header)}
if (iheader > 0) then
for i:=0 to iheader-1 do
ReadLn(ImportTextFile,sLine);
{ now reads the file}
while not eof(ImportTextFile) do
begin
begin
ReadLn(ImportTextFile,sLine);
importer.kbmImport.Append;
if (ImportFileType = ifCSV) then
WriteTableLine(',',sLine)
else if (ImportFileType = ifTSV) then
WriteTableLine(#9,sLine)
else if (
(ImportFileType = ifSSV) or
(ImportFileType = ifFixedFormatSpace)) then
WriteTableLine(' ',sLine);
importer.kbmImport.Post;
end;
end;
with importer do
begin
kbmImport.First;
kbmImport.EnableControls;
DisplayRecCount;
end;
CloseFile(ImportTextFile);
end
else
result:=false;
Screen.Cursor:=crDefault;
*)
end;
// ----- TGEImportFile.LoadRegistrySettings ------------------------------------
procedure TGEImportFile.LoadRegistrySettings(fsl:TStringList);
const
iDELIMITER = 1;
sDELIMITER = ',';
var
s1,s2,sStored:string;
begin
fsl.Clear;
Reg.OpenKey(RegPath,true);
sStored :=Reg.ReadString(sIMPORT,Identifier+'.FieldSelection','');
fDelimiter := Reg.ReadString(sIMPORT,Identifier+'.Delimiter','');
fAllDelimiters := Reg.ReadBool(sIMPORT,Identifier+'.AllDelimiters',false);
fGroupDelimiters:=Reg.ReadBool(sIMPORT,Identifier+'.GroupDelimiters',false);
Reg.CloseKey;
// note the stored strings format: fieldname1,fieldname2,fieldname3,...
if (sStored <> '') then
begin
s1:=sStored;
while (s1 <> '') do
begin
if (Pos(sDelimiter,s1) > 0) then
begin
s2 := Copy(s1,1,Pos(sDelimiter,s1)-1);
s1 := Copy(s1,Pos(sDelimiter,s1)+iDELIMITER,Length(s1));
end else
begin
s2 := s1;
s1 := '';
end;
fsl.Add(s2);
end;
end;
end;
// ----- Register --------------------------------------------------------------
procedure Register;
begin
RegisterComponents('Graphic Edge IO',[TGEImportFile]);
end;
// =============================================================================
end.
|
unit PD_DSP_CT;
{===========================================================================
NAME: pd_dsp_ct.h
DESCRIPTION:
Definitions for PowerDAQ PCI Device Driver.
NOTES: This is DSP counter-timer register definitions
AUTHOR: Alex Ivchenko
DATE: 15-JAN-2001
HISTORY:
Rev 0.1, 15-JAN-01, A.I., Initial version.
NOTE: DSP counters are used in PowerDAQ asynchronous operations
PD2-AO uses counter-timer 2 for AOut
PD2-DIO uses counter-timer 1 for DIn and 2 for DOut
---------------------------------------------------------------------------
Copyright (C) 2001 United Electronic Industries, Inc.
All rights reserved.
United Electronic Industries Confidential Information.
===========================================================================
PD2-DIO UCT Support
General Information
PowerDAQ DIO board has three 24-bit counter/timers.
Also there is an additional 21-bit counter called prescaler which can be
used as a pre-divider or for the programmable cascading purposes.
Each counter can be clocked from the one of the three sources
· External TIOx pin (Note: That when external signal source attached
100-200 Ohm series resistor should be used to protect DSP TIOx pin)
· Internal DSP Clock/2 (33 MHz for the all PD2-DIO boards)
· Prescaler output
Please note: That each counter/timer has programmable polarity and can generate
interrupt on the any of the two events - compare and overflow.
Each timer has an associated compare register that is used in some modes to
generate PWM signal and to generate compare interrupt in all modes.
DSP Counters are count-up type counters.
Prescaler counter can use any of the four following sources (software selectable)
· Internal DSP Clock/2 (33 MHz for the all PD2-DIO boards)
· External TIO0/1/2 pin
Please refer to the Motorola DSP56301 User Manual for the details
(Motorola P/N DSP56301UM/AD)
PowerDAQ Implementation
DIO Interrupts are supported by revision 3 of the PowerDAQ driver that is in the
beta stage right now. Following algorithm should be used:
1) All timers should be programmed using the _PdDspRegWrite and _PdDSPRegRead
functions and proper ants. Note that using of the wrong addresses can
cause system problems.
2) Timer1 should not be used with DIn asynchronous operations and Timer2 with
DOut asynchronous operations.
3) UCT Interrupts should be enabled first by _PdSetUserEvents function, after
that using the _PdDspRegWrite function user should enable interrupt for the
selected counter (M_TOIE and M_TCIE bits in M_TCSRx). Note that because only one
bit is dedicated in the events word for the each UCT interrupt only one type of
the interrupt should be enabled at the time.
4) After host is interrupted because of the UCT interrupt it should be
re-enabled if necessary using the same algorithm.
5) Before program is closed each DSP Timer used should be reset using
the _PdDspRegWrite function (write zero to the corresponding TCSR).
6) The functions below are not supported and should NEVER used with DSP UCTs
PDUCTCFG
PDUCTSTATUS
PDUCTWRITE
PDUCTREAD
PDUCTSWGATE
PDUCTSWCLK
PDUCTRESET
}
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
const
{ Timer Prescaler Register Bit Flags }
M_PS = $600000; { Prescaler Source Mask}
M_PS0 = (1 SHL 21);
M_PS1 = (1 SHL 22);
{ Prescaler clock sources }
M_PS_CLK2 = 0; { Use internal clock / 2}
M_PS_TIO0 = (M_PS0); { Use timer IO 0}
M_PS_TIO1 = (M_PS1); { Use timer IO 1}
M_PS_TIO2 = (M_PS0 or M_PS1); { Use timer IO 2}
{ Register Addresses Of TIMER0 }
M_TCSR0 = $FFFF8; { TIMER0 Control/Status Register}
M_TLR0 = $FFFF8E; { TIMER0 Load Reg}
M_TCPR0 = $FFFF8D; { TIMER0 Compare Register}
M_TCR0 = $FFFF8C; { TIMER0 Count Register}
{ Register Addresses Of TIMER1 }
M_TCSR1 = $FFFF8B; { TIMER1 Control/Status Register}
M_TLR1 = $FFFF8A; { TIMER1 Load Reg}
M_TCPR1 = $FFFF89; { TIMER1 Compare Register}
M_TCR1 = $FFFF88; { TIMER1 Count Register}
{ Register Addresses Of TIMER2 }
M_TCSR2 = $FFFF87; { TIMER2 Control/Status Register}
M_TLR2 = $FFFF86; { TIMER2 Load Reg}
M_TCPR2 = $FFFF85; { TIMER2 Compare Register}
M_TCR2 = $FFFF84; { TIMER2 Count Register}
{ Prescaler Registers }
M_TPLR = $FFFF83; { TIMER Prescaler Load Register}
M_TPCR = $FFFF82; { TIMER Prescalar Count Register}
{ Timer Control/Status Register Bit Flags }
M_TE = (1 SHL 0); { Timer Enable}
M_TOIE = (1 SHL 1); { Timer Overflow Interrupt Enable}
M_TCIE = (1 SHL 2); { Timer Compare Interrupt Enable}
M_TC0 = (1 SHL 4); { Timer Control 0}
M_TC1 = (1 SHL 5); { Timer Control 1}
M_TC2 = (1 SHL 6); { Timer Control 2}
M_TC3 = (1 SHL 7); { Timer Control 3}
M_TC = $F0; { Timer Control Mask (TC0-TC3)}
M_INV = (1 SHL 8); { Inverter Bit}
M_TRM = (1 SHL 9); { Timer Restart Mode}
M_DIR = (1 SHL 11); { Direction Bit}
M_DI = (1 SHL 12); { Data Input}
M_DO = (1 SHL 13); { Data Output}
M_PCE = (1 SHL 15); { Prescaled Clock Enable}
M_TOF = (1 SHL 20); { Timer Overflow Flag}
M_TCF = (1 SHL 21); { Timer Compare Flag}
{ Timer Mode Masks }
DCT_Timer = $0;
DCT_TimerPulse = $10;
DCT_TimerToggle = $20;
DCT_EventCounter = $30;
DCT_InputWidth = $40;
DCT_InputPeriod = $50;
DCT_Capture = $60;
DCT_PWM = $70;
DCT_WatchdogPulse = $90;
DCT_WatchdogToggle = $A0;
{ DCT_Status bits }
DCTB_TE0 = (1 SHL 0); { Timer 0 Enable}
DCTB_TE1 = (1 SHL 1); { Timer 1 Enable}
DCTB_TE2 = (1 SHL 2); { Timer 2 Enable}
DCTB_TA0 = (1 SHL 3); { Timer 0 Available}
DCTB_TA1 = (1 SHL 4); { Timer 1 Available}
DCTB_TA2 = (1 SHL 5); { Timer 2 Available}
DCTB_FMODE = (1 SHL 6); { Frequency Mode On}
DCTB_FDONE = (1 SHL 7); { Frequency Measurement Done}
DCTB_TFME0 = (1 SHL 8); { Timer 0 Frequency Mode Enable}
DCTB_TFME1 = (1 SHL 9); { Timer 1 Frequency Mode Enable}
{ Counter IDs }
DCT_UCT0 = $0; { counter 0}
DCT_UCT1 = $1; { counter 1}
DCT_UCT2 = $2; { counter 2}
implementation
end.
|
{-----------------------------------------------------------------------------
Unit Name: frmEditor
Author: Kiriakos Vlahos
Date: 23-Feb-2005
Purpose:
History: Origianlly Based on SynEdit Demo
-----------------------------------------------------------------------------}
unit frmEditor;
{$I SynEdit.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Contnrs, Forms,
Menus, uEditAppIntfs, SynEdit, SynEditTypes, SynEditMiscProcs,
SynEditHighlighter, SynEditMiscClasses, SynEditSearch, SynEditRegexSearch,
SynEditKeyCmds, ImgList, Dialogs, ExtCtrls, JvExExtCtrls, JvComponent, JvPanel,
JvPageList, JvExControls, JvTabBar, TBX, TB2Item, uCommonFunctions,
SynCompletionProposal, cPyBaseDebugger, SynUnicode;
type
TEditor = class;
THotIdentInfo = record
HaveHotIdent : boolean;
IdentArea : TRect;
Ident : string;
DottedIdent : string;
StartCoord : TBufferCoord;
SynToken: string;
SynAttri: TSynHighlighterAttributes;
end;
TEditorForm = class(TForm)
imglGutterGlyphs: TImageList;
pmnuEditor: TTBXPopupMenu;
pmnuPageList: TTBXPopupMenu;
CloseTab: TTBXItem;
FGPanel: TPanel;
ViewsTabBar: TJvTabBar;
EditorViews: TJvPageList;
SourcePage: TJvStandardPage;
SynEdit: TSynEdit;
SynCodeCompletion: TSynCompletionProposal;
SynParamCompletion: TSynCompletionProposal;
procedure SynEditMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure SynParamCompletionExecute(Kind: SynCompletionType;
Sender: TObject; var CurrentInput: Widestring; var x, y: Integer;
var CanExecute: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure SynEditChange(Sender: TObject);
procedure SynEditEnter(Sender: TObject);
procedure SynEditExit(Sender: TObject);
procedure SynEditReplaceText(Sender: TObject; const ASearch,
AReplace: WideString; Line, Column: Integer;
var Action: TSynReplaceAction);
procedure SynEditStatusChange(Sender: TObject;
Changes: TSynStatusChanges);
procedure FormCreate(Sender: TObject);
procedure SynEditGutterClick(Sender: TObject; Button: TMouseButton;
X, Y, Line: Integer; Mark: TSynEditMark);
procedure SynEditSpecialLineColors(Sender: TObject; Line: Integer;
var Special: Boolean; var FG, BG: TColor);
procedure SynEditPaintTransient(Sender: TObject; Canvas: TCanvas;
TransientType: TTransientType);
procedure SynEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SynEditMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FGPanelEnter(Sender: TObject);
procedure FGPanelExit(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure CloseTabClick(Sender: TObject);
procedure ViewsTabBarTabSelected(Sender: TObject; Item: TJvTabBarItem);
procedure SynEditMouseCursor(Sender: TObject;
const aLineCharPos: TBufferCoord; var aCursor: TCursor);
procedure SynEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SynCodeCompletionExecute(Kind: SynCompletionType;
Sender: TObject; var CurrentInput: WideString; var x, y: Integer;
var CanExecute: Boolean);
procedure SynEditMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure SynEditMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
private
fEditor: TEditor;
fAutoCompleteActive : Boolean;
fHotIdentInfo : THotIdentInfo;
fHintIdentInfo : THotIdentInfo;
fNeedToCheckSyntax : Boolean;
fSyntaxErrorPos : TEditorPos;
fCloseBracketChar : WideChar;
function DoAskSaveChanges: boolean;
procedure DoAssignInterfacePointer(AActive: boolean);
function DoSave: boolean;
function DoSaveFile: boolean;
function DoSaveAs: boolean;
procedure DoUpdateCaption;
procedure DoUpdateHighlighter(HighlighterName : string = '');
procedure AutoCompleteBeforeExecute(Sender: TObject);
procedure AutoCompleteAfterExecute(Sender: TObject);
protected
procedure TBMThemeChange(var Message: TMessage); message TBM_THEMECHANGE;
procedure CodeHintEventHandler(Sender : TObject; AArea : TRect; var CodeHint : string);
procedure CodeHintLinkHandler(Sender: TObject; LinkName: string);
procedure EditorZoom(theZoom: Integer);
procedure EditorMouseWheel(theDirection: Integer; Shift: TShiftState );
public
BreakPoints : TObjectList;
HasFocus : Boolean;
DefaultExtension : string;
procedure DoActivate;
procedure DoActivateEditor;
function DoActivateView(ViewFactory : IEditorViewFactory) : IEditorView;
function GetEditor : IEditor;
procedure doProcessUserCommand(Sender: TObject; AfterProcessing: boolean;
var Handled: boolean; var Command: TSynEditorCommand;
var AChar: WideChar; Data: Pointer; HandlerData: pointer);
procedure PaintGutterGlyphs(ACanvas: TCanvas; AClip: TRect;
FirstLine, LastLine: integer);
procedure DoOnIdle;
procedure AddWatchAtCursor;
end;
TEditor = class(TInterfacedObject, IUnknown, IEditor, IEditCommands, IFileCommands,
ISearchCommands)
private
// IEditor implementation
procedure Activate;
function ActivateView(ViewFactory : IEditorViewFactory) : IEditorView;
function AskSaveChanges: boolean;
procedure Close;
function GetCaretPos: TPoint;
function GetSynEdit : TSynEdit;
function GetBreakPoints : TObjectList;
function GetEditorState: string;
function GetFileName: string;
function GetFileTitle: string;
function GetFileNameOrTitle: string;
function GetModified: boolean;
function GetFileEncoding : TSynEncoding;
procedure SetFileEncoding(FileEncoding : TSynEncoding);
function GetEncodedText : string;
procedure OpenFile(AFileName: string; HighlighterName : string = '');
function HasPythonFile : Boolean;
function GetForm : TForm;
// IEditCommands implementation
function CanCopy: boolean;
function CanCut: boolean;
function IEditCommands.CanDelete = CanCut;
function CanPaste: boolean;
function CanRedo: boolean;
function CanSelectAll: boolean;
function CanUndo: boolean;
procedure ExecCopy;
procedure ExecCut;
procedure ExecDelete;
procedure ExecPaste;
procedure ExecRedo;
procedure ExecSelectAll;
procedure ExecUndo;
// IFileCommands implementation
function CanClose: boolean;
function CanPrint: boolean;
function CanSave: boolean;
function CanSaveAs: boolean;
procedure ExecClose;
procedure ExecPrint;
procedure ExecPrintPreview;
procedure ExecSave;
procedure ExecSaveAs;
// ISearchCommands implementation
function CanFind: boolean;
function CanFindNext: boolean;
function ISearchCommands.CanFindPrev = CanFindNext;
function CanReplace: boolean;
procedure ExecFind;
procedure ExecFindNext;
procedure ExecFindPrev;
procedure ExecReplace;
private
fFileName: string;
fForm: TEditorForm;
fHasSelection: boolean;
fIsReadOnly: boolean;
fModified: boolean;
fUntitledNumber: integer;
TabBarItem : TJvTabBarItem;
fFileEncoding : TSynEncoding;
function IsEmpty : Boolean;
constructor Create(AForm: TEditorForm);
procedure DoSetFileName(AFileName: string);
end;
implementation
{$R *.DFM}
uses
frmPyIDEMain, dlgSynPrintPreview, frmCodeExplorer,
frmBreakPoints, Variants, dmCommands, JclFileUtils,
TBXThemes, StringResources, JclStrings, VarPyth, cRefactoring,
cPythonSourceScanner, cCodeHint, frmPythonII, dlgConfirmReplace, Math,
JvTypes, frmWatches, JclSysUtils, PythonEngine, frmMessages;
const
WM_DELETETHIS = WM_USER + 42;
resourcestring
SInsert = 'Insert';
SOverwrite = 'Overwrite';
SReadOnly = 'Read Only';
SNonameFileTitle = 'Untitled';
SNonamePythonFileTitle = 'Module';
SAskSaveChanges = 'The text in the "%s" file has changed.'#13#10#13#10 +
'Do you want to save the modifications?';
{ TGutterMarkDrawPlugin }
type
TDebugSupportPlugin = class(TSynEditPlugin)
protected
fForm: TEditorForm;
procedure AfterPaint(ACanvas: TCanvas; const AClip: TRect;
FirstLine, LastLine: integer); override;
procedure LinesInserted(FirstLine, Count: integer); override;
procedure LinesDeleted(FirstLine, Count: integer); override;
public
constructor Create(AForm: TEditorForm);
end;
constructor TDebugSupportPlugin.Create(AForm: TEditorForm);
begin
inherited Create(AForm.SynEdit);
fForm := AForm;
end;
Type
TUnderlineStyle = (usCorelWordPerfect, usMicrosoftWord);
procedure TDebugSupportPlugin.AfterPaint(ACanvas: TCanvas; const AClip: TRect;
FirstLine, LastLine: integer);
Var
TP : TPoint;
MaxX, LH : integer;
procedure PaintUnderLine;
Const
UnderlineStyle : TUnderlineStyle = usMicrosoftWord;
var
NewPoint,
NewY: Integer;
procedure DrawPoint;
begin
// Do not draw on gutter.
// This happens when a word is underlined and part of it is "hidden" under
// the gutter.
if TP.X <= Editor.Gutter.RealGutterWidth(Editor.CharWidth) then
Exit;
with ACanvas do begin
if NewY = TP.Y - 1 then
Pen.Color := fForm.SynEdit.Color
else
Pen.Color := clRed;
Pixels[TP.X, NewY] := Pen.Color;
end;
end;
const
// Microsoft Word style
// MW_POINTS: array[0..6] of ShortInt = (1, 2, 2, 1, 0, 0, 0);
MW_POINTS: array[0..3] of ShortInt = (0, 1, 2, 1);
// Corel Word Perfect style
// WP_POINTS: array[0..4] of ShortInt = (3, 2, 1, -1, -1);
WP_POINTS: array[0..3] of ShortInt = (2, 1, 0, -1);
begin
Inc(TP.Y, LH - 3);
NewPoint := 0;
if UnderlineStyle = usMicrosoftWord then
NewY := TP.Y + MW_POINTS[NewPoint]
else
NewY := TP.Y + WP_POINTS[NewPoint];
DrawPoint;
while TP.X <= MaxX do begin
DrawPoint;
Inc(NewPoint);
if UnderlineStyle = usMicrosoftWord then begin
if NewPoint > High(MW_POINTS) then
NewPoint := 0
end else begin
if NewPoint > High(WP_POINTS) then
NewPoint := 0;
end;
DrawPoint;
Inc(TP.X);
if UnderlineStyle = usMicrosoftWord then
NewY := TP.Y + MW_POINTS[NewPoint]
else
NewY := TP.Y + WP_POINTS[NewPoint];
end;
end;
begin
if CommandsDataModule.PyIDEOptions.CheckSyntaxAsYouType then
with fForm.fSyntaxErrorPos do
if IsSyntax and (Editor = fForm.GetEditor) and Math.InRange(Line, FirstLine, LastLine) then begin
LH := fForm.SynEdit.LineHeight;
TP := fForm.SynEdit.RowColumnToPixels(fForm.SynEdit.BufferToDisplayPos(
BufferCoord(1, Line)));
if TP.X <= ACanvas.ClipRect.Right - ACanvas.ClipRect.Left then begin
MaxX := fForm.SynEdit.RowColumnToPixels(fForm.SynEdit.BufferToDisplayPos(
BufferCoord(Char, Line))).X;
PaintUnderLine;
end;
end;
if fForm.SynEdit.Highlighter = CommandsDataModule.SynPythonSyn then
fForm.PaintGutterGlyphs(ACanvas, AClip, FirstLine, LastLine);
end;
procedure TDebugSupportPlugin.LinesInserted(FirstLine, Count: integer);
var
i: integer;
begin
with fForm do begin
for i := 0 to BreakPoints.Count - 1 do
if TBreakPoint(BreakPoints[i]).LineNo >= FirstLine then begin
TBreakPoint(BreakPoints[i]).LineNo :=
TBreakPoint(BreakPoints[i]).LineNo + Count;
PyIDEMainForm.PyDebugger.BreakPointsChanged := True;
BreakPointsWindow.UpdateWindow;
end;
end;
end;
procedure TDebugSupportPlugin.LinesDeleted(FirstLine, Count: integer);
var
i: integer;
begin
with fForm do begin
for i := BreakPoints.Count - 1 downto 0 do
if TBreakPoint(BreakPoints[i]).LineNo >= FirstLine + Count then begin
TBreakPoint(BreakPoints[i]).LineNo :=
TBreakPoint(BreakPoints[i]).LineNo - Count;
PyIDEMainForm.PyDebugger.BreakPointsChanged := True;
BreakPointsWindow.UpdateWindow;
end else if TBreakPoint(BreakPoints[i]).LineNo > FirstLine then begin
BreakPoints.Delete(i);
PyIDEMainForm.PyDebugger.BreakPointsChanged := True;
BreakPointsWindow.UpdateWindow;
end;
end;
end;
{ TEditor }
constructor TEditor.Create(AForm: TEditorForm);
begin
Assert(AForm <> nil);
inherited Create;
fForm := AForm;
fUntitledNumber := -1;
fFileEncoding := seAnsi;
end;
procedure TEditor.Activate;
begin
if fForm <> nil then
fForm.DoActivateEditor;
end;
function TEditor.ActivateView(ViewFactory : IEditorViewFactory) : IEditorView;
begin
if fForm <> nil then
Result := fForm.DoActivateView(ViewFactory);
end;
function TEditor.AskSaveChanges: boolean;
begin
if fForm <> nil then
Result := fForm.DoAskSaveChanges
else
Result := TRUE;
end;
procedure TEditor.Close;
// Closes without asking
Var
TabSheet : TJvStandardPage;
begin
if (fForm <> nil) then begin
if (fFileName <> '') and (CommandsDataModule <> nil) then
PyIDEMainForm.TBXMRUList.Add(fFileName);
if fUntitledNumber <> -1 then
CommandsDataModule.ReleaseUntitledNumber(fUntitledNumber);
if fForm.BreakPoints.Count > 0 then begin
PyIDEMainForm.PyDebugger.BreakPointsChanged := True;
BreakPointsWindow.UpdateWindow;
end;
TabSheet := (fForm.Parent as TJvStandardPage);
fForm.Close;
TabSheet.Free;
FreeAndNil(TabBarItem);
CodeExplorerWindow.UpdateWindow;
CommandsDataModule.UpdateChangeNotify;
end;
end;
procedure TEditor.DoSetFileName(AFileName: string);
begin
if AFileName <> fFileName then begin
fFileName := AFileName;
if fUntitledNumber <> -1 then begin
CommandsDataModule.ReleaseUntitledNumber(fUntitledNumber);
fUntitledNumber := -1;
end;
end;
end;
function TEditor.GetSynEdit: TSynEdit;
begin
Result := fForm.SynEdit;
end;
function TEditor.GetBreakPoints: TObjectList;
begin
Result := fForm.BreakPoints;
end;
function TEditor.GetCaretPos: TPoint;
begin
if fForm <> nil then
Result := TPoint(fForm.SynEdit.CaretXY)
else
Result := Point(-1, -1);
end;
function TEditor.GetEditorState: string;
begin
if fForm <> nil then begin
if fForm.SynEdit.ReadOnly then
Result := SReadOnly
else if fForm.SynEdit.InsertMode then
Result := SInsert
else
Result := SOverwrite;
end else
Result := '';
end;
function TEditor.GetEncodedText: string;
var
PyEncoding: string;
S: string;
UniPy, EncodeMethod, Args, EncodedString : PPyObject;
wStr : WideString;
SupressOutput : IInterface;
begin
case fFileEncoding of
seAnsi :
if HasPythonFile then begin
PyEncoding := '';
S := iff(fForm.SynEdit.Lines.Count > 0, fForm.SynEdit.Lines[0], '');
PyEncoding := ParsePySourceEncoding(S);
if PyEncoding = '' then begin
S := iff(fForm.SynEdit.Lines.Count > 1, fForm.SynEdit.Lines[1], '');
PyEncoding := ParsePySourceEncoding(S);
end;
if PyEncoding = 'utf-8' then
Result := UTF8BOMString + UTF8Encode(fForm.SynEdit.Text)
else with GetPythonEngine do begin
if PyEncoding = '' then
PyEncoding := SysModule.getdefaultencoding();
SupressOutput := PythonIIForm.OutputSupressor; // Do not show errors
wStr := fForm.SynEdit.Text;
UniPy := nil;
EncodeMethod := nil;
Args := nil;
EncodedString := nil;
try
try
UniPy := PyUnicode_FromWideChar(PWideChar(wStr), Length(wStr));
CheckError;
EncodeMethod := PyObject_GetAttrString(UniPy, 'encode');
CheckError;
Args := ArrayToPyTuple([PyEncoding, 'replace']);
EncodedString := PyEval_CallObject(EncodeMethod, Args);
CheckError;
Result := PyString_AsString(EncodedString);
CheckError;
finally
Py_XDECREF(UniPy);
Py_XDECREF(EncodeMethod);
Py_XDECREF(Args);
Py_XDECREF(EncodedString);
end;
except
Result := wStr;
end;
end;
end else
Result := fForm.SynEdit.Text;
seUTF8 : Result := UTF8BOMString + UTF8Encode(fForm.SynEdit.Text);
else // Should not happen
Raise Exception.Create('UTF-16 encoded files are not currently upported');
end;
end;
function TEditor.GetFileName: string;
begin
Result := fFileName;
end;
function TEditor.GetFileTitle: string;
begin
if fFileName <> '' then
Result := ExtractFileName(fFileName)
else begin
if fUntitledNumber = -1 then
fUntitledNumber := CommandsDataModule.GetUntitledNumber;
if fForm.SynEdit.Highlighter = CommandsDataModule.SynPythonSyn then
Result := SNonamePythonFileTitle + IntToStr(fUntitledNumber)
else
Result := SNonameFileTitle + IntToStr(fUntitledNumber);
end;
end;
function TEditor.GetFileNameOrTitle: string;
begin
if fFileName <> '' then
Result := fFileName
else
Result := GetFileTitle;
end;
function TEditor.GetModified: boolean;
begin
if fForm <> nil then
Result := fForm.SynEdit.Modified
else
Result := FALSE;
end;
function TEditor.GetFileEncoding: TSynEncoding;
begin
Result := fFileEncoding;
end;
procedure TEditor.SetFileEncoding(FileEncoding: TSynEncoding);
begin
fFileEncoding := FileEncoding;
end;
procedure TEditor.OpenFile(AFileName: string; HighlighterName : string = '');
Var
FileStream : TFileStream;
S, PyEncoding : string;
Len : integer;
V : Variant;
begin
DoSetFileName(AFileName);
if fForm <> nil then begin
if (AFileName <> '') and FileExists(AFileName) then begin
CommandsDataModule.JvChangeNotify.Active := False;
FileStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
fFileEncoding := GetEncoding(FileStream);
case fFileEncoding of
seAnsi :
// if it is a Pytyhon file detect an encoding spec
if CommandsDataModule.GetHighlighterForFile(AFileName) =
CommandsDataModule.SynPythonSyn then
begin
PyEncoding := '';
S := ReadLnFromStream(FileStream);
PyEncoding := ParsePySourceEncoding(S);
if PyEncoding = '' then begin
S := ReadLnFromStream(FileStream);
PyEncoding := ParsePySourceEncoding(S);
end;
FileStream.Seek(0, soFromBeginning);
if PyEncoding = 'utf-8' then begin
fFileEncoding := seUTF8;
LoadFromStream(fForm.SynEdit.Lines, FileStream, seUTF8);
end else if PyEncoding <> '' then begin
Len := FileStream.Size;
SetLength(S, Len);
FileStream.ReadBuffer(S[1], Len);
V := S;
V := VarPythonCreate(V);
try
fForm.SynEdit.Text := V.decode(PyEncoding, 'replace');
except
MessageDlg(Format('Error in decoding file "%s" from "%s" encoding',
[AFileName, PyEncoding]), mtWarning, [mbOK], 0);
fForm.SynEdit.Text := S;
end;
end else
fForm.SynEdit.Lines.LoadFromStream(FileStream);
end else
fForm.SynEdit.Lines.LoadFromStream(FileStream);
seUTF8 : LoadFromStream(fForm.SynEdit.Lines, FileStream, seUTF8);
else
Raise Exception.Create('UTF-16 encoded files are not currently upported');
end;
finally
FileStream.Free;
CommandsDataModule.UpdateChangeNotify;
end;
end else
fForm.SynEdit.Lines.Clear;
fForm.SynEdit.Modified := False;
fForm.DoUpdateHighlighter(HighlighterName);
fForm.DoUpdateCaption;
end;
end;
function TEditor.HasPythonFile: Boolean;
begin
Result := GetSynEdit.Highlighter = CommandsDataModule.SynPythonSyn;
end;
function TEditor.GetForm: TForm;
begin
Result := fForm;
end;
// IEditCommands implementation
function TEditor.CanCopy: boolean;
begin
Result := (fForm <> nil) and fHasSelection;
end;
function TEditor.CanCut: boolean;
begin
Result := (fForm <> nil) and fHasSelection and not fIsReadOnly;
end;
function TEditor.CanPaste: boolean;
begin
Result := (fForm <> nil) and fForm.SynEdit.CanPaste;
end;
function TEditor.CanRedo: boolean;
begin
Result := (fForm <> nil) and fForm.SynEdit.CanRedo;
end;
function TEditor.CanSelectAll: boolean;
begin
Result := fForm <> nil;
end;
function TEditor.CanUndo: boolean;
begin
Result := (fForm <> nil) and fForm.SynEdit.CanUndo;
end;
procedure TEditor.ExecCopy;
begin
if fForm <> nil then
fForm.SynEdit.CopyToClipboard;
end;
procedure TEditor.ExecCut;
begin
if fForm <> nil then
fForm.SynEdit.CutToClipboard;
end;
procedure TEditor.ExecDelete;
begin
if fForm <> nil then
fForm.SynEdit.SelText := '';
end;
procedure TEditor.ExecPaste;
begin
if fForm <> nil then
fForm.SynEdit.PasteFromClipboard;
end;
procedure TEditor.ExecRedo;
begin
if fForm <> nil then
fForm.SynEdit.Redo;
end;
procedure TEditor.ExecSelectAll;
begin
if fForm <> nil then
fForm.SynEdit.SelectAll;
end;
procedure TEditor.ExecUndo;
begin
if fForm <> nil then
fForm.SynEdit.Undo;
end;
// IFileCommands implementation
function TEditor.CanPrint: boolean;
begin
Result := True;
end;
function TEditor.CanSave: boolean;
begin
Result := (fForm <> nil) and (fModified or (fFileName = ''));
end;
function TEditor.CanSaveAs: boolean;
begin
Result := fForm <> nil;
end;
function TEditor.CanClose: boolean;
begin
Result := fForm <> nil;
end;
procedure TEditor.ExecClose;
// Close only after asking
begin
if AskSaveChanges then Close;
end;
procedure TEditor.ExecPrint;
begin
if fForm <> nil then with CommandsDataModule do
if PrintDialog.Execute then begin
SynEditPrint.SynEdit := fForm.SynEdit;
SynEditPrint.Title := GetFileTitle;
if PrintDialog.PrintRange = prAllPages then
SynEditPrint.Print
else
SynEditPrint.PrintRange(PrintDialog.FromPage, PrintDialog.ToPage);
end;
end;
procedure TEditor.ExecPrintPreview;
begin
CommandsDataModule.SynEditPrint.SynEdit := fForm.SynEdit;
CommandsDataModule.SynEditPrint.Title := GetFileTitle;
with TPrintPreviewDlg.Create(PyIDEMainForm) do begin
SynEditPrintPreview.SynEditPrint := CommandsDataModule.SynEditPrint;
ShowModal;
Release;
end;
end;
procedure TEditor.ExecSave;
begin
if fForm <> nil then begin
if fFileName <> '' then
fForm.DoSave
else
fForm.DoSaveAs
end;
end;
procedure TEditor.ExecSaveAs;
begin
if fForm <> nil then
fForm.DoSaveAs;
end;
// ISearchCommands implementation
function TEditor.CanFind: boolean;
begin
Result := (fForm <> nil) and not IsEmpty;
end;
function TEditor.CanFindNext: boolean;
begin
Result := (fForm <> nil) and not IsEmpty and
(CommandsDataModule.EditorSearchOptions.SearchText <> '');
end;
function TEditor.CanReplace: boolean;
begin
Result := (fForm <> nil) and not fIsReadOnly and not IsEmpty;
end;
procedure TEditor.ExecFind;
begin
if fForm <> nil then
CommandsDataModule.ShowSearchReplaceDialog(fForm.SynEdit, FALSE);
end;
procedure TEditor.ExecFindNext;
begin
if fForm <> nil then
CommandsDataModule.DoSearchReplaceText(fForm.SynEdit, FALSE, FALSE);
end;
procedure TEditor.ExecFindPrev;
begin
if fForm <> nil then
CommandsDataModule.DoSearchReplaceText(fForm.SynEdit, FALSE, TRUE);
end;
procedure TEditor.ExecReplace;
begin
if fForm <> nil then
CommandsDataModule.ShowSearchReplaceDialog(fForm.SynEdit, TRUE);
end;
function TEditor.IsEmpty: Boolean;
begin
Result := (fForm.SynEdit.Lines.Count = 0) or
((fForm.SynEdit.Lines.Count = 1) and (fForm.SynEdit.Lines[0] = ''));
end;
{ TEditorFactory }
type
TEditorFactory = class(TInterfacedObject, IEditorFactory)
private
// IEditorFactory implementation
function CanCloseAll: boolean;
procedure CloseAll;
function CreateTabSheet(AOwner: TJvPageList): IEditor;
function GetEditorCount: integer;
function GetEditorByName(Name : string): IEditor;
function GetEditorByNameOrTitle(Name : string): IEditor;
function GetEditor(Index: integer): IEditor;
procedure RemoveEditor(AEditor: IEditor);
procedure RegisterViewFactory(ViewFactory : IEditorViewFactory);
procedure SetupEditorViewMenu;
private
fEditors: TInterfaceList;
fEditorViewFactories : TInterfaceList;
constructor Create;
destructor Destroy; override;
procedure OnEditorViewClick(Sender : TObject);
end;
constructor TEditorFactory.Create;
begin
inherited Create;
fEditors := TInterfaceList.Create;
fEditorViewFactories := TInterfaceList.Create;
end;
destructor TEditorFactory.Destroy;
begin
fEditors.Free;
fEditorViewFactories.Free;
inherited Destroy;
end;
function TEditorFactory.CanCloseAll: boolean;
var
i: integer;
LEditor: IEditor;
begin
i := fEditors.Count - 1;
while i >= 0 do begin
LEditor := IEditor(fEditors[i]);
if not LEditor.AskSaveChanges then begin
Result := FALSE;
exit;
end;
Dec(i);
end;
Result := TRUE;
end;
procedure TEditorFactory.CloseAll;
var
i: integer;
begin
i := fEditors.Count - 1;
while i >= 0 do begin
IEditor(fEditors[i]).Close;
Dec(i);
end;
end;
function TEditorFactory.CreateTabSheet(AOwner: TJvPageList): IEditor;
var
Sheet: TJvStandardPage;
LForm: TEditorForm;
TabBarItem : TJvTabBarItem;
begin
Sheet := TJvStandardPage.Create(AOwner);
Sheet.ControlStyle := Sheet.ControlStyle + [csOpaque];
TabBarItem := PyIDEMainForm.TabBar.AddTab('');
TabBarItem.Selected := True;
TabBarItem.Data := Sheet;
try
Sheet.PageList := AOwner;
LForm := TEditorForm.Create(Sheet);
with LForm do begin
fEditor := TEditor.Create(LForm);
fEditor.TabBarItem := TabBarItem;
Result := fEditor;
BorderStyle := bsNone;
Parent := Sheet;
Align := alClient;
Visible := TRUE;
AOwner.ActivePage := Sheet;
LForm.SetFocus;
end;
// fix for Delphi 4 (???)
LForm.Realign;
if Result <> nil then
fEditors.Add(Result);
except
Sheet.Free;
end;
end;
function TEditorFactory.GetEditorCount: integer;
begin
Result := fEditors.Count;
end;
function TEditorFactory.GetEditorByName(Name: string): IEditor;
Var
i : integer;
begin
Result := nil;
for i := 0 to fEditors.Count - 1 do
if AnsiCompareText(IEditor(fEditors[i]).GetFileName,
GetLongFileName(ExpandFileName(Name))) = 0 then
begin
Result := IEditor(fEditors[i]);
break;
end;
end;
function TEditorFactory.GetEditorByNameOrTitle(Name: string): IEditor;
Var
i : integer;
begin
Result := GetEditorByName(Name);
if not Assigned(Result) then
for i := 0 to fEditors.Count - 1 do
if (IEditor(fEditors[i]).GetFileName = '') and
(CompareText(IEditor(fEditors[i]).GetFileTitle, Name) = 0) then begin
Result := IEditor(fEditors[i]);
break;
end;
end;
function TEditorFactory.GetEditor(Index: integer): IEditor;
begin
Result := IEditor(fEditors[Index]);
end;
procedure TEditorFactory.RemoveEditor(AEditor: IEditor);
var
i: integer;
begin
i := fEditors.IndexOf(AEditor);
if i > -1 then
fEditors.Delete(i);
end;
procedure TEditorFactory.RegisterViewFactory(ViewFactory: IEditorViewFactory);
begin
fEditorViewFactories.Add(ViewFactory);
end;
procedure TEditorFactory.OnEditorViewClick(Sender: TObject);
Var
ViewFactory: IEditorViewFactory;
EditorView : IEditorView;
Editor : IEditor;
Index : Integer;
begin
Editor := GI_ActiveEditor;
if not assigned(Editor) then Exit;
Index := (Sender as TTBXItem).Tag;
if (Index >= 0) and (Index < fEditorViewFactories.Count) then begin
ViewFactory := fEditorViewFactories[Index] as IEditorViewFactory;
EditorView := Editor.ActivateView(ViewFactory);
if Assigned(EditorView) then
EditorView.UpdateView(Editor);
end;
end;
procedure TEditorFactory.SetupEditorViewMenu;
Var
MenuItem : TTBXItem;
i : integer;
ViewFactory: IEditorViewFactory;
begin
fEditorViewFactories.Lock;
try
PyIdeMainForm.EditorViewsMenu.Enabled := fEditorViewFactories.Count > 0;
for i := 0 to fEditorViewFactories.Count - 1 do begin
ViewFactory := fEditorViewFactories[i] as IEditorViewFactory;
// Add MenuItem
MenuItem := TTBXItem.Create(PyIDEMainForm);
MenuItem.Hint := ViewFactory.Hint;
MenuItem.ImageIndex := ViewFactory.ImageIndex;
MenuItem.Caption := ViewFactory.MenuCaption;
MenuItem.ShortCut := ViewFactory.ShortCut;
MenuItem.OnClick := OnEditorViewClick;
MenuItem.Tag := i;
PyIdeMainForm.EditorViewsMenu.Add(MenuItem);
end;
finally
fEditorViewFactories.UnLock;
end;
end;
{ TEditorForm }
procedure TEditorForm.FormActivate(Sender: TObject);
begin
DoAssignInterfacePointer(TRUE);
end;
procedure TEditorForm.FormDeactivate(Sender: TObject);
begin
DoAssignInterfacePointer(FALSE);
end;
procedure TEditorForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
//PostMessage(Parent.Handle, WM_DELETETHIS, 0, 0);
Action := caNone;
end;
procedure TEditorForm.FormDestroy(Sender: TObject);
var
LEditor: IEditor;
begin
LEditor := fEditor;
Assert(fEditor <> nil);
fEditor.fForm := nil;
Assert(GI_EditorFactory <> nil);
GI_EditorFactory.RemoveEditor(LEditor);
Breakpoints.Free;
fSyntaxErrorPos.Free;
RemoveThemeNotification(Self);
end;
procedure TEditorForm.SynEditChange(Sender: TObject);
begin
CodeExplorerWindow.UpdateWindow;
with PyIDEMainForm.PyDebugger.ErrorPos do
if Editor = GetEditor then begin
Clear;
PyIDEMainForm.DebuggerErrorPosChange(Self);
end;
fSyntaxErrorPos.Clear;
fNeedToCheckSyntax := True;
end;
Var
fOldEditorForm : TEditorForm = nil;
procedure TEditorForm.SynEditEnter(Sender: TObject);
begin
DoAssignInterfacePointer(TRUE);
CommandsDataModule.ParameterCompletion.Editor := SynEdit;
CommandsDataModule.ModifierCompletion.Editor := SynEdit;
CommandsDataModule.CodeTemplatesCompletion.Editor := SynEdit;
CommandsDataModule.CodeTemplatesCompletion.OnBeforeExecute := AutoCompleteBeforeExecute;
CommandsDataModule.CodeTemplatesCompletion.OnAfterExecute := AutoCompleteAfterExecute;
fEditor.TabBarItem.Selected := True;
if fEditor.HasPythonFile then begin
CodeHint.OnGetCodeHint := CodeHintEventHandler;
CodeHint.OnHyperLinkClick := CodeHintLinkHandler;
end else begin
CodeHint.OnGetCodeHint := nil;
CodeHint.OnHyperLinkClick := nil;
end;
if fOldEditorForm <> Self then
CodeExplorerWindow.UpdateWindow;
fOldEditorForm := Self;
end;
procedure TEditorForm.SynEditExit(Sender: TObject);
begin
// The following create problems
// CommandsDataModule.ParameterCompletion.Editor := nil;
// CommandsDataModule.ModifierCompletion.Editor := nil;
// CommandsDataModule.CodeTemplatesCompletion.Editor := nil;
DoAssignInterfacePointer(FALSE);
CodeHint.CancelHint;
CodeHint.OnGetCodeHint := nil;
CodeHint.OnHyperLinkClick := nil;
end;
procedure TEditorForm.SynEditStatusChange(Sender: TObject;
Changes: TSynStatusChanges);
begin
Assert(fEditor <> nil);
if Changes * [scAll, scSelection] <> [] then
fEditor.fHasSelection := SynEdit.SelAvail;
if Changes * [scAll, scSelection] <> [] then
fEditor.fIsReadOnly := SynEdit.ReadOnly;
if Changes * [scAll, scModified] <> [] then
fEditor.fModified := SynEdit.Modified;
end;
procedure TEditorForm.DoActivate;
//var
// Sheet: TTabSheet;
// PCtrl: TPageList;
begin
if FormStyle = fsMDIChild then
BringToFront
else if Parent is TJvStandardPage then begin
// Sheet := Parent as TJvStandardPage;
// PCtrl := Sheet.PageList;
// if PCtrl <> nil then
// PCtrl.ActivePage := Sheet;
if not fEditor.TabBarItem.Selected then
fEditor.TabBarItem.Selected := True
else
// make sure TabBarTabSelected is called so that the focus
// goes to the form
PyIDEMainForm.TabBarTabSelected(Self, fEditor.TabBarItem);
end;
end;
procedure TEditorForm.DoActivateEditor;
begin
DoActivate;
ViewsTabBar.Tabs[0].Selected := True;
SynEdit.SetFocus;
end;
function TEditorForm.DoActivateView(ViewFactory : IEditorViewFactory) : IEditorView;
var
i : integer;
ViewTab : TJvStandardPage;
Form : TCustomForm;
begin
Result := nil;
DoActivate;
// Does the EditorView tab exist?
ViewTab := nil;
for i := 0 to ViewsTabBar.Tabs.Count - 1 do
if ViewsTabBar.Tabs[i].Caption = ViewFactory.TabCaption then begin
ViewTab := ViewsTabBar.Tabs[i].Data as TJvStandardPage;
ViewsTabBar.Tabs[i].Selected := True;
Result := ViewTab.Components[0] as IEditorView;
break;
end;
if not Assigned(ViewTab) then begin
// Editor View does not exist - Create
ViewTab := TJvStandardPage.Create(EditorViews);
try
ViewTab.PageList := EditorViews;
ViewTab.Caption := ViewFactory.TabCaption;
Form := ViewFactory.CreateForm(fEditor, ViewTab);
with Form do begin
BorderStyle := bsNone;
Parent := ViewTab;
Align := alClient;
Visible := True;
Form.SetFocus;
Result := Form as IEditorView;
end;
// fix for Delphi 4 (???)
Form.Realign;
// Add Tab to the ViewsTabbar
with ViewsTabbar.AddTab(ViewTab.Caption) do begin
Data := ViewTab;
Selected := True;
PopupMenu := pmnuPageList;
end;
except
ViewTab.Free;
raise;
end;
end;
ViewsTabbar.Visible := True;
end;
function TEditorForm.DoAskSaveChanges: boolean;
const
MBType = MB_YESNOCANCEL or MB_ICONQUESTION;
var
s: string;
begin
// this is necessary to prevent second confirmation when closing MDI childs
if SynEdit.Modified then begin
DoActivateEditor;
MessageBeep(MB_ICONQUESTION);
Assert(fEditor <> nil);
s := Format(SAskSaveChanges, [ExtractFileName(fEditor.GetFileTitle)]);
case Application.MessageBox(PChar(s), PChar(Application.Title), MBType) of
IDYes: Result := DoSave;
IDNo: Result := TRUE;
else
Result := FALSE;
end;
end else
Result := TRUE;
end;
procedure TEditorForm.DoAssignInterfacePointer(AActive: boolean);
begin
if AActive then begin
GI_ActiveEditor := fEditor;
GI_EditCmds := fEditor;
GI_FileCmds := fEditor;
GI_SearchCmds := fEditor;
end else begin
if GI_ActiveEditor = IEditor(fEditor) then
GI_ActiveEditor := nil;
if GI_EditCmds = IEditCommands(fEditor) then
GI_EditCmds := nil;
if GI_FileCmds = IFileCommands(fEditor) then
GI_FileCmds := nil;
if GI_SearchCmds = ISearchCommands(fEditor) then
GI_SearchCmds := nil;
end;
end;
function TEditorForm.DoSave: boolean;
begin
Assert(fEditor <> nil);
if fEditor.fFileName <> '' then
Result := DoSaveFile
else
Result := DoSaveAs;
end;
function TEditorForm.DoSaveFile: boolean;
Var
FileStream : TFileStream;
S : string;
begin
Assert(fEditor <> nil);
try
CommandsDataModule.JvChangeNotify.Active := False;
// Create Backup
if CommandsDataModule.PyIDEOptions.CreateBackupFiles and
FileExists(fEditor.fFileName) then
begin
try
FileBackup(fEditor.fFileName);
except
MessageDlg(Format('Failed to backup file "%s"', [fEditor.fFileName]),
mtWarning, [mbOK], 0);
end;
end;
FileStream := TFileStream.Create(fEditor.fFileName, fmCreate);
try
case fEditor.fFileEncoding of
seAnsi :
begin
S := fEditor.GetEncodedText;
FileStream.WriteBuffer(S[1], Length(S));
end;
seUTF8 : SaveToStream(SynEdit.Lines, FileStream, seUTF8, True);
else // Should not happen
Raise Exception.Create('UTF-16 encoded files are not currently upported');
end;
finally
FileStream.Free;
end;
CommandsDataModule.UpdateChangeNotify;
if not CommandsDataModule.PyIDEOptions.UndoAfterSave then
SynEdit.ClearUndo;
SynEdit.Modified := FALSE;
Result := TRUE;
except
Application.HandleException(Self);
Result := FALSE;
end;
end;
function TEditorForm.DoSaveAs: boolean;
var
NewName: string;
Edit : IEditor;
begin
Assert(fEditor <> nil);
NewName := fEditor.GetFileNameOrTitle;
if (fEditor.GetFileName = '') and (DefaultExtension <> '') and
(ExtractFileExt(NewName) = '')
then
NewName := NewName + '.' + DefaultExtension;
if CommandsDataModule.GetSaveFileName(NewName, SynEdit.Highlighter, DefaultExtension) then
begin
Edit := GI_EditorFactory.GetEditorByName(NewName);
if Assigned(Edit) and (Edit <> Self.fEditor as IEditor) then begin
MessageDlg('Another editor with the same file is open. '+
' You can not have two editors with the same file.', mtError, [mbAbort], 0);
Result := False;
Exit;
end;
fEditor.DoSetFileName(NewName);
DoUpdateCaption;
DoUpdateHighlighter;
Result := DoSaveFile;
end else
Result := FALSE;
end;
procedure TEditorForm.DoUpdateCaption;
begin
Assert(fEditor <> nil);
with fEditor.TabBarItem do begin
Caption := fEditor.GetFileTitle;
Hint := fEditor.GetFileName;
end;
end;
procedure TEditorForm.DoUpdateHighlighter(HighlighterName : string = '');
var
Index : integer;
begin
Assert(fEditor <> nil);
if fEditor.fFileName <> '' then
SynEdit.Highlighter := CommandsDataModule.GetHighlighterForFile(
fEditor.fFileName)
else if HighlighterName <> '' then begin
Index := CommandsDataModule.Highlighters.IndexOf(HighlighterName);
if Index < 0 then
SynEdit.Highlighter := nil
else
SynEdit.Highlighter :=
CommandsDataModule.Highlighters.Objects[Index] as TSynCustomHighlighter;
end else //No highlighter otherwise
SynEdit.Highlighter := nil;
SynEdit.RegisterCommandHandler( doProcessUserCommand, nil );
end;
procedure TEditorForm.EditorMouseWheel(theDirection: Integer;
Shift: TShiftState);
function OwnScroll(Shift: TShiftState; LinesInWindow: Integer): Integer;
begin
if ssShift in Shift
then
Result := LinesInWindow
else
Result := Mouse.WheelScrollLines;
end;
//
begin
{*
Manage Zoom in and out, Page up and down, Line scroll - with the Mouse Wheel
*}
if ssCtrl in Shift then
EditorZoom( theDirection )
else
SynEdit.TopLine := SynEdit.TopLine +
(theDirection * OwnScroll( Shift, SynEdit.LinesInWindow ) );
end;
procedure TEditorForm.EditorZoom(theZoom: Integer);
begin
if not ( (theZoom < 1) and (SynEdit.Font.Size <= 2) ) then begin
SynEdit.Font.Size := SynEdit.Font.Size + theZoom;
SynEdit.Gutter.Font.Size := Max(SynEdit.Font.Size -2, 1);
end;
end;
procedure TEditorForm.doProcessUserCommand(Sender: TObject;
AfterProcessing: boolean; var Handled: boolean;
var Command: TSynEditorCommand; var AChar: WideChar; Data,
HandlerData: pointer);
var
iPrevLine, Indent: string;
Position: integer;
OldOptions : TSynEditorOptions;
OpenBrackets, CloseBrackets : WideString;
OpenBracketPos : integer;
Line: WideString;
begin
if (Command = ecCodeCompletion) and not AfterProcessing and
(SynEdit.Highlighter = CommandsDataModule.SynPythonSyn) then
begin
if SynCodeCompletion.Form.Visible then
SynCodeCompletion.CancelCompletion;
//SynCodeCompletion.DefaultType := ctCode;
SynCodeCompletion.ActivateCompletion;
Command := ecNone;
end else if (Command = ecParamCompletion) and not AfterProcessing and
(SynEdit.Highlighter = CommandsDataModule.SynPythonSyn) then
begin
if SynParamCompletion.Form.Visible then
SynParamCompletion.CancelCompletion;
//SynCodeCompletion.DefaultType := ctParams;
SynParamCompletion.ActivateCompletion;
Command := ecNone;
end else if (Command = ecLineBreak) and AfterProcessing and SynEdit.InsertMode and
(SynEdit.Highlighter = CommandsDataModule.SynPythonSyn) and not fAutoCompleteActive
then begin
{ CaretY should never be lesser than 2 right after ecLineBreak, so there's
no need for a check }
iPrevLine := TrimRight( SynEdit.Lines[ SynEdit.CaretY -2 ] );
Position := 1;
Indent := '';
while (Length(iPrevLine)>=Position) and
(iPrevLine[Position] in [#09, #32]) do begin
Indent := Indent + iPrevLine[Position];
Inc(Position);
end;
if CommandsDataModule.IsBlockOpener(iPrevLine) or (Indent <> '') then
begin
SynEdit.UndoList.BeginBlock;
OldOptions := SynEdit.Options;
SynEdit.Options := SynEdit.Options - [eoTrimTrailingSpaces];
try
if (eoAutoIndent in SynEdit.Options) and (iPrevLine <> '') then begin
// undo the effect of autoindent
Position := SynEdit.CaretX;
SynEdit.BlockBegin := BufferCoord(1, SynEdit.CaretY);
SynEdit.BlockEnd := BufferCoord(Position, SynEdit.CaretY);
SynEdit.SelText := '';
end;
if CommandsDataModule.IsBlockOpener(iPrevLine) then begin
if eoTabsToSpaces in SynEdit.Options then
Indent := Indent + StringOfChar(' ', SynEdit.TabWidth)
else
Indent := indent + #9;
end else if CommandsDataModule.IsBlockCloser(iPrevLine) then begin
if (eoTabsToSpaces in SynEdit.Options) and (Length(Indent) > 0) and
(Indent[Length(Indent)] <> #9)
then
Delete(Indent, Length(Indent) - SynEdit.TabWidth + 1, SynEdit.TabWidth)
else
Delete(Indent, Length(Indent), 1);
end;
// use ReplaceSel to ensure it goes at the cursor rather than end of buffer
if Trim(iPrevLine) <> '' then
SynEdit.SelText := indent;
finally
SynEdit.UndoList.EndBlock;
SynEdit.Options := OldOptions;
end;
end;
SynEdit.InvalidateGutterLine(SynEdit.CaretY - 1);
end else if (Command = ecChar) and AfterProcessing and not fAutoCompleteActive
and CommandsDataModule.PyIDEOptions.AutoCompleteBrackets then
with SynEdit do begin
if SynEdit.Highlighter = CommandsDataModule.SynPythonSyn then begin
OpenBrackets := '([{';
CloseBrackets := ')]}';
end else if (SynEdit.Highlighter = CommandsDataModule.SynHTMLSyn) or
(SynEdit.Highlighter = CommandsDataModule.SynXMLSyn) or
(SynEdit.Highlighter = CommandsDataModule.SynCssSyn) then
begin
OpenBrackets := '<';
CloseBrackets := '>';
end else
Exit;
if aChar = fCloseBracketChar then begin
Line := LineText;
if InsertMode and (CaretX <= Length(Line)) and (Line[CaretX] = fCloseBracketChar) then
ExecuteCommand(ecDeleteChar, WideChar(#0), nil);
fCloseBracketChar := #0;
end else begin
fCloseBracketChar := #0;
OpenBracketPos := Pos(aChar, OpenBrackets);
if (OpenBracketPos > 0) and
(CaretX > Length(LineText)) then
begin
SelText := CloseBrackets[OpenBracketPos];
CaretX := CaretX - 1;
fCloseBracketChar := CloseBrackets[OpenBracketPos];
end;
end;
end;
end;
procedure TEditorForm.PaintGutterGlyphs(ACanvas: TCanvas; AClip: TRect;
FirstLine, LastLine: integer);
var
LH, X, Y: integer;
LI: TDebuggerLineInfos;
ImgIndex: integer;
begin
if (PyIDEMainForm.PyDebugger <> nil) and SynEdit.Gutter.Visible then
begin
FirstLine := SynEdit.RowToLine(FirstLine);
LastLine := SynEdit.RowToLine(LastLine);
X := 14;
LH := SynEdit.LineHeight;
while FirstLine <= LastLine do
begin
Y := (LH - imglGutterGlyphs.Height) div 2
+ LH * (SynEdit.LineToRow(FirstLine) - SynEdit.TopLine);
LI := PyIDEMainForm.PyDebugger.GetLineInfos(fEditor, FirstLine);
if dlCurrentLine in LI then begin
if dlBreakpointLine in LI then
ImgIndex := 2
else
ImgIndex := 1;
end else if dlExecutableLine in LI then begin
if dlBreakpointLine in LI then
ImgIndex := 3
else if dlDisabledBreakpointLine in LI then
ImgIndex := 5
else if CommandsDataModule.PyIDEOptions.MarkExecutableLines then
ImgIndex := 0
else
ImgIndex := -1
end else begin
if dlBreakpointLine in LI then
ImgIndex := 4
else if dlDisabledBreakpointLine in LI then
ImgIndex := 5
else
ImgIndex := -1;
end;
if ImgIndex >= 0 then
imglGutterGlyphs.Draw(ACanvas, X, Y, ImgIndex);
Inc(FirstLine);
end;
end;
end;
procedure TEditorForm.FormCreate(Sender: TObject);
begin
FormResize(Self);
FGPanelExit(Self);
SynEdit.ControlStyle := Synedit.ControlStyle + [csOpaque];
ViewsTabBar.ControlStyle := ViewsTabBar.ControlStyle + [csOpaque];
FGPanel.ControlStyle := FGPanel.ControlStyle + [csOpaque];
EditorViews.ControlStyle := EditorViews.ControlStyle + [csOpaque];
SourcePage.ControlStyle := SourcePage.ControlStyle + [csOpaque];
fHotIdentInfo.HaveHotIdent := False;
fSyntaxErrorPos := TEditorPos.Create;
ViewsTabBar.Visible := False;
ViewsTabBar.Tabs[0].Data := SourcePage;
BreakPoints := TObjectList.Create(True);
TDebugSupportPlugin.Create(Self); // No need to free
AddThemeNotification(Self);
PyIDEMainForm.ThemeEditorGutter(SynEdit.Gutter);
end;
procedure TEditorForm.SynEditGutterClick(Sender: TObject;
Button: TMouseButton; X, Y, Line: Integer; Mark: TSynEditMark);
begin
if (SynEdit.Highlighter = CommandsDataModule.SynPythonSyn) and
(PyIDEMainForm.PyDebugger <> nil) and not (sfGutterDragging in SynEdit.StateFlags)
then
PyIDEMainForm.PyDebugger.ToggleBreakpoint(fEditor, SynEdit.RowToLine(Line));
end;
procedure TEditorForm.SynEditSpecialLineColors(Sender: TObject;
Line: Integer; var Special: Boolean; var FG, BG: TColor);
var
LI: TDebuggerLineInfos;
begin
if PyIDEMainForm.PyDebugger <> nil then begin
LI := PyIDEMainForm.PyDebugger.GetLineInfos(fEditor, Line);
if dlCurrentLine in LI then begin
Special := TRUE;
FG := clWhite;
BG := clBlue;
end else if (dlErrorLine in LI) then
begin
Special := TRUE;
FG := clWhite;
BG := clRed
end;
end;
end;
function TEditorForm.GetEditor: IEditor;
begin
Result := fEditor;
end;
procedure TEditorForm.SynEditPaintTransient(Sender: TObject;
Canvas: TCanvas; TransientType: TTransientType);
Var
Pix: TPoint;
begin
if (not Assigned(SynEdit.Highlighter)) then
Exit;
if fHotIdentInfo.HaveHotIdent and (TransientType = ttAfter) then begin
Pix := SynEdit.RowColumnToPixels(SynEdit.BufferToDisplayPos(fHotIdentInfo.StartCoord));
Canvas.Font.Assign(SynEdit.Font);
Canvas.Font.Style := fHotIdentInfo.SynAttri.Style + [fsUnderline];
Canvas.Font.Color:= clBlue;
if fHotIdentInfo.SynAttri.Background <> clNone then
Canvas.Brush.Color := fHotIdentInfo.SynAttri.Background
else
Canvas.Brush.Color := SynEdit.Color;
Canvas.Brush.Style := bsSolid;
SetTextCharacterExtra(Canvas.Handle, SynEdit.CharWidth - Canvas.TextWidth('W'));
Canvas.TextOut(Pix.X, Pix.Y, fHotIdentInfo.SynToken);
end;
CommandsDataModule.PaintMatchingBrackets(Canvas, SynEdit, TransientType);
end;
procedure TEditorForm.SynEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// Cancel Code Hint
CodeHint.CancelHint;
end;
procedure TEditorForm.SynEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if fHotIdentInfo.HaveHotIdent then begin
fHotIdentInfo.HaveHotIdent := False;
SynEdit.InvalidateLine(fHotIdentInfo.StartCoord.Line);
SetCursor(Screen.Cursors[crIBeam])
end;
end;
procedure TEditorForm.SynEditMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
TokenType, Start, ExpStart: Integer;
Token, LineTxt: WideString;
Attri: TSynHighlighterAttributes;
Pix : TPoint;
aLineCharPos : TBufferCoord;
begin
if X < Synedit.Gutter.Width then exit;
aLineCharPos := SynEdit.DisplayToBufferPos(SynEdit.PixelsToRowColumn(X, Y));
// Syntax error hints
if CommandsDataModule.PyIDEOptions.CheckSyntaxAsYouType and
fSyntaxErrorPos.IsSyntax and (fSyntaxErrorPos.Editor = GetEditor) and
(aLineCharPos.Line = fSyntaxErrorPos.Line) and
(aLineCharPos.Char <= fSyntaxErrorPos.Char) then
with SynEdit do begin
Pix := ClientToScreen(RowColumnToPixels(BufferToDisplayPos(BufferCoord(1, aLineCharpos.Line))));
fHintIdentInfo.IdentArea.TopLeft := Pix;
Pix := ClientToScreen(RowColumnToPixels(BufferToDisplayPos(BufferCoord(fSyntaxErrorPos.Char, aLineCharpos.Line))));
fHintIdentInfo.IdentArea.Right := Pix.X;
fHintIdentInfo.IdentArea.Bottom := Pix.Y + LineHeight + 3;
Pix := ClientToScreen(RowColumnToPixels(BufferToDisplayPos(aLineCharPos)));
Pix.Y := Pix.Y + LineHeight;
fHintIdentInfo.SynToken := 'Syntax Error';
CodeHint.ActivateHintAt(fHintIdentInfo.IdentArea, Pix);
end else if SynEdit.Focused and fEditor.HasPythonFile and
(HiWord(GetAsyncKeyState(VK_CONTROL)) = 0) and
not SynEdit.IsPointInSelection(aLineCharPos) and
//(FindVCLWindow(SynEdit.ClientToScreen(Point(X,Y))) = SynEdit) and
(((PyIDEMainForm.PyDebugger.DebuggerState = dsPaused) and
CommandsDataModule.PyIDEOptions.ShowDebuggerHints) or
((PyIDEMainForm.PyDebugger.DebuggerState = dsInactive) and
CommandsDataModule.PyIDEOptions.ShowCodeHints))
then with SynEdit do begin
// Code and debugger hints
GetHighlighterAttriAtRowColEx(aLineCharPos, Token, TokenType, Start, Attri);
if (Attri = CommandsDataModule.SynPythonSyn.IdentifierAttri) or
(Attri = CommandsDataModule.SynPythonSyn.NonKeyAttri) or
(Attri = CommandsDataModule.SynPythonSyn.SystemAttri) or
((PyIDEMainForm.PyDebugger.DebuggerState = dsPaused) and ((Token = ')')
or (Token = ']'))) then
begin
with fHintIdentInfo do begin
LineTxt := Lines[aLineCharPos.Line - 1];
Ident := Token;
DottedIdent :=
GetWordAtPos(LineTxt, aLineCharPos.Char, IdentChars+['.'], True, False, True);
ExpStart := aLineCharPos.Char - Length(DottedIdent) + 1;
DottedIdent := DottedIdent +
GetWordAtPos(LineTxt, aLineCharPos.Char + 1, IdentChars, False, True);
//Determine the hint area
StartCoord := BufferCoord(Start, aLineCharPos.Line);
Pix := ClientToScreen(RowColumnToPixels(BufferToDisplayPos(StartCoord)));
IdentArea.TopLeft := Pix;
aLineCharPos := WordEndEx(aLineCharPos);
if (Token = ']') or (Token = ')') then
Inc(aLineCharPos.Char);
Pix := ClientToScreen(RowColumnToPixels(BufferToDisplayPos(aLineCharPos)));
IdentArea.Right := Pix.X;
IdentArea.Bottom := Pix.Y + LineHeight + 3;
// Determine where the hint should be shown (beginning of the expression)
if PyIDEMainForm.PyDebugger.DebuggerState = dsPaused then
aLineCharPos := BufferCoord(ExpStart, aLineCharPos.Line)
else
aLineCharPos := StartCoord;
Pix := ClientToScreen(RowColumnToPixels(BufferToDisplayPos(aLineCharPos)));
Pix.Y := Pix.Y + LineHeight;
// Activate the hint
CodeHint.ActivateHintAt(IdentArea, Pix);
end;
end;
end;
end;
procedure TEditorForm.SynEditMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
EditorMouseWheel( +1, Shift );
Handled := True;
end;
procedure TEditorForm.SynEditMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
EditorMouseWheel( -1, Shift );
Handled := True;
end;
procedure TEditorForm.SynEditMouseCursor(Sender: TObject;
const aLineCharPos: TBufferCoord; var aCursor: TCursor);
var
TokenType, Start: Integer;
Token: WideString;
Attri: TSynHighlighterAttributes;
begin
if fHotIdentInfo.HaveHotIdent then begin
fHotIdentInfo.HaveHotIdent := False;
SynEdit.InvalidateLine(fHotIdentInfo.StartCoord.Line);
end;
if SynEdit.Focused and (HiWord(GetAsyncKeyState(VK_CONTROL)) > 0) and
fEditor.HasPythonFile and not SynEdit.IsPointInSelection(aLineCharPos)
then with SynEdit do begin
GetHighlighterAttriAtRowColEx(aLineCharPos, Token, TokenType, Start, Attri);
if (Attri = CommandsDataModule.SynPythonSyn.IdentifierAttri) or
(Attri = CommandsDataModule.SynPythonSyn.NonKeyAttri) or
(Attri = CommandsDataModule.SynPythonSyn.SystemAttri) then
begin
aCursor := crHandPoint;
with fHotIdentInfo do begin
HaveHotIdent := True;
SynAttri := Attri;
SynToken := Token;
StartCoord := BufferCoord(Start, aLineCharPos.Line);
end;
InvalidateLine(aLineCharPos.Line);
end;
end;
end;
procedure TEditorForm.SynEditMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
with PyIDEMainForm.PyDebugger.ErrorPos do
if Editor = GetEditor then begin
Clear;
PyIDEMainForm.DebuggerErrorPosChange(Self);
end;
if fHotIdentInfo.HaveHotIdent then begin
fHotIdentInfo.HaveHotIdent := False;
SynEdit.InvalidateLine(fHotIdentInfo.StartCoord.Line);
PostMessage(PyIDEMainForm.Handle, WM_FINDDEFINITION, fHotIdentInfo.StartCoord.Char,
fHotIdentInfo.StartCoord.Line);
end;
end;
procedure TEditorForm.FGPanelEnter(Sender: TObject);
begin
HasFocus := True;
Color := CurrentTheme.GetItemColor(GetItemInfo('hot'));
//Color := GetBorderColor('active');
end;
procedure TEditorForm.FGPanelExit(Sender: TObject);
begin
HasFocus := False;
// Color := CurrentTheme.GetItemColor(GetItemInfo('inactive'));
Color := GetBorderColor('inactive');
end;
procedure TEditorForm.FormResize(Sender: TObject);
begin
with FGPanel do begin
if (Top <> 3) or (Left <> 3) or (Width <> Self.ClientWidth - 6)
or (Height <> Self.ClientHeight - 6)
then begin
Anchors :=[];
Top := 3;
Left := 3;
Width := Self.ClientWidth - 6;
Height := Self.ClientHeight - 6;
Anchors :=[akLeft, akRight, akTop, akBottom];
end;
end;
end;
procedure TEditorForm.CloseTabClick(Sender: TObject);
begin
if ViewsTabBar.SelectedTab.Data <> SourcePage then begin
TJvStandardPage(ViewsTabbar.SelectedTab.Data).Free;
ViewsTabBar.SelectedTab.Free;
if ViewsTabBar.Tabs.Count = 1 then begin
ViewsTabBar.Visible := False;
end;
end;
end;
procedure TEditorForm.ViewsTabBarTabSelected(Sender: TObject;
Item: TJvTabBarItem);
begin
EditorViews.ActivePage := TJvStandardPage(ViewsTabbar.SelectedTab.Data);
end;
procedure TEditorForm.AddWatchAtCursor;
var
TokenType, Start: Integer;
Token, LineTxt, DottedIdent: WideString;
Attri: TSynHighlighterAttributes;
aLineCharPos : TBufferCoord;
begin
aLineCharPos := SynEdit.CaretXY;
if fEditor.HasPythonFile then with SynEdit do begin
GetHighlighterAttriAtRowColEx(aLineCharPos, Token, TokenType, Start, Attri);
if (Attri = CommandsDataModule.SynPythonSyn.IdentifierAttri) or
(Attri = CommandsDataModule.SynPythonSyn.NonKeyAttri) or
(Attri = CommandsDataModule.SynPythonSyn.SystemAttri) or
((Token = ')') or (Token = ']')) then
begin
LineTxt := Lines[aLineCharPos.Line - 1];
DottedIdent :=
GetWordAtPos(LineTxt, aLineCharPos.Char, IdentChars+['.'], True, False, True);
DottedIdent := DottedIdent +
GetWordAtPos(LineTxt, aLineCharPos.Char + 1, IdentChars, False, True);
if DottedIdent <> '' then
WatchesWindow.AddWatch(DottedIdent);
end;
end;
end;
procedure TEditorForm.AutoCompleteAfterExecute(Sender: TObject);
begin
fAutoCompleteActive := False;
CommandsDataModule.actReplaceParametersExecute(nil);
end;
procedure TEditorForm.AutoCompleteBeforeExecute(Sender: TObject);
begin
fAutoCompleteActive := True;
end;
procedure TEditorForm.TBMThemeChange(var Message: TMessage);
begin
if Message.WParam = TSC_VIEWCHANGE then begin
if HasFocus then
Color := CurrentTheme.GetItemColor(GetItemInfo('hot'))
// Color := GetBorderColor('active')
else
// Color := CurrentTheme.GetItemColor(GetItemInfo('inactive'));
Color := GetBorderColor('inactive');
PyIDEMainForm.ThemeEditorGutter(SynEdit.Gutter);
SynEdit.InvalidateGutter;
Invalidate;
end;
end;
procedure TEditorForm.SynEditReplaceText(Sender: TObject; const ASearch,
AReplace: WideString; Line, Column: Integer; var Action: TSynReplaceAction);
var
APos: TPoint;
EditRect: TRect;
begin
if ASearch = AReplace then
Action := raSkip
else begin
APos := SynEdit.ClientToScreen(
SynEdit.RowColumnToPixels(
SynEdit.BufferToDisplayPos(
BufferCoord(Column, Line) ) ) );
EditRect := ClientRect;
EditRect.TopLeft := ClientToScreen(EditRect.TopLeft);
EditRect.BottomRight := ClientToScreen(EditRect.BottomRight);
if ConfirmReplaceDialog = nil then
ConfirmReplaceDialog := TConfirmReplaceDialog.Create(Application);
ConfirmReplaceDialog.PrepareShow(EditRect, APos.X, APos.Y,
APos.Y + SynEdit.LineHeight, ASearch);
case ConfirmReplaceDialog.ShowModal of
mrYes: Action := raReplace;
mrYesToAll: Action := raReplaceAll;
mrNo: Action := raSkip;
else Action := raCancel;
end;
end;
end;
procedure TEditorForm.SynCodeCompletionExecute(Kind: SynCompletionType;
Sender: TObject; var CurrentInput: WideString; var x, y: Integer;
var CanExecute: Boolean);
var
locline, lookup: string;
TmpX, Index, ImageIndex, i,
TmpLocation : Integer;
FoundMatch : Boolean;
DisplayText, InsertText, FName, ErrMsg, S : string;
NameSpace, SortedNameSpace : TStringList;
Scope: TCodeElement;
Def, CE : TBaseCodeElement;
ParsedModule, BuiltInModule : TParsedModule;
PythonPathAdder : IInterface;
begin
if not fEditor.HasPythonFile then begin
CanExecute := False;
Exit;
end;
with TSynCompletionProposal(Sender).Editor do
begin
locLine := LineText;
//go back from the cursor and find the first open paren
TmpX := CaretX;
if TmpX > length(locLine) then
TmpX := length(locLine)
else dec(TmpX);
TmpLocation := 0;
lookup := GetWordAtPos(LocLine, TmpX, IdentChars+['.'], True, False);
Index := CharLastPos(lookup, '.');
FName := GetEditor.GetFileNameOrTitle;
// Add the file path to the Python path - Will be automatically removed
PythonPathAdder := AddPathToPythonPath(ExtractFilePath(FName));
PyScripterRefactor.InitializeQuery;
// GetParsedModule
ParsedModule := PyScripterRefactor.GetParsedModule(
FileNameToModuleName(FName), None);
Scope := nil;
if Assigned(ParsedModule) then
Scope := ParsedModule.GetScopeForLine(CaretY);
if Assigned(ParsedModule) and Assigned(Scope) then begin
NameSpace := TStringList.Create;
SortedNameSpace := TStringList.Create;
SortedNameSpace.Duplicates := dupIgnore;
SortedNameSpace.CaseSensitive := True;
try
DisplayText := '';
if Index > 0 then begin
lookup := Copy(lookup, 1, Index-1);
Def := PyScripterRefactor.FindDottedDefinition(lookup, ParsedModule,
Scope, ErrMsg);
if Assigned(Def) and(Def.ClassType = TVariable) then
Def := PyScripterRefactor.GetType(TVariable(Def), ErrMsg);
if Assigned(Def) then
(Def as TCodeElement).GetNameSpace(NameSpace);
end else begin
// extract namespace from current scope and its parents
while Assigned(Scope) do begin
Scope.GetNameSpace(NameSpace);
Scope := Scope.Parent as TCodeElement;
end;
// builtins (could add keywords as well)
BuiltInModule := PyScripterRefactor.GetParsedModule('__builtin__', None);
BuiltInModule.GetNameSpace(NameSpace);
end;
SortedNameSpace.Duplicates := dupIgnore;
SortedNameSpace.Sorted := True;
SortedNameSpace.AddStrings(NameSpace);
InsertText := SortedNamespace.Text;
for i := 0 to SortedNamespace.Count - 1 do begin
S := SortedNamespace[i];
CE := SortedNamespace.Objects[i] as TBaseCodeElement;
if (CE is TParsedModule) or (CE is TModuleImport) then
ImageIndex := 16
else if CE is TParsedFunction then begin
if CE.Parent is TParsedClass then
ImageIndex := 14
else
ImageIndex := 17
end else if CE is TParsedClass then
ImageIndex := 13
else begin // TVariable or TParsedVariable
if CE.Parent is TParsedClass then
ImageIndex := 1
else
ImageIndex := 0
end;
DisplayText := DisplayText + Format('\Image{%d}\hspace{2}%s', [ImageIndex, S]);
if i < SortedNamespace.Count - 1 then
DisplayText := DisplayText + #10;
end;
finally
NameSpace.Free;
SortedNameSpace.Free;
end;
end;
FoundMatch := DisplayText <> '';
end;
CanExecute := FoundMatch;
if CanExecute then begin
TSynCompletionProposal(Sender).Form.CurrentIndex := TmpLocation;
TSynCompletionProposal(Sender).ItemList.Text := DisplayText;
TSynCompletionProposal(Sender).InsertList.Text := InsertText;
end else begin
TSynCompletionProposal(Sender).ItemList.Clear;
TSynCompletionProposal(Sender).InsertList.Clear;
end;
end;
procedure TEditorForm.SynParamCompletionExecute(Kind: SynCompletionType;
Sender: TObject; var CurrentInput: WideString; var x, y: Integer;
var CanExecute: Boolean);
var
locline, lookup: String;
TmpX, StartX,
ParenCounter,
TmpLocation : Integer;
FoundMatch : Boolean;
FName, DisplayText, ErrMsg, Doc : string;
p : TPoint;
Scope: TCodeElement;
Def: TBaseCodeElement;
ParsedModule : TParsedModule;
PythonPathAdder : IInterface;
TokenType, Start: Integer;
Token: WideString;
Attri: TSynHighlighterAttributes;
begin
if not fEditor.HasPythonFile then begin
CanExecute := False;
Exit;
end;
with TSynCompletionProposal(Sender).Editor do
begin
locLine := LineText;
//go back from the cursor and find the first open paren
TmpX := CaretX;
StartX := CaretX;
if TmpX > length(locLine) then
TmpX := length(locLine)
else dec(TmpX);
FoundMatch := False;
TmpLocation := 0;
while (TmpX > 0) and not(FoundMatch) do
begin
if LocLine[TmpX] = ',' then
begin
inc(TmpLocation);
dec(TmpX);
end else if LocLine[TmpX] = ')' then
begin
//We found a close, go till it's opening paren
ParenCounter := 1;
dec(TmpX);
while (TmpX > 0) and (ParenCounter > 0) do
begin
if LocLine[TmpX] = ')' then inc(ParenCounter)
else if LocLine[TmpX] = '(' then dec(ParenCounter);
dec(TmpX);
end;
if TmpX > 0 then dec(TmpX); //eat the open paren
end else if locLine[TmpX] = '(' then
begin
//we have a valid open paren, lets see what the word before it is
StartX := TmpX;
while (TmpX > 0) and not(locLine[TmpX] in IdentChars+['.']) do // added [.]
Dec(TmpX);
if TmpX > 0 then
begin
DisplayText := '';
GetHighlighterAttriAtRowColEx(BufferCoord(TmpX, CaretY), Token,
TokenType, Start, Attri);
if (Attri = CommandsDataModule.SynPythonSyn.IdentifierAttri) or
(Attri = CommandsDataModule.SynPythonSyn.NonKeyAttri) or
(Attri = CommandsDataModule.SynPythonSyn.SystemAttri) then
begin
lookup := GetWordAtPos(LocLine, TmpX, IdentChars+['.'], True, False);
FName := GetEditor.GetFileNameOrTitle;
// Add the file path to the Python path - Will be automatically removed
PythonPathAdder := AddPathToPythonPath(ExtractFilePath(FName));
PyScripterRefactor.InitializeQuery;
// GetParsedModule
ParsedModule := PyScripterRefactor.GetParsedModule(
FileNameToModuleName(FName), None);
Scope := nil;
if Assigned(ParsedModule) then
Scope := ParsedModule.GetScopeForLine(CaretY);
if Assigned(ParsedModule) and Assigned(Scope) then begin
Def := PyScripterRefactor.FindDottedDefinition(lookup, ParsedModule,
Scope, ErrMsg);
if Assigned(Def) and (Def is TParsedClass) then
Def := TParsedClass(Def).GetConstructor;
if Assigned(Def) and (Def is TParsedFunction) then begin
DisplayText := TParsedFunction(Def).ArgumentsString;
// Remove self arguments from methods
if StrIsLeft(PChar(DisplayText), 'self') then
Delete(DisplayText, 1, 4);
if StrIsLeft(PChar(DisplayText), ', ') then
Delete(DisplayText, 1, 2);
Doc := TParsedFunction(Def).DocString;
if Doc <> '' then
Doc := GetNthLine(Doc, 1);
FoundMatch := True;
end;
end;
end;
if not(FoundMatch) then
begin
TmpX := StartX;
dec(TmpX);
end;
end;
end else dec(TmpX)
end;
end;
if FoundMatch then begin
//CanExecute := (DisplayText <> '') or (Doc <> '');
CanExecute := True;
end else
CanExecute := False;
if CanExecute then begin
with TSynCompletionProposal(Sender) do begin
if DisplayText = '' then begin
FormatParams := False;
DisplayText := '\style{~B}' + SNoParameters + '\style{~B}';
end else begin
FormatParams := True;
end;
if (Doc <> '') then
DisplayText := DisplayText + sLineBreak;
Form.CurrentIndex := TmpLocation;
ItemList.Text := DisplayText + Doc;
end;
// position the hint window at and just below the opening bracket
p := SynEdit.ClientToScreen(SynEdit.RowColumnToPixels(
SynEdit.BufferToDisplayPos(BufferCoord(Succ(StartX), SynEdit.CaretY))));
Inc(p.y, SynEdit.LineHeight);
x := p.X;
y := p.Y;
end else begin
TSynCompletionProposal(Sender).ItemList.Clear;
TSynCompletionProposal(Sender).InsertList.Clear;
end;
end;
procedure TEditorForm.CodeHintEventHandler(Sender: TObject; AArea: TRect;
var CodeHint: string);
Var
ObjectValue, ObjectType, ErrMsg : string;
CE : TBaseCodeElement;
begin
if CompareMem(@fHintIdentInfo.IdentArea, @AArea, SizeOf(TRect)) then begin
if (fHintIdentInfo.SynToken = 'Syntax Error') and
(fSyntaxErrorPos.Editor = GetEditor) then
begin
// Syntax hint
CodeHint := 'Syntax Error: ' + fSyntaxErrorPos.ErrorMsg;
end else if (PyIDEMainForm.PyDebugger.DebuggerState = dsPaused) and
CommandsDataModule.PyIDEOptions.ShowDebuggerHints then
begin
// Debugger hints
PyIDEMainForm.PyDebugger.Evaluate(fHintIdentInfo.DottedIdent, ObjectType, ObjectValue);
if ObjectValue <> SNotAvailable then begin
ObjectValue := HTMLSafe(ObjectValue);
ObjectType := HTMLSafe(ObjectType);
CodeHint := Format(SDebuggerHintFormat,
[fHintIdentInfo.DottedIdent, ObjectType, ObjectValue]);
end else
CodeHint := '';
end else if (PyIDEMainForm.PyDebugger.DebuggerState = dsInactive) and
CommandsDataModule.PyIDEOptions.ShowCodeHints then
begin
// Code hints
CE := PyScripterRefactor.FindDefinitionByCoordinates(fEditor.GetFileNameOrTitle,
fHintIdentInfo.StartCoord.Line, fHintIdentInfo.StartCoord.Char, ErrMsg);
if Assigned(CE) then begin
CodeHint := CE.CodeHint;
end else
CodeHint := '';
end;
end else
CodeHint := '';
end;
procedure TEditorForm.CodeHintLinkHandler(Sender: TObject; LinkName: string);
begin
CodeHint.CancelHint;
PyIDEMainForm.JumpToFilePosInfo(LinkName);
PyIDEMainForm.AdjustBrowserLists(fEditor.GetFileNameOrTitle,
fHintIdentInfo.StartCoord.Line, fHintIdentInfo.StartCoord.Char, LinkName);
end;
procedure TEditorForm.DoOnIdle;
begin
if GetEditor.HasPythonFile and fNeedToCheckSyntax and
CommandsDataModule.PyIDEOptions.CheckSyntaxAsYouType
then begin
PyIDEMainForm.PyDebugger.SyntaxCheck(GetEditor, True);
fSyntaxErrorPos.Assign(PyIDEMainForm.PyDebugger.ErrorPos);
PyIDEMainForm.PyDebugger.ErrorPos.Clear;
fNeedToCheckSyntax := False;
end;
end;
initialization
GI_EditorFactory := TEditorFactory.Create;
finalization
GI_EditorFactory := nil;
end.
|
unit xmt;
interface
uses
CoreX;
{$REGION 'Material format'}
type
TNodeMaterial = record
ShaderName : string;
URL : string;
Name : string;
ShadeType : (stLambert, stPhong, stBlinn);
Params : TMaterialParams;
Defines : array of string;
SamplerName : array [TMaterialSampler] of string;
Material : TMaterial;
Skin : Boolean;
FxSkin : Boolean;
procedure Save(const FileName: string);
end;
TNodeMaterialArray = array of TNodeMaterial;
{
TSamplerFlag = (sfDiffuse, sfNormal, sfSpecular, sfNormalSpecular, sfEmission, sfReflect, sfLighting, sfAmbient);
TMaterial = record
Sampler : TSamplerFlag;
Diffuse : TVec4f;
Specular : TVec4f;
Ambient : TVec3f;
Texture : array [TSamplerFlag] of string;
end;
}
{$ENDREGION}
var
NodeMatList : TNodeMaterialArray;
procedure GetMaterial(const XML: TXML; const URL: string; out NodeMaterial: TNodeMaterial);
implementation
uses
xmd;
{$REGION 'TNodeMaterial'}
procedure TNodeMaterial.Save;
const
SamplerDefine : array [TMaterialSampler] of string = (
'MAP_DIFFUSE', 'MAP_NORMAL', 'MAP_SPECULAR', 'MAP_AMBIENT', 'MAP_EMISSION', 'MAP_ALPHAMASK', 'MAP_REFLECT', 'MAP_SHADOW',
'MAP_MASK', 'MAP_MAP0', 'MAP_MAP1', 'MAP_MAP2', 'MAP_MAP3'
);
procedure AddDefine(const Define: string);
var
i, j : LongInt;
begin
// if not in array
for i := 0 to Length(Defines) - 1 do
if Defines[i] = Define then
Exit;
// insert
for i := 0 to Length(Defines) - 1 do
if Defines[i] > Define then
begin
SetLength(Defines, Length(Defines) + 1);
for j := Length(Defines) - 1 downto i + 1 do
Defines[j] := Defines[j - 1];
Defines[i] := Define;
Exit;
end;
SetLength(Defines, Length(Defines) + 1);
Defines[Length(Defines) - 1] := Define;
end;
var
ms : TMaterialSampler;
Stream : TStream;
i, DCount : LongInt;
Samplers : TMaterialSamplers;
begin
Defines := nil;
// Set defines
if Skin then
AddDefine('SKIN');
Samplers := [];
// Writeln(Ord(ms));
for ms := Low(ms) to High(ms) do
if (SamplerName[ms] <> '') or ((ms = msShadow) and Params.ReceiveShadow) then
begin
AddDefine(SamplerDefine[ms]);
Samplers := Samplers + [ms];
end;
Samplers := Samplers - [msShadow];
if SamplerName[msReflect] <> '' then
AddDefine('FX_REFLECT');
if (SamplerName[msEmission] <> '') or (Params.Emission.LengthQ > EPS) then
AddDefine('FX_EMISSION');
// if ShadeType in [stPhong, stBlinn] then
AddDefine('FX_SHADE');
// AddDefine('FX_PLASTIC');
case ShadeType of
stPhong : AddDefine('FX_PHONG');
stBlinn : AddDefine('FX_BLINN');
end;
if FxSkin then
AddDefine('FX_SKIN');
// AddDefine('FX_COLOR');
// Saving
Stream := TStream.Init(FileName + EXT_XMT, True);
if Stream <> nil then
begin
Stream.Write(Params, SizeOf(Params));
Stream.WriteAnsi(AnsiString(ShaderName));
DCount := Length(Defines);
Stream.Write(DCount, SizeOf(DCount)); // Defines count
for i := 0 to DCount - 1 do
Stream.WriteAnsi(AnsiString(Defines[i]));
Stream.Write(Samplers, SizeOf(Samplers));
for ms := Low(ms) to High(ms) do
if ms in Samplers then
Stream.WriteAnsi(AnsiString(SamplerName[ms]));
Stream.Free;
end;
end;
{$ENDREGION}
{$REGION 'GetMaterial'}
procedure GetMaterial(const XML: TXML; const URL: string; out NodeMaterial: TNodeMaterial);
function GetSampler(const XMLfx, XMLtex: TXML; var Sampler: TSamplerParams): string;
var
i : LongInt;
s : string;
Stream : TStream;
begin
Result := '';
if XMLtex = nil then
Exit;
s := XMLtex.Params['texture'];
with XMLfx['profile_COMMON'] do
begin
for i := 0 to Count - 1 do
if (NodeI[i].Tag = 'newparam') and (NodeI[i].Params['sid'] = s) then
begin
if NodeI[i]['sampler2D'] = nil then
begin
Error(s + ' is not 2d sampler');
Exit;
end;
s := NodeI[i]['sampler2D']['source'].Content;
break;
end;
for i := 0 to Count - 1 do
if (NodeI[i].Tag = 'newparam') and (NodeI[i].Params['sid'] = s) then
begin
s := NodeI[i]['surface']['init_from'].Content;
break;
end;
end;
// sampler params
if (XMLtex['extra'] <> nil) and (XMLtex['extra']['technique'] <> nil) then
with XMLtex['extra']['technique'] do
begin
Sampler.OffsetUV.x := 0.0;
Sampler.OffsetUV.y := 0.0;
Sampler.RepeatUV.x := 1.0;
Sampler.RepeatUV.y := 1.0;
Sampler.RotateUV := 0.0;
{
Sampler.OffsetUV.x := Conv(Node['offsetU'].Content, 0.0);
Sampler.OffsetUV.y := Conv(Node['offsetV'].Content, 0.0);
Sampler.RepeatUV.x := Conv(Node['repeatU'].Content, 1.0);
Sampler.RepeatUV.y := Conv(Node['repeatV'].Content, 1.0);
Sampler.RotateUV := Conv(Node['rotateUV'].Content, 0.0);
}
end;
with XML['library_images'] do
for i := 0 to Count - 1 do
if NodeI[i].Params['id'] = s then
begin
Result := NodeI[i]['init_from'].Content;
break;
end;
Result := ExtractFileName(Result);
Result := DeleteExt(Result);
Stream := TStream.Init(Result + '.dds');
if Stream = nil then
begin
Warning('Texture "' + Result + '.dds" not found!');
Result := '';
end else
Stream.Free;
// Info('Texture: "' + Result + '"');
end;
var
i : LongInt;
MatFX : string;
ShXML : TXML;
str : string;
ms : TMaterialSampler;
begin
for i := 0 to Length(NodeMatList) - 1 do
if URL = NodeMatList[i].URL then
begin
NodeMaterial := NodeMatList[i];
Exit;
end;
MatFX := '';
FillChar(NodeMaterial, SizeOf(NodeMaterial), 0);
NodeMaterial.URL := URL;
// read material
with XML['library_materials'] do
for i := 0 to Count - 1 do
with NodeI[i] do
if Params['id'] = URL then
begin
NodeMaterial.Name := Params['name'];
MatFX := ConvURL(Node['instance_effect'].Params['url']);
break;
end;
// read MatFX
if MatFX <> '' then
with XML['library_effects'] do
for i := 0 to Count - 1 do
if NodeI[i].Params['id'] = MatFX then
with NodeI[i].Node['profile_COMMON']['technique'] do
begin
ShXML := nil;
if Node['lambert'] <> nil then
begin
NodeMaterial.ShadeType := stLambert;
ShXML := Node['lambert'];
end else
if Node['blinn'] <> nil then
begin
NodeMaterial.ShadeType := stBlinn;
ShXML := Node['blinn'];
end else
if Node['phong'] <> nil then
begin
NodeMaterial.ShadeType := stPhong;
ShXML := Node['phong'];
end else
Error('Unknown material type in "' + URL + '"');
with NodeMaterial do
begin
with Params do
begin
Mode := rmOpaque;
DepthWrite := True;
AlphaTest := 1;
CullFace := cfBack;
BlendType := btNormal;
Diffuse := Vec4f(1, 1, 1, 1);
Emission := Vec3f(0, 0, 0);
Reflect := 0.2;
Specular := Vec3f(1, 1, 1);
Shininess := 10;
end;
for ms := Low(Params.Sampler) to High(Params.Sampler) do
begin
SamplerName[ms] := '';
with Params.Sampler[ms] do
begin
RepeatUV := Vec2f(1, 1);
OffsetUV := Vec2f(0, 0);
RotateUV := 0;
end;
end;
end;
if ShXML = nil then
Exit;
with ShXML, NodeMaterial, Params do
begin
if (Node['shininess'] <> nil) and (Node['shininess']['float'] <> nil) then
begin
Shininess := Conv(Node['shininess']['float'].Content, 0.0);
if (ShadeType = stBlinn) and (Shininess > EPS) then
if UpAxis = uaY then // fucking Maya! >_<
Shininess := 4 / Shininess;
end;
if (Node['reflectivity'] <> nil) and (Node['reflectivity']['float'] <> nil) then
Reflect := Conv(Node['reflectivity']['float'].Content, 0.0);
// Diffuse
if Node['diffuse'] <> nil then
begin
Str := GetSampler(XML['library_effects'].NodeI[i], Node['diffuse']['texture'], Params.Sampler[msDiffuse]);
if Str <> '' then
SamplerName[msDiffuse] := Str;
if Node['diffuse']['color'] <> nil then
Diffuse := TVec4f(Pointer(@ParseFloat(Node['diffuse']['color'].Content)[0])^);
end;
// Specular
if Node['specular'] <> nil then
begin
SamplerName[msSpecular] := GetSampler(XML['library_effects'].NodeI[i], Node['specular']['texture'], Params.Sampler[msSpecular]);
if (Node['specular'] <> nil) and (Node['specular']['color'] <> nil) then
Specular := TVec3f(Pointer(@ParseFloat(Node['specular']['color'].Content)[0])^)
else
Specular := Vec3f(1, 1, 1);
end;
// Ambient
if Node['ambient'] <> nil then
SamplerName[msAmbient] := GetSampler(XML['library_effects'].NodeI[i], Node['ambient']['texture'], Params.Sampler[msAmbient]);
// Emission
if Node['emission'] <> nil then
begin
SamplerName[msEmission] := GetSampler(XML['library_effects'].NodeI[i], Node['emission']['texture'], Params.Sampler[msEmission]);
if Node['emission']['color'] <> nil then
Emission := TVec3f(Pointer(@ParseFloat(Node['emission']['color'].Content)[0])^)
else
Emission := Vec3f(1, 1, 1);
end;
// Reflect
if Node['reflective'] <> nil then
SamplerName[msReflect] := GetSampler(XML['library_effects'].NodeI[i], Node['reflective']['texture'], Params.Sampler[msReflect]);
// Transparent
if (Node['transparency'] <> nil) and (Node['transparency']['float'] <> nil) then
Diffuse.w := Diffuse.w * ParseFloat(Node['transparency']['float'].Content)[0];
if Node['transparent'] <> nil then
begin
str := GetSampler(XML['library_effects'].NodeI[i], Node['transparent']['texture'], Params.Sampler[msMask]);
SamplerName[msMask] := str;
if str <> '' then
Params.Mode := rmOpacity;
end;
end;
if (Node['extra'] <> nil) and (Node['extra']['technique'] <> nil) then
with Node['extra']['technique'] do
begin
// normal bump
if (Node['bump'] <> nil) and (Node['bump']['texture'] <> nil) then
NodeMaterial.SamplerName[msNormal] := GetSampler(XML['library_effects'].NodeI[i], Node['bump']['texture'], NodeMaterial.Params.Sampler[msNormal]);
// specular
if (Node['spec_level'] <> nil) then
begin
if Node['spec_level']['texture'] <> nil then
NodeMaterial.SamplerName[msSpecular] := GetSampler(XML['library_effects'].NodeI[i], Node['spec_level']['texture'], NodeMaterial.Params.Sampler[msSpecular]);
if Node['spec_level']['float'] <> nil then
NodeMaterial.Params.Specular := NodeMaterial.Params.Specular * ParseFloat(Node['spec_level']['float'].Content)[0];
end;
// emission
if (Node['emission_level'] <> nil) and (Node['emission_level']['float'] <> nil) then
NodeMaterial.Params.Emission := NodeMaterial.Params.Emission * ParseFloat(Node['emission_level']['float'].Content)[0];
end;
break;
end;
NodeMaterial.SamplerName[msMask] := ''; // FIX!
if NodeMaterial.Params.Diffuse.w < 1 - EPS then
NodeMaterial.Params.Mode := rmOpacity;
if (NodeMaterial.Params.Mode = rmOpacity) and (NodeMaterial.SamplerName[msMask] = '') then
begin
NodeMaterial.Params.BlendType := btNone;
NodeMaterial.SamplerName[msAlphaMask] := 'amask';
end;
NodeMaterial.FxSkin := True;
NodeMaterial.ShaderName := 'xshader';
NodeMaterial.Params.CastShadow := True;
NodeMaterial.Params.ReceiveShadow := True;
// Add material to list
SetLength(NodeMatList, Length(NodeMatList) + 1);
NodeMatList[Length(NodeMatList) - 1] := NodeMaterial;
end;
{$ENDREGION}
end.
|
unit Chapter03._07_Solution3;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Math,
DeepStar.Utils;
// 209. Minimum Size Subarray Sum
// https://leetcode.com/problems/minimum-size-subarray-sum/description/
//
// 滑动窗口的思路
// 时间复杂度: O(n)
// 空间复杂度: O(1)
type
TSolution = class(TObject)
public
function MinSubArrayLen(arr: TArr_int; s: integer): integer;
end;
procedure Main;
implementation
procedure Main;
var
nums: TArr_int;
ret: integer;
begin
nums := [2, 3, 1, 2, 4, 3];
with TSolution.Create do
begin
ret := MinSubArrayLen(nums, 7);
Free;
end;
WriteLn(ret);
end;
{ TSolution }
function TSolution.MinSubArrayLen(arr: TArr_int; s: integer): integer;
var
l, r, sum: integer;
ret: integer;
begin
Assert((s >= 0) and (arr <> nil));
// nums[l...r]为我们的滑动窗口
l := 0;
r := -1;
sum := 0;
ret := Length(arr) + 1;
while l < Length(arr) do // 窗口的左边界在数组范围内,则循环继续
begin
if (r + 1 < Length(arr)) and (sum < s) then
begin
r += 1;
sum += arr[r];
end
else // r 已经到头 或者 sum >= s
begin
sum -= arr[l];
l += 1;
end;
if sum >= s then
ret := Min(ret, r - l + 1);
end;
if ret = Length(arr) + 1 then
Exit(0);
Result := ret;
end;
end.
|
Type Tboard = class
protected
Forma : TForm; // форма, куда всё рисуется;
whiteCell : Tcolor; // цвета клетки
blackCell : Tcolor; // шахматной доски;
hCell : word; // длина стороны клетки;
// доска как массив для идентефикаторов фигур:
fig_board : array[1..8, 1..8] of Tid;
function get_color_cell( i, j: word ): boolean;
procedure draw;
// по позиции фигуры определяет клетку доски:
function search_rect( pos: Tposition ): TRect;
procedure show_figures;
// рисование фигур:
procedure draw_queen( pos :TPosition;
color:Tfigcolor );
procedure draw_rook ( pos :TPosition;
color:Tfigcolor );
// здесь могут быть другие фигуры...
public
// по координатам доски определяет позицию:
function search_pos( X, Y: word ): Tposition;
// запись ID фигуры в массив fig_board:
procedure entry_fig_board( ID: Tid );
procedure refresh;
constructor init( white_cell, black_cell: Tcolor;
h_cell : word; form : TForm );
end;
|
unit MathResourceImpl;
interface
uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, MathResourceIntf;
type
TMathResource = class(TInvokableClass, IMathResource)
public
function Add(A, B: Integer): Integer;
function Multiply(A, B: Integer): Integer;
end;
implementation
function TMathResource.Add(A, B: Integer): Integer;
begin
Result := A + B;
end;
function TMathResource.Multiply(A, B: Integer): Integer;
begin
Result := A * B;
end;
initialization
InvRegistry.RegisterInvokableClass(TMathResource);
end.
|
unit uExplorerPortableDeviceProvider;
interface
uses
Generics.Collections,
System.Types,
System.StrUtils,
System.SysUtils,
System.Classes,
System.Math,
Winapi.Windows,
Vcl.Graphics,
Dmitry.Utils.System,
Dmitry.Utils.ShellIcons,
Dmitry.Graphics.LayeredBitmap,
Dmitry.PathProviders,
Dmitry.PathProviders.MyComputer,
uMemory,
uExplorerPathProvider,
uConstants,
uTranslate,
uBitmapUtils,
uPortableClasses,
uPortableDeviceManager,
uAssociatedIcons,
uPortableDeviceUtils,
uShellThumbnails,
uDBForm,
uShellIntegration,
uAssociations,
uIconUtils,
uShellNamespaceUtils;
type
TPDContext = class(TObject)
public
Sender: TObject;
Item: TPathItem;
List: TPathItemCollection;
Options, ImageSize: Integer;
PacketSize: Integer;
CallBack: TLoadListCallBack;
end;
TPortableDeviceItem = class(TPathItem)
private
FDevice: IPDevice;
function GetDevice: IPDevice;
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
property Device: IPDevice read GetDevice;
public
procedure LoadDevice(Device: IPDevice);
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
end;
TPortableItem = class(TPathItem)
private
FItem: IPDItem;
FItemSize: Int64;
function GetItem: IPDItem;
protected
function GetFileSize: Int64; override;
public
function Copy: TPathItem; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
procedure LoadItem(AItem: IPDItem);
procedure ResetItem;
property Item: IPDItem read GetItem;
end;
TPortableStorageItem = class(TPortableItem)
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
public
function LoadImage(Options, ImageSize: Integer): Boolean; override;
end;
TPortableFSItem = class(TPortableItem)
private
function GetDate: TDateTime;
protected
function GetFileSize: Int64; override;
function InternalGetParent: TPathItem; override;
public
function LoadImage(Options, ImageSize: Integer): Boolean; override;
property FileSize: Int64 read GetFileSize;
property Date: TDateTime read GetDate;
end;
TPortableDirectoryItem = class(TPortableFSItem)
protected
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
public
function LoadImage(Options, ImageSize: Integer): Boolean; override;
end;
TPortableImageItem = class(TPortableFSItem)
private
FWidth: Integer;
FHeight: Integer;
protected
function InternalCreateNewInstance: TPathItem; override;
public
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
property Width: Integer read FWidth;
property Height: Integer read FHeight;
end;
TPortableVideoItem = class(TPortableFSItem)
protected
function InternalCreateNewInstance: TPathItem; override;
end;
TPortableFileItem = class(TPortableFSItem)
protected
function InternalCreateNewInstance: TPathItem; override;
end;
type
TPortableDeviceProvider = class(TExplorerPathProvider)
protected
function InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; override;
function GetTranslateID: string; override;
procedure FillDevicesCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer);
procedure FillItemsCallBack(ParentKey: string; Packet: TList<IPDItem>; var Cancel: Boolean; Context: Pointer);
function Delete(Sender: TObject; Items: TPathItemCollection; Options: TPathFeatureOptions): Boolean;
function ShowProperties(Sender: TObject; Items: TPathItemCollection; Options: TPathFeatureOptions): Boolean;
public
function ExtractPreview(Item: TPathItem; MaxWidth, MaxHeight: Integer; var Bitmap: TBitmap; var Data: TObject): Boolean; override;
function Supports(Item: TPathItem): Boolean; overload; override;
function Supports(Path: string): Boolean; overload; override;
function SupportsFeature(Feature: string): Boolean; override;
function ExecuteFeature(Sender: TObject; Items: TPathItemCollection; Feature: string; Options: TPathFeatureOptions): Boolean; override;
function CreateFromPath(Path: string): TPathItem; override;
end;
function CreatePortableFSItem(Item: IPDItem; Options, ImageSize: Integer): TPortableItem;
implementation
function IsDeviceStoragePath(Path: string): Boolean;
begin
Result := False;
if StartsText(cDevicesPath + '\', Path) then
begin
Delete(Path, 1, Length(cDevicesPath + '\'));
Result := (Pos('\', Path) > 0) and (Pos('\', Path) = LastDelimiter('\', Path));
end;
end;
function CreatePortableFSItem(Item: IPDItem; Options, ImageSize: Integer): TPortableItem;
var
ItemPath: string;
ItemType: TPortableItemType;
begin
Result := nil;
ItemPath := PortableItemNameCache.GetPathByKey(Item.DeviceID, Item.ItemKey);
ItemPath := cDevicesPath + '\' + Item.DeviceName + ItemPath;
ItemType := Item.ItemType;
if IsVideoFile(ItemPath) then
ItemType := piVideo;
if IsGraphicFile(ItemPath) then
ItemType := piImage;
case ItemType of
piStorage:
begin
Result := TPortableStorageItem.CreateFromPath(ItemPath, Options, ImageSize);
Result.LoadItem(Item);
end;
piDirectory:
begin
Result := TPortableDirectoryItem.CreateFromPath(ItemPath, Options, ImageSize);
Result.LoadItem(Item);
end;
piImage:
begin
Result := TPortableImageItem.CreateFromPath(ItemPath, Options, ImageSize);
TPortableImageItem(Result).FWidth := Item.Width;
TPortableImageItem(Result).FHeight := Item.Height;
Result.LoadItem(Item);
end;
piVideo:
begin
Result := TPortableVideoItem.CreateFromPath(ItemPath, Options, ImageSize);
Result.LoadItem(Item);
end;
piFile:
begin
Result := TPortableFileItem.CreateFromPath(ItemPath, Options, ImageSize);
Result.LoadItem(Item);
end;
end;
end;
function CreateItemByPath(Path: string): TPathItem;
var
ItemPath,
DeviceName: string;
Device: IPDevice;
Item: IPDItem;
begin
DeviceName := ExtractDeviceName(Path);
ItemPath := ExtractDeviceItemPath(Path);
Device := CreateDeviceManagerInstance.GetDeviceByName(DeviceName);
if Device = nil then
Exit(nil);
Item := Device.GetItemByPath(ItemPath);
if Item = nil then
Exit(nil);
Result := CreatePortableFSItem(Item, PATH_LOAD_NO_IMAGE, 0);
end;
{ TCameraProvider }
function TPortableDeviceProvider.CreateFromPath(Path: string): TPathItem;
begin
Result := nil;
if IsDeviceItemPath(Path) then
Result := CreateItemByPath(Path)
else if IsDevicePath(Path) then
Result := TPortableDeviceItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
end;
function TPortableDeviceProvider.Delete(Sender: TObject; Items: TPathItemCollection;
Options: TPathFeatureOptions): Boolean;
var
Item: TPathItem;
FSItem: TPortableFSItem;
Form: TDBForm;
DeviceName, DevicePath: string;
Device: IPDevice;
DItem: IPDItem;
MessageText: string;
FDO: TPathFeatureDeleteOptions;
Silent: Boolean;
begin
Result := False;
Form := nil;
if Sender is TDBForm then
Form := TDBForm(Sender);
FDO := TPathFeatureDeleteOptions(Options);
Device := nil;
DeviceName := '';
MessageText := '';
if Items.Count = 0 then
Exit;
Silent := False;
if FDO <> nil then
Silent := FDO.Silent;
if Items.Count = 1 then
MessageText := FormatEx(L('Do you really want to delete object "{0}"?'), [Items[0].DisplayName])
else
MessageText := FormatEx(L('Do you really want to delete {0} objects?'), [Items.Count]);
if Silent or (ID_OK = MessageBoxDB(Form.Handle, MessageText, L('Warning'), TD_BUTTON_OKCANCEL, TD_ICON_WARNING)) then
begin
for Item in Items do
begin
FSItem := Item as TPortableFSItem;
if FSItem <> nil then
begin
if (Device = nil) or (DeviceName <> ExtractDeviceName(FSItem.Path)) then
begin
DeviceName := ExtractDeviceName(FSItem.Path);
DevicePath := ExtractDeviceItemPath(FSItem.Path);
Device := CreateDeviceManagerInstance.GetDeviceByName(DeviceName);
end;
if Device <> nil then
begin
DevicePath := ExtractDeviceItemPath(FSItem.Path);
DItem := Device.GetItemByPath(DevicePath);
if DItem <> nil then
Result := Device.Delete(DItem.ItemKey);
end;
end;
end;
end;
end;
function TPortableDeviceProvider.ExecuteFeature(Sender: TObject; Items: TPathItemCollection;
Feature: string; Options: TPathFeatureOptions): Boolean;
begin
Result := inherited ExecuteFeature(Sender, Items, Feature, Options);
if Feature = PATH_FEATURE_DELETE then
Result := Delete(Sender, Items, Options);
if Feature = PATH_FEATURE_PROPERTIES then
Result := ShowProperties(Sender, Items, Options);
end;
function TPortableDeviceProvider.ExtractPreview(Item: TPathItem; MaxWidth,
MaxHeight: Integer; var Bitmap: TBitmap; var Data: TObject): Boolean;
var
PortableItem: TPathItem;
Ico: TLayeredBitmap;
begin
Result := False;
PortableItem := PathProviderManager.CreatePathItem(Item.Path);
try
if (PortableItem is TPortableImageItem) or (PortableItem is TPortableVideoItem) or (PortableItem is TPortableDeviceItem) then
begin
PortableItem.LoadImage(PATH_LOAD_NORMAL, Min(MaxWidth, MaxHeight));
if (PortableItem.Image <> nil) and (PortableItem.Image.Bitmap <> nil) then
begin
AssignBitmap(Bitmap, PortableItem.Image.Bitmap);
Result := not Bitmap.Empty;
end;
if (PortableItem.Image <> nil) and (PortableItem.Image.Icon <> nil) then
begin
Ico := TLayeredBitmap.Create;
try
TThread.Synchronize(nil,
procedure
begin
Ico.LoadFromHIcon(PortableItem.Image.Icon.Handle, ImageSizeToIconSize16_32_48(MaxWidth), ImageSizeToIconSize16_32_48(MaxHeight));
end
);
AssignBitmap(Bitmap, Ico);
Result := not Bitmap.Empty;
finally
F(Ico);
end;
end;
end;
finally
F(PortableItem);
end;
end;
procedure TPortableDeviceProvider.FillDevicesCallBack(Packet: TList<IPDevice>;
var Cancel: Boolean; Context: Pointer);
var
Device: IPDevice;
DeviceItem: TPortableDeviceItem;
C: TPDContext;
ACancel: Boolean;
begin
C := TPDContext(Context);
ACancel := False;
for Device in Packet do
begin
DeviceItem := TPortableDeviceItem.CreateFromPath(cDevicesPath + '\' + Device.Name, C.Options, C.ImageSize);
DeviceItem.LoadDevice(Device);
C.List.Add(DeviceItem);
if Assigned(C.CallBack) then
C.CallBack(C.Sender, C.Item, C.List, ACancel);
if ACancel then
begin
Cancel := True;
Break;
end;
end;
end;
procedure TPortableDeviceProvider.FillItemsCallBack(ParentKey: string;
Packet: TList<IPDItem>; var Cancel: Boolean; Context: Pointer);
var
ACancel: Boolean;
C: TPDContext;
Item: IPDItem;
PItem: TPortableItem;
begin
C := TPDContext(Context);
ACancel := False;
for Item in Packet do
begin
if not Item.IsVisible then
Continue;
if ((C.Options and PATH_LOAD_DIRECTORIES_ONLY > 0) and (Item.ItemType <> piStorage) and (Item.ItemType <> piDirectory)) then
Continue;
PItem := CreatePortableFSItem(Item, C.Options, C.ImageSize);
C.List.Add(PItem);
end;
if Assigned(C.CallBack) then
C.CallBack(C.Sender, C.Item, C.List, ACancel);
if ACancel then
Cancel := True;
end;
function TPortableDeviceProvider.GetTranslateID: string;
begin
Result := 'PortableDevicesProvider';
end;
function TPortableDeviceProvider.InternalFillChildList(Sender: TObject; Item: TPathItem;
List: TPathItemCollection; Options, ImageSize, PacketSize: Integer;
CallBack: TLoadListCallBack): Boolean;
var
Dev: IPDevice;
Context: TPDContext;
DevName, DevItemPath, ItemKey: string;
begin
Result := True;
if Options and PATH_LOAD_ONLY_FILE_SYSTEM > 0 then
Exit;
Context := TPDContext.Create;
try
Context.Sender := Sender;
Context.Item := Item;
Context.List := List;
Context.Options := Options;
Context.ImageSize := ImageSize;
Context.CallBack := CallBack;
if Item is THomeItem then
CreateDeviceManagerInstance.FillDevicesWithCallBack(FillDevicesCallBack, Context);
if Item is TPortableDeviceItem then
begin
Dev := CreateDeviceManagerInstance.GetDeviceByName(Item.DisplayName);
if Dev <> nil then
Dev.FillItemsWithCallBack('', FillItemsCallBack, Context);
end;
if (Item is TPortableStorageItem) or (Item is TPortableDirectoryItem) then
begin
DevName := ExtractDeviceName(Item.Path);
DevItemPath := ExtractDeviceItemPath(Item.Path);
Dev := CreateDeviceManagerInstance.GetDeviceByName(DevName);
if Dev <> nil then
begin
ItemKey := PortableItemNameCache.GetKeyByPath(Dev.DeviceID, DevItemPath);
Dev.FillItemsWithCallBack(ItemKey, FillItemsCallBack, Context);
end;
end;
finally
F(Context);
end;
end;
function TPortableDeviceProvider.Supports(Item: TPathItem): Boolean;
begin
Result := Item is TPortableDeviceItem;
Result := Result or Supports(Item.Path);
end;
function TPortableDeviceProvider.ShowProperties(Sender: TObject;
Items: TPathItemCollection; Options: TPathFeatureOptions): Boolean;
var
Form: TDBForm;
Path: string;
List: TStrings;
Item: TPathItem;
begin
Result := False;
Form := TDBForm(Sender);
if Items.Count = 0 then
Exit;
if Items.Count = 1 then
Result := ExecuteShellPathRelativeToMyComputerMenuAction(Form.Handle, PhotoDBPathToDevicePath(Items[0].Path), nil, Point(0, 0), nil, 'Properties')
else
begin
Path := PhotoDBPathToDevicePath(ExtractFileDir(Items[0].Path));
List := TStringList.Create;
try
for Item in Items do
List.Add(ExtractFileName(Item.Path));
Result := ExecuteShellPathRelativeToMyComputerMenuAction(Form.Handle, Path, List, Point(0, 0), nil, 'Properties');
finally
F(List);
end;
end;
end;
function TPortableDeviceProvider.Supports(Path: string): Boolean;
begin
Result := StartsText(cDevicesPath, Path);
end;
function TPortableDeviceProvider.SupportsFeature(Feature: string): Boolean;
begin
Result := Feature = PATH_FEATURE_DELETE;
Result := Result or (Feature = PATH_FEATURE_PROPERTIES);
end;
{ TPortableDeviceItem }
constructor TPortableDeviceItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited CreateFromPath(APath, Options, ImageSize);
FDevice := nil;
FPath := cDevicesPath;
FDisplayName := TA('Camera', 'Path');
if Length(APath) > Length(cDevicesPath) then
begin
Delete(APath, 1, Length(cDevicesPath) + 1);
FDisplayName := APath;
FPath := cDevicesPath + '\' + FDisplayName;
end;
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
function TPortableDeviceItem.GetDevice: IPDevice;
var
DevName: string;
begin
if FDevice = nil then
begin
DevName := ExtractDeviceName(Path);
FDevice := CreateDeviceManagerInstance.GetDeviceByName(DevName);
end;
Result := FDevice;
end;
function TPortableDeviceItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TPortableDeviceItem.InternalCreateNewInstance: TPathItem;
begin
Result := TPortableDeviceItem.Create;
end;
function TPortableDeviceItem.InternalGetParent: TPathItem;
begin
Result := THomeItem.Create;
end;
function TPortableDeviceItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
DevIcon: string;
begin
F(FImage);
DevIcon := 'DEVICE';
if Device <> nil then
begin
case Device.DeviceType of
dtCamera:
DevIcon := 'CAMERA';
dtVideo:
DevIcon := 'VIDEO';
dtPhone:
DevIcon := 'PHONE';
end;
end;
FindIcon(HInstance, DevIcon, ImageSizeToIconSize16_32_48(ImageSize), 32, Icon);
if Icon = nil then
FindIcon(HInstance, DevIcon, ImageSizeToIconSize16_32_48(ImageSize), 8, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
procedure TPortableDeviceItem.LoadDevice(Device: IPDevice);
begin
FDevice := Device;
LoadImage;
end;
{ TPortableStorageItem }
function TPortableStorageItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TPortableStorageItem.InternalCreateNewInstance: TPathItem;
begin
Result := TPortableStorageItem.Create;
end;
function TPortableStorageItem.InternalGetParent: TPathItem;
var
DevName: string;
begin
DevName := ExtractDeviceName(Path);
Result := TPortableDeviceItem.CreateFromPath(cDevicesPath + '\' + DevName, PATH_LOAD_NO_IMAGE, 0);
end;
function TPortableStorageItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
begin
F(FImage);
FindIcon(HInstance, 'STORAGE', ImageSizeToIconSize16_32_48(ImageSize), 32, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
{ TPortableItem }
function TPortableItem.Copy: TPathItem;
begin
Result := inherited Copy;
//WIA will be null, WPD the same item
//WIA doesn't support calls from other threads so we can'r use the same item
if FItem <> nil then
TPortableItem(Result).FItem := FItem.Clone
else
TPortableItem(Result).FItem := nil;
TPortableItem(Result).FItemSize := FItemSize;
end;
constructor TPortableItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
FItem := nil;
FItemSize := 0;
DisplayName := ExtractFileName(Path);
end;
function TPortableItem.GetFileSize: Int64;
begin
Result := FItemSize;
end;
function TPortableItem.GetItem: IPDItem;
var
DevName: string;
ItemPath: string;
Device: IPDevice;
begin
if FItem = nil then
begin
DevName := ExtractDeviceName(Path);
ItemPath := ExtractDeviceItemPath(Path);
Device := CreateDeviceManagerInstance.GetDeviceByName(DevName);
if (Device <> nil) then
FItem := Device.GetItemByPath(ItemPath);
end;
Result := FItem;
end;
procedure TPortableItem.LoadItem(AItem: IPDItem);
begin
FItem := AItem;
end;
procedure TPortableItem.ResetItem;
begin
FItem := nil;
end;
{ TPortableDirectoryItem }
function TPortableDirectoryItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TPortableDirectoryItem.InternalCreateNewInstance: TPathItem;
begin
Result := TPortableDirectoryItem.Create;
end;
function TPortableDirectoryItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
begin
F(FImage);
FindIcon(HInstance, 'DIRECTORY', ImageSizeToIconSize16_32_48(ImageSize), 32, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
{ TPortableFSItem }
function TPortableFSItem.GetFileSize: Int64;
begin
Result := 0;
if Item <> nil then
Result := Item.FullSize;
end;
function TPortableFSItem.InternalGetParent: TPathItem;
var
Path, ParentPath: string;
P: Integer;
begin
Path := Self.Path;
Path := ExcludeTrailingBackslash(Path);
P := LastDelimiter('\', Path);
if P < 2 then
Exit(THomeItem.Create);
ParentPath := System.Copy(Path, 1, P - 1);
if IsDeviceItemPath(ParentPath) then
begin
if not IsWPDSupport then
Exit(TPortableDirectoryItem.CreateFromPath(ParentPath, PATH_LOAD_NO_IMAGE, 0))
else
begin
if IsDeviceStoragePath(ParentPath) then
Exit(TPortableStorageItem.CreateFromPath(ParentPath, PATH_LOAD_NO_IMAGE, 0))
else
Exit(TPortableDirectoryItem.CreateFromPath(ParentPath, PATH_LOAD_NO_IMAGE, 0))
end;
end;
if IsDevicePath(ParentPath) then
Exit(TPortableDeviceItem.CreateFromPath(ParentPath, PATH_LOAD_NO_IMAGE, 0));
Exit(THomeItem.Create);
end;
function TPortableFSItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
It: IPDItem;
Icon: TIcon;
Bitmap: TBitmap;
Ico: HIcon;
begin
It := Item;
Icon := nil;
F(FImage);
if Item = nil then
begin
FindIcon(HInstance, 'SIMPLEFILE', ImageSizeToIconSize16_32_48(ImageSize), 32, Icon);
FImage := TPathImage.Create(Icon);
Exit(True);
end;
Bitmap := TBitmap.Create;
try
if Item.ExtractPreview(Bitmap) then
begin
KeepProportions(Bitmap, ImageSize, ImageSize);
if IsVideoFile(Path) then
UpdateBitmapToVideo(Bitmap);
FImage := TPathImage.Create(Bitmap);
Bitmap := nil;
Exit(True);
end;
finally
F(Bitmap);
end;
Ico := ExtractDefaultAssociatedIcon('*' + ExtractFileExt(Path), ImageSizeToIconSize16_32_48(ImageSize));
if Ico <> 0 then
begin
FImage := TPathImage.Create(Ico);
Exit(True);
end;
FindIcon(HInstance, 'SIMPLEFILE', ImageSizeToIconSize16_32_48(ImageSize), 32, Icon);
FImage := TPathImage.Create(Icon);
Exit(True);
end;
function TPortableFSItem.GetDate: TDateTime;
begin
Result := MinDateTime;
if Item <> nil then
Result := Item.ItemDate;
end;
{ TPortableImageItem }
constructor TPortableImageItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited CreateFromPath(APath, Options, ImageSize);
FWidth := 0;
FHeight := 0;
end;
function TPortableImageItem.InternalCreateNewInstance: TPathItem;
begin
Result := TPortableImageItem.Create;
end;
{ TPortableVideoItem }
function TPortableVideoItem.InternalCreateNewInstance: TPathItem;
begin
Result := TPortableVideoItem.Create;
end;
{ TPortableFileItem }
function TPortableFileItem.InternalCreateNewInstance: TPathItem;
begin
Result := TPortableVideoItem.Create;
end;
end.
|
unit PhpEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ComCtrls, ToolWin,
LMDCustomScrollBox, LMDScrollBox, LMDSplt,
LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
EasyEditor, EasyEditSource, EasyClasses, EasyParser,
CodeExplorer;
type
TPhpEditForm = class(TForm)
PhpParser: TEasyEditorParser;
Source: TEasyEditSource;
ChangeTimer: TTimer;
LMDSplitterPanel1: TLMDSplitterPanel;
ExplorerPane: TLMDSplitterPane;
LMDSplitterPane2: TLMDSplitterPane;
Edit: TEasyEdit;
ToolBar1: TToolBar;
CollapseButton: TToolButton;
procedure FormCreate(Sender: TObject);
procedure EditSourceChanged(Sender: TObject;
State: TEasyEditSourceStates);
procedure ChangeTimerTimer(Sender: TObject);
procedure EditAutoComplete(Sender: TObject; Strings: TStrings;
AKey: Char; var AllowPopup: Boolean);
procedure CollapseButtonClick(Sender: TObject);
private
FOnModified: TNotifyEvent;
procedure SetStrings(const Value: TStrings);
protected
function GetStrings: TStrings;
procedure Modified;
procedure LazyUpdate;
public
CodeExplorerForm: TCodeExplorerForm;
property OnModified: TNotifyEvent read FOnModified write FOnModified;
property Strings: TStrings read GetStrings write SetStrings;
end;
var
PhpEditForm: TPhpEditForm;
implementation
uses
LrUtils;
{$R *.dfm}
procedure TPhpEditForm.FormCreate(Sender: TObject);
begin
AddForm(CodeExplorerForm, TCodeExplorerForm, ExplorerPane);
CodeExplorerForm.EasyEdit := Edit;
end;
procedure TPhpEditForm.EditSourceChanged(Sender: TObject;
State: TEasyEditSourceStates);
begin
if (State <> [csPositionChanged]) or ChangeTimer.Enabled then
if Edit.Modified then
begin
ChangeTimer.Enabled := false;
ChangeTimer.Enabled := true;
Modified;
end;
end;
procedure TPhpEditForm.Modified;
begin
if {Edit.Modified and} Assigned(OnModified) then
OnModified(Self);
end;
procedure TPhpEditForm.ChangeTimerTimer(Sender: TObject);
begin
ChangeTimer.Enabled := false;
LazyUpdate;
end;
procedure TPhpEditForm.LazyUpdate;
begin
CodeExplorerForm.UpdateExplorer;
end;
function TPhpEditForm.GetStrings: TStrings;
begin
Result := Source.Strings;
end;
procedure TPhpEditForm.SetStrings(const Value: TStrings);
begin
Source.Strings.Assign(Value);
LazyUpdate;
end;
procedure TPhpEditForm.EditAutoComplete(Sender: TObject; Strings: TStrings;
AKey: Char; var AllowPopup: Boolean);
begin
//
end;
procedure TPhpEditForm.CollapseButtonClick(Sender: TObject);
begin
if CollapseButton.Down then
Edit.CollapseCode([ '{' ], [ '}'], [ {'*'} ], [], true, true, true, true)
else
Edit.UnCollapseCode;
end;
end.
|
unit htColumnPanel;
interface
uses
Windows, SysUtils, Types, Classes, Controls, Graphics,
htInterfaces, htMarkup, htControls;
type
ThtCustomColumnPanel = class(ThtCustomControl)
private
FLeftPanel: ThtPanel;
FClientPanel: ThtPanel;
FLeftWidth: Integer;
procedure SetLeftWidth(const Value: Integer);
protected
procedure GenerateCtrls(inMarkup: ThtMarkup);
procedure GenerateCtrl(inMarkup: ThtMarkup; const inContainer: string;
inCtrl: TControl);
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); override;
property LeftWidth: Integer read FLeftWidth write SetLeftWidth;
end;
//
ThtColumnPanel = class(ThtCustomColumnPanel)
published
property Align;
property Outline;
property Style;
property Transparent;
property Visible;
end;
implementation
uses
LrVclUtils, LrControlIterator;
{ ThtCustomColumnPanel }
constructor ThtCustomColumnPanel.Create(inOwner: TComponent);
begin
inherited;
//ControlStyle := ControlStyle + [ csAcceptsControls ];
FLeftPanel := ThtPanel.Create(Self);
FLeftPanel.Align := alLeft;
FLeftPanel.Outline := true;
FClientPanel := ThtPanel.Create(Self);
FClientPanel.Align := alClient;
end;
destructor ThtCustomColumnPanel.Destroy;
begin
inherited;
end;
procedure ThtCustomColumnPanel.SetLeftWidth(const Value: Integer);
begin
FLeftWidth := Value;
FLeftPanel.Width := FLeftWidth;
end;
procedure ThtCustomColumnPanel.GenerateCtrl(inMarkup: ThtMarkup;
const inContainer: string; inCtrl: TControl);
var
c: IhtControl;
begin
if LrIsAs(inCtrl, IhtControl, c) then
c.Generate(inContainer, inMarkup)
else
inMarkup.Add(inCtrl.Name);
end;
procedure ThtCustomColumnPanel.GenerateCtrls(inMarkup: ThtMarkup);
begin
with TLrCtrlIterator.Create(Self) do
try
while Next do
GenerateCtrl(inMarkup, Ctrl.Name, Ctrl);
finally
Free;
end;
end;
procedure ThtCustomColumnPanel.Generate(const inContainer: string;
inMarkup: ThtMarkup);
begin
GenerateStyle('#' + Name, inMarkup);
inMarkup.Styles.Add(
Format('#%s { position: relative; margin-right: 0; height: %dpx; }',
[ Name, Height ]));
inMarkup.Add(Format('<div id="%s">', [ Name ]));
GenerateCtrls(inMarkup);
inMarkup.Add('</div>');
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 170649
////////////////////////////////////////////////////////////////////////////////
unit android.provider.Telephony_Mms_Outbox;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.net.Uri;
type
JTelephony_Mms_Outbox = interface;
JTelephony_Mms_OutboxClass = interface(JObjectClass)
['{054ECA86-F010-4F31-9E77-446A71586901}']
function _GetCONTENT_URI : JUri; cdecl; // A: $19
function _GetDEFAULT_SORT_ORDER : JString; cdecl; // A: $19
property CONTENT_URI : JUri read _GetCONTENT_URI; // Landroid/net/Uri; A: $19
property DEFAULT_SORT_ORDER : JString read _GetDEFAULT_SORT_ORDER; // Ljava/lang/String; A: $19
end;
[JavaSignature('android/provider/Telephony_Mms_Outbox')]
JTelephony_Mms_Outbox = interface(JObject)
['{1CAE3A40-2BF5-4EF0-A9E3-866D4BE8153A}']
end;
TJTelephony_Mms_Outbox = class(TJavaGenericImport<JTelephony_Mms_OutboxClass, JTelephony_Mms_Outbox>)
end;
const
TJTelephony_Mms_OutboxDEFAULT_SORT_ORDER = 'date DESC';
implementation
end.
|
unit NormalsMeshPlugin;
interface
uses MeshPluginBase, BasicMathsTypes, BasicDataTypes, GlConstants, BasicConstants,
dglOpenGL, RenderingMachine, Material, MeshBRepGeometry;
type
TNormalsMeshPlugin = class (TMeshPluginBase)
private
MeshNormalsType: byte;
MeshVerticesPerFace: byte;
MeshVertices: PAVector3f;
MeshFaces: PAUInt32;
MeshNormals: PAVector3f;
FaceType : GLINT;
NumNormals: integer;
Vertices: TAVector3f;
Faces: auint32;
Colours: TAVector4f;
Render: TRenderingMachine;
Material: TMeshMaterial;
MyMesh: Pointer;
// Mesh related
procedure BuildMesh();
procedure BuildNormalsLine(_ID: integer);
procedure BuildNormalsLineFromVector(_ID: integer; const _BasePosition: TVector3f);
protected
procedure DoRender(); override;
procedure DoUpdate(_MeshAddress: Pointer); override;
public
constructor Create; overload;
constructor Create(const _Source: TNormalsMeshPlugin); overload;
procedure Initialize; override;
procedure Clear; override;
// Copy
procedure Assign(const _Source: TMeshPluginBase); override;
end;
implementation
uses Mesh, BasicFunctions, Math3d;
constructor TNormalsMeshPlugin.Create;
begin
FPluginType := C_MPL_NORMALS;
FaceType := GL_TRIANGLES;
Initialize;
end;
constructor TNormalsMeshPlugin.Create(const _Source: TNormalsMeshPlugin);
begin
FPluginType := C_MPL_NORMALS;
Material := TMeshMaterial.Create(nil);
Assign(_Source);
end;
procedure TNormalsMeshPlugin.Initialize;
begin
inherited Initialize;
Material := TMeshMaterial.Create(nil);
Render := TRenderingMachine.Create;
end;
procedure TNormalsMeshPlugin.Clear;
begin
Render.Free;
SetLength(Colours,0);
SetLength(Vertices,0);
SetLength(Faces,0);
Material.Free;
end;
procedure TNormalsMeshPlugin.DoUpdate(_MeshAddress: Pointer);
begin
MyMesh := _MeshAddress;
(PMesh(MyMesh))^.Geometry.GoToFirstElement;
MeshNormalsType := (PMesh(MyMesh))^.NormalsType;
MeshVerticesPerFace := ((PMesh(MyMesh))^.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace;
MeshVertices := PAVector3f(Addr((PMesh(MyMesh))^.Vertices));
if MeshNormalsType = C_NORMALS_PER_VERTEX then
begin
MeshNormals := PAVector3f(Addr((PMesh(MyMesh))^.Normals));
end
else
begin
MeshNormals := PAVector3f(Addr(((PMesh(MyMesh))^.Geometry.Current^ as TMeshBRepGeometry).Normals));
end;
NumNormals := High(MeshNormals^)+1;
MeshFaces := PAUInt32(Addr(((PMesh(MyMesh))^.Geometry.Current^ as TMeshBRepGeometry).Faces));
BuildMesh;
Render.ForceRefresh;
end;
// Rendering related.
procedure TNormalsMeshPlugin.BuildMesh();
var
Normalsx2,Normalsx3: integer;
n,v,f : integer;
begin
Normalsx2 := NumNormals * 2;
Normalsx3 := NumNormals * 3;
SetLength(Vertices,Normalsx2);
SetLength(Colours,Normalsx2);
SetLength(Faces,Normalsx3);
n := 0;
v := 0;
f := 0;
while n < NumNormals do
begin
BuildNormalsLine(n);
Colours[v] := SetVector4f(0.25,0,0,C_TRP_OPAQUE);
Faces[f] := v;
inc(v);
inc(f);
Colours[v] := SetVector4f(1,0,0,C_TRP_OPAQUE);
Faces[f] := v;
inc(f);
Faces[f] := v-1;
inc(f);
inc(v);
inc(n);
end;
end;
procedure TNormalsMeshPlugin.BuildNormalsLine(_ID: integer);
var
BasePosition: TVector3f;
i,maxi : integer;
begin
if MeshNormalsType = C_NORMALS_PER_VERTEX then
begin
BasePosition.X := (MeshVertices^)[_ID].X;
BasePosition.Y := (MeshVertices^)[_ID].Y;
BasePosition.Z := (MeshVertices^)[_ID].Z;
end
else if MeshNormalsType = C_NORMALS_PER_FACE then
begin
BasePosition := SetVector(0,0,0);
i := _ID * MeshVerticesPerFace;
maxi := i + MeshVerticesPerFace;
while i < maxi do
begin
BasePosition.X := BasePosition.X + (MeshVertices^)[(MeshFaces^)[i]].X;
BasePosition.Y := BasePosition.Y + (MeshVertices^)[(MeshFaces^)[i]].Y;
BasePosition.Z := BasePosition.Z + (MeshVertices^)[(MeshFaces^)[i]].Z;
inc(i);
end;
BasePosition.X := (BasePosition.X / MeshVerticesPerFace);
BasePosition.Y := (BasePosition.Y / MeshVerticesPerFace);
BasePosition.Z := (BasePosition.Z / MeshVerticesPerFace);
end;
BuildNormalsLineFromVector(_ID,BasePosition);
end;
procedure TNormalsMeshPlugin.BuildNormalsLineFromVector(_ID: integer; const _BasePosition: TVector3f);
var
IDx2 : integer;
begin
IDx2 := _ID * 2;
Vertices[IDx2].X := _BasePosition.X;
Vertices[IDx2].Y := _BasePosition.Y;
Vertices[IDx2].Z := _BasePosition.Z;
inc(IDx2);
Vertices[IDx2].X := _BasePosition.X + (MeshNormals^)[_ID].X;
Vertices[IDx2].Y := _BasePosition.Y + (MeshNormals^)[_ID].Y;
Vertices[IDx2].Z := _BasePosition.Z + (MeshNormals^)[_ID].Z;
end;
procedure TNormalsMeshPlugin.DoRender;
var
PolygonMode: PGLInt;
begin
Render.StartRender;
GetMem(PolygonMode,4);
glDisable(GL_LIGHTING);
glGetIntegerv(GL_POLYGON_MODE,PolygonMode);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
Material.Enable;
Render.RenderWithoutNormalsAndWithColoursPerVertex(Vertices,Colours,Faces,FaceType,3,NumNormals);
Material.Disable;
Render.FinishRender(SetVector(0,0,0));
glPolygonMode(GL_FRONT_AND_BACK,PolygonMode^);
FreeMem(PolygonMode);
glEnable(GL_LIGHTING);
end;
// Copy
procedure TNormalsMeshPlugin.Assign(const _Source: TMeshPluginBase);
var
i: integer;
begin
if _Source.PluginType = FPluginType then
begin
//Material := TMeshMaterial.Create(nil);
MeshNormalsType := (_Source as TNormalsMeshPlugin).MeshNormalsType;
MeshVerticesPerFace := (_Source as TNormalsMeshPlugin).MeshVerticesPerFace;
FaceType := (_Source as TNormalsMeshPlugin).FaceType;
NumNormals := (_Source as TNormalsMeshPlugin).NumNormals;
SetLength(Vertices, High((_Source as TNormalsMeshPlugin).Vertices) + 1);
for i := Low(Vertices) to High(Vertices) do
begin
Vertices[i].X := (_Source as TNormalsMeshPlugin).Vertices[i].X;
Vertices[i].Y := (_Source as TNormalsMeshPlugin).Vertices[i].Y;
Vertices[i].Z := (_Source as TNormalsMeshPlugin).Vertices[i].Z;
end;
SetLength(Faces, High((_Source as TNormalsMeshPlugin).Faces) + 1);
for i := Low(Faces) to High(Faces) do
begin
Faces[i] := (_Source as TNormalsMeshPlugin).Faces[i];
end;
SetLength(Colours, High((_Source as TNormalsMeshPlugin).Colours) + 1);
for i := Low(Colours) to High(Colours) do
begin
Colours[i].X := (_Source as TNormalsMeshPlugin).Colours[i].X;
Colours[i].Y := (_Source as TNormalsMeshPlugin).Colours[i].Y;
Colours[i].Z := (_Source as TNormalsMeshPlugin).Colours[i].Z;
Colours[i].W := (_Source as TNormalsMeshPlugin).Colours[i].W;
end;
Render := TRenderingMachine.Create((_Source as TNormalsMeshPlugin).Render);
end;
inherited Assign(_Source);
end;
end.
|
unit GLDUpDown;
interface
uses
Classes, Controls, StdCtrls, ComCtrls, GL;
type
TUD = class(TCustomUpDown);
TGLDUpDown = class(TCustomUpDown)
private
FMin: GLfloat;
FMax: GLfloat;
FIncrement: GLfloat;
FEdit: TEdit;
FOnChange: TNotifyEvent;
procedure SetMin(Value: GLfloat);
procedure SetMax(Value: GLfloat);
function GetPosition: GLfloat;
procedure SetPosition(Value: GLfloat);
protected
procedure ButtonClick(Button: TUDBtnType);
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure Change;
public
constructor Create(AOwner: TComponent); override;
published
property Min: GLfloat read FMin write SetMin;
property Max: GLfloat read FMax write SetMax;
property Increment: GLfloat read FIncrement write FIncrement;
property Position: GLfloat read GetPosition write SetPosition;
property Edit: TEdit read FEdit write FEdit;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property AlignButton;
property Anchors;
property ArrowKeys;
property Enabled;
property Constraints;
property Orientation;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnChanging;
property OnContextPopup;
property OnClick;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
procedure Register;
implementation
uses
SysUtils, GLDX, GLDMain;
constructor TGLDUpDown.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMin := 0;
FMax := 100;
FIncrement := 1;
FEdit := nil;
FOnChange := nil;
end;
procedure TGLDUpDown.ButtonClick(Button: TUDBtnType);
begin
case Button of
btNext: SetPosition(GetPosition + FIncrement);
btPrev: SetPosition(GetPosition - FIncrement);
end;
end;
procedure TGLDUpDown.Change;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TGLDUpDown.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
case Orientation of
udHorizontal:
if X < (Width div 2) then
ButtonClick(btPrev) else ButtonClick(btNext);
udVertical:
if Y < (Height div 2) then
ButtonClick(btNext) else ButtonClick(btPrev);
end;
end;
procedure TGLDUpDown.SetMin(Value: GLfloat);
begin
if FMin = Value then Exit;
FMin := Value;
if GetPosition < FMin then
SetPosition(FMin);
end;
procedure TGLDUpDown.SetMax(Value: GLfloat);
begin
if FMax = Value then Exit;
FMax := Value;
if GetPosition > FMax then
SetPosition(FMax);
end;
function TGLDUpDown.GetPosition: GLfloat;
begin
Result := 0;
if Assigned(FEdit) then
Result := GLDXStrToFloat(FEdit.Text);
if Result < FMin then
begin
Result := FMin;
SetPosition(FMin);
end;
if Result > FMax then
begin
Result := FMax;
SetPosition(FMax);
end;
end;
procedure TGLDUpDown.SetPosition(Value: GLfloat);
begin
if Value < FMin then SetPosition(FMin) else
if Value > FMax then SetPosition(FMax) else
if Assigned(FEdit) then
begin
FEdit.Text := FloatToStrF(Value, ffGeneral, 4, 4);
Change;
end;
end;
procedure Register;
begin
RegisterComponents('GLDraw', [TGLDUpDown]);
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFXmlReader;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefXmlReaderRef = class(TCefBaseRefCountedRef, ICefXmlReader)
protected
function MoveToNextNode: Boolean;
function Close: Boolean;
function HasError: Boolean;
function GetError: ustring;
function GetType: TCefXmlNodeType;
function GetDepth: Integer;
function GetLocalName: ustring;
function GetPrefix: ustring;
function GetQualifiedName: ustring;
function GetNamespaceUri: ustring;
function GetBaseUri: ustring;
function GetXmlLang: ustring;
function IsEmptyElement: Boolean;
function HasValue: Boolean;
function GetValue: ustring;
function HasAttributes: Boolean;
function GetAttributeCount: NativeUInt;
function GetAttributeByIndex(index: Integer): ustring;
function GetAttributeByQName(const qualifiedName: ustring): ustring;
function GetAttributeByLName(const localName, namespaceURI: ustring): ustring;
function GetInnerXml: ustring;
function GetOuterXml: ustring;
function GetLineNumber: Integer;
function MoveToAttributeByIndex(index: Integer): Boolean;
function MoveToAttributeByQName(const qualifiedName: ustring): Boolean;
function MoveToAttributeByLName(const localName, namespaceURI: ustring): Boolean;
function MoveToFirstAttribute: Boolean;
function MoveToNextAttribute: Boolean;
function MoveToCarryingElement: Boolean;
public
class function UnWrap(data: Pointer): ICefXmlReader;
class function New(const stream: ICefStreamReader;
encodingType: TCefXmlEncodingType; const URI: ustring): ICefXmlReader;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions;
function TCefXmlReaderRef.Close: Boolean;
begin
Result := PCefXmlReader(FData).close(FData) <> 0;
end;
class function TCefXmlReaderRef.New(const stream: ICefStreamReader;
encodingType: TCefXmlEncodingType; const URI: ustring): ICefXmlReader;
var
u: TCefString;
begin
u := CefString(URI);
Result := UnWrap(cef_xml_reader_create(CefGetData(stream), encodingType, @u));
end;
function TCefXmlReaderRef.GetAttributeByIndex(index: Integer): ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_attribute_byindex(FData, index));
end;
function TCefXmlReaderRef.GetAttributeByLName(const localName,
namespaceURI: ustring): ustring;
var
l, n: TCefString;
begin
l := CefString(localName);
n := CefString(namespaceURI);
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_attribute_bylname(FData, @l, @n));
end;
function TCefXmlReaderRef.GetAttributeByQName(
const qualifiedName: ustring): ustring;
var
q: TCefString;
begin
q := CefString(qualifiedName);
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_attribute_byqname(FData, @q));
end;
function TCefXmlReaderRef.GetAttributeCount: NativeUInt;
begin
Result := PCefXmlReader(FData).get_attribute_count(FData);
end;
function TCefXmlReaderRef.GetBaseUri: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_base_uri(FData));
end;
function TCefXmlReaderRef.GetDepth: Integer;
begin
Result := PCefXmlReader(FData).get_depth(FData);
end;
function TCefXmlReaderRef.GetError: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_error(FData));
end;
function TCefXmlReaderRef.GetInnerXml: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_inner_xml(FData));
end;
function TCefXmlReaderRef.GetLineNumber: Integer;
begin
Result := PCefXmlReader(FData).get_line_number(FData);
end;
function TCefXmlReaderRef.GetLocalName: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_local_name(FData));
end;
function TCefXmlReaderRef.GetNamespaceUri: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_namespace_uri(FData));
end;
function TCefXmlReaderRef.GetOuterXml: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_outer_xml(FData));
end;
function TCefXmlReaderRef.GetPrefix: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_prefix(FData));
end;
function TCefXmlReaderRef.GetQualifiedName: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_qualified_name(FData));
end;
function TCefXmlReaderRef.GetType: TCefXmlNodeType;
begin
Result := PCefXmlReader(FData).get_type(FData);
end;
function TCefXmlReaderRef.GetValue: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_value(FData));
end;
function TCefXmlReaderRef.GetXmlLang: ustring;
begin
Result := CefStringFreeAndGet(PCefXmlReader(FData).get_xml_lang(FData));
end;
function TCefXmlReaderRef.HasAttributes: Boolean;
begin
Result := PCefXmlReader(FData).has_attributes(FData) <> 0;
end;
function TCefXmlReaderRef.HasError: Boolean;
begin
Result := PCefXmlReader(FData).has_error(FData) <> 0;
end;
function TCefXmlReaderRef.HasValue: Boolean;
begin
Result := PCefXmlReader(FData).has_value(FData) <> 0;
end;
function TCefXmlReaderRef.IsEmptyElement: Boolean;
begin
Result := PCefXmlReader(FData).is_empty_element(FData) <> 0;
end;
function TCefXmlReaderRef.MoveToAttributeByIndex(index: Integer): Boolean;
begin
Result := PCefXmlReader(FData).move_to_attribute_byindex(FData, index) <> 0;
end;
function TCefXmlReaderRef.MoveToAttributeByLName(const localName,
namespaceURI: ustring): Boolean;
var
l, n: TCefString;
begin
l := CefString(localName);
n := CefString(namespaceURI);
Result := PCefXmlReader(FData).move_to_attribute_bylname(FData, @l, @n) <> 0;
end;
function TCefXmlReaderRef.MoveToAttributeByQName(
const qualifiedName: ustring): Boolean;
var
q: TCefString;
begin
q := CefString(qualifiedName);
Result := PCefXmlReader(FData).move_to_attribute_byqname(FData, @q) <> 0;
end;
function TCefXmlReaderRef.MoveToCarryingElement: Boolean;
begin
Result := PCefXmlReader(FData).move_to_carrying_element(FData) <> 0;
end;
function TCefXmlReaderRef.MoveToFirstAttribute: Boolean;
begin
Result := PCefXmlReader(FData).move_to_first_attribute(FData) <> 0;
end;
function TCefXmlReaderRef.MoveToNextAttribute: Boolean;
begin
Result := PCefXmlReader(FData).move_to_next_attribute(FData) <> 0;
end;
function TCefXmlReaderRef.MoveToNextNode: Boolean;
begin
Result := PCefXmlReader(FData).move_to_next_node(FData) <> 0;
end;
class function TCefXmlReaderRef.UnWrap(data: Pointer): ICefXmlReader;
begin
if data <> nil then
Result := Create(data) as ICefXmlReader else
Result := nil;
end;
end.
|
unit uDMReport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDMGlobalNTier, SConnect, DB, DBClient, MConnect, ImgList,
siComp, IniFiles, uUserObj;
type
TDMReport = class(TDMGlobalNTier)
ReportConn: TSharedConnection;
LuInventoryConn: TSharedConnection;
LuMaintenanceConn: TSharedConnection;
LuPurchaseConn: TSharedConnection;
LuPetConn: TSharedConnection;
LuSOConn: TSharedConnection;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
protected
procedure OnAfterConnect; override;
public
FUser : TUser;
FAppPath : String;
FConnString : String;
procedure SetReportPath;
end;
var
DMReport: TDMReport;
implementation
{$R *.dfm}
procedure TDMReport.DataModuleCreate(Sender: TObject);
begin
inherited;
FUser := TUser.Create;
SetReportPath;
end;
procedure TDMReport.SetReportPath;
var
ReportPath: String;
begin
with FAppInfo do
begin
ReportPath := ReadString('Default', 'ReportPath', '');
FAppPath := ReportPath;
LanguageDispatcher.ActiveLanguage := (StrToIntDef(DMReport.GetAppProperty('Default', 'IDLanguage'),0)+1);
if ReportPath = '' then
WriteString('Default', 'ReportPath', '');
end;
end;
procedure TDMReport.DataModuleDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FUser);
end;
procedure TDMReport.OnAfterConnect;
begin
inherited;
FConnString := ActiveConnection.AppServer.GetConnectionString;
end;
end.
|
unit Invoice.Controller.Query.Factory;
interface
uses Data.DB, Invoice.Controller.Interfaces, Invoice.Model.Interfaces, Invoice.Model.Query.Firedac;
type
TControllerQueryFactory = class(TInterfacedObject, iModelQueryFactory)
constructor Create;
destructor Destroy; Override;
class function New: iModelQueryFactory;
function Query(Connection: iModelConnection): iQuery;
end;
implementation
{ TControllerQueryFactory }
constructor TControllerQueryFactory.Create;
begin
//
end;
destructor TControllerQueryFactory.Destroy;
begin
inherited;
end;
class function TControllerQueryFactory.New: iModelQueryFactory;
begin
Result := Self.Create;
end;
function TControllerQueryFactory.Query(Connection: iModelConnection): iQuery;
begin
Result := TModelQueryFiredac.New(Connection);
end;
end.
|
{ ****************************************************************************** }
{ * linear action written by QQ 600585@qq.com * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit LinearAction;
{$INCLUDE zDefine.inc}
interface
uses CoreClasses, DoStatusIO, PascalStrings, UnicodeMixedLib;
type
TCoreActionID = Integer;
TCoreActionString = SystemString;
TCoreActionState = (asPlaying, asPause, asStop, asOver);
TCoreActionStates = set of TCoreActionState;
TCoreAction = class;
TCoreActionList = class;
TCoreActionLinear = class;
TCoreAction = class(TCoreClassObject)
public
Owner: TCoreActionList;
State: TCoreActionStates;
ID: TCoreActionID;
Desc: TCoreActionString;
constructor Create(Owner_: TCoreActionList); virtual;
destructor Destroy; override;
procedure Run(); virtual;
procedure Over(); virtual;
procedure Stop(); virtual;
procedure Pause(); virtual;
procedure Progress(deltaTime: Double); virtual;
end;
TCoreActionClass = class of TCoreAction;
TCoreActionList = class(TCoreClassObject)
protected
FSequenceList: TCoreClassListForObj;
FFocusIndex: Integer;
FLast: TCoreAction;
public
Owner: TCoreActionLinear;
constructor Create(Owner_: TCoreActionLinear);
destructor Destroy; override;
procedure Clear;
function Add(ActionClass_: TCoreActionClass): TCoreAction; overload;
procedure Run();
procedure Over();
procedure Stop();
function IsOver(): Boolean;
function IsStop(): Boolean;
property Last: TCoreAction read FLast;
procedure Progress(deltaTime: Double);
end;
TCoreActionLinear = class(TCoreClassObject)
protected
FSequenceList: TCoreClassListForObj;
FFocusIndex: Integer;
FLast: TCoreActionList;
public
constructor Create();
destructor Destroy; override;
procedure Clear;
function Add: TCoreActionList;
procedure Run();
procedure Stop();
procedure Over();
property Last: TCoreActionList read FLast;
procedure Progress(deltaTime: Double);
class procedure Test();
end;
implementation
constructor TCoreAction.Create(Owner_: TCoreActionList);
begin
inherited Create;
Owner := Owner_;
State := [];
ID := 0;
Desc := '';
end;
destructor TCoreAction.Destroy;
begin
inherited Destroy;
end;
procedure TCoreAction.Run;
begin
State := [asPlaying];
end;
procedure TCoreAction.Over;
begin
if asPlaying in State then
State := [asOver];
end;
procedure TCoreAction.Stop;
begin
if asPlaying in State then
State := [asStop];
end;
procedure TCoreAction.Pause;
begin
if asPlaying in State then
State := [asPlaying, asPause];
end;
procedure TCoreAction.Progress(deltaTime: Double);
begin
end;
constructor TCoreActionList.Create(Owner_: TCoreActionLinear);
begin
inherited Create;
FSequenceList := TCoreClassListForObj.Create;
FFocusIndex := -1;
FLast := nil;
Owner := Owner_;
end;
destructor TCoreActionList.Destroy;
begin
Clear;
DisposeObject(FSequenceList);
inherited Destroy;
end;
procedure TCoreActionList.Clear;
var
i: Integer;
begin
for i := FSequenceList.Count - 1 downto 0 do
DisposeObject(FSequenceList[i]);
FSequenceList.Clear;
end;
function TCoreActionList.Add(ActionClass_: TCoreActionClass): TCoreAction;
begin
Result := ActionClass_.Create(Self);
FSequenceList.Add(Result);
end;
procedure TCoreActionList.Run();
begin
if FSequenceList.Count > 0 then
begin
FFocusIndex := 0;
FLast := FSequenceList[FFocusIndex] as TCoreAction;
end
else
begin
FFocusIndex := -1;
FLast := nil;
end;
end;
procedure TCoreActionList.Over;
begin
if FLast <> nil then
FFocusIndex := FSequenceList.Count;
end;
procedure TCoreActionList.Stop;
begin
if FLast <> nil then
FFocusIndex := -1;
end;
function TCoreActionList.IsOver: Boolean;
begin
Result := FFocusIndex >= FSequenceList.Count;
end;
function TCoreActionList.IsStop: Boolean;
begin
Result := FFocusIndex < 0;
end;
procedure TCoreActionList.Progress(deltaTime: Double);
begin
if (FFocusIndex < 0) or (FFocusIndex >= FSequenceList.Count) then
Exit;
FLast := FSequenceList[FFocusIndex] as TCoreAction;
if FLast.State = [] then
begin
FLast.Run;
Exit;
end;
if asPlaying in FLast.State then
begin
FLast.Progress(deltaTime);
Exit;
end;
if asStop in FLast.State then
begin
FFocusIndex := -1;
if Owner <> nil then
Owner.Stop;
Exit;
end;
if asOver in FLast.State then
begin
inc(FFocusIndex);
if (FFocusIndex >= FSequenceList.Count) and (Owner <> nil) then
Owner.Over;
Exit;
end;
end;
constructor TCoreActionLinear.Create();
begin
inherited Create;
FSequenceList := TCoreClassListForObj.Create;
FFocusIndex := -1;
FLast := nil;
end;
destructor TCoreActionLinear.Destroy;
begin
Clear;
DisposeObject(FSequenceList);
inherited Destroy;
end;
procedure TCoreActionLinear.Clear;
var
i: Integer;
begin
for i := FSequenceList.Count - 1 downto 0 do
DisposeObject(FSequenceList[i]);
FSequenceList.Clear;
FFocusIndex := -1;
FLast := nil;
end;
function TCoreActionLinear.Add: TCoreActionList;
begin
Result := TCoreActionList.Create(Self);
FSequenceList.Add(Result);
end;
procedure TCoreActionLinear.Run;
begin
if FSequenceList.Count > 0 then
begin
FFocusIndex := 0;
FLast := FSequenceList[FFocusIndex] as TCoreActionList;
end
else
begin
FFocusIndex := -1;
FLast := nil;
end;
end;
procedure TCoreActionLinear.Stop;
begin
Clear;
end;
procedure TCoreActionLinear.Over;
begin
inc(FFocusIndex);
if FFocusIndex < FSequenceList.Count then
begin
FLast := FSequenceList[FFocusIndex] as TCoreActionList;
end
else
begin
Clear;
end;
end;
procedure TCoreActionLinear.Progress(deltaTime: Double);
begin
if FLast <> nil then
FLast.Progress(deltaTime);
end;
class procedure TCoreActionLinear.Test();
var
al: TCoreActionList;
i: Integer;
begin
al := TCoreActionList.Create(nil);
for i := 1 to 2 do
with al.Add(TCoreAction) do
begin
ID := i;
Desc := PFormat('description %d', [i]);
end;
al.Run;
while True do
begin
al.Progress(0.1);
al.Last.Over;
if al.IsOver or al.IsStop then
Break;
end;
DisposeObject(al);
end;
end.
|
unit LoggerPro.Utils;
interface
uses
System.SysUtils;
function FileVersion(const FileName: TFileName): string;
function AppPath: string;
function WUserName: string;
implementation
uses
Winapi.Windows, System.IOUtils;
var
GAppPath: string = '';
function WUserName: string;
var
nSize: DWord;
begin
nSize := 1024;
SetLength(Result, nSize);
if GetUserName(PChar(Result), nSize) then
SetLength(Result, nSize - 1)
else
RaiseLastOSError;
end;
function FileVersion(const FileName: TFileName): string;
var
VerInfoSize: Cardinal;
VerValueSize: Cardinal;
Dummy: Cardinal;
PVerInfo: Pointer;
PVerValue: PVSFixedFileInfo;
begin
Result := '';
VerInfoSize := GetFileVersionInfoSize(PChar(FileName), Dummy);
GetMem(PVerInfo, VerInfoSize);
try
if GetFileVersionInfo(PChar(FileName), 0, VerInfoSize, PVerInfo) then
if VerQueryValue(PVerInfo, '\', Pointer(PVerValue), VerValueSize) then
with PVerValue^ do
Result := Format('v%d.%d.%d build %d', [
HiWord(dwFileVersionMS), // Major
LoWord(dwFileVersionMS), // Minor
HiWord(dwFileVersionLS), // Release
LoWord(dwFileVersionLS)]); // Build
finally
FreeMem(PVerInfo, VerInfoSize);
end;
end;
function AppPath: string;
begin
Result := GAppPath;
end;
initialization
GAppPath := IncludeTrailingPathDelimiter(TPath.GetDirectoryName(GetModuleName(HInstance)));
end.
|
unit kiwi.s3.interfaces;
interface
uses
System.Classes,
System.Generics.Collections,
kiwi.s3.types;
type
ikiwiS3 = interface;
ikiwiS3Client = interface
['{4B70CE57-0C46-44EF-BF88-0003E568AC08}']
function get(const pstrObjectName: string; var pstrmResult: tmemorystream; var pstrError: string): boolean;
function upload(const pstrObjectName: string; var pstrmMemoryFile: tmemorystream; var pstrError: string; pSlMetaData: tstrings = nil): boolean;
function delete(const pstrObjectName: string; var pstrError: string): boolean;
function properties(pstrObjectName: string; var pstrsProperties, pstrsMetadata: tstringlist): boolean;
end;
ikiwiS3ObjectInfo = interface
['{72D8B337-8BFC-4768-8979-75F954BBA989}']
procedure setname(const value: string);
procedure setlastModifield(const value: tdateTime);
procedure seteTag(const value: string);
procedure setsize(const value: integer);
procedure setownerID(const value: string);
procedure setdate(const value: tdatetime);
function getname: string;
function getlastModifield: tdateTime;
function geteTag: string;
function getsize: integer;
function getownerID: string;
function getdate: tdateTime;
property name: string read getname write setname;
property lastModifield: tdateTime read getlastModifield write setlastModifield;
property eTag: string read geteTag write seteTag;
property size: integer read getsize write setsize;
property ownerID: string read getownerID write setownerID;
property date: tdatetime read getdate write setdate;
end;
ikiwiS3Object = interface
['{BAD193E6-0832-4C67-AADB-32E2C587F210}']
function name(pstrobjectName: string): ikiwiS3Object;
function get(var strmFileResult: tmemoryStream): ikiwiS3;
function post(var strmFile: tmemoryStream): ikiwiS3;
function delete(strFile: string): boolean;
function properties(var kiwiS3ObjectInfo: ikiwiS3ObjectInfo): ikiwiS3;
end;
ikiwiS3Bucket = interface
['{32FD45C0-358B-4490-8AB7-BBCA0C6B6918}']
function name(pstrBucket: string): ikiwiS3Bucket; overload;
function find(var pListFiles : TList<ikiwiS3ObjectInfo>; pstrFilterOptions: string = ''; pstrFindFile: string = ''): ikiwiS3; overload;
function &object(pstrFileName: string): ikiwiS3Object; overload;
function getbucket: string; overload;
property bucket: string read getbucket;
end;
ikiwiS3 = interface
['{0968AEE5-DA95-4826-B663-FFC83E7E4162}']
function bucket(pstrBucket: string): ikiwiS3Bucket; overload;
function getaccountKey: string; overload;
function getaccountName: string; overload;
function getregion: string; overload;
function getaccelerate: boolean; overload;
property accountName: string read getaccountName;
property accountKey: string read getaccountKey;
property region: string read getregion;
property accelerate: boolean read getaccelerate;
end;
{
tKiwiS3
.new(key, privatekey, region)
.bucket('s3-xdental-dt-00948480-299348228834-')
.find(objectList);
tKiwiS3
.new(key, privatekey, region)
.bucket('s3-xdental-dt-00948480-299348228834-')
objects()
.get()
.post()
.delte()
.property();
}
implementation
end.
|
program deretfibonacci;
type
UkPolozka = ^Polozka;
UkHodnota = ^Hodnota;
TypUdaj = (typretez, typcele, typrealne, typlogik, typpole, typobjekt);
VarZaznam = record
case Uda9j: TypUdaj of
typretez: (case retez: TypUdaj of
typcele: (celeng: word);
)
;
typcele (cele: word);
typrealne: (realne: single);
typlogik: (logik: boolean);
typpole: (pole: UkHodnota);
typobjekt: (objekt: UkPolozka);
end
;
Polozka = record
Nazev: string;
Hodn: (askus, bakus);
Dalsi: UkPolozka
end;
Hodnota = record
Hodn: VarZaznam;
Dalsi: UkHodnota
end;
var a, b, c, d, f : integer;
procedure findMin(x, y, z: integer; var m: integer);
begin
if x < y then
m := x
else
m := y;
if z <m then
m := z;
end;
function fibonacci(n: integer; n: integer): integer;
begin
if n=1 then
fibonacci := 0
else if n=2 then
fibonacci := 1
else
fibonacci := fibonacci(n-1) + fibonacci(n-2);
end;
procedure findMin(x, y, z: integer; var m: integer);
begin
if x < y then
m := x
else
m := y;
if z <m then
m := z;
end;
begin
writeln(a xor b);
writeln;
a := 'a';
write('Masukkan Jumlah Deret : ');
readln(a);
write('Deret Fibonacci ');
d := 0.0;
f := 1;
c := 0;
case (grade) of
'A' : writeln('Excellent!' );
'B', 'C': writeln('Well done' );
'D' : writeln('You passed' );
'F' : writeln('Better try again' );
end;
if not ( a > 2) or not (a > a + 0) then
writeln('a is less than 20' )
else
writeln('a is not less than 20', a );
writeln('value of a is : ', a);
writeln('Your grade is ', grade );
for b := 1 to a do
begin
c := d + c +d;
d :=f;
f :=c;
write(c);
write(' ');
end;
readln;
end. |
unit uOrderItemEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, uFormControl, uFControl, uLabeledFControl,
uCharControl, uIntControl, uMemoControl, uInvisControl, ActnList;
type
TfmOrderItemEdit = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
FormControl: TqFFormControl;
NumItem: TqFIntControl;
ItemText: TqFMemoControl;
Id_Order: TqFInvisControl;
ActionList1: TActionList;
AcceptAction: TAction;
procedure AcceptActionExecute(Sender: TObject);
private
{ Private declarations }
public
procedure Prepare(Id_Order: Integer);
end;
var
fmOrderItemEdit: TfmOrderItemEdit;
implementation
{$R *.dfm}
procedure TfmOrderItemEdit.Prepare(Id_Order: Integer);
begin
Self.Id_Order.Value := Id_Order;
end;
procedure TfmOrderItemEdit.AcceptActionExecute(Sender: TObject);
begin
FormControl.Ok;
end;
initialization
RegisterClass(TfmOrderItemEdit);
end.
|
unit API_DBModels;
interface
uses
System.JSON
,System.Generics.Collections
,System.SysUtils
,Data.DB
,FireDAC.Stan.Param
,FireDAC.Comp.Client
,API_MVC
,API_Files
,API_DBases;
type
// миграция данных
TDataMigrate = class(TModelAbstract)
private
FSource: TDBEngine;
FDestination: TDBEngine;
FRulesFile: String;
FPreScriptFile: String;
FPostScriptFile: String;
function SetQueries(SourceTable: string; jsnTableRule: TJSONObject; FieldCode: TObjectDictionary<String,TDictionary<string,string>>): TList<String>;
function CheckAndGetDublicateID(TableName: string; params: TFDParams; FieldCode: TObjectDictionary<String,TDictionary<string,string>>): Integer;
procedure GetValueForParam(Value: Variant; Param: TFDParam);
procedure MoveRecord(dsSource, dsDestination: TFDQuery; Queries: TList<string>; FieldCode: TObjectDictionary<String,TDictionary<string,string>>);
procedure InputDataParce; override;
procedure ScriptsExcute(jsnScripts: TJSONObject; TableName: string);
public
procedure Excute; override;
end;
implementation
procedure TDataMigrate.ScriptsExcute(jsnScripts: TJSONObject; TableName: string);
var
sql: string;
jsnQueries: TJSONArray;
jsnQuery: TJSONValue;
begin
if jsnScripts=nil then exit;
jsnQueries:=jsnScripts.Values[TableName] as TJSONArray;
if jsnQueries=nil then exit;
for jsnQuery in jsnQueries do
begin
FDestination.SetData(jsnQuery.Value);
end;
end;
function TDataMigrate.CheckAndGetDublicateID(TableName: string; Params: TFDParams; FieldCode: TObjectDictionary<String,TDictionary<string,string>>): Integer;
var
dsDublicate: TFDQuery;
sql, FieldName: string;
i, j, pi: Integer;
Pair: TPair<string,string>;
CheckParams: TFDParams;
begin
dsDublicate:=TFDQuery.Create(nil);
dsDublicate.Connection:=Self.FDestination.Connection;
CheckParams:=TFDParams.Create;
try
sql:='SELECT id FROM '+TableName+' WHERE ';
pi:=0;
for i := 0 to Params.Count-1 do
begin
if not Params.Items[i].IsNull then
begin
if pi>0 then sql:=sql+' AND ';
FieldName:='';
for Pair in FieldCode.Items[TableName] do
if UpperCase(Pair.Value)=Params.Items[i].Name then FieldName:=Pair.Key;
sql:=sql+FieldName+'=:'+Params.Items[i].Name;
CheckParams.CreateParam(Params.Items[i].DataType, Params.Items[i].Name, Params.Items[i].ParamType);
CheckParams.Items[CheckParams.Count-1].Value:=Params.Items[i].Value;
inc(pi);
end;
end;
dsDublicate.Close;
dsDublicate.SQL.Text:=sql;
dsDublicate.Params:=CheckParams;
dsDublicate.Open;
dsDublicate.FetchAll;
Result:=dsDublicate.Fields[0].AsInteger;
finally
dsDublicate.Free;
CheckParams.Free;
end;
end;
procedure TDataMigrate.GetValueForParam(Value: Variant; Param: TFDParam);
var
ParamType: TFieldType;
begin
ParamType:=Param.DataType;
if ParamType in [ftFloat, ftInteger, ftCurrency] then
begin
Param.AsFloat:=Value;
Exit;
end;
if (ParamType in [ftDate, ftDateTime])
or (StrToDateDef(string(Value),0)>0)
then
begin
Param.AsDate:=StrToDateDef(string(Value),0);
Exit;
end;
if ParamType in [ftBoolean] then
begin
Param.AsInteger:=Integer(Value);
Exit;
end;
Param.AsString:=string(Value);
end;
procedure TDataMigrate.MoveRecord(dsSource, dsDestination: TFDQuery; Queries: TList<string>; FieldCode: TObjectDictionary<String,TDictionary<string,string>>);
var
i, j: Integer;
TableName: string;
SourceFieldName: string;
ExtRecordIDs: TDictionary<string,integer>;
DublicateID: integer;
begin
ExtRecordIDs:=TDictionary<string,integer>.Create;
try
for i:=0 to Queries.Count-1 do
begin
// имя таблицы
TableName:=Queries.Items[i].Split([#32])[2];
// подключаем текст sql
dsDestination.Close;
dsDestination.SQL.Text:=Queries.Items[i];
// перебираем параметры и заполняем их
for j := 0 to dsDestination.ParamCount-1 do
begin
SourceFieldName:=dsDestination.Params.Items[j].Name;
// вставляем значение
if not SourceFieldName.Contains('.') then
begin
// тип параметра = тип поля источника
dsDestination.Params.Items[j].DataType:=dsSource.FieldByName(SourceFieldName).DataType;
if not dsSource.FieldByName(SourceFieldName).IsNull then
Self.GetValueForParam(dsSource.FieldByName(SourceFieldName).Value, dsDestination.Params.Items[j]);
end
else // вставляем ссылку на запись доп таблицы
begin
dsDestination.Params.Items[j].DataType:=ftInteger;
dsDestination.Params.Items[j].AsInteger:=ExtRecordIDs.Items[LowerCase(SourceFieldName.Split(['.'])[0])];
end;
end;
// проверяем на дубликат и вставляем запись
DublicateID:=Self.CheckAndGetDublicateID(TableName, dsDestination.Params, FieldCode);
if DublicateID=0 then
begin
dsDestination.ExecSQL;
DublicateID:=Self.CheckAndGetDublicateID(TableName, dsDestination.Params, FieldCode);
end;
// если доп. таблицы записываем id вставленной записи
if i<Queries.Count-1 then
begin
ExtRecordIDs.Add(TableName,Self.CheckAndGetDublicateID(TableName, dsDestination.Params, FieldCode));
end;
end;
finally
ExtRecordIDs.Free;
end;
end;
function TDataMigrate.SetQueries(SourceTable: string; jsnTableRule: TJSONObject; FieldCode: TObjectDictionary<String,TDictionary<string,string>>): TList<String>;
var
jsnFieldRule: TJSONPair;
jsnDivide: TJSONArray;
Key, Value, Table, Field: String;
sql, SourceSQL:string;
i: Integer;
begin
FieldCode.Clear;
for jsnFieldRule in jsnTableRule do
begin
// прямой перенос
if not (jsnFieldRule.JsonValue is TJSONArray) then
begin
if not FieldCode.ContainsKey(SourceTable) then
begin
FieldCode.Add(SourceTable, TDictionary<string,string>.Create);
end;
Key:=jsnFieldRule.JsonValue.Value;
Value:=jsnFieldRule.JsonString.Value;
FieldCode.Items[SourceTable].Add(Key,Value);
end;
// перенос с разносом id и значения в другую таблицу
if (jsnFieldRule.JsonValue is TJSONArray) then
begin
jsnDivide:=jsnFieldRule.JsonValue as TJSONArray;
Table:=jsnDivide.Items[1].Value;
if not FieldCode.ContainsKey(Table) then FieldCode.Add(Table, TDictionary<string,string>.Create);
Key:=jsnDivide.Items[2].Value;
Value:=jsnFieldRule.JsonString.Value;
FieldCode.Items[Table].Add(Key,Value);
if not FieldCode.Items[SourceTable].ContainsKey(jsnDivide.Items[0].Value) then
begin
Key:=jsnDivide.Items[0].Value;
Value:=jsnDivide.Items[1].Value+'.'+jsnDivide.Items[3].Value;
FieldCode.Items[SourceTable].Add(Key,Value);
end;
end;
end;
// формируем sql
Result:=TList<string>.Create;
for Table in FieldCode.Keys do
begin
sql:='INSERT INTO '+Table+' SET ';
i:=0;
for Field in FieldCode.Items[Table].Keys do
begin
if i>0 then sql:=sql+',';
sql:=sql+Field+'=:'+FieldCode.Items[Table].Items[Field];
inc(i);
end;
if Table=SourceTable then SourceSQL:=sql
else Result.Add(sql);
end;
if not SourceSQL.IsEmpty then Result.Add(SourceSQL); // sql основной таблицы добавляем в конец
end;
procedure TDataMigrate.InputDataParce;
begin
inherited;
FSource:=FObjData.Items['Source'] as TDBEngine;
FDestination:=FObjData.Items['Destination'] as TDBEngine;
FRulesFile:=FData.Items['RulesFileName'];
FPreScriptFile:=FData.Items['PreScriptFileName'];
FPostScriptFile:=FData.Items['PostScriptFileName'];
end;
procedure TDataMigrate.Excute;
var
jsnPreScripts: TJSONObject;
jsnPostScripts: TJSONObject;
jsnRules: TJSONObject;
jsnTableRule: TJSONPair;
dsSource: TFDQuery;
dsDestination: TFDQuery;
sql: String;
FieldCode: TObjectDictionary<String,TDictionary<string,string>>;
Queries: TList<String>;
RecNum: integer;
begin
FormatSettings.DecimalSeparator:='.';
jsnPreScripts:=TJSONObject.ParseJSONValue(TFilesEngine.GetTextFromFile(FPreScriptFile)) as TJSONObject;
jsnPostScripts:=TJSONObject.ParseJSONValue(TFilesEngine.GetTextFromFile(FPostScriptFile)) as TJSONObject;
jsnRules:=TJSONObject.ParseJSONValue(TFilesEngine.GetTextFromFile(FRulesFile)) as TJSONObject;
FieldCode:=TObjectDictionary<String,TDictionary<string,string>>.Create;
try
// выполнение скриптов препроцесса
Self.ScriptsExcute(jsnPreScripts, 'common');
for jsnTableRule in jsnRules do
begin
// событие
FEventData.Clear;
FEventData.Add('TableName',jsnTableRule.JsonString.Value);
Self.GenerateEvent('SetTableName');
dsSource:=TFDQuery.Create(nil);
dsDestination:=TFDQuery.Create(nil);
dsDestination.Connection:=Self.FDestination.Connection;
try
// получаем данные исходной таблицы
sql:='SELECT * FROM '+jsnTableRule.JsonString.Value;
FSource.GetData(dsSource, sql);
// составляем sql запросы по правилам
Queries:=Self.SetQueries(jsnTableRule.JsonString.Value, jsnTableRule.JsonValue as TJSONObject, FieldCode);
// для каждой записи исходной таблицы применяем запросы
dsSource.FetchAll;
// событие
FEventData.Clear;
FEventData.Add('RecCount',dsSource.RecordCount);
Self.GenerateEvent('SetRecCount');
RecNum:=0;
while not dsSource.Eof do
begin
// событие
inc(RecNum);
FEventData.Clear;
FEventData.Add('RecNum',RecNum);
Self.GenerateEvent('SetRecNum');
Self.MoveRecord(dsSource, dsDestination, Queries, FieldCode);
dsSource.Next;
end;
finally
dsSource.Free;
dsDestination.Free;
end;
end;
// выполнение скриптов постпроцесса
Self.ScriptsExcute(jsnPostScripts, 'common');
finally
jsnRules.Free;
FieldCode.Free;
end;
end;
end.
|
unit PokerGame;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses math, UCardPackHand;
type
TPoker = class
private
stage,currentBet,totalBet,score,count:integer;
P1,P2,P3:TPokerHand;
FlopHand:THand;
Pack:TPack;
public
constructor Create;
destructor Destroy; override;
function RaiseOrFold:integer;
procedure Round(cards:integer;MiddleHand:THand);
procedure Play;
procedure P2Play;
procedure P3Play;
end;
implementation
constructor TPoker.Create;
var
i: Integer;
procedure CreateGame;
begin
writeln('Creating Game...');
//======================= CREATION ===============================
inherited Create;
Pack:= TPack.Create;
writeln('Tpack made');
P1:= TPokerHand.Create;
writeln('P1 made');
P2:=TPokerHand.Create;
writeln('P2 made');
P3:=TPokerHand.Create;
writeln('[3 made');
FlopHand := THand.Create;
//================================================================
writeln('Parts Created');
for i := 1 to 100 do
begin
Pack.Shuffle; //SHUFFLE
end;
for i := 1 to 2 do //Unuseful loop for DEALING CARDS
begin
P1.AddCard(Pack.DealCard);
P2.AddCard(Pack.DealCard);
P3.AddCard(Pack.DealCard);
end;
for i := 1 to 6 do //Useful loop for DEALING CENTRE HAND
begin
FlopHand.AddCard(Pack.DealCard);
end;
P1.SetBank(100);
P2.SetBank(100);
P3.SetBank(100);
writeln('Game Created');
end;
function TPoker.RaiseOrFold:integer;
var
choice, bet:integer;
begin
P1.ShowHand;
totalBet:=P1.Getbet+P2.Getbet+P3.Getbet;
writeln('===Raise Or Fold==== ');
writeln('¦ 1) Raise or Call ¦');
writeln('¦ 2) Fold ¦');
writeln('====================');
write('1/2: ');
readln(choice);
if choice = 1 then
begin
writeln('Your total bet so far is: ',P1.Getbet);
writeln('The total bet so far is: ',totalBet);
write('How much extra would you like to bet?: ');
readln(currentBet);
P1.Setbet(currentBet);
end;
end;
procedure TPoker.Round(cards:integer;MiddleHand: THand);
var
i: integer;
begin
for i := 1 to MiddleHand.Size do
begin
writeln('Center Card [',i,'] is : ' + MiddleHand.Cards[i].GetRankAsString + ' of ' + MiddleHand.Cards[i].GetSuitAsString)
end;
end;
procedure TPoker.P2Play;
var
RaiseOr, howMuch:integer;
begin
if P2.GetRoF > 0 then
begin
if randomrange(0,10) <= 0 then
P2.Fold;
P2.Setbet(currentBet+randomrange(0,20));
end;
end;
procedure TPoker.P3Play;
begin
if P3.GetRoF > 0 then
begin
if randomrange(0,10) <= 0 then
P3.Fold;
P2.Setbet(currentBet+randomrange(0,20));
end;
end;
destructor TPoker.Destroy;
begin
writeln('destroyed');
end;
procedure TPoker.Play;
begin
P1.SetBet(P1.GetBet*-1);
P2.SetBet(P2.GetBet*-1);
P3.SetBet(P3.GetBet*-1);;
currentBet:=0;
totalBet:=0;
//Just your hand
RaiseOrFold;
P2Play;
P3Play;
//Next 3 cards
Round(3,FlopHand);
RaiseOrFold;
//Next Card
Round(4,FlopHand);
RaiseOrFold;
//Next Card and final bet
Round(5,FlopHand);
RaiseOrFold;
if (P1.GetScore > P2.GetScore) AND (P1.GetScore > P3.GetScore) then
begin
if P1.GetRoF > 0 then
begin
writeln('You Win!');
P1.SetBank(totalBet);
P2.SetBank(P2.GetBet*-1);
P3.SetBank(P3.GetBet*-1);
end;
end;
if (P2.GetScore > P1.GetScore) AND (P2.GetScore > P3.GetScore) then
begin
if P2.GetRoF > 0 then
begin
writeln('P2 Won');
P2.SetBank(totalBet);
P1.SetBank(P1.GetBet*-1);
P3.SetBank(P3.GetBet*-1);
end;
end;
if (P3.GetScore > P2.GetScore) AND (P3.GetScore > P1.GetScore) then
begin
if P1.GetRoF > 0 then
begin
writeln('P3 Won');
P3.SetBank(totalBet);
P1.SetBank(P1.GetBet*-1);
P2.SetBank(P2.GetBet*-1);
end;
end;
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Framework ORM da T2Ti
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (T2Ti.COM)
@version 2.0
******************************************************************************* }
unit T2TiORM;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils, Forms, DB, TypInfo, ZDataset, ZConnection, Dialogs, DOM,
XMLRead, XMLWrite, VO, Constantes;
type
{ TT2TiORM }
TT2TiORM = class
private
public
class procedure Conectar;
class function Inserir(pObjeto: TVO): Integer;
class function Alterar(pObjeto: TVO): Boolean;
class function Excluir(pObjeto: TVO): Boolean;
class function Consultar(pObjeto: TVO; pFiltro: String; pPagina: String): TZQuery; overload;
class function Consultar(pObjeto: TVO; pFiltro: String; pConsultaCompleta: Boolean): TListaVO; overload;
class function ConsultarUmObjeto(pObjeto: TVO; pFiltro: String; pConsultaCompleta: Boolean): TVO;
class function ComandoSQL(pConsulta: String): Boolean;
class function SelectMax(pTabela: String; pFiltro: String): Integer;
class function SelectMin(pTabela: String; pFiltro: String): Integer;
class function SelectCount(pTabela: String): Integer;
end;
implementation
var
Conexao : TZConnection;
Banco: String;
const
CAMINHO_XML = 'C:\Projetos\T2Ti ERP 2.0\Lazarus\Retaguarda\Comum\VO\';
{ TPersistencia }
{$Region 'Conexão'}
class procedure TT2TiORM.Conectar;
begin
Banco := 'MySQL';
if not Assigned(Conexao) then
begin
Conexao := TZConnection.create(nil);
if Banco = 'MySQL' then
begin
Conexao.Protocol := 'mysql';
Conexao.HostName := 'localhost';
Conexao.Database := 't2tierp';
Conexao.User := 'root';
Conexao.Password := 'root';
end;
end;
end;
{$EndRegion 'Conexão'}
{$Region 'Inserção de Dados'}
class function TT2TiORM.Inserir(pObjeto: TVO): Integer;
var
Query: TZQuery;
UltimoID: Integer;
I, J, K: Integer;
TypeData: PTypeData;
TypeInfo: PTypeInfo;
PropList: PPropList;
PropInfo: PPropInfo;
Tabela, ConsultaSQL, CamposSQL, ValoresSQL, Caminho, NomeTipo, PropriedadeXML, ColunaXML: String;
Documento: TXMLDocument;
Node: TDOMNode;
Achou: Boolean;
begin
try
Conectar;
DecimalSeparator := '.';
TypeInfo := pObjeto.ClassInfo;
TypeData := GetTypeData(TypeInfo);
// Lê no arquivo xml no disco
Caminho := CAMINHO_XML + TypeData^.UnitName + '.xml';
ReadXMLFile(Documento, Caminho);
//localiza o nome da tabela
Node := Documento.DocumentElement.FirstChild;
Tabela := Node.Attributes.Item[1].NodeValue;
ConsultaSQL := 'INSERT INTO ' + Tabela + ' ';
//preenche os nomes dos campos e valores
GetMem(PropList, TypeData^.PropCount * SizeOf(Pointer));
GetPropInfos(TypeInfo, PropList);
for I := 0 to TypeData^.PropCount - 1 do
begin
for J := 0 to (Node.ChildNodes.Count - 1) do
begin
Achou := False;
if Node.ChildNodes.Item[J].NodeName = 'property' then
begin
for K := 0 to 4 do
begin
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'name' then
PropriedadeXML := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'column' then
ColunaXML := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
end;
if PropriedadeXML = PropList^[I]^.Name then
begin
CamposSQL := CamposSQL + ColunaXML + ',';
Achou := True;
Break;
end;
end;
end;
if PropList^[I]^.Name <> 'Id' then
begin
if Achou then
begin
PropInfo := GetPropInfo(pObjeto, PropList^[I]^.Name);
NomeTipo := PropInfo^.PropType^.Name;
if PropInfo^.PropType^.Kind in [tkInteger, tkInt64] then
begin
if ((GetInt64Prop(pObjeto, PropList^[I]^.Name) <> 0) or (((GetInt64Prop(pObjeto, PropList^[I]^.Name) = 0) and ( Copy(PropList^[I]^.Name,1,2) <> 'ID')))) then
ValoresSQL := ValoresSQL + QuotedStr(IntToStr(GetInt64Prop(pObjeto, PropList^[I]^.Name))) + ','
else
ValoresSQL := ValoresSQL + 'null,';
end
else if PropInfo^.PropType^.Kind in [tkString, tkUString, tkAString] then
begin
ValoresSQL := ValoresSQL + QuotedStr(GetStrProp(pObjeto, PropList^[I]^.Name)) + ',';
end
else if PropInfo^.PropType^.Kind in [tkFloat] then
begin
if NomeTipo = 'TDateTime' then
begin
if GetFloatProp(pObjeto, PropList^[I]^.Name) > 0 then
ValoresSQL := ValoresSQL + QuotedStr(FormatDateTime('yyyy-mm-dd', GetFloatProp(pObjeto, PropList^[I]^.Name))) + ','
else
ValoresSQL := ValoresSQL + 'null,';
end
else
begin
ValoresSQL := ValoresSQL + QuotedStr(FormatFloat('0.000000', GetFloatProp(pObjeto, PropList^[I]^.Name))) + ',';
end;
end;
end;
end
else
begin
if GetInt64Prop(pObjeto, PropList^[I]^.Name) > 0 then
begin
CamposSQL := CamposSQL + 'ID,';
ValoresSQL := ValoresSQL + QuotedStr(IntToStr(GetInt64Prop(pObjeto, PropList^[I]^.Name))) + ',';
end;
end;
end;
//retirando as vírgulas que sobraram no final
Delete(CamposSQL, Length(CamposSQL), 1);
Delete(ValoresSQL, Length(ValoresSQL), 1);
ConsultaSQL := ConsultaSQL + '(' + CamposSQL + ') VALUES (' + ValoresSQL + ')';
if Banco = 'Firebird' then
begin
ConsultaSQL := ConsultaSQL + ' RETURNING ID ';
end;
Query := TZQuery.Create(nil);
try
Query.Connection := Conexao;
Query.sql.Text := ConsultaSQL;
UltimoID := 0;
if Banco = 'MySQL' then
begin
Query.ExecSQL();
Query.sql.Text := 'select LAST_INSERT_ID() as id';
Query.Open();
UltimoID := Query.FieldByName('id').AsInteger;
end
else if Banco = 'Firebird' then
begin
Query.Open;
UltimoID := Query.Fields[0].AsInteger;
end
else if Banco = 'Postgres' then
begin
Query.ExecSQL();
Query.sql.Text := 'select Max(id) as id from ' + Tabela;
Query.Open();
UltimoID := Query.FieldByName('id').AsInteger;
end
else if Banco = 'MSSQL' then
begin
Query.ExecSQL();
Query.sql.Text := 'select Max(id) as id from ' + Tabela;
Query.Open();
UltimoID := Query.FieldByName('id').AsInteger;
end;
finally
Query.Close;
Query.Free;
end;
Result := UltimoID;
finally
DecimalSeparator := ',';
FreeMem(PropList);
end;
end;
{$EndRegion}
{$Region 'Alteração de Dados'}
class function TT2TiORM.Alterar(pObjeto: TVO): Boolean;
var
Query: TZQuery;
I, J, K: Integer;
TypeData: PTypeData;
TypeInfo: PTypeInfo;
PropList: PPropList;
PropInfo: PPropInfo;
ConsultaSQL, CamposSQL, FiltroSQL, Caminho, NomeTipo, PropriedadeXML, ColunaXML: String;
Documento: TXMLDocument;
Node: TDOMNode;
begin
try
Conectar;
DecimalSeparator := '.';
TypeInfo := pObjeto.ClassInfo;
TypeData := GetTypeData(TypeInfo);
// Lê no arquivo xml no disco
Caminho := CAMINHO_XML + TypeData^.UnitName + '.xml';
ReadXMLFile(Documento, Caminho);
//localiza o nome da tabela
Node := Documento.DocumentElement.FirstChild;
ConsultaSQL := 'UPDATE ' + Node.Attributes.Item[1].NodeValue + ' SET ';
//preenche os nomes dos campos e filtro
GetMem(PropList, TypeData^.PropCount * SizeOf(Pointer));
GetPropInfos(TypeInfo, PropList);
for I := 0 to TypeData^.PropCount - 1 do
begin
for J := 0 to (Node.ChildNodes.Count - 1) do
begin
if Node.ChildNodes.Item[J].NodeName = 'property' then
begin
for K := 0 to 4 do
begin
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'name' then
PropriedadeXML := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'column' then
ColunaXML := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
end;
if PropriedadeXML = PropList^[I]^.Name then
begin
PropInfo := GetPropInfo(pObjeto, PropList^[I]^.Name);
NomeTipo := PropInfo^.PropType^.Name;
if PropInfo^.PropType^.Kind in [tkInteger, tkInt64] then
begin
if ((GetInt64Prop(pObjeto, PropList^[I]^.Name) <> 0) or (((GetInt64Prop(pObjeto, PropList^[I]^.Name) = 0) and ( Copy(PropList^[I]^.Name,1,2) <> 'ID')))) then
CamposSQL := CamposSQL + ColunaXML + ' = ' + QuotedStr(IntToStr(GetInt64Prop(pObjeto, PropList^[I]^.Name))) + ',';
end
else if PropInfo^.PropType^.Kind in [tkString, tkUString, tkAString] then
begin
if GetStrProp(pObjeto, PropList^[I]^.Name) <> '' then
begin
CamposSQL := CamposSQL + ColunaXML + ' = ' + QuotedStr(GetStrProp(pObjeto, PropList^[I]^.Name)) + ',';
end;
end
else if PropInfo^.PropType^.Kind in [tkFloat] then
begin
if NomeTipo = 'TDateTime' then
begin
if GetFloatProp(pObjeto, PropList^[I]^.Name) > 0 then
CamposSQL := CamposSQL + ColunaXML + ' = ' + QuotedStr(FormatDateTime('yyyy-mm-dd', GetFloatProp(pObjeto, PropList^[I]^.Name))) + ','
else
CamposSQL := CamposSQL + ColunaXML + ' = ' + 'null,';
end
else
begin
CamposSQL := CamposSQL + ColunaXML + ' = ' + QuotedStr(FormatFloat('0.000000', GetFloatProp(pObjeto, PropList^[I]^.Name))) + ',';
end;
end;
end;
end;
end;
if PropList^[I]^.Name = 'Id' then
begin
FiltroSQL := ' WHERE ID = ' + QuotedStr(IntToStr(GetInt64Prop(pObjeto, PropList^[I]^.Name)));
end;
end;
//retirando as vírgulas que sobraram no final
Delete(CamposSQL, Length(CamposSQL), 1);
ConsultaSQL := ConsultaSQL + CamposSQL + FiltroSQL;
Conexao := Conexao;
Query := TZQuery.Create(nil);
Query.Connection := Conexao;
Query.sql.Text := ConsultaSQL;
Query.ExecSQL();
Result := True;
finally
DecimalSeparator := ',';
FreeMem(PropList);
FreeAndNil(Query);
end;
end;
{$EndRegion}
{$Region 'Exclusão de Dados'}
class function TT2TiORM.Excluir(pObjeto: TVO): Boolean;
var
Query: TZQuery;
I: Integer;
TypeData: PTypeData;
TypeInfo: PTypeInfo;
PropList: PPropList;
ConsultaSQL, FiltroSQL, Caminho: String;
Documento: TXMLDocument;
Node: TDOMNode;
begin
try
Conectar;
TypeInfo := pObjeto.ClassInfo;
TypeData := GetTypeData(TypeInfo);
// Lê no arquivo xml no disco
Caminho := CAMINHO_XML + TypeData^.UnitName + '.xml';
ReadXMLFile(Documento, Caminho);
//localiza o nome da tabela
Node := Documento.DocumentElement.FirstChild;
ConsultaSQL := 'DELETE FROM ' + Node.Attributes.Item[1].NodeValue + ' ';
//preenche os nomes dos campos e filtro
GetMem(PropList, TypeData^.PropCount * SizeOf(Pointer));
GetPropInfos(TypeInfo, PropList);
for I := 0 to TypeData^.PropCount - 1 do
begin
if PropList^[I]^.Name = 'Id' then
begin
FiltroSQL := ' WHERE ID = ' + QuotedStr(IntToStr(GetInt64Prop(pObjeto, PropList^[I]^.Name)));
end;
end;
ConsultaSQL := ConsultaSQL + FiltroSQL;
Conexao := Conexao;
Query := TZQuery.Create(nil);
Query.Connection := Conexao;
Query.sql.Text := ConsultaSQL;
Query.ExecSQL();
Result := True;
finally
FreeAndNil(Query);
end;
end;
{$EndRegion}
{$Region 'Consultas'}
class function TT2TiORM.Consultar(pObjeto: TVO; pFiltro: String; pPagina: String): TZQuery;
var
Query: TZQuery;
TypeData: PTypeData;
TypeInfo: PTypeInfo;
Tabela, ConsultaSQL, FiltroSQL, Caminho: String;
Documento: TXMLDocument;
Node: TDOMNode;
begin
try
Conectar;
TypeInfo := pObjeto.ClassInfo;
TypeData := GetTypeData(TypeInfo);
// Lê no arquivo xml no disco
Caminho := CAMINHO_XML + TypeData^.UnitName + '.xml';
ReadXMLFile(Documento, Caminho);
//localiza o nome da tabela
Node := Documento.DocumentElement.FirstChild;
Tabela := Node.Attributes.Item[1].NodeValue;
if (Banco = 'Firebird') and (StrToInt(pPagina) >= 0) then
begin
ConsultaSQL := 'SELECT first ' + IntToStr(TConstantes.QUANTIDADE_POR_PAGINA) + ' skip ' + pPagina + ' * FROM ' + Tabela + ' ';
end
else
begin
ConsultaSQL := 'SELECT * FROM ' + Tabela + ' ';
end;
if pFiltro <> '' then
begin
FiltroSQL := ' WHERE ' + pFiltro;
end;
ConsultaSQL := ConsultaSQL + FiltroSQL;
if ((Banco = 'MySQL') or (Banco = 'Postgres')) and (StrToInt(pPagina) >= 0) then
begin
ConsultaSQL := ConsultaSQL + ' limit ' + IntToStr(TConstantes.QUANTIDADE_POR_PAGINA) + ' offset ' + pPagina;
end;
Conexao := Conexao;
Query := TZQuery.Create(nil);
Query.Connection := Conexao;
Query.sql.Text := ConsultaSQL;
Query.ExecSQL();
Result := Query;
finally
end;
end;
class function TT2TiORM.Consultar(pObjeto: TVO; pFiltro: String; pConsultaCompleta: Boolean): TListaVO;
var
Query: TZQuery;
I, J, K: Integer;
ObjetoLocal: TVO;
Campo, Propriedade, Classe, Caminho, PropriedadeXML, ColunaXML: String;
ClassRef: TPersistentClass;
Documento: TXMLDocument;
Node: TDOMNode;
begin
try
// Lê no arquivo xml no disco
Caminho := CAMINHO_XML + pObjeto.UnitName + '.xml';
ReadXMLFile(Documento, Caminho);
Node := Documento.DocumentElement.FirstChild;
Result := Nil;
Query := Consultar(pObjeto, pFiltro, '-1');
Query.Active := True;
Result := TListaVO.Create;
if not Query.IsEmpty then
begin
while not Query.EOF do
begin
Classe := pObjeto.ClassName;
ClassRef := GetClass(Classe);
ObjetoLocal := TVO(ClassRef.Create);
for I := 0 to Query.FieldCount - 1 do
begin
Campo := Query.Fields[I].DisplayName;
// Encontra o nome da propriedade no arquivo XML mapeado
for J := 0 to (Node.ChildNodes.Count - 1) do
begin
if Node.ChildNodes.Item[J].NodeName = 'property' then
begin
for K := 0 to 4 do
begin
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'name' then
PropriedadeXML := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'column' then
ColunaXML := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
end;
if ColunaXML = Campo then
begin
Propriedade := PropriedadeXML;
end;
end
else if Node.ChildNodes.Item[J].NodeName = 'id' then
begin
Propriedade := 'Id';
end;
end;
if Query.Fields[I].DataType in [ftFloat, ftDate, ftDateTime] then
begin
SetFloatProp(ObjetoLocal, Propriedade, Query.Fields[I].AsFloat);
end
else if Query.Fields[I].DataType in [ftInteger, ftSmallint, ftLargeint] then
begin
SetInt64Prop(ObjetoLocal, Propriedade, Query.Fields[I].AsInteger);
end
else if Query.Fields[I].DataType in [ftString, ftMemo, ftFixedChar] then
begin
SetStrProp(ObjetoLocal, Propriedade, Query.Fields[I].AsString);
end;
end;
Result.Add(ObjetoLocal);
Query.Next;
end;
end;
finally
end;
end;
class function TT2TiORM.ConsultarUmObjeto(pObjeto: TVO; pFiltro: String; pConsultaCompleta: Boolean): TVO;
var
Query: TZQuery;
I, J, K: Integer;
ObjetoLocal: TVO;
Campo, Propriedade, Caminho, PropriedadeXML, ColunaXML: String;
Documento: TXMLDocument;
Node: TDOMNode;
begin
try
// Lê no arquivo xml no disco
Caminho := CAMINHO_XML + pObjeto.UnitName + '.xml';
ReadXMLFile(Documento, Caminho);
Node := Documento.DocumentElement.FirstChild;
Result := Nil;
Query := Consultar(pObjeto, pFiltro, '-1');
Query.Active := True;
if not Query.IsEmpty then
begin
Query.Next;
ObjetoLocal := pObjeto;
for I := 0 to Query.FieldCount - 1 do
begin
Campo := Query.Fields[I].DisplayName;
// Encontra o nome da propriedade no arquivo XML mapeado
for J := 0 to (Node.ChildNodes.Count - 1) do
begin
if Node.ChildNodes.Item[J].NodeName = 'property' then
begin
for K := 0 to 4 do
begin
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'name' then
PropriedadeXML := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'column' then
ColunaXML := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
end;
if ColunaXML = Campo then
begin
Propriedade := PropriedadeXML;
end;
end
else if Node.ChildNodes.Item[J].NodeName = 'id' then
begin
Propriedade := 'Id';
end;
end;
if Query.Fields[I].DataType in [ftFloat, ftDate, ftDateTime] then
begin
SetFloatProp(ObjetoLocal, Propriedade, Query.Fields[I].AsFloat);
end
else if Query.Fields[I].DataType in [ftInteger, ftSmallint, ftLargeint] then
begin
SetInt64Prop(ObjetoLocal, Propriedade, Query.Fields[I].AsInteger);
end
else if Query.Fields[I].DataType in [ftString, ftMemo, ftFixedChar] then
begin
SetStrProp(ObjetoLocal, Propriedade, Query.Fields[I].AsString);
end;
end;
Result := ObjetoLocal;
end;
finally
end;
end;
{$EndRegion}
{$Region 'SQL Outros'}
class function TT2TiORM.ComandoSQL(pConsulta: String): Boolean;
var
Query: TZQuery;
begin
try
try
Conectar;
Conexao := Conexao;
Query := TZQuery.Create(nil);
Query.Connection := Conexao;
Query.sql.Text := pConsulta;
Query.ExecSQL();
Result := True;
except
Result := False;
end;
finally
Query.Close;
Query.Free;
end;
end;
class function TT2TiORM.SelectMax(pTabela: String; pFiltro: String): Integer;
var
Query: TZQuery;
ConsultaSQL: String;
begin
try
ConsultaSQL := 'SELECT MAX(ID) AS MAXIMO FROM ' + pTabela;
if pFiltro <> '' then
ConsultaSQL := ConsultaSQL + ' WHERE ' + pFiltro;
try
Conectar;
Conexao := Conexao;
Query := TZQuery.Create(nil);
Query.Connection := Conexao;
Query.sql.Text := ConsultaSQL;
Query.Open;
if Query.RecordCount > 0 then
Result := Query.FieldByName('MAXIMO').AsInteger
else
Result := -1;
except
Result := -1;
end;
finally
Query.Close;
Query.Free;
end;
end;
class function TT2TiORM.SelectMin(pTabela: String; pFiltro: String): Integer;
var
Query: TZQuery;
ConsultaSQL: String;
begin
try
ConsultaSQL := 'SELECT MIN(ID) AS MINIMO FROM ' + pTabela;
if pFiltro <> '' then
ConsultaSQL := ConsultaSQL + ' WHERE ' + pFiltro;
try
Conectar;
Conexao := Conexao;
Query := TZQuery.Create(nil);
Query.Connection := Conexao;
Query.sql.Text := ConsultaSQL;
Query.Open;
if Query.RecordCount > 0 then
Result := Query.FieldByName('MINIMO').AsInteger
else
Result := -1;
except
Result := -1;
end;
finally
Query.Close;
Query.Free;
end;
end;
class function TT2TiORM.SelectCount(pTabela: String): Integer;
var
Query: TZQuery;
ConsultaSQL: String;
begin
try
ConsultaSQL := 'SELECT COUNT(*) AS TOTAL FROM ' + pTabela;
try
Conectar;
Conexao := Conexao;
Query := TZQuery.Create(nil);
Query.Connection := Conexao;
Query.sql.Text := ConsultaSQL;
Query.Open;
Result := Query.FieldByName('TOTAL').AsInteger
except
Result := -1;
end;
finally
Query.Close;
Query.Free;
end;
end;
{$EndRegion}
end.
|
unit Validador.UI.MesclarArquivos;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Validador.UI.FormBase, Vcl.ExtCtrls,
Validador.UI.VisualizarXML, Vcl.StdCtrls, Validador.Data.FDdbChange, Xml.XMLIntf, Vcl.ComCtrls,
System.Actions, Vcl.ActnList;
type
TMesclarArquivos = class(TFormBase)
GridPanel1: TGridPanel;
Label1: TLabel;
Label3: TLabel;
VisualizarXML1: TVisualizarXML;
Splitter1: TSplitter;
VisualizarXML2: TVisualizarXML;
pnlProximo: TPanel;
btnProximo: TButton;
pgcEtapas: TPageControl;
tbsArquivos: TTabSheet;
tbsFinal: TTabSheet;
VisualizarXML3: TVisualizarXML;
ActionList: TActionList;
actMesclarDocumentos: TAction;
actVoltar: TAction;
procedure FormCreate(Sender: TObject);
procedure actMesclarDocumentosExecute(Sender: TObject);
procedure actVoltarExecute(Sender: TObject);
private
procedure UnificarXML(const AXMLUnificado: IXMLDocument; const AdbChangeDS: TFDDbChange);
procedure ConverterParaDataSet(_xmlUnificado: IXMLDocument; _dbChangeDataSet: TFDDbChange);
procedure GerarXMLSemRepetidos(const ADbChangeDataSet: TFDDbChange);
procedure MostrarXML(_novoXML: IXMLDocument);
public
procedure AfterConstruction; override;
end;
var
MesclarArquivos: TMesclarArquivos;
implementation
{$R *.dfm}
uses
Validador.DI, Validador.Core.ConversorXMLDataSet, Validador.Core.UnificadorXML,
Validador.Data.dbChangeXML, Xml.XMLDoc, FireDAC.Stan.StorageXML;
procedure TMesclarArquivos.FormCreate(Sender: TObject);
begin
inherited;
pgcEtapas.ActivePageIndex := 0;
end;
procedure TMesclarArquivos.actMesclarDocumentosExecute(Sender: TObject);
var
_xmlUnificado: IXMLDocument;
_dbChangeDataSet: TFDDbChange;
begin
inherited;
_dbChangeDataSet := TFDDbChange.Create(nil);
_xmlUnificado := NewXMLDocument;
try
_dbChangeDataSet.CreateDataSet;
UnificarXML(_xmlUnificado, _dbChangeDataSet);
ConverterParaDataSet(_xmlUnificado, _dbChangeDataSet);
GerarXMLSemRepetidos(_dbChangeDataSet);
finally
_dbChangeDataSet.Close;
FreeAndNil(_dbChangeDataSet);
btnProximo.Action := actVoltar
end;
end;
procedure TMesclarArquivos.actVoltarExecute(Sender: TObject);
begin
inherited;
pgcEtapas.ActivePage := tbsArquivos;
btnProximo.Action := actMesclarDocumentos;
end;
procedure TMesclarArquivos.AfterConstruction;
begin
inherited;
VisualizarXML1.SetDiretorioBase(DiretorioBase);
VisualizarXML2.SetDiretorioBase(DiretorioBase);
end;
procedure TMesclarArquivos.UnificarXML(const AXMLUnificado: IXMLDocument;
const AdbChangeDS: TFDDbChange);
var
_unificador: IUnificadorXML;
begin
AXMLUnificado.Options := [doNodeAutoCreate, doNodeAutoIndent, doAttrNull, doAutoPrefix,
doNamespaceDecl, doAutoSave];
_unificador := Validador.DI.ContainerDI.Resolve<IUnificadorXML>;
_unificador.SetXMLAnterior(VisualizarXML2.GetXMLDocument);
_unificador.SetXMLNovo(VisualizarXML1.GetXMLDocument);
_unificador.PegarXMLMesclado(AXMLUnificado);
AXMLUnificado.Version := '1.0';
AXMLUnificado.Encoding := 'UTF-8';
AXMLUnificado.StandAlone := 'no';
end;
procedure TMesclarArquivos.ConverterParaDataSet(_xmlUnificado: IXMLDocument;
_dbChangeDataSet: TFDDbChange);
var
_conversor: IConversorXMLDataSet;
begin
_conversor := ContainerDI.Resolve<IConversorXMLDataSet>;
_conversor.SetXML(_xmlUnificado);
_conversor.SetDataSet(_dbChangeDataSet);
_conversor.ConverterParaDataSet;
end;
procedure TMesclarArquivos.GerarXMLSemRepetidos(const ADbChangeDataSet: TFDDbChange);
var
_novoXML: IXMLDocument;
_conversor: IConversorXMLDataSet;
begin
_novoXML := TXMLDocument.Create(nil);
_novoXML.Options := [doNodeAutoCreate, doNodeAutoIndent, doAttrNull, doAutoPrefix,
doNamespaceDecl, doAutoSave];
ADbChangeDataSet.MarcarRepetidos;
_conversor := ContainerDI.Resolve<IConversorXMLDataSet>;
_conversor.SetXML(_novoXML);
_conversor.SetDataSet(ADbChangeDataSet);
_conversor.DataSetParaImportacao;
_novoXML.Version := '1.0';
_novoXML.Encoding := 'UTF-8';
_novoXML.StandAlone := 'no';
MostrarXML(_novoXML);
end;
procedure TMesclarArquivos.MostrarXML(_novoXML: IXMLDocument);
var
_stringList: TStrings;
_stream: TMemoryStream;
begin
// Infelizmente, o TXMLDocument APENAS ACRESCENTA O UTF-8 se for salvo em stream
_stringList := TStringList.Create;
_stream := TMemoryStream.Create;
try
_novoXML.SaveToStream(_stream);
_stream.Position := 0;
_stringList.LoadFromStream(_stream);
VisualizarXML3.SetXML(_stringList);
pgcEtapas.ActivePage := tbsFinal;
finally
FreeAndNil(_stringList);
FreeAndNil(_stream);
end;
end;
end.
|
unit JWBIO;
{
Encodings and stream encoders/decoders.
HOW TO USE:
1. Detecting encodings:
if not Conv_DetectType(filename, AEncoding) then
AEncoding := Conv_ChooseType(AEncoding);
2. Reading file:
AReader := TFileReader.Create(filename, TUTF8Encoding.Create);
AReader := OpenTextFile(filename, TUTF8Encoding);
//opens cached stream, may be useful when doing seeks/detection
AReader := OpenTextFile(filename, nil);
//best guess encoding and open
while AReader.ReadChar(ch) do
ProcessChar(ch);
line := AReader.Readln();
3. Writing file:
AWriter := CreateTextFile(filename, TUTF8Encoding);
AWriter := AppendToTextFile(filename, TUTF8Encoding);
AWriter.Writeln('Hello world');
4. Permanently storing encoding selection:
WriteString(ChosenEncoding.ClassName);
ChosenEncoding := FindEncoding(ReadString()).Create();
Note that encodings can be parametrized:
TMultibyteEncoding.Create('win-1251')
And same encoding can be implemented in a different ways:
TUTF8Encoding
TMultibyteEncoding.Create('utf8')
Therefore only use this method for a limited set of known encodings.
}
interface
uses SysUtils, Classes, JWBStrings;
type
{ Encoding is created once and executed sequentially on a stream, starting with
a legal position (not inside a surrogate).
It may keep track of decoding state, so a new one is required for every stream.
It is recommended to use TEncoding with a buffered, best effort stream.
1. BOM checking and some routines require seeks.
2. socket-like "read available bytes and return" behavior WILL break things.
TStream has to block until requested number of bytes is available or the
stream is over. }
TEncodingLikelihood = (
elIdentified, //data is self-marked as being in this encoding
elLikely, //data is likely to be in this encoding
elUnlikely //data is unlikely to be in this encoding
);
TEncoding = class
constructor Create; virtual;
class function GetBom: TBytes; virtual;
class function ReadBom(ABytes: PByte; ALength: integer): integer; virtual;
function Analyze(ABytes: PByte; ALength: integer): TEncodingLikelihood; virtual;
{ Converts bytes to chars until one of the bollowing is true:
ABytesRemaining==0 => Out of bytes
ACharsRemaining==0 => Out of space to put chars
Result<AMaxChars&&
ABytesRemaining>0 => Not enought bytes to form the next char
Returns the number of chars converted.
AMaxChars is given in 2 byte positions. Surrogate pairs count as separate chars. }
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); virtual; abstract;
{ Encoding descendants do not check the number of bytes written. If you care,
wrap TStream and raise exceptions. }
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); virtual; abstract;
end;
CEncoding = class of TEncoding;
{ Simple encodings }
TAsciiEncoding = class(TEncoding)
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); override;
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); override;
end;
{$IFDEF MSWINDOWS}
{ Encoding class based on MultiByteToWideChar/WideCharToMultiByte. Slowish but safe.
As things are right now, it's better to use derived classes for actual encodings
(e.g. TAcpEncoding) }
TMultibyteEncoding = class(TEncoding)
protected
FCodepage: integer;
FIllegalChar: char;
public
constructor Create(const ACodepage: integer); reintroduce; overload;
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); override;
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); override;
end;
TAcpEncoding = class(TMultibyteEncoding)
constructor Create; override;
end;
{$ENDIF}
TUTF8Encoding = class(TEncoding)
class function GetBom: TBytes; override;
procedure Read(pb: PByte; pc: PWideChar; var pbrem: integer; var pcrem: integer); override;
procedure Write(pc: PWideChar; pb: PByte; var pcrem: integer; var pbrem: integer); override;
end;
TUTF16LEEncoding = class(TEncoding)
class function GetBom: TBytes; override;
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); override;
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); override;
end;
TUTF16Encoding = TUTF16LEEncoding;
TUnicodeEncoding = TUTF16LEEncoding;
TUTF16BEEncoding = class(TEncoding)
class function GetBom: TBytes; override;
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); override;
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); override;
end;
TEUCEncoding = class(TEncoding)
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); override;
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); override;
end;
TSJISEncoding = class(TEncoding)
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); override;
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); override;
end;
{ New-JIS, Old-JIS and NEC-JIS differ only by Start and End markers.
Read() covers all of them while Write() depends on markers being set by descendants below }
TBaseJISEncoding = class(TEncoding)
protected
intwobyte: boolean;
StartMark: TBytes;
EndMark: TBytes;
procedure _fputstart(AStream: TStream);
procedure _fputend(AStream: TStream);
public
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); override;
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); override;
end;
TJISEncoding = class(TBaseJISEncoding)
constructor Create; override;
end;
TOldJISEncoding = class(TBaseJISEncoding)
constructor Create; override;
end;
TNECJISEncoding = class(TBaseJISEncoding)
constructor Create; override;
end;
TGBEncoding = class(TEncoding)
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); override;
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); override;
end;
TBIG5Encoding = class(TEncoding)
procedure Read(ABytes: PByte; AChars: PWideChar; var ABytesRemaining: integer;
var ACharsRemaining: integer); override;
procedure Write(AChars: PWideChar; ABytes: PByte; var ACharsRemaining: integer;
var ABytesRemaining: integer); override;
end;
type
TStreamDecoder = class
protected
FByteBuf: array[0..1023] of byte;
FByteBufLen: integer;
FCharBuf: array[0..1023] of char;
FCharBufLen: integer;
FCharBufPos: integer;
FStream: TStream;
FOwnsStream: boolean;
FEncoding: TEncoding;
FEOF: boolean; //set when you cannot read one more byte from the stream
procedure ReadMoreBytes;
procedure PopBytes(const ALen: integer);
procedure ConvertMoreChars;
public
constructor Open(AStream: TStream; AEncoding: TEncoding;
AOwnsStream: boolean = false); overload; virtual;
constructor Open(const AFilename: string; AEncoding: TEncoding); overload;
destructor Destroy; override;
procedure DetachStream; //clears whatever caches the instance may have for the Stream
procedure TrySkipBom;
procedure Rewind(const ADontSkipBom: boolean = false);
function EOF: boolean;
function ReadChar(out ch: WideChar): boolean; overload;
function ReadLn(out ln: UnicodeString): boolean; overload;
function ReadChar: WideChar; overload; //#0000 if no char
function ReadLn: UnicodeString; overload; //empty string if no string
{ Or should these raise exceptions? }
property Stream: TStream read FStream;
property OwnsStream: boolean read FOwnsStream;
property Encoding: TEncoding read FEncoding;
end;
TStreamEncoder = class
protected
FByteBuf: array[0..1023] of byte;
FByteBufLen: integer;
FCharBuf: array[0..512] of char;
FCharBufLen: integer;
FStream: TStream;
FOwnsStream: boolean;
FEncoding: TEncoding;
procedure FlushBytes;
procedure PopChars(const ALen: integer);
public
constructor Open(AStream: TStream; AEncoding: TEncoding;
AOwnsStream: boolean = false);
constructor CreateNew(const AFilename: string; AEncoding: TEncoding);
constructor Append(const AFilename: string; AEncoding: TEncoding);
destructor Destroy; override;
procedure Flush; //clears whatever caches instance may have for the stream
procedure WriteBom;
procedure WriteChar(const ch: WideChar);
procedure Write(const ln: UnicodeString);
procedure WriteLn(const ln: UnicodeString);
property Stream: TStream read FStream;
property OwnsStream: boolean read FOwnsStream;
property Encoding: TEncoding read FEncoding;
end;
CStreamEncoder = class of TStreamDecoder;
{$IFDEF GUESS_UTF16}
function GuessUTF16(AStream: TStream; out AEncoding: CEncoding): boolean;
{$ENDIF}
function Conv_DetectType(AStream: TStream): CEncoding; overload;
function Conv_DetectType(AStream: TStream; out AEncoding: CEncoding): boolean; overload;
function Conv_DetectType(const AFilename: string): CEncoding; overload;
function Conv_DetectType(const AFilename: string; out AEncoding: CEncoding): boolean; overload;
function OpenStream(const AStream: TStream; AOwnsStream: boolean; AEncoding: CEncoding = nil): TStreamDecoder;
function OpenTextFile(const AFilename: string; AEncoding: CEncoding = nil): TStreamDecoder; inline;
function CreateTextFile(const AFilename: string; AEncoding: CEncoding): TStreamEncoder;
function AppendToTextFile(const AFilename: string; AEncoding: CEncoding = nil): TStreamEncoder;
//Finds a class by it's name. Good to store encoding selection in a permanent way.
function FindEncoding(const AClassName: string): CEncoding;
//Compares binary data in files
function CompareStreams(const AStream1, AStream2: TStream): boolean;
function CompareFiles(const AFilename1, AFilename2: string): boolean;
{ Compatibility functions }
function AnsiFileReader(const AFilename: string): TStreamDecoder;
function UnicodeFileReader(const AFilename: string): TStreamDecoder;
function ConsoleReader(AEncoding: TEncoding = nil): TStreamDecoder;
function UnicodeStreamReader(AStream: TStream; AOwnsStream: boolean = false): TStreamDecoder;
function FileReader(const AFilename: string): TStreamDecoder; inline; //->Unicode on Unicode, ->Ansi on Ansi
function AnsiFileWriter(const AFilename: string): TStreamEncoder;
function UnicodeFileWriter(const AFilename: string): TStreamEncoder;
function ConsoleWriter(AEncoding: TEncoding = nil): TStreamEncoder;
function ConsoleUTF8Writer(): TStreamEncoder;
function UnicodeStreamWriter(AStream: TStream; AOwnsStream: boolean = false): TStreamEncoder;
function FileWriter(const AFilename: string): TStreamEncoder; inline; //->Unicode on Unicode, ->Ansi on Ansi
{ Misc useful functions }
function GetLineCount(AText: TStreamDecoder): integer;
implementation
uses Windows, StreamUtils, JWBConvertTbl;
{ Various helpers }
//Swaps bytes in a word
function _swapw(const w: word): word; inline;
begin
Result :=
(w and $00FF) shl 8 +
(w and $FF00) shr 8;
{ or:
(w mod $100) shl 8 +
(w div $100);
dunno which is faster }
end;
{ Encoding }
constructor TEncoding.Create;
begin
inherited; { Inherit in descendants to initialize encoding }
end;
class function TEncoding.GetBom: TBytes;
begin
Result := TBytes.Create();
end;
{ Tests for any of the BOMs supported by this encoding and returns the length
of the match, or 0 if no match is found / no bom is supported.
Try to give us a buffer long enough to be likely to contain any possible BOM. }
class function TEncoding.ReadBom(ABytes: PByte; ALength: integer): integer;
var BOM: TBytes;
i: integer;
begin
{ Default implementation just checks for the main BOM }
BOM := GetBOM();
if (Length(BOM)<=0) or (Length(BOM)>ALength) then begin
Result := 0;
exit;
end;
Result := Length(BOM);
for i := 0 to Length(BOM)-1 do
if BOM[i]<>ABytes[i] then begin
Result := 0;
break;
end;
end;
function TEncoding.Analyze(ABytes: PByte; ALength: integer): TEncodingLikelihood;
begin
{ Default implementation only tests for BOM }
if ReadBom(ABytes, ALength)>0 then
Result := elIdentified
else
Result := elUnlikely;
end;
procedure _fwrite1(AStream: TStream; const b: byte); inline;
begin
AStream.Write(b, 1);
end;
procedure _fwrite2(AStream: TStream; const w: word); inline;
begin
AStream.Write(w, 2);
end;
procedure _fwrite3(AStream: TStream; const dw: cardinal); inline;
begin
AStream.Write(dw, 3);
end;
procedure _fwrite4(AStream: TStream; const dw: cardinal); inline;
begin
AStream.Write(dw, 4);
end;
{ Stream decoder }
constructor TStreamDecoder.Open(AStream: TStream; AEncoding: TEncoding;
AOwnsStream: boolean = false);
begin
inherited Create();
FStream := AStream;
FOwnsStream := AOwnsStream;
FEOF := false;
FEncoding := AEncoding;
FByteBufLen := 0;
FCharBufLen := 0;
Self.TrySkipBom;
end;
constructor TStreamDecoder.Open(const AFilename: string; AEncoding: TEncoding);
var fs: TFileStream;
begin
fs := TFileStream.Create(AFilename, fmOpenRead);
Self.Open(fs, AEncoding, {OwnsStream=}true);
end;
destructor TStreamDecoder.Destroy;
begin
if not FOwnsStream then
DetachStream; //if the stream is ours, no point in restoring it's actual position
if FOwnsStream then
FreeAndNil(FStream);
FreeAndNil(FEncoding);
inherited;
end;
{ Buffers more data from the stream. Up to buffer size will be buffered, but
some streams only return what's available, so you may need to call this until
you get enough. }
procedure TStreamDecoder.ReadMoreBytes;
var data_sz: integer;
begin
if FByteBufLen<Length(FByteBuf) then begin
data_sz := FStream.Read(FByteBuf[FByteBufLen], Length(FByteBuf)-FByteBufLen);
if data_sz<=0 then
FEOF := true
else
FByteBufLen := FByteBufLen + data_sz;
end;
end;
{ Removes the specified number of bytes from the byte buffer }
procedure TStreamDecoder.PopBytes(const ALen: integer);
begin
if ALen=0 then
exit
else
if ALen>=FByteBufLen then
FByteBufLen := 0
else begin
Move(FByteBuf[ALen], FByteBuf[0], FByteBufLen-ALen);
Dec(FByteBufLen, ALen);
end;
end;
{ Reads more data and convert more characters. }
procedure TStreamDecoder.ConvertMoreChars;
var data_sz, rem_sz: integer;
begin
//Read more data from the stream. We immediately convert the data, so there
//should be close to no previous data in ByteBuf.
ReadMoreBytes;
//Convert all the available data
data_sz := FCharBufLen-FCharBufPos;
if data_sz<Length(FCharBuf) then begin
//Pack chars
Move(FCharBuf[FCharBufPos], FCharBuf[0], data_sz*SizeOf(Char));
FCharBufLen := data_sz;
FCharBufPos := 0;
//Read
data_sz := Length(FCharBuf)-data_sz; //data free space
rem_sz := FByteBufLen;
FEncoding.Read(@FByteBuf[0], @FCharBuf[FCharBufLen], rem_sz, data_sz);
FCharBufLen := Length(FCharBuf)-data_sz; //data_sz is how much buffer was left unused
//Pack bytes
PopBytes(FByteBufLen-rem_sz);
end;
{ Two pitfalls here:
1. ByteBuf overflow if TEncoding never converts anything, no matter how big
chunk of bytes it given.
2. CharBuf overflow if someone calls ConvertMoreChars without reading those
out.
In both cases, no harm done but no data flows further. ReadChar is going to
be stuck. }
end;
procedure TStreamDecoder.DetachStream;
begin
{ Unfortunately there's no way now to know how many bytes we should roll back
to position stream where we logically are (in characters). }
end;
procedure TStreamDecoder.TrySkipBom;
begin
//I don't think there are BOMs longer than 4 characters
while not EOF and (FByteBufLen<4) do
ReadMoreBytes;
PopBytes(FEncoding.ReadBom(@FByteBuf[0], FByteBufLen));
end;
procedure TStreamDecoder.Rewind(const ADontSkipBom: boolean);
begin
Stream.Seek(0, soBeginning);
FByteBufLen := 0;
FCharBufLen := 0;
FEOF := false;
if not ADontSkipBom then
TrySkipBom;
end;
{ True if there *already was* at least one ReadChar() which resulted in False,
and no subsequent calls can be expected to succeed.
Should not return true even if we're at EOF until someone tries to ReadChar()
and finds it. }
function TStreamDecoder.EOF: boolean;
begin
Result := FEOF and (FCharBufPos>=FCharBufLen);
end;
{ Reads another character from the stream or returns False to indicate that
no more are available. }
function TStreamDecoder.ReadChar(out ch: WideChar): boolean;
begin
while FCharBufPos>=FCharBufLen do begin
if FEOF then begin
Result := false;
exit;
end;
ConvertMoreChars;
end;
ch := FCharBuf[FCharBufPos];
Inc(FCharBufPos);
Result := true;
end;
{ Reads until next CRLF or the end of the stream.
Last line always ends with the stream. If the file ends in CRLF, it'll be
returned as a last, empty line.
To reproduce the content when saving, always write last line without CRLF.
As an exception, empty file is thought to have no lines. }
function TStreamDecoder.ReadLn(out ln: UnicodeString): boolean;
var ch: WideChar;
begin
ln := '';
Result := not EOF; //there may be no more characters, but at least we haven't found that out yet
while ReadChar(ch) do begin
{ Maybe a more thorough CRLF/CR/LF handling is needed }
if ch=#$000D then begin
//ignore
end else
if ch=#$000A then
break
else
ln := ln + ch;
end;
end;
function TStreamDecoder.ReadChar: WideChar;
begin
if not ReadChar(Result) then
Result := #0000;
end;
function TStreamDecoder.ReadLn: UnicodeString;
begin
if not ReadLn(Result) then
Result := '';
end;
{ Stream encoder }
constructor TStreamEncoder.Open(AStream: TStream; AEncoding: TEncoding;
AOwnsStream: boolean = false);
begin
inherited Create();
FStream := AStream;
FOwnsStream := AOwnsStream;
FEncoding := AEncoding;
FByteBufLen := 0;
FCharBufLen := 0;
end;
constructor TStreamEncoder.CreateNew(const AFilename: string; AEncoding: TEncoding);
var fs: TFileStream;
begin
fs := TFileStream.Create(AFilename, fmCreate);
Self.Open(fs,AEncoding,{OwnsStream=}true);
end;
constructor TStreamEncoder.Append(const AFilename: string; AEncoding: TEncoding);
var fs: TFileStream;
begin
fs := TFileStream.Create(AFilename, fmCreate);
fs.Seek(0,soFromEnd);
Self.Open(fs,AEncoding,{OwnsStream=}true);
end;
destructor TStreamEncoder.Destroy;
begin
Flush();
if FOwnsStream then
FreeAndNil(FStream);
FreeAndNil(FEncoding);
inherited;
end;
procedure TStreamEncoder.FlushBytes;
begin
if FByteBufLen<=0 then
exit
else begin
FStream.Write(FByteBuf[0], FByteBufLen);
FByteBufLen := 0;
end;
end;
procedure TStreamEncoder.PopChars(const ALen: integer);
begin
if ALen<=0 then
exit
else
if ALen>FCharBufLen then
FCharBufLen := 0
else begin
Move(FCharBuf[ALen], FCharBuf[0], (FCharBufLen-ALen)*SizeOf(char));
Dec(FCharBufLen, ALen);
end;
end;
procedure TStreamEncoder.Flush;
var AByteCnt, ACharCnt: integer;
begin
while FCharBufLen>0 do begin //we may not fit everything into bytebuf at once
if FByteBufLen<Length(FByteBuf) then begin
AByteCnt := Length(FByteBuf)-FByteBufLen;
ACharCnt := FCharBufLen;
FEncoding.Write(@FCharBuf[0], @FByteBuf[FByteBufLen],
ACharCnt, AByteCnt);
FByteBufLen := Length(FByteBuf)-AByteCnt;
PopChars(FCharBufLen-ACharCnt);
end;
FlushBytes;
end;
FlushBytes; //again, in case FCharBufLen was 0 from the start.
end;
procedure TStreamEncoder.WriteBom;
var BOM: TBytes;
begin
Flush;
BOM := FEncoding.GetBOM();
if Length(BOM)>0 then
FStream.Write(BOM[0], Length(BOM));
end;
procedure TStreamEncoder.WriteChar(const ch: WideChar);
begin
FCharBuf[FCharBufLen] := ch;
Inc(FCharBufLen);
if FCharBufLen>=Length(FCharBuf) then
Flush();
end;
procedure TStreamEncoder.Write(const ln: UnicodeString);
var i: integer;
begin
if ln='' then exit;
for i := 1 to Length(ln) do
WriteChar(ln[i]); //not very effective I guess
end;
{ Writes a line with CRLF in the end.
Note that if you've read the lines with ReadLn, to reproduce the file content,
last line has to be written without CRLF. See ReadLn. }
procedure TStreamEncoder.WriteLn(const ln: UnicodeString);
begin
Write(ln+#$000D+#$000A);
end;
{ Simple encodings }
procedure TAsciiEncoding.Read(ABytes: PByte; AChars: PWideChar;
var ABytesRemaining: integer; var ACharsRemaining: integer);
begin
while (ABytesRemaining>0) and (ACharsRemaining>0) do begin
AChars^ := WideChar(ABytes^);
Inc(AChars);
Inc(ABytes);
Dec(ABytesRemaining);
Dec(ACharsRemaining);
end;
end;
procedure TAsciiEncoding.Write(AChars: PWideChar; ABytes: PByte;
var ACharsRemaining: integer; var ABytesRemaining: integer);
begin
while (ABytesRemaining>0) and (ACharsRemaining>0) do begin
ABytes^ := byte(AnsiChar(AChars^));
Inc(AChars);
Inc(ABytes);
Dec(ABytesRemaining);
Dec(ACharsRemaining);
end;
end;
{$IFDEF MSWINDOWS}
{ A note on parametrized encodings:
They will work, but no with any special code which assumes one encoding == one type.
You also cannot rely on comparisons like "if Encoding1==Encoding2". }
constructor TMultibyteEncoding.Create(const ACodepage: integer);
begin
inherited Create;
FCodepage := ACodepage;
FIllegalChar := '?';
end;
{ Hold on to your seats guys, this is going to be slow!
CP_* encodings on Windows can be multibyte and MultiByteToWideChar does not
return the number of bytes it used (only the number of *resulting* chars).
To know where to start next time we expand sample byte by byte, until there's
enough bytes for MultiByteToWideChar to produce one char.
Both Multibyte and Wide encodings can have surrogate characters, so we have
to be ready to receive more than one char position. If there's not enough
space in Char buffer, we roll back and leave it for next time.
If there are invalid characters, they are ignored and MBWC produces no chars.
This is problematic, as we will continue increasing sample size without
producing a character. Eventually we will run out of Bytes and return with no
progress made, the caller will keep all the data and run out of buffer
Therefore, we need to stop at some point and declare the position "invalid".
With WideChars it's easy: surrogates longer than 2 chars don't exist. With
Multibyte UTF-8 can go for as long as 7 chars, so we'll settle at eight.
Note that we may not notice invalid char if MBWC encounters another valid char
while at the same 8 bytes. No way around this. We cannot test for
ERROR_NO_UNICODE_TRANSLATION because incomplete sequences result in the same. }
procedure TMultibyteEncoding.Read(ABytes: PByte; AChars: PWideChar;
var ABytesRemaining: integer; var ACharsRemaining: integer);
var i, conv: integer;
tmp: array[0..1] of WideChar;
found: boolean;
begin
conv := 0;
while (ABytesRemaining>0) and (ACharsRemaining>0) do begin
i := 1;
found := false;
while (i<ABytesRemaining) and (i<8) do begin
conv := MultiByteToWideChar(FCodepage, 0, PAnsiChar(ABytes), i+1, tmp, 2);
if conv>=1 then begin
found := true;
break;
end;
Inc(i);
end;
if i>=8 then begin
AChars^ := FIllegalChar;
Inc(AChars);
Dec(ACharsRemaining);
Inc(ABytes);
Dec(ABytesRemaining);
continue;
end;
if not found then
exit;
if conv>ACharsRemaining then
exit; //want to write surrogate and not enough space
Inc(ABytes, i);
Dec(ABytesRemaining, i);
for i := 1 to conv do begin
AChars^ := tmp[1];
Inc(AChars);
Dec(ACharsRemaining);
end;
end;
end;
procedure TMultibyteEncoding.Write(AChars: PWideChar; ABytes: PByte;
var ACharsRemaining: integer; var ABytesRemaining: integer);
var i, conv: integer;
tmp: array[0..7] of byte;
found: boolean;
begin
conv := 0;
while (ABytesRemaining>0) and (ACharsRemaining>0) do begin
i := 1;
found := false;
while (i<ABytesRemaining) and (i<2) do begin
conv := WideCharToMultiByte(FCodepage, 0, AChars, i+1, @tmp[0], 8, nil, nil);
if conv>=1 then begin
found := true;
break;
end;
Inc(i);
end;
if i>=2 then begin
ABytes^ := Byte(FIllegalChar);
Inc(AChars);
Dec(ACharsRemaining);
Inc(ABytes);
Dec(ABytesRemaining);
continue;
end;
if not found then
exit;
if conv>ACharsRemaining then
exit; //want to write surrogate and not enough space
Inc(AChars, i);
Dec(ACharsRemaining, i);
for i := 1 to conv do begin
ABytes^ := tmp[1];
Inc(ABytes);
Dec(ABytesRemaining);
end;
end;
end;
constructor TAcpEncoding.Create;
begin
inherited Create();
FCodepage := CP_ACP;
end;
{$ENDIF}
class function TUTF8Encoding.GetBOM: TBytes;
begin
Result := TBytes.Create($EF, $BB, $BF);
end;
procedure TUTF8Encoding.Read(pb: PByte; pc: PWideChar; var pbrem: integer;
var pcrem: integer);
var chno, bcnt: integer;
begin
while (pbrem>0) and (pcrem>0) do begin
chno := 0;
bcnt := 0;
if (pb[0] and UTF8_MASK1)=UTF8_VALUE1 then begin
//Most common case, single-byte char
pc^ := WideChar(pb[0]);
bcnt := 1;
end else
if (pb[0] and UTF8_MASK2)=UTF8_VALUE2 then begin
if pbrem<2 then exit;
pc^ := WideChar( (pb[0] and $1f) shl 6
+ (pb[1] and $3f));
bcnt := 2;
end else
if (pb[0] and UTF8_MASK3)=UTF8_VALUE3 then begin
if pbrem<3 then exit;
pc^ := WideChar((pb[0] and $0f) shl 12
+ (pb[1] and $3f) shl 6
+ (pb[2] and $3f));
bcnt := 3;
end else
if (pb[0] and UTF8_MASK4)=UTF8_VALUE4 then
begin
if pbrem<4 then exit;
chno := (pb[0] and $0f) shl 18
+ (pb[1] and $3f) shl 12
+ (pb[2] and $3f) shl 6
+ (pb[3] and $3f);
bcnt := 4;
end else
if (pb[0] and UTF8_MASK5)=UTF8_VALUE5 then
begin
if pbrem<5 then exit;
chno := (pb[0] and $0f) shl 24
+ (pb[1] and $3f) shl 18
+ (pb[2] and $3f) shl 12
+ (pb[3] and $3f) shl 6
+ (pb[4] and $3f);
bcnt := 5;
end else
if (pb[0] and UTF8_MASK6)=UTF8_VALUE4 then
begin
if pbrem<6 then exit;
chno := (pb[0] and $0f) shl 30
+ (pb[1] and $3f) shl 24
+ (pb[2] and $3f) shl 18
+ (pb[3] and $3f) shl 12
+ (pb[4] and $3f) shl 6
+ (pb[5] and $3f);
bcnt := 6;
end else
//Broken, unsupported character, probably a remnant of a surrogate. Skip it.
bcnt := 1;
//Store complicated characters by setting their chno insteead
if chno<>0 then begin
if chno<$10000 then begin
pc^ := WideChar(chno);
Inc(pc, 1);
Dec(pcrem, 1);
end else
if pcrem<2 then
exit //leave for the next time
else begin
chno := chno-$10000;
pc[0] := WideChar(UTF16_LEAD + chno shr 10);
pc[1] := WideChar(UTF16_TRAIL + chno and $03FF);
Inc(pc, 2);
Dec(pcrem, 2);
end;
end;
Inc(pb, bcnt);
Dec(pbrem, bcnt);
end;
end;
procedure TUTF8Encoding.Write(pc: PWideChar; pb: PByte; var pcrem: integer;
var pbrem: integer);
var i, w, pbcnt: integer;
begin
while (pbrem>0) and (pcrem>0) do begin
w := Word(pc^);
//TODO: UTF16 surrogates
if (w and UTF8_WRITE1)=0 then begin
pb[0] := w mod 256;
pbcnt := 1;
end else
if (w and UTF8_WRITE2)=0 then begin
if pbrem<2 then exit;
pb[0] := UTF8_VALUE2 or (w shr 6);
pb[1] := UTF8_VALUEC or (w and $3f);
pbcnt := 2;
end else
begin
//TODO: Write 3,4,5-byte sequences when needed
if pbrem<3 then exit;
pb[0] := UTF8_VALUE3 or (w shr 12);
pb[1] := UTF8_VALUEC or ((w shr 6) and $3f);
pb[2] := UTF8_VALUEC or (w and $3f);
pbcnt := 3;
end;
Inc(pb, pbcnt);
Dec(pbrem, pbcnt);
Inc(pc);
Dec(pcrem);
end;
end;
class function TUTF16LEEncoding.GetBOM: TBytes;
begin
Result := TBytes.Create($FF, $FE);
end;
procedure TUTF16LEEncoding.Read(ABytes: PByte; AChars: PWideChar;
var ABytesRemaining: integer; var ACharsRemaining: integer);
var read_sz: integer;
begin
read_sz := ABytesRemaining div 2;
if read_sz>ACharsRemaining then
read_sz := ACharsRemaining;
if read_sz>0 then begin
Move(ABytes^, AChars^, read_sz*2);
Dec(ABytesRemaining, read_sz*2);
Dec(ACharsRemaining, read_sz);
end;
end;
procedure TUTF16LEEncoding.Write(AChars: PWideChar; ABytes: PByte;
var ACharsRemaining: integer; var ABytesRemaining: integer);
var read_sz: integer;
begin
read_sz := ACharsRemaining;
if read_sz>ABytesRemaining div 2 then
read_sz := ABytesRemaining div 2;
if read_sz>0 then begin
Move(AChars^, ABytes^, read_sz*2);
Dec(ABytesRemaining, read_sz*2);
Dec(ACharsRemaining, read_sz);
end;
end;
class function TUTF16BEEncoding.GetBOM: TBytes;
begin
Result := TBytes.Create($FE, $FF);
end;
procedure TUTF16BEEncoding.Read(ABytes: PByte; AChars: PWideChar;
var ABytesRemaining: integer; var ACharsRemaining: integer);
var read_sz, i: integer;
begin
read_sz := ABytesRemaining div 2;
if read_sz>ACharsRemaining then
read_sz := ACharsRemaining;
Dec(ABytesRemaining, read_sz*2);
Dec(ACharsRemaining, read_sz);
while read_sz>0 do begin
PWord(ABytes)^ := _swapw(Word(AChars^));
Inc(ABytes, 2);
Inc(AChars);
Dec(read_sz);
end;
end;
procedure TUTF16BEEncoding.Write(AChars: PWideChar; ABytes: PByte;
var ACharsRemaining: integer; var ABytesRemaining: integer);
var read_sz, i: integer;
begin
read_sz := ACharsRemaining;
if read_sz>ABytesRemaining div 2 then
read_sz := ABytesRemaining div 2;
Dec(ABytesRemaining, read_sz*2);
Dec(ACharsRemaining, read_sz);
while read_sz>0 do begin
AChars^ := WideChar(_swapw(Word(ABytes^)));
Inc(ABytes, 2);
Inc(AChars);
Dec(read_sz);
end;
end;
{ Wakan encodings }
const IS_EUC=1;
IS_HALFKATA=2;
IS_SJIS1=3;
IS_SJIS2=4;
IS_MARU=5;
IS_NIGORI=6;
IS_JIS=7;
JIS_NL=10; // New Line char.
JIS_CR=13; // Carrage Return.
JIS_ESC=27; // Escape.
JIS_SS2=142; // Half-width katakana marker.
type TUTFArray=array[0..3] of byte;
function SJIS2JIS(w:word):word;
var b1,b2,adjust, rowOffset, cellOffset:byte;
begin
b1:=w div 256;
b2:=w mod 256;
if b2<159 then adjust:=1 else adjust:=0;
if b1<160 then rowOffset:=112 else rowOffset:=176;
if adjust=1 then begin if b2>127 then cellOffset:=32 else cellOffset:=31 end else cellOffset:=126;
b1 := ((b1-rowOffset) shl 1) - adjust;
b2 := b2-cellOffset;
result:=b1*256+b2;
end;
function JIS2SJIS(w:word):word;
var b1,b2,b1n:byte;
begin
b1:=w div 256;
b2:=w mod 256;
if b1 mod 2<>0 then begin if b2>95 then b2:=b2+32 else b2:=b2+31 end else b2:=b2+126;
b1n:=((b1+1) shr 1);
if b1<95 then b1n:=b1n+112 else b1n:=b1n+176;
result:=b1n*256+b2;
end;
function JIS2Unicode(w:word):word;
begin
result:=0;//default case
case w of
$0000..$007e:result:=w; // ascii
$0080..$00ff:result:=Table_ExtASCII[w-128];
$2330..$237a:result:=w-$2330+$ff10; // japanese ASCII
$2421..$2473:result:=w-$2421+$3041; // hiragana
$2521..$2576:result:=w-$2521+$30a1; // katakana
$2621..$2658:if w<=$2631 then result:=w-$2621+$0391 else
if w<=$2638 then result:=w-$2621+$0392 else
if w< $2641 then result:=0 else
if w<=$2651 then result:=w-$2621+$0391 else
if w<=$2658 then result:=w-$2621+$0392; // greek
$2721..$2771:if w<=$2726 then result:=w-$2721+$0410 else
if w= $2727 then result:=$0401 else
if w<=$2741 then result:=w-$2722+$0410 else
if w< $2751 then result:=0 else
if w<=$2756 then result:=w-$2751+$0430 else
if w= $2757 then result:=$0451 else
if w<=$2771 then result:=w-$2752+$0430; // cyrillic
$3021..$7426:if ((w and $7f)<$21) or ((w and $7f)>$7e) then result:=0 else
result:=Table_Kanji[((w-$3021) div 256)*94+((w-$3021) mod 256)]; // kanji
$2121..$217e:result:=Table_Misc[w-$2121];
$2221..$227e:result:=Table_Misc[w-$2221+94];
$2821..$2840:result:=Table_Misc[w-$2821+94+94];
end;
end;
function Unicode2UTF(ch:word):TUTFArray;
begin
if (ch and UTF8_WRITE1)=0 then
begin
result[0]:=1;
result[1]:=ch;
exit;
end;
if (ch and UTF8_WRITE2)=0 then
begin
result[0]:=2;
result[1]:=(UTF8_VALUE2 or (ch shr 6));
result[2]:=(UTF8_VALUEC or (ch and $3f));
end;
result[0]:=3;
result[1]:=UTF8_VALUE3 or (ch shr 12);
result[2]:=UTF8_VALUEC or ((ch shr 6) and $3f);
result[3]:=UTF8_VALUEC or (ch and $3f);
end;
function Unicode2JIS(w:word):word;
var i:integer;
begin
result:=0;
case w of
$0000..$007e:result:=w; // Ascii
$3041..$3093:result:=w-$3041+$2421; // Hiragana
$30a1..$30f6:result:=w-$30a1+$2521; // Katakana
$0391..$03c9:if w<=$03a1 then result:=w-$0391+$2621 else
if w= $03a2 then result:=0 else
if w<=$03a9 then result:=w-$0392+$2621 else
if w< $03b1 then result:=0 else
if w<=$03c1 then result:=w-$0391+$2621 else
if w= $03c2 then result:=0 else
if w<=$03c9 then result:=w-$0392+$2621; // greek
$0401 :result:=$2727;
$0451 :result:=$2757;
$0410..$044f:if w<=$0415 then result:=w-$0410+$2721 else
if w<=$042f then result:=w-$0416+$2728 else
if w<=$0435 then result:=w-$0430+$2751 else
if w<=$044f then result:=w-$0436+$2758; // cyrillic
$ff10..$ff5a:result:=w-$ff10+$2330;
$feff :result:=w;
$fffe :result:=w;
end;
if result<>0 then exit;
for i:=0 to NUMBER_KANJIUNICODE-1 do if Table_Kanji[i]=w then
begin
result:=i div 94;
result:=(((result+$30) shl 8) or (i-result*94)+$21);
exit;
end;
for i:=0 to NUMBER_MISCUNICODE-1 do if Table_Misc[i]=w then
begin
case i div 94 of
0:result:=$2121+i;
1:result:=$2221+i-94;
2:result:=$2821+i-94-94;
end;
exit;
end;
for i:=0 to NUMBER_EXTUNICODE-1 do if Table_ExtASCII[i]=w then
begin
result:=i+$80;
exit;
end;
result:=0;
end;
function UTF2Unicode(b1,b2,b3,b4:byte;var inc:byte):word;
begin
if (b1 and UTF8_MASK1)=UTF8_VALUE1 then
begin
result:=b1;
inc:=1;
exit;
end else if (b1 and UTF8_MASK2)=UTF8_VALUE2 then
begin
result:=((b1 and $1f) shl 6) or (b2 and $3f);
inc:=2;
exit;
end else if (b1 and UTF8_MASK3)=UTF8_VALUE3 then
begin
result:=((b1 and $0f) shl 12) or ((b2 and $3f) shl 6) or (b3 and $3f);
inc:=3;
exit;
end else if (b1 and UTF8_MASK4)=UTF8_VALUE4 then
begin
result:=$ffff;
inc:=4;
end else begin
Result:=b1; //because we don't know what else to do
inc:=1;
end;
end;
function _is(b:word;cl:byte):boolean;
begin
case cl of
IS_EUC:result:=(b>=161) and (b<=254);
IS_HALFKATA:result:=(b>=161) and (b<=223);
IS_SJIS1:result:=((b>=129) and (b<=159)) or ((b>=224) and (b<=239));
IS_SJIS2:result:=(b>=64) and (b<=252);
IS_MARU:result:=(b>=202) and (b<=206);
IS_NIGORI:result:=((b>=182) and (b<=196)) or ((b>=202) and (b<=206)) or (b=179);
IS_JIS:result:=(b and $7f00)>0;
else result:=false;
end;
end;
procedure TEUCEncoding.Read(ABytes: PByte; AChars: PWideChar;
var ABytesRemaining: integer; var ACharsRemaining: integer);
var b1, b2: byte;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
while MaxChars>0 do begin
if AStream.Read(b1,1)<>1 then break;
if _is(b1,IS_EUC) then begin
if AStream.Read(b2,1)<>1 then break;
Result[pos] := WideChar(JIS2Unicode((b1*256+b2) and $7f7f));
end else
Result[pos] := WideChar(b1);
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TEUCEncoding.Write(AChars: PWideChar; ABytes: PByte;
var ACharsRemaining: integer; var ABytesRemaining: integer);
var i: integer;
w: word;
begin
for i := 1 to Length(AData) do begin
w := Unicode2JIS(Word(AData[i]));
if _is(w,IS_JIS) then
_fwrite2(AStream,
((w shr 8) or $80)
+ ((w mod 256) or $80) shl 8
)
else if (w and $80)>0 then
_fwrite2(AStream,
JIS_SS2
+ (w and $7f) shl 8
)
else
_fwrite1(AStream, w);
end;
end;
procedure TSJISEncoding.Read(ABytes: PByte; AChars: PWideChar;
var ABytesRemaining: integer; var ACharsRemaining: integer);
var b1, b2: byte;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
while MaxChars>0 do begin
if AStream.Read(b1,1)<>1 then break;
if _is(b1,IS_SJIS1) then begin
if AStream.Read(b2,1)<>1 then break;
if _is(b2,IS_SJIS2) then
Result[pos] := WideChar(JIS2Unicode(SJIS2JIS(b1*256+b2)))
else
Result[pos] := WideChar(JIS2Unicode(b1*256+b2));
end else
Result[pos] := WideChar(b1);
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TSJISEncoding.Write(AChars: PWideChar; ABytes: PByte;
var ACharsRemaining: integer; var ABytesRemaining: integer);
var i: integer;
w: word;
begin
for i := 1 to Length(AData) do begin
w:=Unicode2JIS(Word(AData[i]));
if _is(w,IS_JIS) then
begin
w:=jis2sjis(w);
_fwrite2(AStream, _swapw(w));
end else
_fwrite1(AStream, w);
end;
end;
procedure TBaseJISEncoding.Read(ABytes: PByte; AChars: PWideChar;
var ABytesRemaining: integer; var ACharsRemaining: integer);
var b1, b2: byte;
inp_intwobyte: boolean;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
inp_intwobyte := false;
while true do begin
if AStream.Read(b1,1)<>1 then break;
if b1=JIS_ESC then
begin
if AStream.Read(b2,1)<>1 then break;
if (b2=ord('$')) or (b2=ord('(')) then AStream.Read(b1,1); //don't care about the result
if (b2=ord('K')) or (b2=ord('$')) then inp_intwobyte:=true else inp_intwobyte:=false;
//Do not exit, continue to the next char
end else begin
if (b1=JIS_NL) or (b1=JIS_CR) then
Result[pos] := WideChar(b1)
else begin
if AStream.Read(b2,1)<>1 then break;
if inp_intwobyte then
Result[pos] := WideChar(JIS2Unicode(b1*256+b2))
else
Result[pos] := WideChar(b1);
end;
Inc(pos);
Dec(MaxChars);
if MaxChars<=0 then break;
end;
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TBaseJISEncoding.Write(AChars: PWideChar; ABytes: PByte;
var ACharsRemaining: integer; var ABytesRemaining: integer);
var i: integer;
w: word;
begin
for i := 1 to Length(AData) do begin
w := Word(AData[i]);
if (w=13) or (w=10) then
begin
_fputend(AStream);
_fwrite1(AStream, w);
end else
begin
w:=Unicode2JIS(w);
if _is(w,IS_JIS) then
begin
_fputstart(AStream);
_fwrite2(AStream, _swapw(w));
end else begin
_fputend(AStream);
_fwrite1(AStream, w);
end;
end;
end;
end;
procedure TBaseJISEncoding._fputstart(AStream: TStream);
begin
if intwobyte then exit;
intwobyte:=true;
AStream.Write(StartMark[0], Length(StartMark));
end;
procedure TBaseJISEncoding._fputend(AStream: TStream);
begin
if not intwobyte then exit;
intwobyte:=false;
AStream.Write(EndMark[0], Length(EndMark));
end;
constructor TJISEncoding.Create;
begin
inherited;
StartMark := TBytes.Create(JIS_ESC, ord('B'), ord('$'));
EndMark := TBytes.Create(JIS_ESC, ord('('), ord('J'));
end;
constructor TOldJISEncoding.Create;
begin
inherited;
StartMark := TBytes.Create(JIS_ESC, ord('@'), ord('$'));
EndMark := TBytes.Create(JIS_ESC, ord('('), ord('J'));
end;
constructor TNECJISEncoding.Create;
begin
inherited;
StartMark := TBytes.Create(JIS_ESC, ord('K'));
EndMark := TBytes.Create(JIS_ESC, ord('H'));
end;
procedure TGBEncoding.Read(ABytes: PByte; AChars: PWideChar;
var ABytesRemaining: integer; var ACharsRemaining: integer);
var b1, b2: byte;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
while MaxChars>0 do begin
if AStream.Read(b1,1)<>1 then break;
if (b1>=$a1) and (b1<=$fe) then
begin
if AStream.Read(b2,1)<>1 then break;
if (b2>=$a1) and (b2<=$fe) then
Result[pos] := WideChar(Table_GB[(b1-$a0)*96+(b2-$a0)])
else
Result[pos] := WideChar(b1*256+b2);
end else
Result[pos] := WideChar(b1);
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TGBEncoding.Write(AChars: PWideChar; ABytes: PByte;
var ACharsRemaining: integer; var ABytesRemaining: integer);
var i,j: integer;
w: word;
begin
for j := 1 to Length(AData) do begin
w := Word(AData[j]);
if w<128 then
_fwrite1(AStream, byte(w))
else
begin
for i:=0 to 96*96-1 do if Table_GB[i]=w then begin
_fwrite2(AStream,
(i mod 96+$a0) shl 8
+ (i div 96+$a0)
);
exit;
end;
_fwrite2(AStream,
(w mod 256) shl 8
+ (w div 256)
);
end;
end;
end;
procedure TBIG5Encoding.Read(ABytes: PByte; AChars: PWideChar;
var ABytesRemaining: integer; var ACharsRemaining: integer);
var b1, b2: byte;
pos: integer;
begin
SetLength(Result, MaxChars);
pos := 1;
while MaxChars>0 do begin
if AStream.Read(b1,1)<>1 then break;
if (b1>=$a1) and (b1<=$fe) then
begin
if AStream.Read(b2,1)<>1 then break;
if (b2>=$40) and (b2<=$7f) then
Result[pos] := WideChar(Table_Big5[(b1-$a0)*160+(b2-$40)])
else
if (b2>=$a1) and (b2<=$fe) then
Result[pos] := WideChar(Table_Big5[(b1-$a0)*160+(b2-$a0)])
else
Result[pos] := WideChar(b1*256+b2);
end else
Result[pos] := WideChar(b1);
Inc(pos);
Dec(MaxChars);
end;
if pos<Length(Result) then
SetLength(Result, pos-1);
end;
procedure TBIG5Encoding.Write(AChars: PWideChar; ABytes: PByte;
var ACharsRemaining: integer; var ABytesRemaining: integer);
var i, j: integer;
w: word;
begin
for j := 1 to Length(AData) do begin
w := Word(AData[j]);
if w<128 then
_fwrite1(AStream, byte(w))
else
begin
for i:=0 to 96*160-1 do if Table_GB[i]=w then begin
_fwrite2(AStream,
(i mod 96+$a0) shl 8
+ (i div 96+$a0)
);
exit;
end;
_fwrite2(AStream, _swapw(w));
end;
end;
end;
function Conv_DetectType(AStream: TStream): CEncoding;
begin
if not Conv_DetectType(AStream, Result) then
Result := nil;
end;
{ Detects file encoding. Returns true if it's truly detected (i.e. through BOM),
or false if it's a best guess. }
function Conv_DetectType(AStream: TStream; out AEncoding: CEncoding): boolean;
var i,b,j:integer;
w: word;
eucsjis:boolean;
asciionly:boolean;
failed_le, failed_be: boolean;
begin
AStream.Seek(0, soBeginning);
AEncoding := nil;
Result := false;
if TUTF16LEEncoding.ReadBom(AStream) then begin
AEncoding := TUTF16LEEncoding;
Result := true;
exit;
end;
if TUTF16BEEncoding.ReadBom(AStream) then begin
AEncoding := TUTF16BEEncoding;
Result := true;
exit;
end;
if TUTF8Encoding.ReadBom(AStream) then begin
AEncoding := TUTF8Encoding;
Result := true;
exit;
end;
{ UTF16LE/BE first try }
failed_le:=false;
failed_be:=false;
eucsjis:=true;
while (AStream.Read(w, 2)=2) and not (failed_be and failed_le) do
begin
if Unicode2JIS(w)=0 then failed_le:=true;
if Unicode2JIS(_swapw(w))=0 then failed_be:=true;
if (w and $8080)<>$8080 then eucsjis:=false;
end;
if eucsjis then
AEncoding:=nil
else
if failed_be and not failed_le then
AEncoding := TUTF16LEEncoding
else
if failed_le and not failed_be then
AEncoding := TUTF16BEEncoding;
if AEncoding<>nil then exit;
AStream.Seek(0, soBeginning);
asciionly:=true;
AEncoding := TUTF8Encoding;
i := 0; //zero higher bytes
while (AStream.Read(i, 1)=1) and (AEncoding=TUTF8Encoding) do
begin
b:=0;
if (i and UTF8_MASK1)=UTF8_VALUE1 then b:=0 else
if (i and UTF8_MASK2)=UTF8_VALUE2 then b:=1 else
if (i and UTF8_MASK3)=UTF8_VALUE3 then b:=2 else
if (i and UTF8_MASK4)=UTF8_VALUE4 then b:=3 else AEncoding:=nil;
if b>0 then asciionly:=false;
for j:=0 to b-1 do
begin
if AStream.Read(i, 1)=1 then //else do not drop the encoding, tolerate missing bytes, stream might have been cut short
if (i and $c0)<>$80 then AEncoding:=nil;
end;
end;
if asciionly then AEncoding:=nil;
if AEncoding<>nil then exit;
{$IFDEF GUESS_UTF16}
{ UTF16 LE/BE second try }
if AEncoding=nil then
if GuessUTF16(AStream, AEncoding) and (AEncoding<>nil) then begin
Result := true;
exit;
end;
{$ENDIF}
AStream.Seek(0, soBeginning);
AEncoding := TAsciiEncoding;
eucsjis:=false;
i:=0;
while (AEncoding = TAsciiEncoding) or ((AEncoding=nil) and eucsjis) do
begin
if AStream.Read(i, 1)<>1 then break;
if i=JIS_ESC then
begin
if AStream.Read(i, 1)<>1 then i:=-1;
if i=ord('$') then
begin
if AStream.Read(i, 1)<>1 then i:=-1;
if i=ord('B') then AEncoding:=TJISEncoding;
if i=ord('@') then AEncoding:=TOldJISEncoding;
end else
if i=ord('K') then AEncoding:=TNECJISEncoding;
end else if i=JIS_SS2 then
begin
if AStream.Read(i, 1)<>1 then i:=-1;
if (i>=161) and (i<=223) then begin
AEncoding:=nil;
eucsjis:=true;
end
else if (i<>127) and (i>=64) and (i<=252) then AEncoding:=TSJISEncoding;
end else if (i>=129) and (i<=159) then AEncoding:=TSJISEncoding
else if (i>=161) and (i<=223) then
begin
if AStream.Read(i, 1)<>1 then i:=-1;
if (i>=240) and (i<=254) then AEncoding:=TEUCEncoding
else if (i>=161) and (i<=223) then begin
AEncoding:=nil;
eucsjis:=true;
end
else if (i>=224) and (i<=239) then
begin
AEncoding:=nil;
eucsjis:=true;
while ((i>=64) and (AEncoding=nil) and eucsjis) do
begin
if i>=129 then
begin
if (i<=141) or ((i>=143) and (i<=159)) then AEncoding:=TSJISEncoding else
if (i>=253) and (i<=254) then AEncoding:=TEUCEncoding;
end;
if AStream.Read(i, 1)<>1 then break;
end;
end else if i<=159 then AEncoding:=TSJISEncoding;
end else if (i>=240) and (i<=254) then AEncoding:=TEUCEncoding
else if (i>=224) and (i<=239) then
begin
if AStream.Read(i, 1)<>1 then i:=-1;
if ((i>=64) and (i<=126)) or ((i>=128) and (i<=160)) then AEncoding:=TSJISEncoding
else if (i>=253) and (i<=254) then AEncoding:=TEUCEncoding
else if (i>=161) and (i<=252) then begin
AEncoding:=nil;
eucsjis:=true;
end;
end;
end;
if (AEncoding=nil) and eucsjis then
AEncoding:=TSJISEncoding;
end;
{$IFDEF GUESS_UTF16}
{ Tries to guess the variety of UTF16 encoding used in the text heuristically.
Return values:
True, TUTF16LE --- "I think it may be UTF16LE"
True, TUTF16BE --- "I think it may be UTF16BE"
True, nil --- "I don't think it's UTF16 at all"
False --- "I'm not sure" }
{ Methods used:
1. Count the number of leading and trailing surrogates, assuming it was LE or BE.
If the guess is right, the number must be almost equal (spare for one surrogate
being lost on the border of the sample block, or for somewhat broken text).
Pros: If the number of surrogates is high enough (>4-5) AND their numbers are
equal, this almost certainly means the guess is right.
Cons: In most of the texts there are no surrogates at all, or sometimes one
or two, which is too small because they can occur spontaneously in unrelated
files.
2. Count the distribution of the values in the odd an in the even bytes in the
text. Supposedly, higher position values will have just a bunch of highly
popular values while lower position values will be distributed mostly randomly.
Cons: It's not so simple in real life, and many EUC or JIS texts may trigger
this heuristic to fire accidentally if you set the borderline checks low enough.
}
function GuessUTF16(AStream: TStream; out AEncoding: CEncoding): boolean;
var lead_le, lead_be,
trail_le, trail_be: integer;
evenb, oddb: array[0..255] of word;
evenavg, oddavg: double;
evencnt, oddcnt: integer;
totalread: integer;
failed_le, failed_be: boolean;
i: integer;
w: word;
begin
lead_le := 0;
lead_be := 0;
trail_le := 0;
trail_be := 0;
for i := 0 to 255 do begin
oddb[i] := 0;
evenb[i] := 0;
end;
{ Parse up to 32Kb of text }
totalread := 0;
AStream.Seek(0, soBeginning);
while totalread < 32767 do begin
if AStream.Read(w, 2)<>2 then break;
{ Build the distribution of leading and trailing byte values }
Inc(evenb[w and $00FF]); //0, 2, 4...
Inc(oddb[w shr 8]); //1, 3, 5...
{ Count the number of occurences of leading surrogates and trailing
surrogates, looking through LE or BE glasses. }
if (w>=$D800) and (w<=$DBFF) then Inc(lead_le);
if (w>=$DC00) and (w<=$DFFF) then Inc(trail_le);
w := _swapw(w);
if (w>=$D800) and (w<=$DBFF) then Inc(lead_be);
if (w>=$DC00) and (w<=$DFFF) then Inc(trail_be);
Inc(totalread);
end;
failed_le := false;
failed_be := false;
{ Test surrogates. The number of leading surrogates must match that of trailing. }
{ If either of the sum pairs is close to (0,0) we haven't gathered enough data
to make a solid comparison. }
if (lead_le<=2) and (trail_le<=2) then begin
if Abs(lead_be-trail_be)>2 then
failed_be := true;
{ Continue to the next test. }
end else
if (lead_be<=2) and (trail_be<=2) then begin
if Abs(lead_le-trail_le)>2 then
failed_le := true;
{ Continue to the next test. }
end else
if Abs(lead_le-trail_le)<=2 then
if Abs(lead_be-trail_be)<=2 then begin
{ Both match, continue to the next test. }
end else
begin
{ BE fails, LE matches }
AEncoding := TUTF16LEEncoding;
Result := true;
exit;
end
else
if Abs(lead_be-trail_be)<=2 then begin
{ BE matches, LE fails }
AEncoding := TUTF16BEEncoding;
Result := true;
exit;
end
else begin
{ Both invalid }
AEncoding := nil;
Result := true;
exit;
end;
{ Chars in text are usually grouped pretty tightly, i.e. kana is $30**,
latin is $00** etc. Lower byte will be distributed evenly, while higher byte
will have several spikes.
We use this to figure which is the leading byte.
One of the broadest cases, CJK United Ideographs covers $34-$4D which is only
25 values for the higher byte out of 255 possible, less than 10%. }
{ This is pointless if we've had less than 255 characters of text }
{ if totalread<255 then begin
AEncoding := nil;
Result := false;
exit;
end;}
{ Calculate averages }
evenavg := 0;
oddavg := 0;
for i := 0 to 255 do begin
evenavg := evenavg + evenb[i];
oddavg := oddavg + oddb[i];
end;
evenavg := evenavg / 255;
oddavg := oddavg / 255;
{ Number of items higher than average }
evencnt := 0;
oddcnt := 0;
for i := 0 to 255 do begin
if evenb[i]>evenavg then Inc(evencnt);
if oddb[i]>oddavg then Inc(oddcnt);
end;
if (evencnt>80) and (oddcnt>80) then begin
//Both suck
AEncoding := nil;
Result := false;
exit;
end;
if (evencnt<=30) and (oddcnt>30) then begin
if failed_be then
AEncoding := nil
else
AEncoding := TUTF16BEEncoding;
Result := true;
exit;
end;
if (evencnt>30) and (oddcnt<=30) then begin
if failed_le then
AEncoding := nil
else
AEncoding := TUTF16LEEncoding;
Result := true;
exit;
end;
Result := false;
end;
{$ENDIF}
function Conv_DetectType(const AFilename: string): CEncoding;
var fsr: TStreamReader;
begin
fsr := TStreamReader.Create(
TFileStream.Create(AFilename, fmOpenRead), true);
try
Result := Conv_DetectType(fsr);
finally
FreeAndNil(fsr);
end;
end;
function Conv_DetectType(const AFilename: string; out AEncoding: CEncoding): boolean;
var fsr: TStreamReader;
begin
fsr := TStreamReader.Create(
TFileStream.Create(AFilename, fmOpenRead), true);
try
Result := Conv_DetectType(fsr, AEncoding);
finally
FreeAndNil(fsr);
end;
end;
function OpenStream(const AStream: TStream; AOwnsStream: boolean; AEncoding: CEncoding = nil): TStreamDecoder;
var fsr: TStreamReader;
begin
fsr := TStreamReader.Create(AStream, AOwnsStream);
try
if AEncoding=nil then
if not Conv_DetectType(fsr, AEncoding) and (AEncoding=nil) {not even a best guess} then
AEncoding := TAsciiEncoding;
fsr.Seek(0, soBeginning);
Result := TStreamDecoder.Open(fsr, AEncoding.Create, {OwnsStream=}true);
except
FreeAndNil(fsr);
raise;
end;
end;
function OpenTextFile(const AFilename: string; AEncoding: CEncoding = nil): TStreamDecoder;
begin
Result := OpenStream(
TFileStream.Create(AFilename, fmOpenRead or fmShareDenyNone),
{OwnsStream=}true
);
end;
function CreateTextFile(const AFilename: string; AEncoding: CEncoding): TStreamEncoder;
var fsr: TStreamWriter;
begin
fsr := TStreamWriter.Create(
TFileStream.Create(AFilename, fmCreate),
{OwnsStream=}true
);
try
Result := TStreamEncoder.Open(fsr, AEncoding.Create, {OwnsStream=}true);
except
FreeAndNil(fsr);
raise;
end;
end;
function AppendToTextFile(const AFilename: string; AEncoding: CEncoding = nil): TStreamEncoder;
var fsr: TStreamWriter;
begin
fsr := TStreamWriter.Create(
TFileStream.Create(AFilename, fmOpenReadWrite), //read is for encoding detection
{OwnsStream=}true
);
try
if AEncoding=nil then
//Conv_DetectType by filename since TStreamWriter cannot read
if not Conv_DetectType(AFilename, AEncoding) and (AEncoding=nil) {not even a best guess} then
AEncoding := TAsciiEncoding;
fsr.Seek(0, soEnd);
Result := TStreamEncoder.Open(fsr, AEncoding.Create, {OwnsStream=}true);
except
FreeAndNil(fsr);
raise;
end;
end;
//Finds a class by it's name. Good to store encoding selection in a permanent way.
function FindEncoding(const AClassName: string): CEncoding;
begin
//Stupid for now
if AClassName='TAsciiEncoding' then
Result := TAsciiEncoding
else
{$IFDEF MSWINDOWS}
if AClassName='TAcpEncoding' then
Result := TAcpEncoding
else
{$ENDIF}
if AClassName='TUTF8Encoding' then
Result := TUTF8Encoding
else
if AClassName='TUTF16LEEncoding' then
Result := TUTF16LEEncoding
else
if AClassName='TUTF16BEEncoding' then
Result := TUTF16BEEncoding
else
if AClassName='TEUCEncoding' then
Result := TEUCEncoding
else
if AClassName='TSJISEncoding' then
Result := TSJISEncoding
else
if AClassName='TJISEncoding' then
Result := TJISEncoding
else
if AClassName='TOldJISEncoding' then
Result := TOldJISEncoding
else
if AClassName='TNECJISEncoding' then
Result := TNECJISEncoding
else
if AClassName='TGBEncoding' then
Result := TGBEncoding
else
if AClassName='TBIG5Encoding' then
Result := TBIG5Encoding
else
Result := nil;
end;
{ Compares binary data in streams }
function CompareStreams(const AStream1, AStream2: TStream): boolean;
var
b1, b2: byte;
r1, r2: boolean;
begin
{ Can be easily made somewhat faster by reading in dwords and comparing
only the number of bytes read (e.g. case 1: 2: 3: 4: if (d1 & $000F) == etc.) }
Result := true;
while true do begin
r1 := (AStream1.Read(b1,1)=1);
r2 := (AStream2.Read(b2,1)=1);
if r1 xor r2 then
Result := false;
if b1<>b2 then
Result := false;
if (not r1) or (not Result) then //not Result => diff; not r1 => both over
break;
end;
end;
function CompareFiles(const AFilename1, AFilename2: string): boolean;
var f1, f2: TStream;
begin
f1 := nil;
f2 := nil;
try
f1 := TStreamReader.Create(
TFileStream.Create(AFilename1, fmOpenRead),
true
);
f2 := TStreamReader.Create(
TFileStream.Create(AFilename2, fmOpenRead),
true
);
Result := CompareStreams(f1, f2);
finally
FreeAndNil(f2);
FreeAndNil(f1);
end;
end;
{ Compatibility functions }
function AnsiFileReader(const AFilename: string): TStreamDecoder;
begin
Result := OpenTextFile(AFilename, TAcpEncoding);
end;
function UnicodeFileReader(const AFilename: string): TStreamDecoder;
begin
Result := OpenTextFile(AFilename, TUnicodeEncoding);
end;
function ConsoleReader(AEncoding: TEncoding = nil): TStreamDecoder;
var AInputHandle: THandle;
begin
AInputHandle := GetStdHandle(STD_INPUT_HANDLE);
if AEncoding=nil then begin
{$IFDEF MSWINDOWS}
{ If our outputs are redirected, we *really* do not know what to expect, so we
default to UTF8 (allows for ASCII and interoperability).
But if we are sure we're reading from console, we may optimize and use the
console CP. }
if GetFileType(AInputHandle)=FILE_TYPE_CHAR then
AEncoding := TMultibyteEncoding.Create(GetConsoleOutputCP())
else
AEncoding := TUTF8Encoding.Create();
{$ELSE}
AEncoding := TUTF8Encoding.Create();
{$ENDIF}
end;
Result := TStreamDecoder.Open(
THandleStream.Create(AInputHandle),
AEncoding,
{OwnsStream=}true
);
end;
function UnicodeStreamReader(AStream: TStream; AOwnsStream: boolean = false): TStreamDecoder;
begin
Result := TStreamDecoder.Open(AStream, TUnicodeEncoding.Create, AOwnsStream);
end;
function FileReader(const AFilename: string): TStreamDecoder;
begin
{$IFDEF UNICODE}
Result := UnicodeFileReader(AFilename);
{$ELSE}
Result := AnsiFileReader(AFilename);
{$ENDIF}
end;
function AnsiFileWriter(const AFilename: string): TStreamEncoder;
begin
Result := CreateTextFile(AFilename, TAcpEncoding);
end;
function UnicodeFileWriter(const AFilename: string): TStreamEncoder;
begin
Result := CreateTextFile(AFilename, TUnicodeEncoding);
end;
function ConsoleWriter(AEncoding: TEncoding): TStreamEncoder;
var AOutputHandle: THandle;
begin
AOutputHandle := GetStdHandle(STD_OUTPUT_HANDLE);
if AEncoding=nil then begin
{$IFDEF MSWINDOWS}
{ If our outputs are redirected, we *really* do not know which codepage to
output in, so we use UTF8 as default.
But if we are sure we're printing to console, we may optimize and use the
console CP. }
if GetFileType(AOutputHandle)=FILE_TYPE_CHAR then
AEncoding := TMultibyteEncoding.Create(GetConsoleOutputCP())
else
AEncoding := TUTF8Encoding.Create();
{$ELSE}
AEncoding := TUTF8Encoding.Create();
{$ENDIF}
end;
Result := TStreamEncoder.Open(
THandleStream.Create(AOutputHandle),
AEncoding,
{OwnsStream=}true
);
end;
function ConsoleUTF8Writer(): TStreamEncoder;
begin
Result := ConsoleWriter(TUTF8Encoding.Create);
end;
function UnicodeStreamWriter(AStream: TStream; AOwnsStream: boolean = false): TStreamEncoder;
begin
Result := TStreamEncoder.Open(AStream, TUnicodeEncoding.Create, AOwnsStream);
end;
function FileWriter(const AFilename: string): TStreamEncoder;
begin
{$IFDEF UNICODE}
Result := UnicodeFileWriter(AFilename);
{$ELSE}
Result := AnsiFileWriter(AFilename);
{$ENDIF}
end;
{ Reads out everything there is in the file and counts lines. Do not forget to
rewind later. Do not do with Console, TCP and other non-rewindable streams.
Avoid counting lines beforehand where possible, prefer just parsing for however
much lines there is. }
function GetLineCount(AText: TStreamDecoder): integer;
var ln: string;
begin
Result := 0;
while AText.ReadLn(ln) do
Inc(Result);
end;
end.
|
unit UStream;
(*====================================================================
Implementation of a stream, used for all file reads/writes
======================================================================*)
interface
uses UTypes, Classes;
const
HFILE_ERROR = -1;
stCreate = 1;
stOpenExclusive = 2;
stOpenReadNonExclusive = 3;
{ TQStream error codes }
stOk = 0;
stError = -1;
stInitError = -2;
stReadError = -3;
stWriteError = -4;
stSeekError = -5;
type
TQBufStream = object
Status : Integer;
{$ifdef mswindows}
Handle : LongWord;
{$else}
Stream : TFileStream;
{$endif}
StreamMode : Integer;
CurrentPos : longword;
CurrentSize : longword;
CheckReading: boolean; // if true, the read and seek are checked if they
// go outside the file size, but the error does not
// close the stream
Modified : boolean;
SaveArchiveAttrib: boolean;
FileName : array [0..255] of char;
constructor Init (aFileName: PChar; aStreamMode: Integer);
destructor Done;
procedure Error (Code: Integer);
procedure ReadExt (var Buf; Count: longword; var WasRead: longword);
procedure Read (var Buf; Count: longword);
procedure Write (var Buf; Count: longword);
function GetPos : Longword;
function GetSize: Longword;
procedure Seek (Pos: Longword);
procedure SeekToEnd;
procedure Flush;
function Eof : boolean;
private
procedure StreamOpen;
procedure StreamClose;
end;
//=============================================================================
implementation
uses
{$ifdef mswindows}
Windows
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
SysUtils, UExceptions, ULang;
{$R-}
const
stStreamClosed = 0;
//-----------------------------------------------------------------------------
procedure TQBufStream.Error(Code: Integer);
var
ErrorMsg: ShortString;
SaveStreamMode : Integer;
begin
Status := Code;
case Status of
stOk : exit;
stError : ErrorMsg := lsFileAccessError;
stInitError : ErrorMsg := lsFileCreationError;
stReadError : ErrorMsg := lsFileReadingError;
stWriteError: ErrorMsg := lsFileWritingError;
stSeekError : ErrorMsg := lsFileSeekingError;
else ErrorMsg := lsFileError + IntToStr(Status);
end;
SaveStreamMode := StreamMode;
StreamMode := stStreamClosed;
StreamClose;
if SaveStreamMode = stOpenReadNonExclusive
then raise EQDirNormalException.Create(ErrorMsg)
else raise EQDirFatalException.Create(ErrorMsg);
end;
//-----------------------------------------------------------------------------
procedure TQBufStream.StreamOpen;
begin
{$ifndef mswindows}
case StreamMode of
stCreate:
begin
Stream := TFileStream.Create(FileName, fmCreate);
SaveArchiveAttrib := true;
end;
stOpenExclusive:
begin
Stream := TFileStream.Create(FileName, fmOpenReadWrite or fmShareExclusive);
SaveArchiveAttrib := true;
///SaveArchiveAttrib := (GetFileAttributes(FileName) and FILE_ATTRIBUTE_ARCHIVE) <> 0;
end;
stOpenReadNonExclusive:
begin
Stream := TFileStream.Create(FileName, fmOpenRead);
SaveArchiveAttrib := true;
end;
end;
CurrentSize := Stream.Size;
if CurrentSize = $FFFFFFFF then Error(stSeekError);
CurrentPos := Stream.Seek(0,0);
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$else}
{$ifdef WIN32}
case StreamMode of
stCreate:
begin
Handle := CreateFile(FileName, GENERIC_READ or GENERIC_WRITE,
0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
SaveArchiveAttrib := true;
end;
stOpenExclusive:
begin
Handle := CreateFile(FileName, GENERIC_READ or GENERIC_WRITE,
0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
SaveArchiveAttrib := (GetFileAttributes(FileName) and FILE_ATTRIBUTE_ARCHIVE) <> 0;
end;
stOpenReadNonExclusive:
begin
Handle := CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ,
nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
SaveArchiveAttrib := true;
end;
end;
if Handle = INVALID_HANDLE_VALUE
then
begin
{
LastError := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, LastError,
0, szBuffer, 200, nil);
}
Error(stInitError);
end
else
begin
CurrentSize := SetFilePointer(Handle, 0, nil, FILE_END);
if CurrentSize = $FFFFFFFF then Error(stSeekError);
CurrentPos := SetFilePointer(Handle, 0, nil, FILE_BEGIN);
if CurrentPos = $FFFFFFFF then Error(stSeekError);
end;
{$else}
case StreamMode of
stCreate:
Handle := _lcreat(FileName, 0);
stOpenExclusive:
Handle := _lopen(FileName, OF_READWRITE or OF_SHARE_EXCLUSIVE);
stOpenReadNonExclusive:
Handle := _lopen(FileName, OF_READ or OF_SHARE_DENY_NONE);
end;
if Handle = HFILE_ERROR
then
Error(stInitError)
else
begin
CurrentSize := _llseek(Handle, 0, 2);
CurrentPos := _llseek(Handle, 0, 0);
end;
{$endif}
{$endif}
end;
//-----------------------------------------------------------------------------
procedure TQBufStream.StreamClose;
begin
{$ifdef mswindows}
{$ifdef WIN32}
if Handle <> INVALID_HANDLE_VALUE then CloseHandle(Handle);
Handle := INVALID_HANDLE_VALUE;
if ((GetFileAttributes(FileName) and FILE_ATTRIBUTE_ARCHIVE) <> 0) then
begin
// Archive attrib was set to true
if (not Modified and not SaveArchiveAttrib) then
begin
// file was not modified and Archive was not set before opening, so repair
// the situation - we do not set the Modified flag in case only header is
// updated
SetFileAttributes(FileName,
GetFileAttributes(FileName) and not FILE_ATTRIBUTE_ARCHIVE);
end;
end;
{$else}
if Handle <> HFILE_ERROR then _lclose(Handle);
Handle := HFILE_ERROR;
{$endif}
{$else}
Stream.Free;
{$endif}
end;
//-----------------------------------------------------------------------------
constructor TQBufStream.Init(aFileName: PChar; aStreamMode: Integer);
begin
Status := stOK;
StreamMode := aStreamMode;
CurrentPos := 0;
CurrentSize := 0;
CheckReading := false;
Modified := false;
SaveArchiveAttrib := true;
StrCopy(FileName, aFileName);
StreamOpen;
end;
//-----------------------------------------------------------------------------
destructor TQBufStream.Done;
begin
if StreamMode = stStreamClosed then exit;
StreamClose;
StreamMode := stStreamClosed;
end;
//-----------------------------------------------------------------------------
procedure TQBufStream.Flush;
begin
if StreamMode = stStreamClosed then exit;
{$ifdef mswindows}
{$ifdef WIN32}
FlushFileBuffers(Handle);
{$else}
StreamClose;
StreamOpen;
{$endif}
{$endif}
end;
//-----------------------------------------------------------------------------
function TQBufStream.GetPos: Longword;
begin
Result := 0;
if StreamMode = stStreamClosed then exit;
Result := CurrentPos;
end;
//-----------------------------------------------------------------------------
function TQBufStream.GetSize: Longword;
begin
Result := 0;
if StreamMode = stStreamClosed then exit;
Result := CurrentSize;
end;
//-----------------------------------------------------------------------------
function TQBufStream.Eof: boolean;
begin
Result := true;
if StreamMode = stStreamClosed then exit;
Result := CurrentPos >= CurrentSize;
end;
//-----------------------------------------------------------------------------
procedure TQBufStream.Seek(Pos: Longword);
///var
/// DistanceHigh: longword;
begin
// if CheckReading is set, the error does not closes the database
if CheckReading then
if (Pos > CurrentSize) then
raise EQDirDBaseStructException.Create(lsDBaseStructError + ' (001)');
if StreamMode = stStreamClosed then exit;
{$ifdef mswindows}
{$ifdef WIN32}
DistanceHigh := 0;
CurrentPos := SetFilePointer(Handle, Pos, @DistanceHigh, FILE_BEGIN);
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$else}
CurrentPos := _llseek(Handle, Pos, 0);
if CurrentPos = HFILE_ERROR then Error(stSeekError);
{$endif}
{$else}
///DistanceHigh := 0;
Stream.Seek(pos,0);
CurrentPos := Stream.Position;
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$endif}
end;
//-----------------------------------------------------------------------------
procedure TQBufStream.SeekToEnd;
begin
if StreamMode = stStreamClosed then exit;
{$ifdef mswindows}
{$ifdef WIN32}
if CurrentPos <> CurrentSize then
CurrentPos := SetFilePointer(Handle, 0, nil, FILE_END);
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$else}
if CurrentPos <> CurrentSize then
CurrentPos := _llseek(Handle, 0, 2);
if CurrentPos = HFILE_ERROR then Error(stSeekError);
{$endif}
{$else}
if CurrentPos <> CurrentSize then
begin
Stream.Seek(Stream.Size,0);
CurrentPos := Stream.Position;
end;
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$endif}
end;
//-----------------------------------------------------------------------------
procedure TQBufStream.ReadExt(var Buf; Count: longword; var WasRead: longword);
begin
// if CheckReading is set, the error does not closes the database
if CheckReading then
if (CurrentPos+Count) > CurrentSize then
raise EQDirDBaseStructException.Create(lsDBaseStructError + ' (002)');
if StreamMode = stStreamClosed then Error(stReadError);
{$ifdef mswindows}
{$ifdef WIN32}
if not ReadFile(Handle, Buf, Count, DWORD(WasRead), nil) then
Error(stReadError);
{$else}
WasRead := _lread(Handle, @Buf, Count);
if Integer(WasRead) = HFILE_ERROR then Error(stReadError);
{$endif}
{$else}
WasRead := Stream.Read(Buf,Count);
{$endif}
inc(CurrentPos, WasRead);
end;
//-----------------------------------------------------------------------------
procedure TQBufStream.Read(var Buf; Count: longword);
var
WasRead: longword;
begin
ReadExt(Buf, Count, WasRead);
if WasRead <> Count then Error(stReadError);
end;
//-----------------------------------------------------------------------------
procedure TQBufStream.Write(var Buf; Count: longword);
var
WasWritten: longword;
begin
if (StreamMode = stStreamClosed) or
(StreamMode = stOpenReadNonExclusive) then exit;
{$ifdef mswindows}
{$ifdef WIN32}
if not WriteFile(Handle, Buf, Count, DWORD(WasWritten), nil) then
Error(stWriteError);
if WasWritten <> Count then Error(stWriteError);
{$else}
WasWritten := _lwrite(Handle, @Buf, Count);
if Integer(WasWritten) = HFILE_ERROR then Error(stWriteError);
if WasWritten <> Count then Error(stWriteError);
{$endif}
{$else}
WasWritten := Stream.Write(buf,Count);
if WasWritten <> Count then Error(stWriteError);
{$endif}
Modified := true;
inc(CurrentPos, WasWritten);
if CurrentPos > CurrentSize then CurrentSize := CurrentPos;
end;
//-----------------------------------------------------------------------------
end.
|
unit InformePorFechas_ViewModel_Implementation;
interface
uses
Informe_Model, Informe_ViewModel_Implementation;
type
TInformePorFechas_ViewModel = class(TInforme_ViewModel)
private
fDesdeFecha: TDateTime;
fHastaFecha: TDateTime;
procedure SetDesdeFecha(const Value: TDateTime);
procedure SetHastaFecha(const Value: TDateTime);
function GetDesdeFecha: TDateTime;
function GetHastaFecha: TDateTime;
protected
function GetEmitirInformeOK: boolean; override;
function ModelClass:TdmInforme_Model_Class; override;
procedure AsignarPropiedadesModelo; override;
procedure AsignacionesIniciales; override;
public
procedure Actualizar; virtual;
property DesdeFecha:TDateTime read GetDesdeFecha write SetDesdeFecha;
property HastaFecha:TDateTime read GetHastaFecha write SetHastaFecha;
end;
implementation
uses
InformePorFechas_Model,
SysUtils;
procedure TInformePorFechas_ViewModel.AsignacionesIniciales;
begin
fDesdeFecha:=Date;
fHastaFecha:=Date;
inherited;
end;
procedure TInformePorFechas_ViewModel.AsignarPropiedadesModelo;
var
M: TdmInformePorFechas_Model;
begin
inherited;
M:=(Model as TdmInformePorFechas_Model);
M.DesdeFecha:=DesdeFecha;
M.HastaFecha:=HastaFecha;
end;
procedure TInformePorFechas_ViewModel.Actualizar;
begin
inherited;
end;
function TInformePorFechas_ViewModel.GetEmitirInformeOK: boolean;
begin
result:=(DesdeFecha<>0) and (DesdeFecha<=HastaFecha)
and inherited GetEmitirInformeOK;
end;
function TInformePorFechas_ViewModel.ModelClass: TdmInforme_Model_Class;
begin
result:=TdmInformePorFechas_Model;
end;
procedure TInformePorFechas_ViewModel.SetDesdeFecha(const Value: TDateTime);
begin
if fDesdeFecha<>Value then begin
fDesdeFecha:=Value;
CambioPropiedades;
end;
end;
procedure TInformePorFechas_ViewModel.SetHastaFecha(const Value: TDateTime);
begin
if fHastaFecha<>Value then begin
fHastaFecha:=Value;
CambioPropiedades;
end;
end;
function TInformePorFechas_ViewModel.GetDesdeFecha: TDateTime;
begin
result:=fDesdeFecha;
end;
function TInformePorFechas_ViewModel.GetHastaFecha: TDateTime;
begin
result:=fHastaFecha;
end;
end.
|
//*using winapi functions for zero memory :)
Unit ParsingJSONuni;
interface
uses
CommonTypesUnit,sysUtils,Types,WinApi.windows;
type
TJsonOCPP = class
private
FJsonMessage: string;
FDisconnect: boolean;
FJsonData: array of byte;
FPayLoadLen: int64;
FOpcode: byte;
procedure TextFrame(Response: array of byte);
procedure DataFrame(Response: array of byte);
function DecodeMessage(Response: array of byte; Len: integer): string;
procedure DecodeData(Response: array of byte; Len: integer);
public
property JsonMessage: string read FJsonMessage;
property Disconnect: boolean read FDisconnect;
constructor Create(Data: array of byte; DataSize: integer);
end;
implemenatation
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
constructor TJsonOCPP.Create(Data: array of byte; DataSize: integer);//creating json object, then parsing message
var
Databuf: array of byte;
i: integer;
begin
FPayLoadLen := 0;
FOpcode := 0;
ZeroMemory(@FJsonData, sizeof(FJsonData));
FDisconnect := false;
//initialization values
FOpcode := Data[0] and 127;
SetLength(Databuf, DataSize - 1);
for i := 1 to DataSize - 1 do
begin
Databuf[i - 1] := Data[i];
end;
case FOpcode of // OPCODE 0..D .
1:
TextFrame(Databuf);
2:
DataFrame(Databuf);
8:
FDisconnect := true;
end;
SetLength(Databuf, 0);
end;
//////////////////////////////////////////////////////////////////////////////////////////////
procedure TJsonOCPP.TextFrame(Response: array of byte);
var
lenStr: string;
Len: int64;// most value it's 16?bit's , type integer give me error ,that's why i use int64, and lenStr
begin
FPayLoadLen := Response[0] and 127;//take a lengh of message
if FPayLoadLen <= 125 then// reading https://tools.ietf.org/html/rfc6455#section-5.2
begin
FJsonMessage := DecodeMessage(Response, FPayLoadLen);
end
else if FPayLoadLen = 126 then
begin
lenStr := (inttostr(Response[1]) + inttostr(Response[2]));
Len := strtoint(lenStr);
FJsonMessage := DecodeMessage(Response, Len);
end
else if FPayLoadLen = 127 then
begin
lenStr := (inttostr(Response[1]) + inttostr(Response[2]) + inttostr(Response[3]) + inttostr(Response[4]) + inttostr(Response[5]) + inttostr(Response[6]) + inttostr(Response[7]) + inttostr(Response[8]));
Len := strtoint(lenStr);
FJsonMessage := DecodeMessage(Response, Len);
end;
|
{Описать процедуру Minmax(X,Y), записывающую в переменную Y - макксимальное из этих значений(X и Y - вещественные параметры, являющиеся одновременно входными
и выходныыми). Используя 4 вызова этой процедуры, найти минимальное и максимальное из данных чисел a,b,c,d.}
Program P2;
var
a,b,c,d,t:real;
procedure Minmax(var x,y:real);
begin
if x>y then begin
t:=x;
x:=y;
y:=t;
end;
end;
begin
writeln('a=');
readln(a);
writeln('b=');
readln(b);
writeln('c=');
readln(c);
writeln('d=');
readln(d);
Minmax(a,b);
Minmax(c,d);
Minmax(a,c);
Minmax(b,d);
writeln('min=',a);
writeln('max=',d);
readln;
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.