text stringlengths 14 6.51M |
|---|
unit TabbedFormwithNavigation;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Graphics, FMX.Forms, FMX.Dialogs, FMX.TabControl, FMX.StdCtrls,
System.Actions, FMX.ActnList, FMX.ListView.Types, FMX.Edit, FMX.ListView,
FMX.Layouts, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors,
Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope,
FMX.Memo, FMX.ListBox, Fmx.Bind.Navigator;
type
TTabbedwithNavigationForm = class(TForm)
tcMain: TTabControl;
tabEmployees: TTabItem;
tabProjects: TTabItem;
ActionList1: TActionList;
ctaEmployeeDetail: TChangeTabAction;
ctaEmployeeList: TChangeTabAction;
tcEmployee: TTabControl;
tabEmployeesList: TTabItem;
tabEmployeeDetail: TTabItem;
ToolBar2: TToolBar;
lblTitle2: TLabel;
Layout1: TLayout;
btnBack_Employees: TSpeedButton;
ListView1: TListView;
bsEmployees: TBindSourceDB;
BindingsList1: TBindingsList;
bsProjects: TBindSourceDB;
bsEmployeeProjects: TBindSourceDB;
LinkListControlToField2: TLinkListControlToField;
ctaProjectDetails: TChangeTabAction;
ctaProjectList: TChangeTabAction;
ListBox2: TListBox;
ListBoxItem5: TListBoxItem;
ListBoxItem6: TListBoxItem;
ListBoxItem7: TListBoxItem;
ListBoxGroupHeader2: TListBoxGroupHeader;
ListBoxItem8: TListBoxItem;
LinkPropertyToFieldItemDataDetail5: TLinkPropertyToField;
LinkPropertyToFieldItemDataDetail6: TLinkPropertyToField;
LinkPropertyToFieldItemDataDetail7: TLinkPropertyToField;
LinkPropertyToFieldItemDataDetail8: TLinkPropertyToField;
ScrollBox1: TScrollBox;
ListBox3: TListBox;
LinkListControlToField4: TLinkListControlToField;
Layout2: TLayout;
Button1: TButton;
Button2: TButton;
LiveBindingsBindNavigatePrior1: TFMXBindNavigatePrior;
LiveBindingsBindNavigateNext1: TFMXBindNavigateNext;
ctaProjectEmployees: TChangeTabAction;
ListView2: TListView;
bsProjectEmployess: TBindSourceDB;
ToolBar3: TToolBar;
Label2: TLabel;
LinkListControlToField1: TLinkListControlToField;
tcProjects: TTabControl;
tabProjectList: TTabItem;
tabProjectDetails: TTabItem;
lbProjectDetails: TListBox;
ListBoxGroupHeader1: TListBoxGroupHeader;
lbiProjectID: TListBoxItem;
lbiProjectName: TListBoxItem;
lbiProjectProduct: TListBoxItem;
lbiProjectLead: TListBoxItem;
lvProjects: TListView;
LinkListControlToField5: TLinkListControlToField;
MemoPROJ_DESC: TMemo;
LinkPropertyToFieldItemDataDetail9: TLinkPropertyToField;
LinkPropertyToFieldItemDataDetail10: TLinkPropertyToField;
LinkPropertyToFieldItemDataDetail11: TLinkPropertyToField;
LinkPropertyToFieldItemDataDetail12: TLinkPropertyToField;
ToolBar4: TToolBar;
Layout3: TLayout;
btnBack_Projects: TSpeedButton;
Layout4: TLayout;
btnProjectStaff: TSpeedButton;
lblTitle4: TLabel;
ToolBar5: TToolBar;
Label3: TLabel;
tabProjectEmployees: TTabItem;
ToolBar1: TToolBar;
Label1: TLabel;
Layout5: TLayout;
btnBack_Project: TSpeedButton;
Layout6: TLayout;
Button3: TButton;
Button4: TButton;
LiveBindingsBindNavigateNext2: TFMXBindNavigateNext;
LiveBindingsBindNavigatePrior2: TFMXBindNavigatePrior;
lblProjectStaffTitle: TLabel;
LinkPropertyToFieldText2: TLinkPropertyToField;
tabLogin: TTabItem;
ToolBar6: TToolBar;
Label5: TLabel;
ListBox1: TListBox;
ListBoxGroupHeader3: TListBoxGroupHeader;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxGroupHeader4: TListBoxGroupHeader;
lbiServer: TListBoxItem;
lbiPort: TListBoxItem;
sbLogin: TScrollBox;
lbiURLPath: TListBoxItem;
edtURLPath: TEdit;
edtPort: TEdit;
edtServer: TEdit;
edtUserName: TEdit;
edtPassword: TEdit;
btnLogin: TButton;
LinkControlToField1: TLinkControlToField;
LinkControlToField2: TLinkControlToField;
LinkControlToField3: TLinkControlToField;
LinkControlToField4: TLinkControlToField;
LinkControlToField5: TLinkControlToField;
procedure FormCreate(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure OnEmployeeSelected(const Sender: TObject;
const AItem: TListViewItem);
procedure OnProjectClick(const Sender: TObject; const AItem: TListViewItem);
procedure btnLoginClick(Sender: TObject);
private
{ Private declarations }
procedure SetTabsActive(State : Boolean);
public
{ Public declarations }
end;
var
TabbedwithNavigationForm: TTabbedwithNavigationForm;
implementation
uses
BackButtonManager,
DataModuleMain;
{$R *.fmx}
procedure TTabbedwithNavigationForm.btnLoginClick(Sender: TObject);
begin
// Update the details on the screen into the Object
DataModule1.pbsServerSettings.ApplyUpdates;
// Reconnect (with the new settings)
DataModule1.SQLConnection1.Connected := False;
DataModule1.SQLConnection1.Connected := True;
SetTabsActive(DataModule1.SQLConnection1.Connected);
end;
procedure TTabbedwithNavigationForm.FormCreate(Sender: TObject);
begin
{ This defines the default active tab at runtime }
tcMain.ActiveTab := tcMain.Tabs[0];
tcEmployee.ActiveTab := tabEmployeesList;
tcProjects.ActiveTab := tabProjectList;
SetTabsActive(False);
if TOSVersion.Platform = pfAndroid then
TBackActionManager.HideBackActionControls(Self);
end;
procedure TTabbedwithNavigationForm.FormKeyUp(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
var
BackAction : TChangeTabAction;
begin
if {(TOSVersion.Platform = pfAndroid) and} (Key = vkHardwareBack) then begin
BackAction := TBackActionManager.FindBackAction(tcMain,True);
if Assigned(BackAction) then begin
BackAction.ExecuteTarget(Self);
Key := 0;
end;
end;
end;
procedure TTabbedwithNavigationForm.OnEmployeeSelected(const Sender: TObject;
const AItem: TListViewItem);
begin
// On List Click - Navigate to Detail
ctaEmployeeDetail.ExecuteTarget(Self);
end;
procedure TTabbedwithNavigationForm.OnProjectClick(const Sender: TObject;
const AItem: TListViewItem);
begin
// On List Click - Navigate to Detail
ctaProjectDetails.ExecuteTarget(Self);
end;
procedure TTabbedwithNavigationForm.SetTabsActive(State: Boolean);
begin
tabEmployees.Enabled := State;
tabProjects.Enabled := State;
if State then
tcMain.ActiveTab := tabEmployees
else
tcMain.ActiveTab := tabLogin;
end;
end.
|
unit About;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMemo,
ComCtrls, Dialogs;
type
TAboutBox = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Panel1: TPanel;
ProgramIcon: TImage;
ProductName: TLabel;
Panel2: TPanel;
OKButton: TButton;
cxMemo1: TcxMemo;
Label1: TLabel;
Label2: TLabel;
procedure OKButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function GetVersionStrInfo:string;
end;
var
AboutBox: TAboutBox;
implementation
{$R *.dfm}
procedure TAboutBox.OKButtonClick(Sender: TObject);
begin
ModalResult:=mrYes;
end;
function TAboutBox.GetVersionStrInfo:string;
var
VerInfoSize: DWORD;
VerInfo: Pointer;
VerValueSize: DWORD;
VerValue: PVSFixedFileInfo;
Dummy: DWORD;
V1,V2,V3,V4:DWORD;
begin
VerInfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy);
if VerInfoSize = 0 then begin
Dummy := GetLastError;
ShowMessage(IntToStr(Dummy));
end; {if}
GetMem(VerInfo, VerInfoSize);
GetFileVersionInfo(PChar(ParamStr(0)), 0, VerInfoSize, VerInfo);
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
with VerValue^ do begin
V1 := dwFileVersionMS shr 16;
V2 := dwFileVersionMS and $FFFF;
V3 := dwFileVersionLS shr 16;
V4 := dwFileVersionLS and $FFFF;
end;
FreeMem(VerInfo, VerInfoSize);
GetVersionStrInfo:=' '+IntToStr(V1)+'.'+IntToStr(V2)+'.'+IntToStr(V3)+'.'+IntToStr(V4)+' ';
end;
procedure TAboutBox.FormCreate(Sender: TObject);
begin
Label1.Caption:='Âåðñ³ÿ '+GetVersionStrInfo;
if FileExists(ExtractFilepath(Application.ExeName)+'\'+'MBook_Whats_New.txt')
then cxMemo1.Lines.LoadFromFile(ExtractFilepath(Application.ExeName)+'\'+'MBook_Whats_New.txt');
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmGuage
Purpose : Visual UI eye-candy type gages.
Date : 09-03-1998
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmGauge;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, math;
type
TGaugeShape = (gsTriangle, gsVertRect, gsHorzRect, gsEllipse, gsArc, gsPole);
TGaugeBorder = (gbNone, gbSingle, gbRaised, gbLowered);
TrmGauge = class(TGraphicControl)
private
{ Private declarations }
fBorder : TGaugeBorder;
fShape : TGaugeShape;
fgradient, fusemiddle: boolean;
fpercent : integer;
fStartColor, fMiddleColor, fEndColor : TColor;
fOnChangeEvent : TNotifyEvent;
procedure SetGradient(Value:Boolean);
procedure SetShape(Value : TGaugeShape);
procedure SetBorder(Value : TGaugeBorder);
procedure SetPercent(value:integer);
procedure SetStartColor(Value : TColor);
procedure SetMiddleColor(Value:TColor);
procedure SetEndColor(Value :TColor);
procedure SetUseMiddle(Value:Boolean);
protected
{ Protected declarations }
function ColorUsed(TestColor:TColor):boolean;
function UniqueColor:TColor;
function CalcColorIndex(StartColor, EndColor:TColor; Steps, ColorIndex:integer):TColor;
function GradientColorIndex(ColorIndex:integer):TColor;
procedure GetBorderColors(var TopColor, BottomColor:TColor);
procedure PaintTriangle;
procedure PaintEllipse;
procedure PaintHorzRect;
procedure PaintVertRect;
procedure PaintArc;
procedure PaintPole;
procedure paint; override;
public
{ Public declarations }
constructor Create(AOwner:TComponent); override;
published
{ Published declarations }
property Border : TGaugeBorder read fborder write SetBorder default gbsingle;
property Shape : TGaugeShape read fshape write SetShape default gsVertRect;
property GradientFill : boolean read fGradient write SetGradient default False;
property Percent:integer read fpercent write setpercent default 0;
property FillColor : TColor read fStartColor write SetStartColor default clLime;
property GradientColor : TColor read fEndColor write SetEndColor default clRed;
property MedianColor : TColor read fMiddleColor write SetMiddleColor default clYellow;
property UseMedianColor : Boolean read fusemiddle write setusemiddle default false;
property OnChange : TNotifyEvent read fOnChangeEvent write fOnChangeEvent;
end;
implementation
{ TrmGauge }
constructor TrmGauge.Create(AOwner:TComponent);
begin
inherited create(AOwner);
width := 100;
height := 50;
fgradient := false;
fshape := gsVertRect;
fborder := gbSingle;
fstartcolor := cllime;
fendcolor := clred;
fmiddlecolor := clyellow;
fusemiddle := false;
fpercent := 0;
end;
procedure TrmGauge.paint;
begin
case shape of
gsTriangle : PaintTriangle;
gsHorzRect : PaintHorzRect;
gsEllipse : PaintEllipse;
gsArc : PaintArc;
gsVertRect : PaintVertRect;
gsPole : PaintPole;
end;
end;
procedure TrmGauge.GetBorderColors(var TopColor, BottomColor:TColor);
begin
case border of
gbSingle:begin
topColor := clWindowFrame;
bottomcolor := topcolor;
end;
gbRaised:begin
topcolor := clbtnhighlight;
bottomcolor := clbtnshadow;
end;
gbLowered:begin
topcolor := clbtnshadow;
bottomcolor := clbtnhighlight;
end;
else
begin
topcolor := clbtnface;
bottomcolor := topcolor;
end;
end;
end;
procedure TrmGauge.PaintHorzRect;
var
bmp : tbitmap;
wrect, wr2 : TRect;
topColor, bottomcolor : TColor;
NewBrush, OldBrush : HBrush;
loop : integer;
begin
bmp := tbitmap.create;
bmp.width := width;
bmp.height := height;
bmp.canvas.brush.color := clbtnface;
bmp.canvas.fillrect(rect(0,0,width-1,height-1));
GetBorderColors(TopColor,BottomColor);
with bmp.Canvas do
begin
wrect := rect(0,0,width,height);
if border <> gbNone then
begin
pen.color := TopColor;
PolyLine([point(width-1,0),point(0,0),point(0,height-1)]);
pen.color := BottomColor;
PolyLine([point(0,height-1),point(width-1,height-1),point(width-1,0)]);
inflaterect(wrect,-1,-1);
end;
brush.color := clbtnface;
fillrect(wrect);
if gradientfill then
begin
for loop := 0 to percent-1 do
begin
wr2 := rect(0,wrect.top, 0,wrect.bottom);
wr2.Left := wrect.Left+ MulDiv (loop , wrect.Right-wrect.Left, 100);
wr2.Right := wrect.Left+ MulDiv (loop + 1, wrect.Right-wrect.Left, 100);
NewBrush := CreateSolidBrush(GradientColorIndex(loop+1));
OldBrush := SelectObject(bmp.Canvas.handle, NewBrush);
try
PatBlt(bmp.Canvas.handle, wr2.Left, wr2.Top, wr2.Right-wr2.Left, wr2.Bottom-wr2.Top, PATCOPY);
finally
SelectObject(bmp.Canvas.handle, OldBrush);
DeleteObject(NewBrush);
end;
end;
end
else
begin
wrect.Right := wrect.Left + (((wrect.Right-Wrect.left) * percent) div 100);
brush.color := fillcolor;
fillrect(wrect);
end;
end;
bitblt(canvas.handle,0,0,width,height,bmp.canvas.handle,0,0,srccopy);
bmp.free;
end;
procedure TrmGauge.PaintVertRect;
var
bmp : TBitmap;
wrect, wr2 : TRect;
topColor, bottomcolor : TColor;
NewBrush, OldBrush : HBrush;
loop : integer;
begin
bmp := tbitmap.create;
bmp.width := width;
bmp.height := height;
bmp.canvas.brush.color := clbtnface;
bmp.canvas.fillrect(rect(0,0,width-1,height-1));
GetBorderColors(TopColor,BottomColor);
with bmp.canvas do
begin
wrect := rect(0,0,width,height);
if border <> gbNone then
begin
pen.color := TopColor;
PolyLine([point(width-1,0),point(0,0),point(0,height-1)]);
pen.color := BottomColor;
PolyLine([point(0,height-1),point(width-1,height-1),point(width-1,0)]);
inflaterect(wrect,-1,-1);
end;
brush.color := clbtnface;
fillrect(wrect);
if gradientfill then
begin
for loop := 0 to percent-1 do
begin
wr2 := rect(wrect.left,0,wrect.right,0);
wr2.Bottom := wrect.Bottom- MulDiv (loop , wrect.Bottom-wrect.Top, 100);
wr2.Top := wrect.Bottom- MulDiv (loop + 1, wrect.Bottom-wrect.Top, 100);
NewBrush := CreateSolidBrush(GradientColorIndex(loop+1));
OldBrush := SelectObject(bmp.canvas.handle, NewBrush);
try
PatBlt(bmp.canvas.handle, wr2.Left, wr2.Top, wr2.Right-wr2.Left, wr2.Bottom-wr2.Top, PATCOPY);
finally
SelectObject(bmp.canvas.handle, OldBrush);
DeleteObject(NewBrush);
end;
end;
end
else
begin
wrect.Top := wrect.Bottom - (((wrect.Bottom-Wrect.Top) * percent) div 100);
brush.color := fillcolor;
fillrect(wrect);
end;
end;
bitblt(canvas.handle,0,0,width,height,bmp.canvas.handle,0,0,srccopy);
bmp.free;
end;
procedure TrmGauge.PaintTriangle;
var
bmp : TBitMap;
topColor, bottomcolor : TColor;
theta, adjacent : double;
NewBrush, OldBrush : HBrush;
NewPen, OldPen : HPen;
loop : integer;
begin
bmp := tbitmap.create;
bmp.width := width;
bmp.height := height;
bmp.canvas.brush.color := clbtnface;
bmp.canvas.fillrect(rect(0,0,width-1,height-1));
GetBorderColors(TopColor,BottomColor);
with bmp.canvas do
begin
brush.color := clbtnface;
pen.color := brush.color;
Polygon([point(width-1,0),point(0,height-1),point(width-1,height-1)]);
if percent > 0 then
begin
if gradientfill then
begin
theta := ArcTan(height/width);
for loop := Percent downto 1 do
begin
NewBrush := CreateSolidBrush(GradientColorIndex(loop));
OldBrush := SelectObject(bmp.canvas.handle, NewBrush);
NewPen := CreatePen(ps_Solid,1,GradientColorIndex(loop));
OldPen := SelectObject(bmp.canvas.handle, NewPen);
try
adjacent := ((width-1) * loop) / 100;
polygon([point(0,height-1),
point(round(adjacent),height-1),
point(round(adjacent),(height)-trunc(tan(theta) * adjacent))]);
finally
SelectObject(bmp.canvas.handle, OldPen);
DeleteObject(NewPen);
SelectObject(bmp.canvas.handle, OldBrush);
DeleteObject(NewBrush);
end;
end;
end
else
begin
brush.color := fillcolor;
pen.color := fillcolor;
theta := ArcTan(height/width);
adjacent := ((width-1) * percent) / 100;
polygon([point(0,height-1),
point(round(adjacent),height-1),
point(round(adjacent),(height)-trunc(tan(theta) * adjacent))]);
end;
end;
if border <> gbNone then
begin
pen.color := TopColor;
PolyLine([point(width-1,0),point(0,height-1)]);
pen.color := BottomColor;
PolyLine([point(0,height-1),point(width-1,height-1),point(width-1,0)]);
end;
end;
bitblt(canvas.handle,0,0,width,height,bmp.canvas.handle,0,0,srccopy);
bmp.free;
end;
procedure TrmGauge.PaintArc;
var
bmp : TBitMap;
topColor, bottomcolor : TColor;
angle, incangle : double;
lastx, lasty : integer;
NewBrush, OldBrush : HBrush;
NewPen, OldPen : HPen;
loop : integer;
begin
bmp := tbitmap.create;
bmp.width := width;
bmp.height := height;
bmp.canvas.brush.color := clbtnface;
bmp.canvas.fillrect(rect(0,0,width-1,height-1));
GetBorderColors(TopColor,BottomColor);
with bmp.canvas do
begin
Brush.Color := clbtnface;
pen.color := clbtnface;
Pie(0, 0, Width-1, (Height shl 1) - 1, Width-1, height - 1, 0, height - 1);
if percent > 0 then
begin
if gradientfill then
begin
lastx := 0;
lasty := height-1;
for loop := 1 to percent do
begin
NewBrush := CreateSolidBrush(GradientColorIndex(loop));
OldBrush := SelectObject(bmp.canvas.handle, NewBrush);
NewPen := CreatePen(ps_Solid,1,GradientColorIndex(loop));
OldPen := SelectObject(bmp.canvas.handle, NewPen);
try
if loop < percent then incangle := 0.027
else
incangle := 0;
Angle := (Pi * ((loop / 100)));
pie(0, 0, width-1, (Height shl 1) - 1, Round(((Width shr 1)-1) * (1 - Cos(Angle+incangle))), Round((height - 1) * (1 - Sin(Angle+incangle))), lastx, lasty);
lastx := Round(((Width shr 1)-1) * (1 - Cos(Angle)));
lasty := Round((height - 1) * (1 - Sin(Angle)));
finally
SelectObject(bmp.canvas.handle, OldPen);
DeleteObject(NewPen);
SelectObject(bmp.canvas.handle, OldBrush);
DeleteObject(NewBrush);
end;
end;
end
else
begin
Pen.Color := clblack;
Pen.Width := 1;
brush.color := fillcolor;
Angle := (Pi * ((Percent / 100)));
pie(0, 0, width-1, (Height shl 1) - 1, Round(((Width shr 1)-1) * (1 - Cos(Angle))), Round((height - 1) * (1 - Sin(Angle))), 0, height-1);
end;
end;
if border <> gbNone then
begin
Pen.Width := 1;
Pen.Color := TopColor;
Arc (0, 0, width-1, (height shl 1)-1, // ellipse
width-1, 0, // start
0, (height shl 1)-1); // end
Pen.Color := BottomColor;
Arc (0, 0, width - 1, (height shl 1)-1, // ellipse
0, (height shl 1)-1, // start
width - 1, 0); // end
moveto(0,height-1);
lineto(width-1,height-1);
end;
end;
bitblt(canvas.handle,0,0,width-1,height,bmp.canvas.handle,0,0,srccopy);
bmp.free;
end;
procedure TrmGauge.PaintEllipse;
var
bmp : TBitMap;
topColor, bottomcolor : TColor;
angle : double;
lastx, lasty : integer;
NewBrush, OldBrush : HBrush;
NewPen, OldPen : HPen;
loop : integer;
incangle : double;
begin
bmp := tbitmap.create;
bmp.width := width;
bmp.height := height;
bmp.canvas.brush.color := clbtnface;
bmp.canvas.fillrect(rect(0,0,width-1,height-1));
GetBorderColors(TopColor,BottomColor);
with bmp.canvas do
begin
Brush.Color := clbtnface;
pen.color := clbtnface;
Ellipse(0, 0, Width-1, Height - 1);
if percent > 0 then
begin
if gradientfill then
begin
lastx := 0;
lasty := (height shr 1)-1;
for loop := 1 to percent do
begin
NewBrush := CreateSolidBrush(GradientColorIndex(loop));
OldBrush := SelectObject(bmp.canvas.handle, NewBrush);
NewPen := CreatePen(ps_Solid,1,GradientColorIndex(loop));
OldPen := SelectObject(bmp.canvas.handle, NewPen);
try
Angle := (2 * Pi * ((loop / 100)));
if loop < percent then incangle := 0.027
else
incangle := 0;
pie(0, 0, width-1, Height-1, Round(((width shr 1)-1) * (1 - Cos(Angle+incangle))), Round(((height shr 1) - 1) * (1 - Sin(Angle+incangle))), lastx, lasty);
lastx := Round(((width shr 1)-1) * (1 - Cos(Angle)));
lasty := Round(((height shr 1) - 1) * (1 - Sin(Angle)));
finally
SelectObject(bmp.canvas.handle, OldPen);
DeleteObject(NewPen);
SelectObject(bmp.canvas.handle, OldBrush);
DeleteObject(NewBrush);
end;
end;
end
else
begin
Pen.Width := 1;
brush.color := fillcolor;
Pen.Color := clblack;
Angle := (2*Pi * ((Percent / 100)));
pie(0, 0, width-1, Height-1, Round(((width shr 1)-1) * (1 - Cos(Angle))), Round(((height shr 1) - 1) * (1 - Sin(Angle))), 0, (height shr 1)-1);
end;
end;
if border <> gbNone then
begin
Pen.Color := TopColor;
Arc (0, 0, width-1, height-1, // ellipse
width-1, 0, // start
0, height-1); // end
Pen.Color := BottomColor;
Arc (0, 0, width-1, height-1, // ellipse
0, height-1, // start
width, 0); // end
end;
end;
bitblt(canvas.handle,0,0,width-1,height-1,bmp.canvas.handle,0,0,srccopy);
bmp.free;
end;
procedure TrmGauge.PaintPole;
const
bw = 15;
var
bmp : TBitMap;
wrect : TRect;
NewBrush, OldBrush : HBrush;
ph, loop : integer;
begin
bmp := tbitmap.create;
bmp.width := width;
bmp.height := height;
bmp.canvas.brush.color := clbtnface;
bmp.canvas.fillrect(rect(0,0,width-1,height-1));
with bmp.canvas do
begin
moveto(width-1,0);
pen.Color := clblack;
lineto(0,0);
lineto(0,height-1);
lineto(width-1,height-1);
wrect := rect(((width-1)-3)-bw, 1,((width-1)-3),(height-1));
brush.color := clbtnface;
fillrect(wrect);
ph := round((((height-1)-1) * percent) / 100);
wrect := rect(((width-1)-3)-bw,(height-1) - ph,((width-1)-3),(height-1));
for loop := 1 to (bw shr 1) do
begin
if loop <= percent then
begin
NewBrush := CreateSolidBrush(CalcColorIndex(fendcolor,fstartcolor,bw shr 1,loop));
OldBrush := SelectObject(bmp.canvas.handle, NewBrush);
try
PatBlt(bmp.canvas.handle, wrect.Left, wrect.Top, wrect.Right-wrect.Left, wrect.Bottom-wrect.Top, PATCOPY);
inflaterect(wrect,-1,-1);
finally
SelectObject(bmp.canvas.handle, OldBrush);
DeleteObject(NewBrush);
end;
end;
end;
end;
bitblt(canvas.handle,0,0,width-1,height,bmp.canvas.handle,0,0,srccopy);
bmp.free;
end;
procedure TrmGauge.SetGradient(Value:Boolean);
begin
if fGradient <> value then
begin
fgradient := value;
invalidate;
end;
end;
procedure TrmGauge.SetShape(Value : TGaugeShape);
begin
if fshape <> value then
begin
fshape := value;
invalidate;
end;
end;
procedure TrmGauge.SetBorder(Value : TGaugeBorder);
begin
if fborder <> value then
begin
fborder := value;
invalidate;
end;
end;
procedure TrmGauge.SetPercent(value:integer);
begin
if (value < 0) or (value > 100) then exit;
if fpercent <> value then
begin
fpercent := value;
paint;
if assigned(fOnChangeEvent) then fOnChangeEvent(self);
end;
end;
procedure TrmGauge.SetStartColor(Value : TColor);
begin
if fStartcolor <> value then
begin
fStartColor := Value;
paint;
end;
end;
procedure TrmGauge.SetUseMiddle(Value:Boolean);
begin
if fUseMiddle <> value then
begin
fUseMiddle := Value;
paint;
end;
end;
procedure TrmGauge.SetMiddleColor(Value:TColor);
begin
if fMiddleColor <> value then
begin
fMiddleColor := Value;
paint;
end;
end;
procedure TrmGauge.SetEndColor(Value :TColor);
begin
if fendcolor <> value then
begin
fendcolor := value;
paint;
end;
end;
function TrmGauge.GradientColorIndex(ColorIndex:integer):TColor;
var
BeginRGBValue : array[0..2] of Byte;
RGBDifference : array[0..2] of integer;
Red : Byte;
Green : Byte;
Blue : Byte;
StartColor, EndColor : TColor;
NumColors : integer;
begin
if (Colorindex < 1) or (colorindex > 100) then
raise ERangeError.create('ColorIndex can''t be less than 1 or greater than 100');
if UseMedianColor then
begin
NumColors := 50;
if Colorindex <= 50 then
begin
StartColor := fStartColor;
EndColor := fMiddleColor;
end
else
begin
dec(ColorIndex,50);
StartColor := fMiddleColor;
EndColor := fEndColor;
end;
end
else
begin
NumColors := 100;
StartColor := fStartColor;
EndColor := fEndColor;
end;
dec(ColorIndex);
BeginRGBValue[0] := GetRValue (ColorToRGB (StartColor));
BeginRGBValue[1] := GetGValue (ColorToRGB (StartColor));
BeginRGBValue[2] := GetBValue (ColorToRGB (StartColor));
RGBDifference[0] := GetRValue (ColorToRGB (EndColor)) - BeginRGBValue[0];
RGBDifference[1] := GetGValue (ColorToRGB (EndColor)) - BeginRGBValue[1];
RGBDifference[2] := GetBValue (ColorToRGB (EndColor)) - BeginRGBValue[2];
{ Calculate the color band's color }
Red := BeginRGBValue[0] + MulDiv (ColorIndex, RGBDifference[0], NumColors - 1);
Green := BeginRGBValue[1] + MulDiv (ColorIndex, RGBDifference[1], NumColors - 1);
Blue := BeginRGBValue[2] + MulDiv (ColorIndex, RGBDifference[2], NumColors - 1);
result := rgb(red, green, blue);
end;
function TrmGauge.CalcColorIndex(StartColor, EndColor:TColor; Steps, ColorIndex:integer):TColor;
var
BeginRGBValue : array[0..2] of Byte;
RGBDifference : array[0..2] of integer;
Red : Byte;
Green : Byte;
Blue : Byte;
NumColors : integer;
begin
if (Colorindex < 1) or (colorindex > steps) then
raise ERangeError.create('ColorIndex can''t be less than 1 or greater than '+inttostr(steps));
NumColors := steps;
dec(ColorIndex);
BeginRGBValue[0] := GetRValue (ColorToRGB (StartColor));
BeginRGBValue[1] := GetGValue (ColorToRGB (StartColor));
BeginRGBValue[2] := GetBValue (ColorToRGB (StartColor));
RGBDifference[0] := GetRValue (ColorToRGB (EndColor)) - BeginRGBValue[0];
RGBDifference[1] := GetGValue (ColorToRGB (EndColor)) - BeginRGBValue[1];
RGBDifference[2] := GetBValue (ColorToRGB (EndColor)) - BeginRGBValue[2];
{ Calculate the color band's color }
Red := BeginRGBValue[0] + MulDiv (ColorIndex, RGBDifference[0], NumColors - 1);
Green := BeginRGBValue[1] + MulDiv (ColorIndex, RGBDifference[1], NumColors - 1);
Blue := BeginRGBValue[2] + MulDiv (ColorIndex, RGBDifference[2], NumColors - 1);
result := rgb(red, green, blue);
end;
function TrmGauge.ColorUsed(TestColor:TColor):boolean;
var
loop : integer;
tc, bc : TColor;
begin
for loop := 1 to 100 do
begin
result := GradientColorIndex(loop) = testcolor;
if result then exit;
end;
GetBorderColors(Tc,Bc);
result := (TestColor = TC) or (TestColor = BC);
end;
function TrmGauge.UniqueColor:TColor;
begin
randomize;
result := random(rgb(255,255,255)+1);
while ColorUsed(result) do
result := random(rgb(255,255,255)+1);
end;
end.
|
{
InCo- Fing
Programación 1
Laboratorio 2016
Segunda Tarea
Diego Sirio
}
(******************************************************)
(* Funciones Auxiliares *)
(******************************************************)
{
La función ‘expbn’ se encarga de calcular la potencia de base ‘n’ y exponente ‘e’.
La función es auxiliar (su implementación no es obligatoria) pero permite un cálculo
más eficiente de potencias sin usar números reales.
}
function expbn(e : Natural; n : Natural): Natural; (*Exponente Base n*)
VAR i : Integer;
resu : Natural;
begin
resu := 1;
for i := 1 to e do
resu := resu*n;
expbn := resu;
end;
{
La idea del corrimiento de celdas, sobre la que se basa mi código, es universal a varias
funciones y procedimientos, por lo cual puedo reutilizar varias funciones auxiliares:
}
{
La función ‘sumables’ se encarga de verificar si dos celdas cualesquiera son sumables
(según las reglas del juego).
}
function sumable(a,b : TipoCelda): Boolean; (*Revisar si se puede mejorar*)
var resu : Boolean;
begin
resu := false;
if (a.color = blanca) AND (b.color = blanca) then
begin
if (a.exponente = b.exponente) then
resu := true
end
else
if ((a.color = roja)and(b.color = azul))
OR ((a.color = azul)and(b.color = roja)) then
resu := true;
sumable := resu;
end;
{
La función ‘corrible’ se encarga de verificar si alguna de dos celdas cualesquiera
está vacía.
}
function corrible(a1,a2 : TipoCelda): Boolean;
begin
corrible := false;
if (a1.color = gris) OR (a2.color = gris) then
corrible := true;
end;
(******************************************************)
(* ALGORITMO DE CORRIMIENTO UNIVERSAL *)
(******************************************************)
{
Dada una fila o columna fija, comienzo (en dicha fila o columna) sobre el borde
del tablero hacia el cual me voy a mover (como jugador).
Por ejemplo, dada la primera fila del tablero, empiezo en la posicion (1,1) si el
movimiento es hacia la izquierda.
1)Si la celda actual o la siguiente ESTAN VACIAS, entonces no se van a poder sumar las
celdas en toda esa columna o fila, ya que se van a correr todas las celdas a partir
de la celda vacía, en direccion del movimiento del jugador.
Si no, paso a 2)
2)Si la celda actual y la siguiente SON SUMABLES, entonces se suman con las reglas
adecuadas. La celda en la posición siguiente (respecto a la actual) se vuelve vacía.
Luego ocurre un corrimiento del resto de la fila o columna a partir de la celda vacía,
en direccion del movimiento del jugador y ya no se puede sumar más nada en toda esa
fila o columna.
Si no, paso a 3)
3)Si alguna de las dos condiciones anteriores se cumple, entonces 'ya estoy' por esa
fila o columna. Si no pasa nada de esto y no estoy al final de dicha fila o columna,
me muevo una posición en esa fila o columna, en dirección opuesta al movimiento del
jugador y evaluó las dos condiciones anteriores (1 y 2).
}
(******************************************************)
(* Funciones y Procedimientos Obligatorios *)
(******************************************************)
{
La función ‘TerminaJuego’ utiliza el Algoritmo de Corrimiento Universal salvo que cuando
se cumplen alguna de las dos primeras condiciones, ya la función devuelve el valor True.
}
function TerminaJuego(tablero: TipoTablero) : Boolean;
VAR i, j : Integer;
b : Boolean;(*bandera*)
begin
i := 1;
b := false;
while (i <= MAXTablero) AND (b = false) do
begin
j := 1;
while (j+1 <= MAXTablero) AND (b = false) do
begin
if (corrible(tablero[i,j],tablero[i,j+1])) OR (sumable(tablero[i,j],tablero[i,j+1])) then
b := true;
j := j+1;
end;
i := i+1;
end;
j := 1;
while (j <= MAXTablero) AND (b = false) do
begin
i := 1;
while (i+1 <= MAXTablero) AND (b = false) do
begin
if (corrible(tablero[i,j],tablero[i+1,j])) OR (sumable(tablero[i,j],tablero[i+1,j])) then
b := true;
i := i+1;
end;
j := j+1;
end;
TerminaJuego := NOT b;
end;
{
La función ‘Puntaje’ realiza una recorrida completa del tablero actualizando el
resultado ‘resu’ según los exponentes de las celdas blancas que me encuentro.
Al final devuelve ‘resu’.
}
function Puntaje(tablero: TipoTablero) : Natural;
VAR i,j : Integer;
resu : Natural;
begin
resu := 0;
for i := 1 to MAXTablero do
for j := 1 to MAXTablero do
if tablero[i,j].color = blanca then
resu := resu + expbn(tablero[i,j].exponente + 1,3);
Puntaje := resu;
end;
{
El procedimiento ‘DesplazamientoIzquierda’ se encarga de actualizar el tablero usando
el Algoritmo de Corrimiento Universal, restringiéndome al movimiento hacia la izquierda
(del jugador). Este algoritmo se aplica a TODAS las filas, y la búsqueda mencionada
se aplica de izquierda a derecha (en este caso).
El corrimiento de celdas que no van a ser sumadas utiliza un procedimiento auxiliar
‘corrimiento’ ya que la acción se realiza más de una vez en ‘DesplazamientoIzquierda’.
Observacion: Este procediemento no utiliza la funcion corrible, si no que se fija si
la celda en la que estoy es vacia o no (sin mirar la siguiente).
}
procedure DesplazamientoIzquierda(var tablero : TipoTablero; var cambios : boolean);
VAR i,j : Integer;
b,c : Boolean; (*bandera*)
procedure corrimiento(a : Integer; var tablero : TipoTablero);
VAR k : Integer;
begin
for k := a to (MAXTablero-1) do
tablero[i,k] := tablero[i,k+1];
tablero[i,MAXTablero].color := gris;
end;
begin
c := false;
for i := 1 to MAXTablero do
begin
b := false;
j := 1;
while (j+1 <= MAXTablero) AND (b = false) do
if (tablero[i,j].color = gris) then
begin
corrimiento(j,tablero);
b := true;
end
else
if (sumable(tablero[i,j],tablero[i,j+1])) then
begin
if (tablero[i,j].color = roja) OR (tablero[i,j].color = azul) then
begin
tablero[i,j].color := blanca;
tablero[i,j].exponente := 0;
end
else
tablero[i,j].exponente := tablero[i,j].exponente + 1;
corrimiento(j+1,tablero);
b := true;
end
else j := j + 1;
if (c = false) AND (b = true) then
c := true;
end;
cambios := c;
end;
{
El procedimiento ‘SimetriaVertical’ se encarga de realizar la simetría de la matriz
recorriendo CADA fila hasta la mitad del tablero (el eje de la matriz) e intercambiando
con las celdas simétricas respecto a dicho eje.
}
procedure SimetriaVertical(var tablero : TipoTablero);
VAR i,j : Integer;
aux : TipoCelda;
begin
for i := 1 to MAXTablero do
for j := 1 to (MAXTablero DIV 2) do
begin
aux := tablero[i,j];
tablero[i,j] := tablero[i,MAXTablero-j+1];
tablero[i,MAXTablero-j+1] := aux;
end;
end;
{
Tanto el procedimiento ‘RotacionDerecha’ y ‘RotacionIzquierda’ intercambian las celdas
del tablero directamente para realizar la rotaciones. Si pensamos el tablero como un
cuadrado con un borde cuadrado, guardamos ese borde y lo sacamos. Obtenemos otro cuadrado
con un borde cuadrado. Guardamos ese borde y lo sacamos…, y así hasta quedar con una
sola celda o con ninguna (Según si MAXTablero es Impar o Par). En esos bordes se mueven
las celdas como un ciclo hasta que se obtiene el borde rotado (hacia la Derecha o Izquierda).
Sin embargo en mi caso estos ciclos los realizo intercambiando 4 celdas en cada lado del
borde en cuestión, y repitiendo por todo el lado del borde.
}
procedure RotacionDerecha(var tablero : TipoTablero);
VAR i,j : Integer;
aux : TipoCelda;
begin
for j := 1 to (MAXTablero DIV 2) do
for i := j to (MAXTablero - j) do
begin
aux := tablero[i,MAXTablero+1-j];{1}
tablero[i,MAXTablero+1-j]{1} := tablero[j,i];{4}
tablero[j,i]{4} := tablero[MAXTablero+1-i,j];{3}
tablero[MAXTablero+1-i,j]{3} := tablero[MAXTablero+1-j,MAXTablero+1-i];{2}
tablero[MAXTablero+1-j,MAXTablero+1-i]{2} := aux;
end;
end;
procedure RotacionIzquierda(var tablero : TipoTablero);
VAR i,j : Integer;
aux : TipoCelda;
begin
for j := 1 to (MAXTablero DIV 2) do
for i := j to (MAXTablero - j) do
begin
aux := tablero[i,j];{1}
tablero[i,j]{1} := tablero[j,MAXTablero+1-i];{4}
tablero[j,MAXTablero+1-i]{4} := tablero[MAXTablero+1-i,MAXTablero+1-j];{3}
tablero[MAXTablero+1-i,MAXTablero+1-j]{3} := tablero[MAXTablero-j+1,i];{2}
tablero[MAXTablero-j+1,i]{2} := aux;
end;
end;
{
El procedimiento ‘PosiblesSumas’ utiliza el Algoritmo de Corrimiento Universal
(pero sin realizar ningun corrimiento).
Se encarga de en CADA fila y columna del tablero y en todas las direcciones, encontrar
las celdas sumables (Segunda condición del algoritmo) y guardar estas celdas en una lista
junto con el movimiento que realiza el jugador para obtener dicha suma, y el valor de esta.
Para ello utilizo un procedimiento auxiliar llamado ‘Agregar’, que agrega
registros con estos datos al principio de una lista.
}
function PosiblesSumas(tablero : TipoTablero) : ListaSumables;
VAR i,j,a : Integer;
s,e : Natural;
m : TipoDireccion;
b : Boolean;
lista : ListaSumables;
procedure Agregar(var l : ListaSumables; f, c : RangoIndice; mov : TipoDireccion; s : Natural);
VAR p : ListaSumables;
begin
new(p);
p^.posicion.fila := f;
p^.posicion.columna := c;
p^.movimiento := mov;
p^.suma := s;
p^.siguiente := l;
l:= p;
end;
begin
lista := nil;
for i := 1 to MAXTablero do
for a := 0 to 1 do
begin
b := false;
j := 1;
while (j+1 <= MAXTablero) AND (NOT corrible(tablero[i,j + a*(MAXTablero+1-2*j)],
tablero[i,j+1 + a*(MAXTablero+1-2*(j+1))])) AND (NOT b) do
begin
if (sumable(tablero[i,j + a*(MAXTablero+1-2*j)],
tablero[i,j+1 + a*(MAXTablero+1-2*(j+1))])) then
begin
if tablero[i,j + a*(MAXTablero+1-2*j)].color = blanca then
begin
e := tablero[i,j + a*(MAXTablero+1-2*j)].exponente;
s := 3*expbn(e+1,2);
end
else s := 3;
Case a of
0 : m := izquierda;
1 : m := derecha;
end;
Agregar(lista,i,j + a*(MAXTablero+1-2*j),m,s);
b := true;
end;
j := j+1;
end;
end;
for j := 1 to MAXTablero do
for a := 0 to 1 do
begin
b := false;
i := 1;
while (i+1 <= MAXTablero) AND (NOT corrible(tablero[i + a*(MAXTablero+1-2*i),j],
tablero[i+1 + a*(MAXTablero+1-2*(i+1)),j])) AND (NOT b) do
begin
if (sumable(tablero[i + a*(MAXTablero+1-2*i),j],
tablero[i+1 + a*(MAXTablero+1-2*(i+1)),j])) then
begin
if tablero[i + a*(MAXTablero+1-2*i),j].color = blanca then
begin
e := tablero[i + a*(MAXTablero+1-2*i),j].exponente;
s := 3*expbn(e+1,2);
end
else s := 3;
Case a of
0 : m := arriba;
1 : m := abajo;
end;
Agregar(lista,i + a*(MAXTablero+1-2*i),j,m,s);
b := true;
end;
i := i+1;
end;
end;
PosiblesSumas := lista;
end;
{
Por último la función ‘ObtenerCeldaPosicion’, dado un natural ‘k’, realiza un recorrido
(en la lista creada en el procedimiento anterior) parando en la k-iteración
(Si antes no se terminó la lista). Si la lista termina ahí devuelve NIL
y si existe un registro devuelve el puntero que señala a dicho registro.
}
function ObtenerCeldaPosicion(k : Natural; lista : ListaSumables) : ListaSumables;
VAR i : Integer;
p : ListaSumables;
begin
i := 0;
p := lista;
while (p <> nil) AND (i < k) do
begin
p := p^.siguiente;
i := i + 1;
end;
ObtenerCeldaPosicion := p;
end;
|
unit Period_Add;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons,
cxTextEdit, cxControls, cxContainer, cxEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, ExtCtrls, ActnList, cxRadioGroup, DB, FIBDataSet, pFIBDataSet,
cxCurrencyEdit;
type
TPeriod_Add_Form = class(TForm)
Date_Beg_Edit: TcxDateEdit;
Date_End_Edit: TcxDateEdit;
Label1: TLabel;
Label2: TLabel;
ApplyButton: TcxButton;
CancelButton: TcxButton;
ActionList1: TActionList;
Action3: TAction;
Shape1: TShape;
RadioGroup: TcxRadioGroup;
DataSet: TpFIBDataSet;
Label3: TLabel;
Summa_Edit: TcxCurrencyEdit;
procedure Summa_EditKeyPress(Sender: TObject; var Key: Char);
procedure Date_Beg_EditKeyPress(Sender: TObject; var Key: Char);
procedure Date_End_EditKeyPress(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CancelButtonClick(Sender: TObject);
procedure ApplyButtonClick(Sender: TObject);
procedure Action3Execute(Sender: TObject);
procedure RadioGroupPropertiesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
private
public
index : currency;
UseInflation : boolean;
function CheckIndex : boolean;
destructor Destroy; override;
end;
var
Period_Add_Form: TPeriod_Add_Form;
implementation
uses Arnd_Contract_Add, Math;
{$R *.dfm}
function CheckExtended(s : string; Key : Char; Decimal : integer; Position : byte) : boolean;
var
k : integer;
begin
Result := False;
if Key in [#8, #9, #13] then Result := True
else if Key = #44 then Result := ((Pos(#44, s) = 0) and (Length(s) - Position <= Decimal))
else if Key in ['0'..'9'] then begin
k := Pos(#44, s);
if (k = 0) or (Position < k) then Result := True
else Result := (Length(s) - k < 2);
end;
end;
procedure TPeriod_Add_Form.Summa_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
ApplyButton.SetFocus;
end;
end;
procedure TPeriod_Add_Form.Date_Beg_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
Date_End_Edit.SetFocus;
end;
end;
procedure TPeriod_Add_Form.Date_End_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
Summa_Edit.SetFocus;
end;
end;
destructor TPeriod_Add_Form.Destroy;
begin
Period_Add_Form := nil;
inherited;
end;
procedure TPeriod_Add_Form.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TPeriod_Add_Form.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TPeriod_Add_Form.ApplyButtonClick(Sender: TObject);
begin
if (Date_Beg_Edit.Text = '') or (Date_End_Edit.Text = '') then begin
ShowMessage('Введите корректно даты начала и окончания периода!');
Exit;
end;
if Date_Beg_Edit.Date > Date_End_Edit.Date then begin
ShowMessage('Дата начала периода не может быть больше даты его окончания!');
Exit;
end;
if Date_Beg_Edit.Date < Arnd_Contract_Add_Form.DogDateBeg.Date then begin
ShowMessage('Дата начала периода не может быть меньше чем ' + DateToStr(Arnd_Contract_Add_Form.DogDateBeg.Date));
Exit;
end;
if Date_End_Edit.Date > Arnd_Contract_Add_Form.DogDateEnd.Date then begin
ShowMessage('Дата начала периода не может быть бльше чем ' + DateToStr(Arnd_Contract_Add_Form.DogDateEnd.Date));
Exit;
end;
if (RadioGroup.ItemIndex = 1) and (Summa_Edit.Text = '') then begin
ShowMessage('Введите сумму по периоду!');
Exit;
end;
if RadioGroup.ItemIndex = 0 then if not CheckIndex then Exit;
ModalResult := mrOk;
end;
procedure TPeriod_Add_Form.Action3Execute(Sender: TObject);
begin
CancelButtonClick(Sender);
end;
procedure TPeriod_Add_Form.RadioGroupPropertiesChange(Sender: TObject);
begin
Summa_Edit.Enabled := RadioGroup.ItemIndex = 1;
end;
procedure TPeriod_Add_Form.FormShow(Sender: TObject);
begin
if not UseInflation then begin
RadioGroup.Visible := False;
RadioGroup.ItemIndex := 1;
Label3.Left := 16;
Label3.Top := 59;
Label3.Visible := True;
Shape1.Height := 97;
ApplyButton.Top := 110;
CancelButton.Top := 110;
Height := 175;
Summa_Edit.Top := 72;
end;
Summa_Edit.SetFocus;
RadioGroupPropertiesChange(Sender);
end;
function TPeriod_Add_Form.CheckIndex: boolean;
begin
Result := False;
DataSet.SelectSQL.Text := 'select first(1) INFLATION_INDEX from DOG_SP_INFLATION_SEL_PERIOD('
+ QuotedStr(DateToStr(Date_Beg_Edit.Date)) + ',' + QuotedStr(DateToStr(Date_End_Edit.Date)) + ')';
DataSet.Open;
if VarIsNull(DataSet['INFLATION_INDEX']) then begin
DataSet.Close;
ShowMessage('Індекс інфляції за вказаний період не знайдено!');
Exit;
end
else begin
index := DataSet['INFLATION_INDEX'];
Result := True;
end;
DataSet.Close;
end;
end.
|
unit Code;
{*******************************************************************************
Description: a non-modal dialog box used for inserting codes into heading, question, and scale text
Modifications:
--------------------------------------------------------------------------------
Date UserID Description
--------------------------------------------------------------------------------
04-07-2006 GN01 Making sure the translate richedit control has the active
focus to avoid the invalid typecast error
05-02-2006 GN02 Bookmark the current Language
*******************************************************************************}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Clipbrd,
DBCGrids, StdCtrls, DBCtrls, ExtCtrls, Grids, DBGrids, Buttons, ComCtrls, DBRichEdit;
type
TfrmCode = class(TForm)
Panel2: TPanel;
DBNavigator1: TDBNavigator;
btnClose: TSpeedButton;
btnNext: TSpeedButton;
btnInsertCode: TSpeedButton;
btnFind: TSpeedButton;
DBGrid1: TDBGrid;
procedure CloseClick(Sender: TObject);
procedure InsertClick(Sender: TObject);
procedure FindClick(Sender: TObject);
procedure NextClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
vForm : TForm;
selectedLanguage : integer;
end;
var
frmCode: TfrmCode;
implementation
uses Data, Support
{$IFDEF cdLibrary}
, Edit, Common, Browse
{$ENDIF}
;
{$R *.DFM}
{ ACTIVATION SECTION }
{ sets the button states each time the form is activated }
procedure TfrmCode.FormActivate(Sender: TObject);
begin
btnInsertCode.Enabled := ( vForm.ActiveControl is TclDBRichEdit ) and
not TclDBRichEdit( vForm.ActiveControl ).ReadOnly;
if modSupport.dlgLocate.DataSource <> modLibrary.srcCode then btnNext.Enabled := False;
//GN01: Refresh the code data on this screen when the user changes the language in the Translation form
modLibrary.tblCode.Refresh ;
Caption := 'Code Selection: ' + IntToStr(modLibrary.tblCode.RecordCount);
end;
{ BUTTON SECTION }
{ calls the DBRichEdit's embed method, passing in the currently selected code }
procedure TfrmCode.InsertClick(Sender: TObject);
//var fieldedcode:string;
var
i : integer;
begin
//GN01: Make sure the active control is the RichEdit or else it would lead to
//typecast error if the user has other control as the active focus.
//For example, if the language dropdown has the active focus in the translation form
if Trim(modLibrary.tblCodeCode.AsString) <> '' then
begin
{
if not (vForm.ActiveControl is TclDBRichCodeBtn) then
begin
for i := 0 to vForm.ComponentCount - 1 do
begin
if (vForm.Components[i] is TclDBRichCodeBtn) and ((vForm.Components[i]).Tag = 1) then
begin
vForm.Show;
vForm.ActiveControl := (vForm.Components[i] As TWinControl);
Break;
end;
end;
end;}
vForm.Show;
//Edit Question
if (vForm.Name= 'frmEdit') and (vForm.FindComponent( 'pclEdit' ) is TPageControl) then
begin
vForm.ActiveControl := (vForm.FindComponent( 'rtfText' ) as TclDBRichCodeBtn );
( vForm.ActiveControl as TclDBRichCodeBtn ).EmbedCode( modLibrary.tblCodeCode.AsString );
end
//new scale
else if (vForm.Name= 'frmNewScale') and (vForm.FindComponent( 'PageControl') is TPageControl) then
begin
vForm.ActiveControl := (vForm.FindComponent( 'clDBRichCodeBtn' ) as TclDBRichCodeBtn );
( vForm.ActiveControl as TclDBRichCodeBtn ).EmbedCode( modLibrary.tblCodeCode.AsString );
end
//Edit Translation
else if (vForm.Name= 'frmTranslate') and (vForm.FindComponent( 'pclPage' ) is TPageControl) then
begin
case (vForm.FindComponent( 'pclPage' ) as TPageControl).ActivePage.PageIndex of
0 : vForm.ActiveControl := (vForm.FindComponent( 'rtfTrHead' ) as TclDBRichCodeBtn );
1 : vForm.ActiveControl := (vForm.FindComponent( 'rtfTrText' ) as TclDBRichCodeBtn );
2 : vForm.ActiveControl := (vForm.FindComponent( 'rtfTrScale' ) as TclDBRichCodeBtn );
end;
//Now the typecast should be safe
if (vForm.FindComponent( 'pclPage' ) as TPageControl).ActivePage.PageIndex <= 2 then
( vForm.ActiveControl as TclDBRichCodeBtn ).EmbedCode( modLibrary.tblCodeCode.AsString );
end
else
( vForm.ActiveControl as TclDBRichCode ).EmbedCode( modLibrary.tblCodeCode.AsString );
//fieldedcode := '';
with modlibrary do
if tblcodefielded.value <> 1 then
begin
tblcode.edit;
tblcodefielded.value := 1;
tblcode.post;
//fieldedcode := tblcodefielded.asstring;
end;
end;
(*
if fieldedcode <> '' then
with modlibrary.ww_Query do begin
close;
databasename := '_QualPro';
sql.clear;
sql.add('Update codes set fielded=1 where code='+fieldedcode);
execsql;
end;
*)
end;
procedure TfrmCode.FindClick(Sender: TObject);
begin
with modSupport.dlgLocate do
begin
Caption := 'Locate Code';
DataSource := modLibrary.srcCode;
SearchField := 'Description';
btnNext.Enabled := Execute;
end;
end;
procedure TfrmCode.NextClick(Sender: TObject);
begin
btnNext.Enabled := modSupport.dlgLocate.FindNext;
end;
procedure TfrmCode.CloseClick(Sender: TObject);
begin
Close;
end;
{ FINALIZATION SECTION }
{ resets the calling form on close:
1. repositions calling form to the center of the screen
2. pops up the code button on the calling form }
procedure TfrmCode.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Hide;
with vForm do
begin
Position := poScreenCenter;
( FindComponent( 'btnCode' ) as TSpeedButton ).Down := False;
//Translation
if FindComponent( 'cmbLanguage' ) is TComboBox then
( FindComponent( 'cmbLanguage' ) as TComboBox ).ItemIndex := selectedLanguage; //GN02
end;
Action := caFree;
frmCode := nil;
end;
end.
|
unit OTFECrossCrypt_U;
// Description: Delphi CrossCrypt Component
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
OTFE_U,
OTFEConsts_U,
OTFECrossCrypt_DriverAPI,
WinSVC, // needed for OpenSCManager, etc
dialogs; // xxx - get rid of this
//xxx - WASTE all showmessages left in this file.
type
// Exceptions...
ECrossCryptError = Exception;
ECrossCryptCannotSetActive = ECrossCryptError;
type
TOTFECrossCryptVolumeInfo = packed record
DriveLetter: Ansichar;
FileName: string;
UserModeDeviceName: string;
KernelModeDeviceName: string;
ReadOnly: boolean;
end;
TOTFECrossCrypt = class(TOTFE)
private
{ private declarations here}
protected
// Set the component active/inactive
procedure SetActive(status: Boolean); override;
function IsServiceRunning(): boolean;
procedure AddKey(ka: POPEN_FILE_INFORMATION; cipher: TCROSSCRYPT_CIPHER_TYPE; var key: Ansistring);
function FileDiskMount(
mountDeviceName: Ansistring;
OpenFileInformation: POPEN_FILE_INFORMATION;
DriveLetter: Ansichar;
CdImage: boolean
): boolean;
// Note: These are the symlinks to be used in USER MODE - *NOT* THE DEVICE
// DRIVER'S ACTUAL NAME
function GetAllUserDeviceNames(deviceNames: TStringList): boolean;
// As GetAllUserDeviceNames, but for CD devices only
function GetCDUserDeviceNames(deviceNames: TStringList): boolean;
// As GetAllUserDeviceNames, but for disk devices only
function GetDiskUserDeviceNames(deviceNames: TStringList): boolean;
function GetNextFreeDev(getCDDevice: boolean): string;
function GetDeviceInfo(deviceName: string; var volumeInfo: TOTFECrossCryptVolumeInfo): boolean;
// Get a list of all CrossCrypt devices which are currently mounted
function GetMountedDevices(driveLetters: TStringList; deviceNames: TStringList): boolean;
function DoesLogicalDriveExist(driveLetter: char): boolean;
function UserToKernelModeDeviceName(deviceName: string): string;
function DoMount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE; volumeSizeInBytes: int64 = -1): boolean;
public
// Standard TOTFE methods
constructor Create(AOwner : TComponent); override;
destructor Destroy(); override;
function Title(): string; overload; override;
function IsDriverInstalled(): boolean; overload; override;
function Mount(volumeFilename: Ansistring; readonly: boolean = FALSE): Ansichar; overload; override;
function Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean; overload; override;
function MountDevices(): AnsiString; override;
function CanMountDevice(): boolean; override;
// Note: CrossCrypt doesn't have the concept of an "emergency dismount"
function Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean; overload; override;
// Note: CrossCrypt doesn't have the concept of an "emergency dismount"
function Dismount(driveLetter: Ansichar; emergency: boolean = FALSE): boolean; overload; override;
// Note: You can only get the version ID with CrossCrypt, if there's one or
// more volumes mounted.
// *Stupid*, but true - a problem with the CrossCrypt driver!
function Version(): cardinal; overload; override;
function VersionStr(): string; overload; override;
function IsEncryptedVolFile(volumeFilename: string): boolean; override;
function DrivesMounted(): Ansistring; overload; override;
function GetVolFileForDrive(driveLetter: Ansichar): string; override;
function GetDriveForVolFile(volumeFilename: string): Ansichar; override;
function GetMainExe(): string; override;
// Extensions to the standard TOTFE class...
function GetVolumeInfo(driveLetter: Ansichar; var volumeInfo: TOTFECrossCryptVolumeInfo): boolean;
// Attempt to create and mount a volume file of the specified size
// Returns the drive letter of the volume file, or #0 on error
function CreateVolume(volumeFilename: Ansistring; sizeInBytes: int64): Ansichar;
// Returns the number of devices for each of the types disk/CDROM
function GetNumberOfDevices(): integer;
// Set the number of devices for each of the types disk/CDROM
function SetNumberOfDevices(deviceCount: integer): boolean;
end;
procedure Register;
implementation
uses
OTFECrossCrypt_PasswordEntry,
HashValue_U,
HashAlg_U,
HashAlgRIPEMD_U,
HashAlgSHA256_U,
HashAlgSHA384_U,
HashAlgSHA512_U,
Registry;
const
CRLF = #13+#10;
MIN_LINUX_PASSWORD_LENGTH = 20;
procedure Register;
begin
RegisterComponents('OTFE', [TOTFECrossCrypt]);
end;
constructor TOTFECrossCrypt.Create(AOwner : TComponent);
begin
inherited;
end;
destructor TOTFECrossCrypt.Destroy();
begin
inherited;
end;
procedure TOTFECrossCrypt.SetActive(status: boolean);
var
allOK: boolean;
begin
LastErrorCode := OTFE_ERR_NOT_ACTIVE;
allOK := TRUE;
if (Active = FALSE) and (status = TRUE) then
begin
allOK := IsDriverInstalled() AND IsServiceRunning();
if not(allOK) then
begin
raise ECrossCryptCannotSetActive.Create('CrossCrypt driver not installed/service not running');
end;
end;
if allOK then
begin
LastErrorCode := OTFE_ERR_SUCCESS;
inherited;
end;
end;
function TOTFECrossCrypt.IsServiceRunning(): boolean;
var
scmHandle: SC_HANDLE;
servHandle: SC_HANDLE;
serviceStatus: SERVICE_STATUS;
isRunning: boolean;
begin
isRunning := FALSE;
//showmessage('OpenSCManager');
scmHandle:= OpenSCManager(nil, nil, GENERIC_READ);
if (scmHandle <> 0) then
begin
//showmessage('OpenService');
servHandle := OpenService(scmHandle, 'FileDisk', GENERIC_READ);
if (servHandle <> 0) then
begin
//showmessage('QueryServiceStatus');
if QueryServiceStatus(servHandle, serviceStatus) then
begin
isRunning := (serviceStatus.dwCurrentState = SERVICE_RUNNING);
//showmessage('xxx');
// xxx - DOES THIS WORK FOR NON ADMIN?
// xxx - DOES THIS WORK FOR w9x?
end;
end;
end;
//showmessage('ENDING FUNCTION');
Result := isRunning;
end;
function TOTFECrossCrypt.Mount(volumeFilename: Ansistring; readonly: boolean = FALSE): Ansichar;
var
retVal: Ansichar;
filenames: TStringList;
mountedAs: AnsiString;
begin
retVal := #0;
LastErrorCode := OTFE_ERR_UNKNOWN_ERROR;
CheckActive();
filenames:= TStringList.Create();
try
filenames.Add(volumeFilename);
if Mount(filenames, mountedAs, readonly) then
begin
retVal := mountedAs[1];
end;
finally
filenames.Text := StringOfChar('X', length(filenames.text));
filenames.Free();
end;
Result := retVal;
end;
function TOTFECrossCrypt.Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean;
begin
CheckActive();
LastErrorCode := OTFE_ERR_UNKNOWN_ERROR;
Result := DoMount(volumeFilenames, mountedAs, readonly, -1);
end;
// Do an actual mount
// If "volumeSizeInBytes" is >0 then it will attempt to create the volume if
// the file doesn't already exist, otherwise it'll fail the mount if the volume
// file doesn't exist
function TOTFECrossCrypt.DoMount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE; volumeSizeInBytes: int64 = -1): boolean;
var
ka: TOPEN_FILE_INFORMATION;
retVal: boolean;
passwordDlg: TOTFECrossCrypt_PasswordEntry_F;
tmpPw: Ansistring;
tmpStr: string;
multiPasswords: TStringList;
i: integer;
mountDeviceName: string;
x: integer;
currVolumeFilename: string;
currVolumeDrive: Ansichar;
fileCheck: boolean;
begin
retVal := FALSE;
CheckActive();
mountedAs := '';
// This is purely a sanity check to see if *all* CrossCrypt devices are in
// use
mountDeviceName := GetNextFreeDev(FALSE);
if (mountDeviceName='') then
begin
mountDeviceName := GetNextFreeDev(TRUE);
if (mountDeviceName='') then
begin
LastErrorCode := OTFE_ERR_NO_FREE_DEVICES;
Result := retVal;
exit;
end;
end;
passwordDlg := TOTFECrossCrypt_PasswordEntry_F.Create(nil);
try
// If we're creating a new volume file, then we'd better get the user
// to confirm the passwords they'll be using
passwordDlg.Confirm := (volumeSizeInBytes>0);
passwordDlg.OnlyReadWrite := (volumeSizeInBytes>0);
passwordDlg.MinPasswordLength := 0;
if (volumeSizeInBytes>0) then
begin
passwordDlg.MinPasswordLength := MIN_LINUX_PASSWORD_LENGTH;
end;
// Default password entry options
passwordDlg.MountReadOnly:= readonly;
if not(passwordDlg.ShowModal() = mrOK) then
begin
LastErrorCode := OTFE_ERR_USER_CANCEL;
end
else
begin
// --- FROM HERE ON IN WE JUST TRY TO MOUNT USING THE DETAILS SUPPLIED ---
for x:=0 to (volumeFilenames.count-1) do
begin
currVolumeFilename := volumeFilenames[x];
currVolumeDrive:= #0;
// Quick sanity check: Does the file exist? Should it?
fileCheck := FileExists(currVolumeFilename);
if (volumeSizeInBytes>0) then
begin
// If the file already exists, but we're trying to create it; the
// filecheck is inverted
fileCheck := not(fileCheck);
end;
if fileCheck then
begin
// Attempt to get a CrossCrypt device name to use.
mountDeviceName := GetNextFreeDev(passwordDlg.MountAsCD);
// showmessage('mountdeives: '+mountDeviceName);
// Now try to mount the volume on the free CrossCrypt device just
// found... (If there *was* a free CrossCrypt device found...)
if (mountDeviceName='') then
begin
LastErrorCode := OTFE_ERR_NO_FREE_DEVICES;
end
else
begin
ka.FileSize.QuadPart := volumeSizeInBytes;
ka.DriveLetter := passwordDlg.DriveLetter;
ka.ReadOnly := passwordDlg.MountReadOnly;
ka.KeyType := CROSSCRYPT_CIPHER_IDS[passwordDlg.Cipher];
ka.KeyNum := 0;
if (passwordDlg.Cipher <> cphrNone) then
begin
if not(passwordDlg.MultipleKey) then
begin
// Not multikey mode: We want a single key
passwordDlg.GetSinglePassword(tmpPw);
AddKey(@ka, passwordDlg.Cipher, tmpPw);
tmpPw := StringOfChar('X', length(tmpPw));
end
else
begin
// Multikey mode: We want multiple keys
multiPasswords := TStringList.Create();
try
passwordDlg.GetMultiplePasswords(multiPasswords);
for i:=0 to (multiPasswords.count-1) do
begin
// The password is passed by var to ensure that we don't make a
// duplicate which is never overwritten...
tmpPw := multiPasswords[i];
AddKey(@ka, passwordDlg.Cipher, tmpPw);
tmpPw := StringOfChar('X', length(tmpPw));
end;
finally
multiPasswords.Text := StringOfChar('X', length(multiPasswords.text));
multiPasswords.Free();
end;
end; // if not(passwordDlg.MultipleKey) then
end; // if (passwordDlg.Cipher <> cphrNone) then
// Sort out ka.Filename and ka.FilenameLength
// The TOPEN_FILE_INFORMATION stores the filename, and the length of the file
// - the length of the file is stored as a WORD (USHORT; unsigned number 2
// bytes long - max 65535); therefore we cannot handle filenames which
// exceed this is length
// (Less 10, as we may add in UNC info to the front)
if (
(length(currVolumeFilename) <= (65535 - 10)) AND
(length(currVolumeFilename) <= (MAX_PATH - 10))
) then
begin
// showmessage('vol filename OK lengthwise');
if Pos('\', currVolumeFilename)=1 then
begin
if Pos('\\', currVolumeFilename)=1 then
begin
// \\server\share\path\filedisk.img
Delete(currVolumeFilename, 0, 1);
tmpStr := '\??\UNC'+currVolumeFilename;
ka.FileNameLength := Length(tmpStr);
StrPCopy(ka.Filename, tmpStr);
end
else
begin
// \Device\Harddisk0\Partition1\path\filedisk.img
tmpStr := currVolumeFilename;
ka.FileNameLength := Length(tmpStr);
StrPCopy(ka.Filename, tmpStr);
end;
end
else
begin
// c:\path\filedisk.img
tmpStr := '\??\'+currVolumeFilename;
ka.FileNameLength := Length(tmpStr);
StrPCopy(ka.Filename, tmpStr);
end;
if (FileDiskMount(mountDeviceName, @ka, passwordDlg.DriveLetter, passwordDlg.MountAsCD)) then
begin
currVolumeDrive := passwordDlg.DriveLetter;
end;
end;
end; // if (mountDeviceName=='') then
end; // if fileCheck then
mountedAs := mountedAs + currVolumeDrive;
end; // for x:=0 to (volumeFilenames.count-1) do
end; // if not(passwordDlg.ShowModal() = mrOK) then
finally
passwordDlg.Wipe();
passwordDlg.Free();
end;
// If any drives could be mounted; set the return value to TRUE
for i:=1 to length(mountedAs) do
begin
if (mountedAs[i]<>#0) then
begin
retVal := TRUE;
LastErrorCode := OTFE_ERR_SUCCESS;
end;
end;
Result := retVal;
end;
procedure TOTFECrossCrypt.AddKey(ka: POPEN_FILE_INFORMATION; cipher: TCROSSCRYPT_CIPHER_TYPE; var key: Ansistring);
var
hashAlg: THashAlg;
hashValue: THashArray;
i: integer;
x, y: integer;
begin
if (ka.KeyNum >= MAX_KEYS) then
begin
exit;
end;
case (cipher) of
cphrNone:
begin
// Do nothing
end;
cphrTwoFish:
begin
ka.KeyLength := 20;
hashAlg:= THashAlgRIPEMD160.Create(nil);
try
hashValue := hashAlg.HashString(key);
x := low(ka.Key);
y := low(hashValue);
for i:=1 to ka.KeyLength do
begin
ka.Key[ka.KeyNum][x] := hashValue[y];
inc(x);
inc(y);
end;
hashAlg.ClearHash(hashValue);
finally
hashAlg.Free();
end;
inc(ka.KeyNum);
end;
cphrAES256:
begin
ka.KeyLength := 32;
hashAlg:= THashAlgSHA512.Create(nil);
try
hashValue := hashAlg.HashString(key);
x := low(ka.Key);
y := low(hashValue);
for i:=1 to ka.KeyLength do
begin
ka.Key[ka.KeyNum][x] := hashValue[y];
inc(x);
inc(y);
end;
hashAlg.ClearHash(hashValue);
finally
hashAlg.Free();
end;
inc(ka.KeyNum);
end;
cphrAES128:
begin
ka.KeyLength := 16;
hashAlg:= THashAlgSHA256.Create(nil);
try
hashValue := hashAlg.HashString(key);
x := low(ka.Key);
y := low(hashValue);
for i:=1 to ka.KeyLength do
begin
ka.Key[ka.KeyNum][x] := hashValue[y];
inc(x);
inc(y);
end;
hashAlg.ClearHash(hashValue);
finally
hashAlg.Free();
end;
inc(ka.KeyNum);
end;
cphrAES192:
begin
ka.KeyLength := 24;
hashAlg:= THashAlgSHA384.Create(nil);
try
hashValue := hashAlg.HashString(key);
x := low(ka.Key);
y := low(hashValue);
for i:=1 to ka.KeyLength do
begin
ka.Key[ka.KeyNum][x] := hashValue[y];
inc(x);
inc(y);
end;
hashAlg.ClearHash(hashValue);
finally
hashAlg.Free();
end;
inc(ka.KeyNum);
end;
cphrUnknown:
begin
// <shrug>
// Do nothing
end;
end;
end;
function TOTFECrossCrypt.FileDiskMount(
mountDeviceName: Ansistring;
OpenFileInformation: POPEN_FILE_INFORMATION;
DriveLetter: Ansichar;
CdImage: boolean
): boolean;
var
VolumeName: string;
BytesReturned: DWORD;
retVal: boolean;
Device: THandle;
driveColon: string;
kernelModeMountDeviceName: string;
begin
retVal := FALSE;
CheckActive();
driveLetter := upcase(driveLetter);
VolumeName := '\\.\'+driveLetter+':';
driveColon := driveLetter+':';
kernelModeMountDeviceName := UserToKernelModeDeviceName(mountDeviceName);
Device := CreateFile(
PChar(VolumeName),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0
);
// We *want* this to *FAIL*; it indicates that the drive isn't already in use
if (Device <> INVALID_HANDLE_VALUE) then
begin
LastErrorCode := OTFE_ERR_INVALID_DRIVE;
CloseHandle(Device);
end
else
begin
// showmessage('about to define dosdevice: '+driveColon+' -- '+kernelModeMountDeviceName);
if not(DefineDosDevice(
DDD_RAW_TARGET_PATH,
PChar(driveColon),
PChar(kernelModeMountDeviceName)
)) then
begin
// Unable to create drive
LastErrorCode := OTFE_ERR_MOUNT_FAILURE;
// showmessage('FAILED DEFINEDOSDEVICE');
end
else
begin
// showmessage('about to createfile on new DOSDEVICE on: '+VolumeName);
Device := CreateFile(
PChar(VolumeName),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0
);
// We want this to SUCCEED; it indicates that the drive is connected to
// the device
if (Device = INVALID_HANDLE_VALUE) then
begin
LastErrorCode := OTFE_ERR_MOUNT_FAILURE;
DefineDosDevice(DDD_REMOVE_DEFINITION, PChar(driveColon), nil);
end
else
begin
// showmessage('about to IOCTL_FILE_DISK_OPEN_FILE');
if (DeviceIoControl(
Device,
IOCTL_FILE_DISK_OPEN_FILE,
OpenFileInformation,
sizeof(TOPEN_FILE_INFORMATION) + OpenFileInformation.FileNameLength - 1,
nil,
0,
BytesReturned,
nil
)) then
begin
// showmessage('OKOKOK');
retVal := TRUE;
end
else
begin
// showmessage('BARFOUT - BARFOUT - BARFOUT - removign the DosDevice');
LastErrorCode := OTFE_ERR_MOUNT_FAILURE;
DefineDosDevice(DDD_REMOVE_DEFINITION, PChar(driveColon), nil);
end;
CloseHandle(Device);
end;
end;
end;
Result := retVal;
end;
function TOTFECrossCrypt.Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean;
begin
LastErrorCode := OTFE_ERR_DISMOUNT_FAILURE;
Result := Dismount(GetDriveForVolFile(volumeFilename), emergency);
end;
function TOTFECrossCrypt.Dismount(driveLetter: AnsiChar; emergency: boolean = FALSE): boolean;
var
VolumeName: string;
driveDevice: THandle;
BytesReturned: DWORD;
retVal: boolean;
deviceName: string;
begin
CheckActive();
LastErrorCode := OTFE_ERR_DISMOUNT_FAILURE;
retVal := FALSE;
driveLetter := upcase(driveLetter);
VolumeName := '\\.\'+driveLetter+':';
deviceName := driveLetter+':';
//showmessage('About to createfile... ('+VolumeName+')');
driveDevice := CreateFile(
PChar(VolumeName),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0
);
if (driveDevice <> INVALID_HANDLE_VALUE) then
begin
//showmessage('Got handle...');
if (DeviceIoControl(
driveDevice,
FSCTL_LOCK_VOLUME,
nil,
0,
nil,
0,
BytesReturned,
nil
)) then
begin
//showmessage('Locked...');
if (DeviceIoControl(
driveDevice,
IOCTL_FILE_DISK_CLOSE_FILE,
nil,
0,
nil,
0,
BytesReturned,
nil
)) then
begin
//showmessage('CrossCrypt closed disk...');
if (DeviceIoControl(
driveDevice,
FSCTL_DISMOUNT_VOLUME,
nil,
0,
nil,
0,
BytesReturned,
nil
)) then
begin
//showmessage('Dismounted...');
if (DeviceIoControl(
driveDevice,
FSCTL_UNLOCK_VOLUME,
nil,
0,
nil,
0,
BytesReturned,
nil
)) then
begin
//showmessage('Unlocked...');
CloseHandle(driveDevice);
driveDevice := 0;
retVal := DefineDosDevice(
DDD_REMOVE_DEFINITION,
PChar(deviceName),
nil
);
if (retVal) then
begin
//showmessage('Undefined DosDevice OK!');
LastErrorCode:= OTFE_ERR_SUCCESS;
end;
end; // DIOC for FSCTL_UNLOCK_VOLUME
end; // DIOC for FSCTL_DISMOUNT_VOLUME
end; // DIOC for IOCTL_FILE_DISK_CLOSE_FILE
end; // DIOC for FSCTL_LOCK_VOLUME
// Only close the device if it hasn't already been closed
if (driveDevice<>0) then
begin
//showmessage('Closing handle...');
CloseHandle(driveDevice);
//showmessage('Closed.');
end;
end; // if (driveDevice <> INVALID_HANDLE_VALUE) then
//showmessage('Exiting dismount.');
Result := retVal;
end;
function TOTFECrossCrypt.Title(): string;
begin
Result := 'CrossCrypt';
end;
function TOTFECrossCrypt.IsDriverInstalled(): boolean;
var
registry: TRegistry;
installed: boolean;
begin
installed := FALSE;
// The check to see if the driver is installed consists of just checking to
// see if the relevant registry entries exist for the driver...
registry := TRegistry.create();
try
registry.RootKey := CROSSCRYPT_REGISTRY_ROOT;
if registry.OpenKeyReadOnly(CROSSCRYPT_REGISTRY_KEY_MAIN) then
begin
// Options
if registry.ValueExists(CROSSCRYPT_REGGISTRY_MAIN_NAME_START) then
begin
installed := TRUE;
end;
registry.CloseKey;
end;
finally
registry.Free();
end;
FLastErrCode:= OTFE_ERR_SUCCESS;
Result := installed;
end;
function TOTFECrossCrypt.Version(): cardinal;
var
BytesReturned: DWORD;
retVal: cardinal;
deviceHandle: THandle;
OpenFileInformation: TOPEN_FILE_INFORMATION;
deviceNames: TStringList;
i: integer;
begin
retVal := $FFFFFFFF;
CheckActive();
LastErrorCode := OTFE_ERR_UNKNOWN_ERROR;
deviceNames := TStringList.Create();
try
if GetAllUserDeviceNames(deviceNames) then
begin
for i:=0 to (deviceNames.count-1) do
begin
deviceHandle := CreateFile(
PChar(deviceNames[i]),
GENERIC_READ,
FILE_SHARE_READ OR FILE_SHARE_WRITE,
nil,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0
);
if (deviceHandle <> INVALID_HANDLE_VALUE) then
begin
if (DeviceIoControl(
deviceHandle,
IOCTL_FILE_DISK_QUERY_FILE,
nil,
0,
@OpenFileInformation,
sizeof(OpenFileInformation), // Note: We don't add MAX_PATH due to the fixed buffer we used for this struct
BytesReturned,
nil
)) then
begin
retVal := OpenFileInformation.Version;
LastErrorCode := OTFE_ERR_SUCCESS;
break;
end;
CloseHandle(deviceHandle);
end;
end; // for i:=0 to (deviceNames.count-1) do
end; // if GetAllDeviceNames(deviceNames) then
finally
deviceNames.Free();
end;
Result := retVal;
end;
function TOTFECrossCrypt.VersionStr(): string;
var
verNo: cardinal;
majorVer: integer;
minorVer: integer;
retval: string;
begin
retval := '';
CheckActive();
verNo := Version();
if (verNo <> $FFFFFFFF) then
begin
majorVer := (verNo AND $FF00) div $FF;
minorVer := (verNo AND $FF);
retval := Format('v%d.%.d', [majorVer, minorVer]);
end;
Result := retval;
end;
function TOTFECrossCrypt.IsEncryptedVolFile(volumeFilename: string): boolean;
begin
CheckActive();
LastErrorCode:= OTFE_ERR_SUCCESS;
// We can't tell, so always return TRUE
Result := TRUE;
end;
function TOTFECrossCrypt.DrivesMounted(): Ansistring;
var
retVal: Ansistring;
i: integer;
driveLetters: TStringList;
deviceNames: TStringList;
begin
retVal := '';
LastErrorCode:= OTFE_ERR_SUCCESS;
CheckActive();
driveLetters:= TStringList.Create();
try
deviceNames:= TStringList.Create();
try
if GetMountedDevices(driveLetters, deviceNames) then
begin
for i:=0 to (driveLetters.count-1) do
begin
if (driveLetters[i]<>'') then
begin
retVal := retVal + driveLetters[i];
end;
end;
retVal := SortString(retVal);
end;
finally
deviceNames.Free();
end;
finally
driveLetters.Free();
end;
Result := retVal;
end;
function TOTFECrossCrypt.GetVolFileForDrive(driveLetter: AnsiChar): string;
var
retVal: string;
volumeInfo: TOTFECrossCryptVolumeInfo;
begin
retVal := '';
LastErrorCode := OTFE_ERR_UNKNOWN_ERROR;
CheckActive();
if (GetVolumeInfo(driveLetter, volumeInfo)) then
begin
retVal := volumeInfo.Filename;
LastErrorCode := OTFE_ERR_SUCCESS;
end;
Result := retVal;
end;
function TOTFECrossCrypt.GetDriveForVolFile(volumeFilename: string): Ansichar;
var
mounted: Ansistring;
volumeInfo: TOTFECrossCryptVolumeInfo;
retVal: Ansichar;
i: integer;
begin
retVal := #0;
LastErrorCode := OTFE_ERR_UNKNOWN_ERROR;
CheckActive();
mounted := DrivesMounted();
for i:=1 to length(mounted) do
begin
if GetVolumeInfo(mounted[i], volumeInfo) then
begin
if (uppercase(volumeInfo.Filename) = uppercase(volumeFilename)) then
begin
retVal := volumeInfo.DriveLetter;
LastErrorCode := OTFE_ERR_SUCCESS;
break;
end;
end;
end;
Result := retVal;
end;
function TOTFECrossCrypt.GetMainExe(): string;
begin
// This is not meaningful for CrossCrypt
FLastErrCode:= OTFE_ERR_UNABLE_TO_LOCATE_FILE;
Result := '';
end;
// Get a list of all CrossCrypt devices which are currently mounted
// Drive letters will be added to "driveLetters", and the corresponding device
// in "deviceNames".
// Returns TRUE/FALSE on success/failure
function TOTFECrossCrypt.GetMountedDevices(driveLetters: TStringList; deviceNames: TStringList): boolean;
var
allOK: boolean;
i: integer;
volumeInfo: TOTFECrossCryptVolumeInfo;
begin
allOK := TRUE;
CheckActive();
deviceNames:= TStringList.Create();
try
GetAllUserDeviceNames(deviceNames);
// Extract details for each of the devices in turn...
for i:=0 to (deviceNames.count-1) do
begin
if GetDeviceInfo(deviceNames[i], volumeInfo) then
begin
driveLetters.Add(volumeInfo.DriveLetter);
deviceNames.Add(volumeInfo.UserModeDeviceName);
end; // if GetDeviceInfo(deviceNames[i], open_file_information) then
end; // for i:=0 to (deviceNames.count-1) do
finally
deviceNames.Free();
end;
Result := allOK;
end;
function TOTFECrossCrypt.GetVolumeInfo(driveLetter: AnsiChar; var volumeInfo: TOTFECrossCryptVolumeInfo): boolean;
var
found: boolean;
deviceNames: TStringList;
i: integer;
begin
found := FALSE;
LastErrorCode := OTFE_ERR_UNKNOWN_ERROR;
CheckActive();
driveLetter := upcase(driveLetter);
deviceNames:= TStringList.Create();
try
GetAllUserDeviceNames(deviceNames);
// Extract details for each of the devices in turn...
for i:=0 to (deviceNames.count-1) do
begin
if GetDeviceInfo(deviceNames[i], volumeInfo) then
begin
if (upcase(volumeInfo.DriveLetter) = driveLetter) then
begin
found := TRUE;
LastErrorCode := OTFE_ERR_SUCCESS;
break;
end; // if (uppercase(open_file_information.DriveLetter) = driveLetter) then
end; // if GetDeviceInfo(deviceNames[i], open_file_information) then
end; // for i:=0 to (deviceNames.count-1) do
finally
deviceNames.Free();
end;
Result := found;
end;
// Set deviceNames to be a list of *all* CrossCrypt devices
// Note: These are the symlinks to be used in USER MODE - *NOT* THE DEVICE
// DRIVER'S ACTUAL NAME
function TOTFECrossCrypt.GetAllUserDeviceNames(deviceNames: TStringList): boolean;
var
allOK: boolean;
tmpDeviceNames: TStringList;
begin
allOK := TRUE;
// Generate a list of all CrossCrypt device names
deviceNames.Clear();
tmpDeviceNames:= TStringList.Create();
try
tmpDeviceNames.Clear();
allOK := allOK AND GetDiskUserDeviceNames(tmpDeviceNames);
deviceNames.AddStrings(tmpDeviceNames);
tmpDeviceNames.Clear();
allOK := allOK AND GetCDUserDeviceNames(tmpDeviceNames);
deviceNames.AddStrings(tmpDeviceNames);
finally
tmpDeviceNames.Free();
end;
Result := allOK;
end;
// Set deviceNames to be a list of all CrossCrypt disk devices
function TOTFECrossCrypt.GetCDUserDeviceNames(deviceNames: TStringList): boolean;
var
i: integer;
deviceCount: integer;
begin
deviceCount := GetNumberOfDevices();
// Generate a list of all CrossCrypt device names
deviceNames.Clear();
for i:=0 to (deviceCount-1) do
begin
deviceNames.Add(USER_MODE_DEVICE_NAME_PREFIX+'Cd'+inttostr(i));
end;
Result := TRUE;
end;
// Set deviceNames to be a list of all CrossCrypt CD devices
function TOTFECrossCrypt.GetDiskUserDeviceNames(deviceNames: TStringList): boolean;
var
i: integer;
deviceCount: integer;
begin
deviceCount := GetNumberOfDevices();
// Generate a list of all CrossCrypt device names
deviceNames.Clear();
for i:=0 to (deviceCount-1) do
begin
deviceNames.Add(USER_MODE_DEVICE_NAME_PREFIX+inttostr(i));
end;
Result := TRUE;
end;
// Get the next free CrossCrypt device
// Returns '' if there are none, and on error
function TOTFECrossCrypt.GetNextFreeDev(getCDDevice: boolean): string;
var
deviceNames: TStringList;
retVal: string;
volumeInfo: TOTFECrossCryptVolumeInfo;
i: integer;
begin
retVal := '';
deviceNames := TStringList.Create();
try
if (getCDDevice) then
begin
GetCDUserDeviceNames(deviceNames);
end
else
begin
GetDiskUserDeviceNames(deviceNames);
end;
// Scan through all the device names, attempting to find one which isn't
// in use
for i:=0 to (deviceNames.count-1) do
begin
if not(GetDeviceInfo(deviceNames[i], volumeInfo)) then
begin
// We couldn't get any information - the device must be unused
retVal := deviceNames[i];
break;
end;
end;
finally
deviceNames.Free();
end;
Result := retVal;
end;
function TOTFECrossCrypt.GetDeviceInfo(deviceName: string; var volumeInfo: TOTFECrossCryptVolumeInfo): boolean;
var
BytesReturned: DWORD;
allOK: boolean;
deviceHandle: THandle;
open_file_information: TOPEN_FILE_INFORMATION;
begin
allOK := FALSE;
CheckActive();
deviceHandle := CreateFile(
PChar(deviceName),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0
);
if (deviceHandle <> INVALID_HANDLE_VALUE) then
begin
if (DeviceIoControl(
deviceHandle,
IOCTL_FILE_DISK_QUERY_FILE,
nil,
0,
@open_file_information,
sizeof(open_file_information), // Note: We don't add MAX_PATH due to the fixed buffer we used for this struct
BytesReturned,
nil
)) then
begin
volumeInfo.UserModeDeviceName:= deviceName;
volumeInfo.KernelModeDeviceName := UserToKernelModeDeviceName(deviceName);
volumeInfo.DriveLetter := upcase(open_file_information.DriveLetter);
volumeInfo.ReadOnly:= open_file_information.ReadOnly;
volumeInfo.FileName := copy(open_file_information.FileName, 0, open_file_information.FileNameLength);
// Clean up the filename...
if Pos('\??\UNC', volumeInfo.FileName)=1 then
begin
// \??\UNC\server\share\path\filedisk.img
// should display as:
// \\server\share\path\filedisk.img
delete(volumeInfo.FileName, 1, length('\??\UNC'));
volumeInfo.FileName := '\'+volumeInfo.FileName;
end
else if Pos('\??\', volumeInfo.FileName)=1 then
begin
// \??\c:\path\filedisk.img
// should display as:
// c:\path\filedisk.img
delete(volumeInfo.FileName, 1, length('\??\'));
end
else
begin
// \Device\Harddisk0\Partition1\path\filedisk.img
// should display as:
// \Device\Harddisk0\Partition1\path\filedisk.img
// i.e. No change...
end;
allOK := TRUE;
end;
CloseHandle(deviceHandle);
end;
Result := allOK;
end;
// Returns the number of devices for each of the types disk/CDROM
// Returns -1 on error
function TOTFECrossCrypt.GetNumberOfDevices(): integer;
var
registry: TRegistry;
deviceCount: integer;
begin
LastErrorCode:= OTFE_ERR_UNKNOWN_ERROR;
deviceCount := CROSSCRYPT_DFLT_REGGISTRY_PARAM_NAME_NUMEROFDEVICES;
registry := TRegistry.create();
try
registry.RootKey := CROSSCRYPT_REGISTRY_ROOT;
if registry.OpenKeyReadOnly(CROSSCRYPT_REGISTRY_KEY_PARAM) then
begin
// Options
if registry.ValueExists(CROSSCRYPT_REGGISTRY_PARAM_NAME_NUMEROFDEVICES) then
begin
try
deviceCount := registry.ReadInteger(CROSSCRYPT_REGGISTRY_PARAM_NAME_NUMEROFDEVICES);
except
deviceCount := CROSSCRYPT_DFLT_REGGISTRY_PARAM_NAME_NUMEROFDEVICES;
end;
end;
registry.CloseKey;
end;
finally
registry.Free();
end;
LastErrorCode:= OTFE_ERR_SUCCESS;
Result := deviceCount;
end;
// Set the number of devices for each of the types disk/CDROM
function TOTFECrossCrypt.SetNumberOfDevices(deviceCount: integer): boolean;
var
registry: TRegistry;
allOK: boolean;
begin
LastErrorCode:= OTFE_ERR_UNKNOWN_ERROR;
allOK := FALSE;
registry := TRegistry.create();
try
registry.RootKey := CROSSCRYPT_REGISTRY_ROOT;
if registry.OpenKey(CROSSCRYPT_REGISTRY_KEY_PARAM, FALSE) then
begin
registry.WriteInteger(CROSSCRYPT_REGGISTRY_PARAM_NAME_NUMEROFDEVICES, deviceCount);
registry.CloseKey;
allOK := TRUE;
end;
finally
registry.Free();
end;
LastErrorCode:= OTFE_ERR_SUCCESS;
Result := allOK;
end;
// Checks to see if the specified logical drive letter currently exists
// Returns TRUE if it does, otherwise FALSE
function TOTFECrossCrypt.DoesLogicalDriveExist(driveLetter: char): boolean;
var
driveNum: Integer;
driveBits: set of 0..25;
retVal: boolean;
begin
retVal:= FALSE;
driveLetter := upcase(driveLetter);
Integer(driveBits) := GetLogicalDrives();
driveNum := ord(driveLetter) - ord('A');
if (driveNum in DriveBits) then
begin
retVal := TRUE;
end;
Result := retVal;
end;
// Convert a user-mode device naem (a symlink) into the corresponding *actual*
// device name
function TOTFECrossCrypt.UserToKernelModeDeviceName(deviceName: string): string;
begin
// Strip off the USER_MODE_DEVICE_NAME_PREFIX and replace with the
// DEVICE_NAME_PREFIX
delete(deviceName, 1, Length(USER_MODE_DEVICE_NAME_PREFIX));
deviceName := DEVICE_NAME_PREFIX + deviceName;
Result := deviceName;
end;
function TOTFECrossCrypt.CreateVolume(volumeFilename: Ansistring; sizeInBytes: int64): AnsiChar;
var
retVal: AnsiChar;
filenames: TStringList;
mountedAs: Ansistring;
begin
retVal := #0;
CheckActive();
LastErrorCode:= OTFE_ERR_UNKNOWN_ERROR;
filenames:= TStringList.Create();
try
filenames.Add(volumeFilename);
if DoMount(filenames, mountedAs, FALSE, sizeInBytes) then
begin
retVal := mountedAs[1];
LastErrorCode:= OTFE_ERR_SUCCESS;
end;
finally
filenames.Text := StringOfChar('X', length(filenames.text));
filenames.Free();
end;
Result := retVal;
end;
// -----------------------------------------------------------------------------
// Prompt the user for a device (if appropriate) and password (and drive
// letter if necessary), then mount the device selected
// Returns the drive letter of the mounted devices on success, #0 on failure
function TOTFECrossCrypt.MountDevices(): Ansistring;
begin
// Not supported...
Result := #0;
end;
// -----------------------------------------------------------------------------
// Determine if OTFE component can mount devices.
// Returns TRUE if it can, otherwise FALSE
function TOTFECrossCrypt.CanMountDevice(): boolean;
begin
// Not supported...
Result := FALSE;
end;
// -----------------------------------------------------------------------------
END.
|
namespace SqliteApp;
interface
uses
Foundation,
UIKit,
libsqlite3;
type
MasterViewController = public class (UITableViewController)
private
fObjects: NSMutableArray;
protected
public
property detailViewController: DetailViewController;
method awakeFromNib; override;
method viewDidLoad; override;
method didReceiveMemoryWarning; override;
method prepareForSegue(segue: not nullable UIStoryboardSegue) sender(sender: id); override;
{$REGION Table view data source}
method numberOfSectionsInTableView(tableView: UITableView): NSInteger;
method tableView(tableView: UITableView) canMoveRowAtIndexPath(indexPath: NSIndexPath): RemObjects.Oxygene.System.Boolean;
method tableView(tableView: UITableView) moveRowAtIndexPath(fromIndexPath: NSIndexPath) toIndexPath(toIndexPath: NSIndexPath);
method tableView(tableView: UITableView) commitEditingStyle(editingStyle: UITableViewCellEditingStyle) forRowAtIndexPath(indexPath: NSIndexPath);
method tableView(tableView: UITableView) canEditRowAtIndexPath(indexPath: NSIndexPath): RemObjects.Oxygene.System.Boolean;
method tableView(tableView: UITableView) cellForRowAtIndexPath(indexPath: NSIndexPath): UITableViewCell;
method tableView(tableView: UITableView) numberOfRowsInSection(section: NSInteger): NSInteger;
{$ENDREGION}
{$REGION Table view delegate}
method tableView(tableView: UITableView) didSelectRowAtIndexPath(indexPath: NSIndexPath);
{$ENDREGION}
end;
implementation
method MasterViewController.awakeFromNib;
begin
if UIDevice.currentDevice.userInterfaceIdiom = UIUserInterfaceIdiom.UIUserInterfaceIdiomPad then begin
clearsSelectionOnViewWillAppear := true;
//contentSizeForViewInPopover := CGSizeMake(320.0, 600.0); //59091: Toffee: Linker error on CGSizeMake - we dont have inline functions yet
end;
inherited awakeFromNib;
end;
method MasterViewController.viewDidLoad;
begin
inherited viewDidLoad;
detailViewController := splitViewController:viewControllers:lastObject:topViewController as DetailViewController;
fObjects := new NSMutableArray();
var lDatabaseName := NSBundle.mainBundle.pathForResource('PCTrade.sqlite') ofType('db');
NSLog('%@', lDatabaseName);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), method begin
NSLog('async!');
NSLog('self: %@', self);
end);
var lDatabase: ^sqlite3 := nil;
if sqlite3_open(lDatabaseName.cStringUsingEncoding(NSStringEncoding.NSUTF8StringEncoding), @lDatabase) = SQLITE_OK then begin
var lStatement: ^sqlite3_stmt;
if sqlite3_prepare_v2(lDatabase, 'select * from Customers', -1, @lStatement, nil) = SQLITE_OK then begin
while sqlite3_step(lStatement) = SQLITE_ROW do begin
var lName := ^AnsiChar(sqlite3_column_text(lStatement, 1));
fObjects.addObject(NSString.stringWithUTF8String(lName));
NSLog('row: %s', lName);
end;
end;
sqlite3_close(lDatabase);
end;
tableView.reloadData();
end;
method MasterViewController.didReceiveMemoryWarning;
begin
inherited didReceiveMemoryWarning;
// Dispose of any resources that can be recreated.
end;
{$REGION Table view data source}
method MasterViewController.numberOfSectionsInTableView(tableView: UITableView): NSInteger;
begin
result := 1;
end;
method MasterViewController.tableView(tableView: UITableView) numberOfRowsInSection(section: NSInteger): NSInteger;
begin
//result := fObjects:count;
result := if assigned(fObjects) then fObjects.count else 0; //59096: Toffee: Compiler NRE when jusing ":" on a simple type
end;
method MasterViewController.tableView(tableView: UITableView) cellForRowAtIndexPath(indexPath: NSIndexPath): UITableViewCell;
begin
var CellIdentifier := "Cell";
result := tableView.dequeueReusableCellWithIdentifier(CellIdentifier);
// this is required if you are targetting iOS 5.1 or lower, only
if not assigned(result) then
result := new UITableViewCell withStyle(UITableViewCellStyle.UITableViewCellStyleDefault) reuseIdentifier(CellIdentifier);
var lObject := fObjects[indexPath.row];
result.textLabel.text := lObject.description;
end;
// Override to support conditional editing of the table view.
method MasterViewController.tableView(tableView: UITableView) canEditRowAtIndexPath(indexPath: NSIndexPath): RemObjects.Oxygene.System.Boolean;
begin
// Return FALSE if you do not want the specified item to be editable.
result := true;
end;
// Override to support editing the table view.
method MasterViewController.tableView(tableView: UITableView) commitEditingStyle(editingStyle: UITableViewCellEditingStyle) forRowAtIndexPath(indexPath: NSIndexPath);
begin
if (editingStyle = UITableViewCellEditingStyle.UITableViewCellEditingStyleDelete) then begin
// Delete the row from the data source
fObjects.removeObjectAtIndex(indexPath.row);
tableView.deleteRowsAtIndexPaths([indexPath]) withRowAnimation(UITableViewRowAnimation.UITableViewRowAnimationFade);
end
else if (editingStyle = UITableViewCellEditingStyle.UITableViewCellEditingStyleInsert) then begin
// Create a new instance of the appropriabte class, insert it into the array, and add a new row to the table view
end;
end;
// Override to support conditional rearranging of the table view.
method MasterViewController.tableView(tableView: UITableView) canMoveRowAtIndexPath(indexPath: NSIndexPath): RemObjects.Oxygene.System.Boolean;
begin
// Return NO if you do not want the item to be re-orderable.
result := true;
end;
method MasterViewController.tableView(tableView: UITableView) moveRowAtIndexPath(fromIndexPath: NSIndexPath) toIndexPath(toIndexPath: NSIndexPath);
begin
end;
{$ENDREGION}
{$REGION Table view delegate}
method MasterViewController.tableView(tableView: UITableView) didSelectRowAtIndexPath(indexPath: NSIndexPath);
begin
if UIDevice.currentDevice.userInterfaceIdiom = UIUserInterfaceIdiom.UIUserInterfaceIdiomPad then begin
var lObject := fObjects[indexPath.row];
detailViewController.detailItem := lObject;
end;
end;
{$ENDREGION}
method MasterViewController.prepareForSegue(segue: not nullable UIStoryboardSegue) sender(sender: id);
begin
if segue.identifier.isEqualToString('showDetail') then begin
var lIndexPath := tableView.indexPathForSelectedRow;
//var lObject := fObjects[lIndexPath.row]; // 59210: Toffee: object subscripting support on older deployment targets
var lObject := fObjects.objectAtIndex(lIndexPath.row);
// segue.destinationViewController.setDetailItem(lObject); //59090: Toffee: cannot access members defined in project, on "id"
(segue.destinationViewController as DetailViewController).setDetailItem(lObject);
end;
end;
end. |
unit Objekt.FeldList;
interface
uses
SysUtils, Classes, Contnrs, Objekt.Feld;
type
TFeldList = class
private
fPraefix: string;
function GetCount: Integer;
function getFeld(Index: Integer): TFeld;
procedure setPreafix(const Value: string);
protected
fList: TObjectList;
public
constructor Create; virtual;
destructor Destroy; override;
property Count: Integer read GetCount;
function Add: TFeld;
property Item[Index: Integer]: TFeld read getFeld;
procedure Clear;
procedure PropertyList(aStrings: TStrings);
procedure InitList(aStrings: TStrings);
procedure SaveToDBList(aStrings: TStrings);
procedure LoadFromQuery(aStrings: TStrings);
property Preafix: string read fPraefix write setPreafix;
function getMaxNamenlaenge: Integer;
function FuelleMitLeer(aValue: string; aMaxLength: Integer): string;
end;
implementation
{ TFeldList }
uses
db;
constructor TFeldList.Create;
begin
fList := TObjectList.Create;
fPraefix := '';
end;
destructor TFeldList.Destroy;
begin
FreeAndNil(fList);
inherited;
end;
function TFeldList.FuelleMitLeer(aValue: string; aMaxLength: Integer): string;
begin
Result := aValue;
while Length(Result) < aMaxLength do
Result := Result + ' ';
end;
procedure TFeldList.Clear;
begin
fList.Clear;
end;
function TFeldList.GetCount: Integer;
begin
Result := fList.Count;
end;
function TFeldList.getFeld(Index: Integer): TFeld;
begin
Result := nil;
if Index > fList.Count -1 then
exit;
Result := TFeld(fList[Index]);
end;
function TFeldList.getMaxNamenlaenge: Integer;
var
i1: Integer;
s: string;
begin
Result := 0;
for i1 := 0 to fList.Count -1 do
begin
if Length(Item[i1].Name) > Result then
Result := Length(Item[i1].Name);
end;
end;
function TFeldList.Add: TFeld;
begin
Result := TFeld.Create;
fList.Add(Result);
end;
procedure TFeldList.PropertyList(aStrings: TStrings);
var
i1: Integer;
s: string;
MaxLength: Integer;
VariName: string;
begin
aStrings.Clear;
MaxLength := getMaxNamenlaenge;
for i1 := 0 to fList.Count -1 do
begin
VariName := FuelleMitLeer(Item[i1].Name, MaxLength);
s := 'property ' + VariName + ': ' + Item[i1].TypAsString + ' read f' + Variname + ' write set' + Item[i1].Name + ';';
aStrings.Add(s);
end;
end;
procedure TFeldList.SaveToDBList(aStrings: TStrings);
var
i1: Integer;
s: string;
begin
aStrings.Clear;
aStrings.Add('queryBuilder');
aStrings.Add('.table(getTableName)');
for i1 := 0 to fList.Count -1 do
begin
if Item[i1].Typ = ftDateTime then
s := '.fieldDT(' + '''' + fPraefix + Item[i1].Name + '''' + ', f' + Item[i1].Name + ')'
else
s := '.field(' + '''' + fPraefix + Item[i1].Name + '''' + ', f' + Item[i1].Name + ')';
aStrings.Add(s);
end;
end;
procedure TFeldList.InitList(aStrings: TStrings);
var
i1: Integer;
s: string;
MaxLength: Integer;
begin
MaxLength := getMaxNamenlaenge;
aStrings.Clear;
for i1 := 0 to fList.Count -1 do
begin
s := 'f' + Item[i1].Name;
s := FuelleMitLeer(s, MaxLength);
s := s + ' := ';
if Item[i1].TypIsString then
s := s + QuotedStr('') + ';';
if Item[i1].TypIsZahl then
s := s + '0;';
if Item[i1].Typ = ftBoolean then
s := s + 'false;';
if Item[i1].Typ = ftDateTime then
s := s + '0;';
aStrings.Add(s);
end;
end;
procedure TFeldList.LoadFromQuery(aStrings: TStrings);
var
i1: Integer;
s: string;
qry: string;
MaxLength: Integer;
begin
MaxLength := 0;
aStrings.Clear;
for i1 := 0 to fList.Count -1 do
begin
qry := 'aQuery.FieldByName(' + QuotedStr(fPraefix + Item[i1].Name) + ').';
if Item[i1].Typ = ftInteger then
qry := qry + 'AsInteger;';
if Item[i1].Typ = ftFloat then
qry := qry + 'AsFloat;';
if (Item[i1].TypIsString) and (Item[i1].Typ <> ftBoolean) then
qry := qry + 'AsString;';
if (Item[i1].Typ = ftBoolean) then
qry := qry + 'AsString = ' + QuotedStr('T') + ';';
if (Item[i1].Typ = ftDateTime) then
qry := qry + 'AsDateTime;';
s := 'f' + Item[i1].Name;
if Length(s) > MaxLength then
MaxLength := Length(s);
s := s + ' := ';
s := s + qry;
//aStrings.Add(s);
end;
for i1 := 0 to fList.Count -1 do
begin
qry := 'aQuery.FieldByName(' + QuotedStr(fPraefix + Item[i1].Name) + ').';
if Item[i1].Typ = ftInteger then
qry := qry + 'AsInteger;';
if Item[i1].Typ = ftFloat then
qry := qry + 'AsFloat;';
if (Item[i1].TypIsString) and (Item[i1].Typ <> ftBoolean) then
qry := qry + 'AsString;';
if (Item[i1].Typ = ftBoolean) then
qry := qry + 'AsString = ' + QuotedStr('T') + ';';
if (Item[i1].Typ = ftDateTime) then
qry := qry + 'AsDateTime;';
s := 'f' + Item[i1].Name;
s := FuelleMitLeer(s, MaxLength);
s := s + ' := ';
s := s + qry;
aStrings.Add(s);
end;
end;
procedure TFeldList.setPreafix(const Value: string);
begin
fPraefix := Value;
if fPraefix[Length(fPraefix)] <> '_' then
fPraefix := fPraefix + '_';
end;
end.
|
{ hello main program:
File Name : hello.pas
Version : 1.00
Date : 2018-10-12
Software :
Development tool : VCL for RAD Studio V10.x
Description : 项目主界面功能模块
}
unit hello1; //该单元名称
//beginning of interface module ----------------------------------------------------------------------
//本单元可向其它单元提供的属性,函数以及过程声明
interface
//uses 本单元引用文件声明-------------------------------------------------------------------------------
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.ListBox, FMX.Edit,
FMX.ScrollBox, FMX.Memo,
hello2; //若使用自定义单元,需在此添加引用单元名(此处引用文件名:hello2)
//type
//同时,也为本单元使用属性声明
type
Tform1 = class(TForm)
btn: TButton; //hello 按钮
ComboBox1: TComboBox; //下拉框体
input1: TLabel; //输入提示1
input2: TLabel; //输入提示2
result: TButton; //result按钮
Edit1: TEdit; //文本输入框1
Edit2: TEdit; // 文本输入框2
compare: TButton; //compare按钮
enter: TButton; //enter按钮
exit: TButton; // 退出按钮(右下角 X 图案)
Button1: TButton; //+ 按钮
Button2: TButton; //- 按钮
Button3: TButton; //* 按钮
Button4: TButton; // / 按钮
ImageControl1: TImageControl;
Edit3: TEdit; // 图片控制器
procedure btnClick(Sender: TObject); // hello 按钮点击事件过程首部声明
procedure resultClick(Sender: TObject);// 实现运算并打印结果
procedure compareClick(Sender: TObject);// 比较输入值的大小
procedure enterClick(Sender: TObject); // 点击打开子界面
procedure exitClick(Sender: TObject); // 退出当前窗口
procedure Button1Click(Sender: TObject);// 定义运算符号
procedure Button2Click(Sender: TObject);//如上
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
//定义全局变量
var
//就是组件函式库套件(component package)的 Register 函式,
//这个函式一定必须写成第一个字母大写的 Register, 因为必须兼容于 C++。
form1:TForm;
s1,s2,res:string;
s3:Integer;
//The end of interface--------------------------------------------------------------------
//具体功能实现模块------------------------------------------------------------------------
implementation
{$R *.fmx}
//hello按钮点击事件
procedure Tform1.btnClick(Sender: TObject); //过程名首部
//局部变量声明(近用于当前模块)
var name:string;
//功能实现代码
begin
// 注释一: {注释二} (*注释三*)
//获取下拉框内容 并赋值给name(可设置默认选择项)
name:=ComboBox1.Items.Strings[combobox1.ItemIndex];
//以弹出框打印结果
ShowMessage('hello '+name);
end;
//点击 + 按钮,将 +赋值给res
procedure Tform1.Button1Click(Sender: TObject);
begin
res:='+';
end;
procedure Tform1.Button2Click(Sender: TObject);
begin
res:='-';
end;
procedure Tform1.Button3Click(Sender: TObject);
begin
res:='*';
end;
procedure Tform1.Button4Click(Sender: TObject);
begin
res:='/';
end;
//比较值大小,打印较大的结果
procedure Tform1.compareClick(Sender: TObject);
begin
s1:=Edit1.Text; //获取Edit1的值,并赋值给s1
s2:=Edit2.Text;
if (s1>=s2) then
begin
if (S1=s2) then
begin
ShowMessage('--相等--')
end
else
ShowMessage('max:--'+s1)
end
else
ShowMessage('max:--'+s2)
end;
//点击打开子面板
procedure Tform1.enterClick(Sender: TObject);
begin
form2:=TForm2.create(Application);
form2.showmodal;
form2.Free;
end;
//点击退出当前面板
procedure Tform1.exitClick(Sender: TObject);
begin
Close;
end;
//简单整数的计算
procedure Tform1.resultClick(Sender: TObject);
var
result:string;
g:real;
begin
s1:=Edit1.Text;
s2:=Edit2.Text;
if res='+' then
begin
s3:=(StrtoInt(s1)+StrtoInt(s2));
result:=s1+res+s2+'='+inttostr(s3);
end
else if res='-' then
begin
s3:=(StrtoInt(s1)-StrtoInt(s2));
result:=s1+res+s2+'='+inttostr(s3);
end
else if res='*' then
begin
s3:=(StrtoInt(s1)*StrtoInt(s2));
result:=s1+res+s2+'='+inttostr(s3);
end
else if res='/' then
begin
g:=(StrtoInt(s1)/StrtoInt(s2));
result:=s1+res+s2+'='+floattostr(g);
end
else
result:='请选择操作符!!';
//动态创建label框打印计算结果
with Tlabel.create(self) do
try
Parent:=Self;
Position.X:=40;
Position.Y:=210;
width:=60;
height:=33;
TextSettings.FontColor:= TAlphaColors.Red;
TextSettings.Font.Size:= 26;
text:='结果';
finally
end;
Edit3.Text:=result;
end;
end.
//End of file---------------------------------------------------------------------
|
{ -$Id: uVihodsReg.pas,v 1.1 2005/12/01 08:48:50 oleg Exp $ }
unit uVihodsReg;
interface
uses WorkModeCentral, Controls, TableCentral;
type
TVihodCount = record
vihod: TVihod;
count: Integer;
end;
TVihodsReg = class(TObject)
private
VCounts: array of TVihodCount;
function GetVihodCount(vihod: Integer): Integer;
function GetTotalVihodsCount: Integer;
function GetCount: Integer;
function GetCell(ind: Integer): TVihodCount;
public
property Count: Integer read GetCount;
property Cells[ind: Integer]: TVihodCount read GetCell;
property VihodCount[vihod: Integer]: Integer
read GetVihodCount; default;
property TotalVihodsCount: Integer read GetTotalVihodsCount;
procedure AddVihodCount(vihod: TVihod; count: Integer = 1);
procedure Clear;
procedure AddReg(VihodsReg: TVihodsReg);
end;
implementation
function TVihodsReg.GetCell(ind: Integer): TVihodCount;
begin
Result := VCounts[ind];
end;
function TVihodsReg.GetCount: Integer;
begin
Result := Length(VCounts);
end;
procedure TVihodsReg.AddReg(VihodsReg: TVihodsReg);
var
i: Integer;
begin
for i:=0 to VihodsReg.Count-1 do
AddVihodCount(VihodsReg.Cells[i].vihod, VihodsReg.Cells[i].count);
end;
procedure TVihodsReg.Clear;
begin
SetLength(VCounts, 0);
end;
function TVihodsReg.GetTotalVihodsCount: Integer;
var
i: Integer;
begin
Result := 0;
for i:=0 to High(VCounts) do
Result := Result + VCounts[i].count;
end;
function TVihodsReg.GetVihodCount(vihod: Integer): Integer;
var
i: Integer;
begin
Result := 0;
for i:=0 to High(VCounts) do
if VCounts[i].vihod.Id_Vihod = vihod then
Result := Result + VCounts[i].count;
end;
procedure TVihodsReg.AddVihodCount(vihod: TVihod; count: Integer = 1);
var
i: Integer;
begin
if vihod = nil then Exit;
for i:=0 to High(VCounts) do
if VCounts[i].vihod = vihod then
begin
VCounts[i].count := VCounts[i].count + count;
Exit;
end;
SetLength(VCounts, Length(VCounts)+1);
VCounts[High(VCounts)].vihod := vihod;
VCounts[High(VCounts)].count := count;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Simple X format support for Delphi (Microsoft's favorite format)
}
unit uFileX;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
VXS.VectorTypes,
VXS.VectorGeometry,
VXS.VectorLists,
VXS.PersistentClasses,
VXS.Utils;
type
TDXNode = class;
TDXFileHeader = record
Magic: array [0 .. 3] of AnsiChar;
Major: array [0 .. 1] of AnsiChar;
Minor: array [0 .. 1] of AnsiChar;
FileType: array [0 .. 3] of AnsiChar;
FloatType: array [0 .. 3] of AnsiChar;
end;
TDXNode = class(TList)
private
FName, FTypeName: String;
FOwner: TDXNode;
function GetItem(index: Integer): TDXNode;
public
constructor CreateOwned(AOwner: TDXNode);
constructor Create; virtual;
procedure Clear; override;
property Name: String read FName write FName;
property TypeName: String read FTypeName write FTypeName;
property Owner: TDXNode read FOwner;
property Items[index: Integer]: TDXNode read GetItem;
end;
TDXMaterialList = class;
TDXMaterial = class(TPersistentObject)
private
FDiffuse: TVector4f;
FSpecPower: Single;
FSpecular, FEmissive: TVector3f;
FTexture: String;
public
constructor CreateOwned(AOwner: TDXMaterialList);
property Diffuse: TVector4f read FDiffuse write FDiffuse;
property SpecPower: Single read FSpecPower write FSpecPower;
property Specular: TVector3f read FSpecular write FSpecular;
property Emissive: TVector3f read FEmissive write FEmissive;
property Texture: String read FTexture write FTexture;
end;
TDXMaterialList = class(TDXNode)
private
function GetMaterial(index: Integer): TDXMaterial;
public
property Items[index: Integer]: TDXMaterial read GetMaterial;
end;
TDXFrame = class(TDXNode)
private
FMatrix: TMatrix;
public
constructor Create; override;
function GlobalMatrix: TMatrix;
property Matrix: TMatrix read FMatrix write FMatrix;
end;
TDXMesh = class(TDXNode)
private
FVertices, FNormals, FTexCoords: TAffineVectorList;
FVertexIndices, FNormalIndices, FMaterialIndices, FVertCountIndices
: TIntegerList;
FMaterialList: TDXMaterialList;
public
constructor Create; override;
destructor Destroy; override;
property Vertices: TAffineVectorList read FVertices;
property Normals: TAffineVectorList read FNormals;
property TexCoords: TAffineVectorList read FTexCoords;
property VertexIndices: TIntegerList read FVertexIndices;
property NormalIndices: TIntegerList read FNormalIndices;
property MaterialIndices: TIntegerList read FMaterialIndices;
property VertCountIndices: TIntegerList read FVertCountIndices;
property MaterialList: TDXMaterialList read FMaterialList;
end;
TDXFile = class
private
FRootNode: TDXNode;
FHeader: TDXFileHeader;
protected
procedure ParseText(Stream: TStream);
procedure ParseBinary(Stream: TStream);
public
constructor Create;
destructor Destroy; override;
procedure LoadFromStream(Stream: TStream);
// procedure SaveToStream(Stream : TStream);
property Header: TDXFileHeader read FHeader;
property RootNode: TDXNode read FRootNode;
end;
// ----------------------------------------------------------------------
implementation
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Text parsing functions
// ----------------------------------------------------------------------
procedure RemoveComments(Text: TStringList);
var
i, comment: Integer;
begin
for i := 0 to Text.Count - 1 do
begin
comment := Pos('//', Text[i]);
if comment > 0 then
Text[i] := Copy(Text[i], 0, comment - 1);
comment := Pos('#', Text[i]);
if comment > 0 then
Text[i] := Copy(Text[i], 0, comment - 1);
end;
end;
// ----------------------------------------------------------------------
// TDXFile
// ----------------------------------------------------------------------
constructor TDXFile.Create;
begin
FRootNode := TDXNode.Create;
end;
destructor TDXFile.Destroy;
begin
FRootNode.Free;
inherited;
end;
procedure TDXFile.LoadFromStream(Stream: TStream);
begin
Stream.Read(FHeader, SizeOf(TDXFileHeader));
Assert(Header.Magic = 'xof ', 'Invalid DirectX file');
if Header.FileType = 'txt ' then
ParseText(Stream)
else if Header.FileType = 'bin ' then
raise Exception.Create('FileX error, "bin" filetype not supported')
else if Header.FileType = 'tzip' then
raise Exception.Create('FileX error, "tzip" filetype not supported')
else if Header.FileType = 'bzip' then
raise Exception.Create('FileX error, "bzip" filetype not supported');
end;
procedure TDXFile.ParseBinary(Stream: TStream);
begin
// To-do
end;
procedure TDXFile.ParseText(Stream: TStream);
var
XText, TempBuffer: TStringList;
Cursor: Integer;
Buffer: String;
function ContainsColon(Buffer: String): Boolean;
begin
Result := Pos(';', Buffer) > 0;
end;
function ContainsBegin(Buffer: String): Boolean;
begin
Result := Pos('{', Buffer) > 0;
end;
function ContainsEnd(Buffer: String): Boolean;
begin
Result := Pos('}', Buffer) > 0;
end;
function ReadString: String;
begin
if Cursor < XText.Count then
Result := XText[Cursor]
else
Result := '';
Inc(Cursor);
end;
function GetNodeData(var NodeType, NodeName: String): Boolean;
begin
NodeType := '';
NodeName := '';
Result := False;
if Cursor < 3 then
exit;
NodeType := XText[Cursor - 3];
NodeName := XText[Cursor - 2];
if ContainsBegin(NodeType) or ContainsEnd(NodeType) or
ContainsColon(NodeType) then
begin
NodeType := NodeName;
NodeName := '';
end;
NodeType := LowerCase(NodeType);
end;
function ReadInteger: Integer;
var
str: String;
begin
str := ReadString;
if ContainsColon(str) then
str := StringReplace(str, ';', '', [rfReplaceAll]);
if ContainsBegin(str) then
str := StringReplace(str, '{', '', [rfReplaceAll]);
if ContainsEnd(str) then
str := StringReplace(str, '}', '', [rfReplaceAll]);
Result := StrToInt(str);
end;
function ReadSingle: Single;
var
str: String;
begin
str := ReadString;
if ContainsColon(str) then
str := StringReplace(str, ';', '', [rfReplaceAll]);
if ContainsBegin(str) then
str := StringReplace(str, '{', '', [rfReplaceAll]);
if ContainsEnd(str) then
str := StringReplace(str, '}', '', [rfReplaceAll]);
Result := StrToFloatDef(str);
end;
function ReadMatrix: TMatrix;
var
i, j: Integer;
begin
try
for j := 0 to 3 do
for i := 0 to 3 do
Result.V[i].V[j] := ReadSingle;
except
on E: Exception do
begin
Result := IdentityHMGMatrix;
end;
end;
end;
function ReadVector3f: TAffineVector;
var
str: String;
begin
str := ReadString;
str := StringReplace(str, ';', ' ', [rfReplaceAll]);
TempBuffer.CommaText := str;
if TempBuffer.Count > 1 then
begin
Result.X := StrToFloatDef(TempBuffer[0]);
Result.Y := StrToFloatDef(TempBuffer[1]);
Result.Z := StrToFloatDef(TempBuffer[2]);
end
else
begin
Result.X := StrToFloatDef(TempBuffer[0]);
Result.Y := ReadSingle;
Result.Z := ReadSingle;
end;
end;
function ReadVector4f: TVector;
var
str: String;
begin
str := ReadString;
str := StringReplace(str, ';', ' ', [rfReplaceAll]);
TempBuffer.CommaText := str;
if TempBuffer.Count > 1 then
begin
Result.X := StrToFloatDef(TempBuffer[0]);
Result.Y := StrToFloatDef(TempBuffer[1]);
Result.Z := StrToFloatDef(TempBuffer[2]);
Result.W := StrToFloatDef(TempBuffer[3]);
end
else
begin
Result.X := StrToFloatDef(TempBuffer[0]);
Result.Y := ReadSingle;
Result.Z := ReadSingle;
Result.W := ReadSingle;
end;
end;
function ReadTexCoord: TAffineVector;
var
str: String;
begin
str := ReadString;
str := StringReplace(str, ';', ' ', [rfReplaceAll]);
TempBuffer.CommaText := str;
if TempBuffer.Count > 1 then
begin
Result.X := StrToFloatDef(TempBuffer[0]);
Result.Y := StrToFloatDef(TempBuffer[1]);
end
else
begin
Result.X := StrToFloatDef(TempBuffer[0]);
Result.Y := ReadSingle;
end;
Result.Z := 0;
end;
procedure ReadMeshVectors(VectorList: TAffineVectorList);
var
i, NumVectors: Integer;
begin
NumVectors := ReadInteger;
for i := 0 to NumVectors - 1 do
VectorList.Add(ReadVector3f);
end;
procedure ReadMeshIndices(IndexList: TIntegerList;
VertCountIndices: TIntegerList = nil);
var
str: String;
i, j, NumFaces, NumIndices, jStart: Integer;
Indices: array of Integer;
begin
NumFaces := ReadInteger;
for i := 0 to NumFaces - 1 do
begin
str := ReadString;
str := StringReplace(str, ';', ' ', [rfReplaceAll]);
TempBuffer.CommaText := str;
NumIndices := StrToInt(TempBuffer[0]);
SetLength(Indices, NumIndices);
jStart := 0;
if TempBuffer.Count > 1 then
begin
Indices[0] := StrToInt(TempBuffer[1]);
jStart := 1;
end;
for j := jStart to NumIndices - 1 do
Indices[j] := ReadInteger;
case NumIndices of
3:
begin
IndexList.Add(Indices[0], Indices[1], Indices[2]);
if Assigned(VertCountIndices) then
VertCountIndices.Add(3);
end;
4:
begin
IndexList.Add(Indices[0], Indices[1], Indices[2]);
IndexList.Add(Indices[0], Indices[2], Indices[3]);
if Assigned(VertCountIndices) then
VertCountIndices.Add(6);
end;
end;
SetLength(Indices, 0);
end;
end;
procedure ReadTexCoords(VectorList: TAffineVectorList);
var
i, NumVectors: Integer;
begin
NumVectors := ReadInteger;
for i := 0 to NumVectors - 1 do
VectorList.Add(ReadTexCoord);
end;
procedure ReadMeshVertices(Mesh: TDXMesh);
begin
ReadMeshVectors(Mesh.Vertices);
ReadMeshIndices(Mesh.VertexIndices, Mesh.VertCountIndices);
end;
procedure ReadMeshNormals(Mesh: TDXMesh);
begin
ReadMeshVectors(Mesh.Normals);
ReadMeshIndices(Mesh.NormalIndices);
end;
procedure ReadMeshTexCoords(Mesh: TDXMesh);
begin
ReadTexCoords(Mesh.TexCoords);
end;
procedure ReadMeshMaterialList(Mesh: TDXMesh);
var
i, { NumMaterials, } NumIndices: Integer;
begin
{ NumMaterials:= } ReadInteger;
NumIndices := ReadInteger;
for i := 0 to NumIndices - 1 do
Mesh.MaterialIndices.Add(ReadInteger);
end;
procedure ReadMeshMaterial(Mesh: TDXMesh);
begin
with TDXMaterial.CreateOwned(Mesh.MaterialList) do
begin
Diffuse := ReadVector4f;
SpecPower := ReadSingle;
Specular := ReadVector3f;
Emissive := ReadVector3f;
end;
end;
procedure ReadTextureFilename(Mesh: TDXMesh);
var
str: String;
begin
if Mesh.MaterialList.Count > 0 then
begin
str := ReadString;
str := StringReplace(str, '"', '', [rfReplaceAll]);
str := StringReplace(str, ';', '', [rfReplaceAll]);
str := Trim(str);
Mesh.MaterialList.Items[Mesh.MaterialList.Count - 1].Texture := str;
end;
end;
procedure ReadStruct(ParentNode: TDXNode);
var
Buffer, NodeType, NodeName: String;
Loop: Boolean;
NewNode: TDXNode;
begin
Loop := True;
while Loop do
begin
Buffer := ReadString;
if Cursor > XText.Count - 1 then
break;
if ContainsEnd(Buffer) then
Loop := False
else if ContainsBegin(Buffer) then
begin
GetNodeData(NodeType, NodeName);
NewNode := nil;
// Frame
if NodeType = 'frame' then
begin
NewNode := TDXFrame.CreateOwned(ParentNode);
ReadStruct(NewNode);
// Frame transform matrix
end
else if NodeType = 'frametransformmatrix' then
begin
if ParentNode is TDXFrame then
TDXFrame(ParentNode).Matrix := ReadMatrix;
ReadStruct(ParentNode);
// Mesh
end
else if NodeType = 'mesh' then
begin
NewNode := TDXMesh.CreateOwned(ParentNode);
ReadMeshVertices(TDXMesh(NewNode));
ReadStruct(NewNode);
// Mesh normals
end
else if NodeType = 'meshnormals' then
begin
if ParentNode is TDXMesh then
ReadMeshNormals(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Mesh texture coords
end
else if NodeType = 'meshtexturecoords' then
begin
if ParentNode is TDXMesh then
ReadMeshTexCoords(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Mesh material list
end
else if NodeType = 'meshmateriallist' then
begin
if ParentNode is TDXMesh then
ReadMeshMaterialList(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Mesh material
end
else if NodeType = 'material' then
begin
if ParentNode is TDXMesh then
ReadMeshMaterial(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Material texture filename
end
else if NodeType = 'texturefilename' then
begin
if ParentNode is TDXMesh then
ReadTextureFilename(TDXMesh(ParentNode));
ReadStruct(ParentNode);
// Unknown type
end
else
begin
// NewNode:=TDXNode.CreateOwned(ParentNode);
// NodeType:='*'+NodeType;
// ReadStruct(NewNode);
ReadStruct(ParentNode);
end;
if Assigned(NewNode) then
begin
NewNode.TypeName := NodeType;
NewNode.Name := NodeName;
end;
end;
end;
end;
begin
XText := TStringList.Create;
TempBuffer := TStringList.Create;
XText.LoadFromStream(Stream);
// Remove comments and white spaces
RemoveComments(XText);
XText.CommaText := XText.Text;
// Fix embedded open braces
Cursor := 0;
while Cursor < XText.Count - 1 do
begin
Buffer := ReadString;
if Pos('{', Buffer) > 1 then
begin
XText[Cursor - 1] := Copy(Buffer, 0, Pos('{', Buffer) - 1);
XText.Insert(Cursor, '{');
end;
end;
XText.SaveToFile('XText_dump.txt');
// Start parsing
Cursor := 0;
while Cursor < XText.Count - 1 do
ReadStruct(RootNode);
TempBuffer.Free;
XText.Free;
end;
// ----------------------------------------------------------------------
// TDXMaterialList
// ----------------------------------------------------------------------
function TDXMaterialList.GetMaterial(index: Integer): TDXMaterial;
begin
Result := TDXMaterial(Get(index));
end;
// ----------------------------------------------------------------------
// TDXMesh
// ----------------------------------------------------------------------
constructor TDXMesh.Create;
begin
inherited;
FVertices := TAffineVectorList.Create;
FNormals := TAffineVectorList.Create;
FTexCoords := TAffineVectorList.Create;
FVertexIndices := TIntegerList.Create;
FNormalIndices := TIntegerList.Create;
FMaterialIndices := TIntegerList.Create;
FVertCountIndices := TIntegerList.Create;
FMaterialList := TDXMaterialList.Create;
end;
destructor TDXMesh.Destroy;
begin
FVertices.Free;
FNormals.Free;
FTexCoords.Free;
FVertexIndices.Free;
FNormalIndices.Free;
FMaterialIndices.Free;
FVertCountIndices.Free;
FMaterialList.Free;
inherited;
end;
// ----------------------------------------------------------------------
// TDXNode
// ----------------------------------------------------------------------
constructor TDXNode.Create;
begin
// Virtual
end;
// CreateOwned
//
constructor TDXNode.CreateOwned(AOwner: TDXNode);
begin
FOwner := AOwner;
Create;
if Assigned(FOwner) then
FOwner.Add(Self);
end;
// GetItem
//
function TDXNode.GetItem(index: Integer): TDXNode;
begin
Result := TDXNode(Get(index));
end;
// Clear
//
procedure TDXNode.Clear;
var
i: Integer;
begin
for i := 0 to Count - 1 do
Items[i].Free;
inherited;
end;
// ----------------------------------------------------------------------
// TDXFrame
// ----------------------------------------------------------------------
// Create
//
constructor TDXFrame.Create;
begin
inherited;
FMatrix := IdentityHMGMatrix;
end;
// GlobalMatrix
//
function TDXFrame.GlobalMatrix: TMatrix;
begin
if Owner is TDXFrame then
Result := MatrixMultiply(TDXFrame(Owner).GlobalMatrix, FMatrix)
else
Result := FMatrix;
end;
// ----------------------------------------------------------------------
// TDXMaterial
// ----------------------------------------------------------------------
// CreateOwned
constructor TDXMaterial.CreateOwned(AOwner: TDXMaterialList);
begin
Create;
if Assigned(AOwner) then
AOwner.Add(Self);
end;
end.
|
{覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧抑
{ Project : Demo.dpr }
{ Comment : }
{ }
{ Date : 05/04/2009 00:03:35 }
{ Author : Cirec http://www.delphifr.com/auteur/CIREC/311214.aspx }
{覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧抑
{ Last modified }
{ Date : 18/04/2009 12:38:24 }
{ Author : Cirec http://www.delphifr.com/auteur/CIREC/311214.aspx }
{覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧抑
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtDlgs, jpeg, ExtCtrls, ComCtrls;
type
TFrm_Main = class(TForm)
img_BkGround: TImage;
img_ForeGround: TImage;
OpenPictureDialog1: TOpenPictureDialog;
btnChangeImg: TButton;
tkb_Opacity: TTrackBar;
ckb_NoAlpha: TCheckBox;
Label1: TLabel;
GroupBox1: TGroupBox;
ckb_Center: TCheckBox;
ckb_Proportional: TCheckBox;
ckb_Stretched: TCheckBox;
GroupBox2: TGroupBox;
Label2: TLabel;
btn_ChangeBkgImg: TButton;
ckb_bkNoAlpha: TCheckBox;
tkb_bkOpacity: TTrackBar;
ckb_bkCenter: TCheckBox;
ckb_bkProportional: TCheckBox;
ckb_bkStretched: TCheckBox;
Label3: TLabel;
ckb_Transparent: TCheckBox;
ckb_bkTransparent: TCheckBox;
Image1: TImage;
procedure btnChangeImgClick(Sender: TObject);
procedure tkb_OpacityChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ckb_NoAlphaClick(Sender: TObject);
private
{ D馗larations priv馥s }
public
{ D馗larations publiques }
end;
var
Frm_Main: TFrm_Main;
implementation
{$R *.dfm}
uses crBitmap32;
procedure TFrm_Main.btnChangeImgClick(Sender: TObject);
var MemFilter: string;
aImg: TImage;
begin
MemFilter := OpenPictureDialog1.Filter;
aImg := img_ForeGround;
if TComponent(Sender).Tag > 4 then
aImg := img_BkGround
else
OpenPictureDialog1.Filter := 'Bitmap (*.bmp)|*.bmp';
if OpenPictureDialog1.Execute then
begin
aImg.Picture.LoadFromFile(OpenPictureDialog1.FileName);
tkb_OpacityChange(Sender);
ckb_NoAlphaClick(Sender);
end;
OpenPictureDialog1.Filter := MemFilter;
end;
procedure TFrm_Main.tkb_OpacityChange(Sender: TObject);
var aImg: TImage;
aTkb: TTrackBar;
begin
aImg := img_ForeGround;
aTkb := tkb_Opacity;
if TComponent(Sender).Tag > 4 then
begin
aImg := img_BkGround;
aTkb := tkb_bkOpacity;
end;
if (aImg.Picture.Graphic is TBitmap) then
(aImg.Picture.Graphic as TBitmap).Opacity := aTkb.Position;
end;
procedure TFrm_Main.FormCreate(Sender: TObject);
begin
DoubleBuffered := True;
end;
procedure TFrm_Main.ckb_NoAlphaClick(Sender: TObject);
var aImg: TImage;
begin
aImg := img_ForeGround;
if TComponent(Sender).Tag > 4 then
aImg := img_BkGround;
with aImg do
begin
case TComponent(Sender).Tag of
0: begin
if (Picture.Graphic is TBitmap) then
(Picture.Graphic as TBitmap).NoAlpha := ckb_NoAlpha.Checked;
end;
5: begin
if (Picture.Graphic is TBitmap) then
(Picture.Graphic as TBitmap).NoAlpha := ckb_bkNoAlpha.Checked;
end;
1, 6: Center := TCheckBox(Sender).Checked;
2, 7: Proportional := TCheckBox(Sender).Checked;
3, 8: Stretch := TCheckBox(Sender).Checked;
4, 9: Transparent := TCheckBox(Sender).Checked;
end;
Invalidate;
end;
end;
end.
|
unit DXPConsts;
interface
const
{ color constants.
these constants are used as default colors for descendant controls
and may be replaced with other (common) values. }
{ colors - WindowsXP }
DXPColor_Enb_Border_WXP = $00733800; // border line
DXPColor_Dis_Border_WXP = $00BDC7CE; // border line (disabled)
DXPColor_Enb_Edges_WXP = $00AD9E7B; // border edges
DXPColor_Dis_Edges_WXP = $00BDC7CE; // border edges (disabled)
DXPColor_Enb_BgFrom_WXP = $00FFFFFF; // background from
DXPColor_Enb_BgTo_WXP = $00E7EBEF; // background to
DXPColor_Enb_CkFrom_WXP = $00C6CFD6; // clicked from
DXPColor_Enb_CkTo_WXP = $00EBF3F7; // clicked to
DXPColor_Enb_FcFrom_WXP = $00FFE7CE; // focused from
DXPColor_Enb_FcTo_WXP = $00EF846D; // focused to
DXPColor_Enb_HlFrom_WXP = $00CEF3FF; // highlight from
DXPColor_Enb_HlTo_WXP = $000096E7; // highlight to
DXPColor_Enb_HotTrack_WXP = $000000FF; // hottrack
{ checkbox colors - WindowsXP }
DXPColor_Chk_Enb_Border_WXP = $00845118; // border line
DXPColor_Chk_Enb_NmSymb_WXP = $0021A621; // symbol normal
{ misc colors - WindowsXP }
DXPColor_Msc_Dis_Caption_WXP = $0094A6A5; // caption color (disabled)
DXPColor_DotNetFrame = $00F7FBFF; // $00E7EBEF;
DXPColor_BorderLineOXP = $00663300;
DXPColor_BgOXP = $00D6BEB5;
DXPColor_BgCkOXP = $00CC9999;
implementation
end.
|
//*******************************************************//
// //
// DelphiFlash.com //
// Copyright (c) 2004-2007 FeatherySoft, Inc. //
// info@delphiflash.com //
// //
//*******************************************************//
// Description: Image routines
// Last update: 28 mar 2007
unit ImageReader;
interface
uses Windows, Classes;
type
PFColor =^TFColor;
TFColor = packed record
b,g,r: Byte;
end;
PFColorA =^TFColorA;
TFColorA = packed record
case Integer of
0: (i: DWord);
1: (c: TFColor);
2: (hi,lo: Word);
3: (b,g,r,a: Byte);
end;
PFColorTable =^TFColorTable;
TFColorTable = array[Byte]of TFColorA;
PFPackedColorTable =^TFPackedColorTable;
TFPackedColorTable = array[Byte]of TFColor;
TLines = array[Word]of Pointer; PLines =^TLines;
TLine8 = array[Word]of Byte; PLine8 =^TLine8;
TLine16 = array[Word]of Word; PLine16 =^TLine16;
TLine24 = array[Word]of TFColor; PLine24 =^TLine24;
TLine32 = array[Word]of TFColorA; PLine32 =^TLine32;
TPixels8 = array[Word]of PLine8; PPixels8 =^TPixels8;
TPixels16 = array[Word]of PLine16; PPixels16 =^TPixels16;
TPixels24 = array[Word]of PLine24; PPixels24 =^TPixels24;
TPixels32 = array[Word]of PLine32; PPixels32 =^TPixels32;
PBMInfo =^TBMInfo;
TBMInfo = packed record
Header: TBitmapInfoHeader;
case Integer of
0: (Colors: TFColorTable);
1: (RMask,GMask,BMask: DWord);
end;
TBMPReader = class
private
Info: TBMInfo; // bitmap information
FreeDC: Boolean; // default true, free GDI surface on destroy
FreeBits: Boolean; // default true, free Bits on destroy (non GDI only)
FreeHandle: Boolean;
FTransparentIndex: integer;
procedure SetTransparentIndex(const Value: integer); // default true, free GDI handle on destroy
function GetBMask: DWord;
function GetGMask: DWord;
function GetRMask: DWord;
procedure SetBMask(const Value: DWord);
procedure SetGMask(const Value: DWord);
procedure SetRMask(const Value: DWord);
function GetClrUsed: DWord;
procedure SetClrUsed(const Value: DWord);
function GetSizeImage: DWord;
procedure SetSizeImage(const Value: DWord);
function GetCompression: DWord;
procedure SetCompression(const Value: DWord);
function GetBpp: Word;
procedure SetBpp(const Value: Word);
function GetHeight: Integer;
procedure SetHeight(const Value: Integer);
function GetWidth: Integer;
procedure SetWidth(const Value: Integer);
protected
procedure PrepareAlphaTables(bmHeader: TBitmapInfoHeader);
public
DC: HDC;
Handle: HBITMAP; // current DIB in hDC
BWidth: Integer; // number of bytes per scanline
AbsHeight: Integer; // number of scanlines in bitmap
Gap: Integer; // number of pad bytes at end of scanline
Bits: PLine8; // typed pointer to bits
Colors: PFColorTable; // typed pointer to color table
Bpb,Bpg,Bpr: Byte; // bits per channel (only 16 & 32bpp)
BShr,GShr,RShr: Byte; // (B shr BShr)or(G shr GShr shl GShl)or
BShl,GShl,RShl: Byte; // (R shr RShr shl RShl) = 16bit/32bit pixel
Scanlines: PLines; // typed pointer to array of scanline offsets
Pixels8: PPixels8; // typed scanlines - Pixels8[y,x]: Byte
Pixels16: PPixels16; // typed scanlines - Pixels16[y,x]: Word
Pixels24: PPixels24; // typed scanlines - Pixels24[y,x]: TFColor
Pixels32: PPixels32; // typed scanlines - Pixels32[y,x]: TFColorA
constructor Create;
destructor Destroy; override;
procedure FreeHandles;
procedure Assign(Bmp:TBMPReader);
// use these for debugging or reference (these don't belong in long loops)
procedure SetPixel(y,x:Integer;c:TFColor);
procedure SetPixelB(y,x:Integer;c:Byte);
function GetPixel(y,x:Integer):TFColor;
function GetPixelB(y,x:Integer):Byte;
property Pixels[y,x:Integer]:TFColor read GetPixel write SetPixel;
property PixelsB[y,x:Integer]:Byte read GetPixelB write SetPixelB;
property Width: Integer read GetWidth write SetWidth;
property Height: Integer read GetHeight write SetHeight;
property Bpp: Word read GetBpp write SetBpp;
property Compression: DWord read GetCompression write SetCompression;
property SizeImage: DWord read GetSizeImage write SetSizeImage;
property ClrUsed: DWord read GetClrUsed write SetClrUsed;
property RMask: DWord read GetRMask write SetRMask;
property GMask: DWord read GetGMask write SetGMask;
property BMask: DWord read GetBMask write SetBMask;
// initializers
procedure SetSize(fWidth,fHeight:Integer;fBpp:Byte);
procedure SetSizeEx(fWidth, fHeight: Integer; fBpp, fBpr, fBpg, fBpb: Byte);
procedure SetSizeIndirect(bmInfo: TBMInfo);
procedure SetInterface(fBits: Pointer; fWidth, fHeight: Integer; fBpp, fBpr, fBpg, fBpb: Byte);
procedure SetInterfaceIndirect(fBits:Pointer;bmInfo:TBMInfo);
procedure MakeCopy(Bmp:TBMPReader;CopyBits:Boolean);
procedure LoadFromHandle(hBmp:HBITMAP);
procedure LoadFromFile(FileName:string);
procedure LoadFromStream(stream: TStream);
procedure LoadFromRes(hInst:HINST;ResID,ResType:PChar);
// blitting methods
procedure UpdateColors;
property TransparentIndex: integer read FTransparentIndex write SetTransparentIndex;
// utilities
procedure Clear(c:TFColor);
procedure ClearB(c:DWord);
procedure SaveToFile(FileName:string);
procedure SaveToStream(stream: TStream);
procedure CopyRect(Src:TBMPReader; x,y, w,h, sx,sy:Integer);
procedure ShiftColors(i1,i2,Amount:Integer);
end;
function CreateDIB(fDC:HDC;bmInfo:PBMInfo;iColor:DWord;var Bits:PLine8;hSection,dwOffset:DWord):HBITMAP; stdcall;
Function LoadHeaderFromFile(FileName:string): TBMInfo;
procedure SetAlphaChannel(Bmp, Alpha: TBMPReader);
procedure FillAlpha(Bmp: TBMPReader; Alpha: byte);
procedure FillAlphaNoSrc(Bmp: TBMPReader; Alpha: byte);
function IsInitAlpha(Bmp: TBMPReader): boolean;
procedure MultiplyAlpha(Bmp:TBMPReader);
procedure SwapChannels(Bmp:TBMPReader);
procedure FillMem(Mem:Pointer;Size,Value:Integer);
procedure Clear(Bmp:TBMPReader;c:TFColor);
procedure ClearB(Bmp:TBMPReader;c:DWord);
procedure DecodeRLE4(Bmp:TBMPReader;Data:Pointer);
procedure DecodeRLE8(Bmp:TBMPReader;Data:Pointer);
function ClosestColor(Pal:PFColorTable;Max:Integer;c:TFColor):Byte;
function LoadHeader(Data:Pointer; var bmInfo:TBMInfo):Integer;
function PackedDIB(Bmp:TBMPReader):Pointer;
function CountColors(Bmp:TBMPReader):DWord;
procedure IntToMask(Bpr,Bpg,Bpb:DWord;var RMsk,GMsk,BMsk:DWord);
procedure MaskToInt(RMsk,GMsk,BMsk:DWord;var Bpr,Bpg,Bpb:DWord);
function UnpackColorTable(Table:TFPackedColorTable):TFColorTable;
function PackColorTable(Table:TFColorTable):TFPackedColorTable;
function FRGB(r,g,b:Byte):TFColor;
function FRGBA(r,g,b,a:Byte):TFColorA;
function ColorToInt(c:TFColor):DWord;
function ColorToIntA(c:TFColorA):DWord;
function IntToColor(i:DWord):TFColor;
function IntToColorA(i:DWord):TFColorA;
function Scale8(i,n:Integer):Integer;
function Get16Bpg:Byte;
Function isSupportImageFormat(fn: string): boolean;
procedure GetJPGSize(const sFile: string; var wWidth, wHeight: word);
//procedure GetPNGSize(const sFile: string; var wWidth, wHeight: word);
//procedure GetGIFSize(const sGIFFile: string; var wWidth, wHeight: word);
implementation
Uses SysUtils;
function CreateDIB; external 'gdi32.dll' name 'CreateDIBSection';
function ReadMWord(f: TFileStream): word;
type
TMotorolaWord = record
case byte of
0: (Value: word);
1: (Byte1, Byte2: byte);
end;
var
MW: TMotorolaWord;
begin
{It would probably be better to just read these two bytes in normally and
then do a small ASM routine to swap them. But we aren't talking about
reading entire files, so I doubt the performance gain would be worth the trouble.}
f.Read(MW.Byte2, SizeOf(Byte));
f.Read(MW.Byte1, SizeOf(Byte));
Result := MW.Value;
end;
procedure GetJPGSize(const sFile: string; var wWidth, wHeight: word);
const
ValidSig : array[0..1] of byte = ($FF, $D8);
Parameterless = [$01, $D0, $D1, $D2, $D3, $D4, $D5, $D6, $D7];
var
Sig: array[0..1] of byte;
f: TFileStream;
x: integer;
Seg: byte;
Dummy: array[0..15] of byte;
Len: word;
ReadLen: LongInt;
begin
FillChar(Sig, SizeOf(Sig), #0);
f := TFileStream.Create(sFile, fmOpenRead+fmShareDenyWrite);
try
ReadLen := f.Read(Sig[0], SizeOf(Sig));
for x := Low(Sig) to High(Sig) do
if Sig[x] <> ValidSig[x] then ReadLen := 0;
if ReadLen > 0 then begin
ReadLen := f.Read(Seg, 1);
while (Seg = $FF) and (ReadLen > 0) do begin
ReadLen := f.Read(Seg, 1);
if Seg <> $FF then begin
if (Seg = $C0) or (Seg = $C1) then begin
ReadLen := f.Read(Dummy[0], 3); { don't need these bytes }
wHeight := ReadMWord(f);
wWidth := ReadMWord(f);
end else begin
if not (Seg in Parameterless) then begin
Len := ReadMWord(f);
f.Seek(Len-2, 1);
f.Read(Seg, 1);
end else
Seg := $FF; { Fake it to keep looping. }
end;
end;
end;
end;
finally
f.Free;
end;
end;
Function isSupportImageFormat(fn: string): boolean;
var Ext: string;
begin
Ext := UpperCase(ExtractFileExt(fn));
Result := (Ext = '.BMP') or (Ext = '.JPG') or (Ext = '.JPEG');
end;
constructor TBMPReader.Create;
begin
inherited Create;
Bits := nil;
Scanlines := nil;
FTransparentIndex := -1;
FillChar(Info, SizeOf(Info),0);
Info.Header.biSize := SizeOf(TBitmapInfoHeader);
Info.Header.biPlanes := 1;
Colors := @Info.Colors;
end;
destructor TBMPReader.Destroy;
begin
FreeHandles;
inherited Destroy;
end;
procedure TBMPReader.FreeHandles;
begin
if (DC <> 0) and FreeDC then DeleteDC(DC);
if (Handle <> 0) and FreeHandle then DeleteObject(Handle);
if (Scanlines <> nil) then ReallocMem(Scanlines, 0);
if (Bits <> nil) and FreeBits then ReallocMem(Bits, 0);
end;
procedure TBMPReader.Assign(Bmp:TBMPReader);
begin
FreeHandles;
DC := Bmp.DC;
Handle:=Bmp.Handle; BWidth:=Bmp.BWidth;
AbsHeight:=Bmp.AbsHeight; Gap:=Bmp.Gap;
Bits:=Bmp.Bits; Colors^:=Bmp.Colors^;
Info:=Bmp.Info; BShr:=Bmp.BShr;
GShr:=Bmp.GShr; GShl:=Bmp.GShl;
RShr:=Bmp.RShr; RShl:=Bmp.RShl;
Bpr:=Bmp.Bpr; Bpg:=Bmp.Bpg;
Bpb:=Bmp.Bpb; Scanlines:=Bmp.Scanlines;
Pixels8:=Bmp.Pixels8; Pixels16:=Bmp.Pixels16;
Pixels24:=Bmp.Pixels24; Pixels32:=Bmp.Pixels32;
FreeDC:=Bmp.FreeDC;
FreeBits:=Bmp.FreeBits; FreeHandle:=Bmp.FreeHandle;
Bmp.FreeDC:=False;
Bmp.FreeHandle:=False;
Bmp.Scanlines:=nil;
Bmp.FreeBits:=False;
Bmp.Free;
end;
procedure TBMPReader.SetPixel(y,x:Integer;c:TFColor);
begin
case Bpp of
1,4,8: PixelsB[y,x]:=ClosestColor(Colors,(1 shl Bpp)-1,c);
16: Pixels16[y,x]:=
c.r shr RShr shl RShl or
c.g shr GShr shl GShl or
c.b shr BShr;
24: Pixels24[y,x]:=c;
32: if Compression=0 then Pixels32[y,x].c:=c else
Pixels32[y,x].i:=
c.r shr RShr shl RShl or
c.g shr GShr shl GShl or
c.b shr BShr;
end;
end;
procedure TBMPReader.SetPixelB(y,x:Integer;c:Byte);
var
mo: Byte;
pb: PByte;
begin
case Bpp of
1:
begin
c:=c and 1;
mo:=(x and 7)xor 7;
pb:=@Pixels8[y,x shr 3];
pb^:=pb^ and(not(1 shl mo))or(c shl mo);
end;
4:
begin
c:=c and 15;
pb:=@Pixels8[y,x shr 1];
if(x and 1)=0 then pb^:=(pb^and $0F)or(c shl 4)else pb^:=(pb^and $F0)or c;
end;
8: Pixels8[y,x]:=c;
end;
end;
function TBMPReader.GetBMask: DWord;
begin
Result := Info.BMask;
end;
procedure TBMPReader.SetRMask(const Value: DWord);
begin
Info.RMask := Value;
end;
function TBMPReader.GetBpp: Word;
begin
Result := Info.Header.biBitCount;
end;
function TBMPReader.GetClrUsed: DWord;
begin
Result := Info.Header.biClrUsed
end;
function TBMPReader.GetCompression: DWord;
begin
Result := Info.Header.biCompression
end;
function TBMPReader.GetGMask: DWord;
begin
Result := Info.GMask;
end;
function TBMPReader.GetHeight: Integer;
begin
Result := Info.Header.biHeight;
end;
function TBMPReader.GetPixel(y,x:Integer):TFColor;
var
w: Word;
d: DWord;
begin
case Bpp of
1,4,8: Result:=Colors[PixelsB[y,x]].c;
16:
begin
w:=Pixels16[y,x];
Result.b:=Scale8(w and BMask,Bpb);
Result.g:=Scale8(w and GMask shr GShl,Bpg);
Result.r:=Scale8(w and RMask shr RShl,Bpr);
end;
24: Result:=Pixels24[y,x];
32:
if Compression=0 then Result:=Pixels32[y,x].c else
begin
d:=Pixels32[y,x].i;
Result.b:=Scale8(d and BMask,Bpb);
Result.g:=Scale8(d and GMask shr GShl,Bpg);
Result.r:=Scale8(d and RMask shr RShl,Bpr);
end;
end;
end;
function TBMPReader.GetPixelB(y,x:Integer):Byte;
var
mo: Byte;
begin
case Bpp of
1:
begin
mo := (x and 7)xor 7;
Result := Pixels8[y, x shr 3] and (1 shl mo) shr mo;
end;
4: if (x and 1) = 0 then Result := Pixels8[y,x shr 1] shr 4 else Result:=Pixels8[y,x shr 1] and 15;
8: Result:=Pixels8[y,x];
else Result:=0;
end;
end;
function TBMPReader.GetRMask: DWord;
begin
Result := Info.RMask;
end;
function TBMPReader.GetSizeImage: DWord;
begin
Result := Info.Header.biSizeImage;
end;
procedure TBMPReader.SetWidth(const Value: Integer);
begin
Info.Header.biWidth := Value;
end;
procedure TBMPReader.SetSize(fWidth,fHeight:Integer;fBpp:Byte);
begin
SetInterface(nil,fWidth,fHeight,fBpp,0,0,0);
end;
procedure TBMPReader.SetSizeEx(fWidth,fHeight:Integer;fBpp,fBpr,fBpg,fBpb:Byte);
begin
SetInterface(nil,fWidth,fHeight,fBpp,fBpr,fBpg,fBpb);
end;
procedure TBMPReader.SetSizeImage(const Value: DWord);
begin
Info.Header.biSizeImage := Value;
end;
procedure TBMPReader.SetSizeIndirect(bmInfo: TBMInfo);
var
r, g, b: DWord;
begin
if bmInfo.Header.biCompression in [1, 2] then
if (bmInfo.RMask <> 0) or (bmInfo.GMask <> 0) or (bmInfo.BMask <> 0)then
bmInfo.Header.biCompression := 3 else bmInfo.Header.biCompression := 0;
if (bmInfo.Header.biBitCount in [16, 32]) and (bmInfo.Header.biCompression = 3) then
MaskToInt(bmInfo.RMask, bmInfo.GMask, bmInfo.BMask, r, g, b) else
begin
r:=0;
g:=0;
b:=0;
end;
FTransparentIndex := -1;
if bmInfo.Header.biBitCount <= 8 then
Colors^ := bmInfo.Colors;
PrepareAlphaTables(bmInfo.Header);
SetInterface(nil, bmInfo.Header.biWidth, bmInfo.Header.biHeight, bmInfo.Header.biBitCount, r, g, b);
end;
procedure TBMPReader.SetTransparentIndex(const Value: integer);
begin
if (BPP <= 8) and (FTransparentIndex <> Value) then
begin
Colors[FTransparentIndex].A := $FF;
FTransparentIndex := Value;
Colors[FTransparentIndex].A := 0;
end;
end;
function TBMPReader.GetWidth: Integer;
begin
Result := Info.Header.biWidth;
end;
procedure TBMPReader.SetBMask(const Value: DWord);
begin
Info.BMask := Value;
end;
procedure TBMPReader.SetBpp(const Value: Word);
begin
Info.Header.biBitCount := Value;
end;
procedure TBMPReader.SetClrUsed(const Value: DWord);
begin
Info.Header.biClrUsed := Value;
end;
procedure TBMPReader.SetCompression(const Value: DWord);
begin
Info.Header.biCompression := Value;
end;
procedure TBMPReader.SetGMask(const Value: DWord);
begin
Info.GMask := Value;
end;
procedure TBMPReader.SetHeight(const Value: Integer);
begin
Info.Header.biHeight := Value;
end;
procedure TBMPReader.SetInterface(fBits: Pointer; fWidth, fHeight: Integer;
fBpp, fBpr, fBpg, fBpb: Byte);
var
x, il: Integer;
sDC: Windows.HDC;
begin
if fBpp=0 then
begin
sDC:=GetDC(0);
fBpp:=GetDeviceCaps(sDC, BITSPIXEL);
ReleaseDC(0,sDC);
if fBpp=16 then
begin
fBpr:=5;
fBpg:=Get16Bpg;
fBpb:=5;
end else if fBpp=32 then
begin
fBpr:=8;
fBpg:=8;
fBpb:=8;
end;
end;
if (fBpr = 0) and (fBpg = 0) and (fBpb = 0) then
begin
Compression:=0;
if fBpp=16 then
begin
fBpr:=5;
fBpg:=5;
fBpb:=5;
end else if fBpp=32 then
begin
fBpr:=8;
fBpg:=8;
fBpb:=8;
end;
end else Compression:=3;
if( fBpp=16) or (fBpp=32) then IntToMask(fBpr, fBpg, fBpb, Info.RMask, Info.GMask, Info.BMask);
if((fBits=nil) and (fWidth=Width) and (fHeight=Height) and (fBpp=Bpp) and
(fBpr=Bpr) and (fBpg=Bpg) and (fBpb=Bpb)) and (DC<>0) then Exit;
Width:=fWidth; Height:=fHeight;
AbsHeight:=Abs(fHeight); Bpp:=fBpp;
Bpr:=fBpr; Bpg:=fBpg;
Bpb:=fBpb; GShl:=Bpb;
RShl:=Bpb+Bpg;
if Bpb<8 then BShr:=8-Bpb else BShr:=0;
if Bpg<8 then GShr:=8-Bpg else GShr:=0;
if Bpr<8 then RShr:=8-Bpr else RShr:=0;
case Bpp of
1:
begin
x:=(Width+7)and -8;
BWidth:=((x+31)and -32)shr 3;
Gap:=BWidth-(x shr 3);
end;
4:
begin
x:=((Width shl 2)+7)and -8;
BWidth:=((x+31)and -32)shr 3;
Gap:=BWidth-(x shr 3);
end;
8:
begin
BWidth:=(((Width shl 3)+31)and -32)shr 3;
Gap:=BWidth-Width;
end;
16:
begin
BWidth:=(((Width shl 4)+31)and -32)shr 3;
Gap:=BWidth-(Width shl 1);
end;
24:
begin
BWidth:=(((Width*24)+31)and -32)shr 3;
Gap:=BWidth-((Width shl 1)+Width);
end;
32:
begin
BWidth:=(((Width shl 5)+31)and -32)shr 3;
Gap:=0;
end;
end;
SizeImage := AbsHeight * BWidth;
if (fBits<>nil) then Bits := fBits else
begin
if (DC<>0) and FreeDC then DeleteDC(DC);
if (Handle<>0) and FreeHandle then DeleteObject(Handle);
if (Bits <> nil) and FreeBits then ReallocMem(Bits, 0);
Handle := CreateDIB(0, @Info, 0, Bits, 0, 0);
DC := CreateCompatibleDC(0);
SelectObject(DC, Handle);
FreeBits := False;
FreeDC := True;
FreeHandle := True;
end;
ReallocMem(Scanlines, AbsHeight shl 2);
Pixels8 := Pointer(Scanlines);
Pixels16 := Pointer(Scanlines);
Pixels24 := Pointer(Scanlines);
Pixels32 := Pointer(Scanlines);
if AbsHeight>0 then
begin
x := Integer(Bits);
for il:=0 to AbsHeight-1 do
begin
Scanlines[il] := Ptr(x);
Inc(x, BWidth);
end;
end;
end;
procedure TBMPReader.SetInterfaceIndirect(fBits: Pointer; bmInfo: TBMInfo);
var
r, g, b: DWord;
begin
With bmInfo.Header do
begin
if biCompression in [1, 2] then
if (bmInfo.RMask<>0) or (bmInfo.GMask<>0) or (bmInfo.BMask<>0) then
biCompression := 3 else biCompression := 0;
if (biBitCount in [16, 32]) and (biCompression = 3) then
MaskToInt(bmInfo.RMask, bmInfo.GMask, bmInfo.BMask, r, g, b) else
begin
r:=0; g:=0; b:=0;
end;
if biBitCount<=8 then Colors^:=bmInfo.Colors;
end;
SetInterface(fBits, bmInfo.Header.biWidth, bmInfo.Header.biHeight, bmInfo.Header.biBitCount, r, g, b);
end;
procedure TBMPReader.MakeCopy(Bmp: TBMPReader; CopyBits: Boolean);
begin
SetSizeIndirect(Bmp.Info);
if CopyBits then Move(Bmp.Bits^, Bits^, SizeImage);
end;
procedure TBMPReader.PrepareAlphaTables(bmHeader: TBitmapInfoHeader);
var
il, maxCheck: integer;
NeedFillAlpha, is0, is255: boolean;
begin
FTransparentIndex := -1;
if bmHeader.biBitCount <= 8 then
begin
if bmHeader.biBitCount = 8 then
begin
is0 := false;
is255 := false;
if bmHeader.biClrUsed > 0 then maxCheck := bmHeader.biClrUsed - 1
else maxCheck := $FF;
for il := 0 to maxCheck do
begin
if Colors[il].A = $FF then is255 := true else
if Colors[il].A = 0 then is0 := true;
end;
NeedFillAlpha := (is0 and not is255);
if is0 and is255 then
for il := 0 to $FF do
if Colors[il].A = 0 then
begin
FTransparentIndex := il;
Break;
end;
end else
NeedFillAlpha := true;
if NeedFillAlpha then
for il := 0 to (1 shl bmHeader.biBitCount) - 1 do
Colors[il].A := $FF;
end;
end;
procedure TBMPReader.LoadFromHandle(hBmp:HBITMAP);
var
dsInfo: TDIBSection;
begin
if GetObject(hBmp,SizeOf(dsInfo),@dsInfo)=84 then
begin
SetSizeIndirect(PBMInfo(@dsInfo.dsBmih)^);
if dsInfo.dsBmih.biCompression = 1 then DecodeRLE8(Self,dsInfo.dsBm.bmBits)
else if dsInfo.dsBmih.biCompression = 2 then DecodeRLE4(Self,dsInfo.dsBm.bmBits)
else Move(dsInfo.dsBm.bmBits^, Bits^, dsInfo.dsBmih.biSizeImage);
if Bpp <= 8 then
begin
GetDIBits(DC, hBmp, 0, 0, nil, PBitmapInfo(@Info)^, 0);
UpdateColors;
PrepareAlphaTables(Info.Header);
end;
end else
begin
SetSize(dsInfo.dsBm.bmWidth, dsInfo.dsBm.bmHeight, 0);
GetDIBits(DC, hBmp, 0, AbsHeight, Bits, PBitmapInfo(@Info)^, 0);
if Bpp <= 8 then
begin
UpdateColors;
PrepareAlphaTables(Info.Header);
end;
end;
end;
procedure TBMPReader.LoadFromFile(FileName: string);
var
FS : TFileStream;
begin
FS := TFileStream.Create(FileName, fmOpenRead + fmShareDenyWrite);
LoadFromStream(FS);
FS.Free;
end;
procedure TBMPReader.LoadFromStream(stream: TStream);
var
Buffer: Pointer;
bmInfo: TBMInfo;
fBits, xSize: DWord;
begin
xSize := stream.size;
if xSize > 1078 then xSize := 1078;
GetMem(Buffer, 1078);
stream.read(Buffer^, xSize);
fBits := LoadHeader(Buffer, bmInfo);
SetSizeIndirect(bmInfo);
stream.Seek(fBits - xSize, soFromCurrent);
if bmInfo.Header.biCompression in [1, 2] then xSize := PDWord(Integer(Buffer)+2)^ - fBits
else
if (stream.size - fBits) > SizeImage then xSize := SizeImage else xSize := stream.size - fBits;
if bmInfo.Header.biCompression in [0, 3] then stream.read(Bits^, xSize) else
begin
ReAllocMem(Buffer, xSize);
stream.read(Buffer^, xSize);
if bmInfo.Header.biCompression=1 then DecodeRLE8(Self, Buffer) else DecodeRLE4(Self, Buffer);
end;
FreeMem(Buffer);
end;
Function LoadHeaderFromFile(FileName:string): TBMInfo;
var
Buffer: Pointer;
hFile: Windows.HFILE;
xSize, fSize, i: DWord;
begin
hFile := CreateFile(PChar(FileName),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,0,0);
fSize := GetFileSize(hFile,nil);
xSize := fSize;
if xSize > 1078 then xSize :=1078;
GetMem(Buffer, 1078);
ReadFile(hFile, Buffer^, xSize, i, nil);
LoadHeader(Buffer, Result);
CloseHandle(hFile);
FreeMem(Buffer);
end;
procedure TBMPReader.LoadFromRes(hInst: HINST; ResID, ResType: PChar);
var
pMem: Pointer;
bmInfo: TBMInfo;
fSize,fBits: DWord;
begin
pMem := LockResource(LoadResource(hInst, FindResource(hInst, ResID, ResType)));
if pMem<>nil then
begin
fBits := LoadHeader(pMem,bmInfo);
fSize := PDWord(pMem)^-DWord(fBits);
SetSizeIndirect(bmInfo);
if SizeImage < fSize then fSize := SizeImage;
if bmInfo.Header.biCompression=1 then DecodeRLE8(Self, Ptr(DWord(pMem) + fBits))
else
if bmInfo.Header.biCompression=2 then DecodeRLE4(Self, Ptr(DWord(pMem) + fBits))
else Move(Ptr(DWord(pMem)+fBits)^,Bits^,fSize);
end;
end;
procedure TBMPReader.UpdateColors;
begin
SetDIBColorTable(DC, 0, 1 shl Bpp, Colors^);
end;
procedure TBMPReader.Clear(c:TFColor);
begin
ImageReader.Clear(Self, c);
end;
procedure TBMPReader.ClearB(c:DWord);
begin
ImageReader.ClearB(Self,c);
end;
procedure TBMPReader.SaveToFile(FileName:string);
var
FS: TFileStream;
begin
if fileExists(FileName) then DeleteFile(FileName);
FS := TFileStream.Create(FileName, fmCreate);
SaveToStream(FS);
FS.Free;
end;
procedure TBMPReader.SaveToStream(stream: TStream);
var
cSize: DWord;
fHead: TBitmapFileHeader;
begin
if Info.Header.biClrUsed<>0
then cSize := (Info.Header.biClrUsed shl 2)
else if Info.Header.biCompression=BI_BITFIELDS then cSize := 12
else if Bpp <= 8 then cSize := (1 shl Bpp) shl 2
else cSize := 0;
fHead.bfType := $4D42;
fHead.bfOffBits := 54 + cSize;
fHead.bfSize := fHead.bfOffBits + SizeImage;
stream.Write(fHead, SizeOf(fHead));
stream.Write(Info,cSize+40);
stream.WriteBuffer(Bits^, SizeImage);
end;
procedure TBMPReader.CopyRect(Src:TBMPReader;x,y,w,h,sx,sy:Integer);
var
iy,pc,sc,b: Integer;
begin
if Height>0 then y:=AbsHeight-h-y;
if Src.Height>0 then sy:=Src.Height-h-sy;
if x<0 then
begin
Dec(sx,x);
Inc(w,x);
x:=0;
end;
if y<0 then
begin
Dec(sy,y);
Inc(h,y);
y:=0;
end;
if sx<0 then
begin
Dec(x,sx);
Inc(w,sx);
sx:=0;
end;
if sy<0 then
begin
Dec(y,sy);
Inc(h,sy);
sy:=0;
end;
if(sx<Src.Width)and(sy<Src.AbsHeight)and(x<Width)and(y<AbsHeight)then
begin
if w+sx>=Src.Width then w:=Src.Width-sx;
if h+sy>=Src.AbsHeight then h:=Src.AbsHeight-sy;
if w+x>=Width then w:=Width-x;
if h+y>=AbsHeight then h:=AbsHeight-y;
if (Bpp <= 8) and (Bpp=Src.Bpp) then
Move(Src.Colors^, Colors^, SizeOf(TFColorTable));
if(Bpp>=8)and(Bpp=Src.Bpp)then
begin
b:=w;
case Bpp of
16:
begin
b:=w shl 1;
x:=x shl 1;
sx:=sx shl 1;
end;
24:
begin
b:=w*3;
x:=x*3;
sx:=sx*3;
end;
32:
begin
b:=w shl 2;
x:=x shl 2;
sx:=sx shl 2;
end;
end;
pc:=Integer(Scanlines[y])+x;
sc:=Integer(Src.Scanlines[sy])+sx;
for iy:=0 to h-1 do
begin
Move(Ptr(sc)^,Ptr(pc)^,b);
Inc(pc,BWidth);
Inc(sc,Src.BWidth);
end;
end else
begin
for iy:=0 to h-1 do
for b:=0 to w-1 do
Pixels[y+iy,x+b]:=Src.Pixels[sy+iy,sx+b];
end;
end;
end;
procedure TBMPReader.ShiftColors(i1, i2, Amount: Integer);
var
p: PFColorTable;
i: Integer;
begin
i:= i2 - i1;
if (Amount < i) and (Amount > 0) then
begin
GetMem(p, i shl 2);
Move(Colors[i1], p[0], i shl 2);
Move(p[0], Colors[i1 + Amount], (i - Amount) shl 2);
Move(p[i - Amount], Colors[i1], Amount shl 2);
FreeMem(p);
end;
if DC <> 0 then UpdateColors;
end;
////////////////////////////////////////////////////////////////////////////////
procedure SetAlphaChannel(Bmp, Alpha: TBMPReader);
var
pb: PByte;
pc: PFColorA;
x,y: Integer;
begin
pb := Pointer(Alpha.Bits);
pc := Pointer(Bmp.Bits);
for y := 0 to Alpha.AbsHeight - 1 do
begin
for x := 0 to Alpha.Width - 1 do
begin
pc^.a := pb^;
Inc(pc);
Inc(pb);
end;
pc := Ptr(Integer(pc) + Bmp.Gap);
Inc(pb, Alpha.Gap);
end;
end;
procedure FillAlpha(Bmp: TBMPReader; Alpha: byte);
var
pc: PFColorA;
x,y: Integer;
begin
pc := Pointer(Bmp.Bits);
for y := 0 to Bmp.AbsHeight - 1 do
begin
for x := 0 to Bmp.Width - 1 do
begin
pc^.a := Alpha;
Inc(pc);
end;
pc := Ptr(Integer(pc) + Bmp.Gap);
end;
end;
procedure FillAlphaNoSrc(Bmp: TBMPReader; Alpha: byte);
var
pc: PFColorA;
x,y: Integer;
begin
pc := Pointer(Bmp.Bits);
for y := 0 to Bmp.AbsHeight - 1 do
begin
for x := 0 to Bmp.Width - 1 do
begin
if (pc^.r > 0) or (pc^.g > 0) or (pc^.b > 0)
then pc^.a := Alpha
else pc^.a := 0;
Inc(pc);
end;
pc := Ptr(Integer(pc) + Bmp.Gap);
end;
end;
function IsInitAlpha(Bmp: TBMPReader): boolean;
var
pc: PFColorA;
x,y: Integer;
begin
pc := Pointer(Bmp.Bits);
Result := false;
for y := 0 to Bmp.AbsHeight - 1 do
begin
for x := 0 to Bmp.Width - 1 do
begin
Result := pc^.a > 0;
if Result then Exit;
Inc(pc);
end;
pc := Ptr(Integer(pc) + Bmp.Gap);
end;
end;
procedure MultiplyAlpha(Bmp:TBMPReader);
var
pc: PFColorA;
x,y,i: Integer;
begin
pc:=Pointer(Bmp.Bits);
for y:=0 to Bmp.AbsHeight-1 do
begin
for x:=0 to Bmp.Width-1 do
begin
i:=pc.a;
if i=0 then
begin
pc.b:=0;
pc.g:=0;
pc.r:=0;
end else if i<255 then
begin
pc.b:=(pc.b*i)shr 8;
pc.g:=(pc.g*i)shr 8;
pc.r:=(pc.r*i)shr 8;
end;
Inc(pc);
end;
pc:=Ptr(Integer(pc)+Bmp.Gap);
end;
end;
procedure SwapChannels24(Bmp:TBMPReader);
var
pc: PFColor;
x,y,z: Integer;
begin
pc:=Pointer(Bmp.Bits);
for y:=0 to Bmp.AbsHeight-1 do
begin
for x:=0 to Bmp.Width-1 do
begin
z:=pc.r;
pc.r:=pc.b;
pc.b:=z;
Inc(pc);
end;
pc:=Ptr(Integer(pc)+Bmp.Gap);
end;
end;
procedure SwapChannels32(Bmp:TBMPReader);
var
pc: PFColorA;
x,y,z: Integer;
begin
pc:=Pointer(Bmp.Bits);
for y:=0 to Bmp.AbsHeight-1 do
begin
for x:=0 to Bmp.Width-1 do
begin
z:=pc.r;
pc.r:=pc.b;
pc.b:=z;
Inc(pc);
end;
pc:=Ptr(Integer(pc)+Bmp.Gap);
end;
end;
procedure SwapChannels(Bmp:TBMPReader);
begin
case Bmp.Bpp of
24: SwapChannels24(Bmp);
32: SwapChannels32(Bmp);
end;
end;
procedure FillMem(Mem:Pointer;Size,Value:Integer);
asm
push edi
push ebx
mov ebx,edx
mov edi,eax
mov eax,ecx
mov ecx,edx
shr ecx,2
jz @word
rep stosd
@word:
mov ecx,ebx
and ecx,2
jz @byte
mov [edi],ax
add edi,2
@byte:
mov ecx,ebx
and ecx,1
jz @exit
mov [edi],al
@exit:
pop ebx
pop edi
end;
procedure Clear(Bmp:TBMPReader;c:TFColor);
begin
case Bmp.Bpp of
1,4,8: ClearB(Bmp,ClosestColor(Bmp.Colors,(1 shl Bmp.Bpp)-1,c));
16: ClearB(Bmp,c.r shr Bmp.RShr shl Bmp.RShl or
c.g shr Bmp.GShr shl Bmp.GShl or
c.b shr Bmp.BShr);
24: ClearB(Bmp,PDWord(@c)^);
32: if Bmp.Compression = 0 then ClearB(Bmp,PDWord(@c)^) else
ClearB(Bmp,c.r shr Bmp.RShr shl Bmp.RShl or
c.g shr Bmp.GShr shl Bmp.GShl or
c.b shr Bmp.BShr);
end;
end;
procedure ClearB(Bmp:TBMPReader;c:DWord);
var
i: Integer;
pc: PFColor;
begin
if(Bmp.Bpp=1)and(c=1)then c:=15;
if Bmp.Bpp<=4 then c:=c or c shl 4;
if Bmp.Bpp<=8 then
begin
c:=c or c shl 8;
c:=c or c shl 16;
end else if Bmp.Bpp=16 then c:=c or c shl 16;
if Bmp.Bpp=24 then
begin
pc:=Pointer(Bmp.Bits);
for i:=0 to Bmp.Width-1 do
begin
pc^:=PFColor(@c)^;
Inc(pc);
end;
for i:=1 to Bmp.AbsHeight-1 do
Move(Bmp.Bits^,Bmp.Scanlines[i]^,Bmp.BWidth-Bmp.Gap);
end else
begin
if Bmp.SizeImage <> 0 then FillMem(Bmp.Bits, Bmp.SizeImage, c) else
for i:=0 to Bmp.AbsHeight-1 do
FillMem(Bmp.Scanlines[i],Bmp.BWidth-Bmp.Gap,c);
end;
end;
procedure DecodeRLE4(Bmp:TBMPReader;Data:Pointer);
procedure OddMove(Src,Dst:PByte;Size:Integer);
begin
if Size=0 then Exit;
repeat
Dst^:=(Dst^ and $F0)or(Src^ shr 4);
Inc(Dst);
Dst^:=(Dst^ and $0F)or(Src^ shl 4);
Inc(Src);
Dec(Size);
until Size=0;
end;
procedure OddFill(Mem:PByte;Size,Value:Integer);
begin
Value:=(Value shr 4)or(Value shl 4);
Mem^:=(Mem^ and $F0)or(Value and $0F);
Inc(Mem);
if Size>1 then FillChar(Mem^,Size,Value);
Mem^:=(Mem^ and $0F)or(Value and $F0);
end;
var
pb: PByte;
x,y,z,i: Integer;
begin
pb:=Data; x:=0; y:=0;
while y<Bmp.AbsHeight do
begin
if pb^=0 then
begin
Inc(pb);
z:=pb^;
case pb^ of
0: begin
Inc(y);
x:=0;
end;
1: Break;
2: begin
Inc(pb); Inc(x,pb^);
Inc(pb); Inc(y,pb^);
end;
else
begin
Inc(pb);
i:=(z+1)shr 1;
if(z and 2)=2 then Inc(i);
if((x and 1)=1)and(x+i<Bmp.Width)then
OddMove(pb,@Bmp.Pixels8[y,x shr 1],i)
else
Move(pb^,Bmp.Pixels8[y,x shr 1],i);
Inc(pb,i-1);
Inc(x,z);
end;
end;
end else
begin
z:=pb^;
Inc(pb);
if((x and 1)=1)and(x+z<Bmp.Width)then
OddFill(@Bmp.Pixels8[y,x shr 1],z shr 1,pb^)
else
FillChar(Bmp.Pixels8[y,x shr 1],z shr 1,pb^);
Inc(x,z);
end;
Inc(pb);
end;
end;
procedure DecodeRLE8(Bmp:TBMPReader;Data:Pointer);
var
pb: PByte;
x,y,z,i,s: Integer;
begin
pb:=Data; y:=0; x:=0;
while y<Bmp.AbsHeight do
begin
if pb^=0 then
begin
Inc(pb);
case pb^ of
0: begin
Inc(y);
x:=0;
end;
1: Break;
2: begin
Inc(pb); Inc(x,pb^);
Inc(pb); Inc(y,pb^);
end;
else
begin
i:=pb^;
s:=(i+1)and(not 1);
z:=s-1;
Inc(pb);
if x+s>Bmp.Width then s:=Bmp.Width-x;
Move(pb^,Bmp.Pixels8[y,x],s);
Inc(pb,z);
Inc(x,i);
end;
end;
end else
begin
i:=pb^; Inc(pb);
if i+x>Bmp.Width then i:=Bmp.Width-x;
FillChar(Bmp.Pixels8[y,x],i,pb^);
Inc(x,i);
end;
Inc(pb);
end;
end;
procedure FillColors(Pal:PFColorTable;i1,i2,nKeys:Integer;Keys:PLine24);
var
pc: PFColorA;
c1,c2: TFColor;
i,n,cs,w1,w2,x,ii: Integer;
begin
i:=0;
n:=i2-i1;
Dec(nKeys);
ii:=(nKeys shl 16)div n;
pc:=@Pal[i1];
for x:=0 to n-1 do
begin
cs:=i shr 16;
c1:=Keys[cs];
if cs<nKeys then Inc(cs);
c2:=Keys[cs];
w1:=((not i)and $FFFF)+1;
w2:=i and $FFFF;
if(w1<(ii-w1))then pc.c:=c2 else
if(w2<(ii-w2))then pc.c:=c1 else
begin
pc.b:=((c1.b*w1)+(c2.b*w2))shr 16;
pc.g:=((c1.g*w1)+(c2.g*w2))shr 16;
pc.r:=((c1.r*w1)+(c2.r*w2))shr 16;
end;
Inc(i,ii);
Inc(pc);
end;
pc.c:=c2;
end;
function ClosestColor(Pal:PFColorTable;Max:Integer;c:TFColor):Byte;
var
n: Byte;
pc: PFColorA;
i,x,d: Integer;
begin
x:=765; n:=0;
pc:=Pointer(Pal);
for i:=0 to Max do
begin
if pc.b>c.b then d:=pc.b-c.b else d:=c.b-pc.b;
if pc.g>c.g then Inc(d,pc.g-c.g) else Inc(d,c.g-pc.g);
if pc.r>c.r then Inc(d,pc.r-c.r) else Inc(d,c.r-pc.r);
if d<x then
begin
x:=d;
n:=i;
end;
Inc(pc);
end;
Result:=n;
end;
function LoadHeader(Data:Pointer; var bmInfo:TBMInfo):Integer;
var
i: Integer;
begin
if PDWord(Ptr(Integer(Data)+14))^ = 40 then
Move(Ptr(Integer(Data)+14)^, bmInfo, SizeOf(bmInfo))
else
if PDWord(Ptr(Integer(Data)+14))^ = 12 then
with PBitmapCoreInfo(Ptr(Integer(Data)+14))^ do
begin
FillChar(bmInfo, SizeOf(bmInfo), 0);
bmInfo.Header.biWidth := bmciHeader.bcWidth;
bmInfo.Header.biHeight := bmciHeader.bcHeight;
bmInfo.Header.biBitCount := bmciHeader.bcBitCount;
if bmciHeader.bcBitCount <= 8 then
for i:=0 to (1 shl bmciHeader.bcBitCount)-1 do
bmInfo.Colors[i] := PFColorA(@bmciColors[i])^;
end;
Result:=PDWord(Ptr(Integer(Data)+10))^;
end;
function PackedDIB(Bmp:TBMPReader):Pointer;
var
i: DWord;
begin
if Bmp.Bpp <= 8 then i := 40 + ((1 shl Bmp.Bpp) shl 2) else
if (((Bmp.Bpp = 16) or (Bmp.Bpp = 32)) and (Bmp.Compression =3 )) then i:=52 else i:=40;
GetMem(Result, Bmp.SizeImage + i);
Move(Bmp.Info, Result^,i);
Move(Bmp.Bits^, Ptr(DWord(Result)+i)^, Bmp.SizeImage);
end;
function Count1(Bmp:TBMPReader):Integer;
var
pb: PByte;
w,c,x,y: Integer;
begin
Result:=2;
pb:=Pointer(Bmp.Bits); c:=pb^;
if(c<>0)and(c<>255)then Exit;
w:=(Bmp.Width div 8)-1;
for y:=0 to Bmp.AbsHeight-1 do
begin
for x:=0 to w do
begin
if pb^<>c then Exit;
Inc(pb);
end;
Inc(pb,Bmp.Gap);
end;
Result:=1;
end;
function Count4(Bmp:TBMPReader):Integer;
var
I,J: Integer;
pb,pc: PByte;
x,y,w: Integer;
Check: array[0..15]of Byte;
begin
Result:=0;
FillChar(Check,SizeOf(Check),0);
pb:=Pointer(Bmp.Bits);
w:=(Bmp.Width div 2)-1;
for y:=0 to Bmp.AbsHeight-1 do
begin
for x:=0 to w do
begin
pc:=@Check[pb^ shr 4];
if pc^=0 then
begin
Inc(Result);
pc^:=1;
end;
pc:=@Check[pb^ and 15];
if pc^=0 then
begin
Inc(Result);
pc^:=1;
end;
if Result=16 then Exit;
Inc(pb);
end;
Inc(pb,Bmp.Gap);
end;
x:=0; y:=0; w:=w*Bmp.AbsHeight-1;
for I := 0 to Result - 1 do
begin
while check[x]=0 do inc(x);
if x<>y then
begin
Bmp.Colors[y]:=Bmp.Colors[x];
pb:=Pointer(Bmp.Bits);
for J := 0 to w do // Iterate
begin
if x=(pb^ shr 4) then pb^:=(pb^ and 15) or (y shl 4);
if x=(pb^ and 15) then pb^:=(pb^ and $f0) or y;
inc(pb);
end; // for J
end;
inc(x); inc(y);
end; // for I
end;
function Count8(Bmp:TBMPReader):Integer;
var
x,y: Integer;
I,J : Integer;
pb: PByte;
Check: array[Byte]of Byte;
begin
Result:=0;
FillChar(Check,SizeOf(Check),0);
pb:=Pointer(Bmp.Bits);
for y:=0 to Bmp.AbsHeight-1 do
begin
for x:=0 to Bmp.Width-1 do
begin
// pc:=@Check[pb^];
if Check[pb^] = 0 then
begin
Inc(Result);
Check[pb^] := 1;
end;
if Result=256 then Exit;
Inc(pb);
end;
Inc(pb,Bmp.Gap);
end;
if (Result = 1) and (Check[0] = 0) and (Check[1] = 1) then
begin
Result := 2;
exit; // bug monobrush
end;
j := 0;
for I := 0 to 255 do
if Check[i] = 0 then inc(J) else Check[i] := J;
if J > 0 then
begin
pb:=Pointer(Bmp.Bits);
for y:=0 to Bmp.AbsHeight-1 do
begin
for x:=0 to Bmp.Width-1 do
begin
if Check[pb^] > 0 then pb^ := pb^ - Check[pb^];
Inc(pb);
end;
Inc(pb,Bmp.Gap);
end;
for I := 1 to 255 do
if Check[i] > 0 then
Bmp.Colors[i - Check[i]] := Bmp.Colors[i];
end;
end;
function Count16(Bmp:TBMPReader):Integer;
var
pw: PWord;
pc: PByte;
x,y: Integer;
Check: array[Word]of Byte;
begin
Result:=0;
FillChar(Check,SizeOf(Check),0);
pw:=Pointer(Bmp.Bits);
for y:=0 to Bmp.AbsHeight-1 do
begin
for x:=0 to Bmp.Width-1 do
begin
pc:=@Check[pw^];
if pc^=0 then
begin
Inc(Result);
pc^:=1;
end;
Inc(pw);
end;
pw:=Ptr(Integer(pw)+Bmp.Gap);
end;
end;
function Count24(Bmp:TBMPReader):Integer;
type
PCheck =^TCheck;
TCheck = array[Byte,Byte,0..31]of Byte;
var
pb: PByte;
pc: PFColor;
Check: PCheck;
x,y,c: Integer;
begin
Result:=0;
New(Check);
FillChar(Check^,SizeOf(TCheck),0);
pc:=Pointer(Bmp.Bits);
for y:=0 to Bmp.AbsHeight-1 do
begin
for x:=0 to Bmp.Width-1 do
begin
pb:=@Check[pc.r,pc.g,pc.b shr 3];
c:=1 shl(pc.b and 7);
if(c and pb^)=0 then
begin
Inc(Result);
pb^:=pb^ or c;
end;
Inc(pc);
end;
pc:=Ptr(Integer(pc)+Bmp.Gap);
end;
Dispose(Check);
end;
function Count32(Bmp:TBMPReader):Integer;
type
PCheck =^TCheck;
TCheck = array[Byte,Byte,0..31]of Byte;
var
pb: PByte;
pc: PFColorA;
i,c: Integer;
Check: PCheck;
begin
Result:=0;
New(Check);
FillChar(Check^,SizeOf(TCheck),0);
pc:=Pointer(Bmp.Bits);
for i:=0 to (Bmp.SizeImage shr 2)-1 do
begin
pb:=@Check[pc.r,pc.g,pc.b shr 3];
c:=1 shl(pc.b and 7);
if(c and pb^)=0 then
begin
Inc(Result);
pb^:=pb^ or c;
end;
Inc(pc);
end;
Dispose(Check);
end;
function CountColors(Bmp:TBMPReader):DWord;
begin
case Bmp.Bpp of
1: Result:=Count1(Bmp);
4: Result:=Count4(Bmp);
8: Result:=Count8(Bmp);
16: Result:=Count16(Bmp);
24: Result:=Count24(Bmp);
32: Result:=Count32(Bmp);
else Result:=0;
end;
end;
procedure IntToMask(Bpr,Bpg,Bpb:DWord;var RMsk,GMsk,BMsk:DWord);
begin
BMsk:=(1 shl Bpb)-1;
GMsk:=((1 shl(Bpb+Bpg))-1)and not BMsk;
if(Bpr+Bpg+Bpb)=32 then RMsk:=$FFFFFFFF else RMsk:=(1 shl(Bpr+Bpb+Bpg))-1;
RMsk:=RMsk and not(BMsk or GMsk);
end;
procedure MaskToInt(RMsk,GMsk,BMsk:DWord;var Bpr,Bpg,Bpb:DWord);
function CountBits(i:DWord):DWord;
asm
bsr edx,eax
bsf ecx,eax
sub edx,ecx
inc edx
mov eax,edx
end;
begin
Bpb:=CountBits(BMsk);
Bpg:=CountBits(GMsk);
Bpr:=CountBits(RMsk);
end;
function UnpackColorTable(Table:TFPackedColorTable):TFColorTable;
var
i: Integer;
begin
for i:=0 to 255 do
Result[i].c:=Table[i];
end;
function PackColorTable(Table:TFColorTable):TFPackedColorTable;
var
i: Integer;
begin
for i:=0 to 255 do
Result[i]:=Table[i].c;
end;
function FRGB(r,g,b:Byte):TFColor;
begin
Result.b:=b;
Result.g:=g;
Result.r:=r;
end;
function FRGBA(r,g,b,a:Byte):TFColorA;
begin
Result.b:=b;
Result.g:=g;
Result.r:=r;
Result.a:=a;
end;
function ColorToInt(c:TFColor):DWord;
begin
Result:=c.b shl 16 or c.g shl 8 or c.r;
end;
function ColorToIntA(c:TFColorA):DWord;
begin
Result:=c.b shl 24 or c.g shl 16 or c.r shl 8 or c.a;
end;
function IntToColor(i:DWord):TFColor;
begin
Result.b:=i shr 16;
Result.g:=i shr 8;
Result.r:=i;
end;
function IntToColorA(i:DWord):TFColorA;
begin
Result.a:=i shr 24;
Result.b:=i shr 16;
Result.g:=i shr 8;
Result.r:=i;
end;
function Scale8(i,n:Integer):Integer;
begin // Result:=(i*255)div([1 shl n]-1);
case n of
1: if Boolean(i) then Result:=255 else Result:=0;
2: Result:=(i shl 6)or(i shl 4)or(i shl 2)or i;
3: Result:=(i shl 5)or(i shl 2)or(i shr 1);
4: Result:=(i shl 4)or i;
5: Result:=(i shl 3)or(i shr 2);
6: Result:=(i shl 2)or(i shr 4);
7: Result:=(i shl 1)or(i shr 6);
else Result:=i;
end;
end;
function Get16Bpg:Byte;
var
c: DWord;
hBM: HBITMAP;
sDC,bDC: Windows.HDC;
begin
sDC:=GetDC(0);
bDC:=CreateCompatibleDC(sDC);
hBM:=CreateCompatibleBitmap(sDC,1,1);
SelectObject(bDC,hBM);
SetPixel(bDC,0,0,RGB(0,100,0));
c:=GetPixel(bDC,0,0);
DeleteDC(bDC);
DeleteObject(hBM);
ReleaseDC(0,sDC);
if GetGValue(c)>=100 then Result:=6 else Result:=5;
end;
initialization
finalization
end.
|
unit E_MemStream;
//------------------------------------------------------------------------------
// Модуль реализует поток памяти по принципу FIFO,
// но с возможностью повторного чтения
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils,
T_Common, E_Utils;
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! поток памяти по принципу FIFO
//------------------------------------------------------------------------------
TMyMemStream = class
private
//! указатель на буфер памяти
FData: PUInt8;
//! указатель на текую позицию чтения
FPosition: PUInt8;
//! объём данных в буфере
FSize: Integer;
//! объём буфера
FCapacity: Integer;
//! проперть
function Get_Remaining(): Integer;
public
//!
constructor Create();
//!
destructor Destroy(); override;
//! прочесть байт
function ReadByte(
var RWhere: UInt8
): Boolean;
//! прочесть слово = 2 байта
//! AReverse = true - развернуть порядок байт
function ReadWord(
const AReverse: Boolean;
var RWhere: UInt16
): Boolean;
//! прочесть двойное слово = 4 байта
//! AReverse = true - развернуть порядок байт
function ReadDWord(
const AReverse: Boolean;
var RWhere: UInt32
): Boolean;
//! прочесть четверное слово = 8 байт
//! AReverse = true - развернуть порядок байт
function ReadQWord(
const AReverse: Boolean;
var RWhere: UInt64
): Boolean;
//! считать данные
function ReadData(
const ANumber: Integer;
const RWhere: Pointer
): Boolean;
//! пропустить данные
function SkipData(
const ANumber: Integer
): Boolean;
//! добавить данные
procedure AddData(
const ANumber: Integer;
const AFrom: Pointer
);
//! полностью очистить буфер
procedure ClearAll();
//! очистить буфер от данных, прочитанных ранее через ReadXXX
procedure ClearReaded();
//! вернуть указатель буфера на момент последнего ClearReaded
//! т.е. отменить предыдущие операции чтения
procedure UnreadReaded();
//! объём непрочитанных данных
property Remaining: Integer read Get_Remaining;
end;
//------------------------------------------------------------------------------
implementation
const
//------------------------------------------------------------------------------
//! переменные управление буфером данных
//! гранулярность выделения памяти = 256 байт
//------------------------------------------------------------------------------
CMemPage = Integer( $00000100 );
CMemGran = Integer( $FFFFFF00 );
CMemSmoother = Integer( $000000FF );
//------------------------------------------------------------------------------
// TMyMemStream
//------------------------------------------------------------------------------
constructor TMyMemStream.Create();
begin
inherited Create();
//
ClearAll(); // тут FData = nil
end;
destructor TMyMemStream.Destroy();
begin
if Assigned( FData ) then // на всякий пожарный
FreeMem( FData );
//
inherited Destroy();
end;
function TMyMemStream.ReadByte(
var RWhere: UInt8
): Boolean;
begin
if ( FPosition - FData > NativeInt( FSize - 1 ) ) then Exit( False );
RWhere := PUInt8( FPosition )^;
FPosition := FPosition + 1;
Result := True;
end;
function TMyMemStream.ReadWord(
const AReverse: Boolean;
var RWhere: UInt16
): Boolean;
begin
if ( FPosition - FData > NativeInt( FSize - 2 ) ) then Exit( False );
if AReverse then
RWhere := Swap16( PUInt16( FPosition )^ )
else
RWhere := PUInt16( FPosition )^;
FPosition := FPosition + 2;
Result := True;
end;
function TMyMemStream.ReadDWord(
const AReverse: Boolean;
var RWhere: UInt32
): Boolean;
begin
if ( FPosition - FData > NativeInt( FSize - 4 ) ) then Exit( False );
if AReverse then
RWhere := Swap32( PUInt32( FPosition )^ )
else
RWhere := PUInt32( FPosition )^;
FPosition := FPosition + 4;
Result := True;
end;
function TMyMemStream.ReadQWord(
const AReverse: Boolean;
var RWhere: UInt64
): Boolean;
begin
if ( FPosition - FData > NativeInt( FSize - 8 ) ) then Exit( False );
if AReverse then
RWhere := Swap64( PUInt64( FPosition )^ )
else
RWhere := PUInt64( FPosition )^;
FPosition := FPosition + 8;
Result := True;
end;
function TMyMemStream.ReadData(
const ANumber: Integer;
const RWhere: Pointer
): Boolean;
begin
if ( FPosition - FData > NativeInt( FSize - ANumber ) ) then Exit( False );
Move( FPosition^, RWhere^, ANumber );
FPosition := FPosition + ANumber;
Result := True;
end;
function TMyMemStream.SkipData(
const ANumber: Integer
): Boolean;
begin
if ( FPosition - FData > NativeInt( FSize - ANumber ) ) then Exit( False );
FPosition := FPosition + ANumber;
Result := True;
end;
procedure TMyMemStream.AddData(
const ANumber: Integer;
const AFrom: Pointer
);
var
//! новый объём данных в буфере
NewSize: Integer;
//! новый объём буфера
NewSizeGran: Integer;
//! позиция чтения - числом
Shift: NativeInt;
//! позиция добавления новых данных
AddPos: PUInt8;
//------------------------------------------------------------------------------
begin
// новый объём данных
NewSize := FSize + ANumber;
// если не хватает текущего буфера
if ( FCapacity < NewSize ) then
begin // то выделим новый и перезапишем
// сохраним позицию чтения как число
Shift := FPosition - FData;
// новый полный объём буфера
NewSizeGran := ( NewSize + CMemSmoother ) and CMemGran;
// выделяем новый размер штатными средствами - сохраняем старые данные
ReallocMem( FData, NewSizeGran );
// новый объём буфера
FCapacity := NewSizeGran;
// новая позиция
FPosition := FData + Shift;
end;
// указатель позиции добавления
AddPos := FData + FSize;
// добавляем новое
Move( AFrom^, AddPos^, ANumber );
// устанавливаем новый объём данных
FSize := NewSize;
end;
procedure TMyMemStream.ClearAll();
begin
if Assigned( FData ) then
begin
FreeMem( FData );
FData := nil;
end;
GetMem( FData, CMemPage );
FPosition := FData;
FSize := 0;
FCapacity := CMemPage;
end;
procedure TMyMemStream.ClearReaded();
var
//! новый буфер
NewBuffer: PUInt8;
//! новый объём данных в буфере
NewSize: Integer;
//! новый объём буфера
NewSizeGran: Integer;
//------------------------------------------------------------------------------
begin
if ( FPosition = FData ) then Exit; // ничего не прочитано
if ( FPosition - FData = NativeInt( FSize ) ) then
ClearAll() // всё прочитано
else
begin // частично прочитано
// новый объём данных
NewSize := Get_Remaining();
// новый полный объём буфера
NewSizeGran := ( NewSize + CMemSmoother ) and CMemGran;
// выделяем память
GetMem( NewBuffer, NewSizeGran );
// перемещаем остаток
Move( FPosition^, NewBuffer^, NewSize );
// освобождаем старую
FreeMem( FData );
// новые параметры
FData := NewBuffer;
FPosition := NewBuffer; // теперь с нуля
FSize := NewSize;
FCapacity := NewSizeGran;
end;
end;
procedure TMyMemStream.UnreadReaded();
begin
FPosition := FData;
end;
function TMyMemStream.Get_Remaining(): Integer;
begin
Result := FSize - Integer( FPosition - FData );
end;
//------------------------------------------------------------------------------
initialization
IsMultiThread := True;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
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 Kitto.Ext.InputPIN;
{$I Kitto.Defines.inc}
interface
uses
Ext, ExtForm,
Kitto.Ext.Base;
type
TKExtInputPINWindow = class(TKExtWindowControllerBase)
private
FSecretCode: string;
FTokenField: TExtFormTextField;
FTokenFieldRules: TExtFormLabel;
FConfirmButton: TKExtButton;
FStatusBar: TKExtStatusBar;
FFormPanel: TExtFormFormPanel;
strict protected
procedure DoDisplay; override;
protected
procedure InitDefaults; override;
public
/// <summary>Returns the display label to use by default when not specified
/// at the view or other level. Called through RTTI.</summary>
class function GetDefaultDisplayLabel: string;
/// <summary>Returns the image name to use by default when not specified at
/// the view or other level. Called through RTTI.</summary>
class function GetDefaultImageName: string;
published
procedure DoCheckPIN;
end;
implementation
uses
SysUtils, StrUtils, Math,
ExtPascalUtils, ExtPascal,
EF.Classes, EF.Localization, EF.Tree, EF.StrUtils,
Kitto.Types, Kitto.Config,
Kitto.Ext.Controller, Kitto.Ext.Session;
//GoogleOTP, Base32U;
{ TKExtInputPINWindow }
procedure TKExtInputPINWindow.DoCheckPIN;
var
LTokenValue: integer;
begin
if not TryStrToInt(Session.Query['PIN'],LTokenValue) then
begin
FStatusBar.SetErrorStatus(_('PIN must be a 6-digit number.'));
FTokenField.Focus(False, 500);
end
(*
else if not ValidateTOPT(FSecretCode,LTokenValue) then
begin
FStatusBar.SetErrorStatus(_('6-digit token is wrong.'));
FTokenField.Focus(False, 500);
end
*)
else
begin
Close;
Session.Config.Authenticator.MustInputPIN := False;
Session.UpdateObserver(Self,'LoggedIn');
end;
end;
procedure TKExtInputPINWindow.DoDisplay;
var
LEditWidth: Integer;
begin
Title := Config.GetString('DisplayLabel', GetDefaultDisplayLabel);
Width := Config.GetInteger('FormPanel/Width', 300);
Height := Config.GetInteger('FormPanel/Height', 120);
LEditWidth := Config.GetInteger('FormPanel/EditWidth', 120);
FTokenField.Width := LEditWidth;
Self.Closable := Config.GetBoolean('AllowClose', True);
inherited;
end;
class function TKExtInputPINWindow.GetDefaultDisplayLabel: string;
begin
Result := _('Input PIN');
end;
class function TKExtInputPINWindow.GetDefaultImageName: string;
begin
Result := 'password';
end;
procedure TKExtInputPINWindow.InitDefaults;
var
LTokenRules: string;
function ReplaceMacros(const ACode: string): string;
begin
Result := ReplaceStr(ACode, '%BUTTON%', FConfirmButton.JSName);
Result := ReplaceStr(Result, '%TOKEN%', FTokenField.JSName);
Result := ReplaceStr(Result, '%STATUSBAR%', FStatusBar.JSName);
Result := ReplaceStr(Result, '%CAPS_ON%', _('Caps On'));
end;
function GetEnableButtonJS: string;
begin
Result := ReplaceMacros(
'%BUTTON%.setDisabled(%TOKEN%.getValue() == "" ' +
'|| !(%TOKEN%.getValue().length == 6));')
end;
function GetCheckCapsLockJS: string;
begin
Result := ReplaceMacros(
'if (event.keyCode !== 13 && event.getModifierState("CapsLock")) ' +
'{%STATUSBAR%.setText(''%CAPS_ON%''); %STATUSBAR%.setIcon('''');} ' +
'else {%STATUSBAR%.setText('''');}');
end;
function GetSubmitJS: string;
begin
Result := ReplaceMacros(
'if (e.getKey() == 13 && !(%TOKEN%.getValue() == "") ' +
'&& %TOKEN%.length == 6) %BUTTON%.handler.call(%BUTTON%.scope, %BUTTON%);');
end;
begin
inherited;
FSecretCode := Session.Config.Authenticator.SecretCode;
Modal := True;
Maximized := Session.IsMobileBrowser;
Border := not Maximized;
Closable := True;
Resizable := False;
FStatusBar := TKExtStatusBar.Create(Self);
FStatusBar.DefaultText := '';
FStatusBar.BusyText := _('Processing PIN...');
FFormPanel := TExtFormFormPanel.CreateAndAddTo(Items);
FFormPanel.Region := rgCenter;
FFormPanel.LabelWidth := Config.GetInteger('FormPanel/LabelWidth', 150);
FFormPanel.LabelAlign := laRight;
FFormPanel.Border := False;
FFormPanel.BodyStyle := SetPaddings(5, 5);
FFormPanel.Frame := False;
FFormPanel.MonitorValid := True;
FFormPanel.Bbar := FStatusBar;
FConfirmButton := TKExtButton.CreateAndAddTo(FStatusBar.Items);
FConfirmButton.SetIconAndScale('password', 'medium');
FConfirmButton.Text := _('Check PIN');
FTokenField := TExtFormTextField.CreateAndAddTo(FFormPanel.Items);
FTokenField.Name := 'PIN';
//FTokenField.Value := ...
FTokenField.FieldLabel := _('PIN');
//FTokenField.InputType := itPassword;
FTokenField.AllowBlank := False;
FTokenField.EnableKeyEvents := True;
LTokenRules := _('Input Authenticator''s 6-digit PIN');
if LTokenRules <> '' then
begin
FTokenFieldRules := TExtFormLabel.CreateAndAddTo(FFormPanel.Items);
FTokenFieldRules.Text := LTokenRules;
FTokenFieldRules.Width := CharsToPixels(Length(FTokenFieldRules.Text));
Height := Height + 30;
end;
FTokenField.On('keyup', JSFunction(GetEnableButtonJS));
FTokenField.On('keydown', JSFunction(GetCheckCapsLockJS));
FTokenField.On('specialkey', JSFunction('field, e', GetSubmitJS));
FConfirmButton.Handler := Ajax(DoCheckPIN, ['Dummy', FStatusBar.ShowBusy,
'PIN', FTokenField.GetValue]);
FConfirmButton.Disabled := True;
FTokenField.Focus(False, 500);
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('InputPIN', TKExtInputPINWindow);
finalization
TKExtControllerRegistry.Instance.UnregisterClass('InputPIN');
end.
|
unit Caixa;
interface
uses
DBXJSONReflect, RTTI, DBXPlatform, Generics.Collections, ItemPedidoVenda, Cliente;
type
TDoubleInterceptor = class(TJSONInterceptor)
public
function StringConverter(Data: TObject; Field: string): string; override;
procedure StringReverter(Data: TObject; Field: string; Arg: string); override;
end;
TCaixa = class
private
FId: integer;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FData: TDateTime;
FFechado: Boolean;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FValorAbertura: Currency;
public
property Id: integer read FId write FId;
property Data: TDateTime read FData write FData;
property Fechado: Boolean read FFechado write FFechado;
property ValorAbertura: Currency read FValorAbertura write FValorAbertura;
end;
implementation
{ TDoubleInterceptor }
function TDoubleInterceptor.StringConverter(Data: TObject; Field: string): string;
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := LRttiContext.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<Double>;
Result := TDBXPlatform.JsonFloat(LValue);
end;
procedure TDoubleInterceptor.StringReverter(Data: TObject; Field, Arg: string);
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := TDBXPlatform.JsonToFloat(Arg);
LRttiContext.GetType(Data.ClassType).GetField(Field).SetValue(Data, TValue.From<Double>(LValue));
end;
end.
|
unit uSwiper;
{$mode objfpc}{$H+}
{$modeswitch externalclass}
interface
uses
Classes, SysUtils, Types, JS, Web;
(* ╔═══════════════════════════════════════════════════════════════════════╗
║ JSwiper ║
╚═══════════════════════════════════════════════════════════════════════╝ *)
type
JSwiper = class external name 'Swiper'
constructor New(targetRef: String); overload;
function _slideNext: JSwiper;
function swipeNext: JSwiper;
function _slideTo(form: integer): JSwiper;
function swipeTo(form: integer): JSwiper; overload;
function swipeTo(form: integer; speed: Integer): JSwiper; overload;
function swipeTo(form: integer; speed: Integer; callbackFn: TProcedure): JSwiper; overload;
end;
end.
|
(*
* FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*)
unit uColor16bits;
interface
uses
LCLIntf, LCLType;
const
FPG16_CDIV = 3;
type
TRGBTriple = record
R, G, B : Byte;
end;
TRGBLine = Array[Word] of TRGBTriple;
pRGBLine = ^TRGBLine;
procedure Calculate_BGR( byte0, byte1 : Byte; var red, green, blue : Byte );
procedure Calculate_RGB( byte0, byte1 : Byte; var red, green, blue : Byte );
procedure Calculate_RGB16( byte0, byte1 : Byte; var red, green, blue : Byte );
procedure set_BGR16( var byte0, byte1 : Byte; red, green, blue : Byte );
procedure set_RGB16( var byte0, byte1 : Byte; red, green, blue : Byte );
procedure truncate_BGR2416( var rgb: TRGBTriple; FPG_type: LongInt );
procedure truncate_BGR3216( var Red, Green, Blue : byte ; FPG_type: LongInt );
function BGR16_RGB16( in2bytes : Word ) : Word;
implementation
// Calcula las componentes RGB almacenadas en 2 bytes como BGR
procedure Calculate_BGR( byte0, byte1 : Byte; var red, green, blue : Byte );
begin
blue := byte0 and $F8; // me quedo 5 bits 11111000
green := (byte0 shl 5) or ( (byte1 and $E0) shr 3); // me quedo 3 bits de byte0 y 3 bits de byte 1 (11100000)
red := byte1 shl 3; // me quedo 5 bits
end;
// Calcula las componentes RGB almacenadas en 2 bytes como RGB
procedure Calculate_RGB( byte0, byte1 : Byte; var red, green, blue : Byte );
begin
red := byte0 and $F8; // me quedo 5 bits 11111000
green := (byte0 shl 5) or ( (byte1 and $E0) shr 3); // me quedo 3 bits de byte0 y 3 bits de byte 1 (11100000)
blue := byte1 shl 3; // me quedo 5 bits
end;
procedure Calculate_RGB16( byte0, byte1 : Byte; var red, green, blue : Byte );
begin
Calculate_RGB(byte0,byte1,red,green,blue);
red := red shr 3;
green := green shr 2;
blue := blue shr 3;
end;
// Establece las componentes RGB almacenandolas en 2 bytes como BGR
procedure set_BGR16( var byte0, byte1 : Byte; red, green, blue : Byte );
begin
// F8 = 11111000
// 1C = 00011100
byte0 := (blue and $F8) or (green shr 5);
byte1 := ( (green and $1C) shl 3) or (red shr 3);
end;
// Establece las componentes RGB almacenandolas en 2 bytes como RGB
procedure set_RGB16( var byte0, byte1 : Byte; red, green, blue : Byte );
begin
// F8 = 11111000
// 1C = 00011100
byte0 := (red and $F8) or (green shr 5);
byte1 := ( (green and $1C) shl 3) or (blue shr 3);
end;
// Establece las componentes RGB almacenandolas en 2 bytes como BGR
procedure truncate_BGR2416( var rgb: TRGBTriple; FPG_type: LongInt );
var
R, G, B : Byte;
begin
R := rgb.R;
G := rgb.G;
B := rgb.B;
rgb.R := rgb.R shr 3;
rgb.G := rgb.G shr 2;
rgb.B := rgb.B shr 3;
rgb.R := rgb.R shl 3;
rgb.G := rgb.G shl 2;
rgb.B := rgb.B shl 3;
// Si la conversión va ha procudir un color transparente lo corregimos
if( (R <> 0) or (G <> 0) or (B <> 0) or (FPG_type = FPG16_CDIV) ) then
if ( (rgb.R = 0) and (rgb.G = 0) and (rgb.B = 0) ) then
rgb.G := 4;
// Si la conversión va ha procudir un color transparente lo corregimos
if( (R < 255) or (G <> 0) or (B < 255) or (FPG_type <> FPG16_CDIV) ) then
if ( (rgb.R = 248) and (rgb.G = 0) and (rgb.B = 248) ) then
rgb.G := 4;
end;
procedure truncate_BGR3216( var Red, Green, Blue : byte ; FPG_type: LongInt );
var
R, G, B : Byte;
begin
R := Red;
G := Green;
B := Blue;
Red := ( Red shr 3 ) shl 3;
Green := ( Green shr 2) shl 2;
Blue := ( Blue shr 3) shl 3;
// Si la conversión va ha procudir un color transparente lo corregimos
if( (R <> 0) or (G <> 0) or (B <> 0) or (FPG_type = FPG16_CDIV) ) then
if ( (Red = 0) and (Green = 0) and (Blue = 0) ) then
Green := 4;
// Si la conversión va ha procudir un color transparente lo corregimos
if( (R < 255) or (G <> 0) or (B < 255) or (FPG_type <> FPG16_CDIV) ) then
if ( (Red = 248) and (Green = 0) and (Blue = 248) ) then
Green := 4;
end;
function BGR16_RGB16( in2bytes : Word ) : Word;
var
byte0, byte1 : Byte;
R16, G16, B16 : Byte;
begin
byte1 := in2bytes shr 8;
byte0 := 255 and in2bytes;
Calculate_BGR(byte0, byte1, R16, G16, B16);
set_RGB16(byte0, byte1, R16, G16, B16);
result := (byte1 shl 8) + byte0;
end;
end.
|
unit DSA.Graph.PrimMST;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Tree.IndexHeap,
DSA.Interfaces.DataStructure,
DSA.Interfaces.Comparer,
DSA.Graph.Edge,
DSA.List_Stack_Queue.ArrayList;
type
generic TPrimMst<T> = class
private
type
TArr_bool = specialize TArray<boolean>;
TEdge_T = specialize TEdge<T>;
TMinIndexHeap = specialize TIndexHeap<T>;
TList_Edge = specialize TArrayList<TEdge_T>;
TArrEdge = specialize TArray<TEdge_T>;
TWeightGraph_T = specialize TWeightGraph<T>;
TCmp_T = specialize TComparer<T>;
var
__g: TWeightGraph_T;
__cmp: TCmp_T;
__ipq: TMinIndexHeap; // 最小索引堆, 算法辅助数据结构
__marked: TArr_bool; // 标记数组, 在算法运行过程中标记节点i是否被访问
__mstList: TList_Edge; // 最小生成树所包含的所有边
__mstWeight: T; // 最小生成树的权值
__edgeTo: TArrEdge; // 访问的点所对应的边, 算法辅助数据结构
/// <summary> 访问节点v </summary>
procedure __visit(v: integer);
public
constructor Create(g: TWeightGraph_T);
destructor Destroy; override;
/// <summary> 返回最小生成树的所有边 </summary>
function MstEdges: TArrEdge;
/// <summary> 返回最小生成树的权值 </summary>
function Weight: T;
end;
procedure Main;
implementation
uses
DSA.Graph.DenseWeightedGraph,
DSA.Graph.SparseWeightedGraph,
DSA.Utils;
type
TDenseWeightedGraph_dbl = specialize TDenseWeightedGraph<double>;
TSparseWeightedGraph_dbl = specialize TSparseWeightedGraph<double>;
TWeightGraph_dbl = specialize TWeightGraph<double>;
TReadGraphWeight_dbl = specialize TReadGraphWeight<double>;
TPrimMST_dbl = specialize TPrimMST<double>;
procedure Main;
var
fileName: string;
v, i: integer;
g: TWeightGraph_dbl;
PrimMst: TPrimMST_dbl;
mst: TPrimMST_dbl.TArrEdge;
begin
fileName := WEIGHT_GRAPH_FILE_NAME_1;
v := 250;
begin
g := TDenseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + FileName);
// Test Lazy Prim MST
WriteLn('Test Dense Weighted Graph Prim MST:');
PrimMst := TPrimMST_dbl.Create(g);
mst := PrimMst.MstEdges;
for i := 0 to High(mst) do
WriteLn(mst[i].ToString);
WriteLn('The MST weight is: ', PrimMst.Weight.ToString);
end;
TDSAUtils.DrawLine;
begin
g := TSparseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + fileName);
// Test Lazy Prim MST
WriteLn('Test Sparse Weighted Graph Prim MST:');
PrimMst := TPrimMST_dbl.Create(g);
mst := PrimMst.MstEdges;
for i := 0 to high(mst) do
WriteLn(mst[i].ToString);
WriteLn('The MST weight is: ', PrimMst.Weight.ToString);
end;
end;
{ TPrimMst }
constructor TPrimMst.Create(g: TWeightGraph_T);
var
i: integer;
v: longint;
begin
__g := g;
__mstList := TList_Edge.Create;
__ipq := TMinIndexHeap.Create(g.Vertex);
__cmp := TCmp_T.Default;
// 算法初始化
SetLength(__edgeTo, g.Vertex);
SetLength(__marked, g.Vertex);
for i := 0 to Pred(g.Vertex) do
begin
__marked[i] := False;
__edgeTo[i] := nil;
end;
// Prim
__visit(0);
while not __ipq.IsEmpty do
begin
// 使用最小索引堆找出已经访问的边中权值最小的边
// 最小索引堆中存储的是点的索引, 通过点的索引找到相对应的边
v := __ipq.ExtractFirstIndex;
Assert(__edgeTo[v] <> nil);
__mstList.AddLast(__edgeTo[v]);
__visit(v);
end;
// 计算最小生成树的权值
__mstWeight := Default(T);
for i := 0 to __mstList.GetSize - 1 do
begin
__mstWeight += __mstList[i].Weight;
end;
end;
destructor TPrimMst.Destroy;
begin
FreeAndNil(__ipq);
FreeAndNil(__mstList);
FreeAndNil(__cmp);
inherited Destroy;
end;
function TPrimMst.MstEdges: TArrEdge;
begin
Result := __mstList.ToArray;
end;
function TPrimMst.Weight: T;
begin
Result := __mstWeight;
end;
procedure TPrimMst.__visit(v: integer);
var
e: TEdge_T;
w: integer;
begin
Assert(__marked[v] = False);
__marked[v] := True;
// 将和节点v相连接的未访问的另一端点, 和与之相连接的边, 放入最小索引堆中
for e in __g.AdjIterator(v) do
begin
w := e.OtherVertex(v);
// 如果边的另一端点未被访问
if __marked[w] = False then
begin
// 如果从没有考虑过这个端点, 直接将这个端点和与之相连接的边加入索引堆
if __edgeTo[w] = nil then
begin
__edgeTo[w] := e;
__ipq.Insert(w, e.Weight);
end
// 如果曾经考虑这个端点, 但现在的边比之前考虑的边更短, 则进行替换
else if __cmp.Compare(e.Weight, __edgeTo[w].Weight) < 0 then
begin
__edgeTo[w] := e;
__ipq.Change(w, e.Weight);
end;
end;
end;
end;
end.
|
program Cradle;
{Constants}
const TAB = ^I;
{Variables}
var Look : char;
{Read new characters from input stream}
procedure Getchar;
begin
Read(Look);
end;
{Report error}
procedure Error(s : string);
begin
WriteLn;
WriteLn(^G, 'Error: ', s, '.');
end;
{Report error and halt}
procedure Abort(s : string);
begin
Error(s);
Halt;
end;
{Report what was expected}
procedure Expected(s : string);
begin
Abort(s + ' expected');
end;
{Match an input character}
procedure Match(x : char);
begin
if Look = x then GetChar
else Expected ('''' + x + '''');
end;
{Recognize alpha character}
function IsAlpha(c : char): boolean;
begin
IsAlpha := upcase(c) in ['A'..'Z'];
end;
{Recognize decimal digit}
function IsDigit(c : char): boolean;
begin
IsDigit := c in ['0'..'9'];
end;
{Get an identifier}
function GetName: char;
begin
if not IsAlpha(Look) then Expected('Name');
GetName := UpCase(Look);
GetChar;
end;
{Get a number}
function GetNum: char;
begin
if not IsDigit(Look) then Expected('Integer');
GetNum := Look;
GetChar;
end;
{Output string w/ tab}
procedure Emit(s : string);
begin
Write(TAB, s);
end;
{Output string w/ tab and CRLF}
procedure EmitLn(s : string);
begin
Emit(s);
WriteLn;
end;
procedure Expression; Forward;
{Parse and translate a math FACTOR}
procedure Factor;
begin
if Look = '(' then begin
Match('(');
Expression;
Match(')');
end
else if Look = '-' then begin
GetChar;
EmitLn('movq $' + GetNum + ', %r12');
EmitLn('neg %r12');
end
else
EmitLn('movq $' + GetNum + ', %r12');
end;
{Recognize and translate *}
procedure Multiply;
begin
Match('*');
Factor;
EmitLn('popq %r13');
EmitLn('imulq %r13, %r12');
end;
{Recognize and translate /}
procedure Divide;
begin
Match('/');
Factor;
EmitLn('popq %rax');
EmitLn('cqto');
EmitLn('idivq %r12');
end;
{Parse and translate a mult. term}
procedure Term;
begin
Factor;
while Look in ['*', '/'] do begin
EmitLn('pushq %r12');
case Look of
'*' : Multiply;
'/' : Divide;
else Expected('mult. operation');
end;
end;
end;
{Recognize and translate +}
procedure Add;
begin
Match('+');
Term;
EmitLn('popq %r13');
EmitLn('addq %r13, %r12');
end;
{Recognize and translate -}
procedure Subtract;
begin
Match('-');
Term;
EmitLn('popq %r13');
EmitLn('subq %r13, %r12');
EmitLn('neg %r12');
end;
{Parse + translate expression}
procedure Expression;
begin
Term;
while Look in ['+', '-'] do begin
EmitLn('pushq %r12');
case Look of
'+' : Add;
'-' : Subtract;
else Expected('add operation');
end;
end;
end;
{Init}
procedure Init;
begin
getChar;
end;
{MAIN}
begin
Init;
Expression;
end.
|
// -------------------------------------------------------------
// Dadas duas matrizes A e B, programa calcula C = A + B. :~
// -------------------------------------------------------------
Program ExemploPzim ;
Var A,B,C : array [ 1..2 , 1..4 ] of integer;
i,j : integer;
Begin
// Leitura da matriz A
For i:= 1 to 2 do
For j:= 1 to 4 do
Begin
write('Entre com o valor A[',i, ',',j, '] : ');
readln(A[i][j]);
End;
// Leitura da matriz B
For i:= 1 to 2 do
For j:= 1 to 4 do
Begin
write('Entre com o valor B[',i, ',',j, '] : ');
readln(B[i,j]);
End;
// Calcula matriz C = A + B
For i:= 1 to 2 do
For j:= 1 to 4 do
C[i,j] := A[i,j] + B[i,j];
// Impressao das matrizes
writeln('Matriz A : ');
For i:= 1 to 2 do
writeln(A[i,1]:4, A[i,2]:4, A[i,3]:4, A[i,4]:4);
writeln('Matriz B : ');
For i:= 1 to 2 do
writeln(B[i,1]:4, B[i,2]:4, B[i,3]:4, B[i,4]:4);
writeln('Matriz C : ');
For i:= 1 to 2 do
writeln(C[i,1]:4, C[i,2]:4, C[i,3]:4, C[i,4]:4);
End.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Program: TNEMULVT.PAS
Description: Delphi component combining both TnCnx and EmulVT components.
Hence it does ANSI emulation using TCP/IP telnet protocol.
Author: François PIETTE
EMail: http://users.swing.be/francois.piette francois.piette@swing.be
http://www.rtfm.be/fpiette francois.piette@rtfm.be
francois.piette@pophost.eunet.be
Creation: May, 1996
Version: 2.11
Support: Use the mailing list twsocket@rtfm.be See website for details.
Legal issues: Copyright (C) 1996-2000 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@pophost.eunet.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
Updates:
Jul 22, 1997 Revised Connect method to be callable from FormCreate event
Adapted to Delphi 3
Sep 05, 1997 TnCnx made public, Minor change to method visibility
Added OnTermType and OnDataAvailable events.
Sep 23, 1997 V202. Added local echo support (incomplete because we should ask
the remote host not to echo characters. Will implement later)
Added TnEmultVTVersion
Sep 24, 1997 V2.03 Complete local echo support.
Sep 25, 1997 V2.04 Port to C++Builder
Feb 19, 1998 V2.05 Replaced private section by protected.
Added TriggerDataAvailable virtual function.
Dec 21, 1998 V2.06 Added fixes from Steve Endicott.
Mar 01, 1999 V2.07 Added conditional compile for BCB4. Thanks to James
Legg <jlegg@iname.com>.
Mar 14, 1999 V2.08 Added OnKeyDown event to allow key trapping.
Ignore any exception when sending fct keys.
Aug 15, 1999 V2.09 Move KeyPress procedure to public section for BCB4 compat.
Aug 20, 1999 V2.10 Added compile time options. Revised for BCB4.
Sep 25, 1999 V2.11 Corrected GetSelTextBuf so that lines are returned in
corrected order (they where returned in reverse order).
Thanks to Laurent Navarro <r2363c@email.sps.mot.com> for finding
this bug and fixing it.
Nov 2, 2001 Chinese Input Output support, KeyPress, DataAvailable
InvertRect Selection: MouseMove, MouseUp
URL Link support
Remove Xlat Support
Remove Inifiles, Optfrm
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit TNEMULVT;
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$IFNDEF VER80} { Not for Delphi 1 }
{$H+} { Use long strings }
{$J+} { Allow typed constant to be modified }
{$ENDIF}
{$IFDEF VER110} { C++ Builder V3.0 }
{$ObjExportAll On}
{$ENDIF}
{$IFDEF VER125} { C++ Builder V4.0 }
{$ObjExportAll On}
{$ENDIF}
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, EmulVT, TnCnx, WSocket;
const
TnEmultVTVersion = 211;
CopyRight: string = ' TTnEmulVT (c) 1996-2000 F. Piette V2.11 ';
type
TTnEmulVTDataAvailable = procedure(Sender: TObject;
Buffer: PChar;
var Len: integer) of object;
{fuse +}
TLinkClickEvent = procedure(Sender: TObject;
LinkStr: string) of object;
{fuse -}
TTnEmulVT = class(TEmulVT)
public
TnCnx: TTnCnx;
protected
FError: word;
FHostName: string;
FPort: string;
FTag: longint;
FUpperLock: boolean;
FLocalEcho: boolean;
FOnSessionClosed: TNotifyEvent;
FOnSessionConnected: TNotifyEvent;
FOnNamesClick: TNotifyEvent;
FOnSendLoc: TNotifyEvent;
FOnTermType: TNotifyEvent;
FOnLocalEcho: TNotifyEvent;
FOnDataAvailable: TTnEmulVTDataAvailable;
FAfterDataAvailable: TTnEmulVTDataAvailable;
FMouseDown: boolean;
FMouseTop: integer;
FMouseLeft: integer;
FFocusDrawn: boolean;
FFocusRect: TRect;
{fuse +}
FOnLinkMoveIn: TNotifyEvent;
FOnLinkMoveOut: TNotifyEvent;
FOnLinkClick: TLinkClickEvent;
FSystemEcho: boolean;
cnchar1: char;
cnsent: boolean;
FMouseEnter, FMouseLeave: TNotifyEvent;
{fuse -}
procedure TriggerDataAvailable(Buffer: PChar; Len: integer); virtual;
procedure TnCnxDataAvailable(Sender: TTnCnx; Buffer: PChar; Len: integer);
procedure TnCnxSessionClosed(Sender: TTnCnx; Erc: word);
procedure TnCnxSessionConnected(Sender: TTnCnx; Erc: word);
procedure TnCnxSendLoc(Sender: TObject);
procedure TnCnxTermType(Sender: TObject);
procedure TnCnxLocalEcho(Sender: TObject);
procedure Display(Msg: string);
procedure DoKeyBuffer(Buffer: PChar; Len: integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: integer); override;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure SetOnEndOfRecord(Value: TNotifyEvent);
function GetOnEndOfRecord: TNotifyEvent;
procedure SetLocation(Value: string);
function GetLocation: string;
procedure SetHostName(newValue: string);
procedure DrawFocusRectangle(Wnd: HWnd; Rect: TRect);
public
procedure RequestLocalEcho(newValue: boolean);
function GetLocalEcho: boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Connect;
procedure Disconnect;
function IsConnected: boolean;
function Send(Data: Pointer; Len: integer): integer;
function SendStr(Data: string): integer;
function GetSelTextBuf(Buffer: PChar; BufSize: integer): integer;
procedure KeyPress(var Key: char); override;
procedure UnSelect;
function SearchURL(nRow, nCol: integer; var chfrom, chto: integer;
var prefix: string): string;
procedure SetIndicatorRect(r: TRect);
procedure SetUrlRect(r: TRect);
procedure SetSingleCharPaint(bSCP: boolean);
procedure XtermMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer);
procedure XtermMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer);
property rURL: TRect read urlrect;
published
{fuse +}
property VScrollBar;
property NoScrollBar;
property ParseURL;
property CaretType;
property GraphicDraw;
property SelectMode;
property SystemEcho: boolean read FSystemEcho write FSystemEcho;
{fuse -}
property Error: word read FError write FError;
property HostName: string read FHostName write SetHostName;
property Port: string read FPort write FPort;
property Tag: longint read FTag write FTag;
property Location: string read GetLocation write SetLocation;
property UpperLock: boolean read FUpperLock write FUpperLock;
property LocalEcho: boolean read FLocalEcho write FLocalEcho;
property OnKeyDown;
property OnSessionClosed: TNotifyEvent read FOnSessionClosed write FOnSessionClosed;
property OnSessionConnected: TNotifyEvent
read FOnSessionConnected write FOnSessionConnected;
property OnEndOfRecord: TNotifyEvent read GetOnEndOfRecord write SetOnEndOfRecord;
property OnNamesClick: TNotifyEvent read FOnNamesClick write FOnNamesClick;
property OnSendLoc: TNotifyEvent read FOnSendLoc write FOnSendLoc;
property OnTermType: TNotifyEvent read FOnTermType write FOnTermType;
property OnLocalEcho: TNotifyEvent read FOnLocalEcho write FOnLocalEcho;
property OnDataAvailable: TTnEmulVTDataAvailable
read FOnDataAvailable write FOnDataAvailable;
property AfterDataAvailable: TTnEmulVTDataAvailable
read FAfterDataAvailable write FAfterDataAvailable;
{fuse +}
property OnFuncAction;
property OnLinkMoveIn: TNotifyEvent read FOnLinkMoveIn write FOnLinkMoveIn;
property OnLinkMoveOut: TNotifyEvent read FOnLinkMoveOut write FOnLinkMoveOut;
property OnMouseEnter: TNotifyEvent read FMouseEnter write FMouseEnter;
property OnMouseLeave: TNotifyEvent read FMouseLeave write FMouseLeave;
property OnLinkClick: TLinkClickEvent read FOnLinkClick write FOnLinkClick;
property TelnetCnx: TTnCnx read TnCnx write TnCnx;
{fuse -}
end;
procedure Register;
implementation
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure Register;
begin
RegisterComponents('FPiette', [TTnEmulVT]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TTnEmulVT.Create(AOwner: TComponent);
var
Rect: TRect;
begin
inherited Create(AOwner);
if TnCnxVersion < 203 then
raise Exception.Create('TTnEmulVT need TTnCnx version 2.03 or higher ' +
'Please download last release from ' +
'http://www.rtfm.be/fpiette/indexuk.htm');
TnCnx := TTnCnx.Create(Self);
TnCnx.OnDataAvailable := TnCnxDataAvailable;
TnCnx.OnSessionClosed := TnCnxSessionClosed;
TnCnx.OnSessionConnected := TnCnxSessionConnected;
TnCnx.OnSendLoc := TnCnxSendLoc;
TnCnx.OnTermType := TnCnxTermType;
TnCnx.OnLocalEcho := TnCnxLocalEcho;
FPort := 'telnet';
Rect.Top := -1;
SelectRect := Rect;
{fuse +}
AutoCr := False;
AutoLF := False;
LocalEcho := False;
MonoChrome := False;
UpperLock := False;
GraphicDraw := False;
CharZoom := 1.0;
LineZoom := 1.36;
LineHeight := 12;
{fuse -}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TTnEmulVT.Destroy;
begin
TnCnx.Free;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.SetHostName(newValue: string);
begin
FHostName := newValue;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTnEmulVT.GetLocalEcho: boolean;
begin
Result := TnCnx.LocalEcho;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.RequestLocalEcho(newValue: boolean);
begin
if newValue then
TnCnx.DontOption(TN_ECHO)
else
TnCnx.DoOption(TN_ECHO);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.SetLocation(Value: string);
begin
TnCnx.Location := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTnEmulVT.GetLocation: string;
begin
Result := TnCnx.Location;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.Display(Msg: string);
begin
if FSystemEcho then
begin
WriteStr(Msg);
Repaint;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.SetOnEndOfRecord(Value: TNotifyEvent);
begin
TnCnx.OnEndOfRecord := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTnEmulVT.GetOnEndOfRecord: TNotifyEvent;
begin
Result := TnCnx.OnEndOfRecord;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.TnCnxSendLoc(Sender: TObject);
begin
if Assigned(FOnSendLoc) then
FOnSendLoc(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.TnCnxTermType(Sender: TObject);
begin
if Assigned(FOnTermType) then
FOnTermType(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.TnCnxLocalEcho(Sender: TObject);
begin
if Assigned(FOnLocalEcho) then
FOnLocalEcho(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.TriggerDataAvailable(Buffer: PChar; Len: integer);
begin
if Assigned(FOnDataAvailable) then
FOnDataAvailable(Self, Buffer, Len);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.TnCnxDataAvailable(Sender: TTnCnx; Buffer: PChar;
Len: integer);
var
I: integer;
bAllValid: boolean;
begin
TriggerDataAvailable(Buffer, Len);
if Len <= 0 then
Exit;
{ for I := 0 to Len - 1 do begin
try
WriteChar((Buffer + I)^);
except
Break;
end;
end;
}
I := 0;
while I <= Len - 1 do
begin
try
if (I < Len - 1) and (Buffer[I] >= #$80) and (Buffer[I + 1] >= #$80) then
begin
WriteChar(Buffer[I]);
Inc(I);
WriteChar(Buffer[I]);
Inc(I);
if cnsent and (cnchar1 = #0) then
begin
UpdateScreen;
Repaint;
//InvalidateRect(Handle, nil, False);
//Invalidate;
//Repaint;
cnchar1 := #1;
end;
end
else
begin
WriteChar(Buffer[I]);
Inc(I);
end;
except
Break;
end;
end;
urlrect.Top := -1;
indicatorrect.Top := -1;
//FScreen.FAllInvalid := true;
bAllValid := FScreen.FAllInvalid;
UpdateScreen;
//Invalidate;
//Repaint;
if (Len < 30) and (not bAllValid) and (Buffer[0] > #$A0) then Repaint;
//if Len <= 2 then Invalidate;
if Assigned(FAfterDataAvailable) then
FAfterDataAvailable(Self, Buffer, Len);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.TnCnxSessionClosed(Sender: TTnCnx; Erc: word);
begin
Display(#13 + #10 + '*** Server has closed ***' + #13 + #10);
//MessageBeep(MB_ICONASTERISK);
//FScreen.ClearScreen;
//Repaint;
HideCaret(Handle);
FError := Erc;
if Assigned(FOnSessionClosed) then
FOnSessionClosed(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.TnCnxSessionConnected(Sender: TTnCnx; Erc: word);
begin
if Erc = 0 then
begin
Display('Connected' + #13 + #10);
end
else
begin
Display('Connection failed: ' +
{$IFDEF DELPHI}
TnCnx.Socket.SocketErrorDesc(Error) +
{$ELSE}
WSocketErrorDesc(Error) +
{$ENDIF}
#13 + #10);
MessageBeep(MB_ICONASTERISK);
end;
FError := Erc;
if Assigned(FOnSessionConnected) then
FOnSessionConnected(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.Connect;
var
{$IFDEF VER80} { Delphi 1 }
Form: TForm;
{$ELSE}
{$IFDEF VER90} { Delphi 2 }
Form: TForm;
{$ELSE}
{$IFDEF VER93} { Bcb 1 }
Form: TForm;
{$ELSE} { Delphi 3/4, Bcb 3/4 }
Form: TCustomForm;
{$ENDIF}
{$ENDIF}
{$ENDIF}
begin
if Length(FHostname) <= 0 then
Exit;
Clear;
TnCnx.Port := FPort;
TnCnx.Host := FHostName;
{fuse +}
cnsent := True;
cnchar1 := #1;
{fuse -}
//TnCnx.Socket.DnsLookup(FHostName);
TnCnx.Connect;
Display('Connecting to ''' + HostName + '''' + #13 + #10);
Form := GetParentForm(Self);
Form.ActiveControl := Self;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.Disconnect;
begin
TnCnx.Close;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTnEmulVT.Send(Data: Pointer; Len: integer): integer;
begin
if TnCnx.IsConnected then
Result := TnCnx.Send(Data, Len)
else
Result := -1;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTnEmulVT.SendStr(Data: string): integer;
begin
if TnCnx.IsConnected then
Result := TnCnx.SendStr(Data)
else
Result := -1;
LastKeyinTime := Now;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTnEmulVT.IsConnected: boolean;
begin
Result := TnCnx.IsConnected;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.KeyPress(var Key: char);
var
cnchars: array[0..4] of char;
begin
inherited KeyPress(Key);
{fuse +}
if not IsConnected then Exit;
if TopLine <> 0 then
begin
TopLine := 0;
UpdateScreen;
Repaint;
end;
{fuse -}
if FUpperLock and (Key in ['a'..'z']) then
Key := chr(Ord(Key) and $DF);
if Key <> #0 then
begin
try
if FLocalEcho then
WriteChar(Key);
{fuse +}
if (Key >= #$80) then
begin
if not cnsent then
begin
cnchars[0] := cnchar1;
cnchars[1] := Key;
TnCnx.Send(@cnchars, 2);
//TnCnx.Send(@Key, 1);
cnsent := True;
cnchar1 := #0;
end
else
begin
cnsent := False;
cnchar1 := Key;
end;
end
else
begin
{fuse -}
if not cnsent then
begin
cnchars[0] := cnchar1;
TnCnx.Send(@cnchars, 1);
cnsent := True;
cnchar1 := #0;
end;
cnchar1 := #1;
TnCnx.Send(@Key, 1);
end;
except
{ Ignore any exception ! }
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.DoKeyBuffer(Buffer: PChar; Len: integer);
begin
try
if FLocalEcho then
WriteBuffer(Buffer, Len);
if TnCnx.IsConnected then
TnCnx.Send(Buffer, Len);
except
{ Ignore exception ! }
end;
end;
function ValidLastDns(ldns: string): boolean;
var
i: integer;
ch: char;
begin
Result := True;
if (Length(ldns) <= 4) and (Length(ldns) > 1) then
begin
for i := 1 to Length(ldns) do
begin
ch := ldns[i];
if not IsCharAlpha(ch) then
begin
Result := False;
break;
end;
end;
end
else
Result := False;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTnEmulVT.SearchURL(nRow, nCol: integer;
var chfrom, chto: integer;
var prefix: string): string;
type
TURLState = (usPrefix, usDot, usDNS, usDNS2, usIP, usPort, usSlash, usParam, usError);
TEMailState = (esUser, esEta, esDNS, esDot, esDNS2, esError);
var
i, j, k: integer;
surl, ustr: string;
bfound: boolean;
sturl: TURLState;
stEmail: TEmailState;
lastdns: string;
ndot: integer;
const
DelimitChars = [' ', '"', ';', ',', ')', '(', '[', ']', '{', '}', '<', '>'];
URLChars = ['-', '_'];
ParamChars = ['?', '%', '&', '@', '=', '/', '~', '.', '_', '-'];
URLPrefix: array[0..7] of string[10] =
('http://', 'ftp://', 'mailto:', 'mms://', 'news://',
'telnet://', 'rstp://', 'https://');
begin
Result := '';
ustr := '';
i := nCol;
while (i >= 0) and (not (Screen.Lines[nRow + TopLine].Txt[i] in DelimitChars)) and
(Screen.Lines[nRow + TopLine].Txt[i] < #$80) do
begin
ustr := Screen.Lines[nRow + TopLine].Txt[i] + ustr;
Dec(i);
end;
j := nCol + 1;
while (j < Cols) and (not (Screen.Lines[nRow + TopLine].Txt[j] in DelimitChars)) and
(Screen.Lines[nRow + TopLine].Txt[j] < #$80) do
begin
ustr := ustr + Screen.Lines[nRow + TopLine].Txt[j];
Inc(j);
end;
chfrom := i + 1;
chto := j;
if Length(ustr) < 5 then Exit;
i := 0;
bfound := False;
surl := '';
while (i <= 7) and (not bfound) do
begin
j := Pos(URLPrefix[i], LowerCase(ustr));
if j > 0 then
begin
bFound := True;
break;
end;
Inc(i);
end;
prefix := '';
if bFound and (j = 1) then
begin
bfound := True;
surl := URLPrefix[i];
Delete(ustr, 1, Length(URLPrefix[i]));
prefix := URLPrefix[i];
end
else
begin
if Pos('@', ustr) > 1 then
begin
i := 2;
bFound := True;
prefix := 'mailto:';
end;
end;
if (i = 2) and bFound then
begin
stEmail := esUser;
k := 1;
ndot := 0;
while k <= Length(ustr) do
begin
case stemail of
esUser:
if IsCharAlphaNumeric(ustr[k]) or (ustr[k] = '.') then
begin
stemail := esUser;
surl := surl + ustr[k];
end
else if ustr[k] = '@' then
begin
stemail := esEta;
end
else
stemail := esError;
esEta:
if IsCharAlphaNumeric(ustr[k]) then
begin
stemail := esDNS;
surl := surl + ustr[k];
end
else
stemail := esError;
esDNS:
if IsCharAlphaNumeric(ustr[k]) then
begin
stemail := esDNS;
surl := surl + ustr[k];
end
else if ustr[k] = '.' then
begin
stemail := esDot;
surl := surl + ustr[k];
end
else
stemail := esError;
esDNS2:
if IsCharAlphaNumeric(ustr[k]) then
begin
stemail := esDNS2;
surl := surl + ustr[k];
lastdns := lastdns + ustr[k];
end
else if ustr[k] = '.' then
begin
stemail := esDot;
surl := surl + ustr[k];
end
else
stemail := esError;
esDot:
if IsCharAlphaNumeric(ustr[k]) then
begin
stemail := esDNS2;
lastdns := ustr[k];
surl := surl + ustr[k];
end
else
stemail := esError;
end;{case}
Inc(k);
end; {While}
if stemail in [esDNS2] then
begin
if ValidLastDNS(lastdns) or (ndot > 2) then
begin
Result := surl;
Exit;
end;
end;
end
else
begin
sturl := usPrefix;
k := 1;
ndot := 0;
while k <= Length(ustr) do
begin
case sturl of
usPrefix:
if IsCharAlphaNumeric(ustr[k]) then
begin
sturl := usDNS;
surl := surl + ustr[k];
end
else
sturl := usError;
usDNS:
if IsCharAlphaNumeric(ustr[k]) or (ustr[k] in URLChars) then
begin
sturl := usDNS;
surl := surl + ustr[k];
end
else if ustr[k] = '.' then
begin
sturl := usDot;
surl := surl + ustr[k];
end
else
sturl := usError;
usDNS2:
if IsCharAlphaNumeric(ustr[k]) or (ustr[k] in URLChars) then
begin
sturl := usDNS2;
surl := surl + ustr[k];
lastdns := lastdns + ustr[k];
end
else if ustr[k] = '.' then
begin
sturl := usDot;
surl := surl + ustr[k];
end
else if ustr[k] = '/' then
begin
sturl := usSlash;
surl := surl + ustr[k];
end
else if ustr[k] = ':' then
begin
sturl := usPort;
surl := surl + ustr[k];
end
else
sturl := usError;
usDot:
if IsCharAlphaNumeric(ustr[k]) then
begin
sturl := usDNS2;
lastdns := ustr[k];
surl := surl + ustr[k];
Inc(ndot);
end
else
sturl := usError;
usPort:
if IsCharAlphaNumeric(ustr[k]) then
begin
sturl := usPort;
surl := surl + ustr[k];
end
else if ustr[k] = '/' then
begin
sturl := usSlash;
surl := surl + ustr[k];
end
else
sturl := usError;
usSlash:
if (ustr[k] in ParamChars) or IsCharAlphaNumeric(ustr[k]) then
begin
sturl := usParam;
surl := surl + ustr[k];
end
else
sturl := usError;
usParam:
if (ustr[k] in ParamChars) or IsCharAlphaNumeric(ustr[k]) then
begin
sturl := usParam;
surl := surl + ustr[k];
end
else
sturl := usError;
usError:
Exit;
end; {case}
Inc(k);
end; {while}
if sturl in [usDNS2, usParam, usPort, usSlash] then
begin
if ValidLastDNS(lastdns) or (ndot > 2) then
begin
Result := surl;
Exit;
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.DrawFocusRectangle(Wnd: HWnd; Rect: TRect);
var
DC: HDC;
r1: TRect;
l1: integer;
begin
DC := GetDC(Wnd);
if not FFocusDrawn then
begin
DrawSelectRect(DC, rect);
end
else if SelectMode = smBlock then
begin
{DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
}
if ((rect.Bottom >= rect.Top) and (FFocusRect.Bottom <= FFocusRect.Top)) or
((rect.Bottom <= rect.Top) and (FFocusRect.Bottom >= FFocusRect.Top)) then
begin
DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
end
else if rect.Bottom <= rect.Top then
begin
if FFocusRect.Bottom > rect.Bottom then
begin
r1 := rect;
r1.Top := FFocusRect.Bottom;
DrawSelectRect(DC, r1);
r1 := rect;
r1.Bottom := FFocusRect.Bottom;
r1.Left := FFocusRect.Right;
DrawSelectRect(DC, r1);
end
else
begin
r1 := FFocusRect;
r1.Top := rect.Bottom;
DrawSelectRect(DC, r1);
r1 := FFocusRect;
r1.Bottom := rect.Bottom;
r1.Left := rect.Right;
DrawSelectRect(DC, r1);
end;
end
else
begin
if FFocusRect.Bottom <= rect.Bottom then
begin
r1 := rect;
r1.Left := FFocusRect.Right;
DrawSelectRect(DC, r1);
r1 := rect;
r1.Right := FFocusRect.Right;
r1.Top := FFocusRect.Bottom;
DrawSelectRect(DC, r1);
end
else
begin
r1 := FFocusRect;
r1.Left := rect.Right;
DrawSelectRect(DC, r1);
r1 := FFocusRect;
r1.Right := rect.Right;
r1.Top := rect.Bottom;
DrawSelectRect(DC, r1);
end;
end;
end
else if (rect.Top >= rect.Bottom) then
begin
if (FFocusRect.Top < FFocusRect.Bottom) then
begin
DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
end
{else if (FFocusRect.Bottom < TopMargin) or (rect.Bottom < TopMargin) then begin
DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
end}
else
begin
if FFocusRect.Bottom > rect.Bottom then
begin
l1 := PixelToRow(rect.Bottom);
if rect.Bottom < TopMargin then l1 := -1;
r1.Top := TopMargin + FLinePos[l1 + 1];
r1.Left := rect.Right;
l1 := PixelToRow(FFocusRect.Bottom);
if FFocusRect.Bottom < TopMargin then l1 := -1;
r1.Bottom := TopMargin + FLinePos[l1 + 2];
r1.Right := FFocusRect.Right;
DrawSelectRect(DC, r1);
end
else
begin
l1 := PixelToRow(FFocusRect.Bottom);
if FFocusRect.Bottom < TopMargin then l1 := -1;
r1.Top := TopMargin + FLinePos[l1 + 1];
r1.Left := FFocusRect.Right;
l1 := PixelToRow(rect.Bottom);
if rect.Bottom < TopMargin then l1 := -1;
r1.Bottom := TopMargin + FLinePos[l1 + 2];
r1.Right := rect.Right;
DrawSelectRect(DC, r1);
end;
end;
end
else if (rect.Top < rect.Bottom) and (FFocusRect.Top >= FFocusRect.Bottom) then
begin
DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
end
else if (rect.Top = FFocusRect.Top) and (rect.Left = FFocusRect.Left) and
(rect.Top < rect.Bottom) then
begin
if rect.Bottom = FFocusRect.Bottom then
begin
l1 := PixelToRow(FFocusRect.Bottom - LineHeight);
r1.Left := rect.Right;
r1.Right := FFocusRect.Right;
r1.Top := rect.Bottom;
r1.Bottom := TopMargin + FLinePos[l1];
InvertRect(DC, r1);
end
else if rect.Bottom > FFocusRect.Bottom then
begin
l1 := PixelToRow(FFocusRect.Bottom - LineHeight);
r1 := rect;
r1.Left := FFocusRect.Right;
r1.Top := TopMargin + FLinePos[l1];
DrawSelectRect(DC, r1);
end
else
begin
l1 := PixelToRow(rect.Bottom - LineHeight);
r1 := FFocusRect;
r1.Left := rect.Right;
r1.Top := TopMargin + FLinePos[l1];
DrawSelectRect(DC, r1);
end;
end;
ReleaseDC(Wnd, DC);
end;
procedure TTnEmulVT.XtermMouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
var
c1, r1: integer;
cx, cy, cb: char;
begin
//SendStr(#$1B + '[?9h');
c1 := PixelToCol(X);
r1 := PixelToRow(Y);
if Button = mbLeft then cb := #$0
else if Button = mbMiddle then cb := #$1
else if Button = mbRight then cb := #$2;
if ssShift in Shift then cb := char(4 + Ord(cb));
if ssAlt in Shift then cb := char(8 + Ord(cb));
if ssCtrl in Shift then cb := char(16 + Ord(cb));
cb := char(32 + Ord(cb));
cx := char(32 + c1 + 1);
cy := char(32 + r1 + 1);
SendStr(#$1B + '[M' + cb + cx + cy);
end;
procedure TTnEmulVT.XtermMouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
var
c1, r1: integer;
cx, cy, cb: char;
begin
//SendStr(#$1B + '[?9h');
c1 := PixelToCol(X);
r1 := PixelToRow(Y);
cb := #3;
if ssShift in Shift then cb := char(4 + Ord(cb));
if ssAlt in Shift then cb := char(8 + Ord(cb));
if ssCtrl in Shift then cb := char(16 + Ord(cb));
cb := char(32 + Ord(cb));
cx := char(32 + c1 + 1);
cy := char(32 + r1 + 1);
SendStr(#$1B + '[M' + cb + cx + cy);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTnEmulVT.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if not IsConnected then Exit;
if FScreen.FXtermMouse then
begin
if not (ssShift in Shift) then begin
XtermMouseDown(Button, Shift, X, Y);
Exit;
end;
end;
if Button = mbRight then Exit;
FMouseDown := True;
if FFocusDrawn then
begin
//if not swapdraw then DrawFocusRectangle(Handle, FFocusRect);
FFocusDrawn := False;
end;
if (SelectRect.Top <> -1) and (Button = mbLeft) then
begin
FFocusRect.Top := -1;
SelectRect := FFocusRect;
//if swapdraw then UpdateScreen;
Repaint;
end;
end;
function EqualRect(r1, r2: TRect): boolean;
begin
if (r1.Left = r2.Left) and (r1.Top = r2.Top) and (r1.Right = r2.Right) and
(r1.Bottom = r2.Bottom) then Result := True
else
Result := False;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.MouseMove(Shift: TShiftState; X, Y: integer);
var
Rect: TRect;
Point: TPoint;
i, j, ch1, ch2: integer;
pstr: string;
r: TRect;
begin
inherited MouseMove(Shift, X, Y);
{fuse +}
if not IsConnected then Exit;
GetTextRect(r);
if (X > r.Right) or (Y > r.Bottom) then Exit;
{ Point.X := X; Point.Y := y;
if not PtInRect(r, Point) then Exit;
}
if ParseUrl and (not FMouseCaptured) then
begin
i := PixelToRow(Y);
j := PixelToCol(X);
if SearchURL(i, j, ch1, ch2, pstr) <> '' then
begin
r.Left := FCharPos[ch1] + LeftMargin;
r.Right := FCharPos[ch2] + LeftMargin;
r.Top := SnapPixelToRow(Y);
r.Bottom := SnapPixelToRow(Y) + FLinePos[i + 1] - FLinePos[i];
SetUrlRect(r);
if Assigned(FOnLinkMoveIn) then
begin
FOnLinkMoveIn(Self);
end;
end
else
begin
if urlrect.Top <> -1 then
begin
r.Top := -1;
SetUrlRect(r);
if Assigned(FOnLinkMoveOut) then
begin
FOnLinkMoveOut(Self);
end;
end;
end;
end;
{fuse -}
if not FMouseDown then
Exit;
r.Top := -1;
SetUrlRect(r);
SetIndicatorRect(r);
if not FMouseCaptured then
begin
SetCapture(Handle);
FMouseCaptured := True;
FMouseTop := SnapPixelToRow(Y);
FMouseLeft := SnapPixelToCol(X);
Point.X := 0;
Point.Y := 0;
Rect.TopLeft := ClientToScreen(Point);
Point.X := Width;
Point.Y := Height;
Rect.BottomRight := ClientToScreen(Point);
ClipCursor(@Rect);
end
else if (FMouseTop <> Y) or (FMouseLeft <> X) then
begin
Rect.Top := FMouseTop;
Rect.Left := FMouseLeft;
i := PixelToRow(Y);
if i >= Rows then Exit;
if Y > Rect.Top then
Rect.Bottom := SnapPixelToRow(Y) + FLinePos[i + 1] - FLinePos[i]
else
begin
{if Y < TopMargin then begin
Rect.Bottom := TopMargin;
end
else}
if i > 1 then
Rect.Bottom := SnapPixelToRow(Y) - (FLinePos[i] - FLinePos[i - 1])
else
Rect.Bottom := SnapPixelToRow(Y) - FLinePos[1];
end;
//i := PixelToCol(X);
Rect.Right := SnapPixelToCol(X);
if EqualRect(FFocusRect, Rect) then Exit;
// if FFocusDrawn and (not swapdraw) then DrawFocusRectangle(Handle, FFocusRect);
{ if swapdraw then
begin
UpdateScreen;
Repaint;
end
else
}
DrawFocusRectangle(Handle, Rect);
FFocusRect := Rect;
SelectRect := FFocusRect; {fuse +}
FFocusDrawn := True;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
var
urlstr: string;
i: integer;
begin
inherited MouseUp(Button, Shift, X, Y);
if not IsConnected then Exit;
if FScreen.FXtermMouse and (not FMouseCaptured) then
begin
if not (ssShift in Shift) then begin
XtermMouseUp(Button, Shift, X, Y);
Exit;
end;
end;
if Button = mbRight then Exit;
FMouseDown := False;
if FMouseCaptured then
begin
ReleaseCapture;
FMouseCaptured := False;
ClipCursor(nil);
end;
if FFocusDrawn then
begin
//if not swapdraw then InvalidateRect(Handle, @SelectRect, false); //DrawFocusRectangle(Handle, FFocusRect);
FFocusDrawn := False;
i := PixelToCol(FFocusRect.Left);
if Abs(FFocusRect.Right - FFocusRect.Left) < DrawCharWidth(i) then
FFocusRect.Top := -1;
i := PixelToRow(FFocusRect.Top);
if Abs(FFocusRect.Bottom - FFocusRect.Top) < DrawLineHeight(i) then
FFocusRect.Top := -1;
SelectRect := FFocusRect;
//if swapdraw then UpdateScreen;
InvalidateRect(Handle, @SelectRect, False);
//Repaint;
Exit;
end
else
begin
FFocusRect.Top := -1;
SelectRect := FFocusRect;
end;
{fuse +}
if ParseURL then
begin
if Assigned(FOnLinkClick) and (not (FMouseCaptured)) and (urlrect.Top > 0) then
begin
urlstr := '';
for i := PixelToCol(urlrect.Left) to PixelToCol(urlrect.Right - 2) do
begin
urlstr := urlstr + Screen.Lines[PixelToRow(urlrect.Top) + TopLine].Txt[i];
end;
if urlstr <> '' then
begin
FOnLinkClick(Self, urlstr);
end;
end;
end;
{fuse -}
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.UnSelect;
begin
if FMouseCaptured then
begin
ReleaseCapture;
FMouseCaptured := False;
ClipCursor(nil);
end;
if SelectRect.Top <> -1 then
begin
FFocusRect.Top := -1;
SelectRect := FFocusRect;
UpdateScreen;
Repaint;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
function TTnEmulVT.GetSelTextBuf(Buffer: PChar; BufSize: integer): integer;
var
StartRow: integer;
StopRow: integer;
StartCol: integer;
StopCol: integer;
nRow: integer;
nCol: integer;
Line: TLine;
nCnt: integer;
begin
nCnt := 0;
if (SelectRect.Top = -1) or (BufSize < 1) then
begin
if BufSize > 0 then
Buffer[0] := #0;
Result := nCnt;
Exit;
end;
StartRow := PixelToRow(SelectRect.Top);
StopRow := PixelToRow(SelectRect.Bottom) - 1;
StartCol := PixelToCol(SelectRect.Left);
StopCol := PixelToCol(SelectRect.Right) - 1;
for nRow := StartRow to StopRow do
begin
if BufSize < 2 then
Break;
Line := Screen.FLines^[Rows - 1 - nRow];
for nCol := StartCol to StopCol do
begin
Buffer[0] := Line.Txt[nCol];
Inc(Buffer);
Dec(BufSize);
Inc(nCnt);
if BufSize < 2 then
Break;
end;
if nRow < StopRow then
begin
if BufSize < 4 then
Break;
Buffer[0] := #13;
Buffer[1] := #10;
Inc(Buffer);
Inc(Buffer);
Dec(BufSize);
Dec(BufSize);
Inc(nCnt);
Inc(nCnt);
end;
end;
Buffer[0] := #0;
Result := nCnt;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.SetUrlRect(r: TRect);
var
saverc: TRect;
begin
if (r.Top = urlrect.Top) and (r.Left = urlrect.Left) and
(r.Bottom = urlrect.Bottom) and (r.Right = urlrect.Right) then Exit;
if (urlrect.Top <> -1) then
begin
saverc := urlrect;
urlrect.Top := -1;
//saverc.Top := saverc.Bottom;
//Inc(saverc.Bottom, 1);
InvalidateRect(Handle, @saverc, False);
end;
if r.Top <> -1 then
begin
urlrect := r;
InvalidateRect(Handle, @urlrect, False);
//Repaint;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TTnEmulVT.SetIndicatorRect(r: TRect);
var
saverc: TRect;
drawrc: TRect;
begin
if r.Top = -1 then
begin
if (indicatorrect.Top <> -1) then
begin
saverc := indicatorrect;
indicatorrect.Top := -1;
saverc.Top := saverc.Bottom;
Inc(saverc.Bottom, 1);
InvalidateRect(Handle, @saverc, False);
end;
Exit;
end;
drawrc.Left := FCharPos[r.Left] + LeftMargin;
drawrc.Right := FCharPos[r.Right] + LeftMargin;
drawrc.Top := FLinePos[r.Top] + TopMargin;
drawrc.Bottom := FLinePos[r.Bottom] + TopMargin;
saverc := indicatorrect;
if (drawrc.Top = saverc.Top) and (drawrc.Left = saverc.Left) and
(drawrc.Bottom = saverc.Bottom) and (drawrc.Right = saverc.Right) then Exit;
if (indicatorrect.Top <> -1) then
begin
saverc := indicatorrect;
indicatorrect.Top := -1;
saverc.Top := saverc.Bottom;
Inc(saverc.Bottom, 1);
InvalidateRect(Handle, @saverc, False);
end;
if drawrc.Top <> -1 then
begin
indicatorrect := drawrc;
drawrc.Top := drawrc.Bottom;
Inc(drawrc.Bottom, 1);
InvalidateRect(Handle, @drawrc, False);
//Repaint;
end;
end;
procedure TTnEmulVT.CMMouseEnter(var Message: TMessage);
var
r: TRect;
begin
r.Top := -1;
SetUrlRect(r);
SetIndicatorRect(r);
if Assigned(FMouseEnter) then
FMouseLeave(self);
end;
procedure TTnEmulVT.CMMouseLeave(var Message: TMessage);
var
r: TRect;
begin
r.Top := -1;
SetUrlRect(r);
SetIndicatorRect(r);
// Repaint;
if Assigned(FMouseLeave) then
FMouseLeave(self);
end;
procedure TTnEmulVT.SetSingleCharPaint(bSCP: boolean);
begin
if bSCP <> SingleCharPaint then
begin
SingleCharPaint := bSCP;
Repaint;
end;
end;
end.
|
{*******************************************************}
{ }
{ Copyright(c) 2003-2018 Oamaru Group , Inc. }
{ }
{ Copyright and license exceptions noted in source }
{ }
{ Non Commerical Use Permitted }
{*******************************************************}
unit EndPointClient;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdSSL, IdSSLOpenSSL,
IdSSLOpenSSLHeaders, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack;
type
TEndpointClient = class
protected
{ Protected declarations }
FEndpointURL: String;
FHttp: TIdHTTP;
FResponseCode: Integer;
FResponseText: String;
FFullURL: String;
FHandler: TIdSSLIOHandlerSocketOpenSSL;
public
{ Public declarations }
constructor Create(AEndpointURL: String; APort: WORD; AUserName, APAssword: String; AResource: String); virtual;
destructor Destroy; override;
function Head: Integer; overload;
function Head(AResource: String): Integer; overload;
function Get: String; overload;
function Get(AResource: String): String; overload;
function Put(AContents: String): String; overload;
function Put(AResource: String; AContents: String): String; overload;
procedure Post(AContents: String); overload;
procedure Post(AResource: String; AContents: String); overload;
function Delete: String; overload;
function Delete(AResource: String): String; overload;
property ResponseCode: Integer read FResponseCode;
property ResponseText: String read FResponseText;
property StatusCode: Integer read FResponseCode;
property StatusText: String read FResponseText;
property FullURL: String read FFullURl;
end;
implementation
constructor TEndpointClient.Create(AEndpointURL: String; APort: WORD; AUserName, APassword: String; AResource: String);
begin
FHandler := nil;
FHttp := TIdHTTP.Create(nil);
if not String.IsNullorWhiteSpace(AUserName) then
begin
FHttp.Request.Username := AUserName;
FHttp.Request.Password := APassword;
FHttp.Request.BasicAuthentication:= TRUE;
FHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
FHttp.IOHandler := FHandler;
FHandler.SSLOptions.SSLVersions := [sslvTLSv1_2];
FHandler.SSLOptions.Method := sslvTLSv1_2;
end;
FEndpointURL := String.Format('%s:%d', [AEndpointURL, APort]);
FFullURL := String.Format('%s/%s', [FEndpointURL, AResource]);
end;
destructor TEndpointClient.Destroy;
begin
FHttp.Free;
if Assigned(FHandler) then
FHandler.Free;
inherited Destroy;
end;
function TEndpointClient.Head: Integer;
begin
FResponseText := String.Empty;
try
FHttp.Head(FFullURL);
except
end;
FResponseCode := FHttp.ResponseCode;
Result := FResponseCode;
FResponseText := FHttp.ResponseText;
end;
function TEndpointClient.Head(AResource: String): Integer;
begin
FResponseText := String.Empty;
try
FHttp.Head(String.Format('%s/%s', [FEndpointURL, AResource]));
except
end;
FResponseCode := FHttp.ResponseCode;
Result := FResponseCode;
FResponseText := FHttp.ResponseText;
end;
function TEndpointClient.Get: String;
begin
FResponseText := String.Empty;
try
Result := FHttp.Get(FFullURL);
except
on E:Exception do
begin
Result := String.Format('%s', [E.Message]);
end;
end;
FResponseCode := FHttp.ResponseCode;
FResponseText := FHttp.ResponseText;
end;
function TEndpointClient.Get(AResource: String): String;
begin
FResponseText := String.Empty;
try
Result := FHttp.Get(String.Format('%s/%s', [FEndpointURL, AResource]));
except
on E:Exception do
begin
Result := String.Format('%s', [E.Message]);
end;
end;
FResponseCode := FHttp.ResponseCode;
FResponseText := FHttp.ResponseText;
end;
function TEndpointClient.Put(AContents: String): String;
var
LStream: TStringStream;
begin
FResponseText := String.Empty;
try
LStream := TStringStream.Create(AContents);
try
FHttp.Request.Accept := 'application/json';
FHttp.Request.ContentType := 'application/json';
Result := FHttp.Put(FFullURL, LStream);
FResponseCode := FHttp.ResponseCode;
FResponseText := FHttp.ResponseText;
EXIT;
finally
LStream.Free;
end;
except
end;
FResponseCode := FHttp.ResponseCode;
FResponseText := FHttp.ResponseText;
LStream := TStringStream.Create;
try
LStream.CopyFrom(FHttp.Response.ContentStream,FHttp.Response.ContentStream.Size );
Result := LStream.DataString;
finally
LStream.Free;
end;
end;
function TEndpointClient.Put(AResource: String; AContents: String): String;
var
LStream: TStringStream;
begin
FResponseText := String.Empty;
try
LStream := TStringStream.Create(AContents);
try
FHttp.Request.Accept := 'application/json';
FHttp.Request.ContentType := 'application/json';
FHttp.Put(String.Format('%s/%s', [FEndpointURL, AResource]), LStream);
finally
LStream.Free;
end;
except
//Do not throw
end;
FResponseCode := FHttp.ResponseCode;
FResponseText := FHttp.ResponseText;
end;
procedure TEndpointClient.Post(AContents: String);
var
LStream: TStringStream;
begin
FResponseText := String.Empty;
try
LStream := TStringStream.Create(AContents);
try
FHttp.Request.ContentType := 'application/json';
FHttp.Post(FFullURL, LStream);
finally
LStream.Free;
end;
except
//Do not throw
end;
FResponseCode := FHttp.ResponseCode;
FResponseText := FHttp.ResponseText;
end;
procedure TEndpointClient.Post(AResource: String; AContents: String);
var
LStream: TStringStream;
begin
FResponseText := String.Empty;
try
LStream := TStringStream.Create(AContents);
try
FHttp.Request.ContentType := 'application/json';
FHttp.Post(String.Format('%s/%s', [FEndpointURL, AResource]), LStream);
finally
LStream.Free;
end;
except
//Do not throw
end;
FResponseCode := FHttp.ResponseCode;
FResponseText := FHttp.ResponseText;
end;
function TEndpointClient.Delete: String;
begin
FResponseText := String.Empty;
try
Result := FHttp.Delete(FFullURL);
except
//Do not throw
end;
FResponseCode := FHttp.ResponseCode;
FResponseText := FHttp.ResponseText;
end;
function TEndpointClient.Delete(AResource: String): String;
begin
FResponseText := String.Empty;
try
Result := FHttp.Delete(String.Format('%s/%s', [FEndpointURL, AResource]));
except
//Do not throw
end;
FResponseCode := FHttp.ResponseCode;
FResponseText := FHttp.ResponseText;
end;
end.
|
{==============================================================================
Copyright (C) combit GmbH
-------------------------------------------------------------------------------
File : uChart.pas, uChart.dfm, chart.dpr
Module : chart sample
Descr. : D: Dieses Beispiel demonstriert das Designen und Drucken von Charts.
US: This example demonstrates how to design and print charts.
===============================================================================}
unit uChart;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DB,
Registry, DBTables, ADODB, L28, StdCtrls, cmbtll28, L28db;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
LL: TDBL28_;
dsOrders: TDataSource;
dsCustomers: TDataSource;
dsOrderDetails: TDataSource;
Customers: TADOTable;
ADOConnection1: TADOConnection;
Orders: TADOTable;
OrderDetails: TADOTable;
btnDesign: TButton;
btnPrint: TButton;
procedure LLExprError(Sender: TObject; ErrorText: string;
lResult: Integer);
procedure btnDesignClick(Sender: TObject);
procedure btnPrintClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
workingPath: String;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.LLExprError(Sender: TObject; ErrorText: string;
lResult: Integer);
begin
ShowMessage(ErrorText);
end;
procedure TForm1.btnDesignClick(Sender: TObject);
begin
LL.AutoShowSelectFile := No;
LL.AutoDesignerFile := workingPath + 'chart.lst';
LL.AutoDesign('Sales Report');
end;
procedure TForm1.btnPrintClick(Sender: TObject);
begin
LL.AutoShowSelectFile := No;
LL.AutoDesignerFile := workingPath + 'chart.lst';
LL.AutoPrint('Sales Report', '');
end;
procedure TForm1.FormCreate(Sender: TObject);
var registry: TRegistry;
var regKeyPath: String;
var dbPath: String;
var tmp: String;
begin
// D: Datenbankpfad auslesen
// US: Read database path
registry := TRegistry.Create();
registry.RootKey := HKEY_CURRENT_USER;
regKeyPath := 'Software\combit\cmbtll\';
if registry.KeyExists(regKeyPath) then
begin
if registry.OpenKeyReadOnly(regKeyPath) then
begin
dbPath := registry.ReadString('NWINDPath');
tmp := registry.ReadString('LL' + IntToStr(LL.LlGetVersion(LL_VERSION_MAJOR)) + 'SampleDir');
if (tmp[Length(tmp)] = '\') then
begin
workingPath := tmp + 'Delphi\BDE (Legacy)\Samples\';
end
else
workingPath := tmp + '\Delphi\BDE (Legacy)\Samples\';
registry.CloseKey();
end;
end;
registry.Free();
if (dbPath = '') OR (workingPath = '') then
begin
ShowMessage('Unable to find sample database. Make sure List & Label is installed correctly.');
exit;
end;
// D: Verzeichnis setzen
// US: Set current dir
workingpath := GetCurrentDir() +'\';
if not ADOConnection1.Connected then
begin
ADOConnection1.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;' +
'User ID=Admin;' +
'Data Source=' + dbPath + ';' +
'Mode=Share Deny None;' +
'Extended Properties="";' +
'Jet OLEDB:Engine Type=4;';
ADOConnection1.Connected := true;
Customers.Active := true;
Orders.Active := true;
OrderDetails.Active := true;
end;
end;
end.
|
namespace mandelbrot;
// Sample app by Brian Long (http://blong.com)
{
This example demonstrates using varying density characters to render the
Mandelbrot set out to stdout
}
interface
type
ConsoleApp = class
public
class method Main(args: array of String);
end;
implementation
class method ConsoleApp.Main(args: array of String);
const
cols = 78;
lines = 30;
chars = " .,`':;=|+ihIHEOQSB#$";
maxIter = length(chars);
begin
var minRe := -2.0;
var maxRe := 1.0;
var minIm := -1.0;
var maxIm := 1.0;
var im := minIm;
while im <= maxIm do begin
var re := minRe;
while re <= maxRe do begin
var zr := re;
var zi := im;
var n: Integer := -1;
while n < maxIter-1 do begin
inc(n);
var a := zr * zr;
var b := zi * zi;
if a + b > 4.0 then
Break;
zi := 2 * zr * zi + im;
zr := a - b + re;
end;
write(chars[n]);
re := re + ((maxRe - minRe) / cols);
end;
writeLn();
im := im + ((maxIm - minIm) / lines)
end;
//Press ENTER to continue
writeLn("Press ENTER to exit");
Console.Read();
end;
end.
|
(*
Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES
Original name: 0011.PAS
Description: DEC2BIN2.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:53
*)
{ True so here is another version of the process that returns a String : }
Program Dec2BinRec;
Type
Str32 = String[32];
Function Dec2BinStr(aNumber : LongInt) : Str32;
Function Bit(aBit : Byte) : Char;
(* return either Char '0' or Char '1' *)
begin
if aBit = 0 then
Bit := '0'
else
Bit := '1'
end;
begin
If aNumber = 0 Then
Dec2BinStr := '' (* done With recursion ?*)
else (* convert high bits + last bit *)
Dec2BinStr := Dec2BinStr(ANumber Div 2) + Bit(aNumber Mod 2);
end;
Var
L : LongInt;
begin
Repeat
Write('Enter a number (0 to end): ');
Readln (L);
If L <> 0 then
Writeln(Dec2BinStr(L));
Until (L = 0)
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics,
VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser,
VCL.TMSFNCMaps, Vcl.StdCtrls;
type
TFrmMain = class(TForm)
Map: TTMSFNCMaps;
txtDistance: TEdit;
procedure FormCreate(Sender: TObject);
procedure MapMapClick(Sender: TObject; AEventData: TTMSFNCMapsEventData);
private
{ Private declarations }
LPlaces: TTMSFNCMapsCoordinateRecArray;
procedure AddPlace( ACoord: TTMSFNCMapsCoordinate );
procedure Measure;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses Flix.Utils.Maps, IOUtils;
procedure TFrmMain.AddPlace(ACoord: TTMSFNCMapsCoordinate);
begin
LPlaces[1] := LPlaces[0];
LPlaces[0] := ACoord.ToRec;
Measure;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
var
LKeys: TServiceAPIKeys;
begin
SetLength( LPlaces, 2 );
LPlaces[0] := EmptyCoordinate;
LPlaces[1] := EmptyCoordinate;
LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) );
try
Map.APIKey := LKeys.GetKey( msGoogleMaps );
finally
LKeys.Free;
end;
end;
procedure TFrmMain.MapMapClick(Sender: TObject; AEventData: TTMSFNCMapsEventData);
begin
AddPlace( AEventData.Coordinate );
end;
procedure TFrmMain.Measure;
var
LDistance : Double;
begin
Map.BeginUpdate;
try
// clear markers and polylines
Map.ClearMarkers;
// if index 0 has content
// ...add marker
if LPlaces[0].Longitude <> 0 then
begin
Map.AddMarker(LPlaces[0]);
end;
// if index 1 has content
// ... add marker
if LPlaces[1].Longitude <> 0 then
begin
Map.AddMarker(LPlaces[1]);
end;
// if both elements have a coordinate
if (LPlaces[0].Longitude <> 0) AND
(LPlaces[1].Longitude <> 0 ) then
begin
// calculate distance
LDistance := MeasureDistance(LPlaces[0], LPlaces[1]);
// output distance
txtDistance.Text := Format( '%f km, %f m',
[
LDistance / 1000,
LDistance
]
);
end
else
begin
// clear distance
txtDistance.Text := '';
end;
finally
// update map display
Map.EndUpdate;
end;
end;
end.
|
// Copyright (©) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
///Модуль элементов управления для GraphWPF
unit Controls;
interface
uses GraphWPFBase;
uses System.Windows;
uses System.Windows.Media;
uses System.Windows.Controls;
uses System.ComponentModel;
procedure AddRightPanel(Width: real := 200; c: Color := Colors.LightGray; Margin: real := 10);
procedure AddLeftPanel(Width: real := 200; c: Color := Colors.LightGray; Margin: real := 10);
procedure AddTopPanel(Height: real := 70; c: Color := Colors.LightGray; Margin: real := 10);
procedure AddBottomPanel(Height: real := 70; c: Color := Colors.LightGray; Margin: real := 10);
procedure AddStatusBar(Height: real := 24);
var
ActivePanel: Panel;
GlobalHMargin := 12;
type
GButton = System.Windows.Controls.Button;
GTextBlock = System.Windows.Controls.TextBlock;
GTextBox = System.Windows.Controls.TextBox;
GListBox = System.Windows.Controls.ListBox;
Key = System.Windows.Input.Key;
///!#
CommonControl = class
protected
element: FrameworkElement;
function GetM: real := InvokeReal(()->element.Margin.Top);
procedure SetMP(m: real) := element.Margin := new Thickness(m);
procedure SetM(m: real) := Invoke(SetMP, m);
function GetW: real := InvokeReal(()->element.Width);
procedure SetWP(w: real) := element.Width := w;
procedure SetW(w: real) := Invoke(SetWP, w);
function GetH: real := InvokeReal(()->element.Height);
procedure SetHP(h: real) := element.Height := h;
procedure SetH(h: real) := Invoke(SetHP, h);
public
property Width: real read GetW write SetW;
property Height: real read GetH write SetH;
property Margin: real read GetM write SetM;
end;
///!#
ButtonT = class(CommonControl)
protected
function b: GButton := element as GButton;
procedure BClick(sender: Object; e: RoutedEventArgs);
begin
if Click <> nil then
Click;
end;
function GetText: string := InvokeString(()->b.Content as string);
procedure SetTextP(t: string) := b.Content := t;
procedure SetText(t: string) := Invoke(SetTextP, t);
procedure CreateP(Txt: string; fontSize: real);
begin
element := new GButton;
element.Margin := new Thickness(0, 0, 0, GlobalHMargin);
//Margin := GlobalMargin;
Text := Txt;
Self.FontSize := fontSize;
b.Click += BClick;
b.Focusable := False;
ActivePanel.Children.Add(b);
end;
procedure CreatePXY(x, y: real; Txt: string; fontSize: real);
begin
element := new GButton;
element.SetLeft(x);
element.SetTop(y);
element.Margin := new Thickness(0, 0, 0, GlobalHMargin);
//Margin := GlobalMargin;
Text := Txt;
b.Click += BClick;
b.Focusable := False;
ActivePanel.Children.Add(b);
end;
public
Click: procedure;
constructor Create(Txt: string; fontSize: real := 12);
begin
Invoke(CreateP, Txt, fontSize);
end;
constructor Create(x, y: real; Txt: string; fontsize: real := 12);
begin
Invoke(CreatePXY, x, y, Txt, fontsize);
end;
property Text: string read GetText write SetText;
property FontSize: real read InvokeReal(()->b.FontSize) write Invoke(procedure(t: real) -> b.FontSize := t, value);
property Enabled: boolean read InvokeBoolean(()->b.IsEnabled) write Invoke(procedure(t: boolean) -> b.IsEnabled := t, value);
end;
///!#
TextBlockT = class(CommonControl)
protected
function b: GTextBlock := element as GTextBlock;
procedure CreateP(Txt: string; fontsize: real);
begin
var tb := new GTextBlock;
element := tb;
element.Margin := new Thickness(0, 0, 0, GlobalHMargin);
//element.Margin := new Thickness(5,5,5,0);
tb.FontSize := fontsize;
Text := Txt;
ActivePanel.Children.Add(b);
end;
procedure CreatePXY(x, y: real; Txt: string; fontsize: real);
begin
var tb := new GTextBlock;
element := tb;
element.Margin := new Thickness(0, 0, 0, GlobalHMargin);
//tb.Background := new SolidColorBrush(Colors.White);
//tb.Opacity := 0.7;
Canvas.SetLeft(element, x);
Canvas.SetTop(element, y);
tb.FontSize := fontsize;
Text := Txt;
ActivePanel.Children.Add(b);
end;
public
constructor Create(Txt: string; fontsize: real := 12):= Invoke(CreateP, Txt, fontsize);
constructor Create(x, y: real; Txt: string; fontsize: real := 12):= Invoke(CreatePXY, x, y, Txt, fontsize);
property Text: string read InvokeString(()->b.Text) write Invoke(procedure(t: string) -> b.Text := t, value);
property FontSize: real read InvokeReal(()->b.FontSize) write Invoke(procedure(t: real) -> b.FontSize := t, value);
end;
IntegerBlockT = class(TextBlockT)
private
val := 0;
message: string;
procedure CreateP(message: string; fontSize: real := 12; initValue: integer := 0);
begin
inherited CreateP(message + ' ' + initValue, fontSize);
Self.message := message;
val := initValue;
end;
public
property Value: integer read val write begin val := value; Text := message + ' ' + val; end;
constructor Create(message: string; fontSize: real := 12; initValue: integer := 0):= Invoke(CreateP, message, fontSize, initValue);
end;
RealBlockT = class(TextBlockT)
private
val := 0.0;
message: string;
procedure CreateP(message: string; fontSize: real := 12; initValue: real := 0);
begin
inherited CreateP(message + ' ' + initValue.ToString(FracDigits), fontSize);
Self.message := message;
val := initValue;
end;
public
property Value: real read val write begin val := value; Text := message + ' ' + val.ToString(FracDigits); end;
constructor Create(message: string; fontSize: real := 12; initValue: real := 0):= Invoke(CreateP, message, fontSize, initValue);
auto property FracDigits: integer := 1;
end;
///!#
TextBoxT = class(CommonControl)
protected
function tb: GTextBox := element as GTextBox;
procedure BTextChanged(sender: Object; e: TextChangedEventArgs);
begin
if Click <> nil then
Click;
end;
function GetText: string := InvokeString(()->tb.Text);
procedure SetTextP(t: string) := tb.Text := t;
procedure SetText(t: string) := Invoke(SetTextP, t);
procedure CreateP(Txt: string; w: real);
begin
element := new GTextBox;
element.HorizontalAlignment := HorizontalAlignment.Stretch;
element.Margin := new Thickness(0, 0, 0, GlobalHMargin);
Text := Txt;
if w > 0 then
Width := w;
tb.TextChanged += BTextChanged;
ActivePanel.Children.Add(tb);
end;
public
event Click: procedure;
constructor Create(Txt: string := ''; w: real := 0);
begin
Invoke(CreateP, Txt, w);
end;
property Text: string read GetText write SetText;
property FontSize: real read InvokeReal(()->tb.FontSize) write Invoke(procedure(t: real) -> tb.FontSize := t, value);
end;
IntegerBoxT = class(TextBoxT)
function GetValue: integer;
begin
if Trim(Text) = '' then
Result := 0
else Result := integer.Parse(Text);
end;
procedure SetValue(x: integer) := Text := x.ToString;
public
constructor Create(w: real := 0);
begin
inherited Create('0', w);
var tb := element as GTextBox;
tb.MouseWheel += procedure (o, e) -> begin
if e.Delta > 0 then
SetValue(GetValue + 1)
else if e.Delta < 0 then
SetValue(GetValue - 1)
end;
tb.KeyDown += procedure (o, e) -> begin
if not ((e.Key >= Key.D0) and (e.Key <= Key.D9)) then
e.Handled := True;
end;
{tb.TextInput += procedure (o,e) -> begin
Print(e.Text);
if not ((e.Key>=Key.D0) and (e.Key<=Key.D9)) then
e.Handled := True;
end;}
end;
property Value: integer read GetValue write SetValue;
property FontSize: real read InvokeReal(()->tb.FontSize) write Invoke(procedure(t: real) -> tb.FontSize := t, value);
end;
TextBoxWithBlockT = class(CommonControl)
private
l: TextBlock;
protected
function tb: GTextBox := (element as StackPanel).Children[1] as GTextBox;
procedure BTextChanged(sender: Object; e: TextChangedEventArgs);
begin
if Click <> nil then
Click;
end;
function GetText: string := InvokeString(()->tb.Text);
procedure SetTextP(t: string) := tb.Text := t;
procedure SetText(t: string) := Invoke(SetTextP, t);
procedure CreateP(BlockTxt, Txt: string; w: real);
begin
var sp := new StackPanel;
element := sp;
sp.Orientation := Orientation.Horizontal;
sp.HorizontalAlignment := HorizontalAlignment.Stretch;
l := new TextBlock();
l.Text := BlockTxt;
sp.Children.Add(l);
var tb := new GTextBox;
tb.Width := 100;
tb.VerticalAlignment := VerticalAlignment.Stretch;
tb.Margin := new Thickness(0, 0, 0, GlobalHMargin);
sp.Children.Add(tb);
Text := Txt;
if w > 0 then
Width := w;
tb.TextChanged += BTextChanged;
ActivePanel.Children.Add(sp);
end;
public
event Click: procedure;
constructor Create(BlockTxt: string; Txt: string := ''; w: real := 0);
begin
Invoke(CreateP, BlockTxt, Txt, w);
end;
property Text: string read GetText write SetText;
property FontSize: real read InvokeReal(()->tb.FontSize) write Invoke(procedure(t: real) -> begin tb.FontSize := t; l.FontSize := t; end, value);
end;
///!#
ListBoxT = class(CommonControl)
protected
function tb: GListBox := element as GListBox;
procedure CreateP(w, h: real);
begin
element := new GListBox;
element.HorizontalAlignment := HorizontalAlignment.Stretch;
element.Margin := new Thickness(0, 0, 0, GlobalHMargin);
if w > 0 then
Width := w;
Height := h;
ActivePanel.Children.Add(tb);
end;
procedure AddP(s: string);
begin
var lbi := new ListBoxItem();
lbi.Content := s;
tb.Items.Add(lbi);
end;
procedure SortP := tb.Items.SortDescriptions.Add(new SortDescription('Content', ListSortDirection.Ascending));
procedure SortPDescending := tb.Items.SortDescriptions.Add(new SortDescription('Content', ListSortDirection.Descending));
public
event Click: procedure;
constructor Create(w: real := 0; h: real := 200):= Invoke(CreateP, w, h);
procedure Sort := Invoke(SortP);
procedure SortDescending := Invoke(SortPDescending);
procedure Add(s: string) := Invoke(AddP, s);
property FontSize: real read InvokeReal(()->tb.FontSize) write Invoke(procedure(t: real) -> tb.FontSize := t, value);
property Count: integer read InvokeInteger(()->tb.Items.Count);
property SelectedIndex: integer read InvokeInteger(()->tb.SelectedIndex) write Invoke(procedure(t: integer) -> tb.SelectedIndex := t, value);
property SelectedText: string read InvokeString(()->tb.SelectedItem as string) write Invoke(procedure(t: string) -> tb.SelectedItem := t, value);
end;
SliderT = class(CommonControl)
private
function sl: Slider := element as Slider;
function GetMinimum: real := InvokeReal(()->sl.Minimum);
procedure SetMinimumP(r: real) := sl.Minimum := r;
procedure SetMinimum(r: real) := Invoke(SetMinimumP, r);
function GetMaximum: real := InvokeReal(()->sl.Maximum);
procedure SetMaximumP(r: real) := sl.Maximum := r;
procedure SetMaximum(r: real) := Invoke(SetMaximumP, r);
function GetValue: real := InvokeReal(()->sl.Value);
procedure SetValueP(r: real) := sl.Value := r;
procedure SetValue(r: real) := Invoke(SetValueP, r);
function GetFrequency: real := InvokeReal(()->sl.TickFrequency);
procedure SetFrequencyP(r: real) := sl.TickFrequency := r;
procedure SetFrequency(r: real) := Invoke(SetFrequencyP, r);
protected
procedure CreateP(min, max, val: real);
begin
element := new Slider;
sl.ValueChanged += procedure(o, e) -> ValueChangedP;
sl.TickPlacement := System.Windows.Controls.Primitives.TickPlacement.BottomRight;
sl.Minimum := min;
sl.Maximum := max;
sl.Value := val;
ActivePanel.Children.Add(sl);
end;
procedure ValueChangedP := if ValueChanged <> nil then ValueChanged;
public
event ValueChanged: procedure;
constructor Create(min, max, val: real);
begin
Invoke(CreateP, min, max, val);
end;
property Minimum: real read GetMinimum write SetMinimum;
property Maximum: real read GetMaximum write SetMaximum;
property Value: real read GetValue write SetValue;
property Frequency: real read GetFrequency write SetFrequency;
end;
function Button(Txt: string; fontSize: real := 12): ButtonT;
function Button(x, y: integer; Txt: string; fontSize: real := 12): ButtonT;
function TextBlock(Txt: string; fontSize: real := 12): TextBlockT;
function TextBlock(x, y: real; Txt: string; fontSize: real := 12): TextBlockT;
function IntegerBlock(message: string; fontSize: real := 12; initValue: integer := 0): IntegerBlockT;
function RealBlock(message: string; fontSize: real := 12; initValue: real := 0): RealBlockT;
function TextBox(Txt: string := ''; w: real := 0): TextBoxT;
function ListBox(w: real := 0; h: real := 200): ListBoxT;
function IntegerBox(w: real := 0): IntegerBoxT;
function Slider(min: real := 0; max: real := 10; val: real := 0): SliderT;
procedure EmptyBlock(sz: integer := 16);
implementation
uses GraphWPF;
uses System.Windows;
uses System.Windows.Controls;
uses System.Windows.Controls.Primitives;
uses System.Windows.Media.Imaging;
var
StatusBarPanel: StatusBar;
LeftPanel, RightPanel, TopPanel, BottomPanel: Panel;
procedure AddPanel(var pp: StackPanel; wh: real; d: Dock; c: Color; Margin: real := 10);
begin
if pp <> nil then
exit;
var bb := new Border();
bb.Background := new SolidColorBrush(c);
var p := new StackPanel;
bb.Child := p;
//bb.Children.Add(p);
p.Margin := new System.Windows.Thickness(Margin);
if (d = Dock.Left) or (d = Dock.Right) then
begin
p.Orientation := Orientation.Vertical;
bb.Width := wh;
end
else
begin
p.Orientation := Orientation.Horizontal;
bb.Height := wh;
end;
p.Background := new SolidColorBrush(c);
DockPanel.SetDock(bb, d);
//MainDockPanel.children.Insert(MainDockPanel.children.Count-1,bb);
MainDockPanel.children.Insert(0, bb);
//MainDockPanel.children.Add(bb);
pp := p;
ActivePanel := p;
end;
procedure AddRightPanel(Width: real; c: Color; Margin: real) := Invoke(AddPanel, RightPanel, Width, Dock.Right, c, Margin);
procedure AddLeftPanel(Width: real; c: Color; Margin: real) := Invoke(AddPanel, LeftPanel, Width, Dock.Left, c, Margin);
procedure AddTopPanel(Height: real; c: Color; Margin: real) := Invoke(AddPanel, TopPanel, Height, Dock.Top, c, Margin);
procedure AddBottomPanel(Height: real; c: Color; Margin: real) := Invoke(AddPanel, BottomPanel, Height, Dock.Bottom, c, Margin);
procedure AddStatusBarP(Height: real);
begin
if StatusBarPanel <> nil then
exit;
var sb := new StatusBar;
sb.Height := 24;
DockPanel.SetDock(sb, Dock.Bottom);
// Всегда первая
MainDockPanel.children.Insert(0, sb);
StatusBarPanel := sb;
{var sbi := new StatusBarItem();
sbi.Content := 'sdghj';
sb.Items.Add(sbi);
sbi := new StatusBarItem();
sbi.Content := '222';
sb.Items.Add(sbi);}
end;
procedure AddStatusBar(Height: real) := Invoke(AddStatusBarP, Height);
function Button(Txt: string; fontSize: real): ButtonT := ButtonT.Create(Txt,fontSize);
function Button(x, y: integer; Txt: string; fontSize: real): ButtonT := ButtonT.Create(x, y, Txt,fontSize);
function TextBlock(Txt: string; fontsize: real): TextBlockT := TextBlockT.Create(Txt, fontsize);
function TextBlock(x, y: real; Txt: string; fontsize: real): TextBlockT := TextBlockT.Create(x, y, Txt, fontsize);
function IntegerBlock(message: string; fontsize: real; initValue: integer): IntegerBlockT := IntegerBlockT.Create(message, fontsize, initValue);
function RealBlock(message: string; fontsize: real; initValue: real): RealBlockT := RealBlockT.Create(message, fontsize, initValue);
function TextBox(Txt: string; w: real): TextBoxT := TextBoxT.Create(Txt, w);
function ListBox(w, h: real): ListBoxT := ListBoxT.Create(w, h);
function IntegerBox(w: real): IntegerBoxT := IntegerBoxT.Create(w);
function Slider(min, max, val: real): SliderT := SliderT.Create(min, max, val);
procedure EmptyBlock(sz: integer);
begin
var e := TextBlock('');
e.Height := sz;
e.Width := sz;
end;
procedure SetActivePanelInit;
begin
ActivePanel := MainWindow.MainPanel.Children[0] as Panel
end;
begin
Invoke(SetActivePanelInit);
end. |
unit FormExplore;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil,
Forms, Controls, StdCtrls, Graphics, Buttons, Grids, ExtCtrls;
type
TExplorerForm = class(TForm)
private
FPathPanel: TPanel;
FEditPath: TEdit;
FSBUpPath: TSpeedButton;
FFilenamePanel: TPanel;
FEditFilename: TEdit;
FSBOkFile: TSpeedButton;
FActiveDir: String;
FGridFiles: TStringGrid;
FilesDir: TStringList;
FoldersDir: TStringList;
procedure ResizeExplorer(Sender: TObject);
procedure FSBOkFileOnClick(Sender: TObject);
function OnlyName(const conpath: String): String;
procedure FGridFilesDblClick(Sender: TObject);
procedure FGridFilesSelection(Sender: TObject; aCol, aRow: Integer);
procedure SBUpPathClick(Sender: TObject);
procedure LoadDirectory(const Directory: String);
procedure FGridFilesPrepareCanvas(sender: TObject; aCol, aRow: Integer;aState: TGridDrawState);
procedure FGridFilesDrawCell(Sender: TObject; aCol, aRow: Integer;aRect: TRect; aState: TGridDrawState);
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
end;
procedure ShowExplorer(const Directory: String; titulo,mascara,lineaaprocesar:string;fijarnombre:boolean);
procedure CloseExplorer();
var
FResult : STring = '';
FileMasK : String;
LineaEjecutar : String;
implementation
Uses
MasterPaskalForm, MpGUI;
var
explorer: TExplorerForm = Nil;
procedure ShowExplorer(const Directory: String; titulo,mascara,lineaaprocesar:string;fijarnombre:boolean);
begin
if not Assigned(explorer) then
explorer := TExplorerForm.Create(Nil);
explorer.Caption:=titulo;
FileMask := Mascara;
LineaEjecutar := lineaaprocesar;
explorer.LoadDirectory(Directory);
Explorer.FEditFilename.ReadOnly:=fijarnombre;
explorer.Show;
FResult := '';
explorer.FGridFiles.ColWidths[0] := thispercent(100,explorer.FGridFiles.Width);
end;
Procedure CloseExplorer();
Begin
if Assigned(explorer) then explorer.Visible:=false;
End;
{ TExplorerForm }
constructor TExplorerForm.Create(TheOwner: TComponent);
begin
inherited CreateNew(TheOwner);
Caption := 'File Explorer';
//SetBounds(0, 0, 450, 350);
Constraints.MinWidth:= 450;
// This hides the extra cols, remove if you want full resize
//Constraints.MaxWidth:= 450;
Constraints.MinHeight:= 350;
// BY GUS
// Remove this comment if you want to make it non resizable
//BorderStyle := bssingle;
Position := poOwnerFormCenter;
BorderIcons := BorderIcons - [biminimize];
ShowInTaskBar:=sTAlways;
OnResize:=@ResizeExplorer;
FilesDir := TStringList.Create;
FoldersDir := TStringList.Create;
FPathPanel:= TPanel.Create(Self);
with FPathPanel do
begin
Parent:= Self;
AutoSize:= True;
Align:= alTop;
Caption:='';
BevelOuter:= bvNone;
end;
FEditPath := TEdit.Create(FPathPanel);
with FEditPath do
begin
Parent:= FPathPanel;
Align:= alLeft;
Width:= FPathPanel.ClientWidth - 50;
Anchors:= [akTop, akleft, akRight];
Font.Name := 'consolas';
Font.Size := 12;
Font.Color := clWhite;
Color := clBlack;
Alignment := taLeftJustify;
ReadOnly := True;
end;
FSBUpPath := TSpeedButton.Create(FPathPanel);
with FSBUpPath do
begin
Parent := FPathPanel;
Align:= alRight;
Width:= 42;
Anchors:= [akTop, akRight];
Hint := 'Go up';
ShowHint := True;
OnClick := @SBUpPathClick;
end;
FGridFiles := TStringGrid.Create(explorer);
with FGridFiles do
begin
Align:= alClient;
Font.Name := 'consolas';
Font.Size := 9;
FixedCols := 0;
FixedRows := 1;
RowCount := 1;
ColCount := 1;
GridLineWidth := 0;
ScrollBars := ssAutoVertical;
Options := Options - [goRangeSelect];
Cells[0,0] := 'Name';
FocusRectVisible := False;
OnDblClick := @FGridFilesDblClick;
OnSelection := @FGridFilesSelection;
OnPrepareCanvas := @FGridFilesPrepareCanvas;
OnDrawCell := @FGridFilesDrawCell;
Parent := Self;
end;
FFilenamePanel:= TPanel.Create(Self);
with FFilenamePanel do
begin
Parent:= Self;
AutoSize:= True;
Align:= alBottom;
Caption:='';
BevelOuter:= bvNone;
end;
FEditFilename := TEdit.Create(FFilenamePanel);
with FEditFilename do
begin
Parent := FFilenamePanel;
Align:= alLeft;
Width:= FFilenamePanel.ClientWidth - 50;
Anchors:= [akTop, akleft, akRight];
Font.Name := 'consolas';
Font.Size := 12;
Font.Color := clWhite;
Color := clBlack;
Alignment := taLeftJustify;
ReadOnly := True;
end;
FSBOkFile := TSpeedButton.Create(FFilenamePanel);
with FSBOkFile do
begin
Parent := FFilenamePanel;
Align:= alRight;
Width:= 42;
Anchors:= [akTop, akRight];
ShowHint := True;
Hint := 'Accept';
OnClick := @FSBOkFileOnClick;
end;
Form1.imagenes.GetBitmap(17,FSBOkFile.Glyph);
Form1.imagenes.GetBitmap(40,FSBUpPath.Glyph);
end;
destructor TExplorerForm.Destroy;
begin
FilesDir.Free;
FoldersDir.Free;
inherited Destroy;
end;
// Adjust grid when resizing
procedure TExplorerForm.ResizeExplorer(Sender: TObject);
var
GridWidth : integer;
begin
GridWidth := FGridFiles.Width;
FGridFiles.ColWidths[0]:= thispercent(100,GridWidth);
end;
procedure TExplorerForm.FGridFilesDblClick(Sender: TObject);
begin
if (FGridFiles.Row > 0) and (Copy(FGridFiles.Cells[0,FGridFiles.Row],1,3) = ' ' ) then
begin
FActiveDir := FActiveDir+DirectorySeparator+ Copy(FGridFiles.Cells[0,FGridFiles.Row],4,Length(FGridFiles.Cells[0,FGridFiles.Row]));
LoadDirectory(FActiveDir);
end;
if (FGridFiles.Row > 0) and (Copy(FGridFiles.Cells[0,FGridFiles.Row],1,3) <> ' ' ) then
begin
FEditFilename.Text := FGridFiles.Cells[0,FGridFiles.Row];
FSBOkFileOnClick(nil);
end;
end;
procedure TExplorerForm.FGridFilesSelection(Sender: TObject; aCol, aRow: Integer);
begin
FEditFilename.Text := FGridFiles.Cells[0,FGridFiles.Row];
if Copy(FEditFilename.Text,1,3) = ' ' then FEditFilename.Text := '';
end;
procedure TExplorerForm.FSBOkFileOnClick(Sender: TObject);
begin
if FEditFilename.Text = '' then
begin
explorer.visible := false;
exit;
end;
FResult := FActiveDir+DirectorySeparator+FEditFilename.Text;
FResult := StringReplace(FResult,' ','*',[rfReplaceAll, rfIgnoreCase]);
ProcessLines.Add(StringReplace(LineaEjecutar,'(-resultado-)',FResult,[rfReplaceAll, rfIgnoreCase]));
explorer.visible := false;
end;
procedure TExplorerForm.LoadDirectory(const Directory: String);
var
cont: Integer;
begin
FilesDir.Clear;
FoldersDir.Clear;
FGridFiles.RowCount := 1;
FindAllFiles(FilesDir, Directory, FileMask, False);
FindAllDirectories(FoldersDir, Directory, False);
if FoldersDir.Count > 0 then
for cont := 0 to FoldersDir.Count-1 do
begin
FGridFiles.RowCount := FGridFiles.RowCount+1;
FGridFiles.Cells[0,cont+1] := ' ' + OnlyName(FoldersDir[cont]);
end;
if FilesDir.Count > 0 then
for cont := 0 to FilesDir.Count-1 do
begin
FGridFiles.RowCount := FGridFiles.RowCount+1;
FGridFiles.Cells[0,FGridFiles.RowCount-1] := OnlyName(FilesDir[cont]);
end;
FEditPath.Text := Directory;
FActiveDir := Directory;
FEditFilename.Text := FGridFiles.Cells[0,FGridFiles.Row];
if Copy(FEditFilename.Text,1,3) = ' ' then FEditFilename.Text := '';
end;
function TExplorerForm.OnlyName(const conpath: String): String;
var
cont: Integer;
begin
result := '';
for cont := Length(conpath) downto 1 do
if conpath[cont] = DirectorySeparator then
begin
Result := Copy(conpath, cont+1, Length(conpath));
Break;
end;
end;
procedure TExplorerForm.FGridFilesPrepareCanvas(sender: TObject; aCol, aRow: Integer;
aState: TGridDrawState);
begin
if ((arow = FGridFiles.Row) and (arow>0)) then
begin
(Sender as TStringGrid).Canvas.Brush.Color := clblue;
(Sender as TStringGrid).Canvas.Font.Color:=clwhite
end;
end;
procedure TExplorerForm.FGridFilesDrawCell(Sender: TObject; aCol, aRow: Integer;
aRect: TRect; aState: TGridDrawState);
var
Bitmap : TBitmap;
myRect : TRect;
begin
if copy((sender as TStringGrid).Cells[0,arow],1,3) = ' ' then
begin
Bitmap:=TBitmap.Create;
Form1.imagenes.GetBitmap(41,Bitmap);
myRect := Arect;
myrect.Left:=myRect.Left+6;
myRect.Right := myrect.Left+16;
myrect.Bottom:=myrect.Top+16;
(sender as TStringGrid).Canvas.StretchDraw(myRect,bitmap);
Bitmap.free
end;
end;
procedure TExplorerForm.SBUpPathClick(Sender: TObject);
var
contador : integer;
begin
for contador := length(FActiveDir) downto 1 do
begin
if FActiveDir[contador] = DirectorySeparator then
begin
FActiveDir := copy(FActiveDir,1,contador-1);
LoadDirectory(FActiveDir);
Break;
end;
end;
end;
finalization
explorer.Free;
explorer := Nil;
END.
|
unit GLDTypes;
interface
uses
Windows, Controls, GL;
const
GLD_MAX_LISTITEMS = $FFFFFF;
type
PGLDMethod = ^TGLDMethod;
TGLDMethod = procedure of object;
PGLDAlphaFunc = ^TGLDAlphaFunc;
TGLDAlphaFunc =
(afNever,
afLess,
afEqual,
afLessOrEqual,
afGreater,
afNotEqual,
afGreaterOrEqual,
afAlways);
PGLDBlendFuncSourceFactor = ^TGLDBlendFuncSourceFactor;
TGLDBlendFuncSourceFactor =
(sfZero,
sfOne,
sfDstColor,
sfOneMinusDstColor,
sfSrcAlpha,
sfOneMinusSrcAlpha,
sfDstAlpha,
sfOneMinusDstAlpha,
sfSrcAlphaSaturate);
PGLDBlendFuncDestinationFactor = ^TGLDBlendFuncDestinationFactor;
TGLDBlendFuncDestinationFactor =
(dfZero,
dfOne,
dfSrcColor,
dfOneMinusSrcColor,
dfSrcAlpha,
dfOneMinusSrcAlpha,
dfDstAlpha,
dfOneMinusDstAlpha);
PGLDCullFace = ^TGLDCullFace;
TGLDCullFace =
(cfFront,
cfBack);
PGLDDepthFunc = ^TGLDDepthFunc;
TGLDDepthFunc =
(dfNever,
dfLess,
dfEqual,
dfLessOrEqual,
dfGreater,
dfNotEqual,
dfGreaterOrEqual,
dfAlways);
PGLDHintMode = ^TGLDHintMode;
TGLDHintMode =
(hmFastest,
hmNicest,
hmDontCare);
PGLDStencilFunc = ^TGLDStencilFunc;
TGLDStencilFunc =
(sfNever,
sfLess,
sfLessOrEqual,
sfGreater,
sfGreaterOrEqual,
sfEqual,
sfNotEqual,
sfAlways);
PGLDColorMask = ^TGLDColorMask;
TGLDColorMask = (Red, Green, Blue, Alpha);
PGLDColorMasks = ^TGLDColorMasks;
TGLDColorMasks = set of TGLDColorMask;
PGLDFogMode = ^TGLDFogMode;
TGLDFogMode =
(fmLinear,
fmExp,
fmExp2);
PGLDFrontFace = ^TGLDFrontFace;
TGLDFrontFace =
(ffCW,
ffCCW);
PGLDLogicOp = ^TGLDLogicOp;
TGLDLogicOp =
(loClear,
loSet,
loCopy,
loCopyInverted,
loNoop,
loInvert,
loAnd,
loNand,
loOr,
loNor,
loXor,
loEquiv,
loAndReverse,
loAndInverted,
loOrReverse,
loOrInverted);
PGLDPolygonMode = ^TGLDPolygonMode;
TGLDPolygonMode =
(pmPoint,
pmLine,
pmFill);
PGLDShadeModel = ^TGLDShadeModel;
TGLDShadeModel =
(smFlat,
smSmooth);
PGLDStencilOp = ^TGLDStencilOp;
TGLDStencilOp =
(soKeep,
soZero,
soReplace,
soIncr,
soDecr,
soInvert);
PGLDSelectionType = ^TGLDSelectionType;
TGLDSelectionType = (
GLD_ST_VERTICES,
GLD_ST_POLYGONS,
GLD_ST_OBJECTS);
PGLDSysClassType = ^TGLDSysClassType;
TGLDSysClassType = (
GLD_SYSCLASS_STANDARD,
GLD_SYSCLASS_COLOR,
GLD_SYSCLASS_COLOR4UB,
GLD_SYSCLASS_COLOR4F,
GLD_SYSCLASS_VECTOR4F,
GLD_SYSCLASS_ROTATION3D,
GLD_SYSCLASS_MATRIXFCLASS,
GLD_SYSCLASS_VECTOR3FLIST,
GLD_SYSCLASS_TEXCOORD2FLIST,
GLD_SYSCLASS_WORDLIST,
GLD_SYSCLASS_UINTLIST,
GLD_SYSCLASS_TRIFACELIST,
GLD_SYSCLASS_QUADFACELIST,
GLD_SYSCLASS_POLYGONLIST,
GLD_SYSCLASS_LIGHT,
GLD_SYSCLASS_LIGHTLIST,
GLD_SYSCLASS_CAMERA,
GLD_SYSCLASS_PERSPECTIVECAMERA,
GLD_SYSCLASS_SIDECAMERA,
GLD_SYSCLASS_FRONTCAMERA,
GLD_SYSCLASS_BACKCAMERA,
GLD_SYSCLASS_LEFTCAMERA,
GLD_SYSCLASS_RIGHTCAMERA,
GLD_SYSCLASS_TOPCAMERA,
GLD_SYSCLASS_BOTTOMCAMERA,
GLD_SYSCLASS_USERCAMERA,
GLD_SYSCLASS_CAMERASYSTEM,
GLD_SYSCLASS_CAMERALIST,
GLD_SYSCLASS_MATERIAL,
GLD_SYSCLASS_MATERIALLIST,
GLD_SYSCLASS_VISUALOBJECT,
GLD_SYSCLASS_EDITABLEOBJECT,
GLD_SYSCLASS_OBJECTLIST,
GLD_SYSCLASS_MOVEGIZMO,
GLD_SYSCLASS_ROTATEGIZMO,
GLD_SYSCLASS_GRID,
GLD_SYSCLASS_HOMEGRID,
GLD_SYSCLASS_ORTHOGRID,
GLD_SYSCLASS_ARCROTATIONGIZMO,
GLD_SYSCLASS_BOUNDINGBOX,
GLD_SYSCLASS_PLANE,
GLD_SYSCLASS_DISK,
GLD_SYSCLASS_RING,
GLD_SYSCLASS_BOX,
GLD_SYSCLASS_PYRAMID,
GLD_SYSCLASS_CYLINDER,
GLD_SYSCLASS_CONE,
GLD_SYSCLASS_TORUS,
GLD_SYSCLASS_SPHERE,
GLD_SYSCLASS_TUBE,
GLD_SYSCLASS_CUSTOMMESH,
GLD_SYSCLASS_TRIMESH,
GLD_SYSCLASS_QUADMESH,
GLD_SYSCLASS_POLYMESH,
GLD_SYSCLASS_MODIFY,
GLD_SYSCLASS_MODIFYC,
GLD_SYSCLASS_MODIFY_BEND,
GLD_SYSCLASS_MODIFY_ROTATE,
GLD_SYSCLASS_MODIFY_ROTATEXYZ,
GLD_SYSCLASS_MODIFY_SCALE,
GLD_SYSCLASS_MODIFY_SKEW,
GLD_SYSCLASS_MODIFY_TAPER,
GLD_SYSCLASS_MODIFY_TWIST,
GLD_SYSCLASS_MODIFYLIST,
GLD_SYSCLASS_3DS_FOG,
GLD_SYSCLASS_3DS_LAYERFOG,
GLD_SYSCLASS_3DS_DISTANCECUE,
GLD_SYSCLASS_3DS_ATMOSPHERE,
GLD_SYSCLASS_3DS_BITMAP,
GLD_SYSCLASS_3DS_SOLID,
GLD_SYSCLASS_3DS_GRADIENT,
GLD_SYSCLASS_3DS_BACKGROUND,
GLD_SYSCLASS_3DS_CAMERA,
GLD_SYSCLASS_3DS_CAMERALIST,
GLD_SYSCLASS_3DS_FILE,
GLD_SYSCLASS_3DS_LIGHT,
GLD_SYSCLASS_3DS_LIGHTLIST,
GLD_SYSCLASS_3DS_TEXTUREMAP,
GLD_SYSCLASS_3DS_AUTOREFLMAP,
GLD_SYSCLASS_3DS_MATERIAL,
GLD_SYSCLASS_3DS_MATERIALLIST,
GLD_SYSCLASS_3DS_BOXMAP,
GLD_SYSCLASS_3DS_MAPDATA,
GLD_SYSCLASS_3DS_FACELIST,
GLD_SYSCLASS_3DS_MESH,
GLD_SYSCLASS_3DS_MESHLIST,
GLD_SYSCLASS_3DS_AMBIENTDATA,
GLD_SYSCLASS_3DS_OBJECTDATA,
GLD_SYSCLASS_3DS_CAMERADATA,
GLD_SYSCLASS_3DS_TARGETDATA,
GLD_SYSCLASS_3DS_LIGHTDATA,
GLD_SYSCLASS_3DS_SPOTDATA,
GLD_SYSCLASS_3DS_NODEDATA,
GLD_SYSCLASS_3DS_NODE,
GLD_SYSCLASS_3DS_NODELIST,
GLD_SYSCLASS_3DS_QUAT,
GLD_SYSCLASS_3DS_SHADOW,
GLD_SYSCLASS_3DS_TCB,
GLD_SYSCLASS_3DS_BOOLKEY,
GLD_SYSCLASS_3DS_BOOLTRACK,
GLD_SYSCLASS_3DS_LIN1Key,
GLD_SYSCLASS_3DS_LIN1TRACK,
GLD_SYSCLASS_3DS_LIN3Key,
GLD_SYSCLASS_3DS_LIN3TRACK,
GLD_SYSCLASS_3DS_QUATKEY,
GLD_SYSCLASS_3DS_QUATTRACK,
GLD_SYSCLASS_3DS_MORPHKEY,
GLD_SYSCLASS_3DS_MORPHTRACK,
GLD_SYSCLASS_3DS_VIEW,
GLD_SYSCLASS_3DS_VIEWLIST,
GLD_SYSCLASS_3DS_LAYOUT,
GLD_SYSCLASS_3DS_DEFAULTVIEW,
GLD_SYSCLASS_3DS_VIEWPORT,
GLD_SYSCLASS_REPOSITORY,
GLD_SYSCLASS_STATEOPTIONS,
GLD_SYSCLASS_DRAWER,
GLD_SYSCLASS_SYSTEMRENDEROPTIONS,
GLD_SYSCLASS_SYSTEM);
PGLDSystemRenderMode = ^TGLDSystemRenderMode;
TGLDSystemRenderMode = (
rmSmooth,
rmWireframe,
rmBoundingBox);
PGLDSystemRenderOptionsParams = ^TGLDSystemRenderOptionsParams;
TGLDSystemRenderOptionsParams = packed record
RenderMode: TGLDSystemRenderMode;
DrawEdges: GLboolean;
EnableLighting: GLboolean;
TwoSidedLighting: GLboolean;
CullFacing: GLboolean;
CullFace: TGLDCullFace;
end;
PGLDSystemStatus = ^TGLDSystemStatus;
TGLDSystemStatus = (
GLD_SYSTEM_STATUS_NONE,
GLD_SYSTEM_STATUS_SELECT,
GLD_SYSTEM_STATUS_ARC_ROTATION,
GLD_SYSTEM_STATUS_PANNING,
GLD_SYSTEM_STATUS_ZOOMING,
GLD_SYSTEM_STATUS_VERTICES_MOVING,
GLD_SYSTEM_STATUS_POLYGONS_MOVING,
GLD_SYSTEM_STATUS_OBJECT_MOVING,
GLD_SYSTEM_STATUS_VERTICES_ROTATING,
GLD_SYSTEM_STATUS_POLYGONS_ROTATING,
GLD_SYSTEM_STATUS_OBJECT_ROTATING,
GLD_SYSTEM_STATUS_CREATING_VERTICES,
GLD_SYSTEM_STATUS_CREATING_POLYGONS1,
GLD_SYSTEM_STATUS_CREATING_POLYGONS2,
GLD_SYSTEM_STATUS_PLANE_DRAWING1,
GLD_SYSTEM_STATUS_PLANE_DRAWING2,
GLD_SYSTEM_STATUS_DISK_DRAWING1,
GLD_SYSTEM_STATUS_DISK_DRAWING2,
GLD_SYSTEM_STATUS_RING_DRAWING1,
GLD_SYSTEM_STATUS_RING_DRAWING2,
GLD_SYSTEM_STATUS_RING_DRAWING3,
GLD_SYSTEM_STATUS_BOX_DRAWING1,
GLD_SYSTEM_STATUS_BOX_DRAWING2,
GLD_SYSTEM_STATUS_BOX_DRAWING3,
GLD_SYSTEM_STATUS_CONE_DRAWING1,
GLD_SYSTEM_STATUS_CONE_DRAWING2,
GLD_SYSTEM_STATUS_CONE_DRAWING3,
GLD_SYSTEM_STATUS_CONE_DRAWING4,
GLD_SYSTEM_STATUS_CYLINDER_DRAWING1,
GLD_SYSTEM_STATUS_CYLINDER_DRAWING2,
GLD_SYSTEM_STATUS_CYLINDER_DRAWING3,
GLD_SYSTEM_STATUS_PYRAMID_DRAWING1,
GLD_SYSTEM_STATUS_PYRAMID_DRAWING2,
GLD_SYSTEM_STATUS_PYRAMID_DRAWING3,
GLD_SYSTEM_STATUS_SPHERE_DRAWING1,
GLD_SYSTEM_STATUS_SPHERE_DRAWING2,
GLD_SYSTEM_STATUS_TORUS_DRAWING1,
GLD_SYSTEM_STATUS_TORUS_DRAWING2,
GLD_SYSTEM_STATUS_TORUS_DRAWING3,
GLD_SYSTEM_STATUS_TORUS_DRAWING4,
GLD_SYSTEM_STATUS_TUBE_DRAWING1,
GLD_SYSTEM_STATUS_TUBE_DRAWING2,
GLD_SYSTEM_STATUS_TUBE_DRAWING3,
GLD_SYSTEM_STATUS_TUBE_DRAWING4,
GLD_SYSTEM_STATUS_USERCAMERA_DRAWING1,
GLD_SYSTEM_STATUS_USERCAMERA_DRAWING2);
PGLDSystemOperation = ^TGLDSystemOperation;
TGLDSystemOperation =
(GLD_SYSTEM_OPERATION_OBJECT_SELECT,
GLD_SYSTEM_OPERATION_DELETE_SELECTED_OBJECTS,
GLD_SYSTEM_OPERATION_DELETE_SELECTIONS,
GLD_SYSTEM_OPERATION_START_OBJECT_DRAWING,
GLD_SYSTEM_OPERATION_EDITED_OBJECT_CHANGED);
PGLDSystemNotificationEvent = ^TGLDSystemNotificationEvent;
TGLDSystemNotificationEvent = procedure(Sender: TObject; Operation: TGLDSystemOperation; Data: Pointer) of object;
PGLDAxis = ^TGLDAxis;
TGLDAxis = (
GLD_AXIS_X,
GLD_AXIS_Y,
GLD_AXIS_Z);
PGLDHomeGridAxis = ^TGLDHomeGridAxis;
TGLDHomeGridAxis = (gaXY, gaXZ, gaYZ);
PGLDWordArray = ^TGLDWordArray;
TGLDWordArray = array[1..GLD_MAX_LISTITEMS] of GLushort;
PGLDWordArrayData = ^TGLDWordArrayData;
TGLDWordArrayData = packed record
Data: PGLDWordArray;
Count: GLuint;
end;
PGLDUintArray = ^TGLDUintArray;
TGLDUintArray = array[1..GLD_MAX_LISTITEMS] of GLuint;
PGLDUintArrayData = ^TGLDUintArrayData;
TGLDUintArrayData = packed record
Data: PGLDUintArray;
Count: GLuint;
end;
PGLDPoint2D = ^TGLDPoint2D;
TGLDPoint2D = packed record
case GLubyte of
0: (X, Y: GLint);
1: (XPos, YPos: GLint);
2: (C: array[1..2] of GLint);
end;
PGLDColor3ub = ^TGLDColor3ub;
TGLDColor3ub = packed record
case GLubyte of
0: (R, G, B: GLubyte);
1: (Red, Green, Blue: GLubyte);
2: (C: array[1..3] of GLubyte);
3: (C0: array[0..2] of GLubyte);
end;
PGLDColor3ubArray = ^TGLDColor3ubArray;
TGLDColor3ubArray = array[1..GLD_MAX_LISTITEMS] of TGLDColor3ub;
PGLDColor4ub = ^TGLDColor4ub;
TGLDColor4ub = packed record
case GLubyte of
0: (R, G, B, A: GLubyte);
1: (Red, Green, Blue, Alpha: GLubyte);
2: (Color3ub: TGLDColor3ub; CA: GLubyte);
3: (C: array[1..4] of GLubyte);
4: (C0: array[0..3] of GLubyte);
end;
PGLDColor4ubArray = ^TGLDColor4ubArray;
TGLDColor4ubArray = array[1..GLD_MAX_LISTITEMS] of TGLDColor4ub;
PGLDColor3f = ^TGLDColor3f;
TGLDColor3f = packed record
case GLubyte of
0: (R, G, B: GLfloat);
1: (Red, Green, Blue: GLfloat);
2: (C: array[1..3] of GLfloat);
3: (C0: array[0..2] of GLfloat);
end;
PGLDColor3fArray = ^TGLDColor3fArray;
TGLDColor3fArray = array[1..GLD_MAX_LISTITEMS] of TGLDColor3f;
PGLDColor4f = ^TGLDColor4f;
TGLDColor4f = packed record
case GLubyte of
0: (R, G, B, A: GLfloat);
1: (Red, Green, Blue, Alpha: GLfloat);
2: (Color3f: TGLDColor3f; CA: GLfloat);
3: (C: array[1..4] of GLfloat);
4: (C0: array[0..3] of GLfloat);
end;
PGLDColor4fArray = ^TGLDColor4fArray;
TGLDColor4fArray = array[1..GLD_MAX_LISTITEMS] of TGLDColor4f;
PGLDVector3f = ^TGLDVector3f;
TGLDVector3f = packed record
case GLubyte of
0: (X, Y, Z: GLfloat);
1: (NX, NY, NZ: GLfloat);
2: (XPos, YPos, ZPos: GLfloat);
3: (C0: array[0..2] of GLfloat);
4: (C: array[1..3] of GLfloat);
end;
PGLDVector3fArray = ^TGLDVector3fArray;
TGLDVector3fArray = array[1..GLD_MAX_LISTITEMS] of TGLDVector3f;
PGLDVector3fArrayData = ^TGLDVector3fArrayData;
TGLDVector3fArrayData = packed record
Data: PGLDVector3fArray;
Count: GLuint;
end;
PGLDVector4f = ^TGLDVector4f;
TGLDVector4f = packed record
case GLubyte of
0: (X, Y, Z, W: GLfloat);
1: (NX, NY, NZ, NW: GLfloat);
2: (XPos, YPos, ZPos, Weight: GLfloat);
3: (C0: array[0..3] of GLfloat);
4: (C1: array[1..4] of GLfloat);
5: (Vector3f: TGLDVector3f; F4: GLfloat);
end;
PGLDVector4fArray = ^TGLDVector4fArray;
TGLDVector4fArray = array[1..GLD_MAX_LISTITEMS] of TGLDVector4f;
PGLDVector4fArrayData = ^TGLDVector4fArrayData;
TGLDVector4fArrayData = packed record
Data: PGLDVector4fArray;
Count: GLuint;
end;
PGLDVector3d = ^TGLDVector3d;
TGLDVector3d = packed record
case GLubyte of
0: (X, Y, Z: GLdouble);
1: (NX, NY, NZ: GLdouble);
2: (XPos, YPos, ZPos: GLdouble);
3: (C0: array[0..2] of GLdouble);
4: (C: array[1..3] of GLdouble);
end;
PGLDVector3dArray = ^TGLDVector3dArray;
TGLDVector3dArray = array[1..GLD_MAX_LISTITEMS] of TGLDVector3d;
PGLDVector3dArrayData = ^TGLDVector3dArrayData;
TGLDVector3dArrayData = packed record
Data: PGLDVector3dArray;
Count: GLuint;
end;
PGLDVector4d = ^TGLDVector4d;
TGLDVector4d = packed record
case GLubyte of
0: (X, Y, Z, W: GLdouble);
1: (NX, NY, NZ, NW: GLdouble);
2: (XPos, YPos, ZPos, Weight: GLdouble);
3: (C0: array[0..3] of GLdouble);
4: (C1: array[1..4] of GLdouble);
5: (Vector3d: TGLDVector3d; D4: GLdouble);
end;
PGLDVector4dArray = ^TGLDVector4dArray;
TGLDVector4dArray = array[1..GLD_MAX_LISTITEMS] of TGLDVector4d;
PGLDVector4dArrayData = ^TGLDVector4dArrayData;
TGLDVector4dArrayData = packed record
Data: PGLDVector4dArray;
Count: GLuint;
end;
PGLDQuadPoints3f = ^TGLDQuadPoints3f;
TGLDQuadPoints3f = packed record
case GLubyte of
0: (V1, V2, V3, V4: TGLDVector3f);
1: (V: array[1..4] of TGLDVector3f);
2: (V0: array[0..3] of TGLDVector3f);
end;
PGLDQuadPoints4f = ^TGLDQuadPoints4f;
TGLDQuadPoints4f = packed record
case GLubyte of
0: (V1, V2, V3, V4: TGLDVector4f);
1: (V: array[1..4] of TGLDVector4f);
2: (V0: array[0..3] of TGLDVector4f);
end;
PGLDQuadPoints3d = ^TGLDQuadPoints3d;
TGLDQuadPoints3d = packed record
case GLubyte of
0: (V1, V2, V3, V4: TGLDVector3d);
1: (V: array[1..4] of TGLDVector3d);
2: (V0: array[0..3] of TGLDVector3d);
end;
PGLDQuadPoints4d = ^TGLDQuadPoints4d;
TGLDQuadPoints4d = packed record
case GLubyte of
0: (V1, V2, V3, V4: TGLDVector4d);
1: (V: array[1..4] of TGLDVector4d);
2: (V0: array[0..3] of TGLDVector4d);
end;
PGLDQuadPatchData3f = ^TGLDQuadPatchData3f;
TGLDQuadPatchData3f = packed record
Points: TGLDVector3fArrayData;
Normals: TGLDVector3fArrayData;
Segs1: GLushort;
Segs2: GLushort;
end;
PGLDQuadPatchData4f = ^TGLDQuadPatchData4f;
TGLDQuadPatchData4f = packed record
Points: TGLDVector4fArrayData;
Normals: TGLDVector4fArrayData;
Segs1: GLushort;
Segs2: GLushort;
end;
PGLDQuadPatchData3d = ^TGLDQuadPatchData3d;
TGLDQuadPatchData3d = packed record
Points: TGLDVector3dArrayData;
Normals: TGLDVector3dArrayData;
Segs1: GLushort;
Segs2: GLushort;
end;
PGLDQuadPatchData4d = ^TGLDQuadPatchData4d;
TGLDQuadPatchData4d = packed record
Points: TGLDVector4dArrayData;
Normals: TGLDVector4dArrayData;
Segs1: GLushort;
Segs2: GLushort;
end;
PGLDTexCoord1f = ^TGLDTexCoord1f;
TGLDTexCoord1f = packed record
case GLubyte of
0: (S: GLfloat);
1: (C: array[1..1] of GLfloat);
2: (C0: array[0..0] of GLfloat);
end;
PGLDTexCoord1fArray = ^TGLDTexCoord1fArray;
TGLDTexCoord1fArray = array[1..GLD_MAX_LISTITEMS] of TGLDTexCoord1f;
PGLDTexCoord2f = ^TGLDTexCoord2f;
TGLDTexCoord2f = packed record
case GLubyte of
0: (S, T: GLfloat);
1: (C: array[1..2] of GLfloat);
2: (C0: array[0..1] of GLfloat);
end;
PGLDTexCoord2fArray = ^TGLDTexCoord2fArray;
TGLDTexCoord2fArray = array[1..GLD_MAX_LISTITEMS] of TGLDTexCoord2f;
PGLDTexCoord3f = ^TGLDTexCoord3f;
TGLDTexCoord3f = packed record
case GLubyte of
0: (S, T, R: GLfloat);
1: (C: array[1..3] of GLfloat);
2: (C0: array[0..2] of GLfloat);
end;
PGLDTexCoord3fArray = ^TGLDTexCoord3fArray;
TGLDTexCoord3fArray = array[1..GLD_MAX_LISTITEMS] of TGLDTexCoord3f;
PGLDTexCoord4f = ^TGLDTexCoord4f;
TGLDTexCoord4f = packed record
case GLubyte of
0: (S, T, R, Q: GLfloat);
1: (C: array[1..4] of GLfloat);
2: (C0: array[0..3] of GLfloat);
end;
PGLDTexCoord4fArray = ^TGLDTexCoord4fArray;
TGLDTexCoord4fArray = array[1..GLD_MAX_LISTITEMS] of TGLDTexCoord4f;
PGLDTexCoord1d = ^TGLDTexCoord1d;
TGLDTexCoord1d = packed record
case GLubyte of
0: (S: GLdouble);
1: (C: array[1..1] of GLdouble);
2: (C0: array[0..0] of GLdouble);
end;
PGLDTexCoord1dArray = ^TGLDTexCoord1dArray;
TGLDTexCoord1dArray = array[1..GLD_MAX_LISTITEMS] of TGLDTexCoord1d;
PGLDTexCoord2d = ^TGLDTexCoord2d;
TGLDTexCoord2d = packed record
case GLubyte of
0: (S, T: GLdouble);
1: (C: array[1..2] of GLdouble);
2: (C0: array[0..1] of GLdouble);
end;
PGLDTexCoord2dArray = ^TGLDTexCoord2dArray;
TGLDTexCoord2dArray = array[1..GLD_MAX_LISTITEMS] of TGLDTexCoord2d;
PGLDTexCoord3d = ^TGLDTexCoord3d;
TGLDTexCoord3d = packed record
case GLubyte of
0: (S, T, R: GLdouble);
1: (C: array[1..3] of GLdouble);
2: (C0: array[0..2] of GLdouble);
end;
PGLDTexCoord3dArray = ^TGLDTexCoord3dArray;
TGLDTexCoord3dArray = array[1..GLD_MAX_LISTITEMS] of TGLDTexCoord3d;
PGLDTexCoord4d = ^TGLDTexCoord4d;
TGLDTexCoord4d = packed record
case GLubyte of
0: (S, T, R, Q: GLdouble);
1: (C: array[1..4] of GLdouble);
2: (C0: array[0..3] of GLdouble);
end;
PGLDTexCoord4dArray = ^TGLDTexCoord4dArray;
TGLDTexCoord4dArray = array[1..GLD_MAX_LISTITEMS] of TGLDTexCoord4d;
PGLDTriFace = ^TGLDTriFace;
TGLDTriFace = packed record
case GLubyte of
0: (Points: array[1..3] of GLushort;
Smoothing: GLubyte;
Normals: array[1..3] of TGLDVector3f);
1: (Point1, Point2, Point3: GLushort;
SmoothMode: GLubyte;
Normal1, Normal2, Normal3: TGLDVector3f);
end;
PGLDTriFaceArray = ^TGLDTriFaceArray;
TGLDTriFaceArray = array[1..GLD_MAX_LISTITEMS] of TGLDTriFace;
PGLDQuadFace = ^TGLDQuadFace;
TGLDQuadFace = packed record
case GLubyte of
0: (Points: array[1..4] of GLushort;
Smoothing: GLubyte;
Normals: array[1..4] of TGLDVector3f);
1: (Point1, Point2, Point3, Point4: GLushort;
SmoothMode: GLubyte;
Normal1, Normal2, Normal3, Normal4: TGLDVector3f);
end;
PGLDQuadFaceArray = ^TGLDQuadFaceArray;
TGLDQuadFaceArray = array[1..GLD_MAX_LISTITEMS] of TGLDQuadFace;
PGLDPolygon = ^TGLDPolygon;
TGLDPolygon = TGLDWordArrayData;
PGLDPolygonArray = ^TGLDPolygonArray;
TGLDPolygonArray = array[1..GLD_MAX_LISTITEMS] of TGLDPolygon;
PGLDMatrixf = ^TGLDMatrixf;
TGLDMatrixf = packed record
case GLubyte of
0: (M0: array[0..3, 0..3] of GLfloat);
1: (M: array[1..4, 1..4] of GLfloat);
2: (_11, _12, _13, _14,
_21, _22, _23, _24,
_31, _32, _33, _34,
_41, _42, _43, _44: GLfloat);
end;
PGLDMatrixfArray = ^TGLDMatrixfArray;
TGLDMatrixfArray = array[1..GLD_MAX_LISTITEMS] of TGLDMatrixf;
PGLDMatrixd = ^TGLDMatrixd;
TGLDMatrixd = packed record
case GLubyte of
0: (M0: array[0..3, 0..3] of GLdouble);
1: (M: array[1..4, 1..4] of GLdouble);
2: (_11, _12, _13, _14,
_21, _22, _23, _24,
_31, _32, _33, _34,
_41, _42, _43, _44: GLdouble);
end;
PGLDMatrixdArray = ^TGLDMatrixdArray;
TGLDMatrixdArray = array[1..GLD_MAX_LISTITEMS] of TGLDMatrixd;
PGLDRotation3D = ^TGLDRotation3D;
TGLDRotation3D = packed record
case GLubyte of
0: (XAngle, YAngle, ZAngle: GLfloat);
1: (Angles: array[1..3] of GLfloat);
end;
PGLDViewport = ^TGLDViewport;
TGLDViewport = packed record
X, Y, Width, Height: GLsizei;
end;
PGLDKeys = ^TGLDKeys;
TGLDKeys = packed record
case GLubyte of
0: (KeyCode: array[GLubyte] of GLboolean);
1: (KeyChar: array[Char] of GLboolean);
end;
PGLDMouseButtons = ^TGLDMouseButtons;
TGLDMouseButtons = packed array[TMouseButton] of GLboolean;
PGLDLightParams = ^TGLDLightParams;
TGLDLightParams = packed record
Ambient: TGLDColor3ub;
Diffuse: TGLDColor3ub;
Specular: TGLDColor3ub;
Position: TGLDVector3f;
SpotDirection: TGLDVector3f;
SpotExponent: GLubyte;
SpotCutoff: GLubyte;
ConstantAttenuation: GLfloat;
LinearAttenuation: GLfloat;
QuadraticAttenuation: GLfloat;
end;
PGLDProjectionMode = ^TGLDProjectionMode;
TGLDProjectionMode =
(GLD_ORTHOGONAL,
GLD_PERSPECTIVE);
PGLDPerspectiveCameraParams = ^TGLDPerspectiveCameraParams;
TGLDPerspectiveCameraParams = packed record
Zoom: GLfloat;
Rotation: TGLDRotation3D;
Offset: TGLDVector3f;
end;
PGLDSideCameraParams = ^TGLDSideCameraParams;
TGLDSideCameraParams = packed record
Zoom: GLfloat;
Offset: TGLDVector3f;
end;
PGLDFrontCameraParams = ^TGLDFrontCameraParams;
TGLDFrontCameraParams = TGLDSideCameraParams;
PGLDBackCameraParams = ^TGLDBackCameraParams;
TGLDBackCameraParams = TGLDSideCameraParams;
PGLDLeftCameraParams = ^TGLDLeftCameraParams;
TGLDLeftCameraParams = TGLDSideCameraParams;
PGLDRightCameraParams = ^TGLDRightCameraParams;
TGLDRightCameraParams = TGLDSideCameraParams;
PGLDTopCameraParams = ^TGLDFrontCameraParams;
TGLDTopCameraParams = TGLDSideCameraParams;
PGLDBottomCameraParams = ^TGLDBottomCameraParams;
TGLDBottomCameraParams = TGLDSideCameraParams;
PGLDUserCameraParams = ^TGLDUserCameraParams;
TGLDUserCameraParams = packed record
Target: TGLDVector3f;
Rotation: TGLDRotation3D;
ZNear: GLfloat;
ZFar: GLfloat;
case ProjectionMode: TGLDProjectionMode of
GLD_ORTHOGONAL: (Zoom: GLfloat);
GLD_PERSPECTIVE: (Radius, Fov, Aspect: GLfloat);
end;
PGLDCameraParams = ^TGLDCameraParams;
TGLDCameraParams = packed record
Radius: GLfloat;
Rotation: TGLDRotation3D;
Target: TGLDVector3f;
Visible: GLboolean;
end;
PGLDMaterialParams = ^TGLDMaterialParams;
TGLDMaterialParams = packed record
Ambient: TGLDColor4f;
Diffuse: TGLDColor4f;
Specular: TGLDColor4f;
Emission: TGLDColor4f;
Shininess: GLubyte;
end;
PGLDHomeGridParams = ^TGLDHomeGridParams;
TGLDHomeGridParams = packed record
Axis: TGLDHomeGridAxis;
WidthSegs: GLushort;
LengthSegs: GLushort;
WidthStep: GLfloat;
LengthStep: GLfloat;
Position: TGLDVector3f;
end;
PGLDMinMaxCoords = ^TGLDMinMaxCoords;
TGLDMinMaxCoords = packed record
case GLubyte of
0: (MinX: GLfloat;
MaxX: GLfloat;
MinY: GLfloat;
MaxY: GLfloat;
MinZ: GLfloat;
MaxZ: GLfloat);
1: (XMin: GLfloat;
XMax: GLfloat;
YMin: GLfloat;
YMax: GLfloat;
ZMin: GLfloat;
ZMax: GLfloat);
end;
PGLDBoundingBoxParams = ^TGLDBoundingBoxParams;
TGLDBoundingBoxParams = packed record
Width: GLfloat;
Height: GLfloat;
Depth: GLfloat;
Center: TGLDVector3f;
end;
PGLDPlaneParams = ^TGLDPlaneParams;
TGLDPlaneParams = packed record
Color: TGLDColor3ub;
Length: GLfloat;
Width: GLfloat;
LengthSegs: GLushort;
WidthSegs: GLushort;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDDiskParams = ^TGLDDiskParams;
TGLDDiskParams = packed record
Color: TGLDColor3ub;
Radius: GLfloat;
Segments: GLushort;
Sides: GLushort;
StartAngle: GLfloat;
SweepAngle: GLfloat;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDRingParams = ^TGLDRingParams;
TGLDRingParams = packed record
Color: TGLDColor3ub;
InnerRadius: GLfloat;
OuterRadius: GLfloat;
Segments: GLushort;
Sides: GLushort;
StartAngle: GLfloat;
SweepAngle: GLfloat;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDBoxParams = ^TGLDBoxParams;
TGLDBoxParams = packed record
Color: TGLDColor3ub;
Length: GLfloat;
Width: GLfloat;
Height: GLfloat;
LengthSegs: GLushort;
WidthSegs: GLushort;
HeightSegs: GLushort;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDPyramidParams = ^TGLDPyramidParams;
TGLDPyramidParams = packed record
Color: TGLDColor3ub;
Width: GLfloat;
Depth: GLfloat;
Height: GLfloat;
WidthSegs: GLushort;
DepthSegs: GLushort;
HeightSegs: GLushort;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDCylinderParams = ^TGLDCylinderParams;
TGLDCylinderParams = packed record
Color: TGLDColor3ub;
Radius: GLfloat;
Height: GLfloat;
HeightSegs: GLushort;
CapSegs: Glushort;
Sides: GLushort;
StartAngle: GLfloat;
SweepAngle: GLfloat;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDConeParams = ^TGLDConeParams;
TGLDConeParams = packed record
Color: TGLDColor3ub;
Radius1: GLfloat;
Radius2: GLfloat;
Height: GLfloat;
HeightSegs: GLushort;
CapSegs: Glushort;
Sides: GLushort;
StartAngle: GLfloat;
SweepAngle: GLfloat;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDTorusParams = ^TGLDTorusParams;
TGLDTorusParams = packed record
Color: TGLDColor3ub;
Radius1: GLfloat;
Radius2: GLfloat;
Segments: GLushort;
Sides: GLushort;
StartAngle1: GLfloat;
SweepAngle1: GLfloat;
StartAngle2: GLfloat;
SweepAngle2: GLfloat;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDSphereParams = ^TGLDSphereParams;
TGLDSphereParams = packed record
Color: TGLDColor3ub;
Radius: GLfloat;
Segments: GLushort;
Sides: GLushort;
StartAngle1: GLfloat;
SweepAngle1: GLfloat;
StartAngle2: GLfloat;
SweepAngle2: GLfloat;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDTubeParams = ^TGLDTubeParams;
TGLDTubeParams = packed record
Color: TGLDColor3ub;
InnerRadius: GLfloat;
OuterRadius: GLfloat;
Height: GLfloat;
HeightSegs: GLushort;
CapSegs: GLushort;
Sides: GLushort;
StartAngle: GLfloat;
SweepAngle: GLfloat;
Position: TGLDVector3f;
Rotation: TGLDRotation3D;
end;
PGLDPrimitiveParams = ^TGLDPrimitiveParams;
TGLDPrimitiveParams = packed record
PrimitiveType: GLubyte;
UseNormals: GLboolean;
UseVertices: GLboolean;
Visible: GLboolean;
end;
PGLDBendParams = ^TGLDBendParams;
TGLDBendParams = packed record
Center: TGLDVector3f;
Angle: GLfloat;
Axis: TGLDAxis;
LimitEffect: GLboolean;
UpperLimit: GLfloat;
LowerLimit: GLfloat;
end;
PGLDRotateParams = ^TGLDRotateParams;
TGLDRotateParams = packed record
Center: TGLDVector3f;
Angle: GLfloat;
Axis: TGLDAxis;
end;
PGLDRotateXYZParams = ^TGLDRotateXYZParams;
TGLDRotateXYZParams = packed record
Center: TGLDVector3f;
AngleX: GLfloat;
AngleY: GLfloat;
AngleZ: GLfloat;
end;
PGLDScaleParams = ^TGLDScaleParams;
TGLDScaleParams = packed record
case GLubyte of
0: (ScaleX, ScaleY, ScaleZ: GLfloat);
1: (X, Y, Z: GLfloat);
2: (SX, SY, SZ: GLfloat);
3: (ScaleVector: TGLDVector3f);
end;
PGLDSkewParams = ^TGLDSkewParams;
TGLDSkewParams = packed record
Center: TGLDVector3f;
Amount: GLfloat;
Direction: GLfloat;
Axis: TGLDAxis;
LimitEffect: GLboolean;
UpperLimit: GLfloat;
LowerLimit: GLfloat;
end;
PGLDTaperEffectSet = ^TGLDTaperEffectSet;
TGLDTaperEffectSet = set of (X, Y, Z);
PGLDTaperParams = ^TGLDTaperParams;
TGLDTaperParams = packed record
Amount: GLfloat;
Axis: TGLDAxis;
Effect: GLubyte;
LimitEffect: GLboolean;
UpperLimit: GLfloat;
LowerLimit: GLfloat;
end;
PGLDTwistParams = ^TGLDTwistParams;
TGLDTwistParams = packed record
Center: TGLDVector3f;
Angle: GLfloat;
Axis: TGLDAxis;
LimitEffect: GLboolean;
UpperLimit: GLfloat;
LowerLimit: GLfloat;
end;
implementation
end.
|
//Se quiere calcular el precio que debe abonar para asegurar un automotor. Los parámetros que determinan el costo son:
//• Tipo de vehículo : C- Comercial ($200) ; P- Particular ($ 100)
//• Tipo de seguro : 1- Todo riesgo (+30%) ; 2- Básico (sin incremento)
//• Accidentes en el período anterior : S ; N ( – 5%)
//• Edad del conductor (más de 65 años + 10%)
Program calculaPrecio;
Var
vehiculo,accidente,seguro:char;
edad:byte;
precio:real;
Begin
write(' ingrese su tipo de vehiculo : C- Comercial / P- Particular: ');readln(vehiculo);
write('ingrese el tipo de seguro : 1- Todo riesgo / 2- Basico: ');readln(seguro);
write('Tuvo accidentes en el periodo anterior? S / N: ');readln(accidente);
write('Cual es la edad del conductor? ');readln(edad);
if(vehiculo = 'C') then
precio:= 200
Else
precio:=100;
If(seguro = '1') then
precio:= precio *1.3
Else
precio:=precio;
If(accidente = 'S') then
precio:= precio
Else
precio:= precio * 0.95;
If(edad > 65 ) then
precio:= precio*1.10
Else
precio:=precio;
writeln(' debe abonar :',precio:4:2);readln(precio);
end.
|
unit GameObject;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, GamePoints, strutils, contnrs;
type
{ TGameObject }
TGameObject = class
private
function GetO: TGamePoint;
function GetV: TGamePoint;
procedure SetO(AValue: TGamePoint);
procedure SetV(AValue: TGamePoint);
public
OX, OY, R: Double;
VX, VY: Double;
T: Integer;
procedure NextFrame;
property O: TGamePoint read GetO write SetO;
property V: TGamePoint read GetV write SetV;
constructor Create(AOX, AOY, AVX, AVY, AR: Double; AT: Integer = MaxInt);
constructor Create(AO, AV: TGamePoint; AR: Double; AT: Integer = MaxInt);
end;
implementation
{ TGameObject }
function TGameObject.GetO: TGamePoint;
begin
Result.X := OX;
Result.Y := OY;
end;
function TGameObject.GetV: TGamePoint;
begin
Result.X := VX;
Result.Y := VY;
end;
procedure TGameObject.SetO(AValue: TGamePoint);
begin
OX := AValue.X;
OY := AValue.Y;
end;
procedure TGameObject.SetV(AValue: TGamePoint);
begin
VX := AValue.X;
VY := AValue.Y;
end;
procedure TGameObject.NextFrame;
begin
OX += VX;
OY += VY;
T -= 1;
end;
constructor TGameObject.Create(AOX, AOY, AVX, AVY, AR: Double; AT: Integer);
begin
OX := AOX; OY := AOY;
VX := AVX; VY := AVY;
R := AR;
T := AT;
end;
constructor TGameObject.Create(AO, AV: TGamePoint; AR: Double; AT: Integer);
begin
O := AO;
V := AV;
R := AR;
T := AT;
end;
end.
|
PROGRAM Fill;
CONST
Width = 70;
Height = 20;
TYPE
Color = (S, B, R, G, W);
Canvas = ARRAY[1..Height] OF ARRAY[1..Width] OF Color;
VAR
mainCanvas: Canvas;
selectedPixel: Color;
FUNCTION ColorToChar(col: Color): CHAR;
BEGIN
IF col = S THEN
ColorToChar := 'S'
ELSE IF col = B THEN
ColorToChar := 'B'
ELSE IF col = R THEN
ColorToChar := 'R'
ELSE IF col = G THEN
ColorToChar := 'G'
ELSE IF col = W THEN
ColorToChar := '.'
END;
PROCEDURE InitCanvas;
VAR
i, j: INTEGER;
BEGIN
FOR i := 1 TO Height DO BEGIN
FOR j := 1 TO Width DO BEGIN
mainCanvas[i][j] := W;
END;
END;
END;
PROCEDURE DisplayCanvas;
VAR
i, j: INTEGER;
BEGIN
WriteLn();
WriteLn();
FOR i := 1 TO Height DO BEGIN
FOR j := 1 TO Width DO BEGIN
Write(' ', ColorToChar(mainCanvas[i][j]), ' ');
END;
WriteLn();
WriteLn();
END;
WriteLn();
END;
PROCEDURE SetPixel(x, y: INTEGER; col: Color);
BEGIN
IF (x <= Width) and (y <= Height) THEN
IF (x > 0) and (y > 0) then
mainCanvas[y][x] := col;
END;
PROCEDURE InitStandardCanvas;
BEGIN
SetPixel(4, 1, S);
SetPixel(3, 2, S);
SetPixel(4, 3, S);
SetPixel(4, 4, S);
SetPixel(5, 5, S);
SetPixel(5, 6, S);
SetPixel(5, 7, G);
SetPixel(5, 8, S);
SetPixel(4, 8, G);
SetPixel(3, 8, G);
SetPixel(5, 9, S);
SetPixel(1, 9, G);
SetPixel(2, 9, G);
SetPixel(6, 10, S);
SetPixel(6, 7, G);
SetPixel(7, 7, G);
SetPixel(8, 6, G);
SetPixel(9, 5, G);
SetPixel(10, 4, G);
SetPixel(11, 3, G);
SetPixel(12, 2, G);
SetPixel(12, 1, G);
END;
FUNCTION XYInRange(x, y: INTEGER): BOOLEAN;
BEGIN
XYInRange := true;
IF (x < 1) or (y < 1) THEN
XYInRange := false;
IF (x > 70) or (y > 20) then
XYInRange := false;
END;
PROCEDURE FloodFill(x, y: INTEGER; col: Color; VAR changedPixels: INTEGER);
BEGIN
IF XYInRange(x, y) AND NOT (mainCanvas[y][x] = col)
AND (mainCanvas[y][x] = selectedPixel) THEN BEGIN
SetPixel(x, y, col);
Inc(changedPixels);
FloodFill(x-1, y, col, changedPixels);
FloodFill(x+1, y, col, changedPixels);
FloodFill(x, y-1, col, changedPixels);
FloodFill(x, y+1, col, changedPixels);
END;
END;
FUNCTION AssertTrue(bool: BOOLEAN): STRING;
BEGIN
AssertTrue := 'X';
IF bool THEN
AssertTrue := 'OK'
END;
FUNCTION AssertFalse(bool: BOOLEAN): STRING;
BEGIN
AssertFalse := 'X';
IF not bool THEN
AssertFalse := 'OK'
END;
FUNCTION AssertFloodFill(x, y: INTEGER; col: Color; selectColor: Color; expectedResult: INTEGER): BOOLEAN;
VAR
changedPixels: INTEGER;
BEGIN
changedPixels := 0;
selectedPixel := selectColor;
FloodFill(x, y, col, changedPixels);
AssertFloodFill := (changedPixels = expectedResult);
END;
PROCEDURE RunFloodFill(x, y: INTEGER; col: Color; selectColor: Color);
VAR
changedPixels: INTEGER;
BEGIN
WriteLn('RunFloodFill(', x, ', ', y, ', ', col,', ', selectColor, ')');
changedPixels := 0;
selectedPixel := selectColor;
FloodFill(x, y, col, changedPixels);
WriteLn('changed pixels: ', changedPixels);
DisplayCanvas;
END;
BEGIN
InitCanvas;
InitStandardCanvas;
WriteLn('Test FloodFill');
WriteLn('AssertFloodFill(6, 3, R, W, 31) -> ', AssertTrue(AssertFloodFill(6, 3, R, W, 31)));
WriteLn('AssertFloodFill(5, 8, G, S, 2) -> ', AssertTrue(AssertFloodFill(5, 8, G, S, 2)));
WriteLn('AssertFloodFill(5, 8, G, S, 0) -> ', AssertTrue(AssertFloodFill(5, 8, G, S, 0)));
WriteLn('AssertFloodFill(5, 8, B, G, 7) -> ', AssertTrue(AssertFloodFill(5, 8, B, G, 7)));
WriteLn('AssertFloodFill(11, 3, S, G, 1) -> ', AssertTrue(AssertFloodFill(11, 3, S, G, 1)));
WriteLn('AssertFloodFill(15, 20, S, W, 1322) -> ', AssertTrue(AssertFloodFill(15, 20, S, W, 1322)));
WriteLn('AssertFloodFill(15, 22, W, S, 0) -> ', AssertTrue(AssertFloodFill(7, 22, W, S, 0)));
WriteLn;
WriteLn('Test XYInRange');
WriteLn('XYInRange(1, 1) -> ', AssertTrue(XYInRange(1, 1)));
WriteLn('XYInRange(1, 20) -> ', AssertTrue(XYInRange(1, 20)));
WriteLn('XYInRange(70, 1) -> ', AssertTrue(XYInRange(70, 1)));
WriteLn('XYInRange(70, 20) -> ', AssertTrue(XYInRange(70, 20)));
WriteLn('XYInRange(71, 20) -> ', AssertFalse(XYInRange(71, 20)));
WriteLn('XYInRange(70, 21) -> ', AssertFalse(XYInRange(70, 21)));
WriteLn('XYInRange(0, 10) -> ', AssertFalse(XYInRange(0, 10)));
WriteLn('XYInRange(10, 0) -> ', AssertFalse(XYInRange(10, 0)));
WriteLn;
// Can't test other letters since there would be a identifier error!
WriteLn('Test ColorToChar');
WriteLn('ColorToChar(S) = ''S'' -> ', AssertTrue(ColorToChar(S) = 'S'));
WriteLn('ColorToChar(R) = ''R'' -> ', AssertTrue(ColorToChar(R) = 'R'));
WriteLn('ColorToChar(B) = ''B'' -> ', AssertTrue(ColorToChar(B) = 'B'));
WriteLn('ColorToChar(G) = ''G'' -> ', AssertTrue(ColorToChar(G) = 'G'));
WriteLn('ColorToChar(W) = ''.'' -> ', AssertTrue(ColorToChar(W) = '.'));
WriteLn;
WriteLn('Press any key to continue ...');
ReadLn();
InitCanvas;
InitStandardCanvas;
WriteLn('Display FloodFill');
RunFloodFill(6, 3, R, W);
RunFloodFill(5, 8, G, S);
RunFloodFill(5, 8, G, S);
RunFloodFill(5, 8, B, G);
RunFloodFill(11, 3, S, G);
RunFloodFill(15, 20, S, W);
RunFloodFill(7, 22, W, S);
WriteLn;
END. |
{
Copyright (c) 2016 by Albert Molina
Copyright (c) 2017 by BlaiseCoin developers
Distributed under the MIT software license, see the accompanying file LICENSE
or visit http://www.opensource.org/licenses/mit-license.php.
This unit is a part of BlaiseCoin, a P2P crypto-currency.
}
unit UOpTransaction;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses UCrypto, UBlockChain, Classes, UAccounts;
Type
// Operations Type
TOpTransactionData = record
version : Word;
sender: Cardinal;
n_operation : Cardinal;
target: Cardinal;
amount: UInt64;
fee: UInt64;
payload: AnsiString;
public_key: TECDSA_Public;
sign: TECDSA_SIG;
end;
TOpChangeKeyData = record
version : Word;
account: Cardinal;
n_operation : Cardinal;
fee: UInt64;
payload: AnsiString;
public_key: TECDSA_Public;
new_accountkey: TAccountKey;
sign: TECDSA_SIG;
end;
TOpRecoverFundsData = record
version : Word;
account: Cardinal;
n_operation : Cardinal;
fee: UInt64;
end;
{ TOpTransaction }
TOpTransaction = class(TPCOperation)
private
FData : TOpTransactionData;
public
function GetOperationBufferToHash : TRawBytes; override;
function DoOperation(AccountTransaction : TPCSafeBoxTransaction; var errors : AnsiString) : Boolean; override;
function SaveToStream(Stream : TStream) : Boolean; override;
function LoadFromStream(Stream : TStream) : Boolean; override;
procedure AffectedAccounts(list : TList); override;
//
class function GetTransactionHashToSign(const trans : TOpTransactionData) : TRawBytes;
class function DoSignOperation(key : TECPrivateKey; var trans : TOpTransactionData) : Boolean;
class function OpType : Byte; override;
function OperationVersion : Word; override;
function OperationAmount : Int64; override;
function OperationFee : UInt64; override;
function OperationPayload : TRawBytes; override;
function SenderAccount : Cardinal; override;
function N_Operation : Cardinal; override;
property Data : TOpTransactionData read FData;
constructor Create(sender, n_operation, target: Cardinal; key: TECPrivateKey; amount, fee: UInt64; payload: AnsiString);
function toString : String; Override;
end;
{ TOpChangeKey }
TOpChangeKey = class(TPCOperation)
private
FData : TOpChangeKeyData;
public
class function GetOperationHashToSign(const op : TOpChangeKeyData) : TRawBytes;
class function DoSignOperation(key : TECPrivateKey; var op : TOpChangeKeyData) : Boolean;
class function OpType : Byte; override;
function GetOperationBufferToHash : TRawBytes; override;
function DoOperation(AccountTransaction : TPCSafeBoxTransaction; var errors : AnsiString) : Boolean; override;
function SaveToStream(Stream : TStream) : Boolean; override;
function LoadFromStream(Stream : TStream) : Boolean; override;
function OperationVersion : Word; override;
function OperationAmount : Int64; override;
function OperationFee : UInt64; override;
function OperationPayload : TRawBytes; override;
function SenderAccount : Cardinal; override;
function N_Operation : Cardinal; override;
procedure AffectedAccounts(list : TList); override;
constructor Create(account_number, n_operation: Cardinal; key:TECPrivateKey; new_account_key : TAccountKey; fee: UInt64; payload: AnsiString);
property Data : TOpChangeKeyData read FData;
function toString : String; Override;
end;
{ TOpRecoverFunds }
TOpRecoverFunds = class(TPCOperation)
private
FData : TOpRecoverFundsData;
public
class function OpType : Byte; override;
constructor Create(account_number, n_operation: Cardinal; fee: UInt64);
function GetOperationBufferToHash : TRawBytes; override;
function DoOperation(AccountTransaction : TPCSafeBoxTransaction; var errors : AnsiString) : Boolean; override;
function SaveToStream(Stream : TStream) : Boolean; override;
function LoadFromStream(Stream : TStream) : Boolean; override;
function OperationVersion : Word; override;
function OperationAmount : Int64; override;
function OperationFee : UInt64; override;
function OperationPayload : TRawBytes; override;
function SenderAccount : Cardinal; override;
function N_Operation : Cardinal; override;
procedure AffectedAccounts(list : TList); override;
property Data : TOpRecoverFundsData read FData;
function toString : String; override;
end;
procedure RegisterOperationsClass;
implementation
uses
SysUtils, UConst, ULog, UStreamOp;
procedure RegisterOperationsClass;
Begin
TPCOperationsComp.RegisterOperationClass(TOpTransaction);
TPCOperationsComp.RegisterOperationClass(TOpChangeKey);
TPCOperationsComp.RegisterOperationClass(TOpRecoverFunds);
End;
{ TOpTransaction }
procedure TOpTransaction.AffectedAccounts(list: TList);
begin
list.Add(TObject(FData.sender));
list.Add(TObject(FData.target));
end;
constructor TOpTransaction.Create(sender, n_operation, target: Cardinal;
key: TECPrivateKey; amount, fee: UInt64; payload: AnsiString);
begin
FData.version := CT_OpTransactionVersion;
FData.sender := sender;
FData.n_operation := n_operation;
FData.target := target;
FData.amount := amount;
FData.fee := fee;
FData.payload := payload;
FData.public_key := key.PublicKey;
if not DoSignOperation(key, FData) then begin
TLog.NewLog(lterror, Classname, 'Error signing a new Transaction');
FHasValidSignature := False;
end else FHasValidSignature := True;
end;
function TOpTransaction.DoOperation(AccountTransaction : TPCSafeBoxTransaction; var errors : AnsiString): Boolean;
var
totalamount : Cardinal;
sender, target : TAccount;
_h : TRawBytes;
begin
Result := False;
errors := '';
//
if FData.version <> CT_OpTransactionVersion then
begin
errors := Format('Unrecognised transaction version %d', [FData.version]);
exit;
end;
if (FData.sender >= AccountTransaction.FreezedSafeBox.AccountsCount) then
begin
errors := Format('Invalid sender %d', [FData.sender]);
exit;
end;
if (FData.target >= AccountTransaction.FreezedSafeBox.AccountsCount) then
begin
errors := Format('Invalid target %d', [FData.target]);
exit;
end;
if (FData.sender = FData.target) then begin
errors := Format('Sender = Target %d', [FData.sender]);
exit;
end;
if TAccountComp.IsAccountBlockedByProtocol(FData.sender, AccountTransaction.FreezedSafeBox.BlocksCount) then
begin
errors := Format('sender (%d) is blocked for protocol', [FData.sender]);
exit;
end;
if TAccountComp.IsAccountBlockedByProtocol(FData.target, AccountTransaction.FreezedSafeBox.BlocksCount) then
begin
errors := Format('target (%d) is blocked for protocol', [FData.target]);
exit;
end;
if (FData.amount <= 0) or (FData.amount > CT_MaxTransactionAmount) then
begin
errors := Format('Invalid amount %d (0 or max: %d)', [FData.amount, CT_MaxTransactionAmount]);
exit;
end;
if (FData.fee < 0) or (FData.fee > CT_MaxTransactionFee) then
begin
errors := Format('Invalid fee %d (max %d)', [FData.fee, CT_MaxTransactionFee]);
exit;
end;
if (length(FData.payload) > CT_MaxPayloadSize) then
begin
errors := 'Invalid Payload size:' + inttostr(length(FData.payload)) + ' (Max: ' + inttostr(CT_MaxPayloadSize) + ')';
end;
sender := AccountTransaction.Account(FData.sender);
target := AccountTransaction.Account(FData.target);
if ((sender.n_operation + 1) <> FData.n_operation) then
begin
errors := Format('Invalid n_operation %d (expected %d)', [FData.n_operation, sender.n_operation + 1]);
exit;
end;
totalamount := FData.amount + FData.fee;
if (sender.balance < totalamount) then
begin
errors := Format('Insuficient founds %d < (%d + %d = %d)', [sender.balance, FData.amount, FData.fee, totalamount]);
exit;
end;
if (target.balance + FData.amount > CT_MaxWalletAmount) then
begin
errors := Format('Target cannot accept this transaction due to max amount %d + %d = %d > %d', [target.balance, FData.amount, target.balance + FData.amount, CT_MaxWalletAmount]);
exit;
end;
// Build 1.4
if (FData.public_key.EC_OpenSSL_NID <> CT_TECDSA_Public_Nul.EC_OpenSSL_NID) and (not TAccountComp.Equal(FData.public_key, sender.accountkey)) then
begin
errors := Format('Invalid sender public key for account %d. Distinct from SafeBox public key! %s <> %s', [
FData.sender,
TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(FData.public_key)),
TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(sender.accountkey))]);
exit;
end;
// Check signature
_h := GetTransactionHashToSign(FData);
if (not TCrypto.ECDSAVerify(sender.accountkey, _h, FData.sign)) then
begin
errors := 'Invalid sign';
FHasValidSignature := False;
exit;
end else FHasValidSignature := True;
//
FPrevious_Sender_updated_block := sender.updated_block;
FPrevious_Destination_updated_block := target.updated_block;
// Do operation
Result := AccountTransaction.TransferAmount(FData.sender, FData.target, FData.n_operation, FData.amount, FData.fee, errors);
end;
class function TOpTransaction.DoSignOperation(key : TECPrivateKey; var trans : TOpTransactionData) : Boolean;
var
s : AnsiString;
_sign : TECDSA_SIG;
begin
if not Assigned(key.PrivateKey) then
begin
Result := False;
trans.sign.r:='';
trans.sign.s:='';
exit;
end;
s := GetTransactionHashToSign(trans);
try
_sign := TCrypto.ECDSASign(key.PrivateKey, s);
trans.sign := _sign;
Result := True;
except
trans.sign.r:='';
trans.sign.s:='';
Result := False;
end;
SetLength(s, 0);
end;
function TOpTransaction.GetOperationBufferToHash: TRawBytes;
var
ms : TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ms.WriteBuffer(FData.version, SizeOf(FData.version));
ms.WriteBuffer(FData.sender, SizeOf(FData.sender));
ms.WriteBuffer(FData.n_operation, SizeOf(FData.n_operation));
ms.WriteBuffer(FData.target, SizeOf(FData.target));
ms.WriteBuffer(FData.amount, SizeOf(FData.amount));
ms.WriteBuffer(FData.fee, SizeOf(FData.fee));
TStreamOp.WriteAnsiString(ms, FData.payload);
ms.WriteBuffer(FData.public_key.EC_OpenSSL_NID, SizeOf(FData.public_key.EC_OpenSSL_NID));
TStreamOp.WriteAnsiString(ms, FData.public_key.x);
TStreamOp.WriteAnsiString(ms, FData.public_key.y);
TStreamOp.WriteAnsiString(ms, FData.sign.r);
TStreamOp.WriteAnsiString(ms, FData.sign.s);
SetLength(Result, ms.Size);
ms.Position := 0;
ms.ReadBuffer(Result[1], ms.Size);
finally
ms.Free;
end;
end;
class function TOpTransaction.GetTransactionHashToSign(const trans: TOpTransactionData): TRawBytes;
var ms : TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ms.WriteBuffer(trans.version, SizeOf(trans.version));
ms.WriteBuffer(trans.sender, SizeOf(trans.sender));
ms.WriteBuffer(trans.n_operation, SizeOf(trans.n_operation));
ms.WriteBuffer(trans.target, SizeOf(trans.target));
ms.WriteBuffer(trans.amount, SizeOf(trans.amount));
ms.WriteBuffer(trans.fee, SizeOf(trans.fee));
TStreamOp.WriteAnsiString(ms, trans.payload);
ms.WriteBuffer(trans.public_key.EC_OpenSSL_NID, SizeOf(trans.public_key.EC_OpenSSL_NID));
TStreamOp.WriteAnsiString(ms, trans.public_key.x);
TStreamOp.WriteAnsiString(ms, trans.public_key.y);
SetLength(Result, ms.Size);
ms.Position := 0;
ms.ReadBuffer(Result[1], ms.Size);
finally
ms.Free;
end;
end;
function TOpTransaction.OperationVersion: Word;
begin
Result := FData.version;
end;
function TOpTransaction.OperationAmount: Int64;
begin
Result := FData.amount;
end;
function TOpTransaction.OperationFee: UInt64;
begin
Result := FData.fee;
end;
function TOpTransaction.OperationPayload: TRawBytes;
begin
Result := FData.payload;
end;
class function TOpTransaction.OpType: Byte;
begin
Result := CT_Op_Transaction;
end;
function TOpTransaction.SaveToStream(Stream: TStream): Boolean;
begin
Stream.WriteBuffer(CT_OpTransactionVersion, SizeOf(CT_OpTransactionVersion));
Stream.WriteBuffer(FData.sender, SizeOf(FData.sender));
Stream.WriteBuffer(FData.n_operation, SizeOf(FData.n_operation));
Stream.WriteBuffer(FData.target, SizeOf(FData.target));
Stream.WriteBuffer(FData.amount, SizeOf(FData.amount));
Stream.WriteBuffer(FData.fee, SizeOf(FData.fee));
TStreamOp.WriteAnsiString(Stream, FData.payload);
Stream.WriteBuffer(FData.public_key.EC_OpenSSL_NID, SizeOf(FData.public_key.EC_OpenSSL_NID));
TStreamOp.WriteAnsiString(Stream, FData.public_key.x);
TStreamOp.WriteAnsiString(Stream, FData.public_key.y);
TStreamOp.WriteAnsiString(Stream, FData.sign.r);
TStreamOp.WriteAnsiString(Stream, FData.sign.s);
Result := True;
end;
function TOpTransaction.LoadFromStream(Stream: TStream): Boolean;
begin
Result := False;
if Stream.Size - Stream.Position < 30 then
exit; // Invalid stream
Stream.ReadBuffer(FData.version, SizeOf(FData.version));
Stream.ReadBuffer(FData.sender, SizeOf(FData.sender));
Stream.ReadBuffer(FData.n_operation, SizeOf(FData.n_operation));
Stream.ReadBuffer(FData.target, SizeOf(FData.target));
Stream.ReadBuffer(FData.amount, SizeOf(FData.amount));
Stream.ReadBuffer(FData.fee, SizeOf(FData.fee));
if TStreamOp.ReadAnsiString(Stream, FData.payload) < 0 then
exit;
if Stream.Read(FData.public_key.EC_OpenSSL_NID, SizeOf(FData.public_key.EC_OpenSSL_NID)) < 0 then
exit;
if TStreamOp.ReadAnsiString(Stream, FData.public_key.x) < 0 then
exit;
if TStreamOp.ReadAnsiString(Stream, FData.public_key.y) < 0 then
exit;
if TStreamOp.ReadAnsiString(Stream, FData.sign.r) < 0 then
exit;
if TStreamOp.ReadAnsiString(Stream, FData.sign.s) < 0 then
exit;
Result := True;
end;
function TOpTransaction.SenderAccount: Cardinal;
begin
Result := FData.sender;
end;
function TOpTransaction.N_Operation: Cardinal;
begin
Result := FData.n_operation;
end;
function TOpTransaction.toString: String;
begin
Result := Format('Transaction from %s to %s amount:%s fee:%s (n_op:%d) payload size:%d', [
TAccountComp.AccountNumberToAccountTxtNumber(FData.sender),
TAccountComp.AccountNumberToAccountTxtNumber(FData.target),
TAccountComp.FormatMoney(FData.amount), TAccountComp.FormatMoney(FData.fee), FData.n_operation, Length(FData.payload)]);
end;
{ TOpChangeKey }
procedure TOpChangeKey.AffectedAccounts(list: TList);
begin
list.Add(TObject(FData.account));
end;
constructor TOpChangeKey.Create(account_number, n_operation: Cardinal; key:TECPrivateKey; new_account_key : TAccountKey; fee: UInt64; payload: AnsiString);
begin
FData.version := CT_OpChangeKeyVersion;
FData.account := account_number;
FData.n_operation := n_operation;
FData.fee := fee;
FData.payload := payload;
FData.public_key := key.PublicKey;
FData.new_accountkey := new_account_key;
if not DoSignOperation(key, FData) then
begin
TLog.NewLog(lterror, Classname, 'Error signing a new Change key');
FHasValidSignature := False;
end
else
FHasValidSignature := True;
end;
function TOpChangeKey.DoOperation(AccountTransaction : TPCSafeBoxTransaction; var errors: AnsiString): Boolean;
var account : TAccount;
begin
Result := False;
if FData.version <> CT_OpChangeKeyVersion then
begin
errors := Format('Unrecognised transaction version %d', [FData.version]);
exit;
end;
if (FData.account >= AccountTransaction.FreezedSafeBox.AccountsCount) then
begin
errors := 'Invalid account number';
exit;
end;
if TAccountComp.IsAccountBlockedByProtocol(FData.account, AccountTransaction.FreezedSafeBox.BlocksCount) then
begin
errors := 'account is blocked for protocol';
exit;
end;
if (FData.fee < 0) or (FData.fee > CT_MaxTransactionFee) then
begin
errors := 'Invalid fee: ' + Inttostr(FData.fee);
exit;
end;
account := AccountTransaction.Account(FData.account);
if ((account.n_operation + 1) <> FData.n_operation) then
begin
errors := 'Invalid n_operation';
exit;
end;
if (account.balance < FData.fee) then
begin
errors := 'Insuficient founds';
exit;
end;
if (length(FData.payload) > CT_MaxPayloadSize) then
begin
errors := 'Invalid Payload size:' + inttostr(length(FData.payload)) + ' (Max: ' + inttostr(CT_MaxPayloadSize) + ')';
end;
if not TAccountComp.IsValidAccountKey( FData.new_accountkey, errors ) then
begin
exit;
end;
// Build 1.4
if (FData.public_key.EC_OpenSSL_NID <> CT_TECDSA_Public_Nul.EC_OpenSSL_NID) and (not TAccountComp.Equal(FData.public_key, account.accountkey)) then
begin
errors := Format('Invalid public key for account %d. Distinct from SafeBox public key! %s <> %s', [
FData.account,
TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(FData.public_key)),
TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(account.accountkey))]);
exit;
end;
if not TCrypto.ECDSAVerify(account.accountkey, GetOperationHashToSign(FData), FData.sign) then
begin
errors := 'Invalid sign';
FHasValidSignature := False;
exit;
end
else
FHasValidSignature := True;
FPrevious_Sender_updated_block := account.updated_block;
Result := AccountTransaction.UpdateAccountkey(FData.account, FData.n_operation, FData.new_accountkey, FData.fee, errors);
end;
class function TOpChangeKey.DoSignOperation(key: TECPrivateKey; var op: TOpChangeKeyData): Boolean;
var s : AnsiString;
_sign : TECDSA_SIG;
begin
s := GetOperationHashToSign(op);
try
_sign := TCrypto.ECDSASign(key.PrivateKey, s);
op.sign := _sign;
Result := True;
except
on E:Exception do
begin
Result := False;
TLog.NewLog(lterror, ClassName, 'Error signing ChangeKey operation: ' + E.Message);
end;
end;
end;
function TOpChangeKey.GetOperationBufferToHash: TRawBytes;
var ms : TMemoryStream;
s : AnsiString;
begin
ms := TMemoryStream.Create;
try
ms.WriteBuffer(FData.version, SizeOf(FData.version));
ms.WriteBuffer(FData.account, SizeOf(FData.account));
ms.WriteBuffer(FData.n_operation, SizeOf(FData.n_operation));
ms.WriteBuffer(FData.fee, SizeOf(FData.fee));
TStreamOp.WriteAnsiString(ms, FData.payload);
ms.WriteBuffer(FData.public_key.EC_OpenSSL_NID, SizeOf(FData.public_key.EC_OpenSSL_NID));
TStreamOp.WriteAnsiString(ms, FData.public_key.x);
TStreamOp.WriteAnsiString(ms, FData.public_key.y);
s := TAccountComp.AccountKey2RawString(FData.new_accountkey);
TStreamOp.WriteAnsiString(ms, s);
TStreamOp.WriteAnsiString(ms, FData.sign.r);
TStreamOp.WriteAnsiString(ms, FData.sign.s);
ms.Position := 0;
SetLength(Result, ms.Size);
ms.ReadBuffer(Result[1], ms.Size);
finally
ms.Free;
end;
end;
class function TOpChangeKey.GetOperationHashToSign(const op: TOpChangeKeyData): TRawBytes;
var ms : TMemoryStream;
s : AnsiString;
begin
ms := TMemoryStream.Create;
try
ms.WriteBuffer(op.version, SizeOf(op.version));
ms.WriteBuffer(op.account, SizeOf(op.account));
ms.WriteBuffer(op.n_operation, SizeOf(op.n_operation));
ms.WriteBuffer(op.fee, SizeOf(op.fee));
TStreamOp.WriteAnsiString(ms, op.payload);
ms.WriteBuffer(op.public_key.EC_OpenSSL_NID, SizeOf(op.public_key.EC_OpenSSL_NID));
TStreamOp.WriteAnsiString(ms, op.public_key.x);
TStreamOp.WriteAnsiString(ms, op.public_key.y);
s := TAccountComp.AccountKey2RawString(op.new_accountkey);
TStreamOp.WriteAnsiString(ms, s);
ms.Position := 0;
SetLength(Result, ms.Size);
ms.ReadBuffer(Result[1], ms.Size);
finally
ms.Free;
end;
end;
function TOpChangeKey.OperationVersion: Word;
begin
Result := FData.version;
end;
function TOpChangeKey.OperationAmount: Int64;
begin
Result := 0;
end;
function TOpChangeKey.OperationFee: UInt64;
begin
Result := FData.fee;
end;
function TOpChangeKey.OperationPayload: TRawBytes;
begin
Result := FData.payload;
end;
class function TOpChangeKey.OpType: Byte;
begin
Result := CT_Op_Changekey;
end;
function TOpChangeKey.SaveToStream(Stream: TStream): Boolean;
begin
Stream.WriteBuffer(CT_OpChangeKeyVersion, SizeOf(CT_OpChangeKeyVersion));
Stream.WriteBuffer(FData.account, SizeOf(FData.account));
Stream.WriteBuffer(FData.n_operation, SizeOf(FData.n_operation));
Stream.WriteBuffer(FData.fee, SizeOf(FData.fee));
TStreamOp.WriteAnsiString(Stream, FData.payload);
Stream.WriteBuffer(FData.public_key.EC_OpenSSL_NID, SizeOf(FData.public_key.EC_OpenSSL_NID));
TStreamOp.WriteAnsiString(Stream, FData.public_key.x);
TStreamOp.WriteAnsiString(Stream, FData.public_key.y);
TStreamOp.WriteAnsiString(Stream, TAccountComp.AccountKey2RawString(FData.new_accountkey));
TStreamOp.WriteAnsiString(Stream, FData.sign.r);
TStreamOp.WriteAnsiString(Stream, FData.sign.s);
Result := True;
end;
function TOpChangeKey.LoadFromStream(Stream: TStream): Boolean;
var s : AnsiString;
begin
Result := False;
if Stream.Size - Stream.Position < 18 then
exit; // Invalid stream
Stream.ReadBuffer(FData.version, SizeOf(FData.version));
Stream.ReadBuffer(FData.account, SizeOf(FData.account));
Stream.ReadBuffer(FData.n_operation, SizeOf(FData.n_operation));
Stream.ReadBuffer(FData.fee, SizeOf(FData.fee));
if TStreamOp.ReadAnsiString(Stream, FData.payload) < 0 then
exit;
if Stream.Read(FData.public_key.EC_OpenSSL_NID, SizeOf(FData.public_key.EC_OpenSSL_NID)) < 0 then
exit;
if TStreamOp.ReadAnsiString(Stream, FData.public_key.x) < 0 then
exit;
if TStreamOp.ReadAnsiString(Stream, FData.public_key.y) < 0 then
exit;
if TStreamOp.ReadAnsiString(Stream, s) < 0 then
exit;
FData.new_accountkey := TAccountComp.RawString2Accountkey(s);
if TStreamOp.ReadAnsiString(Stream, FData.sign.r) < 0 then
exit;
if TStreamOp.ReadAnsiString(Stream, FData.sign.s) < 0 then
exit;
Result := True;
end;
function TOpChangeKey.SenderAccount: Cardinal;
begin
Result := FData.account;
end;
function TOpChangeKey.N_Operation: Cardinal;
begin
Result := FData.n_operation;
end;
function TOpChangeKey.toString: String;
begin
Result := Format('Change key of %s to new key: %s fee:%s (n_op:%d) payload size:%d', [
TAccountComp.AccountNumberToAccountTxtNumber(FData.account),
TAccountComp.GetECInfoTxt(FData.new_accountkey.EC_OpenSSL_NID),
TAccountComp.FormatMoney(FData.fee), FData.n_operation, Length(FData.payload)]);
end;
{ TOpRecoverFunds }
constructor TOpRecoverFunds.Create(account_number, n_operation : Cardinal; fee: UInt64);
begin
FData.version := CT_OpRecoverFundsVersion;
FData.account := account_number;
FData.n_operation := n_operation;
FData.fee := fee;
FHasValidSignature := True; // Recover funds doesn't need a signature
end;
procedure TOpRecoverFunds.AffectedAccounts(list: TList);
begin
list.Add(TObject(FData.account));
end;
function TOpRecoverFunds.DoOperation(AccountTransaction : TPCSafeBoxTransaction; var errors: AnsiString): Boolean;
var acc : TAccount;
begin
Result := False;
if FData.version <> CT_OpRecoverFundsVersion then
begin
errors := Format('Unrecognised transaction version %d', [FData.version]);
exit;
end;
if TAccountComp.IsAccountBlockedByProtocol(FData.account, AccountTransaction.FreezedSafeBox.BlocksCount) then
begin
errors := 'Account is blocked by protocol: account not mature';
exit;
end;
acc := AccountTransaction.Account(FData.account);
if acc.updated_block + CT_RecoverFundsWaitInactiveCount >= AccountTransaction.FreezedSafeBox.BlocksCount then
begin
errors := Format('Account is active to recover funds! Account %d Updated %d + %d >= BlockCount : %d', [FData.account, acc.updated_block, CT_RecoverFundsWaitInactiveCount, AccountTransaction.FreezedSafeBox.BlocksCount]);
exit;
end;
// Build 1.0.8 ... there was a BUG. Need to prevent recent created accounts
if (TAccountComp.AccountBlock(FData.account) + CT_RecoverFundsWaitInactiveCount >= AccountTransaction.FreezedSafeBox.BlocksCount) then
begin
errors := Format('AccountBlock is active to recover funds! AccountBlock %d + %d >= BlockCount : %d', [TAccountComp.AccountBlock(FData.account), CT_RecoverFundsWaitInactiveCount, AccountTransaction.FreezedSafeBox.BlocksCount]);
exit;
end;
if acc.n_operation + 1 <> FData.n_operation then
begin
errors := 'Invalid n_operation';
exit;
end;
if (FData.fee <= 0) or (FData.fee > CT_MaxTransactionFee) then
begin
errors := 'Invalid fee: ' + Inttostr(FData.fee);
exit;
end;
if acc.balance < FData.fee then
begin
errors := 'Insufficient funds';
exit;
end;
FPrevious_Sender_updated_block := acc.updated_block;
Result := AccountTransaction.TransferAmount(FData.account, FData.account, FData.n_operation, 0, FData.fee, errors);
end;
function TOpRecoverFunds.GetOperationBufferToHash: TRawBytes;
var ms : TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ms.WriteBuffer(FData.version, SizeOf(FData.version));
ms.WriteBuffer(FData.account, SizeOf(FData.account));
ms.WriteBuffer(FData.n_operation, SizeOf(FData.n_operation));
ms.WriteBuffer(FData.fee, SizeOf(FData.fee));
ms.Position := 0;
SetLength(Result, ms.Size);
ms.ReadBuffer(Result[1], ms.Size);
finally
ms.Free;
end;
end;
function TOpRecoverFunds.OperationVersion: Word;
begin
Result := FData.version;
end;
function TOpRecoverFunds.OperationAmount: Int64;
begin
Result := 0;
end;
function TOpRecoverFunds.OperationFee: UInt64;
begin
Result := FData.fee;
end;
function TOpRecoverFunds.OperationPayload: TRawBytes;
begin
Result := '';
end;
class function TOpRecoverFunds.OpType: Byte;
begin
Result := CT_Op_Recover;
end;
function TOpRecoverFunds.SaveToStream(Stream: TStream): Boolean;
begin
Stream.WriteBuffer(CT_OpRecoverFundsVersion, SizeOf(CT_OpRecoverFundsVersion));
Stream.WriteBuffer(FData.account, SizeOf(FData.account));
Stream.WriteBuffer(FData.n_operation, SizeOf(FData.n_operation));
Stream.WriteBuffer(FData.fee, SizeOf(FData.fee));
Result := True;
end;
function TOpRecoverFunds.LoadFromStream(Stream: TStream): Boolean;
begin
Result := False;
if Stream.Size - Stream.Position < 18 then
exit;
Stream.ReadBuffer(FData.version, SizeOf(FData.version));
Stream.ReadBuffer(FData.account, SizeOf(FData.account));
Stream.ReadBuffer(FData.n_operation, SizeOf(FData.n_operation));
Stream.ReadBuffer(FData.fee, SizeOf(FData.fee));
Result := True;
end;
function TOpRecoverFunds.SenderAccount: Cardinal;
begin
Result := FData.account;
end;
function TOpRecoverFunds.N_Operation: Cardinal;
begin
Result := FData.n_operation;
end;
function TOpRecoverFunds.toString: String;
begin
Result := Format('Recover funds of account %s fee:%s (n_op:%d)', [
TAccountComp.AccountNumberToAccountTxtNumber(FData.account),
TAccountComp.FormatMoney(FData.fee), fData.n_operation]);
end;
initialization
RegisterOperationsClass;
end.
|
unit ini_Unit_Meas_Form_Add;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ActnList, ExtCtrls, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, cxButtonEdit, cxLookAndFeelPainters, cxButtons,
Variants, Ibase;
type
Tini_Unit_Meas_Form_Add1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
ActionList1: TActionList;
ActionExit: TAction;
Label4: TLabel;
Name_Group_UnitM: TcxButtonEdit;
Name_Unit_Meas: TcxTextEdit;
Short_Name: TcxTextEdit;
Coefficient: TcxTextEdit;
Button1: TcxButton;
Button2: TcxButton;
procedure Name_Group_UnitMButtonClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Name_Group_UnitMKeyPress(Sender: TObject; var Key: Char);
procedure Name_Unit_MeasKeyPress(Sender: TObject; var Key: Char);
procedure Short_NameKeyPress(Sender: TObject; var Key: Char);
procedure ActionExitExecute(Sender: TObject);
procedure CoefficientKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
id_Group_UnitM : integer;
DBHandle:TISC_DB_HANDLE;
destructor Destroy; override;
end;
var
ini_Unit_Meas_Form_Add1 : Tini_Unit_Meas_Form_Add1;
implementation
uses ini_Group_UnitM_Form, ini_Unit_Meas_Form, GlobalSpr, pUtils;
{$R *.DFM}
destructor Tini_Unit_Meas_Form_Add1.Destroy;
begin
ini_Unit_Meas_Form_Add1 := nil;
inherited;
end;
procedure Tini_Unit_Meas_Form_Add1.Name_Group_UnitMButtonClick(Sender: TObject);
var
Res : Variant;
begin
Res := ShowGroupUnitMeas(Self, DBHandle, fsNormal, id_Group_UnitM);
if not VarIsNull(res) then begin
Name_Group_UnitM.Text := Res[1];
id_Group_UnitM := Res[0];
end;
end;
procedure Tini_Unit_Meas_Form_Add1.Button1Click(Sender: TObject);
begin
if Name_Group_UnitM.Text = '' then begin
ShowMessage('Ви не обрали групу одиниць виміру');
Exit;
end;
if Name_Unit_Meas.Text = 'Ви не ввели назву одиниці виміру' then begin
ShowMessage('');
Exit;
end;
if Short_Name.Text = '' then begin
ShowMessage('Ви не ввели стислу назву одиниці виміру');
Exit;
end;
if Coefficient.Text = '' then begin
ShowMessage('Ви не ввели коефіцієнт одиниці виміру');
Exit;
end;
ModalResult := mrOk;
end;
procedure Tini_Unit_Meas_Form_Add1.Button2Click(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure Tini_Unit_Meas_Form_Add1.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure Tini_Unit_Meas_Form_Add1.Name_Group_UnitMKeyPress(
Sender: TObject; var Key: Char);
begin
if Key = #13 then begin
Key := #0;
Name_Unit_Meas.SetFocus;
end;
end;
procedure Tini_Unit_Meas_Form_Add1.Name_Unit_MeasKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
Short_Name.SetFocus;
end;
end;
procedure Tini_Unit_Meas_Form_Add1.Short_NameKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
Coefficient.SetFocus;
end;
end;
procedure Tini_Unit_Meas_Form_Add1.ActionExitExecute(Sender: TObject);
begin
Button2Click(Sender);
end;
procedure Tini_Unit_Meas_Form_Add1.CoefficientKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
Button1.SetFocus;
Exit;
end;
if not (Key in [Decimalseparator,'0'..'9', #8, #9]) then Key := #0;
end;
end.
|
unit ChainsawMain;
{
Chainsaw - a tool to cut your logs down to size.
Designed to work with the Log4D implementation.
Based on the tool of the same name for log4j (http://log4j.apache.org).
Written by Keith Wood (kbwood@iprimus.com.au)
Version 1.0 - 19 September 2003.
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, StdCtrls, DBGrids, DB, DBClient, Log4D, Menus, ComCtrls,
IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, IdSocketHandle,
DateUtils, StrUtils;
type
TfrmChainsaw = class(TForm)
Label3: TLabel;
datStartDate: TDateTimePicker;
datStartTime: TDateTimePicker;
Label4: TLabel;
datEndDate: TDateTimePicker;
datEndTime: TDateTimePicker;
Label1: TLabel;
cmbLevelOp: TComboBox;
cmbLevel: TComboBox;
Label6: TLabel;
edtLogger: TEdit;
cmbLogger: TComboBox;
chkLoggerIgnoreCase: TCheckBox;
Label2: TLabel;
edtMessage: TEdit;
cmbMessage: TComboBox;
Label5: TLabel;
edtNDC: TEdit;
cmbNDC: TComboBox;
chkNDCIgnoreCase: TCheckBox;
btnClear: TButton;
dbgLogging: TDBGrid;
memDetails: TRichEdit;
stbStatus: TStatusBar;
srcLogging: TDataSource;
mnuMain: TMainMenu;
mniFile: TMenuItem;
mniOpen: TMenuItem;
mniSave: TMenuItem;
mniSep1: TMenuItem;
mniClear: TMenuItem;
mniSep2: TMenuItem;
mniExit: TMenuItem;
mniOptions: TMenuItem;
mniListen: TMenuItem;
mniConfigure: TMenuItem;
popMenu: TPopupMenu;
mniColumns: TMenuItem;
mniFormat: TMenuItem;
mniDefault: TMenuItem;
mniDebug: TMenuItem;
mniInfo: TMenuItem;
mniWarn: TMenuItem;
mniError: TMenuItem;
mniFatal: TMenuItem;
udpServer: TIdUDPServer;
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
btnClearLog: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure dbgLoggingColumnMoved(Sender: TObject; FromIndex,
ToIndex: Integer);
procedure dbgLoggingDrawDataCell(Sender: TObject; const Rect: TRect;
Field: TField; State: TGridDrawState);
procedure dbgLoggingTitleClick(Column: TColumn);
procedure FilterChange(Sender: TObject);
procedure mniClearClick(Sender: TObject);
procedure mniColumnClick(Sender: TObject);
procedure mniConfigureClick(Sender: TObject);
procedure mniFormatClick(Sender: TObject);
procedure mniListenClick(Sender: TObject);
procedure mniOpenClick(Sender: TObject);
procedure mniSaveClick(Sender: TObject);
procedure popMenuPopup(Sender: TObject);
procedure srcLoggingDataChange(Sender: TObject; Field: TField);
procedure udpServerUDPRead(AThread: TIdUDPListenerThread; AData: TBytes; ABinding: TIdSocketHandle);
private
FClearing: Boolean;
procedure Configure;
procedure LoadFile(const FileName: string);
procedure SetListening;
public
end;
var
frmChainsaw: TfrmChainsaw;
implementation
{$R *.dfm}
uses
IdGlobal,
ChainsawConfig,
ChainsawFiler,
ChainsawData;
{ Initialise level lists and dialogs. }
procedure TfrmChainsaw.FormCreate(Sender: TObject);
begin
FClearing := False;
cmbLevel.AddItem(Fatal.Name, Fatal);
cmbLevel.AddItem(Error.Name, Error);
cmbLevel.AddItem(Warn.Name, Warn);
cmbLevel.AddItem(Info.Name, Info);
cmbLevel.AddItem(Debug.Name, Debug);
cmbLevel.AddItem(All.Name, All);
cmbLevel.ItemIndex := 5;
dlgSave.InitialDir := ExtractFileDir(Application.ExeName);
dlgOpen.InitialDir := ExtractFileDir(Application.ExeName);
frmConfig := TfrmConfig.Create(Self);
Configure;
end;
{ Save current form location and size. }
procedure TfrmChainsaw.FormDestroy(Sender: TObject);
begin
frmConfig.SetCoords(Top, Left, Height, Width);
end;
{ Reset filter fields to defaults values. }
procedure TfrmChainsaw.btnClearClick(Sender: TObject);
begin
FClearing := True;
datStartDate.Date := EncodeDate(2001, 01, 01);
datStartTime.Time := EncodeTime(00, 00, 00, 000);
datEndDate.Date := EncodeDate(2099, 12, 31);
datEndTime.Time := EncodeTime(00, 00, 00, 000);
cmbLevelOp.ItemIndex := 0;
cmbLevel.ItemIndex := 5;
cmbLogger.ItemIndex := 0;
edtLogger.Text := '';
chkLoggerIgnoreCase.Checked := False;
cmbMessage.ItemIndex := 0;
edtMessage.Text := '';
cmbNDC.ItemIndex := 0;
edtNDC.Text := '';
chkNDCIgnoreCase.Checked := False;
datStartDate.SetFocus;
FClearing := False;
FilterChange(nil);
end;
{ Initialise controls from saved settings. }
procedure TfrmChainsaw.Configure;
var
Index: Integer;
FieldName: string;
begin
Top := frmConfig.MainTop;
Left := frmConfig.MainLeft;
Height := frmConfig.MainHeight;
Width := frmConfig.MainWidth;
for Index := 0 to srcLogging.DataSet.FieldCount - 1 do
begin
FieldName := frmConfig.FieldName[Index];
srcLogging.DataSet.FieldByName(FieldName).Index := Index;
srcLogging.DataSet.Fields[Index].Visible :=
frmConfig.FieldVisible[FieldName];
end;
udpServer.DefaultPort := frmConfig.SocketPort;
mniListen.Checked := frmConfig.SocketEnabled;
SetListening;
dbgLogging.Invalidate;
end;
{ Save new column positions. }
procedure TfrmChainsaw.dbgLoggingColumnMoved(Sender: TObject; FromIndex,
ToIndex: Integer);
var
Index: Integer;
begin
for Index := 0 to srcLogging.DataSet.FieldCount - 1 do
frmConfig.FieldIndex[srcLogging.DataSet.Fields[Index].FieldName] := Index;
end;
{ Draw the grid cells, taking into account format settings. }
procedure TfrmChainsaw.dbgLoggingDrawDataCell(Sender: TObject;
const Rect: TRect; Field: TField; State: TGridDrawState);
begin
if gdSelected in State then
begin
dbgLogging.Canvas.Font.Assign(dbgLogging.Font);
dbgLogging.Canvas.Brush.Color := clHighlight;
end
else if not frmConfig.FormatColumnOnly or
(Copy(Field.FieldName, 1, 5) = 'Level') then
begin
dbgLogging.Canvas.Font.Assign(frmConfig.FormatFont[
srcLogging.DataSet.FieldByName('LevelValue').AsInteger]);
dbgLogging.Canvas.Brush.Color := frmConfig.FormatBackground[
srcLogging.DataSet.FieldByName('LevelValue').AsInteger];
end;
dbgLogging.DefaultDrawDataCell(Rect, Field, State);
end;
{ Sort by column (ascending only) when header clicked. }
procedure TfrmChainsaw.dbgLoggingTitleClick(Column: TColumn);
begin
dtmLogging.AddSort(Column.FieldName);
end;
{ Update the filter applying to the logging dataset. }
procedure TfrmChainsaw.FilterChange(Sender: TObject);
const
DTFormat = 'dd/mm/yyyy hh:nn:ss ampm';
var
Filter: string;
Level: TLogLevel;
{ Create a text field clause for the filter. }
procedure SetTextCheck(FieldName, Value: string; const Op: Integer;
const IgnoreCase: Boolean);
begin
if Value <> '' then
begin
Filter := Filter + ' and ' +
IfThen(IgnoreCase, 'Upper(' + FieldName + ')', FieldName);
Value := IfThen(IgnoreCase, UpperCase(Value), Value);
case Op of
0: Filter := Filter + ' like ''%' + Value + '%'''; // Contains
1: Filter := Filter + ' = ''' + Value + ''''; // Equals
2: Filter := Filter + ' like ''' + Value + '%'''; // Starts with
3: Filter := Filter + ' like ''%' + Value + ''''; // Ends with
end;
end;
end;
begin
if FClearing then
Exit;
Filter := 'Timestamp >= ''' + FormatDateTime(DTFormat,
DateOf(datStartDate.Date) + TimeOf(datStartTime.Time)) + '''' +
' and Timestamp < ''' + FormatDateTime(DTFormat,
DateOf(datEndDate.Date) + TimeOf(datEndTime.Time)) + '''';
Level := TLogLevel(cmbLevel.Items.Objects[cmbLevel.ItemIndex]);
if Level.Level <> All.Level then
begin
Filter := Filter + ' and LevelValue ';
case cmbLevelOp.ItemIndex of
0: Filter := Filter + '>= '; // At least
1: Filter := Filter + '= '; // Equals
2: Filter := Filter + '<= '; // At most
end;
Filter := Filter + IntToStr(Level.Level);
end;
SetTextCheck('LoggerName', edtLogger.Text, cmbLogger.ItemIndex,
chkLoggerIgnoreCase.Checked);
SetTextCheck('Message', edtMessage.Text, cmbMessage.ItemIndex, False);
SetTextCheck('NDC', edtNDC.Text, cmbNDC.ItemIndex, chkNDCIgnoreCase.Checked);
srcLogging.DataSet.Filter := Filter;
end;
{ Load a logging file in XML format into the dataset. }
procedure TfrmChainsaw.LoadFile(const FileName: string);
begin
stbStatus.SimpleText := 'Loading file ' + FileName;
LoadFromFile(TClientDataSet(srcLogging.DataSet), FileName);
stbStatus.SimpleText := 'Loaded file ' + FileName;
end;
{ Empty the dataset after confirmation. }
procedure TfrmChainsaw.mniClearClick(Sender: TObject);
begin
if MessageDlg('Clear logging events?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
dtmLogging.EmptyDataSet;
end;
{ Toggle visibility of columns in the grid. }
procedure TfrmChainsaw.mniColumnClick(Sender: TObject);
var
MenuItem: TMenuItem;
FieldName: string;
begin
MenuItem := TMenuItem(Sender);
FieldName := srcLogging.DataSet.Fields[MenuItem.Tag].FieldName;
srcLogging.DataSet.Fields[MenuItem.Tag].Visible := not MenuItem.Checked;
// Save visibility setting
frmConfig.FieldVisible[FieldName] := not MenuItem.Checked;
end;
{ Bring up the configuration dialog. }
procedure TfrmChainsaw.mniConfigureClick(Sender: TObject);
begin
if frmConfig.ShowModal = mrOK then
Configure;
end;
{ Bring up the configuration for a particular level format. }
procedure TfrmChainsaw.mniFormatClick(Sender: TObject);
begin
frmConfig.SetFormatLevel(TMenuItem(Sender).Tag);
mniConfigureClick(mniConfigure);
end;
{ Toggle listening on input socket. }
procedure TfrmChainsaw.mniListenClick(Sender: TObject);
begin
mniListen.Checked := not mniListen.Checked;
SetListening;
end;
{ Select a file to load into the dataset. }
procedure TfrmChainsaw.mniOpenClick(Sender: TObject);
var
Listening: Boolean;
begin
Listening := mniListen.Checked;
mniListen.Checked := False;
with dlgOpen do
if Execute then
LoadFile(FileName)
else
mniListen.Checked := Listening;
SetListening;
end;
{ Select an output file and save the dataset contents as XML. }
procedure TfrmChainsaw.mniSaveClick(Sender: TObject);
begin
with dlgSave do
if Execute then
SaveToFile(TClientDataSet(srcLogging.DataSet), FileName);
end;
{ Update the list of columns in the popup menu for the grid. }
procedure TfrmChainsaw.popMenuPopup(Sender: TObject);
var
Index: Integer;
MenuItem: TMenuItem;
begin
for Index := 0 to mniColumns.Count - 1 do
begin
MenuItem := mniColumns[0];
mniColumns.Remove(MenuItem);
MenuItem.Free;
end;
for Index := 0 to srcLogging.DataSet.FieldCount - 1 do
begin
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := srcLogging.DataSet.Fields[Index].DisplayLabel;
MenuItem.Checked := srcLogging.DataSet.Fields[Index].Visible;
MenuItem.Tag := Index;
MenuItem.OnClick := mniColumnClick;
mniColumns.Add(MenuItem);
end;
end;
{ Update UDP server based on user settings. }
procedure TfrmChainsaw.SetListening;
begin
udpServer.Active := mniListen.Checked;
frmConfig.SocketEnabled := mniListen.Checked;
if udpServer.Active then
stbStatus.SimpleText := 'Listening on socket ' +
IntToStr(udpServer.DefaultPort) + ' (' + frmConfig.Threshold.Name + ')'
else
stbStatus.SimpleText := '';
end;
{ Display log event details as rich text when selected. }
procedure TfrmChainsaw.srcLoggingDataChange(Sender: TObject; Field: TField);
const
Cr = #13;
Tab = #9;
var
Index, Posn: Integer;
begin
with memDetails, srcLogging.DataSet do
begin
Text := '';
// Set details as straight text
Lines.Append(FieldByName('ThreadId').DisplayLabel + ':' + Tab +
FieldByName('ThreadId').AsString);
Lines.Append(FieldByName('Timestamp').DisplayLabel + ':' + Tab +
FieldByName('Timestamp').AsString);
Lines.Append(FieldByName('ElapsedTime').DisplayLabel + ':' + Tab +
FieldByName('ElapsedTime').AsString);
Lines.Append(FieldByName('LevelName').DisplayLabel + ':' + Tab +
FieldByName('LevelName').AsString +
' (' + FieldByName('LevelValue').AsString + ')');
Lines.Append(FieldByName('LoggerName').DisplayLabel + ':' + Tab +
FieldByName('LoggerName').AsString);
Lines.Append(FieldByName('Message').DisplayLabel +':' + Tab +
FieldByName('Message').AsString);
Lines.Append(FieldByName('NDC').DisplayLabel + ':' + Tab + Tab +
FieldByName('NDC').AsString);
Lines.Append(FieldByName('ErrorMessage').DisplayLabel +':' + Tab +
'(' + FieldByName('ErrorClass').AsString + ')' + Cr +
FieldByName('ErrorMessage').AsString);
// Apply formatting
SelStart := 0;
for Index := 0 to Lines.Count - 1 do
begin
Posn := Pos(Tab, Lines[Index]);
if Posn = 0 then
SelLength := Length(Lines[Index]) + 1
else
begin
SelLength := Posn;
SelAttributes.Style := [fsBold];
SelStart := SelStart + Posn;
Posn := Length(Lines[Index]) + 2 - Posn;
end;
SelLength := Posn;
SelAttributes.Style := [];
SelStart := SelStart + Posn;
end;
end;
end;
{ Respond to an incoming UDP message.
The expected format is fields separated by tabs (#9):
message#9threadId#9timestamp(yyyymmddhhnnsszzz)#9elapsedTime(ms)#9
levelName#9levelValue#9loggerName#9NDC#9errorMessage#9errorClass
This is the format used by default by the TLogIndySocketAppender. }
procedure TfrmChainsaw.udpServerUDPRead(AThread: TIdUDPListenerThread; AData: TBytes; ABinding: TIdSocketHandle);
var
Event, Value: string;
Index, Field: Integer;
Timestamp: TDateTime;
Message, ThreadId, LevelName, LoggerName: string;
NDC, ErrorMessage, ErrorClass: string;
ElapsedTime, LevelValue: Integer;
begin
Event := BytesToString(AData);
if Event = '' then
Exit;
ElapsedTime := 0;
LevelValue := 0;
Timestamp := Now;
Field := 1;
repeat
Index := Pos(#9, Event);
if Index > 0 then
begin
Value := Copy(Event, 1, Index - 1);
Delete(Event, 1, Index);
end
else
Value := Event;
case Field of
1: Message := Value;
2: ThreadId := Value;
3: try
Timestamp := EncodeDateTime(StrToInt(Copy(Value, 1, 4)),
StrToInt(Copy(Value, 5, 2)), StrToInt(Copy(Value, 7, 2)),
StrToInt(Copy(Value, 9, 2)), StrToInt(Copy(Value, 11, 2)),
StrToInt(Copy(Value, 13, 2)), StrToInt(Copy(Value, 15, 3)));
except on E: EConvertError do
// Ignore
end;
4: try
ElapsedTime := StrToInt(Value);
except on E: EConvertError do
ElapsedTime := 0;
end;
5: LevelName := Value;
6: try
LevelValue := StrToInt(Value);
except on E: EConvertError do
LevelValue := 0;
end;
7: LoggerName := Value;
8: NDC := Value;
9: ErrorMessage := Value;
10: ErrorClass := Value;
end;
Inc(Field);
until Index = 0;
if LevelValue >= frmConfig.Threshold.Level then
dtmLogging.AddLog(Message, ThreadId, Timestamp, ElapsedTime, LevelName,
LevelValue, LoggerName, NDC, ErrorMessage, ErrorClass);
end;
end.
|
unit AsupBirthDatesReportHeaders_PrintDM;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
frxClass, frxDBSet, frxDesgn, IBase, Forms, Variants,
Controls, FIBQuery, pFIBQuery, pFIBStoredProc, Dialogs, Math,
Asup_LoaderPrintDocs_Types, Asup_LoaderPrintDocs_Proc,
Asup_LoaderPrintDocs_WaitForm, ASUP_LoaderPrintDocs_Consts,
ASUP_LoaderPrintDocs_Messages, frxExportXLS, frxExportHTML, frxExportRTF, qFTools;
type
TDM = class(TDataModule)
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
Designer: TfrxDesigner;
DSetData: TpFIBDataSet;
ReportDsetData: TfrxDBDataset;
DSourceData: TDataSource;
RTFExport: TfrxRTFExport;
HTMLExport: TfrxHTMLExport;
XLSExport: TfrxXLSExport;
DSetGlobalData: TpFIBDataSet;
ReportDSetGlobalData: TfrxDBDataset;
Report: TfrxReport;
private
PDateForm:TDate;
PID_Work_Reason:integer;
PID_Month:integer;
PMonthText:string;
PDesignRep:Boolean;
public
constructor Create(AOwner:TComponent);reintroduce;
function PrintSpr(AParameter:TSimpleParam):variant;
property DateForm:TDate read PDateForm write PDateForm;
property ID_Work_Reason:integer read PID_Work_Reason write PID_Work_Reason;
property ID_Month:integer read PID_Month write PID_Month;
property MonthText:string read PMonthText write PMonthText;
property DesignRep:Boolean read PDesignRep write PDesignRep;
end;
implementation
{$R *.dfm}
const NameReport = '\AsupBirthDatesReport.fr3';
constructor TDM.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
PDateForm := Date;
PDesignRep:=False;
end;
function TDM.PrintSpr(AParameter:TSimpleParam):variant;
var wf:TForm;
begin
if AParameter.Owner is TForm then
wf:=ShowWaitForm(AParameter.Owner as TForm,wfPrepareData)
else wf:=ShowWaitForm(Application.MainForm,wfPrepareData);
try
Screen.Cursor:=crHourGlass;
if PID_Work_Reason=-1 then PID_Work_Reason:=0;
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM ASUP_REPORT_BIRTH_DATES_HEADERS('''+DateToStr(PDateForm)+''', '+IntToStr(PID_Month)+','+inttostr(PID_Work_Reason)+')';
DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT FIRM_NAME FROM INI_ASUP_CONSTS';
try
DB.Handle:=AParameter.DB_Handle;
DSetData.Open;
DSetGlobalData.OPen;
except
on E:Exception do
begin
AsupShowMessage(Error_Caption,e.Message,mtError,[mbOK]);
Screen.Cursor:=crDefault;
Exit;
end;
end;
if DSetData.IsEmpty then
begin
qFErrorDialog('За такими даними працівників не знайдено!');
Screen.Cursor:=crDefault;
Exit;
end;
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+Path_ALL_Reports+NameReport,True);
Report.Variables['NameV']:=QuotedStr(DSetGlobalData['FIRM_NAME']);
Report.Variables['Month']:=QuotedStr(MonthText);
Report.Variables['Forma']:=QuotedStr('Форма №33');
Screen.Cursor:=crDefault;
finally
CloseWaitForm(wf);
end;
if not DSetData.IsEmpty then
begin
if PDesignRep then Report.DesignReport
else Report.ShowReport;
Report.Free;
end;
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
end.
|
// the libpipe unit implements piping.
// piping from the point of view of the onedb cli, is a method
// of passing the output of a command as a input of another next command
//
// eg: ls /foo | grep file | split " " 3
// ^ pipe ^ pipe
//
// the above command consists of two pipe processors, "grep" and "split", and
// a cli plugin command, "ls"
//
// i don't know how to explain better, at this point, better look at the code
//
//
unit libpipe;
{$mode objfpc}
interface
uses libutils, sysutils;
const term_no_color = 0;
const term_fg_black = 1;
term_fg_dark_gray = 2;
term_fg_blue = 3;
term_fg_light_blue = 4;
term_fg_green = 5;
term_fg_light_green = 6;
term_fg_cyan = 7;
term_fg_light_cyan = 8;
term_fg_red = 9;
term_fg_light_red = 10;
term_fg_purple = 11;
term_fg_light_purple = 12;
term_fg_brown = 13;
term_fg_yellow = 14;
term_fg_light_gray = 15;
term_fg_white = 16;
const term_bg_black = 1;
term_bg_red = 2;
term_bg_green = 3;
term_bg_yellow = 4;
term_bg_blue = 5;
term_bg_magenta = 6;
term_bg_cyan = 7;
term_bg_light_gray = 8;
type TPipeCommand = class
protected
_input : TStrArray;
_output : TStrArray;
_arguments : TStrArray;
public
// create with input and arguments
constructor Create ( input: TStrArray; arguments: TStrArray );
// create only with arguments
constructor Create ( arguments: TStrArray );
// create without arguments
constructor Create ();
// adds a line to internal _input
procedure write_line( line: string ); virtual;
// adds an argument to internal _arguments
procedure add_arg( argument: string ); virtual;
// removes terminal string codes from a string
function decolorize( s: string ): string;
// adds terminal string codes to a string. use constants term_bg*, term_fg* for background / foreground colors
function colorize ( s: string; const fg_color: byte = 0; const bg_color: byte = 0): string;
// the pipe command compiler. should be overrided
function Compile( arguments: TStrArray ): string; virtual;
// the pipe command code impl. should be overrided
procedure Run(); virtual;
// access to pipe command generated output
property Output : TStrArray read _output;
// access to pipe command arguments list
property Arguments: TStrArray read _arguments;
// the command destructor. can be overidded.
destructor Free();
end;
Type TPipeCommand_Screen = class( TPipeCommand )
function Compile( args: TStrArray ): string; override;
procedure Run; override;
procedure write_line( line: string ); override;
end;
Type TPipeCommand_Grep = class( TPipeCommand )
public
function Compile( args: TStrArray ): string; override;
procedure Run; override;
end;
Type TPipeCommand_EGrep = class( TPipeCommand )
public
function Compile( args: TStrArray ): string; override;
procedure Run; override;
end;
Type TPipeCommand_Split = class( TPipeCommand )
public
function Compile( args: TStrArray ): string; override;
procedure Run; override;
end;
implementation
constructor TPipeCommand.Create( input: TStrArray; arguments: TStrArray );
var i: integer;
begin
setLength( _input, length( input ) );
for i:= 0 to length( input ) - 1 do begin
_input[i] := decolorize( input[i] );
end;
_arguments := arguments;
end;
constructor TPipeCommand.Create( arguments: TStrArray );
begin
_arguments := arguments;
end;
constructor TPipeCommand.create();
begin
end;
destructor TPipeCommand.Free();
begin
end;
procedure TPipeCommand.Run();
begin
end;
function TPipeCommand.Compile( arguments: TStrArray ): string;
begin
exit( 'abstract class TPipeCommand');
end;
function TPipeCommand.decolorize( s: string ): string;
var esc: boolean;
i : integer;
out: string;
begin
out := '';
esc := false;
i := 0;
for i := 1 to length( s ) do
begin
case s[i] of
#27: begin
esc := true;
end;
'0'..'9': begin
if esc = false then
out := concat( out, s[i] );
end;
';': begin
if esc = false then
out := concat( out, s[i] );
end;
'[': begin
if esc = false
then out := concat( out, s[i] );
end;
'm': begin
if esc = true
then esc := false
else out := concat( out, s[i] );
end else
begin
esc := false;
out := concat( out, s[i] );
end;
end;
end;
exit( out );
end;
procedure TPipeCommand.write_line( line: string );
begin
setLength( _input, length( _input ) + 1 );
_input[ length( _input ) - 1 ] := decolorize( line );
end;
procedure TPipeCommand.add_arg( argument: string );
begin
setLength( _arguments, length( _arguments ) + 1 );
_arguments[ length( _arguments ) - 1 ] := argument;
end;
function TPipeCommand.colorize( s: string; const fg_color: byte = 0; const bg_color: byte = 0 ): string;
var pref: string;
begin
pref := '';
case fg_color of
1:
pref := #27'[0;30m';
2:
pref := #27'[1;30m';
3:
pref := #27'[0;34m';
4:
pref := #27'[1;34m';
5:
pref := #27'[0;32m';
6:
pref := #27'[1;32m';
7:
pref := #27'[0;36m';
8:
pref := #27'[1;36m';
9:
pref := #27'[0;31m';
10:
pref := #27'[1;31m';
11:
pref := #27'[0;35m';
12:
pref := #27'[1;35m';
13:
pref := #27'[0;33m';
14:
pref := #27'[1;33m';
15:
pref := #27'[0;37m';
16:
pref := #27'[1;37m';
end;
case bg_color of
1:
pref := concat( pref, #27'[40m' );
2:
pref := concat( pref, #27'[41m' );
3:
pref := concat( pref, #27'[42m' );
4:
pref := concat( pref, #27'[43m' );
5:
pref := concat( pref, #27'[44m' );
6:
pref := concat( pref, #27'[45m' );
7:
pref := concat( pref, #27'[46m' );
8:
pref := concat( pref, #27'[47m' );
end;
if pref = ''
then exit( s )
else exit( concat( pref, s, #27'[0m' ) );
end;
{$i inc/screen.pas}
{$i inc/grep.pas}
{$i inc/split.pas}
{$i inc/egrep.pas}
end. |
unit Pospolite.View.JS.AST.Interfaces;
{
+-------------------------+
| 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.JS.Basics,
Pospolite.View.JS.AST.Basics;
type
{ IPLJSASTInterfaceBase }
IPLJSASTInterfaceBase = interface
['{E78D3A38-E060-47A4-8C78-737860A3CCA4}']
function GetChildren: TPLJSASTNodeList;
function GetID: TPLJSASTIdentifier;
property Children: TPLJSASTNodeList read GetChildren;
property ID: TPLJSASTIdentifier read GetID;
end;
{ IPLJSASTClass }
IPLJSASTClass = interface(IPLJSASTInterfaceBase)
['{0A88E531-9C30-4DFF-AFB3-0A6C67E5AFCE}']
function GetClassBody: TPLJSASTClassBody;
function GetClassSuper: TPLJSASTExpression;
property ClassBody: TPLJSASTClassBody read GetClassBody;
property ClassSuper: TPLJSASTExpression read GetClassSuper;
end;
{ IPLJSASTFunction }
IPLJSASTFunction = interface(IPLJSASTInterfaceBase)
['{2409CC29-B5C1-4035-9089-F7365B4CDE81}']
function GetAsync: TPLBool;
function GetBody: TPLJSASTNode;
function GetExpression: TPLBool;
function GetGenerator: TPLBool;
function GetParams(const AIndex: SizeInt): TPLJSASTExpression;
function GetStrict: TPLBool;
property Params[const AIndex: SizeInt]: TPLJSASTExpression read GetParams;
property Body: TPLJSASTNode read GetBody;
property Expression: TPLBool read GetExpression;
property Strict: TPLBool read GetStrict;
property Generator: TPLBool read GetGenerator;
property Async: TPLBool read GetAsync;
end;
implementation
end.
|
unit uSisPessoaList;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
BrowseConfig, Db, Menus, DBTables, Buttons, dxBar,
StdCtrls, ExtCtrls, Grids,
uParentList, dxGrClms, dxDBGrid, dxDBGridPrint, dxBarExtItems,
dxBarExtDBItems, dxCntner, dxTL, ComCtrls, dxtree, dxdbtree,
DBTreeView, ImgList, uSisPessoaFch, dxDBCtrl, ADODB, PowerADOQuery,
dxPSCore, dxPSdxTLLnk, dxPSdxDBCtrlLnk, dxPSdxDBGrLnk, siComp, siLangRT;
type
TSisPessoaList = class(TParentList)
Splitter: TSplitter;
DBTreeView: TDBTreeView;
quTreeView: TADOQuery;
quTreeViewIDTipoPessoa: TIntegerField;
quTreeViewPath: TStringField;
quTreeViewTipoPessoa: TStringField;
quTreeViewPathName: TStringField;
quBrowseIDPessoa: TIntegerField;
quBrowseCode: TIntegerField;
quBrowsePessoa: TStringField;
brwGridCode: TdxDBGridMaskColumn;
brwGridPessoa: TdxDBGridMaskColumn;
quBrowseAddress: TStringField;
quBrowseCity: TStringField;
quBrowseZipCode: TStringField;
quBrowseCountry: TStringField;
quBrowsePhone: TStringField;
quBrowseCell: TStringField;
quBrowseFax: TStringField;
quBrowseBeeper: TStringField;
quBrowseEmail: TStringField;
quBrowseIDState: TStringField;
quBrowseFederalID: TStringField;
quBrowseSalesTax: TStringField;
quBrowseSocialSecurity: TStringField;
quBrowseDriverLicense: TStringField;
quBrowseFirstName: TStringField;
quBrowseLastName: TStringField;
brwGridAddress: TdxDBGridMaskColumn;
brwGridCity: TdxDBGridMaskColumn;
brwGridZipCode: TdxDBGridMaskColumn;
brwGridCountry: TdxDBGridMaskColumn;
brwGridPhone: TdxDBGridMaskColumn;
brwGridCell: TdxDBGridMaskColumn;
brwGridFax: TdxDBGridMaskColumn;
brwGridBeeper: TdxDBGridMaskColumn;
brwGridEmail: TdxDBGridMaskColumn;
brwGridIDState: TdxDBGridMaskColumn;
brwGridFederalID: TdxDBGridMaskColumn;
brwGridSalesTax: TdxDBGridMaskColumn;
brwGridSocialSecurity: TdxDBGridMaskColumn;
brwGridDriverLicense: TdxDBGridMaskColumn;
brwGridFirstName: TdxDBGridMaskColumn;
brwGridLastName: TdxDBGridMaskColumn;
bbExportProgram: TdxBarButton;
Label2: TLabel;
Label1: TLabel;
cmbName: TComboBox;
Label3: TLabel;
edtName: TEdit;
Label4: TLabel;
cmbDocs: TComboBox;
edtDocs: TEdit;
quBrowseEmployeeID: TStringField;
brwGridEmployeeID: TdxDBGridColumn;
procedure FormCreate(Sender: TObject);
procedure DBTreeViewDblClick(Sender: TObject);
procedure bbListaNovoClick(Sender: TObject);
procedure bbListaOpenClick(Sender: TObject);
procedure brwGridDblClick(Sender: TObject);
procedure DBTreeViewGetSelectedIndex(Sender: TObject; Node: TTreeNode);
procedure FormDestroy(Sender: TObject);
procedure bbExportProgramClick(Sender: TObject);
procedure cmbNameChange(Sender: TObject);
private
{ Private declarations }
MyPathID: String;
MyIDPessoaTipo: Integer;
SisPessoaFch: TSisPessoaFch;
procedure OnBeforeStart; override;
procedure OnAfterStart; override;
public
{ Public declarations }
function ListParamRefresh : integer; override;
end;
implementation
{$R *.DFM}
uses uDM, uSystemTypes, uParamFunctions, uSisEntityWiz;
function TSisPessoaList.ListParamRefresh : integer;
var
sField, sField1 : String;
begin
Case cmbName.ItemIndex of
0 : sField := '';
1 : sField := 'P.PessoaFirstName';
2 : sField := 'P.PessoaLastName';
3 : sField := 'P.NomeJuridico';
end;
Case cmbDocs.ItemIndex of
0 : sField1 := '';
1 : sField1 := 'P.OrgaoEmissor';
2 : sField1 := 'P.CartTrabalho';
3 : sField1 := 'P.CustomerCard';
4 : sField1 := 'P.CPF';
end;
case cmbName.ItemIndex of
-1,0: //Todos
WhereBasicFilter[2] := '';
else //Add like
WhereBasicFilter[2] := sField+ ' Like ' + QuotedStr(trim(edtName.Text) + '%');
end;
case cmbDocs.ItemIndex of
-1,0: //Todos
WhereBasicFilter[3] := '';
else //Add like
WhereBasicFilter[3] := sField1+ ' Like ' + QuotedStr(trim(edtDocs.Text) + '%');
end;
ListRefresh;
DesligaAviso;
end;
procedure TSisPessoaList.FormCreate(Sender: TObject);
begin
inherited;
SisPessoaFch := TSisPessoaFch.Create(Self);
end;
procedure TSisPessoaList.OnBeforeStart;
begin
// Filtro as pessoas pelo tipo selecionado
if MyParametro <> '' then
begin
// O Tree View com os tipos de pessoas deverá abrir filtrado
with quTreeView do
begin
if Active then
Close;
Parameters.ParamByName('Path').Value := ParseParam(MyParametro, 'Path') + '%';
Open;
Splitter.Visible := False;
DBTreeView.Visible := (RecordCount > 1);
Splitter.Visible := (RecordCount > 1);
if not IsEmpty then
DBTreeView.LoadTreeView;
Close;
end;
if Trim(MyParametro) = 'Path=.001' then
HelpContext := 6
else if Trim(MyParametro) = 'Path=.002' then
HelpContext := 8
else if Trim(MyParametro) = 'Path=.003' then
HelpContext := 10
else if Trim(MyParametro) = 'Path=.004' then
HelpContext := 12
end;
if quTreeView.Parameters.ParambyName('Path').Value = '.001%' then
begin
quBrowse.MaxRecords := 1000;
pnlBasicFilter.Visible := True;
pnlExecuta.Visible := True;
LigaAviso;
end;
end;
procedure TSisPessoaList.OnAfterStart;
begin
with DBTreeView do
if Items.Count > 0 then
begin
Selected := Items[0];
DBTreeViewDblClick(Selected);
end;
end;
procedure TSisPessoaList.DBTreeViewDblClick(Sender: TObject);
var
i: Integer;
begin
inherited;
// Aplico o novo filtro no browse
WhereBasicFilter[1] := 'P.IDTipoPessoa = ' + IntTostr(DBTreeView.ActualIDItem);
for i := 0 to DBTreeView.Items.Count-1 do
DBTreeView.Items[i].ImageIndex := 35;
DBTreeView.Selected.ImageIndex := 34;
brwGridPessoa.Caption := DBTreeView.ActualName;
ListRefresh;
// Preencho os field de sugestão
with quBrowse do
begin
FilterFields.Clear;
FilterValues.Clear;
FilterFields.Add('IDTipoPessoa');
FilterValues.Add(IntTostr(DBTreeView.ActualIDItem));
end;
SisPessoaFch.Param := 'IDTipoPessoa=' + IntTostr(DBTreeView.ActualIDItem);
end;
procedure TSisPessoaList.bbListaNovoClick(Sender: TObject);
var
ID1, ID2: String;
begin
//inherited;
if SisPessoaFch.Start(btInc, quBrowse, False, ID1, ID2, '', '', brwGrid) then
begin
// Teoricamente a ficha faz tudo
end;
end;
procedure TSisPessoaList.bbListaOpenClick(Sender: TObject);
var
ID1, ID2: String;
begin
//inherited;
ID1 := quBrowseIDPessoa.AsString;
ID2 := '';
if SisPessoaFch.Start(btAlt, quBrowse, False, ID1, ID2, '', '', brwGrid) then
begin
// Teoricamente a ficha faz tudo
end;
end;
procedure TSisPessoaList.brwGridDblClick(Sender: TObject);
begin
//inherited;
if bbListaOpen.Enabled then
bbListaOpenClick(nil);
end;
procedure TSisPessoaList.DBTreeViewGetSelectedIndex(Sender: TObject;
Node: TTreeNode);
begin
inherited;
Node.SelectedIndex := Node.ImageIndex;
end;
procedure TSisPessoaList.FormDestroy(Sender: TObject);
begin
inherited;
SisPessoaFch.Free;
end;
procedure TSisPessoaList.bbExportProgramClick(Sender: TObject);
var
SisEntityWzd: TSisEntityWiz;
begin
inherited;
SisEntityWzd := nil;
Try
SisEntityWzd := TSisEntityWiz.Create(Self);
if SisEntityWzd.Start then
ListRefresh;
finally
FreeAndNil(SisEntityWzd);
end;
end;
procedure TSisPessoaList.cmbNameChange(Sender: TObject);
begin
inherited;
If TComboBox(Sender).ItemIndex = 0 then
if TComboBox(Sender).Name = 'cmbName' then
edtName.Text := ''
else
edtDocs.Text := '';
LigaAviso;
end;
Initialization
RegisterClass(TSisPessoaList);
end.
|
unit Common.Entities.Gamesituation;
interface
uses System.Classes,System.Generics.Collections,Neon.Core.Attributes,Common.Entities.Player,
Common.Entities.GameType,Common.Entities.Card,Common.Entities.Bet;
type
TGameState=(gsNone,gsBidding,gsCallKing,gsGetTalon,gsFinalBet,gsPlaying,gsTerminated);
TGameResults=record
private
function GetTotal: Smallint;
function GetGrandTotal: Smallint;
public
Points: Double;
Game:Smallint;
Minus10Count:Smallint;
Minus10:Smallint;
ContraGame:Smallint;
KingUlt:Smallint;
PagatUlt:Smallint;
VogelII:Smallint;
VogelIII:Smallint;
VogelIV:Smallint;
Trull:Smallint;
AllKings:Smallint;
CatchPagat:Smallint;
CatchKing:Smallint;
CatchXXI:Smallint;
Valat:Smallint;
Doubles:Smallint;
property Total:Smallint read GetTotal;
property GrandTotal:Smallint read GetGrandTotal;
procedure SetPoints(const Value: Double);
function PointsAsString:String;
end;
TGameSituation<T:TPlayer>=class(TObject)
private
FBeginner: String;
FPlayers: TPlayers<T>;
FState: TGameState;
FTurnOn: String;
FBestBet: Smallint;
FGameType: String;
FGamer: String;
FKingSelected: TCardKey;
FCardsLayedDown: TCards;
FGameInfo: TStringList;
FAddBets: TAddBets;
FTeam2Results: TGameResults;
FTeam1Results: TGameResults;
FDoubles: SmallInt;
FRoundNo: Smallint;
FGameNo:Smallint;
public
property Players: TPlayers<T> read FPlayers write FPlayers;
property State: TGameState read FState write FState;
property TurnOn:String read FTurnOn write FTurnOn;
property Beginner: String read FBeginner write FBeginner;
property GameType:String read FGameType write FGameType;
property AddBets:TAddBets read FAddBets write FAddBets;
property Doubles:SmallInt read FDoubles write FDoubles;
property Gamer:String read FGamer write FGamer;
property BestBet:Smallint read FBestBet write FBestBet;
property KingSelected:TCardKey read FKingSelected write FKingSelected;
property CardsLayedDown:TCards read FCardsLayedDown write FCardsLayedDown;
property GameInfo:TStringList read FGameInfo write FGameInfo;
property Team1Results:TGameResults read FTeam1Results write FTeam1Results;
property Team2Results:TGameResults read FTeam2Results write FTeam2Results;
property RoundNo:Smallint read FRoundNo write FRoundNo;
property GameNo:Smallint read FGameNo write FGameNo;
constructor Create;
destructor Destroy;override;
function Clone:TGameSituation<TPlayer>;
function FirstPlayerGamesEnabled:Boolean;
end;
implementation
uses
System.SysUtils, System.Math;
{ TGameSituation }
function TGameSituation<T>.Clone: TGameSituation<TPlayer>;
var itm:T;
itm2:TPlayer;
begin
Result:=TGameSituation<TPlayer>.Create;
Result.Beginner:=FBeginner;
Result.TurnOn:=FTurnOn;
Result.Gamer:=FGamer;
Result.BestBet:=FBestBet;
Result.Doubles:=FDoubles;
Result.RoundNo:=FRoundNo;
Result.GameNo:=FGameNo;
Result.KingSelected:=FKingSelected;
for itm in FPlayers do begin
itm2:=TPlayer.Create(itm.Name);
itm2.Assign(itm);
Result.Players.Add(itm2);
end;
Result.GameType:=FGameType;
Result.State:=FState;
Result.GameInfo:=TStringList.Create;
Result.GameInfo.Assign(FGameInfo);
Result.AddBets:=FAddBets;
Result.Team1Results:=FTeam1Results;
Result.Team2Results:=FTeam2Results;
Result.CardsLayedDown.Assign(FCardsLayedDown);
// REsult.CardsLayedDown.AddItem(T13,ctTarock,1,13,0);
// REsult.CardsLayedDown.AddItem(T17,ctTarock,5,17,0);
end;
constructor TGameSituation<T>.Create;
begin
inherited Create;
FPlayers:=TPlayers<T>.Create(True);
FState:=gsNone;
FGameInfo:=TStringList.Create;
FAddBets.ContraGame.BetType:=abtBet;
FAddBets.ContraGame.Team:=ttTeam1;
FRoundNo:=0;
FCardsLayedDown:=TCards.Create(True);
end;
destructor TGameSituation<T>.Destroy;
begin
FreeAndNil(FPlayers);
FreeAndNil(FCardsLayedDown);
FreeAndNil(FGameInfo);
inherited;
end;
function TGameSituation<T>.FirstPlayerGamesEnabled: Boolean;
var player:TPlayer;
begin
if (State=gsBidding) then begin
Result:=True;
for player in Players do begin
if (player.Name=Beginner) and (player.BetState<>btHold) then begin
Result:=False;
Break;
end
else if (player.Name<>Beginner) and (player.BetState<>btPass) then begin
Result:=False;
Break;
end;
end;
end
else
result:=False;
end;
{ TGameResults }
function TGameResults.GetGrandTotal: Smallint;
begin
Result:=Total;
if Doubles>0 then
Result:=Trunc(Power(2,Doubles))*Result;
end;
function TGameResults.GetTotal: Smallint;
begin
Result:=Game+Minus10+ContraGame+KingUlt+PagatUlt+VogelII+VogelIII+VogelIV+Trull+AllKings+CatchKing+CatchPagat+CatchXXI+Valat;
end;
function TGameResults.PointsAsString: String;
var rest:Double;
begin
Result:=IntToStr(Trunc(Points));
rest:=Frac(points);
if rest>0.4 then
Result:=result+' 2 Blatt'
else if (rest>0) then
Result:=result+' 1 Blatt'
end;
procedure TGameResults.SetPoints(const Value: Double);
begin
Points := Value;
end;
end.
|
unit MainUnit;
interface
uses
{$IFDEF FPC} LCLIntf, {$ELSE}Windows, Messages, {$ENDIF} SysUtils, Classes,
Graphics, Controls, Forms, Dialogs, GR32_Image;
type
TFmPngDemo = class(TForm)
ImageDisplay: TImage32;
procedure FormCreate(Sender: TObject);
procedure ImageDisplayClick(Sender: TObject);
procedure ImageDisplayDblClick(Sender: TObject);
end;
var
FmPngDemo: TFmPngDemo;
implementation
uses
GR32_PNG, GR32_PortableNetworkGraphic;
{$IFDEF FPC}
{$R *.lfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
procedure TFmPngDemo.FormCreate(Sender: TObject);
begin
if FileExists('Demo.png') then
with TPortableNetworkGraphic32.Create do
try
LoadFromFile('Demo.png');
AssignTo(ImageDisplay.Bitmap);
finally
Free;
end
else
raise Exception.Create('File not found: Demo.png');
ClientWidth := ImageDisplay.Bitmap.Width + 16;
ClientHeight := ImageDisplay.Bitmap.Height + 16;
end;
procedure TFmPngDemo.ImageDisplayClick(Sender: TObject);
begin
with TSaveDialog.Create(Self) do
try
Filter := 'PNG Images (*.png)|*.png';
DefaultExt := '.png';
if Execute then
begin
with TPortableNetworkGraphic32.Create do
try
AdaptiveFilterMethods := [aafmSub, aafmUp, aafmAverage];
Assign(ImageDisplay.Bitmap);
InterlaceMethod := imAdam7;
SaveToFile(FileName);
finally
Free;
end;
end;
finally
Free;
end;
end;
procedure TFmPngDemo.ImageDisplayDblClick(Sender: TObject);
begin
with TPortableNetworkGraphic32.Create do
try
Assign(ImageDisplay.Bitmap);
SaveToFile('Test.png');
finally
Free;
end;
end;
end.
|
program HowToCreateUDPProgram;
uses
SwinGame, SysUtils;
const
PEER_A_PORT = 2000;
PEER_B_PORT = 2001;
function SelectPeerType() : Connection;
var
lInput : String = '';
begin
Write('Are You Hosting? [y/n]: ');
while (lInput <> 'y') and (lInput <> 'n') do
begin
ReadLn(lInput);
if (lInput = 'y') then
begin
CreateUDPHost(PEER_A_PORT);
result := nil;
WriteLn('I am now the host');
end else if (lInput = 'n') then
begin
result := CreateUDPConnection('127.0.0.1', PEER_A_PORT, PEER_B_PORT);
SendUDPMessage('Accept Me', result);
WriteLn('I am now the client');
end;
end;
end;
procedure AcceptConnection(var aPeer : Connection);
begin
while not Assigned(aPeer) do
begin
if UDPMessageReceived() then
begin
aPeer := FetchConnection();
WriteLn('Host Received Message: ', ReadMessage(aPeer));
end;
end;
end;
procedure HandleMessages(var aPeer : Connection; const aIsHost : Boolean);
var
lMessage : String = '';
i : Integer;
const
AUTO_MESSAGE_COUNT = 10;
SEND_DELAY = 1500;
begin
for i := 0 to AUTO_MESSAGE_COUNT do
begin
if (aIsHost) then
SendUDPMessage('Hello. This Message is from the Host. The client should receive it.', aPeer)
else
SendUDPMessage('Hello. This Message is from the Client. The host should receive it.', aPeer);
Delay(SEND_DELAY);
if UDPMessageReceived() then
WriteLn('Received Message: ', ReadMessage(aPeer));
end;
end;
procedure Main();
var
lIsHost : Boolean = False;
lPeer : Connection = nil;
begin
lPeer := SelectPeerType();
lIsHost := not Assigned(lPeer);
if lIsHost then AcceptConnection(lPeer);
HandleMessages(lPeer, lIsHost);
CloseAllConnections();
end;
begin
main();
end. |
unit HTTPServer;
interface
uses
IdHTTPServer, IdContext, IdCustomHTTPServer, System.Classes,
System.SysUtils, IdGlobal, IdGlobalProtocols,idMultipartFormData,
IdCoderQuotedPrintable, IdCoderMIME, IdHeaderList;
type
THTTPServer = class(TIdHTTPServer)
private
fRequestInfo : TIdHTTPRequestInfo;
fResponseInfo: TIdHTTPResponseInfo;
procedure Connect(AContext: TIdContext);
procedure CommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
procedure CommandOther(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
class var instance : THTTPServer;
public
constructor Create(AOwner: TComponent);reintroduce;
class function getInstance() : THTTPServer;
published
property RequestInfo : TIdHTTPRequestInfo read fRequestInfo ;
property ResponseInfo: TIdHTTPResponseInfo read fResponseInfo;
end;
implementation
uses
routes;
procedure THTTPServer.CommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
fRequestInfo := ARequestInfo;
fResponseInfo := AResponseInfo;
AResponseInfo.ContentText := TRoutes.getInstance.endpoint(ARequestInfo,AResponseInfo);
end;
procedure THTTPServer.CommandOther(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
fRequestInfo := ARequestInfo;
fResponseInfo := AResponseInfo;
AResponseInfo.ContentText := TRoutes.getInstance.endpoint(ARequestInfo,AResponseInfo);
end;
procedure THTTPServer.Connect(AContext: TIdContext);
begin
TRoutes.getInstance;
end;
constructor THTTPServer.Create(AOwner: TComponent);
begin
if Assigned(instance) then
raise Exception.Create('Classe deve ser instancia via getInstance');
inherited;
instance := self;
self.OnConnect := Connect;
self.OnCommandGet := CommandGet;
self.OnCommandOther:= CommandOther;
end;
class function THTTPServer.getInstance: THTTPServer;
begin
if Not(Assigned(instance)) then
THTTPServer.Create(nil);
result := instance;
end;
end.
|
unit BZK2_Actor;
interface
const
C_BZKACTOR_OBJECT = 0;
C_BZKACTOR_LIGHT = 1;
type
TBZK2Actor = class
private
Name : string;
Location : integer;
MyClass : string;
Angle : real;
ActorType : byte;
Light : integer;
Mesh : string;
// I/O
procedure WriteName (var MyFile : System.Text);
procedure WriteLocation (var MyFile : System.Text);
procedure WriteClass (var MyFile : System.Text);
procedure WriteAngle (var MyFile : System.Text);
procedure WriteLight (var MyFile : System.Text);
procedure WriteMesh (var MyFile : System.Text);
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// I/O
procedure WriteToFile (var MyFile : System.Text);
// Gets
function GetName : string;
function GetLocation : integer;
function GetClass : string;
function GetAngle : real;
function GetLight: integer;
function GetMesh: string;
function GetType : byte;
// Sets
procedure SetName ( value : string);
procedure SetLocation ( value : integer);
procedure SetClass ( value : string);
procedure SetAngle ( value : real);
procedure SetLight( value : integer);
procedure SetMesh( value : string);
procedure SetType ( value : byte);
// Assign
procedure Assign(const Actor : TBZK2Actor);
end;
implementation
// Constructors and Destructors
constructor TBZK2Actor.Create;
begin
Name := '';
Location := 1;
MyClass := 'DefaultClass';
Angle := 0;
ActorType := C_BZKACTOR_OBJECT;
end;
destructor TBZK2Actor.Destroy;
begin
Name := '';
MyClass := '';
inherited Destroy;
end;
// Gets
function TBZK2Actor.GetName : string;
begin
Result := Name;
end;
function TBZK2Actor.GetLocation : integer;
begin
Result := Location;
end;
function TBZK2Actor.GetClass : string;
begin
Result := MyClass;
end;
function TBZK2Actor.GetAngle : real;
begin
Result := Angle;
end;
function TBZK2Actor.GetLight : integer;
begin
Result := Light;
end;
function TBZK2Actor.GetMesh : string;
begin
Result := Mesh;
end;
function TBZK2Actor.GetType : byte;
begin
Result := ActorType;
end;
// Sets
procedure TBZK2Actor.SetName ( Value : string);
begin
Name := Value;
end;
procedure TBZK2Actor.SetLocation ( Value : integer);
begin
Location := Value;
end;
procedure TBZK2Actor.SetClass ( Value : string);
begin
MyClass := value;
end;
procedure TBZK2Actor.SetAngle ( Value : real);
begin
Angle := value;
end;
procedure TBZK2Actor.SetLight ( Value : integer);
begin
Light := value;
end;
procedure TBZK2Actor.SetMesh ( Value : string);
begin
Mesh := value;
end;
procedure TBZK2Actor.SetType ( Value : byte);
begin
ActorType := value;
end;
// I/O
procedure TBZK2Actor.WriteToFile (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Actor>');
WriteName(MyFile);
if ActorType = C_BZKACTOR_OBJECT then
begin
WriteLocation(MyFile);
WriteMesh(MyFile);
WriteAngle(MyFile);
WriteClass(MyFile);
end
else if ActorType = C_BZKACTOR_LIGHT then
begin
WriteLight(MyFile);
WriteLocation(MyFile);
WriteMesh(MyFile);
end;
WriteLn(MyFile,'</Actor>');
end;
procedure TBZK2Actor.WriteName (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Name>');
WriteLn(MyFile,Name);
WriteLn(MyFile,'</Name>');
end;
procedure TBZK2Actor.WriteLocation (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Location>');
WriteLn(MyFile,Location);
WriteLn(MyFile,'</Location>');
end;
procedure TBZK2Actor.WriteClass (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Class>');
WriteLn(MyFile,MyClass);
WriteLn(MyFile,'</Class>');
end;
procedure TBZK2Actor.WriteAngle (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Angle>');
WriteLn(MyFile,Angle);
WriteLn(MyFile,'</Angle>');
end;
procedure TBZK2Actor.WriteLight (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Light>');
WriteLn(MyFile,Light);
WriteLn(MyFile,'</Light>');
end;
procedure TBZK2Actor.WriteMesh (var MyFile : System.Text);
begin
if Length(Mesh) > 0 then
begin
WriteLn(MyFile,'<Mesh>');
WriteLn(MyFile,Mesh);
WriteLn(MyFile,'</Mesh>');
end;
end;
procedure TBZK2Actor.Assign(const Actor : TBZK2Actor);
begin
SetName(Actor.GetName);
SetType(Actor.ActorType);
SetLocation(Actor.GetLocation);
SetClass(Actor.GetClass);
SetLight(Actor.Light);
SetAngle(Actor.Angle);
SetMesh(Actor.Mesh);
end;
end.
|
{$I-,Q-,R-,S-}
{Problema 6: Vallas Vacunas [Neal Wu, 2007]
El Granjero Juan quiere que las vacas se preparen para la competencia
de salto del condado, por lo tanto Bessie y la pandilla están
practicando saltar sobre vallas. Ellas se están cansando, sin embargo,
ellas quieren ser capaces de usar tan poca energía como sea posible
para saltar las vallas.
Obviamente, no es difícil para una vaca saltar sobre varias vallas
pequeĄas, pero saltar una valla alta puede ser muy estresante. Por lo
tanto, las vacas únicamente están preocupadas por la altura de la
valla más alta que tienen que saltar.
El cuarto de práctica de las vacas tiene N (1 <= N <= 300) estaciones,
convenientemente numeradas 1..N. Un conjunto de M (1 <= M <= 25,000)
caminos de una vía conectan pares de estaciones; los caminos están
también convenientemente numerados 1..M. El camino i va de la estación
S_i a la estación E_i y contiene exactamente una valla de altura H_i
(1 <= H_i <= 1,000,000). Las vacas deben saltar las vallas en todos
los caminos que ellas recorran.
Las vacas tienen T (1 <= T <= 40,000) tareas a completar. La tarea I
comprende dos números diferentes; A_i y B_i (1 <= A_i <= N; 1 <= B_i
<= N), que denotan que una vaca tiene que viajar de la estación A_i a
la estación B_i (recorriendo uno o más caminos a través alguna ruta).
Las vacas quieren tomar un camino que minimice la altura de la mayor
valla que ellas deben saltar cuando viaja de A_i a B_i. Su tarea es
escribir un programa que determine el camino cuya mayor valla sea la
menor y reporte esa altura.
NOMBRE DEL PROBLEMA: hurdles
FORMATO DE ENTRADA:
* Línea 1: Tres enteros separados por espacios: N, M y T
* Líneas 2..M+1: La línea i+1 contiene tres enteros separados por
espacios: S_i, E_i y H_i
* Líneas M+2..M+T+1: La línea i+M+1 contiene dos enteros separados por
espacio que describen la tarea i: A_i y B_i
ENTRADA EJEMPLO (archivo hurdles.in):
5 6 3
1 2 12
3 2 8
1 3 5
2 5 3
3 4 4
2 4 8
3 4
1 2
5 1
FORMATO DE SALIDA:
* Líneas 1..T: La línea i contiene el resultado de la tarea i y dice
la posible menor altura máxima necesaria para ir entre las
estaciones. Dé como salida -1 si es imposible viajar entre las
dos estaciones.
SALIDA EJEMPLO (archivo hurdles.OUT):
4
8
-1
DETALLES DE LA SALIDA:
Pregunta #1: La mejor manera es simplemente viajar en el camino de la
estación 3 a la estación 4.
Pregunta #2: Hay un camino de la estación 1 a la estación 2, pero una
mejor manera sería viajar de la estación 1 a la estación 3 y luego a
la estación 2.
Pregunta #3: No hay caminos que comiencen en la estación 5, por lo
tanto es claro que no hay manera de llegar a la estación 1 desde la
estación 5.
}
const
mx = 301;
inf = 2139062143;
var
fe,fs : text;
n,m,t,i,a,b,c : longint;
tab : array[1..mx,1..mx] of longint;
procedure open;
begin
assign(fe,'hurdles.in'); reset(fe);
assign(fs,'hurdles.out'); rewrite(fs);
readln(fe,n,m,t);
fillchar(tab,sizeof(tab),127);
for i:=1 to m do
begin
readln(fe,a,b,c);
tab[a,b]:=c;
end;
end;
function min(n1,n2 : longint) : longint;
begin
if n1 < n2 then
min:=n1
else min:=n2;
end;
function max(n1,n2 : longint) : longint;
begin
if n1 > n2 then
max:=n1
else max:=n2;
end;
procedure floyd;
var
j,k : longint;
begin
for i:=1 to n do
for j:=1 to n do
if tab[j,i] <> inf then
begin
for k:=1 to n do
tab[j,k]:=min(tab[j,k],max(tab[j,i],tab[i,k]));
end;
end;
procedure work;
begin
floyd;
for i:=1 to t do
begin
readln(fe,a,b);
if tab[a,b] <> inf then
writeln(fs,tab[a,b])
else writeln(fs,-1);
end;
close(fe);
close(fs);
end;
begin
open;
work;
end. |
unit uDataModule;
interface
uses
SysUtils, Windows, Classes, DB, ADODB, Dialogs, ComObj, Registry
{$If CompilerVersion >=28} // >=XE7
, System.UITypes
{$ENDIF}
;
type
TDataModule1 = class(TDataModule)
dsProducts: TDataSource;
ADOConnection1: TADOConnection;
Products: TADOTable;
OrderDetails: TADOTable;
Orders: TADOTable;
Customers: TADOTable;
dsOrderDetails: TDataSource;
dsOrders: TDataSource;
dsCustomers: TDataSource;
OrderDetailsOrderID: TIntegerField;
OrderDetailsProductID: TIntegerField;
OrderDetailsUnitPrice: TBCDField;
OrderDetailsQuantity: TSmallintField;
OrderDetailsDiscount: TFloatField;
OrderDetailsProductNameProductsProductIDProductName: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure ADOConnection1ConnectComplete(Connection: TADOConnection; const error: Error; var EventStatus: TEventStatus);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DataModule1: TDataModule1;
implementation
{$R *.dfm}
procedure TDataModule1.DataModuleCreate(Sender: TObject);
var i: Integer;
var registry: TRegistry;
var regKeyPath: String;
var dbPath: String;
begin
// D: Datenbankpfad auslesen
// US: Read database path
registry := TRegistry.Create();
registry.RootKey := HKEY_CURRENT_USER;
regKeyPath := 'Software\combit\cmbtll\';
if registry.KeyExists(regKeyPath) then
begin
if registry.OpenKeyReadOnly(regKeyPath) then
begin
dbPath := registry.ReadString('NWINDPath');
registry.CloseKey();
end;
end;
registry.Free();
if (dbPath = '') then
begin
ShowMessage('Unable to find sample database. Make sure List & Label is installed correctly.');
end
else
begin
{D: ADO Verbidnungsinformationen setzen}
{US: Specifies the connection information for the data store }
ADOConnection1.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;' +
'Data Source=' + dbPath + ';' +
'Persist Security Info=False';
{D: Lade die Datenbank, fange Fehler ab }
{US: Load the database, checks for errors }
Try
ADOConnection1.Connected := true;
// Customers.Filter := 'CustomerID ' + '< ' + QuotedStr('D');
Customers.Filter := 'CustomerID ' + '< ' + QuotedStr('B');
Customers.Filtered := true;
for i := 0 to (ADOConnection1.DataSetCount-1) do
ADOConnection1.DataSets[i].Active := true;
Except
on E : EADOError do
MessageDlg('D: Beispiel-Datenbank nicht gefunden'+ #13 + 'US: Test database not found',mtError,[mbOK],0);
on E : EOleError do
ShowMessage(Format('D: Beispiel-Datenbank nicht gefunden.'+#13+'US: Test database not found.'+#13#13'%s:''%s''.',[E.ClassName,E.Message]));
on E : EOleException do
ShowMessage(Format('D: Beispiel-Datenbank nicht gefunden.'+#13+'US: Test database not found.'+#13#13'%s:''%s''.',[E.ClassName,E.Message]));
End;
end;
end;
procedure TDataModule1.DataModuleDestroy(Sender: TObject);
var
i: integer;
begin
for i := 0 to (ADOConnection1.DataSetCount-1) do
ADOConnection1.DataSets[i].Active := false;
ADOConnection1.Connected := false;
end;
procedure TDataModule1.ADOConnection1ConnectComplete(Connection: TADOConnection; const error: Error; var EventStatus: TEventStatus);
begin
if EventStatus = esErrorsOccured then
begin
ShowMessage( error.Description );
Halt;
end;
end;
end.
|
unit sqlsupport;
{$IFDEF FPC}
{$MODE Delphi}
{$H+}
{$ELSE}
{$IFNDEF LINUX}
{$DEFINE WIN32}
{$ENDIF}
{$ENDIF}
interface
uses {$IFDEF WIN32}Windows, {$ENDIF} Classes, SysUtils{, DateUtils}{, System};
//{$IFDEF FPC}, LCLIntf{$ENDIF};
type
TDBMajorType = (dbANSI, dbMySQL, dbSQLite, dbODBC, dbJanSQL);
TDBSubType = (dbDefault, dbSqlite2, dbSqlite3, dbSqlite3W, dbODBC32);
const
DblQuote: Char = '"';
SngQuote: Char = #39;
Crlf: String = #13#10;
Tab: Char = #9;
function FloatToMySQL (Value:Extended):String;
function DateTimeToMySQL (Value:TDateTime):String;
function MySQLToDateTime (Value:String):TDateTime;
function Pas2SQLiteStr(const PasString: string): string;
function SQLite2PasStr(const SQLString: string): string;
function AddQuote(const s: string; QuoteChar: Char = #39): string;
function AddQuoteW(const s: WideString; QuoteChar: WideChar = #39): WideString;
function UnQuote(const s: string; QuoteChar: Char = #39): string;
function UnQuoteW(const s: WideString; QuoteChar: WideChar = #39): WideString;
function SystemErrorMsg(ErrNo: Integer = -1): String;
function Escape(Value: String): String;
function UnEscape(Value: String): String;
function EscapeW(Value: WideString): WideString;
function UnEscapeW(Value: WideString): WideString;
function QuoteEscape (Value:String; qt:TDBMajorType):String;
function QuoteEscapeW (Value:WideString; qt:TDBMajorType):WideString;
//This is availabse from delhi 7 and up in unit strutils.
function PosEx (const SubStr, S: string; Offset: Integer = 1): Integer;
implementation
//Support functions
function FloatToMySQL (Value:Extended):String;
begin
Result := StringReplace(FloatToStr(Value), ',', '.', []);
end;
function DateTimeToMySQL (Value:TDateTime):String;
begin
Result := FormatDateTime ('yyyymmddhhnnss', Value);
end;
function MySQLToDateTime (Value:String):TDateTime;
var ayear, amonth, aday, ahour, aminute, asecond, amillisecond: Word;
begin
ayear := StrToIntDef (copy (value, 1, 4), 0);
amonth := StrToIntDef (copy (value, 5, 2), 0);
aday := StrToIntDef (copy (value, 7,2), 0);
ahour := StrToIntDef (copy (value, 9, 2), 0);
aminute := StrToIntDef (copy (value, 11, 2), 0);
asecond := StrToIntDef (copy (value, 13, 2), 0);
amillisecond := 0;
//Result := EncodeDateTime(AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond);
//backward compatability
Result := EncodeDate (AYear, AMonth, ADay) + EncodeTime (AHour, AMinute, ASecond, AMillisecond);
end;
function Pas2SQLiteStr(const PasString: string): string;
var
n: integer;
begin
Result := SQLite2PasStr(PasString);
n := Length(Result);
while n > 0 do
begin
if Result[n] = SngQuote then
Insert(SngQuote, Result, n);
dec(n);
end;
Result := AddQuote(Result);
end;
function SQLite2PasStr(const SQLString: string): string;
const
DblSngQuote: String = #39#39;
var
p: integer;
begin
Result := SQLString;
p := pos(DblSngQuote, Result);
while p > 0 do
begin
Delete(Result, p, 1);
p := pos(DblSngQuote, Result);
end;
Result := UnQuote(Result);
end;
function SystemErrorMsg(ErrNo: Integer = -1): String;
{$IFDEF WIN32}
var
buf: PChar;
size: Integer;
MsgLen: Integer;
{$ENDIF}
begin
{$IFDEF WIN32}
size := 256;
GetMem(buf, size);
If ErrNo = - 1 then
ErrNo := GetLastError;
MsgLen := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, ErrNo, 0, buf, size, nil);
if MsgLen = 0 then
Result := 'ERROR'
else
Result := buf;
{$ELSE}
Result := ''; //unknown
{$ENDIF}
end;
function AddQuote(const s: string; QuoteChar: Char = #39): string;
begin
Result := Concat(QuoteChar, s, QuoteChar);
end;
function AddQuoteW(const s: WideString; QuoteChar: WideChar = #39): WideString;
begin
Result := QuoteChar + s + QuoteChar;
end;
function UnQuote(const s: string; QuoteChar: Char = #39): String;
begin
Result := s;
if length(Result) > 1 then
begin
if Result[1] = QuoteChar then
Delete(Result, 1, 1);
if Result[Length(Result)] = QuoteChar then
Delete(Result, Length(Result), 1);
end;
end;
function UnQuoteW(const s: WideString; QuoteChar: WideChar = #39): WideString;
begin
Result := s;
if length(Result) > 1 then
begin
//this is quite a problem..
if Result[1] = QuoteChar then
Delete(Result, 1, 1);
if Result[Length(Result)] = QuoteChar then
Delete(Result, Length(Result), 1);
end;
end;
function Escape(Value: String): String;
var i:Integer;
begin
for i:=length (Value) downto 1 do
if Value[i] in ['\', '''', '"', #0, #$14] then
begin
if Value[i]=#0 then
Value[i]:='0';
//optionally tabs, backspaces, nl etc:
//if Value[i]=#9 then
//Value[i]='t';
//etc
Insert ('\', Value, i);
end;
Result := Value;
end;
function UnEscape(Value: String): String;
var i:Integer;
begin
for i:=1 to length(Value)-1 do
if Value[i]='\' then
begin
if Value[i+1]='0' then
Value[i+1]:=#0;
Delete (Value,i,1);
end;
Result := Value;
end;
function EscapeW(Value: WideString): WideString;
var i:Integer;
begin
for i:=length (Value) downto 1 do
if Char(Value[i]) in ['\', '''', '"', #0] then
begin
if Value[i]=#0 then
Value[i]:='0';
//optionally tabs, backspaces, nl etc:
//if Value[i]=#9 then
//Value[i]='t';
//etc
Insert ('\', Value, i);
end;
Result := Value;
end;
function EscapeSqLiteW(Value: WideString): WideString;
var i:Integer;
begin
for i:=length (Value) downto 1 do
if Char(Value[i]) in ['\', '''', #0] then
begin
if Value[i]=#0 then begin
Value[i]:='0';
Insert ('\', Value, i);
end
else if Value[i]='\' then begin
Insert ('\', Value, i);
end
else if Value[i]='''' then begin
Insert ('''', Value, i);
end;
end;
Result := Value;
end;
function UnEscapeW(Value: WideString): WideString;
var i:Integer;
begin
for i:=1 to length(Value)-1 do
if Value[i]='\' then
begin
if Value[i+1]='0' then
Value[i+1]:=#0;
Delete (Value,i,1);
end;
Result := Value;
end;
function QuoteEscape (Value:String; qt:TDBMajorType):String;
begin
case qt of
dbAnsi, dbMySQL :
begin
//mysql finds escaping with backslash sufficient to ignore the next quote
Value := AddQuote(Escape (Value));
end;
dbSQLite, dbODBC :
begin
//escape binary chars
Value := Escape (Value);
//replace string quotes with double quotes - sqlite needs this apperently
Value := StringReplace (Value, '''', '''''', [rfReplaceAll]);
Value := AddQuote (Value);
end;
end;
Result := Value;
end;
function QuoteEscapeW (Value:WideString; qt:TDBMajorType):WideString;
begin
case qt of
dbMySQL :
begin
//mysql finds escaping with backslash sufficient to ignore the next quote
Value := AddQuote(Escape (Value));
end;
dbSQLite :
begin
//escape binary chars
Value := EscapeSqLiteW (Value);
Value := AddQuoteW (Value);
end;
end;
Result := Value;
end;
function PosEx (const SubStr, S: string; Offset: Integer = 1): Integer;
var i: Integer;
begin
//by way not the fastest method!
i := Pos (Substr, copy (S, offset, maxint));
if i<=0 then
Result := 0
else
Result := i + Offset - 1;
end;
end.
|
unit UBookClose;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FIBDatabase, pFIBDatabase, Ibase, StdCtrls, DB, FIBDataSet,
pFIBDataSet, dateUtils, ExtCtrls, ComCtrls, cxLookAndFeelPainters,
cxButtons, Menus,pFibStoredProc, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxSplitter, frxClass,
frxDBSet, frxCross, cxContainer, cxRadioGroup, cxDropDownEdit,
cxTextEdit, cxMaskEdit, cxButtonEdit, cxProgressBar,Contnrs, ImgList,
AccMGMT, Placemnt, cxCalendar, frxExportPDF, frxExportImage,
frxExportXML, frxExportXLS, frxExportHTML, frxExportTXT;
type
TfrmCloseBook = class(TForm)
WorkDatabase: TpFIBDatabase;
WriteTransaction: TpFIBTransaction;
ReadTransaction: TpFIBTransaction;
SysDataSet: TpFIBDataSet;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
ErrorsDataSet: TpFIBDataSet;
ErrorDataSource: TDataSource;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Panel2: TPanel;
ActionLog: TRichEdit;
Splitter1: TSplitter;
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
cbMonth: TComboBox;
cbYear: TComboBox;
cxButton1: TcxButton;
CurMonth: TEdit;
CurYear: TEdit;
frxCrossObject1: TfrxCrossObject;
SchMainBookData: TfrxDBDataset;
SchMainBookDataDataSet: TpFIBDataSet;
cxButton2: TcxButton;
cxGrid2DBTableView1: TcxGridDBTableView;
cxGrid2Level1: TcxGridLevel;
cxGrid2: TcxGrid;
cxGrid2DBTableView1DBColumn1: TcxGridDBColumn;
SystemDataSet: TpFIBDataSet;
SystemDataSource: TDataSource;
ProgressBar1: TProgressBar;
PopupMenu2: TPopupMenu;
N3: TMenuItem;
N4: TMenuItem;
N6: TMenuItem;
N7: TMenuItem;
N8: TMenuItem;
SmallImages: TImageList;
N5: TMenuItem;
N9: TMenuItem;
FormStorage1: TFormStorage;
cbWorkYear: TComboBox;
Label3: TLabel;
N10: TMenuItem;
frxTXTExport1: TfrxTXTExport;
frxHTMLExport1: TfrxHTMLExport;
frxXLSExport1: TfrxXLSExport;
frxXMLExport1: TfrxXMLExport;
frxBMPExport1: TfrxBMPExport;
frxJPEGExport1: TfrxJPEGExport;
frxTIFFExport1: TfrxTIFFExport;
frxPDFExport1: TfrxPDFExport;
frxReport1: TfrxReport;
cxButton3: TcxButton;
cxButton4: TcxButton;
cxDateEdit1: TcxDateEdit;
Label4: TLabel;
SchFilterDataSource: TDataSource;
SchFilterDataSet: TpFIBDataSet;
cxGrid2DBTableView1DBColumn2: TcxGridDBColumn;
procedure cxButton1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure N1Click(Sender: TObject);
procedure N2Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure N8Click(Sender: TObject);
procedure N5Click(Sender: TObject);
procedure cxButton3Click(Sender: TObject);
procedure cxButton4Click(Sender: TObject);
private
MBOOK_DATE :TDateTime;
NEWBOOK_DATE :TDateTime;
KEY_SESSION :Int64;
Pages :array of TComponent;
Function GetControlOnPage(ComponentTag:Integer;ComponentClass:TClass;ObjName:String):TComponent;
Function GetCurrentFrame(ComponentTag:Integer):TComponent;
Procedure GetRight;
public
Constructor Create(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE);overload;
Destructor Destroy; override;
end;
procedure GetMBOOK(AOwner:TComponent;DBHandle:TISC_DB_HANDLE);stdcall;
exports GetMBOOK;
implementation
uses Resources_unitb,UProgressForm,
GlobalSpr, UMBookSchFrame,RxMemDS;
procedure GetMBOOK(AOwner:TComponent;DBHandle:TISC_DB_HANDLE);
var f:Boolean;
i:Integer;
begin
f:=true;
for i:=0 to Application.MainForm.MDIChildCount-1 do
begin
if (Application.MainForm.MDIChildren[i] is TfrmCloseBook)
then begin
Application.MainForm.MDIChildren[i].BringToFront;
f:=false;
end;
end;
if f then TfrmCloseBook.Create(AOwner,DBHandle);
end;
{$R *.dfm}
Destructor TfrmCloseBook.Destroy;
begin
inherited Destroy;
end;
Constructor TfrmCloseBook.Create(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE);
var i:Integer;
Y,M,D:WORD;
begin
inherited Create(AOwner);
cxDateEdit1.Date:=Date;
PageControl1.ActivePageIndex:=0;
Screen.Cursor:=crHourGlass;
WorkDatabase.Handle:=DB_HANDLE;
SystemDataSet.SelectSQL.Text:='SELECT * FROM PUB_SP_SYSTEM';
SystemDataSet.Open;
SchFilterDataSet.SelectSQL.Text:='SELECT * FROM MBOOK_PRINT_ITEMS_EXCL_SEL';
SchFilterDataSet.Open;
KEY_SESSION:=WorkDatabase.Gen_Id('MBOOK_SESSION',1);
ErrorsDataSet.SelectSQL.Text:='SELECT * FROM MBOOK_ERRORS WHERE KEY_SESSION='+IntToStr(KEY_SESSION);
//ErrorsDataSet.OPen;
SysDataSet.Open;
MBOOK_DATE:=SysDataSet.FieldByName('MAIN_BOOK_DATE').AsDateTime;
DecodeDate(MBOOK_DATE,Y,M,D);
//Panel3.Caption:='Ðîáîòà ç ãîëîâíîþ êíèãîþ. Ðîáî÷³é ïåð³îä - '+GlobalSpr.MonthTitle(MBOOK_DATE)+' '+IntToStr(Y);
DecodeDate(MBOOK_DATE,Y,M,D);
if (M=12)
then NEWBOOK_DATE:=EncodeDate(Y+1,1,1)
else NEWBOOK_DATE:=EncodeDate(Y,M+1,1);
SysDataSet.Close;
cbMonth.Items.Add(TRIM(BU_Month_01));
cbMonth.Items.Add(TRIM(BU_Month_02));
cbMonth.Items.Add(TRIM(BU_Month_03));
cbMonth.Items.Add(TRIM(BU_Month_04));
cbMonth.Items.Add(TRIM(BU_Month_05));
cbMonth.Items.Add(TRIM(BU_Month_06));
cbMonth.Items.Add(TRIM(BU_Month_07));
cbMonth.Items.Add(TRIM(BU_Month_08));
cbMonth.Items.Add(TRIM(BU_Month_09));
cbMonth.Items.Add(TRIM(BU_Month_10));
cbMonth.Items.Add(TRIM(BU_Month_11));
cbMonth.Items.Add(TRIM(BU_Month_12));
for i:=0 to YEARS_COUNT do
begin
cbYear.Items.Add(TRIM(IntToStr(BASE_YEAR+i)));
end;
for i:=0 to YEARS_COUNT do
begin
cbWorkYear.Items.Add(TRIM(IntToStr(BASE_YEAR+i)));
end;
cbMonth.ItemIndex:=MonthOf(MBOOK_DATE)-1;
CurMonth.Text:=cbMonth.Items[cbMonth.ItemIndex];
cbMonth.ItemIndex:=MonthOf(NEWBOOK_DATE)-1;
for i:=0 to cbYear.Items.Count-1 do
begin
if pos(cbYear.Items[i],IntToStr(YearOf(MBOOK_DATE)))>0
then begin
cbYear.ItemIndex:=i;
break;
end;
end;
CurYear.Text:=cbYear.Items[cbYear.ItemIndex];
for i:=0 to cbWorkYear.Items.Count-1 do
begin
if pos(cbWorkYear.Items[i],IntToStr(YearOf(MBOOK_DATE)))>0
then begin
cbWorkYear.ItemIndex:=i;
break;
end;
end;
for i:=0 to cbYear.Items.Count-1 do
begin
if pos(cbYear.Items[i],IntToStr(YearOf(NEWBOOK_DATE)))>0
then begin
cbYear.ItemIndex:=i;
break;
end;
end;
ActionLog.Lines.Add('Ðîáîòà ç ãîëîâíîþ êíèãîþ...'+TimeToStr(Time));
Screen.Cursor:=crDefault;
GetRight;
end;
procedure TfrmCloseBook.cxButton1Click(Sender: TObject);
var ActualDate:TDateTime;
date_str:String;
i:Integer;
Result:INteger;
Y,M,D:Word;
CloseStoredProc:TpFibStoredProc;
begin
Screen.Cursor:=crHourGlass;
DateSeparator:='.';
ActualDate:=StrToDate('01.'+IntToStr(cbMonth.ItemIndex+1)+'.'+cbYear.Items[cbYear.ItemIndex]);
DateTimeToString(date_str,'dd.mm.yyyy',ActualDate);
CloseStoredProc:=TpFibStoredProc.Create(self);
CloseStoredProc.Database:=WorkDatabase;
CloseStoredProc.Transaction:=WriteTransaction;
CloseStoredProc.StoredProcName:='MBOOK_CLOSE';
WriteTransaction.StartTransaction;
CloseStoredProc.Prepare;
CloseStoredProc.ParamByName('MODE').Value:=1;
CloseStoredProc.ParamByName('KEY_SESSION').AsInt64:=KEY_SESSION;
CloseStoredProc.ParamByName('ID_USER').AsInt64:=0;
ActionLog.Lines.Add('Çàêðèòòÿ ãîëîâíî¿ êíèãè...'+TimeToStr(Time));
CloseStoredProc.ExecProc;
Result:=CloseStoredProc.ParamByName('RESULT').AsInteger;
ActionLog.Lines.Add(CloseStoredProc.ParamByName('LOG_MESSAGE').AsString);
ErrorsDataSet.Open;
ErrorsDataSet.FetchAll;
ErrorsDataSet.First;
for i:=0 to ErrorsDataSet.RecordCount -1 do
begin
ActionLog.Lines.Add(ErrorsDataSet.FieldByName('ERROR_MSG').AsString);
ErrorsDataSet.Next;
end;
ErrorsDataSet.Close;
if Result=0
then WriteTransaction.Rollback
else WriteTransaction.Commit;
CloseStoredProc.Free;
Screen.Cursor:=crDefault;
if Result=1
then begin
if SysDataSet.Active then SysDataSet.Close;
SysDataSet.Open;
MBOOK_DATE:=SysDataSet.FieldByName('MAIN_BOOK_DATE').AsDateTime;
DecodeDate(MBOOK_DATE,Y,M,D);
if (M=12)
then NEWBOOK_DATE:=EncodeDate(Y+1,1,1)
else NEWBOOK_DATE:=EncodeDate(Y,M+1,1);
SysDataSet.Close;
for i:=0 to YEARS_COUNT do
begin
cbYear.Items.Add(TRIM(IntToStr(BASE_YEAR+i)));
end;
cbMonth.ItemIndex:=MonthOf(MBOOK_DATE)-1;
CurMonth.Text:=cbMonth.Items[cbMonth.ItemIndex];
cbMonth.ItemIndex:=MonthOf(NEWBOOK_DATE)-1;
for i:=0 to cbYear.Items.Count-1 do
begin
if pos(cbYear.Items[i],IntToStr(YearOf(MBOOK_DATE)))>0
then begin
cbYear.ItemIndex:=i;
break;
end;
end;
CurYear.Text:=cbYear.Items[cbYear.ItemIndex];
for i:=0 to cbYear.Items.Count-1 do
begin
if pos(cbYear.Items[i],IntToStr(YearOf(NEWBOOK_DATE)))>0
then begin
cbYear.ItemIndex:=i;
break;
end;
end;
//ShowSchPages(MBOOK_DATE,true);
end;
end;
procedure TfrmCloseBook.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TfrmCloseBook.N1Click(Sender: TObject);
begin
cxButton1Click(self);
end;
procedure TfrmCloseBook.N2Click(Sender: TObject);
var date_str:String;
i:Integer;
Result:INteger;
Y,M,D:Word;
CloseStoredProc:TpFibStoredProc;
begin
Screen.Cursor:=crHourGlass;
DecodeDate(MBOOK_DATE,y,m,d);
if (M=1)
then NEWBOOK_DATE:=EncodeDate(Y-1,12,1)
else NEWBOOK_DATE:=EncodeDate(Y,M-1,1);
DateTimeToString(date_str,'dd.mm.yyyy',NEWBOOK_DATE);
CloseStoredProc:=TpFibStoredProc.Create(self);
CloseStoredProc.Database:=WorkDatabase;
CloseStoredProc.Transaction:=WriteTransaction;
CloseStoredProc.StoredProcName:='MBOOK_CLOSE';
WriteTransaction.StartTransaction;
CloseStoredProc.Prepare;
CloseStoredProc.ParamByName('MODE').Value:=2;
CloseStoredProc.ParamByName('KEY_SESSION').AsInt64:=KEY_SESSION;
CloseStoredProc.ParamByName('ID_USER').AsInt64:=KEY_SESSION;
ActionLog.Lines.Add('²ÄÊÀÒ ÃÎÃËÎÂÍί ÊÍÈÃÈ.'+TimeToStr(Time));
CloseStoredProc.ExecProc;
Result:=CloseStoredProc.ParamByName('RESULT').AsInteger;
ActionLog.Lines.Add(CloseStoredProc.ParamByName('LOG_MESSAGE').AsString);
ErrorsDataSet.Open;
ErrorsDataSet.FetchAll;
ErrorsDataSet.First;
for i:=0 to ErrorsDataSet.RecordCount -1 do
begin
ActionLog.Lines.Add(ErrorsDataSet.FieldByName('ERROR_MSG').AsString);
ErrorsDataSet.Next;
end;
ErrorsDataSet.Close;
if Result=0
then WriteTransaction.Rollback
else WriteTransaction.Commit;
CloseStoredProc.Free;
Screen.Cursor:=crDefault;
if Result=1
then begin
if SysDataSet.Active then SysDataSet.Close;
SysDataSet.Open;
MBOOK_DATE:=SysDataSet.FieldByName('MAIN_BOOK_DATE').AsDateTime;
DecodeDate(MBOOK_DATE,Y,M,D);
if (M=12)
then NEWBOOK_DATE:=EncodeDate(Y+1,1,1)
else NEWBOOK_DATE:=EncodeDate(Y,M+1,1);
SysDataSet.Close;
for i:=0 to YEARS_COUNT do
begin
cbYear.Items.Add(TRIM(IntToStr(BASE_YEAR+i)));
end;
cbMonth.ItemIndex:=MonthOf(MBOOK_DATE)-1;
CurMonth.Text:=cbMonth.Items[cbMonth.ItemIndex];
cbMonth.ItemIndex:=MonthOf(NEWBOOK_DATE)-1;
for i:=0 to cbYear.Items.Count-1 do
begin
if pos(cbYear.Items[i],IntToStr(YearOf(MBOOK_DATE)))>0
then begin
cbYear.ItemIndex:=i;
break;
end;
end;
CurYear.Text:=cbYear.Items[cbYear.ItemIndex];
for i:=0 to cbYear.Items.Count-1 do
begin
if pos(cbYear.Items[i],IntToStr(YearOf(NEWBOOK_DATE)))>0
then begin
cbYear.ItemIndex:=i;
break;
end;
end;
//ShowSchPages(MBOOK_DATE,true);
end;
end;
procedure TfrmCloseBook.cxButton2Click(Sender: TObject);
var TempSchQuery:TpFibDataSet;
i:Integer;
WorkYear:Integer;
begin
cxButton2.Enabled:=False;
WorkYear:=StrToInt(cbWorkYear.Items[cbWorkYear.ItemIndex]);
Screen.Cursor:=crHourGlass;
ProgressBar1.Visible:=true;
WriteTransaction.StartTransaction;
TempSchQuery:=TpFibDataSet.Create(self);
TempSchQuery.Database:=WorkDatabase;
TempSchQuery.Transaction:=ReadTransaction;
TempSchQuery.SelectSQL.Text:=' SELECT * FROM MBOOK_GET_SCH_FOR_PRINT('+IntToStr(WorkYear)+','+IntToStr(KEY_SESSION)+') ORDER BY sch_number ASC';
TempSchQuery.Open;
TempSchQuery.FetchAll;
frxReport1.Clear;
ProgressBar1.Visible:=true;
ProgressBar1.Max:=TempSchQuery.RecordCount;
ProgressBar1.Step:=1;
for i:=0 to TempSchQuery.RecordCount-1 do
begin
if SchMainBookDataDataSet.Active then SchMainBookDataDataSet.Close;
SchMainBookDataDataSet.SelectSQL.Text:='SELECT * FROM MBOOK_SCH_PRINT('+TempSchQuery.FieldByName('ID_SCH').AsString+','+
''''+TempSchQuery.FieldByName('PERIOD_BEG').AsString+''''+','+
''''+TempSchQuery.FieldByName('PERIOD_END').AsString+''''+','+''''+',0)';
frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Mbook\ReportSchMainBook.fr3',true);
try
if i=0 then frxReport1.PrepareReport
else frxReport1.PrepareReport(False);
except on E:Exception do begin end;
end;
TempSchQuery.Next;
ProgressBar1.StepIt;
end;
TempSchQuery.Close;
TempSchQuery.Free;
Screen.Cursor:=crDefault;
frxReport1.ShowPreparedReport;
ProgressBar1.Visible:=false;
WriteTransaction.Commit;
cxButton2.Enabled:=true;
end;
Function TfrmCloseBook.GetCurrentFrame(ComponentTag:Integer):TComponent;
var ResComponent:TComponent;
i:Integer;
begin
Screen.Cursor:=crHourglass;
ResComponent:=nil;
for i:=0 to LENGTH(Pages)-1 do
begin
if (Pages[i]<>NIL) and (Pages[i].Tag=ComponentTag)
then begin ResComponent:=Pages[i].Components[0]; Break; end;
end;
Screen.Cursor:=crDefault;
GetCurrentFrame:=ResComponent;
end;
function TfrmCloseBook.GetControlOnPage(ComponentTag:Integer;ComponentClass:TClass;ObjName:String):TComponent;
var ResComponent:TComponent;
CurPage:TComponent;
i:Integer;
begin
Screen.Cursor:=crHourglass;
ResComponent:=nil;
CurPage:=nil;
for i:=0 to LENGTH(Pages)-1 do
begin
if (Pages[i]<>NIL) and (Pages[i].Tag=ComponentTag)
then begin CurPage:=Pages[i]; Break; end;
end;
for i:=0 to CurPage.Components[0].ComponentCount-1 do
begin
if (CurPage.Components[0].Components[i] is TClass) and (CurPage.Components[0].Components[i].Name=ObjName)
then begin
ResComponent:=CurPage.Components[0].Components[i]; Break;
end;
end;
Screen.Cursor:=crDefault;
GetControlOnPage:=ResComponent;
end;
procedure TfrmCloseBook.N8Click(Sender: TObject);
begin
close;
end;
procedure TfrmCloseBook.N5Click(Sender: TObject);
var date_str:String;
i:Integer;
Result:INteger;
Y,M,D:Word;
CloseStoredProc:TpFibStoredProc;
begin
Screen.Cursor:=crHourGlass;
DecodeDate(MBOOK_DATE,y,m,d);
if (M=1)
then NEWBOOK_DATE:=EncodeDate(Y-1,12,1)
else NEWBOOK_DATE:=EncodeDate(Y,M-1,1);
DateTimeToString(date_str,'dd.mm.yyyy',NEWBOOK_DATE);
CloseStoredProc:=TpFibStoredProc.Create(self);
CloseStoredProc.Database:=WorkDatabase;
CloseStoredProc.Transaction:=WriteTransaction;
CloseStoredProc.StoredProcName:='MBOOK_CLOSE_EX';
WriteTransaction.StartTransaction;
CloseStoredProc.Prepare;
CloseStoredProc.ParamByName('MODE').Value:=2;
CloseStoredProc.ParamByName('KEY_SESSION').AsInt64:=KEY_SESSION;
CloseStoredProc.ParamByName('ID_USER').AsInt64:=KEY_SESSION;
ActionLog.Lines.Add('²ÄÊÀÒ ÃÎÃËÎÂÍί ÊÍÈÃÈ.'+TimeToStr(Time));
CloseStoredProc.ExecProc;
Result:=CloseStoredProc.ParamByName('RESULT').AsInteger;
ActionLog.Lines.Add(CloseStoredProc.ParamByName('LOG_MESSAGE').AsString);
ErrorsDataSet.Open;
ErrorsDataSet.FetchAll;
ErrorsDataSet.First;
for i:=0 to ErrorsDataSet.RecordCount -1 do
begin
ActionLog.Lines.Add(ErrorsDataSet.FieldByName('ERROR_MSG').AsString);
ErrorsDataSet.Next;
end;
ErrorsDataSet.Close;
if Result=0
then WriteTransaction.Rollback
else WriteTransaction.Commit;
CloseStoredProc.Free;
Screen.Cursor:=crDefault;
if Result=1
then begin
if SysDataSet.Active then SysDataSet.Close;
SysDataSet.Open;
MBOOK_DATE:=SysDataSet.FieldByName('MAIN_BOOK_DATE').AsDateTime;
DecodeDate(MBOOK_DATE,Y,M,D);
if (M=12)
then NEWBOOK_DATE:=EncodeDate(Y+1,1,1)
else NEWBOOK_DATE:=EncodeDate(Y,M+1,1);
SysDataSet.Close;
for i:=0 to YEARS_COUNT do
begin
cbYear.Items.Add(TRIM(IntToStr(BASE_YEAR+i)));
end;
cbMonth.ItemIndex:=MonthOf(MBOOK_DATE)-1;
CurMonth.Text:=cbMonth.Items[cbMonth.ItemIndex];
cbMonth.ItemIndex:=MonthOf(NEWBOOK_DATE)-1;
for i:=0 to cbYear.Items.Count-1 do
begin
if pos(cbYear.Items[i],IntToStr(YearOf(MBOOK_DATE)))>0
then begin
cbYear.ItemIndex:=i;
break;
end;
end;
CurYear.Text:=cbYear.Items[cbYear.ItemIndex];
for i:=0 to cbYear.Items.Count-1 do
begin
if pos(cbYear.Items[i],IntToStr(YearOf(NEWBOOK_DATE)))>0
then begin
cbYear.ItemIndex:=i;
break;
end;
end;
end;
end;
procedure TfrmCloseBook.GetRight;
begin
if fibCheckPermission('/ROOT/Kernell/MBook','Close')=0
then begin //yes
cxButton1.Enabled:=true;
end
else begin
cxButton1.Enabled:=false;
end;
end;
procedure TfrmCloseBook.cxButton3Click(Sender: TObject);
var InsertSP:TpFibStoredProc;
Res:Variant;
id_sch:int64;
i:Integer;
begin
Res:=GlobalSpr.GetSch(self,
WorkDatabase.handle,
fsNormal,
cxDateEdit1.Date,
DEFAULT_ROOT_ID,0,0);
If (varArrayDimCount(Res)>0)
then begin
for i:=0 to VarArrayHighBound(RES,1) do
begin
id_sch:=RES[i][0];
if not SchFilterDataSet.Locate('ID_SCH',id_sch,[])
then begin
InsertSP:=TpFibStoredProc.Create(self);
InsertSP.Database:=WorkDatabase;
InsertSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertSP.StoredProcName:='MBOOK_PRINT_ITEMS_EXCL_INS';
InsertSP.Prepare;
InsertSP.ParamByName('ID_SCH').AsInt64 :=id_sch;
InsertSP.ParamByName('add_date').Value :=cxDateEdit1.Date;
InsertSP.ExecProc;
WriteTransaction.Commit;
SchFilterDataSet.CloseOpen(true);
SchFilterDataSet.Locate('ID_SCH',ID_SCH,[]);
InsertSP.Free;
end;
end;
end;
end;
procedure TfrmCloseBook.cxButton4Click(Sender: TObject);
var DeleteSP:TpFibStoredProc;
begin
if (SchFilterDataSet.RecordCount>0)
then begin
DeleteSP:=TpFibStoredProc.Create(self);
DeleteSP.Database:=WorkDatabase;
DeleteSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
DeleteSP.StoredProcName:='MBOOK_PRINT_ITEMS_EXCL_DEL';
DeleteSP.Prepare;
DeleteSP.ParamByName('ID_SCH').Value:=SchFilterDataSet.FieldByName('ID_SCH').Value;
DeleteSP.ExecProc;
WriteTransaction.Commit;
SchFilterDataSet.CacheDelete;
DeleteSP.Free;
end;
end;
end.
|
unit LrVclUtils;
interface
uses
SysUtils, Windows, Types, Messages, Classes, Controls, Forms;
procedure LrAddForm(inForm: TForm; inParent: TWinControl;
inAlign: TAlign = alClient; inShow: Boolean = true); overload;
procedure LrAddForm(out outForm; inFormClass: TFormClass;
inParent: TWinControl; inAlign: TAlign = alClient;
inShow: Boolean = true); overload;
procedure LrFindComponentByClass(out inComponent; inOwner: TComponent;
inClass: TClass);
//function LrFindComponentByClass(inOwner: TComponent;
// inClass: TClass): TComponent;
function LrFindControlByClass(inOwner: TWinControl;
inClass: TClass): TControl;
function LrFindElderComponent(inControl: TControl;
const inClass: TClass): TComponent; overload;
procedure LrFindElderComponent(out outComponent; inControl: TControl;
const inClass: TClass); overload;
procedure LrNotifyControls(inCtrl: TWinControl; Msg: Word;
wParam: Pointer = nil);
procedure LrNotifyAll(inCtrl: TWinControl; Msg: Word; wParam: Pointer = nil);
function LrIsAs(inComponent: TComponent; const inIID: TGUID;
out outObj): Boolean;
function LrMin(inA, inB: Integer): Integer;
function LrMax(inA, inB: Integer): Integer;
function LrAbs(inValue: Integer): Integer;
function LrIsDigit(const inChar: Char): Boolean;
function LrStringIsDigits(const inString: string): Boolean;
function LrCat(const inAdd: array of string;
const inDelim: string = ' '): string; overload;
function LrCat(const inPre, inPost: string;
const inDelim: string = ' '): string; overload;
function LrWidth(const inRect: TRect): Integer;
function LrHeight(const inRect: TRect): Integer;
function LrValidateRect(const inRect: TRect): TRect;
function LrNameIsUnique(inOwner: TComponent; const inName: string): Boolean;
function LrUniqueName(inOwner: TComponent; const inClassName: string): string;
function LrLoadComponentFromStream(inComp: TComponent; inStream: TStream;
inOnError: TReaderError = nil): TComponent;
function LrLoadComponentFromString(const inString: string;
inComp: TComponent = nil; inOnError: TReaderError = nil): TComponent;
procedure LrLoadComponentFromFile(inComp: TComponent; const inFilename: string;
inOnError: TReaderError = nil);
function LrLoadComponentFromBinaryStream(inComp: TComponent; inStream: TStream;
inOnError: TReaderError = nil): TComponent;
function LrSaveComponentToString(inComp: TComponent): string;
procedure LrSaveComponentToStream(inComp: TComponent; inStream: TStream);
procedure LrSaveComponentToFile(inComp: TComponent; const inFilename: string);
procedure LrSaveComponentToBinaryStream(inComp: TComponent; inStream: TStream);
procedure LrCopyStreamToClipboard(inFmt: Cardinal; inS: TStream);
procedure LrCopyStreamFromClipboard(inFmt: Cardinal; inS: TStream);
function LrKeyIsDown(inCode: Integer): Boolean;
function LrGetShiftState: TShiftState;
function LrFindHandle(inHandle: HWND; inContainer: TWinControl): TWinControl;
function LrCompareFileDates(const inFileA, inFileB: string): Integer;
implementation
uses
Clipbrd;
procedure LrAddForm(inForm: TForm; inParent: TWinControl;
inAlign: TAlign = alClient; inShow: Boolean = true);
begin
with inForm do
begin
BorderIcons := [];
Caption := '';
BorderStyle := bsNone;
Align := inAlign;
Parent := inParent;
//if inShow then
// Show;
Visible := inShow;
end;
end;
procedure LrAddForm(out outForm; inFormClass: TFormClass; inParent: TWinControl;
inAlign: TAlign = alClient; inShow: Boolean = true);
begin
TForm(outForm) := inFormClass.Create(nil);
LrAddForm(TForm(outForm), inParent, inAlign, inShow);
end;
procedure LrFindComponentByClass(out inComponent; inOwner: TComponent;
inClass: TClass);
var
i: Integer;
begin
TComponent(inComponent) := nil;
if inOwner <> nil then
for i := 0 to Pred(inOwner.ComponentCount) do
if inOwner.Components[i] is inClass then
begin
TComponent(inComponent) := inOwner.Components[i];
break;
end;
end;
{
function LrFindComponentByClass(inOwner: TComponent;
inClass: TClass): TComponent;
var
i: Integer;
begin
Result := nil;
if inOwner <> nil then
for i := 0 to Pred(inOwner.ComponentCount) do
if inOwner.Components[i] is inClass then
begin
Result := inOwner.Components[i];
break;
end;
end;
}
function LrFindControlByClass(inOwner: TWinControl;
inClass: TClass): TControl;
var
i: Integer;
begin
Result := nil;
if inOwner <> nil then
for i := 0 to Pred(inOwner.ControlCount) do
if inOwner.Controls[i] is inClass then
begin
Result := inOwner.Controls[i];
break;
end;
end;
function LrFindParentFormOrFrame(inControl: TControl): TWinControl;
begin
Result := TWinControl(inControl);
while (Result <> nil) and not (Result is TCustomForm)
and not (Result is TCustomFrame) do
Result := TWinControl(Result.Parent);
end;
function LrFindElderComponent(inControl: TControl;
const inClass: TClass): TComponent;
var
f: TWinControl;
begin
Result := nil;
while (inControl <> nil) do
begin
f := LrFindParentFormOrFrame(inControl);
if (f = nil) then
break;
LrFindComponentByClass(Result, f, inClass);
if (Result <> nil) then
break;
inControl := f.Parent;
end;
end;
procedure LrFindElderComponent(out outComponent; inControl: TControl;
const inClass: TClass);
begin
TComponent(outComponent) := LrFindElderComponent(inControl, inClass);
end;
procedure LrNotifyControls(inCtrl: TWinControl; Msg: Word; wParam: Pointer);
var
m: TMessage;
begin
FillChar(m, SizeOf(TMessage), 0);
m.Msg := Msg;
m.wParam := Integer(wParam);
inCtrl.Broadcast(m);
end;
procedure LrNotifyAll(inCtrl: TWinControl; Msg: Word; wParam: Pointer);
var
i: Integer;
begin
LrNotifyControls(inCtrl, Msg, wParam);
with inCtrl do
for i := 0 to ControlCount - 1 do
if (Controls[i] is TWinControl) then
LrNotifyAll(TWinControl(Controls[i]), Msg, wParam);
end;
function LrIsAs(inComponent: TComponent; const inIID: TGUID;
out outObj): Boolean;
begin
with inComponent as IInterface do
Result := QueryInterface(inIID, outObj) = S_OK;
end;
function LrMax(inA, inB: Integer): Integer;
begin
if inB > inA then
Result := inB
else
Result := inA;
end;
function LrMin(inA, inB: Integer): Integer;
begin
if inB < inA then
Result := inB
else
Result := inA;
end;
function LrAbs(inValue: Integer): Integer;
begin
if inValue < 0 then
Result := -inValue
else
Result := inValue;
end;
function LrIsDigit(const inChar: Char): Boolean;
begin
Result := (inChar >= '0') and (inChar <= '9');
end;
function LrStringIsDigits(const inString: string): Boolean;
var
i: Integer;
begin
Result := false;
for i := 1 to Length(inString) do
if not LrIsDigit(inString[i]) then
exit;
Result := inString <> '';
end;
function LrCat(const inAdd: array of string;
const inDelim: string = ' '): string;
var
i: Integer;
begin
Result := '';
for i := 0 to Pred(Length(inAdd)) do
if inAdd[i] <> '' then
if Result = '' then
Result := inAdd[i]
else
Result := Result + inDelim + inAdd[i];
end;
function LrCat(const inPre, inPost: string;
const inDelim: string = ' '): string;
begin
if inPost = '' then
Result := inPre
else
if inPre = '' then
Result := inPost
else
Result := inPre + inDelim + inPost;
end;
function LrWidth(const inRect: TRect): Integer;
begin
Result := inRect.Right - inRect.Left;
end;
function LrHeight(const inRect: TRect): Integer;
begin
Result := inRect.Bottom - inRect.Top;
end;
function LrValidateRect(const inRect: TRect): TRect;
begin
with Result do
begin
if inRect.Right < inRect.Left then
begin
Left := inRect.Right;
Right := inRect.Left;
end
else begin
Left := inRect.Left;
Right := inRect.Right;
end;
if inRect.Bottom < inRect.Top then
begin
Top := inRect.Bottom;
Bottom := inRect.Top;
end
else begin
Top := inRect.Top;
Bottom := inRect.Bottom;
end;
end;
end;
function LrNameIsUnique(inOwner: TComponent; const inName: string): Boolean;
begin
Result := true;
while Result and (inOwner <> nil) do
begin
Result := inOwner.FindComponent(inName) = nil;
inOwner := inOwner.Owner;
end;
end;
function LrUniqueName(inOwner: TComponent; const inClassName: string): string;
var
base: string;
i: Integer;
begin
base := Copy(inClassName, 2, MAXINT);
i := 0;
repeat
Inc(i);
Result := base + IntToStr(i);
until LrNameIsUnique(inOwner, Result);
end;
procedure LrSaveComponentToBinaryStream(inComp: TComponent; inStream: TStream);
var
ms: TMemoryStream;
sz: Int64;
begin
ms := TMemoryStream.Create;
try
ms.WriteComponent(inComp);
ms.Position := 0;
sz := ms.Size;
inStream.Write(sz, 8);
inStream.CopyFrom(ms, sz);
finally
ms.Free;
end;
end;
function LrLoadComponentFromBinaryStream(inComp: TComponent; inStream: TStream;
inOnError: TReaderError): TComponent;
var
ms: TMemoryStream;
sz: Int64;
begin
inStream.Read(sz, 8);
ms := TMemoryStream.Create;
try
ms.CopyFrom(inStream, sz);
ms.Position := 0;
with TReader.Create(ms, 4096) do
try
OnError := inOnError;
Result := ReadRootComponent(inComp);
finally
Free;
end;
finally
ms.Free;
end;
end;
procedure LrSaveComponentToStream(inComp: TComponent; inStream: TStream);
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ms.WriteComponent(inComp);
ms.Position := 0;
ObjectBinaryToText(ms, inStream);
finally
ms.Free;
end;
end;
function LrLoadComponentFromStream(inComp: TComponent; inStream: TStream;
inOnError: TReaderError): TComponent;
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ObjectTextToBinary(inStream, ms);
ms.Position := 0;
with TReader.Create(ms, 4096) do
try
OnError := inOnError;
Result := ReadRootComponent(inComp);
finally
Free;
end;
finally
ms.Free;
end;
end;
function LrSaveComponentToString(inComp: TComponent): string;
var
s: TStringStream;
begin
s := TStringStream.Create('');
try
LrSaveComponentToStream(inComp, s);
Result := s.DataString;
finally
s.Free;
end;
end;
function LrLoadComponentFromString(const inString: string;
inComp: TComponent; inOnError: TReaderError): TComponent;
var
s: TStringStream;
begin
s := TStringStream.Create(inString);
try
//s.Position := 0;
Result := LrLoadComponentFromStream(inComp, s, inOnError);
finally
s.Free;
end;
end;
procedure LrSaveComponentToFile(inComp: TComponent; const inFilename: string);
var
fs: TFileStream;
begin
fs := TFileStream.Create(inFilename, fmCreate);
try
LrSaveComponentToStream(inComp, fs);
finally
fs.Free;
end;
end;
procedure LrLoadComponentFromFile(inComp: TComponent; const inFilename: string;
inOnError: TReaderError);
var
fs: TFileStream;
begin
if FileExists(inFilename) then
begin
fs := TFileStream.Create(inFilename, fmOpenRead);
try
LrLoadComponentFromStream(inComp, fs, inOnError);
finally
fs.Free;
end;
end;
end;
function LrKeyIsDown(inCode: Integer): Boolean;
begin
Result := Boolean(GetAsyncKeyState(inCode) shr 15);
end;
function LrGetShiftState: TShiftState;
begin
Result := [];
if LrKeyIsDown(VK_SHIFT) then
Include(Result, ssShift);
if LrKeyIsDown(VK_CONTROL) then
Include(Result, ssCTRL);
end;
function LrFindHandle(inHandle: HWND; inContainer: TWinControl): TWinControl;
var
i: Integer;
begin
Result := nil;
with inContainer do
if Handle = inHandle then
Result := inContainer
else
for i := 0 to Pred(ControlCount) do
if (inContainer.Controls[i] is TWinControl) then
begin
Result := LrFindHandle(inHandle, TWinControl(Controls[i]));
if Result <> nil then
break;
end;
end;
function LrCompareFileDates(const inFileA, inFileB: string): Integer;
begin
if not FileExists(inFileB) then
Result := 1
else if not FileExists(inFileA) then
Result := -1
else
Result := FileAge(inFileA) - FileAge(inFileB);
end;
procedure LrCopyStreamToClipboard(inFmt: Cardinal; inS: TStream);
var
hMem: THandle;
pMem: Pointer;
begin
inS.Position := 0;
hMem := GlobalAlloc(GHND or GMEM_DDESHARE, inS.Size);
if hMem <> 0 then
begin
pMem := GlobalLock(hMem);
if pMem <> nil then
begin
inS.Read(pMem^, inS.Size);
inS.Position := 0;
GlobalUnlock(hMem);
Clipboard.Open;
try
Clipboard.SetAsHandle(inFmt, hMem);
finally
Clipboard.Close;
end;
end
else begin
GlobalFree(hMem);
OutOfMemoryError;
end;
end else
OutOfMemoryError;
end;
procedure LrCopyStreamFromClipboard(inFmt: Cardinal; inS: TStream);
var
hMem: THandle;
pMem: Pointer;
begin
hMem := Clipboard.GetAsHandle(inFmt);
if hMem <> 0 then
begin
pMem := GlobalLock(hMem);
if pMem <> nil then
begin
inS.Write(pMem^, GlobalSize(hMem));
inS.Position := 0;
GlobalUnlock(hMem);
end else
raise Exception.Create(
'CopyStreamFromClipboard: could not lock global handle ' +
'obtained from clipboard!');
end;
end;
end.
|
unit Fornecedor;
interface
type
TFornecedor = class
private
FCodigo: string;
FNome: string;
FTelefone: string;
public
property Codigo: string read FCodigo write FCodigo;
property Nome: string read FNome write FNome;
property Telefone: string read FTelefone write FTelefone;
constructor Create; overload;
constructor Create(Codigo: string); overload;
constructor Create(Codigo, Nome, Telefone: string); overload;
end;
implementation
{ TFornecedor }
constructor TFornecedor.Create;
begin
end;
constructor TFornecedor.Create(Codigo: string);
begin
Self.Codigo := Codigo;
end;
constructor TFornecedor.Create(Codigo, Nome, Telefone: string);
begin
Self.Codigo := Codigo;
Self.Nome := Nome;
Self.Telefone := Telefone;
end;
end.
|
unit UListItem;
interface
Type
TListItem = class
Private
Info: string;
Next: TListItem;
Prev: TListItem;
FIsFirst: boolean;
FIsLast: boolean;
FIsAddBefore: boolean;
FIsAddAfter: boolean;
FIsDelete: boolean;
Public
Constructor Create(sInfo: string);
Function GetInfo: string;
Function GetPrevInfo: string;
Function GetNextInfo: string;
Function GetNext: TListItem;
Function GetPrev: TListItem;
Procedure SetInfo(sInfo: string);
Procedure SetNext(aNext: TListItem);
Procedure SetPrev(aPrev: TListItem);
function ToString(): string; override;
property IsFirst: boolean read FIsFirst write FIsFirst;
property IsLast: boolean read FIsLast write FIsLast;
property IsAddBefore: boolean read FIsAddBefore write FIsAddBefore;
property IsAddAfter: boolean read FIsAddAfter write FIsAddAfter;
property IsDelete: boolean read FIsDelete write FIsDelete;
End;
implementation
Constructor TListItem.Create(sInfo: string);
begin
Info := sInfo;
Next := nil;
Prev := nil;
FIsFirst := false;
FIsLast := true;
FIsAddBefore := false;
FIsAddAfter := false;
end;
Function TListItem.GetInfo: string;
begin
result := Info;
end;
Function TListItem.GetNextInfo: string;
begin
if Assigned(Next) then
result := 'ύλ. ' + Next.Info
else
result := 'nul';
end;
Function TListItem.GetPrevInfo: string;
begin
if Assigned(Prev) then
result := 'ύλ. ' + Prev.Info
else
result := 'nul';
end;
Function TListItem.GetNext: TListItem;
begin
result := Next;
end;
Function TListItem.GetPrev: TListItem;
begin
result := Prev;
end;
Procedure TListItem.SetInfo(sInfo: string);
begin
Info := sInfo;
end;
Procedure TListItem.SetNext(aNext: TListItem);
begin
Next := aNext;
end;
Procedure TListItem.SetPrev(aPrev: TListItem);
begin
Prev := aPrev;
end;
function TListItem.ToString(): string;
begin
result := 'έλ.' + Info;
end;
end.
|
unit UDTODeleteText;
interface
uses
Classes, Controls, Forms, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeDeleteTextDlg = class(TForm)
btnOk: TButton;
btnCancel: TButton;
pnlDeleteText: TPanel;
editTextStart: TEdit;
lblTextStart: TLabel;
lblTextEnd: TLabel;
editTextEnd: TEdit;
procedure FormCreate(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
end;
var
CrpeDeleteTextDlg: TCrpeDeleteTextDlg;
implementation
{$R *.DFM}
uses SysUtils, UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeDeleteTextDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeDeleteTextDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
if IsNumeric(editTextStart.Text) and IsNumeric(editTextEnd.Text) then
Cr.TextObjects.Item.DeleteText(StrToInt(editTextStart.Text),
StrToInt(editTextEnd.Text));
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeDeleteTextDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeDeleteTextDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Release;
end;
end.
|
{------------------------------------------------------------------------------------}
{program p018_000 exercises production #018 }
{subprogram_head -> FUNCTION ID subprogram_parameters : standard_type ; }
{------------------------------------------------------------------------------------}
{Author: Thomas R. Turner }
{E-Mail: trturner@uco.edu }
{Date: January, 2012 }
{------------------------------------------------------------------------------------}
{Copyright January, 2012 by Thomas R. Turner }
{Do not reproduce without permission from Thomas R. Turner. }
{------------------------------------------------------------------------------------}
program p018_000;
function max(a,b:integer):integer;
begin{max}
if a>b then max:=a else max:=b
end{max};
procedure print(c,d:integer);
var g:array[1..20] of real;
begin{print}
writeln('The maximum of ',c,' and ',d,' is ',max(c,d))
end{print};
begin{p018_000}
print(2,3)
end{p018_000}.
|
unit uEnums;
{$I ..\Include\IntXLib.inc}
interface
type
/// <summary>
/// <see cref="TIntX" /> divide results to return.
/// </summary>
TDivModResultFlags = (
/// <summary>
/// Divident is returned.
/// </summary>
dmrfDiv = 1,
/// <summary>
/// Remainder is returned.
/// </summary>
dmrfMod = 2);
/// <summary>
/// Big integers multiply mode used in <see cref="TIntX" />.
/// </summary>
TMultiplyMode = (
/// <summary>
/// FHT (Fast Hartley Transform) is used for really big integers.
/// Time estimate is O(n * log n).
/// Default mode.
/// </summary>
mmAutoFht,
/// <summary>
/// Classic method is used.
/// Time estimate is O(n ^ 2).
/// </summary>
mmClassic);
/// <summary>
/// Big integers divide mode used in <see cref="TIntX" />.
/// </summary>
TDivideMode = (
/// <summary>
/// Newton approximation algorithm is used for really big integers.
/// Time estimate is same as for multiplication.
/// Default mode.
/// </summary>
dmAutoNewton,
/// <summary>
/// Classic method is used.
/// Time estimate is O(n ^ 2).
/// </summary>
dmClassic);
/// <summary>
/// Big integers parsing mode used in <see cref="TIntX" />.
/// </summary>
TParseMode = (
/// <summary>
/// Fast method which uses divide-by-two approach and fast multiply to parse numbers.
/// Time estimate is O(n * [log n]^2).
/// Default mode.
/// </summary>
pmFast,
/// <summary>
/// Classic method is used (using multiplication).
/// Time estimate is O(n ^ 2).
/// </summary>
pmClassic);
/// <summary>
/// Big integers to string conversion mode used in <see cref="TIntX" />.
/// </summary>
TToStringMode = (
/// <summary>
/// Fast method which uses divide-by-two approach to convert numbers.
/// Default mode.
/// </summary>
tsmFast,
/// <summary>
/// Classic method is used (using division).
/// Time estimate is O(n ^ 2).
/// </summary>
tsmClassic);
implementation
// uses
// IntX;
end.
|
program questao6;
{
Autor: Hugo Deiró Data: 02/06/2012
- Este programa calcula a área de uma circunferência.
Fórmula: PI*R²;
}
const
PI = 3.14;
var
raio : real;
begin
write('Insira o raio do círculo: ');
readln(raio);
writeln;
write('A área da circunferência é: ',(PI*sqr(raio)):6:2);
end.
|
{----------------------------------------------------------------
Nome: UntwIRCSecao
Descrição: Unit que contém a definição do form TwIRCSecao, que
contém o comportamento padrão usado de base para construção dos
outros forms(wIRCPVT, wIRCCanal, wIRCStatus).
O comportamento padrão está descrito abaixo:
-Procedure AdLinha (Adicina texto a área de texto TMemo(MemTexto))
-Iteração com a BarraJanelas do form principal, que funciona como
uma barra de tarefas. O form ao ser criado adiciona uma barra ao
objeto BarraJanelas e obedece aos comandos tal como minimizar,
restaurar.
As descrições individuais estão na implementação de cada uma.
----------------------------------------------------------------}
unit UntwIRCSecao;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, Menus, Buttons, FatThings;
type
TwIRCSecao = class(TForm)
CmdTexto: TEdit;
MenuContexto: TPopupMenu;
Limpar1: TMenuItem;
MemTexto: TFatMemo;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure MemTextoaMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure MemTextoaMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
Estado: TWindowState;
Ativo: boolean;
procedure BarraClick(Sender: TObject);
procedure Tamanho(var Menssagem: TWMSize); message WM_SIZE;
public
{ Public declarations }
Barra: TSpeedButton;
procedure AdLinha(Texto: string);
end;
var
wIRCSecao: TwIRCSecao;
implementation
uses UntPrincipal;
{$R *.DFM}
procedure TwIRCSecao.BarraClick(Sender: TObject);
{Ativamento da barra de tarefas}
begin {Verifica se ela não está desativada(minimizada)}
if (Ativo) then
begin {Caso ela esteja focada, então ela é desativada}
if FrmPrincipal.ActiveMDIChild = Self then
begin {Esconde janela}
Ativo:=false;
ShowWindow(Self.Handle, SW_HIDE);
FrmPrincipal.Previous;
end
else {Dá foco}
Self.BringToFront;
end
else
begin {Mostra janela, restaurando suas características}
if (Estado = wsMinimized) then
ShowWindow(Self.Handle, SW_RESTORE)
else
ShowWindow(Self.Handle, SW_SHOW);
Ativo:=true;
Self.Perform(WM_MDIRESTORE, Self.Handle, 0);
Self.BringToFront;
end;
end;
procedure TwIRCSecao.FormCreate(Sender: TObject);
begin {Criação da barra na BarraJanelas}
MemTexto.Lines.Clear;
Ativo:=true;
Barra:=TSpeedButton.Create(Self);
with Barra do
begin {São definidas suas características básicas}
Parent:=FrmPrincipal.BarraJanelas;
OnClick:=BarraClick; {Procedimento local para controle da barra}
{Características básicas}
ShowHint:=true;
GroupIndex:=1;
Width:=100;
Align:=alLeft;
Flat:=true;
Down:=true;
AllowAllUp:=true;
Margin:=0;
end;
end;
procedure TwIRCSecao.Tamanho(var Menssagem: TWMSize);
begin {Intercepta redimencionamento da janela}
if (Menssagem.SizeType = SIZE_MINIMIZED) then
begin {Verifica se ela foi minimizada}
Ativo:=false; {variável de controle}
ShowWindow(Self.Handle, SW_HIDE);
Self.Perform(WM_MDIRESTORE, Self.Handle, 0);
FrmPrincipal.Previous;
Barra.Down:=false;
Estado:=wsMinimized;
end
else if (Menssagem.SizeType = SIZE_MAXIMIZED) then
Estado:=wsMaximized;
inherited;
end;
procedure TwIRCSecao.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TwIRCSecao.MemTextoaMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Posicao: TPoint;
begin {Não permite que o menu de contexto padrão do Windows intereja}
GetCursorPos(Posicao); {Um menu Popup é acinado na posição do mouse}
if (Button = mbRight) then
MenuContexto.Popup(Posicao.x, Posicao.y);
end;
procedure TwIRCSecao.MemTextoaMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin {Característica padrão do mIRC}
{ MemTexto.CopyToClipboard; {Para copiar um texto basta seleciona-lo
MemTexto.SelLength:=0;
CmdTexto.SetFocus;}
end;
procedure TwIRCSecao.AdLinha(Texto: string);
begin
MemTexto.Lines.AddLineWithIrcTags(Texto);
FrmPrincipal.RolarTexto(MemTexto);
end;
procedure TwIRCSecao.FormActivate(Sender: TObject);
begin
Barra.Down:=true;
end;
end.
|
unit NSqlQueries;
{$I ..\NSql.Inc}
interface
uses
NSqlObj, NSqlIntf, NSqlTypes;
type
TJoin = class(TStatementElement, IJoin)
private
FStructure: IStructureWithFields;
FCondition: ISqlCondition;
protected
function GetElementType: TStatementElementType; override;
function GetParams: TSqlParamIntfArray; override;
function GetSelectableArray: TSelectableIntfArray; override;
{ IJoin }
function GetStructure: IStructureWithFields;
function GetCondition: ISqlCondition;
public
constructor Create(AStructure: IStructureWithFields; ACondition: ISqlCondition);
end;
TTypedJoin = class(TJoin, IJoinType)
private
FJoinType: TJoinType;
protected
{ IJoinType }
function GetJoinType: TJoinType;
public
constructor Create(AJoinType: TJoinType; ATable: IStructureWithFields; ACondition: ISqlCondition);
end;
TUpdateElement = class(TStatementElement, IUpdateElement)
private
FField: IField;
FValue: IStatementElement;
protected
function GetParams: TSqlParamIntfArray; override;
function GetSelectableArray: TSelectableIntfArray; override;
{ IUpdateElement }
function GetField: IField;
function GetValue: IStatementElement;
public
constructor Create(AField: IField; AValue: IStatementElement);
end;
TBaseUpdateQuery = class(TStatementElement, IBaseUpdateQuery)
private
FUpdates: TUpdateElementIntfArray;
FWhere: ISqlCondition;
protected
function GetParams: TSqlParamIntfArray; override;
function GetSelectableArray: TSelectableIntfArray; override;
{ IBaseUpdateQuery }
function Update(const Elements: array of IUpdateElement): IBaseUpdateQuery; overload;
function Update(const Elements: TUpdateElementIntfArray): IBaseUpdateQuery; overload;
function Where(Condition: ISqlCondition): IBaseUpdateQuery;
function AndWhere(Condition: ISqlCondition): IBaseUpdateQuery;
function OrWhere(Condition: ISqlCondition): IBaseUpdateQuery;
function GetUpdateElements: TUpdateElementIntfArray;
function GetWhere: ISqlCondition;
function GetReturnsElements: TSelectableIntfArray;
end;
TBaseInsertQuery = class(TStatementElement, IBaseInsertQuery)
private
FUpdates: TUpdateElementIntfArray;
FReturns: TSelectableIntfArray;
protected
function GetParams: TSqlParamIntfArray; override;
function GetSelectableArray: TSelectableIntfArray; override;
{ IBaseInsertQuery }
function Insert(const Elements: array of IUpdateElement): IBaseInsertQuery; overload;
function Insert(const Elements: TUpdateElementIntfArray): IBaseInsertQuery; overload;
function Returns(const Fields: array of ISelectable): IBaseInsertQuery;
function GetInsertElements: TUpdateElementIntfArray;
function GetReturnsElements: TSelectableIntfArray;
end;
TBaseDeleteQuery = class(TStatementElement, IBaseDeleteQuery)
private
FTable: ITable;
FWhere: ISqlCondition;
protected
function GetParams: TSqlParamIntfArray; override;
function GetSelectableArray: TSelectableIntfArray; override;
{ IBaseDeleteQuery }
function DeleteFrom(Table: ITable) : IBaseDeleteQuery;
function Where(Condition: ISqlCondition): IBaseDeleteQuery;
function AndWhere(Condition: ISqlCondition): IBaseDeleteQuery;
function OrWhere(Condition: ISqlCondition): IBaseDeleteQuery;
function GetFromTable: ITable;
function GetWhere: ISqlCondition;
function GetReturnsElements: TSelectableIntfArray;
end;
TExecQueryResult = class(TInterfacedObject, IExecQueryResult)
end;
TInsertOrUpdateOrDeleteQueryResult = class(TExecQueryResult)
private
FRowsAffected: Int64;
protected
function GetRowsAffected: Int64;
public
constructor Create(const ARowsAffected: Int64);
end;
TUpdateQueryResult = class(TInsertOrUpdateOrDeleteQueryResult, IUpdateQueryResult)
end;
TInsertQueryResult = class(TInsertOrUpdateOrDeleteQueryResult, IInsertQueryResult)
end;
TDeleteQueryResult = class(TInsertOrUpdateOrDeleteQueryResult, IDeleteQueryResult)
end;
TOrderByElement = class(TStatementElement, IOrderByElement)
private
FElements: TOrderByElementRecArray;
protected
{ IOrderByElement }
function GetElements: TOrderByElementRecArray;
public
constructor Create(const AElements: TOrderByElementRecArray);
end;
TRowsElement = class(TStatementElement, IRowsElement)
private
FFromSelectable: ISelectable;
FToSelectable: ISelectable;
protected
{ IRowsElement }
function GetFromSelectable: ISelectable;
function GetToSelectable: ISelectable;
public
constructor Create(AFromSelectable, AToSelectable: ISelectable);
end;
TBaseSelectQuery = class(TSqlObj, IStatementElement, IBaseSelectQuery)
private
FSelectables: TSelectableIntfArray;
FGroupBy: TSelectableIntfArray;
FFromStructures: TStructureWithFieldsIntfArray;
FJoins: TJoinIntfArray;
FWhere: ISqlCondition;
FOrderBy: IOrderByElement;
FIsDistinct: Boolean;
FFirst: ISelectable;
FSkip: ISelectable;
FRowsElement: IRowsElement;
FRowsElementObj: TRowsElement;
FHaving: ISqlCondition;
protected
{ IStatementElement }
function GetElementType: TStatementElementType;
function GetParams: TSqlParamIntfArray;
function GetSelectableArray: TSelectableIntfArray;
{ IBaseSelectQuery }
function Select(const What: array of ISelectable): IBaseSelectQuery; overload;
function Select(const What: TSelectableIntfArray): IBaseSelectQuery; overload;
//// function Select(const What: ISelectable): IBaseSelectQuery; overload;
function From(FromWhat: IStructureWithFields): IBaseSelectQuery; overload;
function From(const FromWhat: array of IStructureWithFields): IBaseSelectQuery; overload;
function InnerJoin(Table: IStructureWithFields; Condition: ISqlCondition): IBaseSelectQuery; overload;
function LeftJoin(Table: IStructureWithFields; Condition: ISqlCondition): IBaseSelectQuery; overload;
function Where(Condition: ISqlCondition): IBaseSelectQuery; overload;
function AndWhere(Condition: ISqlCondition): IBaseSelectQuery; overload;
function OrWhere(Condition: ISqlCondition): IBaseSelectQuery; overload;
function OrderBy(const ByWhat: array of TOrderByElementRec): IBaseSelectQuery; overload;
function OrderBy(const ByWhat: TOrderByElementRecArray): IBaseSelectQuery; overload;
function GroupBy(const ByWhat: array of ISelectable): IBaseSelectQuery; overload;
function GroupBy(const ByWhat: TSelectableIntfArray): IBaseSelectQuery; overload;
function Distinct: IBaseSelectQuery;
function First(Selectable: ISelectable): IBaseSelectQuery;
function Skip(Selectable: ISelectable): IBaseSelectQuery;
function RowsFrom(Selectable: ISelectable): IBaseSelectQuery;
function RowsTo(Selectable: ISelectable): IBaseSelectQuery;
function Having(Condition: ISqlCondition): IBaseSelectQuery;
//
function GetSelectables: TSelectableIntfArray;
function GetFromStructures: TStructureWithFieldsIntfArray;
function GetJoins: TJoinIntfArray;
function GetWhere: ISqlCondition;
function GetOrderBy: IOrderByElement;
function GetGroupBy: TSelectableIntfArray;
function IsDistinct: Boolean;
function GetFirst: ISelectable;
function GetSkip: ISelectable;
function GetRowsElement: IRowsElement;
function GetHaving: ISqlCondition;
end;
function MakeSelectableIntfArray(const Src: array of ISelectable): TSelectableIntfArray;
function MakeUpdateElement(Field: IField; StatementElement: IStatementElement): IUpdateElement;
//function BaseSelect(const What: array of ISelectable): IBaseSelectQuery; overload;
function BaseSelect(const What: TSelectableIntfArray): IBaseSelectQuery; overload;
function BaseInsert(const Elements: array of IUpdateElement): IBaseInsertQuery; overload;
function BaseInsert(const Elements: TUpdateElementIntfArray): IBaseInsertQuery; overload;
function BaseUpdate(const Elements: array of IUpdateElement): IBaseUpdateQuery; overload;
function BaseUpdate(const Elements: TUpdateElementIntfArray): IBaseUpdateQuery; overload;
function BaseDeleteFrom(Table: ITable): IBaseDeleteQuery;
implementation
//function BaseSelect(const What: array of ISelectable): IBaseSelectQuery; overload;
//begin
// Result := TBaseSelectQuery.Create;
// Result.Select(What);
//end;
function BaseSelect(const What: TSelectableIntfArray): IBaseSelectQuery; overload;
begin
Result := TBaseSelectQuery.Create;
Result.Select(What);
end;
function BaseInsert(const Elements: array of IUpdateElement): IBaseInsertQuery; overload;
begin
Result := TBaseInsertQuery.Create;
Result.Insert(Elements);
end;
function BaseInsert(const Elements: TUpdateElementIntfArray): IBaseInsertQuery; overload;
begin
Result := TBaseInsertQuery.Create;
Result.Insert(Elements);
end;
function BaseUpdate(const Elements: array of IUpdateElement): IBaseUpdateQuery; overload;
begin
Result := TBaseUpdateQuery.Create;
Result.Update(Elements);
end;
function BaseUpdate(const Elements: TUpdateElementIntfArray): IBaseUpdateQuery; overload;
begin
Result := TBaseUpdateQuery.Create;
Result.Update(Elements);
end;
function BaseDeleteFrom(Table: ITable): IBaseDeleteQuery;
begin
Result := TBaseDeleteQuery.Create;
Result.DeleteFrom(Table);
end;
function MakeSelectableIntfArray(const Src: array of ISelectable): TSelectableIntfArray;
var
I: Integer;
begin
SetLength(Result, Length(Src));
for I := 0 to High(Src) do
Result[I] := Src[I];
end;
function MakeUpdateElement(Field: IField; StatementElement: IStatementElement): IUpdateElement;
begin
Result := TUpdateElement.Create(Field, StatementElement);
end;
//procedure AddParams(var Params: TSqlParamIntfArray; const What: TSqlParamIntfArray);
//var
// I: Integer;
// StartIdx: Integer;
//begin
// StartIdx := Length(Params);
// SetLength(Params, Length(Params) + Length(What));
// for I := 0 to High(What) do
// Params[StartIdx + I] := What[I];
//end;
{ TJoin }
constructor TJoin.Create(AStructure: IStructureWithFields; ACondition: ISqlCondition);
begin
inherited Create;
FStructure := AStructure;
FCondition := ACondition;
end;
function TJoin.GetStructure: IStructureWithFields;
begin
Result := FStructure;
end;
function TJoin.GetParams: TSqlParamIntfArray;
begin
Result := inherited GetParams;
AddParams(Result, FStructure.GetParams);
AddParams(Result, FCondition.GetParams);
end;
function TJoin.GetSelectableArray: TSelectableIntfArray;
begin
Result := inherited GetSelectableArray;
AddSelectables(Result, FStructure.GetSelectableArray);
AddSelectables(Result, FCondition.GetSelectableArray);
end;
function TJoin.GetCondition: ISqlCondition;
begin
Result := FCondition;
end;
function TJoin.GetElementType: TStatementElementType;
begin
Result := setJoin;
end;
{ TTypedJoin }
constructor TTypedJoin.Create(AJoinType: TJoinType; ATable: IStructureWithFields;
ACondition: ISqlCondition);
begin
inherited Create(ATable, ACondition);
FJoinType := AJoinType;
end;
function TTypedJoin.GetJoinType: TJoinType;
begin
Result := FJoinType;
end;
{ TUpdateElement }
constructor TUpdateElement.Create(AField: IField;
AValue: IStatementElement);
begin
inherited Create;
FField := AField;
FValue := AValue;
end;
function TUpdateElement.GetField: IField;
begin
Result := FField;
end;
function TUpdateElement.GetParams: TSqlParamIntfArray;
begin
Result := FValue.GetParams;
end;
function TUpdateElement.GetSelectableArray: TSelectableIntfArray;
begin
Result := FValue.GetSelectableArray;
end;
function TUpdateElement.GetValue: IStatementElement;
begin
Result := FValue;
end;
{ TBaseUpdateQuery }
function TBaseUpdateQuery.AndWhere(Condition: ISqlCondition): IBaseUpdateQuery;
begin
Result := Self;
if not Assigned(FWhere) then
FWhere := Condition
else
FWhere := FWhere.and_(Condition);
end;
function TBaseUpdateQuery.OrWhere(Condition: ISqlCondition): IBaseUpdateQuery;
begin
Result := Self;
if not Assigned(FWhere) then
FWhere := Condition
else
FWhere := FWhere.or_(Condition);
end;
function TBaseUpdateQuery.Where(Condition: ISqlCondition): IBaseUpdateQuery;
begin
Result := Self;
FWhere := Condition;
end;
function TBaseUpdateQuery.Update(
const Elements: TUpdateElementIntfArray): IBaseUpdateQuery;
var
I: Integer;
Len: Integer;
begin
Result := Self;
Len := Length(FUpdates);
SetLength(FUpdates, Len + Length(Elements));
for I := 0 to High(Elements) do
FUpdates[Len + I] := Elements[I];
end;
function TBaseUpdateQuery.Update(
const Elements: array of IUpdateElement): IBaseUpdateQuery;
var
I: Integer;
Len: Integer;
begin
Result := Self;
Len := Length(FUpdates);
SetLength(FUpdates, Len + Length(Elements));
for I := 0 to High(Elements) do
FUpdates[Len + I] := Elements[I];
end;
function TBaseUpdateQuery.GetUpdateElements: TUpdateElementIntfArray;
begin
Result := FUpdates;
end;
function TBaseUpdateQuery.GetWhere: ISqlCondition;
begin
Result := FWhere;
end;
function TBaseUpdateQuery.GetParams: TSqlParamIntfArray;
var
I: Integer;
begin
Result := nil;
for I := 0 to High(FUpdates) do
AddParams(Result, FUpdates[I].GetParams);
if Assigned(FWhere) then
AddParams(Result, FWhere.GetParams);
end;
function TBaseUpdateQuery.GetReturnsElements: TSelectableIntfArray;
begin
Result := nil;
end;
function TBaseUpdateQuery.GetSelectableArray: TSelectableIntfArray;
var
I: Integer;
begin
Result := nil;
for I := 0 to High(FUpdates) do
AddSelectables(Result, FUpdates[I].GetSelectableArray);
if Assigned(FWhere) then
AddSelectables(Result, FWhere.GetSelectableArray);
end;
{ TBaseInsertQuery }
function TBaseInsertQuery.GetInsertElements: TUpdateElementIntfArray;
begin
Result := FUpdates;
end;
function TBaseInsertQuery.GetParams: TSqlParamIntfArray;
var
I: Integer;
begin
Result := nil;
for I := 0 to High(FUpdates) do
AddParams(Result, FUpdates[I].GetParams);
end;
function TBaseInsertQuery.GetReturnsElements: TSelectableIntfArray;
begin
Result := FReturns;
end;
function TBaseInsertQuery.GetSelectableArray: TSelectableIntfArray;
var
I: Integer;
begin
Result := nil;
for I := 0 to High(FUpdates) do
AddSelectables(Result, FUpdates[I].GetSelectableArray);
end;
function TBaseInsertQuery.Insert(const Elements: TUpdateElementIntfArray): IBaseInsertQuery;
var
I: Integer;
Len: Integer;
begin
Len := Length(FUpdates);
SetLength(FUpdates, Len + Length(Elements));
for I := 0 to High(Elements) do
FUpdates[Len + I] := Elements[I];
Result := Self;
end;
function TBaseInsertQuery.Returns(const Fields: array of ISelectable): IBaseInsertQuery;
var
I: Integer;
begin
FReturns := nil;
SetLength(FReturns, Length(Fields));
for I := 0 to High(Fields) do
begin
FReturns[I] := Fields[I];
end;
Result := Self;
end;
function TBaseInsertQuery.Insert(const Elements: array of IUpdateElement): IBaseInsertQuery;
var
I: Integer;
Len: Integer;
begin
Len := Length(FUpdates);
SetLength(FUpdates, Len + Length(Elements));
for I := 0 to High(Elements) do
FUpdates[Len + I] := Elements[I];
Result := Self;
end;
{ TBaseDeleteQuery }
function TBaseDeleteQuery.AndWhere(Condition: ISqlCondition): IBaseDeleteQuery;
begin
Result := Self;
if not Assigned(FWhere) then
FWhere := Condition
else
FWhere := FWhere.and_(Condition);
end;
function TBaseDeleteQuery.OrWhere(Condition: ISqlCondition): IBaseDeleteQuery;
begin
Result := Self;
if not Assigned(FWhere) then
FWhere := Condition
else
FWhere := FWhere.or_(Condition);
end;
function TBaseDeleteQuery.Where(Condition: ISqlCondition): IBaseDeleteQuery;
begin
Result := Self;
FWhere := Condition;
end;
function TBaseDeleteQuery.GetWhere: ISqlCondition;
begin
Result := FWhere;
end;
function TBaseDeleteQuery.GetParams: TSqlParamIntfArray;
begin
Result := nil;
if Assigned(FWhere) then
AddParams(Result, FWhere.GetParams);
end;
function TBaseDeleteQuery.GetReturnsElements: TSelectableIntfArray;
begin
Result := nil;
end;
function TBaseDeleteQuery.GetSelectableArray: TSelectableIntfArray;
begin
Result := nil;
if Assigned(FWhere) then
AddSelectables(Result, FWhere.GetSelectableArray);
end;
function TBaseDeleteQuery.GetFromTable: ITable;
begin
Result := FTable;
end;
function TBaseDeleteQuery.DeleteFrom(Table: ITable): IBaseDeleteQuery;
begin
FTable := Table;
Result := Self;
end;
{ TInsertOrUpdateOrDeleteQueryResult }
constructor TInsertOrUpdateOrDeleteQueryResult.Create(const ARowsAffected: Int64);
begin
inherited Create;
FRowsAffected := ARowsAffected;
end;
function TInsertOrUpdateOrDeleteQueryResult.GetRowsAffected: Int64;
begin
Result := FRowsAffected;
end;
{ TOrderByElement }
constructor TOrderByElement.Create(const AElements: TOrderByElementRecArray);
begin
inherited Create;
FElements := AElements;
end;
function TOrderByElement.GetElements: TOrderByElementRecArray;
begin
Result := FElements;
end;
{ TBaseSelectQuery }
function TBaseSelectQuery.AndWhere(Condition: ISqlCondition): IBaseSelectQuery;
begin
Result := Self;
if not Assigned(FWhere) then
FWhere := Condition
else
FWhere := FWhere.and_(Condition);
end;
function TBaseSelectQuery.Distinct: IBaseSelectQuery;
begin
FIsDistinct := True;
Result := Self;
end;
function TBaseSelectQuery.From(FromWhat: IStructureWithFields): IBaseSelectQuery;
begin
Result := Self;
SetLength(FFromStructures, Length(FFromStructures) + 1);
FFromStructures[High(FFromStructures)] := FromWhat;
end;
function TBaseSelectQuery.First(Selectable: ISelectable): IBaseSelectQuery;
begin
Result := Self;
FFirst := Selectable;
end;
function TBaseSelectQuery.From(
const FromWhat: array of IStructureWithFields): IBaseSelectQuery;
var
I: Integer;
begin
Result := Self;
for I := 0 to High(FromWhat) do
begin
SetLength(FFromStructures, Length(FFromStructures) + 1);
FFromStructures[High(FFromStructures)] := FromWhat[I];
end;
end;
function TBaseSelectQuery.GetElementType: TStatementElementType;
begin
Result := setBaseSelectQuery;
end;
function TBaseSelectQuery.GetFirst: ISelectable;
begin
Result := FFirst;
end;
function TBaseSelectQuery.GetFromStructures: TStructureWithFieldsIntfArray;
begin
Result := FFromStructures;
end;
function TBaseSelectQuery.GetGroupBy: TSelectableIntfArray;
begin
Result := FGroupBy;
end;
function TBaseSelectQuery.GetHaving: ISqlCondition;
begin
Result := FHaving;
end;
function TBaseSelectQuery.GetJoins: TJoinIntfArray;
begin
Result := FJoins;
end;
function TBaseSelectQuery.GetOrderBy: IOrderByElement;
begin
Result := FOrderBy;
end;
function TBaseSelectQuery.GetParams: TSqlParamIntfArray;
var
I: Integer;
OrderByElements: TOrderByElementRecArray;
begin
Result := nil;
for I := 0 to High(FSelectables) do
AddParams(Result, FSelectables[I].GetParams);
for I := 0 to High(FJoins) do
AddParams(Result, FJoins[I].GetParams);
if Assigned(FWhere) then
AddParams(Result, FWhere.GetParams);
if Assigned(FFromStructures) then
for I := 0 to High(FFromStructures) do
AddParams(Result, FFromStructures[I].GetParams);
if Assigned(FOrderBy) then
begin
OrderByElements := FOrderBy.Elements;
for I := 0 to High(OrderByElements) do
AddParams(Result, OrderByElements[I].Element.GetParams);
end;
for I := 0 to High(FGroupBy) do
AddParams(Result, FGroupBy[I].GetParams);
if Assigned(FFirst) then
AddParams(Result, FFirst.GetParams);
end;
function TBaseSelectQuery.GetRowsElement: IRowsElement;
begin
Result := FRowsElement;
end;
function TBaseSelectQuery.GetSelectableArray: TSelectableIntfArray;
var
I: Integer;
OrderByElements: TOrderByElementRecArray;
begin
Result := nil;
for I := 0 to High(FSelectables) do
AddSelectables(Result, FSelectables[I].GetSelectableArray);
for I := 0 to High(FJoins) do
AddSelectables(Result, FJoins[I].GetSelectableArray);
if Assigned(FWhere) then
AddSelectables(Result, FWhere.GetSelectableArray);
if Assigned(FFromStructures) then
for I := 0 to High(FFromStructures) do
AddSelectables(Result, FFromStructures[I].GetSelectableArray);
if Assigned(FOrderBy) then
begin
OrderByElements := FOrderBy.Elements;
for I := 0 to High(OrderByElements) do
AddSelectables(Result, OrderByElements[I].Element.GetSelectableArray);
end;
for I := 0 to High(FGroupBy) do
AddSelectables(Result, FGroupBy[I].GetSelectableArray);
if Assigned(FFirst) then
AddSelectables(Result, FFirst.GetSelectableArray);
end;
function TBaseSelectQuery.GetSelectables: TSelectableIntfArray;
begin
Result := FSelectables;
end;
function TBaseSelectQuery.GetSkip: ISelectable;
begin
Result := FSkip;
end;
function TBaseSelectQuery.GetWhere: ISqlCondition;
begin
Result := FWhere;
end;
function TBaseSelectQuery.GroupBy(
const ByWhat: TSelectableIntfArray): IBaseSelectQuery;
var
I: Integer;
begin
SetLength(FGroupBy, Length(FGroupBy) + Length(ByWhat));
for I := 0 to High(ByWhat) do
FGroupBy[Length(FGroupBy) - Length(ByWhat) + I] := ByWhat[I];
Result := Self;
end;
function TBaseSelectQuery.Having(
Condition: ISqlCondition): IBaseSelectQuery;
begin
Result := Self;
FHaving := Condition;
end;
function TBaseSelectQuery.GroupBy(
const ByWhat: array of ISelectable): IBaseSelectQuery;
begin
Result := GroupBy(MakeSelectableIntfArray(ByWhat));
end;
function TBaseSelectQuery.InnerJoin(Table: IStructureWithFields;
Condition: ISqlCondition): IBaseSelectQuery;
begin
Result := Self;
SetLength(FJoins, Length(FJoins) + 1);
FJoins[High(FJoins)] := TTypedJoin.Create(jtInner, Table, Condition);
end;
function TBaseSelectQuery.IsDistinct: Boolean;
begin
Result := FIsDistinct;
end;
function TBaseSelectQuery.LeftJoin(Table: IStructureWithFields;
Condition: ISqlCondition): IBaseSelectQuery;
begin
Result := Self;
SetLength(FJoins, Length(FJoins) + 1);
FJoins[High(FJoins)] := TTypedJoin.Create(jtLeft, Table, Condition);
end;
function TBaseSelectQuery.OrderBy(
const ByWhat: array of TOrderByElementRec): IBaseSelectQuery;
var
I: Integer;
Elements: TOrderByElementRecArray;
begin
SetLength(Elements, Length(ByWhat));
for I := 0 to High(ByWhat) do
Elements[I] := ByWhat[I];
Result := OrderBy(Elements);
end;
function TBaseSelectQuery.OrderBy(
const ByWhat: TOrderByElementRecArray): IBaseSelectQuery;
begin
Result := Self;
FOrderBy := TOrderByElement.Create(ByWhat);
end;
function TBaseSelectQuery.OrWhere(Condition: ISqlCondition): IBaseSelectQuery;
begin
Result := Self;
if not Assigned(FWhere) then
FWhere := Condition
else
FWhere := FWhere.or_(Condition);
end;
function TBaseSelectQuery.RowsFrom(
Selectable: ISelectable): IBaseSelectQuery;
begin
if Assigned(FRowsElementObj) then
FRowsElementObj.FFromSelectable := Selectable
else
begin
FRowsElementObj := TRowsElement.Create(Selectable, nil);
FRowsElement := FRowsElementObj;
end;
end;
function TBaseSelectQuery.RowsTo(Selectable: ISelectable): IBaseSelectQuery;
begin
if Assigned(FRowsElementObj) then
FRowsElementObj.FToSelectable := Selectable
else
begin
FRowsElementObj := TRowsElement.Create(nil, Selectable);
FRowsElement := FRowsElementObj;
end;
end;
function TBaseSelectQuery.Select(
const What: TSelectableIntfArray): IBaseSelectQuery;
var
I: Integer;
Len: Integer;
begin
Result := Self;
Len := Length(FSelectables);
SetLength(FSelectables, Len + Length(What));
for I := 0 to High(What) do
FSelectables[Len + I] := What[I];
end;
function TBaseSelectQuery.Skip(Selectable: ISelectable): IBaseSelectQuery;
begin
Result := Self;
FSkip := Selectable;
end;
function TBaseSelectQuery.Select(
const What: array of ISelectable): IBaseSelectQuery;
begin
Result := Select(MakeSelectableIntfArray(What));
end;
function TBaseSelectQuery.Where(Condition: ISqlCondition): IBaseSelectQuery;
begin
Result := Self;
FWhere := Condition;
end;
{ TRowsElement }
constructor TRowsElement.Create(AFromSelectable,
AToSelectable: ISelectable);
begin
inherited Create;
FFromSelectable := AFromSelectable;
FToSelectable := AToSelectable;
end;
function TRowsElement.GetFromSelectable: ISelectable;
begin
Result := FFromSelectable;
end;
function TRowsElement.GetToSelectable: ISelectable;
begin
Result := FToSelectable;
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.Console.Command.Config;
interface
uses
VSoft.CancellationToken,
DPM.Core.Logging,
DPM.Core.Configuration.Interfaces,
DPM.Console.ExitCodes,
DPM.Console.Command,
DPM.Console.Command.Base;
type
TConfigCommand = class(TBaseCommand)
private
protected
function Execute(const cancellationToken : ICancellationToken): TExitCode; override;
public
constructor Create(const logger : ILogger; const configurationManager : IConfigurationManager);override;
end;
implementation
{ TConfigCommand }
{ TConfigCommand }
constructor TConfigCommand.Create(const logger: ILogger; const configurationManager : IConfigurationManager);
begin
inherited Create(logger, configurationManager);
end;
function TConfigCommand.Execute(const cancellationToken : ICancellationToken): TExitCode;
begin
Logger.Error('Config command not implemented');
result := TExitCode.NotImplemented;
end;
end.
|
unit Misc;
interface
uses Classes, ActiveX, SysUtils, DirectShow9, Windows;
function FindFilter(graph: IGraphBuilder; iid: TGUID): IBaseFilter;
function isRomanDigits(const s: String): Boolean;
function isLatinWord(const s: String): Boolean;
function ConvertStrTimeToMilliseconds(const s: String;
const delimiters: String): Integer;
function EscapeHtmlChars(const s: String): String;
function EscapeInvalidChars(const s: String): String;
//deprecated
type
TPinItem = class
Pin: IPin;
MediaType: _AMMediaType;
end;
TPinCollector = class
private
List: TList;
public
constructor Create;
destructor Destroy; override;
function Add(PinItem: TPinItem): Integer;
procedure Delete(Index: Integer);
function Get(Index: Integer): TPinItem;
procedure Put(Index: Integer; Item: TPinItem);
procedure Clear;
property Items[Index: Integer]: TPinItem read Get write Put; default;
function Find(Pin: IPin): Integer;
end;
procedure ExplodeToWords(s: string; ss: TStringList);
procedure ExplodeToWordsOnlyLetters(s: String; ss: TStringList);
function GetMainWindow(wnd: HWND): HWND;
function ConvertDSTimeUnitsToText(pos: Int64): String;
function GetNextFile(const filename, extentions: String): String;
implementation
uses Constants;
function RemoveAsterisks(const s: String): String;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(s) do
begin
if (s[i] <> '*') then Result := Result + s[i];
end;
end;
function GetFirstDigits(const s: String): String;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(s) do
begin
if (s[i] in ['0'..'9']) then
Result := Result + s[i]
else
Exit;
end;
end;
function CompareStringsRespectToFirstDigits(List: TStringList;
Index1, Index2: Integer): Integer;
var
s1, s2: String;
d1, d2: String;
begin
s1 := List[Index1];
s2 := List[Index2];
if (s1 = '') OR (s2 = '') then
begin
Result := CompareStr(s1, s2);
Exit;
end;
//get leading digits of each string
//returns empty string if no leading digits
d1 := GetFirstDigits(s1);
d2 := GetFirstDigits(s2);
if (d1 = '') OR (d2 = '') OR (d1 = d2) then
begin
Result := CompareStr(s1, s2);
Exit;
end;
try
Result := StrToInt(d1) - StrToInt(d2);
except
Result := 0;
end;
end;
function GetFileList(const path, extentions: String;
var filenames: TStringList): Boolean;
var
SearchRec: TSearchRec;
ext_list: TStringList;
begin
Result := False;
if (filenames = nil) then
Exit;
ext_list := TStringList.Create;
try
ext_list.CaseSensitive := False;
//extentions should be like .ext1;.ext2;.ext3...
ext_list.Delimiter := ';';
ext_list.DelimitedText := RemoveAsterisks(extentions);
if FindFirst(path + '\*.*', faAnyFile, SearchRec) = 0 then
begin
repeat
if (SearchRec.Attr = faDirectory) or
(SearchRec.Name = '.') or
(SearchRec.Name = '..') then continue;
if ext_list.IndexOf(ExtractFileExt(SearchRec.Name)) >= 0 then
filenames.Add(SearchRec.Name);
until FindNext(SearchRec)<>0;
SysUtils.FindClose(SearchRec);
Result := True;
end else // if FindFirst <> 0...
Result := False;
finally
ext_list.Free;
end;
end;
function GetNextFile(const filename, extentions: String): String;
var
filenames: TStringList;
path: String;
i: Integer;
begin
Result := '';
filenames := TStringList.Create;
try
path := ExtractFilePath(filename);
if GetFileList(path, extentions, filenames) then
begin
//sort files
filenames.CustomSort(CompareStringsRespectToFirstDigits);
i := filenames.IndexOf(ExtractFileName(filename));
if (i < filenames.Count - 1) AND (i >= 0) then
begin
Result := path + filenames[i + 1];
end;
end;
finally
filenames.Free;
end;
end;
function ConvertDSTimeUnitsToText(pos: Int64): String;
var
Value: Int64;
H, M, S: Integer;
begin
Value := Trunc(pos / 10000000);
H := value div 3600;
M := (value mod 3600) div 60;
S := (value mod 3600) mod 60;
Result:= Format('%d:%2.2d:%2.2d', [H, M, S]);
end;
function GetMainWindow(wnd: HWND): HWND;
begin
repeat
Result := wnd;
wnd := GetWindow(wnd, GW_OWNER);
until wnd = 0;
end;
procedure ExplodeToWordsOnlyLetters(s: String; ss: TStringList);
const
SEPARATOR = ' =~!@#$%^&*()_+'#9'|\?/>.<,][{}:;"';
var i, j: Integer;
w: String;
bFound: Boolean;
begin
w := '';
for i := 1 to Length(s) do
begin
bFound := False;
for j := 1 to Length(SEPARATOR) do
begin
if s[i] = SEPARATOR[j] then
begin
bFound := True;
Break;
end;
end;
if (bFound) then
begin
if (w <> '') then
begin
ss.Add(w);
w := '';
end;
end else
w := w + s[i];
end;
end;
procedure ExplodeToWords(s: String; ss: TStringList);
const
SEPARATOR = ' =~!@#$%^&*()_+'#9'|\?/>.<,][{}:;"';
var i, j: Integer;
w: String;
bFound: Boolean;
begin
w := '';
for i := 1 to Length(s) do
begin
{bFound := False;
for j := 1 to Length(SEPARATOR) do
begin
if s[i] = SEPARATOR[j] then
begin
bFound := True;
Break;
end;
end;}
if ({bFound} s[i] = #$20) then
begin
if (w <> '') then
begin
{if (s[i] <> '"') then
ss.Add(w + s[i])
else
ss.Add(w + '\"');}
ss.Add(w);
w := '';
end;
end else
begin
if (s[i] <> '"') then
w := w + s[i]
else
w := w + '\"';
end;
end;
end;
function EscapeInvalidChars(const s: String): String;
const
VALID = '`-=~!@#$%^&*()_+'#9'|\?/>.<,][{}:;"''';
var
i, j: Integer;
begin
Result := '';
for i := 1 to Length(s) do
begin
if (s[i] in [' ', 'a'..'z']) then
Result := Result + s[i]
else if (s[i] in ['A'..'Z']) then
Result := Result + s[i]
else if (s[i] in ['0'..'9']) then
Result := Result + s[i]
else if (s[i] in ['А'..'Я']) then
Result := Result + s[i]
else if (s[i] in ['а'..'я']) then
Result := Result + s[i];
for j := 1 to Length(VALID) do
begin
if s[i] = VALID[j] then
begin
Result := Result + s[i];
Break;
end;
end;
end;
end;
function findFilter(graph: IGraphBuilder; iid: TGUID): IBaseFilter;
var
vobfil: IBaseFilter;
pEnum: IEnumFilters;
hr: HRESULT;
classid: TGUID;
begin
Result := nil;
//display vobsub filter property page
try
graph.EnumFilters(pEnum);
except
Exit;
end;
vobfil := nil;
//enum all filters in the graph
if (pEnum <> nil) then
begin
while SUCCEEDED(pEnum.Next(1, vobfil, nil)) do
begin
if nil = vobfil then
Break;
if SUCCEEDED(vobfil.GetClassID(classid)) then
begin
if IsEqualGUID(classid, iid) then
begin
Result := vobfil;
Exit;
end;
end;
end;
end;
end;
function isLatinWord(const s: String): Boolean;
var
i: Integer;
begin
for i := 1 to Length(s) do
begin
if NOT (s[i] in LATIN_WORD_LETTERS) then
begin
Result := False;
Exit;
end;
end;
Result := True;
end;
function isRomanDigits(const s: String): Boolean;
var
i: Integer;
begin
for i := 1 to Length(s) do
begin
if NOT (s[i] in ROME_DIGITS) then
begin
Result := False;
Exit;
end;
end;
Result := True;
end;
function ConvertStrTimeToMilliseconds(const s: String;
const delimiters: String): Integer;
var
times: array[1..4] of Integer;
dindex, i: Integer;
t: String;
begin
times[1] := 0;
times[2] := 0;
times[3] := 0;
times[4] := 0;
Result := -1;
dindex := 1;
i := 0;
t := '';
while dindex <= Length(delimiters) do
begin
Inc(i);
if s[i] <> delimiters[dindex] then
begin
t := t + s[i];
end else
begin
times[dindex] := StrToInt(Trim(t));
Inc(dindex);
t := '';
end;
end;
t := Copy(s, i + 1, Length(s));
times[4] := StrToInt(Trim(t));
Result := times[1] * 3600 * 1000 + times[2] * 60 * 1000 + times[3] * 1000 +
times[4];
end;
function EscapeHtmlChars(const s: String): String;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(s) do
begin
case s[i] of
' ': Result := Result + ' ';
'"': Result := Result + '"';
'&': Result := Result + '&';
'<': Result := Result + '<';
'>': Result := Result + '>';
else
Result := Result + s[i];
end;
end;
end;
{ TPinCollector }
function TPinCollector.Add(PinItem: TPinItem): Integer;
begin
Result := List.Add(PinItem)
end;
procedure TPinCollector.Clear;
var
i: Integer;
begin
for i := 0 to List.Count - 1 do
begin
TPinItem(List[i]).Free;
List[i] := nil;
end;
List.Clear;
end;
constructor TPinCollector.Create;
begin
List := TList.Create;
end;
procedure TPinCollector.Delete(Index: Integer);
begin
TPinItem(List[Index]).Free;
List.Delete(Index);
end;
destructor TPinCollector.Destroy;
begin
try
Clear;
finally
List.Free;
inherited;
end;
end;
function TPinCollector.Find(Pin: IPin): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to List.Count - 1 do
if Self[i].Pin = Pin then
begin
Result := i;
Break;
end;
end;
function TPinCollector.Get(Index: Integer): TPinItem;
begin
Result := List[Index];
end;
procedure TPinCollector.Put(Index: Integer; Item: TPinItem);
begin
if (List[Index] <> Item) then
begin
TPinItem(List[Index]).Free;
List[Index] := Item;
end;
end;
{
//improvised unit tests
var
t: String;
initialization
begin
t := GetNextFile('D:\video\serials\Avatar The Last Airbender The book 1.Water\7.Мир Духов Зимнее Солнцестояние, Часть 1 (The Spirit World Winter Solstice, Part 1).mkv', STR_EXTENTIONS);
MessageBox(0, PChar(t), '', 0);
t := GetNextFile('D:\video\serials\dexter.s06\Dexter.s06.HDTVRip.rus.eng.novafilm\dexter.s06e02.hdtv.rus.eng.novafilm.tv.avi', STR_EXTENTIONS);
MessageBox(0, PChar(t), '', 0);
end;
}
end.
|
unit glIteratorGrid;
interface
type
TglIteratorGrid = class
private
FWidth, FFirstX, fFirstY, FCurrentX, FCurrentY: Integer;
public
constructor Create(Width, FirstX, FirstY: Integer);
procedure New(Width, FirstX, FirstY: Integer);
procedure Up;
property Width: Integer read FWidth;
property CurrentX: Integer read FCurrentX;
property CurrentY: Integer read FCurrentY;
end;
implementation
{ TglIteratorGrid }
constructor TglIteratorGrid.Create;
begin
New(Width, FirstX, FirstY);
end;
procedure TglIteratorGrid.New(Width, FirstX, FirstY: Integer);
begin
FWidth := Width;
FFirstX := FirstX;
fFirstY := FirstY;
FCurrentX := FFirstX;
FCurrentY := FirstY;
end;
procedure TglIteratorGrid.Up;
begin
if FCurrentX <> FWidth then
begin
inc(FCurrentX);
end
else
begin
inc(FCurrentY);
FCurrentX := FFirstX;
end;
end;
end.
|
unit trl_urttibroker;
interface
uses
trl_irttibroker, TypInfo, SysUtils, Classes, StrUtils, fgl, contnrs,
trl_ipersist;
type
{ ERBException }
ERBException = class(Exception)
public
class procedure UnsupportedDataAccess(const AItemName: string);
class procedure UnknownDataKind(const AClassName, AItemName: string; const AUnknownKind: integer);
class procedure UnexpectedDataKind(const AClassName, AItemName: string;
const AActualKind: integer);
class procedure Collection_NoCountPropertySpecified(const AItemName: string);
class procedure EnumerationValueNotFound(const AClassName, AItemName, AEnum: string);
class procedure NoClassInCreate;
class procedure NoObjectInCreate;
end;
TRBData = class;
{ TRBDataItem }
TRBDataItem = class(TContainedObject, IRBDataItem)
private
//fObject: TObject;
fParent: TRBData;
fPropInfo: PPropInfo;
function GetPropInfo: PPropInfo;
function GetPropName: string;
protected
property PropInfo: PPropInfo read GetPropInfo;
property PropName: string read GetPropName;
protected
// IRBDataItem
function GetName: string;
function GetClassName: string;
function GetIsObject: Boolean;
function GetIsMemo: Boolean;
function GetIsID: Boolean;
function GetIsInterface: Boolean;
function GetTypeKind: TTypeKind;
function GetAsPersist: string; virtual;
procedure SetAsPersist(AValue: string); virtual;
function GetAsString: string; virtual;
procedure SetAsString(AValue: string); virtual;
function GetAsInteger: integer; virtual;
procedure SetAsInteger(AValue: integer); virtual;
function GetAsBoolean: Boolean; virtual;
procedure SetAsBoolean(AValue: Boolean); virtual;
function GetAsObject: TObject; virtual;
procedure SetAsObject(AValue: TObject); virtual;
function GetAsVariant: Variant; virtual;
procedure SetAsVariant(AValue: Variant); virtual;
function GetAsClass: TClass; virtual;
function GetEnumName(AValue: integer): string; virtual;
function GetEnumNameCount: integer; virtual;
function GetAsPtrInt: PtrInt; virtual;
procedure SetAsPtrInt(AValue: PtrInt); virtual;
function GetAsInterface: IUnknown; virtual;
procedure SetAsInterface(AValue: IUnknown); virtual;
public
constructor Create(AParent: TRBData; const APropInfo: PPropInfo);
property Name: string read GetName;
property ClassName: string read GetClassName;
property IsObject: Boolean read GetIsObject;
property IsMemo: Boolean read GetIsMemo;
property IsID: Boolean read GetIsID;
property IsInterface: Boolean read GetIsInterface;
property TypeKind: TTypeKind read GetTypeKind;
property AsPersist: string read GetAsPersist write SetAsPersist;
property AsString: string read GetAsString write SetAsString;
property AsInteger: integer read GetAsInteger write SetAsInteger;
property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean;
property AsObject: TObject read GetAsObject write SetAsObject;
property AsVariant: variant read GetAsVariant write SetAsVariant;
property AsClass: TClass read GetAsClass;
property EnumNameCount: integer read GetEnumNameCount;
property EnumName[AValue: integer]: string read GetEnumName;
property AsPtrInt: PtrInt read GetAsPtrInt write SetAsPtrInt;
property AsInterface: IUnknown read GetAsInterface write SetAsInterface;
end;
{ TRBStringDataItem }
TRBStringDataItem = class(TRBDataItem)
protected
function GetAsPersist: string; override;
procedure SetAsPersist(AValue: string); override;
function GetAsString: string; override;
procedure SetAsString(AValue: string); override;
function GetAsInteger: integer; override;
procedure SetAsInteger(AValue: integer); override;
function GetAsVariant: Variant; override;
procedure SetAsVariant(AValue: Variant); override;
end;
{ TRBIntegerDataItem }
TRBIntegerDataItem = class(TRBDataItem)
protected
function GetAsPersist: string; override;
procedure SetAsPersist(AValue: string); override;
function GetAsString: string; override;
procedure SetAsString(AValue: string); override;
function GetAsInteger: integer; override;
procedure SetAsInteger(AValue: integer); override;
function GetAsBoolean: Boolean; override;
procedure SetAsBoolean(AValue: Boolean); override;
function GetAsVariant: Variant; override;
procedure SetAsVariant(AValue: Variant); override;
function GetAsPtrInt: PtrInt; override;
procedure SetAsPtrInt(AValue: PtrInt); override;
end;
{ TRBObjectDataItem }
TRBObjectDataItem = class(TRBDataItem)
protected
function GetAsObject: TObject; override;
procedure SetAsObject(AValue: TObject); override;
function GetAsVariant: Variant; override;
procedure SetAsVariant(AValue: Variant); override;
function GetAsClass: TClass; override;
end;
{ TRBEnumerationDataItem }
TRBEnumerationDataItem = class(TRBDataItem)
protected
function GetAsPersist: string; override;
procedure SetAsPersist(AValue: string); override;
function GetAsString: string; override;
procedure SetAsString(AValue: string); override;
function GetEnumName(AValue: integer): string; override;
function GetEnumNameCount: integer; override;
function GetAsVariant: Variant; override;
procedure SetAsVariant(AValue: Variant); override;
end;
{ TRBVariantDataItem }
TRBVariantDataItem = class(TRBDataItem)
protected
function GetAsPersist: string; override;
procedure SetAsPersist(AValue: string); override;
function GetAsString: string; override;
procedure SetAsString(AValue: string); override;
function GetAsInteger: integer; override;
procedure SetAsInteger(AValue: integer); override;
function GetAsVariant: Variant; override;
procedure SetAsVariant(AValue: Variant); override;
end;
{ TRBPtrIntDataItem }
TRBPtrIntDataItem = class(TRBDataItem)
protected
function GetAsString: string; override;
procedure SetAsString(AValue: string); override;
function GetAsPtrInt: PtrInt; override;
procedure SetAsPtrInt(AValue: PtrInt); override;
end;
{ TRBInterfaceDataItem }
TRBInterfaceDataItem = class(TRBDataItem)
protected
function GetAsInterface: IUnknown; override;
procedure SetAsInterface(AValue: IUnknown); override;
end;
{ TRBDataItemList }
TRBDataItemList = class
private
fList: TObjectList;
protected
function GetCount: LongInt;
function GetItems(AIndex: integer): IRBDataItem;
public
constructor Create;
destructor Destroy; override;
procedure Add(ADataItem: TRBDataItem);
property Count: integer read GetCount;
property Items[AIndex: integer]: IRBDataItem read GetItems; default;
end;
{ TRBData }
TRBData = class(TInterfacedObject, IRBData)
private
fObject: TObject;
fClass: TClass;
fDataList: TRBDataItemList;
fSkipUnsupported: Boolean;
fPropNameFilter: string;
function GetClassType: TClass;
function GetData: TRBDataItemList;
function GetItemIndex(const AName: string): integer;
procedure SetUnderObject(AValue: TObject);
property DataList: TRBDataItemList read GetData;
procedure FillData;
function CreateRBData(const APropInfo: PPropInfo): TRBDataItem;
function SupportedRBData(const APropInfo: PPropInfo): Boolean;
protected
function GetClassName: string;
function GetCount: integer;
function GetItems(AIndex: integer): IRBDataItem;
function GetItemByName(const AName: string): IRBDataItem;
function FindItem(const AName: string): IRBDataItem;
function FindItemIndex(const AName: string): integer;
function GetUnderObject: TObject;
procedure AssignObject(const ASource, ATarget: TObject);
procedure Assign(const AData: IRBData);
public
constructor Create(AObject: TObject; ASkipUnsupported: Boolean = False);
constructor Create(AObject: TObject; const APropNameFilter: string);
constructor Create(AClass: TClass; ASkipUnsupported: Boolean = False);
destructor Destroy; override;
property ClassName: string read GetClassName;
property ClassType: TClass read GetClassType;
property Count: integer read GetCount;
property Items[AIndex: integer]: IRBDataItem read GetItems; default;
property ItemByName[const AName: string]: IRBDataItem read GetItemByName;
property ItemIndex[const AName: string]: integer read GetItemIndex;
published
property UnderObject: TObject read GetUnderObject write SetUnderObject;
end;
implementation
{ TRBInterfaceDataItem }
function TRBInterfaceDataItem.GetAsInterface: IUnknown;
begin
Result := GetInterfaceProp(fParent.fObject, PropInfo);
end;
procedure TRBInterfaceDataItem.SetAsInterface(AValue: IUnknown);
begin
SetInterfaceProp(fParent.fObject, PropInfo, AValue);
end;
{ TRBPtrIntDataItem }
function TRBPtrIntDataItem.GetAsString: string;
begin
Result := IntToHex(GetAsPtrInt, SizeOf(PtrInt) * 2);
end;
procedure TRBPtrIntDataItem.SetAsString(AValue: string);
var
m: Int64;
begin
HexToBin(pchar(AValue), @m, SizeOf(m));
SetAsPtrInt(m);
end;
function TRBPtrIntDataItem.GetAsPtrInt: PtrInt;
begin
Result := GetOrdProp(fParent.fObject, PropInfo);
end;
procedure TRBPtrIntDataItem.SetAsPtrInt(AValue: PtrInt);
begin
SetOrdProp(fParent.fObject, PropInfo, AValue);
end;
{ TRBVariantDataItem }
function TRBVariantDataItem.GetAsPersist: string;
begin
Result := GetAsVariant;
end;
procedure TRBVariantDataItem.SetAsPersist(AValue: string);
begin
SetAsVariant(AValue);
end;
function TRBVariantDataItem.GetAsString: string;
begin
Result := GetAsVariant;
end;
procedure TRBVariantDataItem.SetAsString(AValue: string);
begin
SetAsVariant(AValue);
end;
function TRBVariantDataItem.GetAsInteger: integer;
begin
Result := GetAsVariant;
end;
procedure TRBVariantDataItem.SetAsInteger(AValue: integer);
begin
SetAsVariant(AValue);
end;
function TRBVariantDataItem.GetAsVariant: Variant;
begin
Result := GetVariantProp(fParent.fObject, PropInfo);
end;
procedure TRBVariantDataItem.SetAsVariant(AValue: Variant);
begin
SetVariantProp(fParent.fObject, PropInfo, AValue);
end;
{ TRBEnumerationDataItem }
function TRBEnumerationDataItem.GetAsPersist: string;
begin
Result := GetAsString;
end;
procedure TRBEnumerationDataItem.SetAsPersist(AValue: string);
begin
AsString := AValue;
end;
function TRBEnumerationDataItem.GetAsString: string;
begin
Result := GetEnumProp(fParent.fObject, PropInfo);
end;
procedure TRBEnumerationDataItem.SetAsString(AValue: string);
begin
if AValue <> '' then
SetEnumProp(fParent.fObject, PropInfo, AValue);
end;
function TRBEnumerationDataItem.GetEnumName(AValue: integer): string;
begin
Result := typinfo.GetEnumName(PropInfo^.PropType, AValue);
end;
function TRBEnumerationDataItem.GetEnumNameCount: integer;
begin
Result := typinfo.GetEnumNameCount(PropInfo^.PropType);
end;
function TRBEnumerationDataItem.GetAsVariant: Variant;
begin
Result := GetAsString;
end;
procedure TRBEnumerationDataItem.SetAsVariant(AValue: Variant);
begin
SetAsString(AValue);
end;
{ ERBException }
class procedure ERBException.UnsupportedDataAccess(const AItemName: string);
begin
raise ERBException.Create('Unsupported access for dataitem ' + AItemName);
end;
class procedure ERBException.UnknownDataKind(const AClassName, AItemName: string; const AUnknownKind: integer);
begin
raise ERBException.CreateFmt('Unsupported kind (declared via index property %s.%s - %d)', [AClassName, AItemName, AUnknownKind]);
end;
class procedure ERBException.UnexpectedDataKind(const AClassName,
AItemName: string; const AActualKind: integer);
begin
raise ERBException.CreateFmt('Unexpected kind in declaration %s.%s - check mask is %d)',
[AClassName, AItemName, AActualKind]);
end;
class procedure ERBException.Collection_NoCountPropertySpecified(
const AItemName: string);
begin
raise ERBException.CreateFmt('For list property %s is not declared counter property ' +
'(same name with Count suffix', [AItemName]);
end;
class procedure ERBException.EnumerationValueNotFound(const AClassName,
AItemName, AEnum: string);
begin
raise ERBException.CreateFmt('Cannot find enumeration value for %s.%s.%s ',
[AClassName, AItemName, AEnum]);
end;
class procedure ERBException.NoClassInCreate;
begin
raise ERBException.Create('Empty class when try create RBData');
end;
class procedure ERBException.NoObjectInCreate;
begin
raise ERBException.Create('Empty object when try create RBData');
end;
function TRBObjectDataItem.GetAsObject: TObject;
begin
Result := GetObjectProp(fParent.fObject, PropInfo);
end;
procedure TRBObjectDataItem.SetAsObject(AValue: TObject);
begin
SetObjectProp(fParent.fObject, PropInfo, AValue);
end;
function TRBObjectDataItem.GetAsVariant: Variant;
var
mP: Pointer;
begin
mP := GetAsObject;
Result := mP;
end;
procedure TRBObjectDataItem.SetAsVariant(AValue: Variant);
var
mP: Pointer;
begin
//mP := AValue;
//SetAsObject(mP);
end;
function TRBObjectDataItem.GetAsClass: TClass;
begin
Result := GetObjectPropClass(fParent.fClass, PropInfo^.Name);
end;
{ TIRBStringData }
function TRBStringDataItem.GetAsPersist: string;
begin
Result := AsString;
end;
procedure TRBStringDataItem.SetAsPersist(AValue: string);
begin
AsString := AValue;
end;
function TRBStringDataItem.GetAsString: string;
begin
Result := GetStrProp(fParent.fObject, PropInfo);
end;
procedure TRBStringDataItem.SetAsString(AValue: string);
begin
SetStrProp(fParent.fObject, PropInfo, AValue);
end;
function TRBStringDataItem.GetAsInteger: integer;
begin
Result := StrToInt(AsString);
end;
procedure TRBStringDataItem.SetAsInteger(AValue: integer);
begin
AsString := IntToStr(AValue);
end;
function TRBStringDataItem.GetAsVariant: Variant;
begin
Result := AsString;
end;
procedure TRBStringDataItem.SetAsVariant(AValue: Variant);
begin
SetAsString(AValue);
end;
{ TIRBIntegerData }
function TRBIntegerDataItem.GetAsPersist: string;
begin
Result := IfThen(AsInteger = 0, '', AsString);
end;
procedure TRBIntegerDataItem.SetAsPersist(AValue: string);
begin
if AValue = '' then
AsInteger := 0
else
AsString := AValue;
end;
function TRBIntegerDataItem.GetAsString: string;
begin
Result := IntToStr(AsInteger);
end;
procedure TRBIntegerDataItem.SetAsString(AValue: string);
begin
AsInteger := StrToInt(AValue);
end;
function TRBIntegerDataItem.GetAsInteger: integer;
begin
Result := GetOrdProp(fParent.fObject, PropInfo);
end;
procedure TRBIntegerDataItem.SetAsInteger(AValue: integer);
begin
SetOrdProp(fParent.fObject, PropInfo, AValue);
end;
function TRBIntegerDataItem.GetAsBoolean: Boolean;
begin
Result := AsInteger <> 0;
end;
procedure TRBIntegerDataItem.SetAsBoolean(AValue: Boolean);
begin
if AValue then
AsInteger := 1
else
AsInteger := 0;
end;
function TRBIntegerDataItem.GetAsVariant: Variant;
begin
Result := GetAsBoolean;
end;
procedure TRBIntegerDataItem.SetAsVariant(AValue: Variant);
begin
SetAsBoolean(AValue);
end;
function TRBIntegerDataItem.GetAsPtrInt: PtrInt;
begin
Result := GetOrdProp(fParent.fObject, PropInfo);
end;
procedure TRBIntegerDataItem.SetAsPtrInt(AValue: PtrInt);
begin
SetOrdProp(fParent.fObject, PropInfo, AValue);
end;
function TRBDataItem.GetPropInfo: PPropInfo;
begin
Result := fPropInfo;
end;
function TRBDataItem.GetAsPtrInt: PtrInt;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetEnumName(AValue: integer): string;
begin
Result := '';
end;
function TRBDataItem.GetEnumNameCount: integer;
begin
Result := 0;
end;
function TRBDataItem.GetPropName: string;
begin
Result := fPropInfo^.Name;
end;
procedure TRBDataItem.SetAsPtrInt(AValue: PtrInt);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsInterface: IUnknown;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsInterface(AValue: IUnknown);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetTypeKind: TTypeKind;
begin
Result := fPropInfo^.PropType^.Kind;
end;
function TRBDataItem.GetAsPersist: string;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsPersist(AValue: string);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetName: string;
begin
Result := PropInfo^.Name;
end;
function TRBDataItem.GetClassName: string;
var
mTypeData: PTypeData;
begin
if PropInfo^.PropType^.Kind = tkClass then
begin
mTypeData := GetTypeData(PropInfo^.PropType);
Result := mTypeData^.ClassType.ClassName;
end
else
Result := '';
end;
function TRBDataItem.GetIsObject: Boolean;
begin
Result := TypeKind in [tkClass, tkObject];
end;
function TRBDataItem.GetIsMemo: Boolean;
begin
Result := SameText(cMemoStringType, fPropInfo^.PropType^.Name);
end;
function TRBDataItem.GetIsID: Boolean;
begin
Result := SameText(cIDStringType, fPropInfo^.PropType^.Name);
end;
function TRBDataItem.GetIsInterface: Boolean;
begin
Result := TypeKind in [tkInterface, tkInterfaceRaw];
end;
function TRBDataItem.GetAsString: string;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsString(AValue: string);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsInteger: integer;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsInteger(AValue: integer);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsBoolean: Boolean;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsBoolean(AValue: Boolean);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsObject: TObject;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsObject(AValue: TObject);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsVariant: Variant;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsVariant(AValue: Variant);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsClass: TClass;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
constructor TRBDataItem.Create(AParent: TRBData; const APropInfo: PPropInfo);
begin
inherited Create(AParent);
fParent := AParent;
fPropInfo := APropInfo;
end;
{ TIRBDataList }
function TRBDataItemList.GetCount: LongInt;
begin
Result := fList.Count;
end;
function TRBDataItemList.GetItems(AIndex: integer): IRBDataItem;
begin
Result := fList[AIndex] as IRBDataItem;
end;
constructor TRBDataItemList.Create;
begin
fList := TObjectList.Create(True);
end;
destructor TRBDataItemList.Destroy;
begin
FreeAndNil(fList);
inherited Destroy;
end;
procedure TRBDataItemList.Add(ADataItem: TRBDataItem);
begin
fList.Add(ADataItem);
end;
{ TRBInstance }
function TRBData.GetData: TRBDataItemList;
begin
if fDataList = nil then
begin
fDataList := TRBDataItemList.Create;
FillData;
end;
Result := fDataList;
end;
function TRBData.GetClassType: TClass;
begin
if fObject <> nil then
Result := fObject.ClassType
else if fClass <> nil then
Result := fCLass.ClassType
else
Result := nil;
end;
function TRBData.GetItemIndex(const AName: string): integer;
begin
Result := FindItemIndex(AName);
end;
procedure TRBData.SetUnderObject(AValue: TObject);
begin
FreeAndNil(fDataList);
fObject := AValue;
fClass := fObject.ClassType;
end;
procedure TRBData.FillData;
var
mPropList: PPropList;
mTypeData: PTypeData;
i: integer;
begin
mTypeData := GetTypeData(fClass.ClassInfo);
if mTypeData^.PropCount > 0 then
begin
New(mPropList);
try
GetPropInfos(fClass.ClassInfo, mPropList);
for i := 0 to mTypeData^.PropCount - 1 do
begin
if not fSkipUnsupported or SupportedRBData(mPropList^[i]) then
begin
if (fPropNameFilter = '') or (fPropNameFilter = mPropList^[i]^.Name) then
DataList.Add(CreateRBData(mPropList^[i]));
end;
end;
finally
Dispose(mPropList);
end;
end;
end;
function TRBData.CreateRBData(const APropInfo: PPropInfo): TRBDataItem;
begin
case APropInfo^.PropType^.Kind of
tkAString:
Result := TRBStringDataItem.Create(self, APropInfo);
tkInteger, tkBool:
Result := TRBIntegerDataItem.Create(self, APropInfo);
tkClass:
Result := TRBObjectDataItem.Create(self, APropInfo);
tkEnumeration:
Result := TRBEnumerationDataItem.Create(self, APropInfo);
tkVariant:
Result := TRBVariantDataItem.Create(self, APropInfo);
tkClassRef:
Result := TRBIntegerDataItem.Create(self, APropInfo);
tkInterface:
Result := TRBInterfaceDataItem.Create(self, APropInfo);
else
raise ERBException.Create('Unsupported data type');
end;
end;
function TRBData.SupportedRBData(const APropInfo: PPropInfo): Boolean;
begin
Result := APropInfo^.PropType^.Kind in [tkAString, tkInteger, tkBool, tkClass,
tkEnumeration, tkVariant, tkClassRef, tkInterface];
end;
function TRBData.GetClassName: string;
begin
Result := fObject.ClassName;
end;
function TRBData.GetCount: integer;
begin
Result := DataList.Count;
end;
function TRBData.GetItems(AIndex: integer): IRBDataItem;
begin
Result := DataList[AIndex];
end;
function TRBData.GetItemByName(const AName: string): IRBDataItem;
begin
Result := FindItem(AName);
if Result = nil then
raise ERBException.Create('Dataitem ' + AName + ' not exists');
end;
function TRBData.FindItem(const AName: string): IRBDataItem;
var
mIndex: integer;
begin
Result := nil;
mIndex := FindItemIndex(AName);
if mIndex <> -1 then
begin
Result := Items[mIndex];
end;
end;
function TRBData.FindItemIndex(const AName: string): integer;
var
i: integer;
begin
Result := -1;
for i := 0 to Count - 1 do
begin
if SameText(AName, Items[i].Name) then
begin
Result := i;
Exit;
end;
end;
end;
function TRBData.GetUnderObject: TObject;
begin
Result := fObject;
end;
procedure TRBData.AssignObject(const ASource, ATarget: TObject);
var
mSource, mTarget: IRBData;
begin
if (ASource = nil) or (ATarget = nil) then
Exit;
mSource := TRBData.Create(ASource);
mTarget := TRBData.Create(ATarget);
mTarget.Assign(mSource);
end;
procedure TRBData.Assign(const AData: IRBData);
var
i, j: integer;
mSourceMany, mTargetMany: IPersistMany;
mSourceRef, mTargetRef: IPersistRef;
begin
for i := 0 to Count - 1 do begin
if Items[i].IsInterface and Supports(Items[i].AsInterface, IPersistMany) then
begin
mSourceMany := AData[i].AsInterface as IPersistMany;
mTargetMany := Items[i].AsInterface as IPersistMany;
mTargetMany.Count := mSourceMany.Count;
for j := 0 to mSourceMany.Count - 1 do
begin
if Supports(mTargetMany.AsInterface[j], IPersistRef) then
(mTargetMany.AsInterface[j] as IPersistRef).Data := (mSourceMany.AsInterface[j] as IPersistRef).Data
else
mTargetMany.AsPersistData[j].Assign(mSourceMany.AsPersistData[j]);
end;
end
else
if Items[i].IsInterface and Supports(Items[i].AsInterface, IPersistRef) then
begin
mSourceRef := AData[i].AsInterface as IPersistRef;
mTargetRef := Items[i].AsInterface as IPersistRef;
mTargetRef.Data := mSourceRef.Data;
end
else
if Items[i].IsObject then
begin
AssignObject(AData[i].AsObject, Items[i].AsObject);
end
else
begin
Items[i].AsPersist := AData[i].AsPersist;
end;
end;
end;
constructor TRBData.Create(AObject: TObject; ASkipUnsupported: Boolean = False);
begin
if AObject = nil then
ERBException.NoObjectInCreate;
fObject := AObject;
fClass := fObject.ClassType;
fSkipUnsupported := ASkipUnsupported;
end;
constructor TRBData.Create(AObject: TObject; const APropNameFilter: string);
begin
fPropNameFilter := APropNameFilter;
Create(AObject);
end;
constructor TRBData.Create(AClass: TClass; ASkipUnsupported: Boolean = False);
begin
if AClass = nil then
ERBException.NoClassInCreate;
fClass := AClass;
fSkipUnsupported := ASkipUnsupported;
end;
destructor TRBData.Destroy;
begin
FreeAndNil(fDataList);
inherited Destroy;
end;
end.
|
Program SDA4v17_1;
const
n = 5;
var
A: array[1..4*n] of integer;
B: array[1..n] of integer;
i: integer;
begin
randomize;
write('Massiv A: ');
for i:=1 to 4 * n do
begin
a[i]:=random(50);
write(a[i]:4);
end;
writeln;
writeln;
for i:=1 to n do
begin
b[i]:=a[i];
a[i]:=a[i+n];
a[i+n]:=a[4*n+1-i];
end;
for i:=1 to n do
begin
a[3*n+i]:=b[i];
b[i]:=a[2*n+i];
end;
for i:=1 to n do
a[2*n+i]:=b[n-i+1];
write('Massiv <A>:');
for i:=1 to 4*n do
write(a[i]:4);
readln;
end. |
{$I-,Q-,R-,S-}
{ 127þ N£meros de tel‚fono Turqu¡a 1999
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
En el mundo actual usted se encuentra frecuentemente muchos n£meros
telef¢nicos cada vez m s largos. Usted necesita recordar semejante
tipo de n£meros. Un m‚todo de c¢mo hacerlo de una manera f cil es
asignar letras a los d¡gitos como es mostrado en el cuadro siguiente:
1 ij 2 abc 3 def
4 gh 5 kl 6 mn
7 prs 8 tuv 9 wxy
0 oqz
De esta manera cada palabra o grupo de palabras pueden ser
asignados a un £nico n£mero, para que usted puede recordar palabras en
lugar de los n£meros telef¢nicos. Es evidente que tiene su propio
encanto si es posible encontrar alguna relaci¢n simple entre la
palabra y la propia persona. As¡ usted puede aprender que el n£mero
941837296 de un amigo suyo jugador de ajedrez puede leerse como
WHITEPAWN, y el n£mero 285304 de su maestro favorito se lee BULDOG.
Escriba un programa para encontrar la sucesi¢n m s corta de palabras
(es decir una que tiene el posible n£mero m s peque¤o de palabras) que
corresponde a un n£mero dado y una lista dada de palabras. La
correspondencia es descrita en el cuadro de arriba.
Entrada:
La primera l¡nea de archivo de entrada PHONE.IN contiene el n£mero
telef¢nico, la transcripci¢n de la que usted tiene que encontrar. El
n£mero consiste, a lo sumo, en 100 d¡gitos. La segunda l¡nea contiene
el n£mero total de las palabras en el diccionario (el m ximo es
50000). Cada uno de las l¡neas restantes contiene una palabra que
consiste, como m ximo, de 50 letras min£sculas del alfabeto ingl‚s. El
tama¤o total del archivo de entrada no excede los 300 KB.
Salida:
La £nica l¡nea de archivo de salida PHONE.OUT contiene la sucesi¢n m s
corta de palabras que han sido encontradas por su programa. Las
palabras est n separadas solo por espacios. Si no hay ninguna soluci¢n
a los datos de la entrada, la l¡nea contiene el texto 'No soluci¢n'.
Si hay m s soluciones que tienen el n£mero m¡nimo de palabras, usted
puede escoger cualquiera de ellas.
Ejemplo #1:
ÚÄÄÄÄÄÄÄÄÄÄÄ¿ÚÄÄÄÄÄÄÄÄÄÄÄÄ¿
³PHONE.IN ³³PHONE.OUT ³
ÃÄÄÄÄÄÄÄÄÄÄÄ´ÃÄÄÄÄÄÄÄÄÄÄÄÄ´
³7325189087 ³³reality our ³
³5 ³ÀÄÄÄÄÄÄÄÄÄÄÄÄÙ
³it ³ Hay s¢lo una soluci¢n al archivo de la entrada PHONE.IN
³your ³ escrita en el archivo de salida PHONE.OUT.(la pr¢xima
³reality ³ posibilidad 'Real it your', que corresponde al mismo
³real ³ n£mero, es m s larga).
³our ³
ÀÄÄÄÄÄÄÄÄÄÄÄÙ
Ejemplo #2:
ÚÄÄÄÄÄÄÄÄÄÄ¿ÚÄÄÄÄÄÄÄÄÄÄÄ¿
³PHONE.IN ³³PHONE.OUT ³
ÃÄÄÄÄÄÄÄÄÄÄ´ÃÄÄÄÄÄÄÄÄÄÄÄ´
³4294967296³³No soluci¢n³
³5 ³ÀÄÄÄÄÄÄÄÄÄÄÄÙ
³it ³ Porque ninguna palabra dada contiene letras g y h que es
³your ³ necesario para obtener el d¡gito 4.
³reality ³
³real ³
³our ³
ÀÄÄÄÄÄÄÄÄÄÄÙ
}
{ Reinier Cesar Free Pascal Mochila}
const
tec : string='22233344115566070778889990';
max = 50002;
cad = 102;
var
fe,fs : text;
n,m,sol : longint;
num,ch : string[cad];
mk : array[1..cad] of boolean;
best,c : array[0..cad] of longint;
cont : array[1..max] of byte;
w,sav,cam : array[1..max] of string[50];
procedure open;
var
i,j,k : longint;
begin
assign(fe,'phone.in'); reset(fe);
assign(fs,'phone.out'); rewrite(fs);
readln(fe,num);
m:=length(num);
readln(fe,n);
for i:=1 to n do
begin
readln(fe,ch);
sav[i]:=ch;
cont[i]:=length(ch);
for j:=1 to cont[i] do
begin
k:=ord(ch[j]) - 96;
w[i]:=w[i] + tec[k];
end;
end;
close(fe);
end;
function comp(q,p : longint) : boolean;
var
i : longint;
begin
for i:=1 to cont[p] do
if (num[q+i-1] <> w[p,i]) then
begin
comp:=false;
exit;
end;
comp:=true;
end;
procedure work;
var
i,j : longint;
begin
fillchar(mk,sizeof(mk),false);
fillchar(c,sizeof(c),127);
mk[1]:=true; c[0]:=0;
for i:=1 to m do
if mk[i] then
begin
for j:=1 to n do
begin
if (cont[j] <= m - i + 1) and (comp(i,j))
and (c[i+cont[j]-1] > c[i-1]) then
begin
mk[i+cont[j]]:=true;
best[i+cont[j]-1]:=j;
c[i+cont[j]-1]:=c[i-1] + 1;
end;
end;
end;
end;
procedure closer;
var
t : longint;
begin
sol:=0;
t:=m;
if best[t] = 0 then
begin
writeln(fs,'No solution.');
end
else
begin
while t > 0 do
begin
inc(sol);
cam[sol]:=sav[best[t]];
t:=t - cont[best[t]];
end;
for t:=sol downto 1 do write(fs,cam[t],' ');
end;
close(fs);
end;
begin
open;
work;
closer;
end.
|
unit uTurnDef;
interface
uses
System.Classes, System.SysUtils;
type
TTurnStateChange = procedure(AAddr: cardinal) of object;
TTurnDef = class
private
FAddr: cardinal;
FEnterState: word;
FExitState: word;
FReader: byte;
FEnterCardNum: AnsiString;
FIsEnterNew: boolean;
FExitCardNum: AnsiString;
FIsExitNew: boolean;
FEmergency: boolean;
FEnterCount: longword;
FExitCount: longword;
FOnChangeState: TTurnStateChange;
FIndicator: AnsiString;
procedure DoChangeState;
procedure SetEnterState(AValue: word);
procedure SetExitState(AValue: word);
function GetEnterCardNum: AnsiString;
function GetExitCardNum: AnsiString;
procedure SetEnterCardNum(value: AnsiString);
procedure SetExitCardNum(value: AnsiString);
function GetCardNumHex(value: AnsiString): AnsiString;
procedure SetIndicator(value: AnsiString);
public
constructor Create(AAddr: word);
destructor Destroy; override;
property Addr: cardinal read FAddr write FAddr;
property Emergency: boolean read FEmergency write FEmergency;
property EnterCardNum: AnsiString read GetEnterCardNum write SetEnterCardNum;
property ExitCardNum: AnsiString read GetExitCardNum write SetExitCardNum;
property IsEnterNew: boolean read FIsEnterNew;
property IsExitNew: boolean read FIsExitNew;
property EnterState: word read FEnterState write SetEnterState;
property ExitState: word read FExitState write SetExitState;
property EnterCount: longword read FEnterCount write FEnterCount;
property ExitCount: longword read FExitCount write FExitCount;
property Reader: byte read FReader write FReader;
property Indicator: AnsiString read FIndicator write SetIndicator;
property OnChangeState: TTurnStateChange read FOnChangeState write FOnChangeState;
end;
TTurnstiles = class
private
FTurnList: array of TTurnDef;
function GetCount: word;
public
constructor Create;
destructor Destroy; override;
function AddTurn(ANumber: Cardinal): TTurnDef;
function ByAddr(AAddr: cardinal): TTurnDef;
function IsAddrExists(AAddr: Cardinal): boolean;
property Count: word read GetCount;
end;
var
Turnstiles: TTurnstiles;
implementation
{ TTurnDef }
constructor TTurnDef.Create(AAddr: word);
begin
FAddr := AAddr;
FEnterCount := 0;
FExitCount := 0;
FEnterState := 0;
FExitState := 0;
FIsEnterNew := false;
FIsExitNew := false;
FEnterCardNum := '0';
FExitCardNum := '0';
end;
destructor TTurnDef.Destroy;
begin
inherited;
end;
procedure TTurnDef.DoChangeState;
begin
if Assigned(FOnChangeState) then
FOnChangeState(Addr);
end;
function TTurnDef.GetCardNumHex(value: AnsiString): AnsiString;
var
i: integer;
s: char;
begin
result := '';
i:= 1;
if length(value) < 2 then
exit;
while i <= Length(value) do
begin
result := result + AnsiChar(StrToInt('$' + Copy(value, i, 2)));
i := i + 2;
end;
end;
function TTurnDef.GetEnterCardNum: AnsiString;
begin
result := GetCardNumHex(FEnterCardNum);
FIsEnterNew := false;
end;
function TTurnDef.GetExitCardNum: AnsiString;
begin
result := FExitCardNum;
FIsExitNew := false;
end;
procedure TTurnDef.SetEnterCardNum(value: AnsiString);
begin
FEnterCardNum := value;
FIsEnterNew := true;
end;
procedure TTurnDef.SetEnterState(AValue: word);
begin
FEnterState := AValue;
DoChangeState;
end;
procedure TTurnDef.SetExitCardNum(value: AnsiString);
begin
FExitCardNum := value;
FIsExitNew := true;
end;
procedure TTurnDef.SetExitState(AValue: word);
begin
FExitState := AValue;
DoChangeState;
end;
procedure TTurnDef.SetIndicator(value: AnsiString);
var
i: byte;
begin
FIndicator := '';
for i := 1 to length(value) do
FIndicator := FIndicator + AnsiChar(value[i]);
DoChangeState;
end;
{ TTurnstiles }
function TTurnstiles.ByAddr(AAddr: cardinal): TTurnDef;
var
i: byte;
begin
result := nil;
if Length(FTurnList) = 0 then
exit;
for i := 0 to Length(FTurnList) - 1 do
if FTurnList[i].Addr = AAddr then
result := FTurnList[i];
end;
constructor TTurnstiles.Create;
begin
inherited;
SetLength(FTurnList, 0);
end;
destructor TTurnstiles.Destroy;
var
i: byte;
begin
if Length(FTurnList) > 0 then
for i := 0 to Length(FTurnList) - 1 do
FTurnList[i].Free;
SetLength(FTurnList, 0);
inherited;
end;
function TTurnstiles.GetCount: word;
begin
result := Length(FTurnList);
end;
function TTurnstiles.IsAddrExists(AAddr: Cardinal): boolean;
var
i: byte;
begin
result := false;
if Length(FTurnList) = 0 then
exit;
for i := 0 to Length(FTurnList) - 1 do
if FTurnList[i].Addr = AAddr then
result := true;
end;
function TTurnstiles.AddTurn(ANumber: cardinal): TTurnDef;
begin
SetLength(FTurnList, Length(FTurnList) + 1);
FTurnList[Length(FTurnList) - 1] := TTurnDef.Create(Anumber);
result := FTurnList[Length(FTurnList) - 1];
end;
initialization
Turnstiles := nil;
end.
|
///////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_PCU.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PAXCOMP_PCU;
interface
uses {$I uses.def}
SysUtils,
Classes,
TypInfo,
PAXCOMP_CONSTANTS,
PAXCOMP_SYS,
PAXCOMP_MODULE,
PAXCOMP_PARSER,
PAXCOMP_KERNEL;
function CompileUnit(Owner: Pointer;
const UnitName, FileName, PCUName: String;
Parser: TBaseParser;
BuildAll: Boolean;
OutputStream: TStream): Boolean;
function PCUToString(Prg: Pointer; const UnitName,
FileName: String): String; overload;
function PCUToString(Prg: Pointer; const UnitName: String): String; overload;
function PCUToMainScript(Prg: Pointer; const Expression: String): String;
function PCUToScript(Prg: Pointer; Expression: String): TStringList;
implementation
uses
PAXCOMP_BASESYMBOL_TABLE,
PAXCOMP_SYMBOL_TABLE,
PAXCOMP_SYMBOL_REC,
PAXCOMP_BASERUNNER,
PAXCOMP_RTI,
PAXCOMP_MAP,
PAXCOMP_TYPEINFO,
PaxCompiler,
PaxRunner;
procedure AddScopeVars(Prog: TBaseRunner; var CodeLines: String); forward;
procedure CopyLocalImport(RootST, ST: TSymbolTable);
var
I: Integer;
R1, R2: TSymbolRec;
S: TMemoryStream;
Writer: TWriter;
Reader: TReader;
begin
for I := FirstLocalId + 1 to RootST.CompileCard do
begin
S := TMemoryStream.Create;
try
Writer := TWriter.Create(S, 1024);
try
R1 := RootST[I];
R1.SaveToStream(Writer);
finally
FreeAndNil(Writer);
end;
S.Seek(0, soFromBeginning);
Reader := TReader.Create(S, 1024);
try
R2 := ST.AddRecord;
R2.LoadFromStream(Reader);
finally
FreeAndNil(Reader);
end;
R2.Address := R1.Address;
R2.PClass := R1.PClass;
finally
FreeAndNil(S);
end;
end;
end;
function CompileUnit(Owner: Pointer;
const UnitName, FileName, PCUName: String;
Parser: TBaseParser;
BuildAll: Boolean;
OutputStream: TStream): Boolean;
var
PaxCompiler1: TPaxCompiler;
PaxRunner1: TPaxRunner;
UnitParser: TBaseParser;
C: TBaseParserClass;
RootKernel: TKernel;
CodeLines: String;
I: Integer;
PaxRunnerClass: TPaxRunnerClass;
TempProg: Pointer;
begin
RootKernel := TKernel(Owner).RootKernel;
CodeLines := '';
PaxRunnerClass := TPaxRunnerClass(RootKernel.Prog.Owner.ClassType);
if Assigned(RootKernel.OnUsedUnit) then
if RootKernel.Modules.IndexOf(UnitName) = -1 then
if not RootKernel.OnUsedUnit(RootKernel.Owner, UnitName, CodeLines) then
CodeLines := '';
if CodeLines = '' then
if not FileExists(FileName) then
begin
I := RootKernel.Modules.IndexOf(UnitName);
if I >= 0 then
begin
CodeLines := RootKernel.Modules[I].Lines.Text;
end
else
begin
result := FileExists(PCUName);
Exit;
end;
end;
PaxCompiler1 := TPaxCompiler.Create(nil);
CopyLocalImport(RootKernel.SymbolTable,
TKernel(PaxCompiler1.GetKernelPtr).SymbolTable);
PaxRunner1 := PaxRunnerClass.Create(nil);
C := TBaseParserClass(Parser.ClassType);
UnitParser := C.Create;
TKernel(PaxCompiler1.GetKernelPtr).PCUOwner := Owner;
TKernel(PaxCompiler1.GetKernelPtr).CopyRootEvents;
PaxCompiler1.DebugMode := RootKernel.DEBUG_MODE;
TempProg := CurrProg;
try
CurrProg := PaxRunner1.GetProgPtr;
TKernel(PaxCompiler1.GetKernelPtr).RegisterParser(UnitParser);
PaxCompiler1.AddModule(UnitName, UnitParser.LanguageName);
if CodeLines = '' then
PaxCompiler1.AddCodeFromFile(UnitName, FileName)
else
PaxCompiler1.AddCode(UnitName, CodeLines);
if PaxCompiler1.Compile(PaxRunner1, BuildAll) then
begin
if RootKernel.BuildWithRuntimePackages then
PaxRunner1.GetProgPtr.ProgList.Clear;
PaxRunner1.GetProgPtr.PCULang := UnitParser.LanguageId;
if Assigned(OutputStream) then
PaxRunner1.SaveToStream(OutputStream)
else
PaxRunner1.SaveToFile(PCUName);
result := true;
RootKernel.BuildedUnits.Add(UpperCase(PCUName));
end
else
begin
result := false;
RootKernel.Errors.Add(TKernel(PaxCompiler1.GetKernelPtr).Errors[0].Clone(RootKernel));
end;
finally
CurrProg := TempProg;
FreeAndNil(UnitParser);
FreeAndNil(PaxCompiler1);
FreeAndNil(PaxRunner1);
end;
end;
function PCUToString(Prg: Pointer; const UnitName: String): String;
begin
result := PCUToString(Prg, UnitName, UnitName + '.PCU');
end;
function PCUToString(Prg: Pointer; const UnitName,
FileName: String): String;
var
Prog: TBaseRunner;
ModuleRec: TModuleRec;
CodeLines: String;
I, J, J1: Integer;
MapTable: TMapTable;
TypeInfoList: TPaxTypeInfoList;
EnumTypeDataContainer: TEnumTypeDataContainer;
ArrayTypeDataContainer: TArrayTypeDataContainer;
RecordTypeDataContainer: TRecordTypeDataContainer;
SetTypeDataContainer: TSetTypeDataContainer;
AliasTypeDataContainer: TAliasTypeDataContainer;
PointerTypeDataContainer: TPointerTypeDataContainer;
ClassRefTypeDataContainer: TClassRefTypeDataContainer;
DynArrayTypeDataContainer: TDynArrayTypeDataContainer;
ProceduralTypeDataContainer: TProceduralTypeDataContainer;
ClassTypeDataContainer: TClassTypeDataContainer;
MethodTypeDataContainer: TMethodTypeDataContainer;
InterfaceTypeDataContainer: TInterfaceTypeDataContainer;
S, S1, S2: String;
AFullTypeName: String;
MapRec: TMapRec;
SubDesc: TSubDesc;
K: Integer;
L: TStringList;
LangId: Integer;
AClassName: String;
begin
Prog := TBaseRunner(Prg);
LangId := Prog.PCULang;
if LangId <> BASIC_LANGUAGE then
LangId := PASCAL_LANGUAGE;
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := '{$WARNINGS OFF}' + #13#10 +
'unit ' + ExtractName(UnitName) + ';' + #13#10 +
'interface' + #13#10;
end;
BASIC_LANGUAGE:
begin
CodeLines :=
'Module ' + ExtractName(UnitName) + #13#10;
end;
end;
ModuleRec := Prog.RunTimeModuleList.Modules.GetModuleRec(UnitName);
if ModuleRec <> nil then
if ModuleRec.UsedModules.Count > 0 then
begin
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines + 'uses ';
for I := 0 to ModuleRec.UsedModules.Count - 1 do
begin
CodeLines := CodeLines + ModuleRec.UsedModules[I];
if I < ModuleRec.UsedModules.Count - 1 then
CodeLines := CodeLines + ','
else
CodeLines := CodeLines + ';' + #13#10;
end;
end;
BASIC_LANGUAGE:
begin
CodeLines := CodeLines + 'Imports ';
for I := 0 to ModuleRec.UsedModules.Count - 1 do
begin
CodeLines := CodeLines + ModuleRec.UsedModules[I];
if I < ModuleRec.UsedModules.Count - 1 then
CodeLines := CodeLines + ','
else
CodeLines := CodeLines + #13#10;
end;
end;
end;
end;
MapTable := Prog.ScriptMapTable;
TypeInfoList := Prog.ProgTypeInfoList;
for I := 0 to TypeInfoList.Count - 1 do
begin
S := String(TypeInfoList[I].FullName);
if Pos(UpperCase(UnitName) + '.', UpperCase(S)) = 0 then
continue;
case TypeInfoList[I].TypeInfo.Kind of
tkUnknown:
begin
case TypeInfoList[I].FinTypeId of
typeALIAS:
begin
AliasTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TAliasTypeDataContainer;
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = ';
CodeLines := CodeLines +
ExtractName(AliasTypeDataContainer.FullSourceTypeName) + ';' +
#13#10;
end;
BASIC_LANGUAGE:
begin
CodeLines := CodeLines + 'TypeDef ' + PTIName(@TypeInfoList[I].TypeInfo) +
' As ';
CodeLines := CodeLines +
ExtractName(AliasTypeDataContainer.FullSourceTypeName) +
#13#10;
end;
end;
end;
typePOINTER:
begin
PointerTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TPointerTypeDataContainer;
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = ';
CodeLines := CodeLines + '^' +
ExtractName(PointerTypeDataContainer.FullOriginTypeName) + ';' +
#13#10;
end;
BASIC_LANGUAGE:
begin
CodeLines := CodeLines + 'TypeDef ' + PTIName(@TypeInfoList[I].TypeInfo) +
' As ';
CodeLines := CodeLines +
ExtractName(PointerTypeDataContainer.FullOriginTypeName) + ' *' +
#13#10;
end;
end;
end;
typeCLASSREF:
begin
ClassRefTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TClassRefTypeDataContainer;
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = ';
CodeLines := CodeLines + ' class of ' +
ExtractName(ClassRefTypeDataContainer.FullOriginTypeName) + ';' +
#13#10;
end;
BASIC_LANGUAGE:
begin
CodeLines := CodeLines + 'TypeDef ' + PTIName(@TypeInfoList[I].TypeInfo) +
' As ';
CodeLines := CodeLines + ' Class Of ' +
ExtractName(ClassRefTypeDataContainer.FullOriginTypeName) +
#13#10;
end;
end;
end;
typePROC:
begin
ProceduralTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TProceduralTypeDataContainer;
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = ';
with ProceduralTypeDataContainer.SubDesc do
begin
if ResTypeId = typeVOID then
CodeLines := CodeLines + 'procedure ('
else
CodeLines := CodeLines + 'function (';
if ParamList.Count = 0 then
CodeLines := CodeLines + ')'
else
for J := 0 to ParamList.Count - 1 do
begin
if ParamList[J].ParamMod = PM_BYREF then
CodeLines := CodeLines + 'var '
else if ParamList[J].ParamMod = PM_CONST then
CodeLines := CodeLines + 'const ';
CodeLines := CodeLines + ParamList[J].ParamName + ':' +
ParamList[J].ParamTypeName;
if ParamList[J].OptValue <> '' then
CodeLines := CodeLines + '=' + ParamList[J].OptValue;
if J < ParamList.Count - 1 then
CodeLines := CodeLines + ';'
else
CodeLines := CodeLines + ')';
end;
if ResTypeId = typeVOID then
CodeLines := CodeLines + ';'
else
CodeLines := CodeLines + ':' + ResTypeName + ';';
case CallMode of
ccREGISTER: CodeLines := CodeLines + 'register;';
ccSTDCALL: CodeLines := CodeLines + 'stdcall;';
ccCDECL: CodeLines := CodeLines + 'cdecl;';
ccPASCAL: CodeLines := CodeLines + 'pascal;';
ccSAFECALL: CodeLines := CodeLines + 'safecall;';
ccMSFASTCALL: CodeLines := CodeLines + 'msfastcall;';
end;
end;
end;
BASIC_LANGUAGE:
begin
Prog.RaiseError(errInternalError, []);
end;
end;
CodeLines := CodeLines + #13#10;
end;
end;
end;
tkRecord:
begin
RecordTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TRecordTypeDataContainer;
case LangId of
PASCAL_LANGUAGE:
begin
if TypeInfoList[I].IsGeneric then
begin
S := TypeInfoList[I].GenericTypeContainer.Definition;
CodeLines := CodeLines + 'type ' + S + #13#10;
continue;
end;
if RecordTypeDataContainer.IsPacked then
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = packed record' + #13#10
else
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = record' + #13#10;
with RecordTypeDataContainer do
for J := 0 to FieldListContainer.Count - 1 do
begin
CodeLines := CodeLines +
StringFromPShortString(@FieldListContainer[J].Name) + ':' +
ExtractName(FieldListContainer[J].FullFieldTypeName) +
';'#13#10;
end;
AFullTypeName := TypeInfoList[I].FullName;
// methods
for J := 0 to MapTable.Count - 1 do
begin
MapRec := MapTable[J];
if Pos(UpperCase(UnitName), UpperCase(MapRec.FullName)) = 1 then
begin
if MapRec.Kind in KindSUBS then
begin
SubDesc := MapRec.SubDesc;
if not SubDesc.IsMethod then
continue;
S := ExtractFullOwner(MapRec.FullName);
if not StrEql(AFullTypeName, S) then
continue;
S := ExtractName(MapRec.FullName);
case MapRec.Kind of
KindCONSTRUCTOR:
S := 'constructor ' + S + '(';
KindDESTRUCTOR:
S := 'destructor ' + S + '(';
KindSUB:
begin
if SubDesc.ResTypeId = typeVOID then
S := 'procedure ' + S + '('
else
S := 'function ' + S + '(';
end;
end;
if SubDesc.IsShared then
S := 'class ' + S;
case MapRec.Vis of
cvNone: continue;
cvPrivate: S := 'private ' + S;
cvPublic: S := 'public ' + S;
cvProtected: S := 'protected ' + S;
cvPublished:
begin
if MapRec.Kind = KindSUB then
S := 'published ' + S;
end;
end;
for K:=0 to SubDesc.ParamList.Count - 1 do
begin
case SubDesc.ParamList[K].ParamMod of
PM_BYVAL: begin end;
PM_BYREF: S := S + 'var ';
PM_CONST: S := S + 'const ';
end;
S := S + SubDesc.ParamList[K].ParamName;
S := S + ':';
S := S + SubDesc.ParamList[K].ParamTypeName;
if SubDesc.ParamList[K].OptValue <> '' then
S := S + '=' + SubDesc.ParamList[K].OptValue;
if K < SubDesc.ParamList.Count - 1 then
S := S + ';';
end;
S := S + ')';
if MapRec.Kind = KindSUB then
if SubDesc.ResTypeId <> typeVOID then
S := S + ':' + SubDesc.ResTypeName;
S := S + ';';
{
case SubDesc.CallMode of
cmNONE:
if MapRec.Kind = KindDESTRUCTOR then
S := S + 'override;';
cmVIRTUAL:
begin
S := S + 'virtual;';
end;
cmDYNAMIC:
begin
S := S + 'dynamic;';
end;
cmOVERRIDE:
S := S + 'override;';
end;
}
if not Prog.PAX64 then
begin
case SubDesc.CallConv of
ccREGISTER: S := S + 'register';
ccSTDCALL: S := S + 'stdcall';
ccCDECL: S := S + 'cdecl';
ccPASCAL: S := S + 'pascal';
ccSAFECALL: S := S + 'safecall';
ccMSFASTCALL: S := S + 'msfastcall';
end;
S := S + ';';
end;
S := S + 'external ' + '''' + FileName + '''' + ';';
CodeLines := CodeLines + S + #13#10;
end; // kindSUB
end;
end; // methods
CodeLines := CodeLines + 'end;'#13#10;
end; // PASCAL_LANGUAGE
BASIC_LANGUAGE:
begin
if TypeInfoList[I].IsGeneric then
begin
S := TypeInfoList[I].GenericTypeContainer.Definition;
CodeLines := CodeLines + S + #13#10;
continue;
end;
CodeLines := CodeLines + 'Structure ' + PTIName(@TypeInfoList[I].TypeInfo) +
#13#10;
with RecordTypeDataContainer do
for J := 0 to FieldListContainer.Count - 1 do
begin
CodeLines := CodeLines +
StringFromPShortString(@FieldListContainer[J].Name) + ' As ' +
ExtractName(FieldListContainer[J].FullFieldTypeName) +
#13#10;
end;
AFullTypeName := TypeInfoList[I].FullName;
// methods
for J := 0 to MapTable.Count - 1 do
begin
MapRec := MapTable[J];
if Pos(UpperCase(UnitName), UpperCase(MapRec.FullName)) = 1 then
begin
if MapRec.Kind in KindSUBS then
begin
SubDesc := MapRec.SubDesc;
if not SubDesc.IsMethod then
continue;
S := ExtractFullOwner(MapRec.FullName);
if not StrEql(AFullTypeName, S) then
continue;
AClassName := ExtractName(S);
if SubDesc.IsShared then
S := 'Shared '
else
S := '';
case MapRec.Vis of
cvNone: continue;
cvPrivate: S := S + ' Private ';
cvPublic: S := S + ' Public ';
cvProtected: S := S + ' Protected ';
cvPublished:
begin
if MapRec.Kind = KindSUB then
S := S + ' Published ';
end;
end;
{
case SubDesc.CallMode of
cmNONE:
if MapRec.Kind = KindDESTRUCTOR then
S := S + ' Overriden ';
cmVIRTUAL:
begin
S := S + ' Overriadable ';
end;
cmDYNAMIC:
begin
S := S + ' Dynamic ';
end;
cmOVERRIDE:
S := S + ' Overriden ';
end;
}
case MapRec.Kind of
KindCONSTRUCTOR:
S := S + ' Sub New ';
KindDESTRUCTOR:
S := S + ' Sub Finalize ';
KindSUB:
begin
if SubDesc.ResTypeId = typeVOID then
S := S + ' Sub ' + ExtractName(MapRec.FullName)
else
S := S + ' Function ' + ExtractName(MapRec.FullName);
end;
end;
{
case SubDesc.CallConv of
ccREGISTER: S := S + ' Register ';
ccSTDCALL: S := S + ' StdCall ';
ccCDECL: S := S + ' Cdecl ';
ccPASCAL: S := S + ' Pascal ';
ccSAFECALL: S := S + ' Safecall ';
ccMSFASTCALL: S := S + ' msfastcall ';
end;
}
S := S + ' Lib ' + '"' + FileName + '"';
case MapRec.Kind of
KindCONSTRUCTOR:
S := S + ' Alias ' + '"' + AClassName + '.Create' + '"';
KindDESTRUCTOR:
S := S + ' Alias ' + '"' + AClassName + '.Destroy' + '"';
else
S := S + ' Alias ' + '"' + AClassName + '.' + ExtractName(MapRec.FullName) + '"';
end;
S := S + ' (';
for K:=0 to SubDesc.ParamList.Count - 1 do
begin
case SubDesc.ParamList[K].ParamMod of
PM_BYVAL: begin end;
PM_BYREF: S := S + 'ByRef ';
PM_CONST: S := S + 'Const ';
end;
S := S + SubDesc.ParamList[K].ParamName;
S := S + ' As ';
S := S + SubDesc.ParamList[K].ParamTypeName;
if SubDesc.ParamList[K].OptValue <> '' then
S := S + '=' + SubDesc.ParamList[K].OptValue;
if K < SubDesc.ParamList.Count - 1 then
S := S + ',';
end;
S := S + ')';
if MapRec.Kind = KindSUB then
if SubDesc.ResTypeId <> typeVOID then
S := S + ' As ' + SubDesc.ResTypeName;
CodeLines := CodeLines + S + #13#10;
end; // kindSUB
end;
end; // methods
CodeLines := CodeLines + 'End Structure ' + #13#10 + #13#10;
end; // BASIC_LANGUAGE
end;
end; // tkRecord
tkArray:
begin
case LangId of
PASCAL_LANGUAGE:
begin
ArrayTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TArrayTypeDataContainer;
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = array[';
case ArrayTypeDataContainer.FinRangeTypeId of
{$IFNDEF PAXARM}
typeANSICHAR,
{$ENDIF}
typeWIDECHAR:
CodeLines := CodeLines +
'''' + Chr(ArrayTypeDataContainer.B1) + '''' + '..' +
'''' + Chr(ArrayTypeDataContainer.B2) + '''' + ']';
typeENUM, typeBOOLEAN, typeBYTEBOOL, typeWORDBOOL, typeLONGBOOL:
CodeLines := CodeLines +
ExtractName(ArrayTypeDataContainer.FullRangeTypeName) + ']';
else
begin
CodeLines := CodeLines +
IntToStr(ArrayTypeDataContainer.B1) + '..' +
IntToStr(ArrayTypeDataContainer.B2) + ']';
end;
end; // case
CodeLines := CodeLines + ' of ' +
ExtractName(ArrayTypeDataContainer.FullElemTypeName) + ';' +
#13#10;
end;
BASIC_LANGUAGE:
begin
Prog.RaiseError(errInternalError, []);
end;
end;
end; //tkArray
tkDynArray:
begin
DynArrayTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TDynArrayTypeDataContainer;
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = ';
CodeLines := CodeLines + ' array of ' +
ExtractName(DynArrayTypeDataContainer.FullElementTypeName) + ';' +
#13#10;
end;
BASIC_LANGUAGE:
begin
Prog.RaiseError(errInternalError, []);
end;
end;
end;
tkSet:
begin
SetTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TSetTypeDataContainer;
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = set of ';
CodeLines := CodeLines +
ExtractName(SetTypeDataContainer.FullCompName) + ';' +
#13#10;
end;
BASIC_LANGUAGE:
begin
Prog.RaiseError(errInternalError, []);
end;
end;
end; // tkSet
tkMethod:
begin
MethodTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TMethodTypeDataContainer;
if MethodTypeDataContainer.ResultTypeId = 0 then
continue;
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = ';
with MethodTypeDataContainer do
begin
if ResultTypeId = typeVOID then
CodeLines := CodeLines + 'procedure ('
else
CodeLines := CodeLines + 'function (';
if ParamCount = 0 then
CodeLines := CodeLines + ')'
else
for J := 0 to ParamCount - 1 do
with ParamListContainer do
begin
if ParamList[J].Flags = [pfVar] then
CodeLines := CodeLines + 'var '
else if ParamList[J].Flags = [pfConst] then
CodeLines := CodeLines + 'const ';
CodeLines := CodeLines + StringFromPShortString(@ParamList[J].ParamName) + ':' +
StringFromPShortString(@ParamList[J].TypeName);
if J < ParamCount - 1 then
CodeLines := CodeLines + ';'
else
CodeLines := CodeLines + ')';
end;
if ResultTypeId = typeVOID then
CodeLines := CodeLines + ' of object;'
else
CodeLines := CodeLines + ':' + StringFromPShortString(@ResultType) + ' of object;';
case CallConv of
ccREGISTER: CodeLines := CodeLines + 'register;';
ccSTDCALL: CodeLines := CodeLines + 'stdcall;';
ccCDECL: CodeLines := CodeLines + 'cdecl;';
ccPASCAL: CodeLines := CodeLines + 'pascal;';
ccSAFECALL: CodeLines := CodeLines + 'safecall;';
ccMSFASTCALL: CodeLines := CodeLines + 'msfastcall;';
end;
CodeLines := CodeLines + #13#10;
end;
end;
BASIC_LANGUAGE:
begin
Prog.RaiseError(errInternalError, []);
end;
end;
end; // tkMethod
tkClass:
begin
ClassTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TClassTypeDataContainer;
if Pos(UpperCase(UnitName), UpperCase(String(TypeInfoList[I].FullName))) <> 1 then
continue;
case LangId of
PASCAL_LANGUAGE:
begin
if TypeInfoList[I].IsGeneric then
begin
S := TypeInfoList[I].GenericTypeContainer.Definition;
CodeLines := CodeLines + 'type ' + S + #13#10;
continue;
end;
S := ExtractFullName(String(TypeInfoList[I].FullName));
S := RemoveCh('#', S);
CodeLines := CodeLines + 'type ' + S;
S := ExtractName(String(ClassTypeDataContainer.FullParentName));
S := RemoveCh('#', S);
CodeLines := CodeLines + ' = class (' + S;
for J := 0 to ClassTypeDataContainer.SupportedInterfaces.Count - 1 do
begin
CodeLines := CodeLines + ',' +
ClassTypeDataContainer.SupportedInterfaces[J];
end;
CodeLines := CodeLines + ')' + #13#10;
AFullTypeName := String(TypeInfoList[I].FullName);
// public fields
for J := 0 to ClassTypeDataContainer.AnotherFieldListContainer.Count - 1 do
begin
case ClassTypeDataContainer.AnotherFieldListContainer[J].Vis of
cvPrivate: CodeLines := CodeLines + 'private ';
cvProtected: CodeLines := CodeLines + 'protected ';
cvPublic: CodeLines := CodeLines + 'public ';
end;
CodeLines := CodeLines +
StringFromPShortString(@ClassTypeDataContainer.AnotherFieldListContainer[J].Name)
+ ':' +
ClassTypeDataContainer.AnotherFieldListContainer[J].FullFieldTypeName +
';'#13#10;
end;
// published fields
for J := 0 to ClassTypeDataContainer.FieldListContainer.Count - 1 do
begin
CodeLines := CodeLines + 'published ' +
StringFromPShortString(@ClassTypeDataContainer.FieldListContainer[J].Name) + ':' +
ExtractName(ClassTypeDataContainer.FieldListContainer[J].FullFieldTypeName) +
';'#13#10;
end;
// methods
for J := 0 to MapTable.Count - 1 do
begin
MapRec := MapTable[J];
if Pos(UpperCase(UnitName), UpperCase(MapRec.FullName)) = 1 then
begin
if MapRec.Kind in KindSUBS then
begin
SubDesc := MapRec.SubDesc;
if not SubDesc.IsMethod then
continue;
S := ExtractFullOwner(MapRec.FullName);
if not StrEql(AFullTypeName, S) then
continue;
S := ExtractName(MapRec.FullName);
case MapRec.Kind of
KindCONSTRUCTOR:
S := 'constructor ' + S + '(';
KindDESTRUCTOR:
S := 'destructor ' + S + '(';
KindSUB:
begin
if SubDesc.ResTypeId = typeVOID then
S := 'procedure ' + S + '('
else
S := 'function ' + S + '(';
end;
end;
if SubDesc.IsShared then
S := 'class ' + S;
case MapRec.Vis of
cvNone: continue;
cvPrivate: S := 'private ' + S;
cvPublic: S := 'public ' + S;
cvProtected: S := 'protected ' + S;
cvPublished:
begin
if MapRec.Kind = KindSUB then
S := 'published ' + S;
end;
end;
for K:=0 to SubDesc.ParamList.Count - 1 do
begin
case SubDesc.ParamList[K].ParamMod of
PM_BYVAL: begin end;
PM_BYREF: S := S + 'var ';
PM_CONST: S := S + 'const ';
end;
S := S + SubDesc.ParamList[K].ParamName;
S := S + ':';
S := S + SubDesc.ParamList[K].ParamTypeName;
if SubDesc.ParamList[K].OptValue <> '' then
S := S + '=' + SubDesc.ParamList[K].OptValue;
if K < SubDesc.ParamList.Count - 1 then
S := S + ';';
end;
S := S + ')';
if MapRec.Kind = KindSUB then
if SubDesc.ResTypeId <> typeVOID then
S := S + ':' + SubDesc.ResTypeName;
S := S + ';';
case SubDesc.CallMode of
cmNONE:
if MapRec.Kind = KindDESTRUCTOR then
S := S + 'override;';
cmVIRTUAL:
begin
S := S + 'virtual;';
end;
cmDYNAMIC:
begin
S := S + 'dynamic;';
end;
cmOVERRIDE:
S := S + 'override;';
end;
if not Prog.PAX64 then
begin
case SubDesc.CallConv of
ccREGISTER: S := S + 'register';
ccSTDCALL: S := S + 'stdcall';
ccCDECL: S := S + 'cdecl';
ccPASCAL: S := S + 'pascal';
ccSAFECALL: S := S + 'safecall';
ccMSFASTCALL: S := S + 'msfastcall';
end;
S := S + ';';
end;
if MapRec.SubDesc.OverCount > 0 then
S := S + 'overload;';
if (MapRec.SubDesc.DllName = '') and (MapRec.SubDesc.AliasName = '') then
S := S + 'external ' + '''' + FileName + '''' + ';'
else
S := S + ' external ' + '''' + MapRec.SubDesc.DllName + '''' +
' name ' + '''' + MapRec.SubDesc.AliasName + '''' +
';';
CodeLines := CodeLines + S + #13#10;
end; // kindSUB
end;
end; // methods
// public properties
with ClassTypeDataContainer do
for J := 0 to AnotherPropList.Count - 1 do
with AnotherPropList[J] do
begin
case Vis of
cvPrivate: CodeLines := CodeLines + 'private ';
cvProtected: CodeLines := CodeLines + 'protected ';
cvPublic: CodeLines := CodeLines + 'public ';
end;
CodeLines := CodeLines + 'property ' + PropName;
if ParamNames.Count > 0 then
begin
CodeLines := CodeLines + '[';
for K := 0 to ParamNames.Count - 1 do
begin
CodeLines := CodeLines + ParamNames[K] + ':' +
ParamTypes[K];
if K < ParamNames.Count - 1 then
CodeLines := CodeLines + ','
else
CodeLines := CodeLines + ']';
end;
end;
CodeLines := CodeLines + ':' + PropType;
if Length(ReadName) > 0 then
CodeLines := CodeLines + ' read ' + ReadName;
if Length(WriteName) > 0 then
CodeLines := CodeLines + ' write ' + WriteName;
CodeLines := CodeLines + ';';
if IsDefault then
CodeLines := CodeLines + 'default;';
CodeLines := CodeLines + #13#10;
end;
// published properties
for J := 0 to ClassTypeDataContainer.PropDataContainer.PropTypeNames.Count - 1 do
begin
S1 := ExtractName(ClassTypeDataContainer.PropDataContainer.ReadNames[J]);
if Pos(READ_PREFIX, S1) = 1 then
S1 := Copy(S1, Length(READ_PREFIX) + 1, Length(S1) - Length(READ_PREFIX));
S2 := ExtractName(ClassTypeDataContainer.PropDataContainer.WriteNames[J]);
if Pos(WRITE_PREFIX, S2) = 1 then
S2 := Copy(S2, Length(WRITE_PREFIX) + 1, Length(S2) - Length(WRITE_PREFIX));
CodeLines := CodeLines + 'published property ';
S := StringFromPShortString(@ClassTypeDataContainer.PropDataContainer.PropList[J].Name);
CodeLines := CodeLines + S;
for J1 := 0 to MapTable.Count - 1 do
begin
MapRec := MapTable[J1];
if MapRec.Kind <> KindSUB then
continue;
if Pos(UpperCase(UnitName), UpperCase(MapRec.FullName)) = 1 then
begin
SubDesc := MapRec.SubDesc;
if not SubDesc.IsMethod then
continue;
if SubDesc.ParamList.Count = 0 then
continue;
S := ExtractFullOwner(MapRec.FullName);
if not StrEql(AFullTypeName, S) then
continue;
S := ExtractName(MapRec.FullName);
if not StrEql(S, S1) then
continue;
S := '[';
for K:=0 to SubDesc.ParamList.Count - 1 do
begin
case SubDesc.ParamList[K].ParamMod of
PM_BYVAL: begin end;
PM_BYREF: S := S + 'var ';
PM_CONST: S := S + 'const ';
end;
S := S + SubDesc.ParamList[K].ParamName;
S := S + ':';
S := S + SubDesc.ParamList[K].ParamTypeName;
if SubDesc.ParamList[K].OptValue <> '' then
S := S + '=' + SubDesc.ParamList[K].OptValue;
if K < SubDesc.ParamList.Count - 1 then
S := S + ';';
end;
S := S + ']';
CodeLines := CodeLines + S;
break;
end;
end;
if CodeLines[Length(CodeLines)] <> ']' then
for J1 := 0 to MapTable.Count - 1 do
begin
MapRec := MapTable[J1];
if MapRec.Kind <> KindSUB then
continue;
if Pos(UpperCase(UnitName), UpperCase(MapRec.FullName)) = 1 then
begin
SubDesc := MapRec.SubDesc;
if not SubDesc.IsMethod then
continue;
if SubDesc.ParamList.Count <= 1 then
continue;
S := ExtractFullOwner(MapRec.FullName);
if not StrEql(AFullTypeName, S) then
continue;
S := ExtractName(MapRec.FullName);
if not StrEql(S, S2) then
continue;
S := '[';
for K:=0 to SubDesc.ParamList.Count - 2 do
begin
case SubDesc.ParamList[K].ParamMod of
PM_BYVAL: begin end;
PM_BYREF: S := S + 'var ';
PM_CONST: S := S + 'const ';
end;
S := S + SubDesc.ParamList[K].ParamName;
S := S + ':';
S := S + SubDesc.ParamList[K].ParamTypeName;
if SubDesc.ParamList[K].OptValue <> '' then
S := S + '=' + SubDesc.ParamList[K].OptValue;
if K < SubDesc.ParamList.Count - 2 then
S := S + ';';
end;
S := S + ']';
CodeLines := CodeLines + S;
break;
end;
end;
CodeLines := CodeLines +
':' +
ExtractName(ClassTypeDataContainer.PropDataContainer.PropTypeNames[J]);
if Length(S1) > 0 then
CodeLines := CodeLines + ' read ' + S1;
if Length(S2) > 0 then
CodeLines := CodeLines + ' write ' + S2;
CodeLines := CodeLines + ';'#13#10;
end;
CodeLines := CodeLines + 'end;' + #13#10;
end;
BASIC_LANGUAGE:
begin
if TypeInfoList[I].IsGeneric then
begin
S := TypeInfoList[I].GenericTypeContainer.Definition;
CodeLines := CodeLines + S + #13#10;
continue;
end;
if TypeInfoList[I].IsGeneric then
begin
S := TypeInfoList[I].GenericTypeContainer.Definition;
CodeLines := CodeLines + S + #13#10;
continue;
end;
CodeLines := CodeLines + 'Class ' + PTIName(@TypeInfoList[I].TypeInfo) +
#13#10;
S := ExtractName(ClassTypeDataContainer.FullParentName);
S := RemoveCh('#', S);
CodeLines := CodeLines + 'Inherits ' + S;
for J := 0 to ClassTypeDataContainer.SupportedInterfaces.Count - 1 do
begin
CodeLines := CodeLines + ',' +
ClassTypeDataContainer.SupportedInterfaces[J];
end;
CodeLines := CodeLines + #13#10;
with ClassTypeDataContainer do
for J := 0 to FieldListContainer.Count - 1 do
begin
CodeLines := CodeLines +
StringFromPShortString(@FieldListContainer[J].Name) + ' As ' +
ExtractName(FieldListContainer[J].FullFieldTypeName) +
#13#10;
end;
AFullTypeName := TypeInfoList[I].FullName;
// methods
for J := 0 to MapTable.Count - 1 do
begin
MapRec := MapTable[J];
if Pos(UpperCase(UnitName), UpperCase(MapRec.FullName)) = 1 then
begin
if MapRec.Kind in KindSUBS then
begin
SubDesc := MapRec.SubDesc;
if not SubDesc.IsMethod then
continue;
S := ExtractFullOwner(MapRec.FullName);
if not StrEql(AFullTypeName, S) then
continue;
AClassName := ExtractName(S);
if SubDesc.IsShared then
S := 'Shared '
else
S := '';
case MapRec.Vis of
cvNone: continue;
cvPrivate: S := S + ' Private ';
cvPublic: S := S + ' Public ';
cvProtected: S := S + ' Protected ';
cvPublished:
begin
if MapRec.Kind = KindSUB then
S := S + ' Published ';
end;
end;
{
case SubDesc.CallMode of
cmNONE:
if MapRec.Kind = KindDESTRUCTOR then
S := S + ' Overriden ';
cmVIRTUAL:
begin
S := S + ' Overriadable ';
end;
cmDYNAMIC:
begin
S := S + ' Dynamic ';
end;
cmOVERRIDE:
S := S + ' Overriden ';
end;
}
case MapRec.Kind of
KindCONSTRUCTOR:
S := S + ' Sub New ';
KindDESTRUCTOR:
S := S + ' Sub Finalize ';
KindSUB:
begin
S1 := ExtractName(MapRec.FullName);
if Pos('__get', S1) = 1 then
S1 := '__' + S1
else if Pos('__set', S1) = 1 then
S1 := '__' + S1;
if SubDesc.ResTypeId = typeVOID then
S := S + ' Sub ' + S1
else
S := S + ' Function ' + S1;
end;
end;
{
case SubDesc.CallConv of
ccREGISTER: S := S + ' Register ';
ccSTDCALL: S := S + ' StdCall ';
ccCDECL: S := S + ' Cdecl ';
ccPASCAL: S := S + ' Pascal ';
ccSAFECALL: S := S + ' Safecall ';
ccMSFASTCALL: S := S + ' msfastcall ';
end;
}
S := S + ' Lib ' + '"' + FileName + '"';
case MapRec.Kind of
KindCONSTRUCTOR:
S := S + ' Alias ' + '"' + AClassName + '.Create' + '"';
KindDESTRUCTOR:
S := S + ' Alias ' + '"' + AClassName + '.Destroy' + '"';
else
S := S + ' Alias ' + '"' + AClassName + '.' + ExtractName(MapRec.FullName) + '"';
end;
S := S + ' (';
for K:=0 to SubDesc.ParamList.Count - 1 do
begin
case SubDesc.ParamList[K].ParamMod of
PM_BYVAL: begin end;
PM_BYREF: S := S + 'ByRef ';
PM_CONST: S := S + 'Const ';
end;
S := S + SubDesc.ParamList[K].ParamName;
S := S + ' As ';
S := S + SubDesc.ParamList[K].ParamTypeName;
if SubDesc.ParamList[K].OptValue <> '' then
S := S + '=' + SubDesc.ParamList[K].OptValue;
if K < SubDesc.ParamList.Count - 1 then
S := S + ',';
end;
S := S + ')';
if MapRec.Kind = KindSUB then
if SubDesc.ResTypeId <> typeVOID then
S := S + ' As ' + SubDesc.ResTypeName;
CodeLines := CodeLines + S + #13#10;
end; // kindSUB
end;
end; // methods
// public properties
with ClassTypeDataContainer do
for J := 0 to AnotherPropList.Count - 1 do
with AnotherPropList[J] do
begin
case Vis of
cvPrivate: CodeLines := CodeLines + 'Private ';
cvProtected: CodeLines := CodeLines + 'Protected ';
cvPublic: CodeLines := CodeLines + 'Public ';
end;
CodeLines := CodeLines + 'Property ' + PropName;
if ParamNames.Count > 0 then
begin
CodeLines := CodeLines + '(';
for K := 0 to ParamNames.Count - 1 do
begin
CodeLines := CodeLines + ParamNames[K] + ' As ' +
ParamTypes[K];
if K < ParamNames.Count - 1 then
CodeLines := CodeLines + ','
else
CodeLines := CodeLines + ')';
end;
end;
CodeLines := CodeLines + ' As ' +
PropType + #13#10;
if Length(ReadName) > 0 then
begin
CodeLines := CodeLines + 'Get' + #13#10;
CodeLines := CodeLines + ' Return ' + '__' + ReadName;
CodeLines := CodeLines + '(';
for K := 0 to ParamNames.Count - 1 do
begin
CodeLines := CodeLines + ParamNames[K];
if K < ParamNames.Count - 1 then
CodeLines := CodeLines + ',';
end;
CodeLines := CodeLines + ')';
CodeLines := CodeLines + #13#10;
CodeLines := CodeLines + 'End Get' + #13#10;
end;
if Length(WriteName) > 0 then
begin
CodeLines := CodeLines + 'Set' + #13#10;
CodeLines := CodeLines + '__' + WriteName;
CodeLines := CodeLines + '(';
for K := 0 to ParamNames.Count - 1 do
begin
CodeLines := CodeLines + ParamNames[K];
CodeLines := CodeLines + ',';
end;
CodeLines := CodeLines + 'value)';
CodeLines := CodeLines + #13#10;
CodeLines := CodeLines + 'End Set' + #13#10;
end;
CodeLines := CodeLines + 'End Property' + #13#10;
CodeLines := CodeLines + #13#10;
end;
// published properties
for J := 0 to ClassTypeDataContainer.PropDataContainer.PropTypeNames.Count - 1 do
begin
S1 := ExtractName(ClassTypeDataContainer.PropDataContainer.ReadNames[J]);
if Pos(READ_PREFIX, S1) = 1 then
S1 := Copy(S1, Length(READ_PREFIX) + 1, Length(S1) - Length(READ_PREFIX));
S2 := ExtractName(ClassTypeDataContainer.PropDataContainer.WriteNames[J]);
if Pos(WRITE_PREFIX, S2) = 1 then
S2 := Copy(S2, Length(WRITE_PREFIX) + 1, Length(S2) - Length(WRITE_PREFIX));
CodeLines := CodeLines + 'Published Property ';
S := StringFromPShortString(@ClassTypeDataContainer.PropDataContainer.PropList[J].Name);
CodeLines := CodeLines + S;
for J1 := 0 to MapTable.Count - 1 do
begin
MapRec := MapTable[J1];
if MapRec.Kind <> KindSUB then
continue;
if Pos(UpperCase(UnitName), UpperCase(MapRec.FullName)) = 1 then
begin
SubDesc := MapRec.SubDesc;
if not SubDesc.IsMethod then
continue;
if SubDesc.ParamList.Count = 0 then
continue;
S := ExtractFullOwner(MapRec.FullName);
if not StrEql(AFullTypeName, S) then
continue;
S := ExtractName(MapRec.FullName);
if not StrEql(S, S1) then
continue;
S := '(';
for K:=0 to SubDesc.ParamList.Count - 1 do
begin
case SubDesc.ParamList[K].ParamMod of
PM_BYVAL: begin end;
PM_BYREF: S := S + 'var ';
PM_CONST: S := S + 'const ';
end;
S := S + SubDesc.ParamList[K].ParamName;
S := S + ':';
S := S + SubDesc.ParamList[K].ParamTypeName;
if SubDesc.ParamList[K].OptValue <> '' then
S := S + '=' + SubDesc.ParamList[K].OptValue;
if K < SubDesc.ParamList.Count - 1 then
S := S + ';';
end;
S := S + ')';
CodeLines := CodeLines + S;
break;
end;
end;
if CodeLines[Length(CodeLines)] <> ')' then
for J1 := 0 to MapTable.Count - 1 do
begin
MapRec := MapTable[J1];
if MapRec.Kind <> KindSUB then
continue;
if Pos(UpperCase(UnitName), UpperCase(MapRec.FullName)) = 1 then
begin
SubDesc := MapRec.SubDesc;
if not SubDesc.IsMethod then
continue;
if SubDesc.ParamList.Count <= 1 then
continue;
S := ExtractFullOwner(MapRec.FullName);
if not StrEql(AFullTypeName, S) then
continue;
S := ExtractName(MapRec.FullName);
if not StrEql(S, S2) then
continue;
S := '(';
for K:=0 to SubDesc.ParamList.Count - 2 do
begin
case SubDesc.ParamList[K].ParamMod of
PM_BYVAL: begin end;
PM_BYREF: S := S + 'ByRef ';
PM_CONST: S := S + 'Const ';
end;
S := S + SubDesc.ParamList[K].ParamName;
S := S + ' As ';
S := S + SubDesc.ParamList[K].ParamTypeName;
if SubDesc.ParamList[K].OptValue <> '' then
S := S + '=' + SubDesc.ParamList[K].OptValue;
if K < SubDesc.ParamList.Count - 2 then
S := S + ',';
end;
S := S + ')';
CodeLines := CodeLines + S;
break;
end;
end;
CodeLines := CodeLines +
' As ' +
ExtractName(ClassTypeDataContainer.PropDataContainer.PropTypeNames[J]);
CodeLines := CodeLines + #13#10;
if Length(S1) > 0 then
begin
CodeLines := CodeLines + 'Get' + #13#10;
CodeLines := CodeLines + ' Return ' + '__' + String(S1);
CodeLines := CodeLines + '(';
CodeLines := CodeLines + ')';
CodeLines := CodeLines + #13#10;
CodeLines := CodeLines + 'End Get' + #13#10;
end;
if Length(S2) > 0 then
begin
CodeLines := CodeLines + 'Set' + #13#10;
CodeLines := CodeLines + '__' + String(S2);
CodeLines := CodeLines + '(';
CodeLines := CodeLines + 'value)';
CodeLines := CodeLines + #13#10;
CodeLines := CodeLines + 'End Set' + #13#10;
end;
CodeLines := CodeLines + 'End Property' + #13#10;
end;
CodeLines := CodeLines + 'End Class' + #13#10 + #13#10;
end; // Basic
end;
end;
tkString:
begin
case LangId of
PASCAL_LANGUAGE:
begin
{$IFDEF PAXARM}
Prog.RaiseError(errInternalError, []);
{$ELSE}
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = String[' +
IntToStr(TypeInfoList[I].TypeDataContainer.TypeData.MaxLength) +
'];'#13#10;
{$ENDIF}
end;
BASIC_LANGUAGE:
begin
Prog.RaiseError(errInternalError, []);
end;
end;
end;
tkInterface:
begin
InterfaceTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TInterfaceTypeDataContainer;
case LangId of
PASCAL_LANGUAGE:
begin
if TypeInfoList[I].IsGeneric then
begin
S := TypeInfoList[I].GenericTypeContainer.Definition;
CodeLines := CodeLines + ' type ' + S + #13#10;
continue;
end;
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = interface(' +
ExtractName(InterfaceTypeDataContainer.FullParentName)
+ ')' + #13#10;
CodeLines := CodeLines +
'[''' +
GuidToString(InterfaceTypeDataContainer.Guid) +
''']' +
#13#10;
for K := 0 to InterfaceTypeDataContainer.SubDescList.Count - 1 do
with InterfaceTypeDataContainer.SubDescList[K] do
begin
if ResTypeId = typeVOID then
CodeLines := CodeLines + 'procedure '
else
CodeLines := CodeLines + 'function ';
CodeLines := CodeLines + SubName + '(';
if ParamList.Count = 0 then
CodeLines := CodeLines + ')'
else
for J := 0 to ParamList.Count - 1 do
begin
if ParamList[J].ParamMod = PM_BYREF then
CodeLines := CodeLines + 'var '
else if ParamList[J].ParamMod = PM_CONST then
CodeLines := CodeLines + 'const ';
CodeLines := CodeLines + ParamList[J].ParamName + ':' +
ParamList[J].ParamTypeName;
if ParamList[J].OptValue <> '' then
CodeLines := CodeLines + '=' + ParamList[J].OptValue;
if J < ParamList.Count - 1 then
CodeLines := CodeLines + ';'
else
CodeLines := CodeLines + ')';
end; // for-loop
if ResTypeId = typeVOID then
CodeLines := CodeLines + ';'
else
CodeLines := CodeLines + ':' + ResTypeName + ';';
if OverCount > 0 then
CodeLines := CodeLines + 'overload;';
case CallConv of
ccREGISTER: CodeLines := CodeLines + 'register;';
ccSTDCALL: CodeLines := CodeLines + 'stdcall;';
ccCDECL: CodeLines := CodeLines + 'cdecl;';
ccPASCAL: CodeLines := CodeLines + 'pascal;';
ccSAFECALL: CodeLines := CodeLines + 'safecall;';
ccMSFASTCALL: CodeLines := CodeLines + 'msfastcall;';
end;
CodeLines := CodeLines + #13#10;
end; // for-looop SubDescList
for J := 0 to InterfaceTypeDataContainer.PropDataContainer.Count - 1 do
with InterfaceTypeDataContainer do
begin
S1 := ExtractName(PropDataContainer.ReadNames[J]);
S2 := ExtractName(PropDataContainer.WriteNames[J]);
CodeLines := CodeLines + 'property ' +
StringFromPShortString(@PropDataContainer.PropList[J].Name) + ':' +
PropDataContainer.PropTypeNames[J];
if S1 <> '' then
CodeLines := CodeLines + ' read ' + S1;
if S2 <> '' then
CodeLines := CodeLines + ' write ' + S2;
CodeLines := CodeLines + ';'#13#10;
end;
CodeLines := CodeLines + 'end;' + #13#10;
end; // pascal
BASIC_LANGUAGE:
begin
if TypeInfoList[I].IsGeneric then
begin
S := TypeInfoList[I].GenericTypeContainer.Definition;
CodeLines := CodeLines + S + #13#10;
continue;
end;
CodeLines := CodeLines + 'Interface ' + PTIName(@TypeInfoList[I].TypeInfo) +
#13#10;
CodeLines := CodeLines + 'Inherits ' +
ExtractName(InterfaceTypeDataContainer.FullParentName)
+ #13#10;
for K := 0 to InterfaceTypeDataContainer.SubDescList.Count - 1 do
with InterfaceTypeDataContainer.SubDescList[K] do
begin
if ResTypeId = typeVOID then
CodeLines := CodeLines + 'Sub '
else
CodeLines := CodeLines + 'Function ';
CodeLines := CodeLines + SubName + '(';
if ParamList.Count = 0 then
CodeLines := CodeLines + ')'
else
for J := 0 to ParamList.Count - 1 do
begin
if ParamList[J].ParamMod = PM_BYREF then
CodeLines := CodeLines + 'ByRef '
else if ParamList[J].ParamMod = PM_CONST then
CodeLines := CodeLines + 'Const ';
CodeLines := CodeLines + ParamList[J].ParamName + ' As ' +
ParamList[J].ParamTypeName;
if ParamList[J].OptValue <> '' then
CodeLines := CodeLines + '=' + ParamList[J].OptValue;
if J < ParamList.Count - 1 then
CodeLines := CodeLines + ','
else
CodeLines := CodeLines + ')';
end; // for-loop
if ResTypeId <> typeVOID then
CodeLines := CodeLines + ' As ' + ResTypeName;
CodeLines := CodeLines + #13#10;
end; // for-looop SubDescList
CodeLines := CodeLines + 'End Interface' + #13#10;
end;
end;
end; // tkInterface
tkEnumeration:
begin
EnumTypeDataContainer :=
TypeInfoList[I].TypeDataContainer as TEnumTypeDataContainer;
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines + 'type ' + PTIName(@TypeInfoList[I].TypeInfo) +
' = (';
K := System.Length(EnumTypeDataContainer.NameList);
for J := 0 to K - 1 do
begin
CodeLines := CodeLines +
StringFromPShortString(@EnumTypeDataContainer.NameList[J]) + '=' +
IntToStr(EnumTypeDataContainer.ValueList[J]);
if J < K - 1 then
CodeLines := CodeLines + ','
else
CodeLines := CodeLines + ');' + #13#10;
end;
end;
BASIC_LANGUAGE:
begin
CodeLines := CodeLines + 'Enum ' + PTIName(@TypeInfoList[I].TypeInfo) +
#13#10;
K := System.Length(EnumTypeDataContainer.NameList);
for J := 0 to K - 1 do
begin
CodeLines := CodeLines +
StringFromPShortString(@EnumTypeDataContainer.NameList[J]) + '=' +
IntToStr(EnumTypeDataContainer.ValueList[J]) + #13#10;
end;
CodeLines := CodeLines + 'End Enum' + #13#10;
end;
end;
end; //tkEnumeration
end; // case
end; // for-loop
for I := 0 to MapTable.Count - 1 do
begin
MapRec := MapTable[I];
if Pos(UpperCase(ExtractName(UnitName)), UpperCase(MapRec.FullName)) = 1 then
begin
S := ExtractName(MapRec.FullName);
if MapRec.Kind = KindSUB then
begin
SubDesc := MapRec.SubDesc;
if SubDesc.IsMethod then
continue;
if S = '' then
continue;
if SubDesc.ResTypeId = typeVOID then
S := 'procedure ' + S + '('
else
S := 'function ' + S + '(';
for J:=0 to SubDesc.ParamList.Count - 1 do
begin
case SubDesc.ParamList[J].ParamMod of
PM_BYVAL: begin end;
PM_BYREF: S := S + 'var ';
PM_CONST: S := S + 'const ';
end;
S := S + SubDesc.ParamList[J].ParamName;
S := S + ':';
S := S + SubDesc.ParamList[J].ParamTypeName;
if SubDesc.ParamList[J].OptValue <> '' then
S := S + '=' + SubDesc.ParamList[J].OptValue;
if J < SubDesc.ParamList.Count - 1 then
S := S + ';';
end;
S := S + ')';
if SubDesc.ResTypeId <> typeVOID then
S := S + ':' + SubDesc.ResTypeName;
S := S + ';';
if not Prog.PAX64 then
begin
case SubDesc.CallConv of
ccREGISTER: S := S + 'register';
ccSTDCALL: S := S + 'stdcall';
ccCDECL: S := S + 'cdecl';
ccPASCAL: S := S + 'pascal';
ccSAFECALL: S := S + 'safecall';
ccMSFASTCALL: S := S + 'msfastcall';
end;
S := S + ';';
end;
if SubDesc.OverCount > 0 then
S := S + 'overload;';
if (MapRec.SubDesc.DllName = '') and (MapRec.SubDesc.AliasName = '') then
S := S + 'external ' + '''' + FileName + '''' + ';'
else
S := S + ' external ' + '''' + MapRec.SubDesc.DllName + '''' +
' name ' + '''' + MapRec.SubDesc.AliasName + '''' +
';';
CodeLines := CodeLines + S + #13#10;
end // kindSUB
else if MapRec.Kind = KindVAR then
begin
S := 'var ' + S + ':' +
ExtractName(MapRec.FullTypeName) +
';';
S := S + 'external ' + '''' + FileName + '''' + ';';
CodeLines := CodeLines + S + #13#10;
end // kindVAR
else if MapRec.Kind = KindCONST then
begin
S := 'const ' + S + ':' +
ExtractName(MapRec.FullTypeName) +
';';
S := S + 'external ' + '''' + FileName + '''' + ';';
CodeLines := CodeLines + S + #13#10;
end; // kindCONST
CodeLines := CodeLines + #13#10;
end;
end;
if Prog.CurrExpr <> '' then
AddScopeVars(Prog, CodeLines);
case LangId of
PASCAL_LANGUAGE:
begin
CodeLines := CodeLines +
'implementation' + #13#10;
for I := 0 to TypeInfoList.Count - 1 do
begin
if Pos(UpperCase(ExtractName(UnitName)), UpperCase(String(TypeInfoList[I].FullName))) <> 1 then
continue;
if TypeInfoList[I].IsGeneric then
for J := 0 to TypeInfoList[I].GenericTypeContainer.MethodList.Count - 1 do
begin
S := TypeInfoList[I].GenericTypeContainer.MethodList[J];
CodeLines := CodeLines + S + #13#10;
continue;
end;
end;
if Prog.CurrExpr <> '' then
begin
CodeLines := CodeLines +
'begin ' + #13#10;
CodeLines := CodeLines +
'print ' + Prog.CurrExpr + ';' + #13#10;
end;
CodeLines := CodeLines +
'end.' + #13#10;
end;
BASIC_LANGUAGE:
CodeLines := CodeLines +
'End Module' + #13#10;
end;
if IsDump then
begin
L := TStringList.Create;
try
L.Text := CodeLines;
L.SaveToFile(DUMP_PATH + ExtractName(UnitName) + '.dmp');
finally
FreeAndNil(L);
end;
end;
result := CodeLines;
end;
procedure AddScopeVars(Prog: TBaseRunner; var CodeLines: String);
var
MR, MRT: TMapRec;
I: Integer;
S: String;
MapTable: TMapTable;
begin
MR := Prog.GetCurrentSub;
if MR <> nil then
begin
for I := 0 to MR.SubDesc.ParamList.Count - 1 do
with MR.SubDesc.ParamList[I] do
begin
if ParamMod = PM_BYREF then
S := PRR_FILE_EXT
else
S := PRM_FILE_EXT;
CodeLines := CodeLines +
'var ' + ParamName + ':' + ParamTypeName + '; external ' +
'''' + MR.FullName + '.' + S + '''' + ';' +
#13#10;
end;
for I := 0 to MR.SubDesc.LocalVarList.Count - 1 do
with MR.SubDesc.LocalVarList[I] do
begin
if IsByRef then
S := LOR_FILE_EXT
else
S := LOC_FILE_EXT;
CodeLines := CodeLines +
'var ' + LocalVarName + ':' + LocalVarTypeName + '; external ' +
'''' + MR.FullName + '.' + S + '''' + ';' +
#13#10;
end;
if MR.SubDesc.IsMethod then
begin
if MR.SubDesc.ParamList.IndexOf('Self') = -1 then
if MR.SubDesc.LocalVarList.IndexOf('Self') = -1 then
begin
S := ExtractClassName(MR.FullName);
CodeLines := CodeLines +
'var Self: ' + S + '; external ' +
'''' + MR.FullName + '.' + SLF_FILE_EXT + '''' + ';' +
#13#10;
end;
S := ExtractFullOwner(MR.FullName);
MapTable := Prog.ScriptMapTable;
MRT := MapTable.LookupType(S);
if MRT <> nil then
begin
for I := 0 to MRT.FieldList.Count - 1 do
begin
CodeLines := CodeLines +
'var ' + MRT.FieldList[I].FieldName + ':' +
MRT.FieldList[I].FieldTypeName +
'; external ' +
'''' + MR.FullName + '.' +
FLD_FILE_EXT + '''' + ';' +
#13#10;
end;
end;
end;
end;
end;
function PCUToMainScript(Prg: Pointer; const Expression: String): String;
var
Prog: TBaseRunner;
UnitName: String;
begin
Prog := TBaseRunner(Prg);
Prog.CurrExpr := Expression;
try
UnitName := Prog.GetModuleName;
result := PCUToString(Prg, UnitName);
finally
Prog.CurrExpr := '';
end;
end;
function PCUToScript(Prg: Pointer; Expression: String): TStringList;
var
Prog: TBaseRunner;
UnitName: String;
I: Integer;
S: String;
begin
Prog := TBaseRunner(Prg);
UnitName := Prog.GetModuleName;
S := PCUToMainScript(Prg, Expression);
result := TStringList.Create;
result.Add(S);
for I := 0 to Prog.ProgList.Count - 1 do
begin
S := PCUToString(Prog.ProgList[I].Prog,
ExtractName(Prog.ProgList[I].FullPath));
result.Add(S);
end;
if not IsDump then
Exit;
end;
end.
|
{*******************************************************}
{ }
{ Page Parsing Module }
{ }
{ Copyright (C) 2014 Company }
{ }
{*******************************************************}
unit uScanModule;
interface
uses Classes, SHDocVw;
type
{ TPageParserThread - page parsing thread }
TPageParserThread = class (TThread)
private
FWebBrowser: TWebBrowser;
FURL: string;
// FisPageLoaded: Boolean;
{
// Set flag FisPageLoaded in TRUE, if page has loaded
procedure BrowserDocumentComplete(ASender: TObject;
const pDisp: IDispatch; const URL: OleVariant);
}
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean;
aURLtoScan: string); overload;
end;
implementation
uses SysUtils;
{ TPageParserThread }
constructor TPageParserThread.Create(CreateSuspended: Boolean;
aURLtoScan: string);
begin
// FisPageLoaded := False;
FURL := aURLtoScan;
// FWebBrowser.OnDownloadComplete := BrowserDocumentComplete(Self, );
end;
procedure TPageParserThread.Execute;
begin
inherited;
FWebBrowser := TWebBrowser.Create(nil);
try
FWebBrowser.Navigate(FURL);
while FWebBrowser.ReadyState <> 4 do Sleep(0);
finally
FreeAndNil(FWebBrowser);
end;
end;
{
procedure TPageParserThread.BrowserDocumentComplete(ASender: TObject;
const pDisp: IDispatch; const URL: OleVariant);
begin
FisPageLoaded := True;
end;
}
end.
|
unit testtelegram;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, fpjson, tgsendertypes, testbase, tgtypes;
type
{ TTestSender }
{ Test sending messages. Object style }
TTestSender= class(TTestTelegramClass)
private
FJSONMediaGroup: String;
FPhotoFile: String;
FPhotoUrl: String;
FUrl: String;
FVideoFile: String;
FVideoUrl: String;
protected
procedure SetUp; override;
public
property VideoUrl: String read FVideoUrl;
property Url: String read FUrl;
property VideoFile: String read FVideoFile;
property PhotoUrl: String read FPhotoUrl;
property PhotoFile: String read FPhotoFile;
property jsonMediaGroup: String read FJSONMediaGroup;
published
procedure sendMessage;
procedure InlineKeyboard;
procedure sendVideo;
procedure sendVideoByFileName;
procedure sendVideoStream;
procedure sendPhoto;
procedure sendPhotoByFileName;
procedure sendMediaGroup;
procedure ChatMember;
procedure getWebhookInfo;
procedure setWebhook;
procedure deleteWebhook;
procedure testCodePage;
end;
{ TTestProxySender }
TTestProxySender = class(TTestSender)
private
FProxyHost: String;
FProxyPassword: String;
FProxyPort: Word;
FProxyUser: String;
protected
procedure SetUp; override;
public
property ProxyUser: String read FProxyUser write FProxyUser;
property ProxyPassword: String read FProxyPassword write FProxyPassword;
property ProxyHost: String read FProxyHost write FProxyHost;
property ProxyPort: Word read FProxyPort write FProxyPort;
end;
{ TTestSenderProcedure }
{ Test sending messages. Simple procedure style}
TTestSenderProcedure=class(TTestTelegramBase)
published
procedure sendMessage;
end;
{ TTestReceiveLongPollingBase }
{ Test receiving updates via longpolling from the test bot. Please send test messages to the bot
immediately before running the test! }
TTestReceiveLongPolling=class(TTestTelegramClass)
private
FReceived: Boolean;
procedure BotReceiveUpdate({%H-}ASender: TObject; AnUpdate: TTelegramUpdateObj);
protected
procedure SetUp; override;
property Received: Boolean read FReceived write FReceived;
published
procedure ReceiveUpdate;
end;
{ TTestPayments }
TTestPayments=class(TTestTelegramClass)
private
FCurrency: String;
FPortionAmount: Integer;
FPortionLabel: String;
FProviderToken: String;
FReceived: Boolean;
procedure BotReceivePreCheckoutQuery({%H-}ASender: TObject;
APreCheckoutQuery: TTelegramPreCheckOutQuery);
procedure BotReceiveSuccessfulPayment({%H-}ASender: TObject;
AMessage: TTelegramMessageObj);
protected
procedure SetUp; override;
public
property Currency: String read FCurrency write FCurrency; // 3-letter ISO 4217 currency code
property ProviderToken: String read FProviderToken write FProviderToken; // Payments provider token
property PortionLabel: String read FPortionLabel write FPortionLabel; // Price portion label
property PortionAmount: Integer read FPortionAmount write FPortionAmount; // Price portion amount
property Received: Boolean read FReceived write FReceived;
published
procedure sendInvoice; // test send invoice
procedure ReceivePreCheckoutQuery; // test receiving test pre_checkout_query update (after invoice is sent!)
procedure ReceiveSuccessfulPayment;
end;
implementation
uses
URIParser, jsonparser
;
const
Msg='Test message sent from %s. Test procedure: %s';
vd_cptn='Test video sent from %s. Test procedure: %s';
pht_cptn='Test photo sent from %s. Test procedure: %s';
Msg_md='Test message sent from %s. Test procedure: _%s_';
s_Username='Username';
s_Password='Password';
s_Proxy='Proxy';
s_Host='Host';
s_Port='Port';
s_Uri='Uri';
{ TTestProxySender }
procedure TTestProxySender.SetUp;
var
AHost, AUsername, APassword: String;
APort: Word;
URI: TURI;
begin
inherited SetUp;
AHost:= Conf.ReadString(s_Proxy, s_Host, EmptyStr);
AUsername:=Conf.ReadString(s_Proxy, s_Username, EmptyStr);
APassword:=Conf.ReadString(s_Proxy, s_Password, EmptyStr);
APort:= Conf.ReadInteger(s_Proxy, s_Port, 0);
if AHost=EmptyStr then
begin
URI:=URIParser.ParseURI('https://'+Conf.ReadString(s_Proxy, s_Uri, EmptyStr));
AHost:=URI.Host;
APort:=URI.Port;
AUsername:=URI.Username;
APassword:=URI.Password;
end;
Bot.HTTPProxyHost:=AHost;
Bot.HTTPProxyPort:=APort;
Bot.HTTPProxyUser:=AUsername;
Bot.HTTPProxyPassword:=APassword;
end;
{ TTestReceiveLongPolling }
procedure TTestReceiveLongPolling.BotReceiveUpdate(ASender: TObject;
AnUpdate: TTelegramUpdateObj);
begin
SaveJSONData(Bot.JSONResponse, '~responce.json');
SaveString(AnUpdate.AsString, '~update.json');
Received:=True;
end;
procedure TTestReceiveLongPolling.SetUp;
begin
inherited SetUp;
Bot.OnReceiveUpdate:=@BotReceiveUpdate;
FReceived:=False;
end;
procedure TTestReceiveLongPolling.ReceiveUpdate;
begin
Bot.getUpdates();
if not Received then
Fail('No updates were received. Send, for example, a message to the test bot')
else
Bot.getUpdatesEx(100, 1); //
end;
{ TTestPayments }
procedure TTestPayments.BotReceivePreCheckoutQuery(ASender: TObject;
APreCheckoutQuery: TTelegramPreCheckOutQuery);
begin
SaveJSONData(Bot.JSONResponse, '~responce.json');
SaveString(APreCheckoutQuery.AsString, '~PreCheckoutQuery.json');
Received:=True;
Bot.answerPreCheckoutQuery(APreCheckoutQuery.ID, True);
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestPayments.BotReceiveSuccessfulPayment(ASender: TObject;
AMessage: TTelegramMessageObj);
begin
SaveJSONData(Bot.JSONResponse, '~responce.json');
SaveString(AMessage.SuccessfulPayment.AsString, '~SuccessfulPayment.json');
Received:=True;
end;
procedure TTestPayments.SetUp;
begin
inherited SetUp;
Bot.OnReceivePreCheckoutQuery:=@BotReceivePreCheckoutQuery;
Bot.OnReceiveSuccessfulPayment:=@BotReceiveSuccessfulPayment;
FProviderToken:=Conf.ReadString('Payment', 'ProviderToken', EmptyStr);
FCurrency:=Conf.ReadString('Payment', 'Currency', EmptyStr);
FPortionLabel:=Conf.ReadString('Payment', 'PricePortionLabel', EmptyStr);
FPortionAmount:=Conf.ReadInteger('Payment', 'PricePortionAmount', 0);
end;
procedure TTestPayments.sendInvoice;
var
Prices: TLabeledPriceArray;
begin
Prices:=TLabeledPriceArray.Create(PortionLabel, PortionAmount);
try
Bot.sendInvoice(ChatID, 'TestProduct', 'This is test product for the testing purpose', 'payload001',
ProviderToken, 'DeepLinkingStartParameter', Currency, Prices, nil);
finally
FreeAndNil(Prices);
end;
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestPayments.ReceivePreCheckoutQuery;
begin
Bot.getUpdates;
if not Received then
Fail('No updates were received. Please send the (test) payment for the created previously invoice')
else
Bot.getUpdatesEx(100, 1); // Telegram API will understand that previous updates have been processed
end;
procedure TTestPayments.ReceiveSuccessfulPayment;
begin
Bot.getUpdates;
if not Received then
Fail('No updates were received. Please receive PreCheckoutQuery before')
else
Bot.getUpdatesEx(100, 1); // Telegram API will understand that previous updates have been processed
end;
{ TTestSenderProcedure }
procedure TTestSenderProcedure.sendMessage;
var
AToken: String;
AChatID: Int64;
AReply: String;
begin
AToken:=Conf.ReadString('Bot', 'Token', EmptyStr);
AChatID:=Conf.ReadInt64('Chat', 'ID', 0);
if not TgBotSendMessage(AToken, AChatID, Format(Msg, [Self.ClassName, TestName]), AReply) then
Fail('Fail to send message from telegram bot!');
SaveString(AReply, '~JSONResponce.json');
end;
{ TTestSender }
procedure TTestSender.SetUp;
begin
inherited SetUp;
FVideoUrl:=Conf.ReadString('Send', 'videourl', EmptyStr);
FUrl:=Conf.ReadString('Send', 'Url', EmptyStr);
FVideoFile:=Conf.ReadString('Send', 'VideoFile', EmptyStr);
FPhotoUrl:=Conf.ReadString('Send', 'photourl', EmptyStr);
FPhotoFile:=Conf.ReadString('Send', 'PhotoFile', EmptyStr);
FJSONMediaGroup:=Conf.ReadString('Send', 'JSONMediaGroup', EmptyStr);
end;
procedure TTestSender.sendMessage;
begin
if not Bot.sendMessage(ChatID, Format(Msg, [Self.ClassName, TestName])) then
Fail('Connection error. See log');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
if not Bot.sendMessage(ChatID, Format(Msg_md, [Self.ClassName, TestName]), pmMarkdown) then
Fail('Connection error. See log');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.InlineKeyboard;
var
ReplyMarkup: TReplyMarkup;
Buttons: TInlineKeyboardButtons;
begin
ReplyMarkup:=TReplyMarkup.Create;
try
Buttons:=ReplyMarkup.CreateInlineKeyBoard.Add;
Buttons.AddButtonUrl('Github.com',
'https://github.com/Al-Muhandis/fp-telegram');
ReplyMarkup.InlineKeyBoard.Add.AddButtons(['Button 1', 'Callback data 1', 'Button 2', 'Callback data 2']);
if not Bot.sendMessage(ChatID, Format(Msg_md, [Self.ClassName, TestName]), pmMarkdown,
False, ReplyMarkup) then
Fail('Connection error. See log');
finally
ReplyMarkup.Free;
end;
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.sendVideo;
begin
if not Bot.sendVideo(ChatID, VideoUrl, Format(vd_cptn, [Self.ClassName, TestName])) then
Fail('Connection error. See log');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.sendVideoByFileName;
begin
if not Bot.sendVideoByFileName(ChatID, VideoFile, Format(vd_cptn, [Self.ClassName, TestName]), pmDefault, Nil) then
Fail('Connection error. See log');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.sendVideoStream;
var
aStream: TMemoryStream;
begin
aStream:=TMemoryStream.Create;
aStream.LoadFromFile(VideoFile);
if not Bot.sendVideoStream(ChatID, VideoFile, aStream, Format(vd_cptn, [Self.ClassName, TestName])) then
Fail('Connection error. See log');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
aStream.Free;
end;
procedure TTestSender.sendPhoto;
begin
if not Bot.sendPhoto(ChatID, PhotoUrl, Format(pht_cptn, [Self.ClassName, TestName])) then
Fail('Connection error. See log');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.sendPhotoByFileName;
begin
if not Bot.sendPhotoByFileName(ChatID, PhotoFile, Format(pht_cptn, [Self.ClassName, TestName])) then
Fail('Connection error. See log');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.sendMediaGroup;
var
aJSONData: TJSONArray;
aMedias: TInputMediaArray;
i: TJSONEnum;
begin
aJSONData:=GetJSON(JSONMediaGroup) as TJSONArray;
aMedias:=TInputMediaArray.Create;
try
for i in aJSONData do
aMedias.Add(i.Value.Clone as TJSONObject);
if not Bot.sendMediaGroup(ChatID, aMedias) then
Fail('Connection error. See log');
finally
aJSONData.Free;
aMedias.Free;
end;
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.ChatMember;
begin
if not Bot.getChatMember(ChatID, UserID) then
Fail('Connection error. See log');
SaveJSONData(Bot.JSONResponse, '~responce.json');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.getWebhookInfo;
var
aWebhookInfo: TTelegramWebhookInfo;
begin
try
if not Bot.getWebhookInfo(aWebhookInfo) then
Fail('Connection error. See log')
else
SaveString(aWebhookInfo.AsString, '~webhookinfo.json');
finally
aWebhookInfo.Free;
end;
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.setWebhook;
begin
if not Bot.setWebhook(Url, 10, []) then
Fail('Connection error. See log');
SaveJSONData(Bot.JSONResponse, '~responce.json');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.deleteWebhook;
begin
if not Bot.deleteWebhook then
Fail('Connection error. See log');
SaveJSONData(Bot.JSONResponse, '~responce.json');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
procedure TTestSender.testCodePage;
var
aStream: TStringStream;
s: String;
begin
aStream:=TStringStream.Create(EmptyStr);
aStream.LoadFromFile('~debugutf8.txt');
S:=EmptyStr;
s+=aStream.DataString;
Bot.Logger.Debug(CodePageToCodePageName(StringCodePage(S)));
if not Bot.sendMessage(ChatID, s, pmMarkdown) then
Fail('Connection error. See log');
aStream.Free;
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
if not Bot.sendMessage(ChatID, Format(Msg_md, [Self.ClassName, TestName]), pmMarkdown) then
Fail('Connection error. See log');
if Bot.LastErrorCode<>0 then
Fail('Error from telegram API server. Error code: '+IntToStr(Bot.LastErrorCode)+
'. Description: '+Bot.LastErrorDescription);
end;
initialization
RegisterTests([TTestSender, TTestSenderProcedure, TTestProxySender, TTestReceiveLongPolling, TTestPayments]);
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.Sources.Interfaces;
interface
uses
VSoft.Awaitable,
Spring.Collections,
DPM.Core.Sources.Types,
DPM.Core.Options.Push,
DPM.Core.Options.Sources,
VSoft.Uri;
type
ISourcesManager = interface
['{8854A223-60C9-4D65-8FFC-37A0AA503103}']
function AddSource(const options : TSourcesOptions) : boolean;
function RemoveSource(const options : TSourcesOptions) : boolean;
function ListSources(const options : TSourcesOptions) : boolean;
function EnableSource(const options : TSourcesOptions) : boolean;
function DisableSource(const options : TSourcesOptions) : boolean;
function UpdateSource(const options : TSourcesOptions) : boolean;
//TODO : provide some way to re-order the sources when we have a UI.
end;
IServiceIndexItem = interface
['{BD0F1369-563C-49BE-A84A-905DAAED47A6}']
function GetResourceUrl : string;
function GetResourceType : string;
property ResourceUrl : string read GetResourceUrl;
property ResourceType : string read GetResourceType;
end;
IServiceIndex = interface
['{0633BFFC-CAC7-464C-8374-07EC3858E585}']
function GetItems : IList<IServiceIndexItem>;
function FindItems(const resourceType : string) : IEnumerable<IServiceIndexItem>;
//just finds the first one of the type.
function FindItem(const resourceType : string) : IServiceIndexItem;
property Items : IList<IServiceIndexItem> read GetItems;
end;
implementation
end.
|
unit Chapter03._05_Solution1;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DeepStar.Utils;
// 75. Sort Colors
// https://leetcode.com/problems/sort-colors/description/
// 计数排序的思路
// 对整个数组遍历了两遍
// 时间复杂度: O(n)
// 空间复杂度: O(k), k为元素的取值范围
type
TSolution = class(TObject)
public
procedure SortColors(nums: TArr_int);
end;
procedure Main;
implementation
procedure Main;
var
arr: TArr_int;
begin
arr := [2, 2, 2, 1, 1, 0];
with TSolution.Create do
begin
SortColors(arr);
Free;
end;
TArrayUtils_int.Print(arr);
end;
{ TSolution }
procedure TSolution.SortColors(nums: TArr_int);
var
Count: TArr_int;
i, index, j: integer;
begin
Count := [0, 0, 0];
for i := 0 to High(nums) do
begin
Assert((nums[i] >= 0) and (nums[i] <= 2));
Count[nums[i]] += 1;
end;
index := 0;
for i := 0 to High(Count) do
begin
for j := 0 to Count[i] - 1 do
begin
nums[index] := i;
index += 1;
end;
end;
end;
end.
|
//******************************************************************************
// Проект "ГорВодоКанал" (bs)
// Файл строковых ресурсов
// создан 18/01/2010
// последние изменения Перчак А.Л. 18/01/2010
//******************************************************************************
unit uConsts;
interface
{Set Language}
const bs_Lang :array[1..3] of string=('00000409', '00000419', '00000422');
{Options}
const bs_max_sys_timestamp :array[1..2] of String=('Нескінченна дата','Бесконечная дата');
const bs_date_start :array[1..2] of String=('Дата старту системи','Дата старта системы');
{Windows}
const bs_Windows_Tiltle :array[1..2] of String=('Вікна','Окна');
const bs_WindowsCacade :array[1..2] of String=('Каскад','Каскад');
const bs_WindowsHorizontal :array[1..2] of String=('Горизонтально','Горизонтально');
const bs_WindowsVertical :array[1..2] of String=('Вертикально','Вертикально');
const bs_WindowsMinimizeAll :array[1..2] of String=('Звернути усі','Свернуть все');
const bs_WindowsCloseAll :array[1..2] of String=('Закрити усі','Закрыть все');
{Form_Titles}
const bs_ReestrContracts_Tiltle :array[1..2] of String=('Реєстр контрактів','Реестр контрактов');
const bs_DBInfo_Tiltle :array[1..2] of String=('Підключення до БД','Подключение к БД');
const bs_FileVersion :array[1..2] of String=('Версія','Версия');
const bs_AssemblingVersion :array[1..2] of String=('Зборка','Сборка');
const bs_ConnectionInfo :array[1..2] of String=('Інформація про з''єднання','Информация про подключение');
const bs_ApplicationName :array[1..2] of String=('Ім''я файлу: ','Имя приложения: ');
const bs_ApplicationWay :array[1..2] of String=('Розміщення файлу: ','Путь к приложению: ');
const bs_FileVersionFull :array[1..2] of String=('Версія файлу: ','Версия файла: ');
const bs_AssemblingDate :array[1..2] of String=('Дата зборки: ','Дата сборки: ');
const bs_DBWay :array[1..2] of String=('Розміщення файлу БД: ','Путь к базе данных: ');
const bs_FilterText :array[1..2] of String=('введіть прізвище','введите фамилию');
const bs_HelpText :array[1..2] of String=('Допомога','Помощь');
const bs_WorkWithPopulation :array[1..2] of String=('Робота з населенням','Работа с населением');
const bs_WorkWithEnterprise :array[1..2] of String=('Робота з підприємствами','Работа с предприятиями');
const bs_WorkWitDogs :array[1..2] of String=('Робота з договорами','Работа с договорами');
const bs_NowDate_Caption :array[1..2] of String=('Сьогодні: ','Сегодня: ');
const bs_RaschetSchet_Title :array[1..2] of String=('Розрахунковий рахунок','Расчетный счет');
const bs_UserFio :array[1..2] of String=('П.І.Б. користувача: ','ФИО пользователя: ');
const bs_Login :array[1..2] of String=('Логін: ','Логин: ');
const bs_UserInfo :array[1..2] of String=('Інформація про користувача: ','Информация про пользователя');
const bs_grid_ADDVerName :array[1..2] of String=('Назва версії прейскаранта','Название версии прейскуранта');
{Date_Formats}
const bs_Year_Short :array[1..2] of String=(' рр.',' гг.');
{ShortCuts}
const bs_InsertBtn_ShortCut :array[1..2] of String=('Ins ', 'Ins ');
const bs_EditBtn_ShortCut :array[1..2] of String=('F2 ','F2 ');
const bs_DeleteBtn_ShortCut :array[1..2] of String=('Del ','Del ');
const bs_RefreshBtn_ShortCut :array[1..2] of String=('F5 ', 'F5 ');
const bs_ExitBtn_ShortCut :array[1..2] of String=('Esc ','Esc ');
const bs_FilterBtn_ShortCut :array[1..2] of String=('Ctrl+F ','Ctrl+F ');
const bs_EnterBtn_ShortCut :array[1..2] of String=('Enter ','Enter ');
const bs_PaymentBtn_ShortCut :array[1..2] of String=('F6 ','F6 ');
const bs_PrintBtn_ShortCut :array[1..2] of String=('Ctrl+P ','Ctrl+P ');
const bs_ModeBtn_ShortCut :array[1..2] of String=('F9 ','F9 ');
const bs_F10Btn_ShortCut :array[1..2] of String=('F10 ','F10 ');
const bs_F3Btn_ShortCut :array[1..2] of String=('F3 ','F3 ');
{All_Actions}
const bs_InsertBtn_Caption :array[1..2] of String=('Додати','Добавить');
const bs_EditBtn_Caption :array[1..2] of String=('Змінити','Изменить');
const bs_DeleteBtn_Caption :array[1..2] of String=('Видалити','Удалить');
const bs_RefreshBtn_Caption :array[1..2] of String=('Оновити', 'Обновить');
const bs_ExitBtn_Caption :array[1..2] of String=(' Вихід ',' Выход ');
const bs_FilterBtn_Caption :array[1..2] of String=('Фільтр','Фильтр');
const bs_FilterParams_Need :array[1..2] of String=('Не вибрані параметри для фільтрації!','Не выбраны параметры для фильтрации!');
const bs_SearchBtn_Caption :array[1..2] of String=('Пошук','Поиск');
const bs_Print_Caption :array[1..2] of String=(' Друк ',' Печать ');
const bs_Pay_Caption :array[1..2] of String=(' Оплата ',' Оплата ');
const bs_Lgota_Caption :array[1..2] of String=(' Пільги ',' Льготы ');
const bs_living_Caption :array[1..2] of String=('Проживають','Проживающие');
const bs_Kat_Caption :array[1..2] of String=('Послуги','Услуги');
const bs_Subsidy_Caption :array[1..2] of String=('Субсидії','Субсидии');
const bs_EntryRest_Caption :array[1..2] of String=('Вхідний залишок','Входящий остаток');
const bs_History :array[1..2] of String=('Історія','История');
const bs_SelectBtn_Caption :array[1..2] of String=('Вибрати','Выбрать');
const bs_ModeBtn_Caption :array[1..2] of String=('Зміна режиму','Смена режима');
const bs_PrintShort_Caption :array[1..2] of String=('Друк','Печать');
const bs_ViewShort_Caption :array[1..2] of String=('Перегляд','Просмотр');
const bs_AutoShort_Caption :array[1..2] of String=('Автоматично','Автоматично');
const bs_Credit_Caption :array[1..2] of String=('Кредит','Кредит');
const bs_Upload_Caption :array[1..2] of String=('Переоформити','Переоформить');
const bs_BreakDown_Caption :array[1..2] of String=('Розірвати','Расторгнуть');
const bs_PayerInfoData :array[1..2] of String=('Дані про платника','Данные о плательщике');
const bs_Pri4inaRastorg :array[1..2] of String=('Причина розірвання','Причина расторжения');
const bs_ViewAll :array[1..2] of String=('Розгорнути усі','Развернуть все');
const bs_HidenAll :array[1..2] of String=('Згорнути усі','Свернуть все');
{Confirms}
const bs_Confirmation_Caption :array[1..2] of String=('Підтвердження','Подтверждение');
const bs_Uvaga_Caption :array[1..2] of String=('Увага!','Внимание!');
const bs_ExitPromt :array[1..2] of String=('Ви бажаєте вийти?', 'Вы хотите выйти?');
const bs_DeletePromt :array[1..2] of String=('Ви дійсно хочете видалити запис?', 'Вы действительно хотите удалить запись?');
const bs_Accept :array[1..2] of String=('Прийняти','Принять');
const bs_Cancel :array[1..2] of String=('Відмінити','Отмена');
const bs_ClearBufferPromt :array[1..2] of String=('Ви дійсно хочете очистити буфер?', 'Вы действительно хотите очистить буфер?');
{ApplicationInitialise}
const bs_Application_Caption :array[1..2] of String=('Горводоканал','Горводоканал');
const bs_Reestr_Main_Caption :array[1..2] of String=('Реестр договорів','Реестр договоров');
const bs_Main_Ready_Caption :array[1..2] of String=('Готовий','Готов');
const bs_Main_StatusBar_Caption :array[1..2] of String=('Панель інформації','Панель информации');
const bs_HotKeys :array[1..2] of String=('Горячі клавіши','Горячие клавиши');
{MainButtons}
const bs_Main_WorkBtn_Caption :array[1..2] of String=('Робота','Работа');
const bs_Main_SpravBtn_Caption :array[1..2] of String=('Довідники','Справочники');
const bs_Main_AboutBtn_Caption :array[1..2] of String=('Про програму','О программе');
const bs_Main_ExitBtn_Caption :array[1..2] of String=('Вихід','Выход');
{Errors}
const bs_Error_Caption :array[1..2] of String=('Помилка','Ошибка');
const bs_Error_LoadBPL_Text :array[1..2] of String=('Помилка при завантаженні пакету','Ошибка при загрузке пакета');
{MainGuides}
const bs_Main_Lgot :array[1..2] of String=('Довідник типів пільг', 'Справочник типов льгот');
const bs_Main_PayerType :array[1..2] of String=('Довідник типів платників', 'Справочник типов плательщиков');
const bs_Main_FacultySpeciality :array[1..2] of String=('Довідник cпеціальностей та груп', 'Справочник специальностей и групп');
const bs_Main_FormStudy :array[1..2] of String=('Довідник форм навчання', 'Справочник форм обучения');
const bs_Main_Faculty :array[1..2] of String=('Довідник факультетів', 'Справочник факультетов');
const bs_Main_Nationality :array[1..2] of String=('Довідник національностей', 'Справочник национальностей');
const bs_Main_Kat :array[1..2] of String=('Довідник послуг', 'Справочник услуг');
const bs_Main_Subsidy :array[1..2] of String=('Довідник субсидій', 'Справочник субсидий');
const bs_Main_IniPeriodic :array[1..2] of String=('Довідник періодичностей оплат', 'Справочник периодичности оплат');
const bs_Main_FaculSpecGroup :array[1..2] of String=('Довідник факультетів, cпеціальностей та груп', 'Справочник факультетов, специальностей и групп');
const bs_PaymentAnalysis :array[1..2] of String=('Форма аналізу оплати', 'Форма анализа оплаты');
const bs_Main_SpRoles :array[1..2] of String=('Довідник груп користувачів та кошторисів','Справочник групп пользователей и смет');
const bs_Main_SpActions :array[1..2] of String=('Довідник дій','Справочник действий');
const bs_Main_SpSignature :array[1..2] of String=('Довідник підписів','Справочник подписей');
const bs_Main_SpSpec :array[1..2] of String=('Довідник cпеціальностей','Справочник специальностей');
const bs_Main_SpDepartment :array[1..2] of String=('Довідник підрозділів','Справочник подразделений');
const bs_Main_SpDogStatus :array[1..2] of String=('Довідник статусів контрактів','Справочник статусов контрактов');
const bs_Main_SpPeople :array[1..2] of String=('Довідник фізичних осіб','Справочник физических лиц');
const bs_Main_SpYurLiza :array[1..2] of String=('Довідник юрідичних осіб','Справочник юридических лиц');
const bs_Main_SpRapStatus :array[1..2] of String=('Довідник статусів рапортів','Справочник статусов рапортов');
const bs_Main_SpTypeDocum :array[1..2] of String=('Довідник типів стану документів','Справочник типов состояния документов');
const bs_Main_SpOrders :array[1..2] of String=('Довідник наказів','Справочник приказов');
const bs_Main_SpNamesReport :array[1..2] of String=('Довідник найменувань звітів','Справочник наименований отчетов');
const bs_Main_SpTypeDog :array[1..2] of String=('Довідник типів контрактів','Справочник типов контрактов');
const bs_Main_SpDatePay :array[1..2] of String=('Довідник дат оплат','Справочник дат оплат');
const bs_Main_DawaVCImport :array[1..2] of String=('Імпорт даних з ОЦ','Импорт данных из ВЦ');
const bs_Main_DawaVCPrimary :array[1..2] of String=('Імпорт договорів у буфер','Импорт договров в буфер');
const bs_Main_DawaVCLinks :array[1..2] of String=('Імпорт договорів з буферу','Импорт договоров из буфера');
const bs_Main_DawaVCBuffer :array[1..2] of String=('Буфер контрактів','Буфер контрактов');
const bs_Main_RaportOtchisl :array[1..2] of String=('Рапорти на відрахування','Рапорта на отчисление');
const bs_Main_RaportVotanovl :array[1..2] of String=('Рапорти на відновлення','Рапорта на восстановление');
const bs_print_RZ_Postyp :array[1..2] of String=('Реєстр/Зведена форма надходжень за навчання','Реестр/Сводная форма поступлений за обучение');
{Contracts_Grid}
const bs_grid_FIO_Column :array[1..2] of String=('П.І.Б.', 'Ф.И.О.');
const bs_grid_Date_Dog_Column :array[1..2] of String=('Дата укладання', 'Дата заключения');
const bs_grid_Num_Dog_Column :array[1..2] of String=('Номер договору', 'Номер договора');
const bs_grid_Date_Beg :array[1..2] of String=('Дата початку', 'Дата начала');
const bs_grid_Date_End :array[1..2] of String=('Дата закінчення', 'Дата окончания');
const bs_grid_IsDiss_Column :array[1..2] of String=('Не діючий', 'Не действующий');
const bs_grid_IsNotDiss_Column :array[1..2] of String=('Діючий', 'Действующий');
{Contracts_Footer}
const bs_footer_Faculty :array[1..2] of String=('Факультет', 'Факультет');
const bs_footer_Spec :array[1..2] of String=('Спеціальність', 'Специальность');
const bs_footer_Group :array[1..2] of String=('Група', 'Группа');
const bs_footer_FormStudy :array[1..2] of String=('Форма навчання', 'Форма обучения');
const bs_footer_CategoryStudy :array[1..2] of String=('Категорія навчання', 'Категория обучения');
const bs_footer_Kurs :array[1..2] of String=('Курс', 'Курс');
const bs_Gragdanstvo :array[1..2] of String=('Громадянство', 'Гражданство');
const bs_srok_study :array[1..2] of String=('Строк навчання','Срок обучения');
//-----{Contracts_Components}------------------------------------------------------------------//
{Contracts_Components_GroupBox}
const bs_BasicInfo_GroupBox :array[1..2] of String=('Основна інформація', 'Основная информация');
const bs_Study_GroupBox :array[1..2] of String=('Інформація про осіб, що навчаються', 'Обучающиеся');
const bs_Studer_Osoba :array[1..2] of String=('Особа, що навчається', 'Обучающийся');
const bs_Payer_Osoba :array[1..2] of String=('Платник', 'Плательщик');
const bs_Payers_GroupBox :array[1..2] of String=('Платники', 'Плательщики');
const bs_Periods_GroupBox :array[1..2] of String=('Періоди оплати', 'Периоды оплаты');
const bs_Istochniki_GroupBox :array[1..2] of String=('Джерела фінансування', 'Источники финансирования');
{Contracts_Components_Lables}
const bs_Num_Dog_Label :array[1..2] of String=('Номер договору', 'Номер договора');
const bs_Date_Zakl_Label :array[1..2] of String=('Дата укладання', 'Дата заключения');
const bs_Date_Beg_Label :array[1..2] of String=('Дата початку', 'Дата начала');
const bs_Date_End_Label :array[1..2] of String=('Дата закінчення', 'Дата окончания');
const bs_Type_Dog_Label :array[1..2] of String=('Тип договору', 'Тип договора');
const bs_Basic_Dog_Label :array[1..2] of String=('Основний', 'Основной');
const bs_Addit_Dog_Label :array[1..2] of String=('Додатковий', 'Дополнительный');
const bs_Status_Dog_Label :array[1..2] of String=('Статус договору', 'Статус договора');
{Contracts_Components_Grid_Captions}
const bs_Payer_Column :array[1..2] of String=('Платник', 'Плательщик');
const bs_Period_Column :array[1..2] of String=('Періодичність', 'Периодичность');
const bs_Persent_Column :array[1..2] of String=('Відсоток', 'Процент');
const bs_Date_Opl_Column :array[1..2] of String=('Дата оплати', 'Дата оплаты');
const bs_Summa_Column :array[1..2] of String=('Сума', 'Сумма');
const bs_Name_Column :array[1..2] of String=('Найменування', 'Наименование');
const bs_IS_Deleted_Column :array[1..2] of String=('Видалено', 'Удалено');
const bs_CntMonth_Column :array[1..2] of String=('Кількість місяців', 'Кол-во месяцев');
const bs_ParamStudyModify_Caption :array[1..2] of String=('Редагувати параметри навчання', 'Редактировать параметры обучения');
const bs_FIOModify_Caption :array[1..2] of String=('Редагувати особу, що навчається', 'Редактировать обучающегося');
const bs_add_new_summ :array[1..2] of String=('Додати нову ціну', 'Добавить новую цену');
const bs_add_new_summ_by_param :array[1..2] of String=('Додати нову ціну на підставі вибранних параметрів', 'Добавить новую цену на основе выбранных параметров');
{Smeta-Razdel-Statya-Kekv}
const bs_Smeta :array[1..2] of String=('Кошторис', 'Смета');
const bs_Razdel :array[1..2] of String=('Розділ', 'Раздел');
const bs_Statya :array[1..2] of String=('Стаття', 'Статья');
const bs_Kekv :array[1..2] of String=('КЕКВ', 'КЭКЗ');
{Contracts_Components_Filtration}
const bs_Filtration :array[1..2] of String=('Фільтрація', 'Фильтрация');
const bs_FiltrByFIO :array[1..2] of String=('П.І.Б.', 'Ф.И.О.');
const bs_FiltrByNum :array[1..2] of String=('Номер', 'Номер');
const bs_FiltrHint :array[1..2] of String=('Фільтровати негайно!', 'Фильтровать немедленно!');
const bs_FiltrBarCode :array[1..2] of string=('Штрих код','Штрих код');
{Contracts_Add_Edit_Messages}
const bs_Num_Dog_Need :array[1..2] of String=('Необхідно заповнити номер договору!','Необходимо заполнить номер договора!');
const bs_Date_Dog_Need :array[1..2] of String=('Необхідно заповнити дату укладання договору!','Необходимо заполнить дату заключения договора!');
const bs_summ_prices_Need :array[1..2] of string=('Необхідно ввести суму!','Необходимо ввести сумму!');
//--------------{Contracts_Payer_AE}-------------------------------------------------------------
const bs_FizOsoba :array[1..2] of String=('Фізична особа', 'Физическое лицо');
const bs_YurOsoba :array[1..2] of String=('Юридична особа','Юридическое лицо');
const bs_PayerType :array[1..2] of String=('Тип платника','Тип плательщика');
const bs_MFO_Caption :array[1..2] of String=('МФО','МФО');
const bs_RasSchet_Caption :array[1..2] of String=('Розрахунковий рахунок','Расчетный счет');
{Contracts_Payer_AE_Messages}
const bs_Payer_Need :array[1..2] of String=('Необхідно заповнити платника!','Необходимо заполнить плательщика!');
const bs_Percent_Need :array[1..2] of String=('Необхідно заповнити відсоток!','Необходимо заполнить процент!');
const bs_Period_Need :array[1..2] of String=('Необхідно заповнити періодичність!','Необходимо заполнить периодичность!');
//--------------{Contracts_Studer_AE}-------------------------------------------------------------
const bs_Studer :array[1..2] of String=('Особа, що навчається','Обучающийся');
const bs_Studer_Need :array[1..2] of String=('Необхідно заповнити особу, що навчається!','Необходимо заполнить обучающегося!');
//--------------{Contracts_Periods_AE}-------------------------------------------------------------
const bs_Periods_DateOpl :array[1..2] of String=('Дата оплати','Дата оплати');
{Contracts_Periods_AE_Messages}
const bs_Periods_Date_Beg_Need :array[1..2] of String=('Необхідно заповнити дату початку!','Необходимо заполнить дату начала!');
const bs_Periods_Date_End_Need :array[1..2] of String=('Необхідно заповнити дату закінчення!','Необходимо заполнить дату окончания!');
const bs_Periods_Date_Pay_Need :array[1..2] of String=('Необхідно заповнити дату оплати!','Необходимо заполнить дату оплаты!');
const bs_Periods_Date_PaySum_Need :array[1..2] of String=('Необхідно заповнити суму!','Необходимо заполнить сумму!');
//-----------------------------------------------------------------------------------------------
{Contracts_Istochniki_AE_Messages}
const bs_Smeta_Need :array[1..2] of String=('Необхідно заповнити кошторис!','Необходимо заполнить смету!');
const bs_Razdel_Need :array[1..2] of String=('Необхідно заповнити розділ!','Необходимо заполнить раздел!');
const bs_Stat_Need :array[1..2] of String=('Необхідно заповнити статтю!','Необходимо заполнить статью!');
const bs_Kekv_Need :array[1..2] of String=('Необхідно заповнити КЕКВ!','Необходимо заполнить КЭКЗ!');
{Contracts_StudyParams_Title}
const bs_StudyParams_Title :array[1..2] of String=(' параметри навчання',' параметры обучения');
const bs_CollectDog :array[1..2] of String=('КОЛЕКТИВНИЙ','КОЛЛЕКТИВНЫЙ');
const bs_EntryRest :array[1..2] of String=('Вхідний залишок','Входящий остаток');
const bs_EntryRestShort :array[1..2] of String=('Вх.залишок','Вх.остаток');
{Oplata_Analiz}
const bs_Beg_Opl :array[1..2] of String=('Початок періоду', 'Начало периода');
const bs_End_Opl :array[1..2] of String=('Закінчення періоду', 'Конец периода');
const bs_Summa_Opl :array[1..2] of String=('Вартість навчання, грн', 'Стоимость обучения, грн');
const bs_PercentLg_Opl :array[1..2] of String=('Відсоток пільги, %', 'Процент льготы, %');
const bs_SummaLg_Opl :array[1..2] of String=('Сума пільги, грн', 'Сумма льготы, грн');
const bs_MonthCount_Opl :array[1..2] of String=('Кіл-сть місяців', 'Кол-во месяцев');
const bs_SummFinal_Opl :array[1..2] of String=('Сума за період, грн', 'Сумма за период, грн');
const bs_NumDoc_Pay :array[1..2] of String=('Документ №', 'Документ №');
const bs_DateDoc_Pay :array[1..2] of String=('Дата докум.', 'Дата докум.');
const bs_Summa_Pay :array[1..2] of String=('Сума, грн.', 'Сумма, грн.');
const bs_Need_Pay :array[1..2] of String=('Треба сплатити:', 'Надо оплатить:');
const bs_Was_Pay :array[1..2] of String=('Вже сплачено:', 'Уже оплачено:');
const bs_PayPo_Pay :array[1..2] of String=('Сплачено по ', 'Оплачено по ');
const bs_Now_Pay :array[1..2] of String=('До сплати на сьогодні', 'К оплате на сегодня:');
const bs_Itogo_Pay :array[1..2] of String=('Разом', 'Итого');
const bs_Zadolg_Pay :array[1..2] of String=('Заборгованість:', 'Задолженность:');
const bs_Hint_Pay :array[1..2] of String=('Документи оплати не знайдено', 'Документы оплаты не найдены');
const bs_DateBirth :array[1..2] of String=('Дата народження: ', 'Дата рождения:');
const bs_DSetRecordCount :array[1..2] of String=('Кількість записів: ', 'Количество записей: ');
const bs_FullPay :array[1..2] of String=('Cплачено повністю','Оплачено польностью');
const bs_FullName :array[1..2] of String=('Повна назва', 'Полное название');
const bs_ShortName :array[1..2] of String=('Скорочена назва', 'Краткое название');
const bs_sp_ContractsList :array[1..2] of String=('Довідник осіб, що навчаються за контрактом', 'Справочник обучающихся по договорам');
const bs_OplataCaption :array[1..2] of String=('Оплата контракту','Оплата контракта');
const bs_ActionDates :array[1..2] of String=('Період дії','Период действия');
const bs_PayPeriod :array[1..2] of String=('Оплата за період','Оплата за период');
const bs_SumCheck :array[1..2] of String=('Із зазначенням суми','С указанием суммы');
const bs_NeedPay :array[1..2] of String=('Треба сплатити','Надо уплатить');
const bs_WhosPay :array[1..2] of String=('Вже сплачено','Уже уплачено');
const bs_Borg :array[1..2] of String=('Заборгованність','Задолженность');
const bs_EnterSum :array[1..2] of String=('Сума, що вноситься','Вносимая сумма');
const bs_Z :array[1..2] of String=('З','С');
const bs_Po :array[1..2] of String=('По','По');
const bs_View :array[1..2] of String=('Перегляд','Просмотр');
const bs_Pay :array[1..2] of String=('Оплата','Оплата');
const bs_Zaborgov :array[1..2] of String=('Заборгованність','Задолженность');
const bs_Pereplata :array[1..2] of String=('Переплата','Переплата');
const bs_Lgots_Sp :array[1..2] of String=('Пільги за договорами','Льготы по договорам');
const bs_NomPrikaz :array[1..2] of String=('Номер наказу','Номер приказа');
const bs_DatePrikaz :array[1..2] of String=('Дата наказу','Дата приказа');
const bs_Osnovanie :array[1..2] of String=('Підстава','Основание');
const bs_BegDate_Short :array[1..2] of String=('Дата поч.','Дата нач.');
const bs_EndDate_Short :array[1..2] of String=('Дата закін.','Дата оконч.');
const bs_RateAcc_Default :array[1..2] of String=('Довідник розрахункових рахунків','Справочник расчетных счетов');
const bs_RateAcc_Rate :array[1..2] of String=('Розрахунковий рахунок','Расчетный счет');
const bs_SearchCaption_Ex :array[1..2] of String=('Розширений фільтр','Расширенный фильтр');
const bs_Search_Ex :array[1..2] of String=('Шукати за','Искать по');
const bs_TIN_Ex :array[1..2] of String=('ідентифікаційним податковим номером','идентификационному налоговому номеру');
const bs_Need_TIN :array[1..2] of String=('Необхідно заповнити ідентифікаційний податковий номер!','Необходимо заполнить идентификационный налоговый номер!');
const bs_Payer_Ex :array[1..2] of String=('платником','плательщику');
const bs_Config :array[1..2] of String=('Конфігурація','Конфигурация');
const bs_Tunning :array[1..2] of String=('Настройка...','Настройка...');
const bs_Desctop :array[1..2] of String=('Робочий стіл','Рабочий стол');
const bs_StartMenu :array[1..2] of String=('Меню "Пуск"','Меню "Пуск"');
const bs_CreateIcons :array[1..2] of String=('Помістити іконку на ...','Поместить иконку на ...');
const bs_Icons :array[1..2] of String=('Іконки','Иконки');
const bs_WhatsNew :array[1..2] of String=('Контракти: історія версій','Контракты: история версий');
const bs_WhatsNew_Cap :array[1..2] of String=('Що нового?','Что нового?');
const bs_Exit :array[1..2] of String=('Вихід','Выход');
// DogDiss
const bs_InfoDiss :array[1..2] of String=('Інформація про розірвання','Информация про расторжение');
const bs_DateDiss :array[1..2] of String=('Дата розірвання','Дата расторжения');
const bs_DateOrderDiss :array[1..2] of String=('Дата наказу','Дата приказа');
const bs_NumOrderDiss :array[1..2] of String=('Номер наказу','Номер приказа');
const bs_CommentDiss :array[1..2] of String=('Коментарі','Комментарии');
const bs_TypeLg_Label :array[1..2] of String=('Тип пільги','Тип льготы');
const bs_TypeDiss :array[1..2] of String=('Причина(тип розірвання)','Причина(тип расторжения)');
const bs_sp_IniTypeDiss :array[1..2] of String=('Довідник типів розірвання контракту','Справочник типов расторжения контракта');
const bs_Confirm :array[1..2] of String=('Підтвердження','Подтверждения');
const bs_Interface :array[1..2] of String=('Інтерфейс','Интерфейс');
const bs_NoExitConfirm :array[1..2] of String=('Не підтверджувати вихід','Не подтверждать выход');
const bs_DateProv :array[1..2] of String=('Дата проводки','Дата проводки');
const bs_ProvNote :array[1..2] of String=('Підстава','Основание');
const bs_Pevdonim :array[1..2] of String=('Псевдонім','Псевдоним');
const bs_Kr :array[1..2] of String=('Кредит','Кредит');
const bs_Db :array[1..2] of String=('Дебет','Дебет');
const bs_DogNumProv :array[1..2] of String=('Договір №','Договор №');
const bs_Dodatki :array[1..2] of String=('Додаткові дії','Дополнительные действия');
const bs_Cookies :array[1..2] of String=('Заповнити автоматично(взяти з історії)','Заполнить автоматически(взять из истории)');
const bs_Language :array[1..2] of String=('Мова (потрібно перезавантаження програми)','Язык (необходима перезагрузка программы)');
const bs_Rus_Lang :array[1..2] of String=('Російська','Русский');
const bs_Ukr_Lang :array[1..2] of String=('Українська','Украинский');
const bs_LangReload :array[1..2] of String=('Необхідно перезавантаження програми','Чтобы изменения вступили в силу необходим перезапуск программы');
const bs_Baloon :array[1..2] of String=('Підказка','Подсказка');
const bs_Welcome :array[1..2] of String=('Система "Горводоканал" бажає Вам приємної роботи... ','Система "Горводоканал" желает Вам приятной работы...');
const bs_PreyskurantWork :array[1..2] of String=('Робота з прейскурантом','Работа с прейскурантом');
const bs_FizLizoEdit :array[1..2] of String=('Редагувати дані фіз.особи','Редактировать данные физ.лица');
// Tree
const bs_tree_FullOpen :array[1..2] of String=('Розкрити дерево цілком','Раскрыть дерево целиком');
const bs_tree_FullClose :array[1..2] of String=('Згорнути дерево цілком','Свернуть дерево целиком');
const bs_tree_BranchOpen :array[1..2] of String=('Розкрити гілку','Раскрыть ветвь');
const bs_tree_BranchClose :array[1..2] of String=('Згорнути гілку','Свернуть ветвь');
const bs_tree_FullScreen :array[1..2] of String=('Повний екран','Полный экран');
const bs_Preved :array[1..2] of String=('Не показувати вітання при завантаженні ','Не показывать приветствие при загрузке');
const bs_PrevedSelf :array[1..2] of String=('введіть сюди всій варіант привітання чи нагадування','введите сюда свой вариант приветствия или напоминания');
const bs_PrevedHint :array[1..2] of String=('для системної інформації залиште поле пустим','для системной информации оставьте поле пустым');
const bs_PayerSelect :array[1..2] of String=('Вибір платника за договором','Выбор плательщика по договору');
// preyskurant
const bs_ViewPrice_Hint :array[1..2] of String=('Показати актуальну версію','Показать актуальную версию');
const bs_grid_VerName :array[1..2] of String=('Назва версії прейскуранта','Название версии прейскуранта');
const bs_showVerssions :array[1..2] of String=('Показувати версії','Показывать версии');
const bs_AddVerssion :array[1..2] of String=('Додати версію','Добавить версию');
const bs_Preyskurant :array[1..2] of String=('Прейскурант...','Прейскурант...');
const bs_PreyskurantHint :array[1..2] of String=('Вибрати дані з прейскуранту','Выбрать данные из прейскуранта');
const bs_roles_Kod :array[1..2] of String=('Код','Код');
const bs_roles_Group :array[1..2] of String=('Групи користувачів','Группы пользователей');
const bs_roles_Smets :array[1..2] of String=('Кошториси','Сметы');
const bs_AcademYear :array[1..2] of String=('Академ. рік','Академ. год');
const bs_StudInfWarning :array[1..2] of String=('Інформація про осіб, що навчаються заповнена лише частково. Уважно перевірте дані!','Информация про обучающихся заполнена лишь частично. Внимательно проверьте данные!');
const bs_Service :array[1..2] of String=('Служби','Службы');
const bs_VC_Import :array[1..2] of String=('Імпорт контрактів','Импорт контрактов');
const bs_VC_ClearBuffer :array[1..2] of String=('Очистити буфер','Очистить буфер');
const bs_VC_AllBuffer :array[1..2] of String=('Буфер цілком','Буфер целиком');
const bs_VC_BufferCaption :array[1..2] of String=('DBF-буфер','DBF-буфер');
const bs_VCBuffer_or_Not :array[1..2] of String=('Додати з буферу чи вручну?','Добавить из буфера или вручную?');
const bs_Log :array[1..2] of String=('Лог-історія роботи з контрактом','Лог-история работы с контрактом');
const bs_User :array[1..2] of String=('Користувач','Пользователь');
const bs_Action :array[1..2] of String=('Дія','Действие');
const bs_Stamp :array[1..2] of String=('Дата\Час','Дата\Время');
const bs_Use_Beg :array[1..2] of String=('Нач. дії','Нач. действ.');
const bs_Use_End :array[1..2] of String=('Кінець дії','Оконч. действ.');
const bs_RaxynokNaSplaty :array[1..2] of String=('Рахунок на сплату договору №','Счет на оплату обучения №');
const bs_SymaPaxynky :array[1..2] of String=('Сума рахунку','Сумма счета');
const bs_NDS :array[1..2] of String=('ПДВ','НДС');
const bs_PazomZNDS :array[1..2] of String=('Разом з ПДВ','Итого с НДС');
const bs_RaxynokNaSplatyCaption :array[1..2] of String=('Виписка рахунку на сплату навчання','Выписка счета на оплату обучения');
const bs_Vid :array[1..2] of String=('від','от');
const bs_SysOptions :array[1..2] of String=('Системні параметри','Системные параметры');
const bs_Signature :array[1..2] of String=('Підпис','Подпись');
const bs_Signature_off :array[1..2] of String=('Зняти підпис','Снять подпись');
const bs_Signature_on :array[1..2] of String=('Поставити підпис','Поставить подпись');
const bs_TransferToNextCurs :array[1..2] of String=('Переведення на наст. курс','Перевод на след. курс');
const bs_ForEach :array[1..2] of String=('Підтвердження для кожного студенту','Подтверждение для каждого студента');
const bs_AvtoRastorg :array[1..2] of String=('Автоматично розривати контракти','Автоматически расторгать контракты');
const bs_ParamsOtbor :array[1..2] of String=('Установка параметрів відбору','Установка параметров отбора');
const bs_Params :array[1..2] of String=('Параметри','Параметры');
const bs_CurrentTaskPercent :array[1..2] of String=('Відсоток виконання','Процент выполнения');
const bs_Admit :array[1..2] of String=('Пропустити','Пропустить');
const bs_Admit_All :array[1..2] of String=('Пропустити усі','Пропустить все');
const bs_NewPeriod :array[1..2] of String=('Новий період навчання','Новый период обучения');
const bs_Role :array[1..2] of String=('Група','Группа');
const bs_AllForAdmin :array[1..2] of String=('Адміну доступно усе!','Админу доступнно всё!');
const bs_DotypSmetiTitle :array[1..2] of String=('Доступні кошториси','Доступные сметы');
const bs_NextCursAvto :array[1..2] of String=('Додати наступний курс автоматично','Добавить следующий курс автоматично');
const bs_RahunokWork :array[1..2] of String=('Робота з рахунками','Работа со счетами');
const bs_Relation :array[1..2] of String=('Зв''язок','Связь');
const bs_RelDepartment :array[1..2] of String=('Зв''язок з підрозділом','Связь с подразделением');
const bs_NoRelDepartment :array[1..2] of String=('Зв''язку з підрозділом не знайдено','Связь с подразделением не определена');
const bs_DepGrName :array[1..2] of String=('Група у підрозділі','Группа в подразделении');
const bs_NameExec :array[1..2] of String=('Посада відповідального','Должность ответственного');
const bs_Dekan :array[1..2] of String=('ПІБ відповідального','ФИО ответственного');
const bs_SearchAll :array[1..2] of String=('Усі','Все');
const bs_Write :array[1..2] of String=('Запис','Запись');
const bs_Sort :array[1..2] of String=('Сортування','Сортировка');
const bs_Success :array[1..2] of String=('Успішно!','Успешно!');
const bs_WasFullWork :array[1..2] of String=('Оброблено усього: ','Обработано всего: ');
const bs_WasBreak :array[1..2] of String=('Розірвано: ','Расторгнуто: ');
const bs_WasTransfer :array[1..2] of String=('Переведено на наступний курс: ','Переведено на следующий курс: ');
const bs_WasAdmit :array[1..2] of String=('Пропущено: ','Пропущено: ');
const bs_Add_List :array[1..2] of String=('Додати зписок','Добавить список');
const bs_Status :array[1..2] of String=('Статус','Статус');
const bs_Type :array[1..2] of String=('Тип','Тип');
const bs_DateCalc :array[1..2] of String=('Дата розрахунку','Дата расчета');
const bs_RaportAvto :array[1..2] of String=('Додати автоматично на дату розрахунку','Добавить автоматически на дату расчета');
const bs_RaportAvtoComments :array[1..2] of String=('Автоматичне додавання усіх контрактів, які мають заборгованність на дату розрахунку ','Автоматическое добавление всех контрактов, которые имеют задолженность на дату расчета');
const bs_Lgota :array[1..2] of String=('Пільга:','Льгота:');
const bs_OnovnieTypeDoc :array[1..2] of String=('Основні','Основные');
const bs_DodatkovTypeDoc :array[1..2] of String=('Додаткові','Дополнительные');
const bs_Recovery :array[1..2] of String=('Відновлення','Восстановление');
const bs_grid_Actual :array[1..2] of String=('Актуальність','Актуальность');
const bs_price_already_signed :array[1..2] of String=('Підписаний','Подписаный');
const fr_Reports_CALC_NameREP0 :array[1..2] of String=('Розрахунок на','Расчет на');
const fr_Reports_CALC_NameREP :array[1..2] of String=('Довідка №','Справка №');
const fr_Reports_CALC_NameREP1 :array[1..2] of String=('про стан виконання договору за навчання','о состоянии выполнения договора за обучение');
const fr_Reports_CALC_NameREP2 :array[1..2] of String=('Договір №','Договор №');
const fr_Reports_CALC_NameStuder :array[1..2] of String=('Особа, що навчається','Обучаемый');
const fr_Reports_CALC_Beg :array[1..2] of String=('Початок періоду','Начало периода');
const fr_Reports_CALC_End :array[1..2] of String=('Кінець періоду','Конец периода');
const fr_Reports_CALC_Stoimost :array[1..2] of String=('Вартість навч., грн','Стоимость обуч., грн');
const fr_Reports_CALC_SummaLg :array[1..2] of String=('Сумова пільга, грн','Суммовая льгота, грн');
const fr_Reports_CALC_PersentLg :array[1..2] of String=('Відсоток пільги, %','Процент льготы, %');
const fr_Reports_CALC_DolgBeg :array[1..2] of String=('Борг на початок, грн','Долг на начало, грн');
const fr_Reports_CALC_AllPeriod :array[1..2] of String=('Сума за період, грн','Сумма за период, грн');
const fr_Reports_CALC_SumPay :array[1..2] of String=('Сума, що надійшла, грн','Поступившая сумма, грн');
const fr_Reports_CALC_DolgEnd :array[1..2] of String=('Борг на кінець, грн','Долг на конец, грн');
const fr_Reports_CALC_SumDolg :array[1..2] of String=('Сума до сплати, грн','Сумма к оплате, грн');
const fr_Reports_CALC_WhasPay :array[1..2] of String=('Вже сплачено, грн','Уже уплачено, грн');
const fr_Reports_CALC_All :array[1..2] of String=('Разом:','Итого:');
const fr_Reports_CALC_PayConf :array[1..2] of String=('Сплачено','Оплачено');
const fr_Reports_CALC_PayConf1 :array[1..2] of String=('повністю','полностью');
const fr_Reports_SUMMA_K_OPLATE :array[1..2] of String=('Сума оплати','Сумма к оплате');
const fr_Reports_UGE_OPLACHENO :array[1..2] of String=('Вже сплачено','Уже оплачено');
const fr_Reports_SUMMA_DOLGA :array[1..2] of String=('Сума боргу','Сумма долга');
const fr_Reports_CALC_KydaVidana :array[1..2] of String=('Довідка видана для пред''''явлення за місцем вимоги','Справка выдана для предъявления по месту требования.');
const fr_Reports_CALC_Buhg :array[1..2] of String=('Бухгалтер','Бухгалтер');
const fr_Reports_PrintSpravkaCalc :array[1..2] of String=('Друк довідки','Печать справки');
const fr_Reports_PayDocs :array[1..2] of String=('Документи у рахунок оплати договору','Документы в счет оплаты договора');
const fr_Reports_CalcDocs :array[1..2] of String=('Про стан виконання договору','О состоянии выполнения договора');
const fr_Stud :array[1..2] of String=('Реєстр/Зведена форма осіб, що навч. за контрактами','Реестр/Сводная форма договорников');
const fr_Pay :array[1..2] of String=('Реєстр/Зведена форма боржників за навчання','Реестр/Сводная форма должников за обучение');
const fr_Zvit :array[1..2] of String=('Звітні форми','Отчетные формы');
const frSplataIstochnikiBtn :array[1..2] of String=('Аналіз сплати за навч. за джерелами фінанс.',
'Анализ оплаты за обуч. по источникам финанс.');
const frPercentValueBtn :array[1..2] of String=('Відсоткове виконання договорів за навчання',
'Процентное выполнение договоров за обучение');
const frLgotaAnalisBtn :array[1..2] of String=('Аналіз надання пільг за сплату за навчання',
'Анализ выдачи льгот по оплате за обучение');
const frReestrSvodPoOplate :array[1..2] of String=('Реєстр/Аналіт. звіт по сплаті за навчання','Реестр\Аналитич. сводная по оплате за обучение');
const frSvodNepostupSummBtn :array[1..2] of String=('Реєстр/Зведена форма сум,що не надійшли','Реестр\Сводная форма недопоступивших сумм');
const frSvodPoOtchislenim :array[1..2] of String=('Зведена форма по відрахованим','Сводная форма по отчисленным');
const bs_Execution :array[1..2] of String=('Виконати','Выполнить');
const frVikonannya_Btn :array[1..2] of String=('Аналітичний звіт, виконання договорів за навчання',
'Аналитический свод, выполнение договоров по обучению');
const bs_Orders :array[1..2] of String=('Накази','Приказы');
const bs_OrderType :array[1..2] of String=('Тип наказу','Тип приказа');
const bs_NumOrd :array[1..2] of String=('Номер','Номер');
const bs_DateOrd :array[1..2] of String=('Дата','Дата');
const bs_Zvit :array[1..2] of String=('Звіт','Отчет');
const bs_TagOrder :array[1..2] of String=('Пріоритет','Приоритет');
const bs_IsVisibleReestr :array[1..2] of String=('Видимий у реєстрі','Видимый в реестре');
const bs_IsVisibleOplata :array[1..2] of String=('Видимий у сплаті','Видимый в оплате');
const bs_IsVisibleReestrShort :array[1..2] of String=('У реєстрі','В реестре');
const bs_IsVisibleOplataShort :array[1..2] of String=('У сплаті','В оплате');
const bs_BasicContract :array[1..2] of String=('Основний','Основной');
const bs_ContractPrint :array[1..2] of String=('Друк контракту','Печать контракта');
const bs_Day :array[1..2] of String=('День','День');
const bs_Month :array[1..2] of String=('Місяць','Месяц');
const bs_Full_Name :array[1..2] of String=('Повне найменування','Полное наименование');
const bs_CopyPrintCount :array[1..2] of String=('Кіль-сть копій для друку','Кол-во копий для печати');
const bs_LowSpecimen :array[1..2] of String=('Законий представник студента','Законный представитель студента');
const bs_OsosbaCustomer :array[1..2] of String=('Особа, яка уклала контракт','Лицо, заключившее контракт');
const bs_DeletedShow :array[1..2] of String=('Видалені контракти','Удаленные контракты');
const bs_DeletedMode :array[1..2] of String=('Режим перегляду видалених контрактів','Режим просмотра удаленных контрактов');
const bs_ExportData :array[1..2] of String=('Експорт даних контракту','Экспорт данных контракта');
const bs_KillAll :array[1..2] of String=('Видалити усі','Удалить все');
const bs_KillOnlyOne :array[1..2] of String=('Видалити за фільтром','Удалить по фильтру');
const bs_TwainShort :array[1..2] of String=('Скан','Скан');
const bs_Twain :array[1..2] of String=('Сканування','Сканування');
const bs_CreditNote :array[1..2] of String=('Заголовок звіту','Заголовок отчета');
const bs_CreditBank :array[1..2] of String=('Керуючий банком','Управляющий банком');
const bs_LimitSum :array[1..2] of String=('Межа суми кредиту','Предел суммы кредита');
const bs_LimitDogs :array[1..2] of String=('Межа к-сті контрактів','Предел кол-ва контрактов');
const bs_CreditImage :array[1..2] of String=('Тільки з образами','Только с образами');
const bs_Reestr :array[1..2] of String=('Реєстр','Реестр');
const bs_Image :array[1..2] of String=('Образи','Образы');
const bs_DogSum :array[1..2] of String=('Сума договору','Сумма договора');
const bs_PrintRangeImage :array[1..2] of String=('Друк діапазону образів...','Печать диапазона образов...');
const bs_Main_SpCreditStatus :array[1..2] of String=('Довідник статусів кредиту','Справочник статусов кредита');
const bs_PrintAllPages :array[1..2] of String=('Усі сторінки','Все страницы');
const bs_PrintChetPages :array[1..2] of String=('Парні сторінки','Четные страницы');
const bs_PrintNeChetPages :array[1..2] of String=('Непарні сторінки','Нечетные страницы');
const bs_btnSeparate :array[1..2] of String=('Роз''єднання','Разделение');
const bs_btnUnion :array[1..2] of String=('Об''єднання','Объединение');
const bs_CopyPrice :array[1..2] of String=('Копіювати','Копировать');
const bs_Fam :array[1..2] of String=('Прізвище','Фамилия');
const bs_Name :array[1..2] of String=('Ім''я','Имя');
const bs_otch :array[1..2] of String=('По батькові','Отчество');
{
const bs_ :array[1..2] of String=('','');
const bs_ :array[1..2] of String=('','');
const bs_ :array[1..2] of String=('','');
const bs_ :array[1..2] of String=('','');
}
//-----------------------------REG----------------------------------------------
const bs_Can_not_delete :array[1..2] of String=('Реєстр підписаний і не може бути видалений!','Реестр подписан и не может быть удален!');
//-----------------------------Message------------------------------------------
const bs_msg_WARNING :array[1..2] of String=('Попередження','Предупреждение');
const bs_msg_INFO :array[1..2] of String=('Інформація','Информация');
const bs_sp_input : array[1..2] of String=('Довідник вводів','Справочник вводов');
const bs_sp_hydrometer : array[1..2] of String=('Довідник водомірів','Справочник водомеров');
const bs_short_cut : array[1..2] of String=('Гарячі клавіші','Горячие клавиши');
//----------------------Справочник типов водомеров
const bs_sp_hydrometer_type :array[1..2] of String=('Довідник типів водомірів','Справочник типов водомеров');
const bs_name_hydrometer_type :array[1..2] of String=('Назва типу водоміра','Название типа водомера');
const bs_caliber_hydrometer :array[1..2] of String=('Калібр водоміра','Калибр водомера');
const bs_id_unit_meas :array[1..2] of String=('Одиниці виміру калібра водоміра','Единицы измерения калибра водомера');
const bs_capacity_hydrometer :array[1..2] of String=('Розрядність водоміра','Разрядность водомера');
const bs_accuracy_hydrometer :array[1..2] of String=('Точність водоміра','Точность водомера');
const bs_note_hydrometer :array[1..2] of String=('Примітка','Примечание');
const bs_factory_hydrometer :array[1..2] of String=('Виробник водоміра','Производитель водомера');
//----------------------Справочник видов водомеров
const bs_sp_hydrometer_vid :array[1..2] of String=('Довідник видів водомірів','Справочник видов водомеров');
const bs_name_hydrometer_vid :array[1..2] of String=('Назва виду водоміра','Название вида водомера');
//----------------------Справочник типов документов
const bs_sp_document_type :array[1..2] of String=('Довідник типів документів','Справочник типов документов');
const bs_name_document_type :array[1..2] of String=('Назва типу документу','Название типа документа');
//------------Цвета---
const BsClFieldIsEmpty = $00DDBBFF;
implementation
end.
|
namespace BasicWindowsApp;
uses
rtl;
type
Program = class
public
class var szTitle: LPCWSTR := 'RemObjects Elements — Island Windows Sample';
class var szWindowClass: LPCWSTR := 'IslandWindowsSample';
class var fButton: HWND;
[CallingConvention(CallingConvention.Stdcall)]
class method WndProc(hWnd: HWND; message: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT;
begin
case message of
WM_COMMAND:
if (wParam = BN_CLICKED) and (lParam = rtl.LPARAM(fButton)) then begin
MessageBox(hWnd, 'You clicked, hello there!', szTitle, 0);
end;
WM_CLOSE:
PostQuitMessage(0);
end;
result := DefWindowProc(hWnd, message, wParam, lParam);
end;
class method Main(args: array of String): Int32;
begin
//
// Set up and Register the Windows Class
//
var lWindowClass: WNDCLASSEX;
lWindowClass.cbSize := sizeOf(WNDCLASSEX);
lWindowClass.style := CS_HREDRAW or CS_VREDRAW;
lWindowClass.lpfnWndProc := @WndProc;
lWindowClass.cbClsExtra := 0;
lWindowClass.cbWndExtra := 0;
lWindowClass.hInstance := rtl.GetModuleHandleW(nil);
lWindowClass.hIcon := LoadIcon(lWindowClass.hInstance, LPCWSTR(IDI_APPLICATION));
lWindowClass.hCursor := LoadCursor(nil, LPCWSTR(IDC_ARROW));
lWindowClass.hbrBackground := HBRUSH(COLOR_WINDOW + 1);
lWindowClass.lpszMenuName := nil;
lWindowClass.lpszClassName := szWindowClass;
if RegisterClassEx(@lWindowClass) = 0 then begin
MessageBox(nil, 'Call to RegisterClassEx failed', szTitle, 0);
exit 0;
end;
//
// Create the Window
//
var lWindow := CreateWindowExW(0,
szWindowClass,
szTitle,
WS_OVERLAPPED or WS_CAPTION or WS_SYSMENU,
CW_USEDEFAULT,
CW_USEDEFAULT,
400, 300,
nil,
nil,
lWindowClass.hInstance,
nil);
if lWindow = nil then begin
MessageBox(nil, 'Call to CreateWindowExW failed', szTitle, 0);
exit 0;
end;
//
// Add a button to it
//
fButton := CreateWindowEx(0,
'BUTTON', // Predefined class; Unicode assumed
'Click Me', // Button text
WS_TABSTOP or WS_VISIBLE or WS_CHILD or BS_DEFPUSHBUTTON, // Styles
130, // x position
70, // y position
100, // Button width
25, // Button height
lWindow, // Parent window
nil, // No menu.
lWindowClass.hInstance,
nil); // Pointer not needed.
//
// Show the Window
//
ShowWindow(lWindow, SW_SHOW);
UpdateWindow(lWindow);
//
// Finally, run the main Windows message loop
//
var lMsg: MSG;
while GetMessage(@lMsg, nil, 0, 0) do begin
TranslateMessage(@lMsg);
DispatchMessage(@lMsg);
end;
result := Integer(lMsg.wParam);
end;
end;
end. |
//Version 26/01/04
unit ContPlug;
interface
uses Windows;
const
FT_NOMOREFIELDS = 0;
FT_NUMERIC_32 = 1;
FT_NUMERIC_64 = 2;
FT_NUMERIC_FLOATING = 3;
FT_DATE = 4;
FT_TIME = 5;
FT_BOOLEAN = 6;
FT_MULTIPLECHOICE = 7;
FT_STRING = 8;
FT_FULLTEXT = 9;
ft_datetime = 10;
// for ContentGetValue
FT_NOSUCHFIELD = -1;
FT_FILEERROR = -2;
FT_FIELDEMPTY = -3;
ft_ondemand=-4;
FT_DELAYED = 0;
CONTENT_DELAYIFSLOW = 1; // ContentGetValue called in foreground
type
tContentDefaultParamStruct = record
size,
PluginInterfaceVersionLow,
PluginInterfaceVersionHi: longint;
DefaultIniName: array[0..MAX_PATH-1] of char;
end;
pContentDefaultParamStruct = ^tContentDefaultParamStruct;
tdateformat = record
wYear, wMonth, wDay: word;
end;
pdateformat = ^tdateformat;
ttimeformat = record
wHour, wMinute, wSecond: word;
end;
ptimeformat = ^ttimeformat;
implementation
{
procedure ContentGetDetectString(DetectString: pchar;maxlen: integer); stdcall;
function ContentGetSupportedField(FieldIndex: integer;FieldName: pchar;
Units: pchar;maxlen: integer): integer; stdcall;
function ContentGetValue(FileName: pchar;FieldIndex, UnitIndex: integer;
FieldValue: pointer;
maxlen, flags: integer): integer; stdcall;
procedure ContentSetDefaultParams(dps: pContentDefaultParamStruct); stdcall;
}
end.
|
unit AyahComposer;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, CheckLst, AmlView, HtmlView, QuranStruct, StStrS, ClipBrd,
StStrL, XmlObjModel, IslUtils, TextView;
type
TAyahCompositionAction = (acaNone, acaCopy, acaPrint);
TAyahSelectionForm = class(TForm)
TextsGroupBox: TGroupBox;
BooksList: TCheckListBox;
AyahsGroupBox: TGroupBox;
AyahChooseLabel: TLabel;
AyahsEdit: TEdit;
OK: TButton;
Cancel: TButton;
ExampleLabel: TLabel;
Label2: TLabel;
InclNotesCheck: TCheckBox;
AyahSepCheck: TCheckBox;
HTMLViewer: THTMLViewer;
FontDialog: TFontDialog;
ChooseFontBtn: TButton;
procedure OKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure HTMLViewerPrintHeader(Sender: TObject; Canvas: TCanvas;
NumPage, W, H: Integer; var StopPrinting: Boolean);
procedure ChooseFontBtnClick(Sender: TObject);
protected
FDataMgr : TDataManager;
FAction : TAyahCompositionAction;
FQuranStruct : TQuranStructure;
FAyahsMarked : TMarkedAyahs;
FPrintHeader : TPrintHeaderInfo;
function GetAsText : String;
function GetAsHtml : String;
function GetAyahs : String; virtual;
procedure SetAction(const AAction : TAyahCompositionAction);
procedure SetAyahs(const AAyahs : String); virtual;
procedure SetBookId(const ABookId : String); virtual;
procedure SetDataManager(const ADataMgr : TDataManager); virtual;
procedure SetQuranStruct(const AStruct : TQuranStructure); virtual;
public
property DataMgr : TDataManager read FDataMgr write SetDataManager;
property BookId : String write SetBookId;
property QuranStruct : TQuranStructure read FQuranStruct write SetQuranStruct;
property Ayahs : String read GetAyahs write SetAyahs;
property Action : TAyahCompositionAction read FAction write SetAction;
property AyahsMarked : TMarkedAyahs read FAyahsMarked write FAyahsMarked;
property AsText : String read GetAsText;
property AsHtml : String read GetAsHtml;
end;
var
AyahSelectionForm : TAyahSelectionForm;
implementation
uses QuranView, StBits;
{$R *.DFM}
function TAyahSelectionForm.GetAsText : String;
const
CRLF = #13#10;
var
I, J, TotalChecked : Integer;
SingleChecked : Boolean;
Marked : TStBits;
S : TSuraNum;
A : TAyahNum;
Bit : LongInt;
QuranData : TQuranData;
Notes : TXmlNodeList;
AyahElem, NoteElem : TXmlElement;
AyahText : String;
begin
Result := '';
TotalChecked := 0;
for I := 0 to BooksList.Items.Count-1 do
if BooksList.Checked[I] then
Inc(TotalChecked);
if TotalChecked = 0 then
Exit;
SingleChecked := TotalChecked = 1;
for S := Low(TSuraNum) to High(TSuraNum) do begin
Marked := FAyahsMarked.Suras[S];
if Marked.Count > 0 then begin
Result := Result + Format('%0:sSura %1:s (%2:d)%0:s%3:s%0:s', [CRLF, FAyahsMarked.QuranStruct.SuraName[S], S, PadChS('', '-', 79)]);
Bit := Marked.FirstSet;
while Bit <> -1 do begin
A := Bit+1;
if not SingleChecked then
Result := Result + Format('%s[Ayah %d]%s', [CRLF, A, CRLF]);
for I := 0 to BooksList.Items.Count-1 do begin
if not BooksList.Checked[I] then
continue;
QuranData := TQuranData(BooksList.Items.Objects[I]);
try
AyahElem := QuranData.ReadAyah(S, A);
AyahText := GetElementText(AyahElem, True);
except
AyahText := Format('Unable to read Sura %s Ayah %d from %s', [S, A, QuranData.Name]);
end;
if SingleChecked then
Result := Result + Format('%d. %s%s', [A, AyahText, CRLF])
else
Result := Result + Format('(%s) %s%s', [QuranData.ShortName, AyahText, CRLF]);
if InclNotesCheck.Checked then begin
Notes := AyahElem.GetChildElementsByTagName('note');
if Notes.Length > 0 then begin
for J := 0 to Notes.Length-1 do begin
NoteElem := Notes.Item(J) as TXmlElement;
Result := Result + Format('* note %s: %s%s', [GetElemAttr(NoteElem, 'id', '??'), GetElementText(NoteElem, True), CRLF]);
end;
end;
Notes.Free;
end;
end;
Bit := Marked.NextSet(Bit);
end;
end;
end;
end;
function TAyahSelectionForm.GetAsHtml : String;
var
AC, I, J, TotalChecked : Integer;
SingleChecked : Boolean;
Marked : TStBits;
S : TSuraNum;
A : TAyahNum;
Bit : LongInt;
QuranData : TQuranData;
Notes : TXmlNodeList;
AyahElem, NoteElem : TXmlElement;
AyahChild : TXmlNode;
AyahText, AyahAlign, FontSize, AyahSep : String;
AyahFont : TAmlDataFont;
SingleCheckedBook : TAmlData;
begin
Result := '';
TotalChecked := 0;
for I := 0 to BooksList.Items.Count-1 do
if BooksList.Checked[I] then begin
Inc(TotalChecked);
SingleCheckedBook := TAmlData(BooksList.Items.Objects[I]);
end;
if TotalChecked = 0 then
Exit;
SingleChecked := TotalChecked = 1;
FillChar(FPrintHeader, SizeOf(FPrintHeader), 0);
FPrintHeader.AppTitle := PrintHeaderAppName;
if SingleChecked then
FPrintHeader.BookName := SingleCheckedBook.Name
else
FPrintHeader.BookName := 'Quran Comparison';
if AyahSepCheck.Checked then
AyahSep := '<hr size=1 width=100% color=silver noshade>'
else
AyahSep := '';
for S := Low(TSuraNum) to High(TSuraNum) do begin
Marked := FAyahsMarked.Suras[S];
if Marked.Count > 0 then begin
Result := Result + Format('<h2>Sura %s (%d)</h2><hr size=1 width=100%% color=silver noshade>', [FAyahsMarked.QuranStruct.SuraName[S], S]);
Result := Result + '<table>';
Bit := Marked.FirstSet;
while Bit <> -1 do begin
A := Bit+1;
if not SingleChecked then
Result := Result + Format('<tr><td colspan=2><font size=+1><b>Ayah %d</b></font></td></tr>', [A]);
for I := 0 to BooksList.Items.Count-1 do begin
if not BooksList.Checked[I] then
continue;
QuranData := TQuranData(BooksList.Items.Objects[I]);
AyahFont := QuranData.GetFont('ayah');
try
AyahElem := QuranData.ReadAyah(S, A);
AyahText := '';
for AC := 0 to AyahElem.ChildNodes.Length-1 do begin
AyahChild := AyahElem.ChildNodes.Item(AC);
if AyahChild.NodeName = '' then
AyahText := AyahText + AyahChild.NodeValue
else if AyahChild.NodeName = 'fn' then
AyahText := AyahText + Format(' <sup>%s</sup> ', [(AyahChild as TXmlElement).Text]);
end;
except
AyahText := Format('Unable to read Sura %d Ayah %d from %s', [S, A, QuranData.Name]);
end;
Result := Result + '<tr valign=top>';
if QuranData.FlagIsSet(qdfIsArabic) then begin
AyahAlign := 'align=right';
FontSize := 'face="' + AyahFont.Name + '" size=5';
AyahText := Reverse(AyahText);
end else begin
AyahAlign := '';
FontSize := '';
end;
if SingleChecked then
Result := Result + Format('<td align=right>%d.</td><td %s><font %s>%s</font>', [A, AyahAlign, FontSize, AyahText])
else
Result := Result + Format('<td align=right>%s</td><td %s><font %s>%s</font>', [QuranData.ShortName, AyahAlign, FontSize, AyahText]);
if InclNotesCheck.Checked then begin
Notes := AyahElem.GetChildElementsByTagName('note');
if Notes.Length > 0 then begin
for J := 0 to Notes.Length-1 do begin
NoteElem := Notes.Item(J) as TXmlElement;
Result := Result + Format('<br><u>Note %s</u>: %s', [GetElemAttr(NoteElem, 'id', '??'), GetElementText(NoteElem, False)]);
end;
end;
Notes.Free;
end;
Result := Result + AyahSep + '</td></tr>';
end;
Bit := Marked.NextSet(Bit);
end;
Result := Result + '</table>';
end;
end;
end;
function TAyahSelectionForm.GetAyahs : String;
begin
Result := AyahsEdit.Text;
end;
procedure TAyahSelectionForm.SetAction(const AAction : TAyahCompositionAction);
begin
FAction := AAction;
AyahSepCheck.Enabled := FAction = acaPrint;
ChooseFontBtn.Enabled := FAction = acaPrint;
end;
procedure TAyahSelectionForm.SetAyahs(const AAyahs : String);
begin
AyahsEdit.Text := AAyahs;
end;
procedure TAyahSelectionForm.SetBookId(const ABookId : String);
var
I : Integer;
begin
if BooksList.Items.Count > 0 then begin
for I := 0 to BooksList.Items.Count-1 do
BooksList.Checked[I] := CompareText(ABookId, TAmlData(BooksList.Items.Objects[I]).Id) = 0;
end;
end;
procedure TAyahSelectionForm.SetDataManager(const ADataMgr : TDataManager);
function Include(const AData : TAmlData) : Boolean;
begin
Result :=
(FAction = acaNone) or
((FAction = acaCopy) and AData.FlagIsSet(adfCanCopyText)) or
((FAction = acaPrint) and AData.FlagIsSet(adfCanPrintText));
end;
var
QuranList : TDataList;
I, NewItem : Integer;
AmlData : TAmlData;
begin
FDataMgr := ADataMgr;
BooksList.Clear;
QuranList := FDataMgr.DataTypes['quran_text'];
if (QuranList <> Nil) and (QuranList.Count > 0) then begin
// first add all the non-Arabic texts in sorted order
BooksList.Sorted := True;
for I := 0 to QuranList.Count-1 do begin
AmlData := QuranList.Data[I] as TAmlData;
if AmlData.FlagIsSet(qdfIsArabic) then
continue;
if Include(AmlData) then begin
NewItem := BooksList.Items.AddObject(AmlData.Name, AmlData);
BooksList.Checked[NewItem] := AmlData.FlagIsSet(qdfMarkedForCopyPrint);
end;
end;
// now add the Arabic texts at the top of the list
BooksList.Sorted := False;
for I := 0 to QuranList.Count-1 do begin
AmlData := QuranList.Data[I] as TAmlData;
if not AmlData.FlagIsSet(qdfIsArabic) then
continue;
if Include(AmlData) then begin
BooksList.Items.InsertObject(0, AmlData.Name, AmlData);
BooksList.Checked[0] := AmlData.FlagIsSet(qdfMarkedForCopyPrint);
end;
end;
end;
end;
procedure TAyahSelectionForm.SetQuranStruct(const AStruct : TQuranStructure);
begin
FAyahsMarked.QuranStruct := AStruct;
end;
procedure TAyahSelectionForm.OKClick(Sender: TObject);
var
Html : String;
begin
FAyahsMarked.Clear;
if not FAyahsMarked.Mark(Ayahs) then
Exit;
case FAction of
acaNone : ;
acaCopy : Clipboard.AsText := Self.AsText;
acaPrint :
begin
Html := Self.AsHtml;
if Html <> '' then begin
HtmlViewer.DefFontName := FontDialog.Font.Name;
HtmlViewer.DefFontSize := FontDialog.Font.Size;
HtmlViewer.LoadFromBuffer(PChar(Html), Length(Html));
HtmlViewer.Print(1, 9999);
end;
end;
end;
ModalResult := mrOk;
end;
procedure TAyahSelectionForm.FormCreate(Sender: TObject);
begin
FAyahsMarked := TMarkedAyahs.Create;
end;
procedure TAyahSelectionForm.FormDestroy(Sender: TObject);
begin
FAyahsMarked.Free;
end;
procedure TAyahSelectionForm.HTMLViewerPrintHeader(Sender: TObject;
Canvas: TCanvas; NumPage, W, H: Integer; var StopPrinting: Boolean);
begin
PrintStandardHeader(FPrintHeader, Canvas, NumPage, W, H);
end;
procedure TAyahSelectionForm.ChooseFontBtnClick(Sender: TObject);
begin
FontDialog.Execute;
end;
end.
|
unit EstoqueFactory.Controller.interf;
interface
uses Produto.Controller.interf, ImportarProduto.Controller.interf,
Orcamento.Controller.interf, ExportarOrcamento.Controller.interf;
type
IEstoqueFactoryController = interface
['{AE45AEAB-9998-4AC7-BA48-BCBB727F0903}']
function Produto: IProdutoController;
function ImportarProduto: IImportarProdutoController;
function Orcamento: IOrcamentoController;
function exportarOrcamento: IExportarOrcamento;
end;
implementation
end.
|
unit uColorUtils;
interface
uses
Generics.Collections,
System.Math,
System.SysUtils,
System.Classes,
Winapi.Windows,
Vcl.Graphics,
Dmitry.Graphics.Types,
uMemory,
uStringUtils;
type
THLS = record
H: Byte;
L: Byte;
S: byte;
end;
TColorRange = record
HMin, HMax: Byte;
LMin, LMax: Byte;
SMin, SMax: Byte;
end;
const
ColorCount = 15;
cBlackWhiteIndex = 13;
cColoredIndex = 14;
clBlackWhite = $01000000;
clColored = $02000000;
type
TPaletteArray = array[0..ColorCount - 1] of TColor;
TPaletteHLSArray = array[0..ColorCount - 1] of TColorRange;
const
PaletteColorNames: array[0..ColorCount - 1] of string = ('Red', 'Red', 'Orange', 'Yellow', 'Green', 'Teal', 'Blue', 'Purple', 'Pink', 'White', 'Gray', 'Black', 'Brown', 'Black and white', 'Colored');
procedure FindPaletteColorsOnImage(B: TBitmap; Colors: TList<TColor>; MaxColors: Integer);
function ColorPaletteToString(Color: TColor): string;
function ColorsToString(Colors: TArray<TColor>): string;
procedure FillColors(var Palette: TPaletteArray; var PaletteHLS: TPaletteHLSArray);
function ColorToGrayscale(Color: TColor): TColor;
implementation
{$R-}
procedure _RGBtoHSL(RGB: TRGB; var HSL: THLS); inline;
var
HueValue, D, Cmax, Cmin: Integer;
begin
Cmax := Max(RGB.R, Max(RGB.G, RGB.B));
Cmin := Min(RGB.R, Min(RGB.G, RGB.B));
HSL.L := (Cmax + Cmin) div 2;
HueValue := 0;
HSL.S := 0;
if Cmax <> Cmin then
begin
D := (Cmax - Cmin);
if HSL.L < 127 then
HSL.S := (D * 240) div (Cmax + Cmin)
else
HSL.S := (D * 240) div (512 - Cmax - Cmin);
if RGB.R = Cmax then
HueValue := ((RGB.G - RGB.B) * 255) div D
else
if RGB.G = Cmax then
HueValue := 512 + ((RGB.B - RGB.R) * 255) div D
else
HueValue := 1024 + ((RGB.R - RGB.G) * 255) div D;
HueValue := HueValue div 6;
if HueValue < 0 then
HueValue := HueValue + 255;
end;
HSL.L := (HSL.L * 240) div 255;
HSL.H := (HueValue * 239) div 255;
end;
{
procedure _RGBtoHSL(RGB: TRGB; var HSL: THLS); inline;
var
R, G, B, LightValue, SaturationValue, HueValue, D, Cmax, Cmin: double;
begin
R := RGB.R / 255;
G := RGB.G / 255;
B := RGB.B / 255;
Cmax := Max(R, Max(G, B));
Cmin := Min(R, Min(G, B));
LightValue := (Cmax + Cmin) / 2;
HueValue := 0;
SaturationValue := 0;
if Cmax <> Cmin then
begin
D := Cmax - Cmin;
if LightValue < 0.5 then
SaturationValue := D / (Cmax + Cmin)
else
SaturationValue := D / (2 - Cmax - Cmin);
if R = Cmax then
HueValue := (G - B) / D
else
if G = Cmax then
HueValue := 2 + (B - R) / D
else
HueValue := 4 + (R - G) / D;
HueValue := HueValue / 6;
if HueValue < 0 then
HueValue := HueValue + 1;
end;
HSL.H := Round(239 * HueValue);
HSL.S := Round(240 * SaturationValue);
HSL.L := Round(240 * LightValue);
end;}
{$R+}
procedure FillColors(var Palette: TPaletteArray; var PaletteHLS: TPaletteHLSArray);
const
clOrange = $0066FF;
clPink = $BF98FF;
clBrown = $185488;
begin
Palette[0] := clRed;
PaletteHLS[0].HMin := 0;
PaletteHLS[0].HMax := 10;
PaletteHLS[0].LMin := 50;
PaletteHLS[0].LMax := 195;
PaletteHLS[0].SMin := 50;
PaletteHLS[0].SMax := 255;
Palette[1] := clRed;
PaletteHLS[1].HMin := 228;
PaletteHLS[1].HMax := 240;
PaletteHLS[1].LMin := 50;
PaletteHLS[1].LMax := 195;
PaletteHLS[1].SMin := 50;
PaletteHLS[1].SMax := 255;
Palette[2] := clOrange;
PaletteHLS[2].HMin := 11;
PaletteHLS[2].HMax := 24;
PaletteHLS[2].LMin := 110;
PaletteHLS[2].LMax := 210;
PaletteHLS[2].SMin := 151;
PaletteHLS[2].SMax := 255;
Palette[3] := clYellow;
PaletteHLS[3].HMin := 25;
PaletteHLS[3].HMax := 39;
PaletteHLS[3].LMin := 110;
PaletteHLS[3].LMax := 200;
PaletteHLS[3].SMin := 60;
PaletteHLS[3].SMax := 255;
Palette[4] := clGreen;
PaletteHLS[4].HMin := 40;
PaletteHLS[4].HMax := 95;
PaletteHLS[4].LMin := 50;
PaletteHLS[4].LMax := 220;
PaletteHLS[4].SMin := 40;
PaletteHLS[4].SMax := 255;
Palette[5] := clTeal;
PaletteHLS[5].HMin := 96;
PaletteHLS[5].HMax := 106;
PaletteHLS[5].LMin := 40;
PaletteHLS[5].LMax := 210;
PaletteHLS[5].SMin := 100;
PaletteHLS[5].SMax := 255;
Palette[6] := clBlue;
PaletteHLS[6].HMin := 107;
PaletteHLS[6].HMax := 170;
PaletteHLS[6].LMin := 30;
PaletteHLS[6].LMax := 210;
PaletteHLS[6].SMin := 90;
PaletteHLS[6].SMax := 255;
Palette[7] := clPurple;
PaletteHLS[7].HMin := 171;
PaletteHLS[7].HMax := 189;
PaletteHLS[7].LMin := 40;
PaletteHLS[7].LMax := 190;
PaletteHLS[7].SMin := 50;
PaletteHLS[7].SMax := 255;
Palette[8] := clPink;
PaletteHLS[8].HMin := 190;
PaletteHLS[8].HMax := 230;
PaletteHLS[8].LMin := 50;
PaletteHLS[8].LMax := 220;
PaletteHLS[8].SMin := 50;
PaletteHLS[8].SMax := 255;
Palette[9] := clWhite;
PaletteHLS[9].HMin := 0;
PaletteHLS[9].HMax := 255;
PaletteHLS[9].LMin := 230;
PaletteHLS[9].LMax := 255;
PaletteHLS[9].SMin := 0;
PaletteHLS[9].SMax := 255;
Palette[10] := clGray;
PaletteHLS[10].HMin := 0;
PaletteHLS[10].HMax := 255;
PaletteHLS[10].LMin := 150;
PaletteHLS[10].LMax := 200;
PaletteHLS[10].SMin := 0;
PaletteHLS[10].SMax := 40;
Palette[11] := clBlack;
PaletteHLS[11].HMin := 0;
PaletteHLS[11].HMax := 255;
PaletteHLS[11].LMin := 0;
PaletteHLS[11].LMax := 30;
PaletteHLS[11].SMin := 0;
PaletteHLS[11].SMax := 150;
Palette[12] := clBrown;
PaletteHLS[12].HMin := 15;
PaletteHLS[12].HMax := 30;
PaletteHLS[12].LMin := 30;
PaletteHLS[12].LMax := 100;
PaletteHLS[12].SMin := 30;
PaletteHLS[12].SMax := 150;
Palette[13] := clBlackWhite;
PaletteHLS[13].HMin := 0;
PaletteHLS[13].HMax := 255;
PaletteHLS[13].LMin := 0;
PaletteHLS[13].LMax := 255;
PaletteHLS[13].SMin := 0;
PaletteHLS[13].SMax := 40;
Palette[14] := clColored;
PaletteHLS[14].HMin := 0;
PaletteHLS[14].HMax := 255;
PaletteHLS[14].LMin := 0;
PaletteHLS[14].LMax := 255;
PaletteHLS[14].SMin := 41;
PaletteHLS[14].SMax := 255;
end;
procedure FindPaletteColorsOnImage(B: TBitmap; Colors: TList<TColor>; MaxColors: Integer);
var
P: PARGB;
I, J, K: Integer;
MinWeight: Integer;
CR: TColorRange;
Palette: TPaletteArray;
PaletteHLS: TPaletteHLSArray;
Weights: array[0..ColorCount - 1] of Double;
MaxWeight, MaxWeightLimit: Double;
HLS: THLS;
MaxIndex: Integer;
begin
if B.Empty then
Exit;
FillChar(Weights, SizeOf(Weights), 0);
MinWeight := B.Width * B.Height div 50;
FillColors(Palette, PaletteHLS);
for I := 0 to B.Height - 1 do
begin
P := B.ScanLine[I];
for J := 0 to B.Width - 1 do
begin
_RGBtoHSL(P[J], HLS);
for K := 0 to ColorCount - 1 do
begin
CR := PaletteHLS[K];
if (CR.HMin <= HLS.H) and (HLS.H <= CR.HMax) then
if (CR.LMin <= HLS.L) and (HLS.L <= CR.LMax) then
if (CR.SMin <= HLS.S) and (HLS.S <= CR.SMax) then
Weights[K] := Weights[K] + 1;
end;
end;
end;
Weights[1] := Weights[1] + Weights[0];
Weights[0] := 0;
MaxWeight := 0.0;
MaxIndex := -1;
for K := 0 to ColorCount - 3 do
begin
if (MaxWeight < Weights[K]) and (Weights[K] > MinWeight) then
begin
MaxWeight := Weights[K];
MaxIndex := K;
end;
end;
if (MaxIndex > -1) then
begin
Colors.Add(Palette[MaxIndex]);
MaxWeightLimit := MaxWeight / 100;
for I := 0 to MaxColors - 2 do
begin
Weights[MaxIndex] := 0.0;
MaxWeight := 0.0;
MaxIndex := 0;
for K := 0 to ColorCount - 3 do
begin
if (MaxWeight < Weights[K]) and (Weights[K] > MinWeight) then
begin
MaxWeight := Weights[K];
MaxIndex := K;
end;
end;
if MaxWeight > MaxWeightLimit then
Colors.Add(Palette[MaxIndex]);
end;
end;
if (Weights[cColoredIndex] = 0) and (Weights[cBlackWhiteIndex] > MinWeight) then
Colors.Add(clBlackWhite)
else
if Weights[cBlackWhiteIndex] / Weights[cColoredIndex] > 100 then
Colors.Add(clBlackWhite);
end;
function ColorPaletteToString(Color: TColor): string;
begin
if Color = clBlackWhite then
Result := 'BW'
else
Result := IntToHex(Color, 6);
end;
function ColorsToString(Colors: TArray<TColor>): string;
var
Color: TColor;
SL: TStringList;
begin
Result := '';
SL := TStringList.Create;
try
for Color in Colors do
SL.Add(ColorPaletteToString(Color));
Result := SL.Join('#');
finally
F(SL);
end;
end;
function ColorToGrayscale(Color: TColor): TColor;
var
R, G, B, BW: Byte;
begin
R := GetRValue(Color);
G := GetGValue(Color);
B := GetBValue(Color);
BW := (R * 77 + G * 151 + B * 28) shr 8;
Result := RGB(BW, BW, BW);
end;
end.
|
unit Tella_Listar;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TTela_Listar = class(TForm)
mmListar: TMemo;
mmHistorico: TMemo;
Label1: TLabel;
Label2: TLabel;
procedure FormActivate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
telaListar: TTela_Listar;
implementation
{$R *.dfm}
uses Unit_Funcoes;
procedure TTela_Listar.FormActivate(Sender: TObject);
var
i:integer;
tempototal:TTime;
h,m,s,mili:word;
begin
mmHistorico.Clear;
mmListar.Clear;
for i := 1 to Estacionamento.getCont do
begin
if ( TimeToStr(Estacionamento.carros[i].HoraSaida) <> '00:00:00' ) then
begin
mmHistorico.Lines.Add('placa: '+estacionamento.carros[i].placa);
mmHistorico.Lines.Add('Entrada: '+timetostr(estacionamento.carros[i].HoraEntrada));
tempototal:= estacionamento.carros[i].HoraSaida - Estacionamento.carros[i].HoraEntrada;
decodetime(tempototal,h,m,s,mili);
if ((m)<>0) then
begin
h:=h+1;
end;
mmHistorico.Lines.Add('Saída: '+timetostr(estacionamento.carros[i].HoraSaida));
mmHistorico.Lines.Add('Valor Pago: '+inttostr(5+(h*2)));
mmHistorico.Lines.Add('-------------------------');
end;
end;
for i := 1 to Estacionamento.getCont do
begin
if ( TimeToStr(Estacionamento.carros[i].HoraSaida) = '00:00:00' ) then
begin
mmListar.Lines.Add('placa: '+ estacionamento.carros[i].placa);
mmListar.Lines.Add('Entrada: '+ timetostr(estacionamento.carros[i].HoraEntrada));
mmListar.Lines.Add('Vaga: ' + IntToStr(estacionamento.carros[i].vaga));
tempototal:= estacionamento.carros[i].HoraSaida - Estacionamento.carros[i].HoraEntrada;
decodetime(tempototal,h,m,s,mili);
if ((m)<>0) then
begin
h:=h+1;
end;
mmListar.Lines.Add('-------------------------');
end;
end;
end;
procedure TTela_Listar.FormKeyPress(Sender: TObject; var Key: Char);
begin
If Key = #27 Then Close; //ESC fecha form
end;
end.
|
unit uPesquisa;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids,
Vcl.StdCtrls, FireDAC.Comp.Client, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet;
type
TfrmPesquisa = class(TForm)
edNome: TEdit;
lbNome: TLabel;
btPesquisar: TButton;
gdResultado: TDBGrid;
btSelecionar: TButton;
btCancelar: TButton;
dsPesquisa: TDataSource;
FDQueryPesquisa: TFDQuery;
procedure btCancelarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btSelecionarClick(Sender: TObject);
procedure btPesquisarClick(Sender: TObject);
private
FCodigoSelecionado: integer;
FNomeCampoRetorno: string;
FConsultaSQL: string;
FTela: integer;
procedure SetCodigoSelecionado(const Value: integer);
procedure SetNomeCampoRetorno(const Value: string);
procedure SetConsultaSQL(const Value: string);
procedure SetTela(const Value: integer);
{ Private declarations }
public
property CodigoSelecionado: integer read FCodigoSelecionado write SetCodigoSelecionado;
property NomeCampoRetorno: string read FNomeCampoRetorno write SetNomeCampoRetorno;
property ConsultaSQL: string read FConsultaSQL write SetConsultaSQL;
property Tela: integer read FTela write SetTela;
end;
var
frmPesquisa: TfrmPesquisa;
const
nTELA_PESSOA = 0;
nTELA_CIDADE = 1;
implementation
uses
uDMPrincipal;
{$R *.dfm}
procedure TfrmPesquisa.btCancelarClick(Sender: TObject);
begin
Self.Close;
end;
procedure TfrmPesquisa.btPesquisarClick(Sender: TObject);
var
sConsultaSQL: string;
begin
sConsultaSQL := FConsultaSQL;
if (FTela = nTELA_PESSOA) and (Trim(edNome.Text) <> EmptyStr) then
sConsultaSQL := sConsultaSQL + ' where upper(nmPessoa) like ' + QuotedStr('%' + UpperCase(Trim(edNome.Text)) + '%')
else
if (FTela = nTELA_CIDADE) and (Trim(edNome.Text) <> EmptyStr) then
sConsultaSQL := sConsultaSQL + ' where upper(nmCidade) like ' + QuotedStr('%' + UpperCase(Trim(edNome.Text)) + '%');
FDQueryPesquisa.SQL.Text := sConsultaSQL;
FDQueryPesquisa.Open;
if FDQueryPesquisa.IsEmpty then
begin
ShowMessage('Não encontrou registros.');
Exit;
end;
if FTela = nTELA_PESSOA then
begin
FDQueryPesquisa.FieldByName('cdPessoa').Visible := False;
FDQueryPesquisa.FieldByName('nmPessoa').DisplayLabel := 'Nome';
FDQueryPesquisa.FieldByName('deLogradouro').DisplayLabel := 'Logradouro';
FDQueryPesquisa.FieldByName('deBairro').DisplayLabel := 'Bairro';
FDQueryPesquisa.FieldByName('nmCidade').DisplayLabel := 'Cidade';
FDQueryPesquisa.FieldByName('UF').DisplayLabel := 'UF';
end
else
if FTela = nTELA_CIDADE then
begin
FDQueryPesquisa.FieldByName('cdCidade').Visible := False;
FDQueryPesquisa.FieldByName('nmCidade').DisplayLabel := 'Nome';
FDQueryPesquisa.FieldByName('UF').DisplayLabel := 'UF';
end;
end;
procedure TfrmPesquisa.btSelecionarClick(Sender: TObject);
begin
FCodigoSelecionado := FDQueryPesquisa.FieldByName(FNomeCampoRetorno).AsInteger;
Self.Close;
end;
procedure TfrmPesquisa.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmPesquisa.SetCodigoSelecionado(const Value: integer);
begin
FCodigoSelecionado := Value;
end;
procedure TfrmPesquisa.SetConsultaSQL(const Value: string);
begin
FConsultaSQL := Value;
end;
procedure TfrmPesquisa.SetNomeCampoRetorno(const Value: string);
begin
FNomeCampoRetorno := Value;
end;
procedure TfrmPesquisa.SetTela(const Value: integer);
begin
FTela := Value;
end;
end.
|
unit Generator;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ComCtrls, ToolWin, StdCtrls,
LrTagParser,
htColumns, htRows, htLayout, htAutoTable, htDocument, htGenerator,
htWebControl;
type
// This is a stupid class
TGenerator = class
private
FDocument: ThtDocument;
FContent: TWinControl;
FHtml: TStringList;
HtmlGenerator: ThtGenerator;
protected
procedure FormatHtml;
procedure SetContent(const Value: TWinControl);
procedure SetHtml(const Value: TStringList);
public
constructor Create;
destructor Destroy; override;
procedure GenerateDocument;
procedure GenerateHtml;
property Content: TWinControl read FContent write SetContent;
property Document: ThtDocument read FDocument;
property Html: TStringList read FHtml write SetHtml;
end;
implementation
uses
ShellApi,
Globals;
{ TGenerator }
constructor TGenerator.Create;
begin
FHtml := TStringList.Create;
HtmlGenerator := ThtGenerator.Create;
//HtmlGenerator.OnGenerateCtrl := GenerateCtrl;
FDocument := ThtDocument.Create;
end;
destructor TGenerator.Destroy;
begin
Document.Free;
HtmlGenerator.Free;
Html.Free;
inherited;
end;
procedure TGenerator.SetContent(const Value: TWinControl);
begin
FContent := Value;
end;
procedure TGenerator.SetHtml(const Value: TStringList);
begin
FHtml.Assign(Value);
end;
procedure TGenerator.GenerateDocument;
begin
Document.Free;
FDocument := ThtDocument.Create;
HtmlGenerator.Generate(Content, Document);
end;
procedure TGenerator.GenerateHtml;
begin
Html.Clear;
Document.Build(Html);
FormatHtml;
end;
procedure TGenerator.FormatHtml;
var
tags: TLrTaggedDocument;
begin
tags := TLrTaggedDocument.Create;
try
tags.Text := Html.Text;
Html.Clear;
tags.Indent(Html);
finally
tags.Free;
end;
end;
end.
|
{ sort with concatenation }
var
sorted : string;
begin
sorted := sort('Hello''World'+''#33'');
write('Sorted string is: ', sorted)
end. |
{
Double Commander
-------------------------------------------------------------------------
Search & Replace dialog
Copyright (C) 2003-2004 Radek Cervinka (radek.cervinka@centrum.cz)
Copyright (C) 2006-2022 Alexander Koblov (alexx2000@mail.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit fEditSearch;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, StdCtrls, ExtCtrls, Buttons, ButtonPanel,
SynEdit, SynEditTypes, uOSForms, DCClassesUtf8;
type
{ TEditSearchOptions }
TEditSearchOptions = record
SearchText: String;
ReplaceText: String;
Flags: TSynSearchOptions;
end;
{ TEditSearchDialogOption }
//Not only it helps to show what we want to offer to user, it will help to determine the default
//When used as parameters of function, place on required.
//When used as a returned value, we'll include the status of all.
TEditSearchDialogOption = set of (eswoCaseSensitiveChecked, eswoCaseSensitiveUnchecked,
eswoWholeWordChecked, eswoWholeWordUnchecked,
eswoSelectedTextChecked, eswoSelectedTextUnchecked,
eswoSearchFromCursorChecked, eswoSearchFromCursorUnchecked,
eswoRegularExpressChecked, eswoRegularExpressUnchecked,
eswoDirectionDisabled, eswoDirectionEnabledForward, eswoDirectionEnabledBackward);
{ TfrmEditSearchReplace }
TfrmEditSearchReplace = class(TModalForm)
ButtonPanel: TButtonPanel;
cbSearchText: TComboBox;
cbSearchCaseSensitive: TCheckBox;
cbSearchWholeWords: TCheckBox;
cbSearchSelectedOnly: TCheckBox;
cbSearchFromCursor: TCheckBox;
cbSearchRegExp: TCheckBox;
cbReplaceText: TComboBox;
cbMultiLine: TCheckBox;
gbSearchOptions: TGroupBox;
lblReplaceWith: TCheckBox;
lblSearchFor: TLabel;
rgSearchDirection: TRadioGroup;
procedure btnOKClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lblReplaceWithChange(Sender: TObject);
procedure RequestAlign(Data: PtrInt);
private
function GetSearchOptions: TEditSearchOptions;
procedure SetSearchOptions(AValue: TEditSearchOptions);
function GetTextSearchOptions: UIntPtr;
public
constructor Create(AOwner: TComponent; AReplace: TCheckBoxState); reintroduce;
property SearchOptions: TEditSearchOptions read GetSearchOptions write SetSearchOptions;
end;
function GetSimpleSearchAndReplaceString(AOwner: TComponent; OptionAllowed: TEditSearchDialogOption; var sSearchText: string; var sReplaceText: string; var OptionsToReturn:TEditSearchDialogOption; PastSearchList:TStringListEx; PastReplaceList:TStringListEx):boolean;
procedure DoSearchReplaceText(AEditor: TCustomSynEdit; AReplace, ABackwards: Boolean; AOptions: TEditSearchOptions);
procedure ShowSearchReplaceDialog(AOwner: TComponent; AEditor: TCustomSynEdit; AReplace: TCheckBoxState; var AOptions: TEditSearchOptions);
implementation
{$R *.lfm}
uses
Math, Graphics, uGlobs, uLng, uDCUtils, uFindFiles, uShowMsg;
function GetSimpleSearchAndReplaceString(AOwner:TComponent; OptionAllowed:TEditSearchDialogOption; var sSearchText:string; var sReplaceText:string; var OptionsToReturn:TEditSearchDialogOption; PastSearchList:TStringListEx; PastReplaceList:TStringListEx):boolean;
var
dlg: TfrmEditSearchReplace;
begin
result:=FALSE;
OptionsToReturn:=[];
dlg := TfrmEditSearchReplace.Create(AOwner, cbChecked);
try
with dlg do
begin
//1. Let's enable to options host wanted to offer to user
cbSearchCaseSensitive.Enabled := ((eswoCaseSensitiveChecked in OptionAllowed) OR (eswoCaseSensitiveUnchecked in OptionAllowed));
cbSearchWholeWords.Enabled := ((eswoWholeWordChecked in OptionAllowed) OR (eswoWholeWordUnchecked in OptionAllowed));
cbSearchSelectedOnly.Enabled := ((eswoSelectedTextChecked in OptionAllowed) OR (eswoSelectedTextUnchecked in OptionAllowed));
cbSearchFromCursor.Enabled := ((eswoSearchFromCursorChecked in OptionAllowed) OR (eswoSearchFromCursorUnchecked in OptionAllowed));
cbSearchRegExp.Enabled := ((eswoRegularExpressChecked in OptionAllowed) OR (eswoRegularExpressUnchecked in OptionAllowed));
rgSearchDirection.Enabled := ((eswoDirectionEnabledForward in OptionAllowed) OR (eswoDirectionEnabledBackward in OptionAllowed));
//2. Let's set the option to their default according to what host wants to offer
cbSearchCaseSensitive.Checked := (eswoCaseSensitiveChecked in OptionAllowed);
cbSearchWholeWords.Checked := (eswoWholeWordChecked in OptionAllowed);
cbSearchSelectedOnly.Checked := (eswoSelectedTextChecked in OptionAllowed);
cbSearchFromCursor.Checked := (eswoSearchFromCursorChecked in OptionAllowed);
cbSearchRegExp.Checked := (eswoRegularExpressChecked in OptionAllowed);
rgSearchDirection.ItemIndex:=ifthen((eswoDirectionEnabledBackward in OptionAllowed),1,0);
//3. Setup the SEARCH info
if sSearchText='' then sSearchText:=rsEditSearchCaption;
cbSearchText.Items.Assign(PastSearchList);
cbSearchText.Text:= sSearchText;
//4. Setup the REPLACE info
if sReplaceText='' then sReplaceText:=rsEditSearchReplace;
cbReplaceText.Items.Assign(PastReplaceList);
cbReplaceText.Text:=sReplaceText;
//5. Get feedback from user
if ShowModal=mrOk then
begin
//6. Let's set the options wanted by the user
if cbSearchCaseSensitive.Enabled then
if cbSearchCaseSensitive.Checked then OptionsToReturn:=OptionsToReturn+[eswoCaseSensitiveChecked] else OptionsToReturn:=OptionsToReturn+[eswoCaseSensitiveUnchecked];
if cbSearchWholeWords.Enabled then
if cbSearchWholeWords.Checked then OptionsToReturn:=OptionsToReturn+[eswoWholeWordChecked] else OptionsToReturn:=OptionsToReturn+[eswoWholeWordUnchecked];
if cbSearchSelectedOnly.Enabled then
if cbSearchSelectedOnly.Checked then OptionsToReturn:=OptionsToReturn+[eswoSelectedTextChecked] else OptionsToReturn:=OptionsToReturn+[eswoSelectedTextUnchecked];
if cbSearchFromCursor.Enabled then
if cbSearchFromCursor.Checked then OptionsToReturn:=OptionsToReturn+[eswoSearchFromCursorChecked] else OptionsToReturn:=OptionsToReturn+[eswoSearchFromCursorUnchecked];
if cbSearchRegExp.Enabled then
if cbSearchRegExp.Checked then OptionsToReturn:=OptionsToReturn+[eswoRegularExpressChecked] else OptionsToReturn:=OptionsToReturn+[eswoRegularExpressUnchecked];
if rgSearchDirection.Enabled then
if rgSearchDirection.ItemIndex=1 then OptionsToReturn:=OptionsToReturn+[eswoDirectionEnabledBackward] else OptionsToReturn:=OptionsToReturn+[eswoDirectionEnabledForward];
//7. Let's set our history
PastSearchList.Assign(cbSearchText.Items);
PastReplaceList.Assign(cbReplaceText.Items);
//8. And FINALLY, our valuable text to search we wanted to replace!
sSearchText:=cbSearchText.Text;
sReplaceText:=cbReplaceText.Text;
result:=((sSearchText<>sReplaceText) AND (sSearchText<>''));
end;
end;
finally
FreeAndNil(Dlg);
end;
end;
procedure DoSearchReplaceText(AEditor: TCustomSynEdit; AReplace,
ABackwards: Boolean; AOptions: TEditSearchOptions);
var
Flags: TSynSearchOptions;
begin
Flags := AOptions.Flags;
if ABackwards then
Include(Flags, ssoBackwards)
else begin
Exclude(Flags, ssoBackwards);
end;
if AReplace then begin
Flags += [ssoPrompt, ssoReplace, ssoReplaceAll];
end;
try
if AEditor.SearchReplace(AOptions.SearchText, AOptions.ReplaceText, Flags) = 0 then
begin
if ssoBackwards in Flags then
AEditor.BlockEnd := AEditor.BlockBegin
else begin
AEditor.BlockBegin := AEditor.BlockEnd;
end;
AEditor.CaretXY := AEditor.BlockBegin;
msgOK(Format(rsViewNotFound, ['"' + AOptions.SearchText + '"']));
end;
except
on E: Exception do msgError(E.Message);
end;
end;
procedure ShowSearchReplaceDialog(AOwner: TComponent; AEditor: TCustomSynEdit;
AReplace: TCheckBoxState; var AOptions: TEditSearchOptions);
var
Options: TEditSearchOptions;
begin
with TfrmEditSearchReplace.Create(AOwner, AReplace) do
try
Options := AOptions;
if AEditor.SelAvail and (AEditor.BlockBegin.Y <> AEditor.BlockEnd.Y) then
Options.Flags += [ssoSelectedOnly];
// If something is selected then search for that text
if AEditor.SelAvail and (AEditor.BlockBegin.Y = AEditor.BlockEnd.Y) then
Options.SearchText := AEditor.SelText
else begin
Options.SearchText := AEditor.GetWordAtRowCol(AEditor.CaretXY);
end;
cbSearchText.Items.Text := glsSearchHistory.Text;
cbReplaceText.Items.Text := glsReplaceHistory.Text;
// Assign search options
SearchOptions := Options;
if ShowModal = mrOK then
begin
AOptions := SearchOptions;
glsSearchHistory.Assign(cbSearchText.Items);
glsReplaceHistory.Assign(cbReplaceText.Items);
if AOptions.SearchText <> '' then
begin
DoSearchReplaceText(AEditor, AReplace = cbChecked, ssoBackwards in AOptions.Flags, AOptions);
AOptions.Flags -= [ssoEntireScope];
gFirstTextSearch := False;
end;
end;
finally
Free;
end;
end;
{ TfrmEditSearchReplace }
procedure TfrmEditSearchReplace.btnOKClick(Sender: TObject);
begin
InsertFirstItem(cbSearchText.Text, cbSearchText, GetTextSearchOptions);
ModalResult := mrOK
end;
procedure TfrmEditSearchReplace.FormCloseQuery(Sender: TObject;
var CanClose: boolean);
begin
if ModalResult = mrOK then
InsertFirstItem(cbReplaceText.Text, cbReplaceText, GetTextSearchOptions);
end;
procedure TfrmEditSearchReplace.FormCreate(Sender: TObject);
begin
InitPropStorage(Self);
end;
procedure TfrmEditSearchReplace.FormShow(Sender: TObject);
begin
if cbSearchText.Text = EmptyStr then
begin
if cbSearchText.Items.Count > 0 then
cbSearchText.Text:= cbSearchText.Items[0];
end;
cbSearchText.SelectAll;
// Fixes AutoSize under Qt
Application.QueueAsyncCall(@RequestAlign, 0);
end;
procedure TfrmEditSearchReplace.lblReplaceWithChange(Sender: TObject);
begin
if lblReplaceWith.Checked then
Caption:= rsEditSearchReplace
else begin
Caption:= rsEditSearchCaption;
end;
cbReplaceText.Enabled := lblReplaceWith.Checked;
end;
procedure TfrmEditSearchReplace.RequestAlign(Data: PtrInt);
begin
Width := Width + 1;
Width := Width - 1;
end;
function TfrmEditSearchReplace.GetSearchOptions: TEditSearchOptions;
begin
Result.SearchText:= cbSearchText.Text;
Result.ReplaceText := cbReplaceText.Text;
Result.Flags := [];
if cbSearchCaseSensitive.Checked then
Result.Flags += [ssoMatchCase];
if cbSearchWholeWords.Checked then
Result.Flags += [ssoWholeWord];
if cbSearchSelectedOnly.Checked then
Result.Flags += [ssoSelectedOnly];
if not cbSearchFromCursor.Checked then
Result.Flags += [ssoEntireScope];
if cbSearchRegExp.Checked then
Result.Flags += [ssoRegExpr];
if cbMultiLine.Checked then
Result.Flags += [ssoRegExprMultiLine];
if rgSearchDirection.ItemIndex = 1 then
Result.Flags += [ssoBackwards];
end;
procedure TfrmEditSearchReplace.SetSearchOptions(AValue: TEditSearchOptions);
begin
cbSearchText.Text := AValue.SearchText;
cbReplaceText.Text := AValue.ReplaceText;
with AValue do
begin
cbSearchCaseSensitive.Checked := ssoMatchCase in Flags;
cbSearchWholeWords.Checked := ssoWholeWord in Flags;
cbSearchSelectedOnly.Checked := ssoSelectedOnly in Flags;
cbSearchFromCursor.Checked := not (ssoEntireScope in Flags);
cbSearchRegExp.Checked := ssoRegExpr in Flags;
cbMultiLine.Checked := ssoRegExprMultiLine in Flags;
rgSearchDirection.ItemIndex := Ord(ssoBackwards in Flags);
end;
end;
function TfrmEditSearchReplace.GetTextSearchOptions: UIntPtr;
var
Options: TTextSearchOptions absolute Result;
begin
Result:= 0;
if cbSearchCaseSensitive.Checked then
Include(Options, tsoMatchCase);
if cbSearchRegExp.Checked then
Include(Options, tsoRegExpr);
end;
constructor TfrmEditSearchReplace.Create(AOwner: TComponent; AReplace: TCheckBoxState);
begin
inherited Create(AOwner);
lblReplaceWith.Visible:= (AReplace <> cbGrayed);
cbReplaceText.Visible:= (AReplace <> cbGrayed);
cbReplaceText.Enabled := (AReplace = cbChecked);
lblReplaceWith.Checked := (AReplace = cbChecked);
if (AReplace = cbChecked) then
Caption:= rsEditSearchReplace
else begin
Caption:= rsEditSearchCaption;
end;
rgSearchDirection.Items.Strings[0]:= rsEditSearchFrw;
rgSearchDirection.Items.Strings[1]:= rsEditSearchBack;
end;
end.
|
unit ULancamentoContabilVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,
UPlanoContasVO, UContasReceberVO, UContasPagarVO,UhistoricoVO, ULoteVO, UCondominioVO, ULancamentoPadraoVO, UItensLeituraGasVO;
type
[TEntity]
[TTable('LancamentoContabil')]
TLancamentoContabilVO = class(TGenericVO)
private
FidLcto : Integer;
FdtLcto : TDateTime;
FVlValor : currency;
FComplemento : String;
FidContaDebito : Integer;
FidContaCredito : Integer;
FidContasReceber : Integer;
FidContasPagar : Integer;
FidHistorico : Integer;
FidLote : Integer;
FidItensLeituraGas : Integer;
FidItensRateio : Integer;
FDsClassificacaoDebito : string;
FDsClassificacaoCredito : string;
FDsContaDebito : String;
FDsContaCredito : String;
FDsHistorico : String;
FidBaixa : Integer;
public
ContaDebitoVo : TPlanoContasVO;
ContaCreditoVO : TPlanoContasVO;
ContasReceberVO : TContasReceberVO;
ContasPagarVo : TContasPagarVO;
HistoricoVO : THistoricoVO;
LoteVO : TLoteVo;
CondominioVO : TCondominioVO;
LctoPadraoVo : TLancamentoPadraoVO;
ItensLeituraGasVO : TItensLeituraGasVO;
[TId('idLcto')]
[TGeneratedValue(sAuto)]
property idLcto : Integer read FidLcto write FidLcto;
[TColumn('dtLcto','Data',0,[ldGrid,ldLookup,ldComboBox], False)]
property dtLcto: TDateTime read FdtLcto write FdtLcto;
[TColumn('vlValor','Valor',30,[ldGrid,ldLookup,ldComboBox], False)]
property VlValor: Currency read FVlValor write FVlValor;
[TColumn('dscomplemento','Complemento',80,[ldGrid,ldLookup,ldComboBox], False)]
property complemento: string read FComplemento write Fcomplemento;
[TColumn('idcontacredito','Crédito',0,[ldLookup,ldComboBox], False)]
property idContaCredito: integer read FidContaCredito write FidContaCredito;
[TColumn('idcontadebito','Débito',0,[ldLookup,ldComboBox], False)]
property idcontadebito: integer read FidContaDebito write FidContaDebito;
[TColumn('idcontasreceber','ContasReceber',0,[ldLookup,ldComboBox], False)]
property idContasReceber: integer read FidContasReceber write FidContasReceber;
[TColumn('idcontaspagar','ContasPagar',0,[ldLookup,ldComboBox], False)]
property idContasPagar: integer read FidContasPagar write FidContasPagar;
[TColumn('idlote','idLote',0,[ldLookup,ldComboBox], False)]
property idLote: integer read FIdLote write FIdLote;
[TColumn('idItensLeituragas','idItensLeituragas',0,[ldLookup,ldComboBox], False)]
property iditensleituragas : integer read Fiditensleituragas write Fiditensleituragas;
[TColumn('idItensRateio','idItensLeituragas',0,[ldLookup,ldComboBox], False)]
property idItensRateio : integer read FidItensRateio write FidItensRateio;
[TColumn('idbaixa','idbaixa',0,[ldLookup,ldComboBox], False)]
property idbaixa: integer read FidBaixa write FidBaixa;
[TColumn('idHistorico','idHistorico',0,[ldLookup,ldComboBox], False)]
property idHistorico: integer read FIdHistorico write FIdHistorico;
[TColumn('DSCLASSIFICACAODEBITO','Classificacao',0,[], True, 'PlanoContas', 'idContaDebito', 'idPlanoContas', 'PlanoDebitoDS', 'DSCONTA')]
property DsClassificacaoDebito : string read FDsClassificacaoDebito write FDsClassificacaoDebito;
[TColumn('DSCLASSIFICACAOCREDITO','Classificacao',0,[], True, 'PlanoContas', 'idContaCredito', 'idPlanoContas', 'PlanoCreditoDs', 'DSCONTA')]
property DsClassificacaoCredito : string read FDsClassificacaoCredito write FDsClassificacaoCredito;
[TColumn('DSCONTADEBITO','ContaDebito',0,[], True, 'PlanoContas', 'idContaDebito', 'idPlanoContas', 'PlanoDebito', 'DSCONTA')]
property DsContaDebito: string read FDsContaDebito write FDsContaDebito;
[TColumn('DSCONTACREDITO','ContaCredito',0,[], True, 'PlanoContas', 'idContaCredito', 'idPlanoContas', 'PlanoCredito', 'DSCONTA')]
property DsContaCredito: string read FDsContaCredito write FDsContaCredito;
[TColumn('DSHISTORICO','',0,[], True, 'Historicos', 'idHistorico', 'idHistorico')]
property DsHistorico: string read FDsHistorico write FDsHistorico;
procedure ValidarCamposObrigatorios;
end;
implementation
{ TLancamentoContabilVO }
procedure TLancamentoContabilVO.ValidarCamposObrigatorios;
begin
if (self.FDtLcto = 0) then
begin
raise Exception.Create('O campo Data é obrigatório!');
end;
if ((self.FidContaDebito = 0) and (self.idContaCredito = 0))then
begin
raise Exception.Create('O campo Conta débito ou conta crédito é obrigatório!');
end;
if (Self.FidHistorico = 0) then
begin
raise Exception.Create('O campo Histórico é obrigatório!');
end;
if (Self.FVlValor <= 0) then
begin
raise Exception.Create('O campo Valor é obrigatório!');
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [NFE_DETALHE]
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
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit NfeDetalheVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL, ProdutoVO, NfeDetalheImpostoIcmsVO;
type
TNfeDetalheVO = class(TVO)
private
FID: Integer;
FID_PRODUTO: Integer;
FID_NFE_CABECALHO: Integer;
FNUMERO_ITEM: Integer;
FCODIGO_PRODUTO: String;
FGTIN: String;
FNOME_PRODUTO: String;
FNCM: String;
FNVE: String;
FEX_TIPI: Integer;
FCFOP: Integer;
FUNIDADE_COMERCIAL: String;
FQUANTIDADE_COMERCIAL: Extended;
FVALOR_UNITARIO_COMERCIAL: Extended;
FVALOR_BRUTO_PRODUTO: Extended;
FGTIN_UNIDADE_TRIBUTAVEL: String;
FUNIDADE_TRIBUTAVEL: String;
FQUANTIDADE_TRIBUTAVEL: Extended;
FVALOR_UNITARIO_TRIBUTAVEL: Extended;
FVALOR_FRETE: Extended;
FVALOR_SEGURO: Extended;
FVALOR_DESCONTO: Extended;
FVALOR_OUTRAS_DESPESAS: Extended;
FENTRA_TOTAL: Integer;
FVALOR_SUBTOTAL: Extended;
FVALOR_TOTAL: Extended;
FNUMERO_PEDIDO_COMPRA: String;
FITEM_PEDIDO_COMPRA: Integer;
FINFORMACOES_ADICIONAIS: String;
FNUMERO_FCI: String;
FNUMERO_RECOPI: String;
FVALOR_TOTAL_TRIBUTOS: Extended;
FPERCENTUAL_DEVOLVIDO: Extended;
FVALOR_IPI_DEVOLVIDO: Extended;
FProdutoVO: TProdutoVO;
// Grupo N
FNfeDetalheImpostoIcmsVO: TNfeDetalheImpostoIcmsVO; //1:1
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdProduto: Integer read FID_PRODUTO write FID_PRODUTO;
property IdNfeCabecalho: Integer read FID_NFE_CABECALHO write FID_NFE_CABECALHO;
property NumeroItem: Integer read FNUMERO_ITEM write FNUMERO_ITEM;
property CodigoProduto: String read FCODIGO_PRODUTO write FCODIGO_PRODUTO;
property Gtin: String read FGTIN write FGTIN;
property NomeProduto: String read FNOME_PRODUTO write FNOME_PRODUTO;
property Ncm: String read FNCM write FNCM;
property Nve: String read FNVE write FNVE;
property ExTipi: Integer read FEX_TIPI write FEX_TIPI;
property Cfop: Integer read FCFOP write FCFOP;
property UnidadeComercial: String read FUNIDADE_COMERCIAL write FUNIDADE_COMERCIAL;
property QuantidadeComercial: Extended read FQUANTIDADE_COMERCIAL write FQUANTIDADE_COMERCIAL;
property ValorUnitarioComercial: Extended read FVALOR_UNITARIO_COMERCIAL write FVALOR_UNITARIO_COMERCIAL;
property ValorBrutoProduto: Extended read FVALOR_BRUTO_PRODUTO write FVALOR_BRUTO_PRODUTO;
property GtinUnidadeTributavel: String read FGTIN_UNIDADE_TRIBUTAVEL write FGTIN_UNIDADE_TRIBUTAVEL;
property UnidadeTributavel: String read FUNIDADE_TRIBUTAVEL write FUNIDADE_TRIBUTAVEL;
property QuantidadeTributavel: Extended read FQUANTIDADE_TRIBUTAVEL write FQUANTIDADE_TRIBUTAVEL;
property ValorUnitarioTributavel: Extended read FVALOR_UNITARIO_TRIBUTAVEL write FVALOR_UNITARIO_TRIBUTAVEL;
property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE;
property ValorSeguro: Extended read FVALOR_SEGURO write FVALOR_SEGURO;
property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO;
property ValorOutrasDespesas: Extended read FVALOR_OUTRAS_DESPESAS write FVALOR_OUTRAS_DESPESAS;
property EntraTotal: Integer read FENTRA_TOTAL write FENTRA_TOTAL;
property ValorSubtotal: Extended read FVALOR_SUBTOTAL write FVALOR_SUBTOTAL;
property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL;
property NumeroPedidoCompra: String read FNUMERO_PEDIDO_COMPRA write FNUMERO_PEDIDO_COMPRA;
property ItemPedidoCompra: Integer read FITEM_PEDIDO_COMPRA write FITEM_PEDIDO_COMPRA;
property InformacoesAdicionais: String read FINFORMACOES_ADICIONAIS write FINFORMACOES_ADICIONAIS;
property NumeroFci: String read FNUMERO_FCI write FNUMERO_FCI;
property NumeroRecopi: String read FNUMERO_RECOPI write FNUMERO_RECOPI;
property ValorTotalTributos: Extended read FVALOR_TOTAL_TRIBUTOS write FVALOR_TOTAL_TRIBUTOS;
property PercentualDevolvido: Extended read FPERCENTUAL_DEVOLVIDO write FPERCENTUAL_DEVOLVIDO;
property ValorIpiDevolvido: Extended read FVALOR_IPI_DEVOLVIDO write FVALOR_IPI_DEVOLVIDO;
property ProdutoVO: TProdutoVO read FProdutoVO write FProdutoVO;
property NfeDetalheImpostoIcmsVO: TNfeDetalheImpostoIcmsVO read FNfeDetalheImpostoIcmsVO write FNfeDetalheImpostoIcmsVO;
end;
TListaNfeDetalheVO = specialize TFPGObjectList<TNfeDetalheVO>;
implementation
constructor TNfeDetalheVO.Create;
begin
inherited;
FProdutoVO := TProdutoVO.Create;
FNfeDetalheImpostoIcmsVO := TNfeDetalheImpostoIcmsVO.Create;
end;
destructor TNfeDetalheVO.Destroy;
begin
FreeAndNil(FProdutoVO);
FreeAndNil(FNfeDetalheImpostoIcmsVO);
inherited;
end;
initialization
Classes.RegisterClass(TNfeDetalheVO);
finalization
Classes.UnRegisterClass(TNfeDetalheVO);
end.
|
unit DSA.List_Stack_Queue.ArrayListQueue;
interface
uses
System.SysUtils,
System.Rtti,
DSA.Interfaces.DataStructure,
DSA.List_Stack_Queue.ArrayList;
type
TArrayListQueue<T> = class(TInterfacedObject, IQueue<T>)
private type
TArrayList_T = TArrayList<T>;
var
__arrayList: TArrayList<T>;
public
function GetSize: Integer;
function IsEmpty: Boolean;
procedure EnQueue(e: T);
function DeQueue: T;
function Peek: T;
function GetCapactiy: Integer;
function ToString: string; override;
constructor Create(capacity: Integer = 10);
end;
procedure Main;
implementation
type
TArrayListQueue_int = TArrayListQueue<Integer>;
procedure Main;
var
queue: TArrayListQueue_int;
i: Integer;
begin
queue := TArrayListQueue_int.Create();
for i := 0 to 4 do
begin
queue.EnQueue(i);
Writeln(queue.ToString);
if i mod 3 = 2 then
begin
queue.DeQueue;
Writeln(queue.ToString);
end;
end;
end;
{ TArrayListQueue<T> }
constructor TArrayListQueue<T>.Create(capacity: Integer);
begin
__arrayList := TArrayList_T.Create();
end;
function TArrayListQueue<T>.DeQueue: T;
begin
Result := __arrayList.RemoveFirst;
end;
procedure TArrayListQueue<T>.EnQueue(e: T);
begin
__arrayList.AddLast(e);
end;
function TArrayListQueue<T>.GetCapactiy: Integer;
begin
Result := __arrayList.GetCapacity;
end;
function TArrayListQueue<T>.Peek: T;
begin
Result := __arrayList.GetFirst;
end;
function TArrayListQueue<T>.GetSize: Integer;
begin
Result := __arrayList.GetSize;
end;
function TArrayListQueue<T>.IsEmpty: Boolean;
begin
Result := __arrayList.IsEmpty;
end;
function TArrayListQueue<T>.ToString: string;
var
res: TStringBuilder;
i: Integer;
value: TValue;
a: T;
begin
res := TStringBuilder.Create;
try
res.AppendFormat('Queue: Size = %d, capacity = %d',
[Self.GetSize, Self.GetCapactiy]);
res.AppendLine;
res.Append(' front [');
for i := 0 to __arrayList.GetSize - 1 do
begin
a := __arrayList[i];
TValue.Make(@a, TypeInfo(T), value);
if not(value.IsObject) then
res.Append(value.ToString)
else
res.Append(value.AsObject.ToString);
if i <> __arrayList.GetSize - 1 then
res.Append(', ');
end;
res.Append('] tail');
Result := res.ToString;
finally
res.Free;
end;
end;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit uFileProvider;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
uCodeProvider, uConfig, uConst;
type
TFileProvider = class(TCodeProvider)
protected
procedure HookChanges; override;
procedure UnhookChanges; override;
public
function LoadStream(const AName: string): TStream; override;
procedure SaveStream(const AName: string; AStream: TStream); override;
function LocateFile(const AName: string): string; override;
end;
implementation
function TFileProvider.LoadStream(const AName: string): TStream;
begin
if AName <> '' then
begin
Feedback.Message(rsReading_ic + ' ' + AName);
Inc(LoadedCount);
Result := TFileStream.Create(AName, fmOpenRead);
AddChangeWatch(AName);
end
else
Result := nil;
end;
procedure TFileProvider.SaveStream(const AName: string; AStream: TStream);
var
fs: TFileStream;
begin
//inherited;
{ TODO : Make a backup before we save the file. }
fs := TFileStream.Create(AName, fmOpenWrite + fmShareDenyWrite);
try
fs.CopyFrom(AStream, 0);
finally
FreeAndNil(fs);
end;
end;
procedure TFileProvider.HookChanges;
begin
{ TODO : Attach a filesystem listener. }
end;
procedure TFileProvider.UnhookChanges;
begin
{ TODO : Dettach the filesystem listener. }
end;
function TFileProvider.LocateFile(const AName: string): string;
var
i: Integer;
p, adjName: string;
begin
Result := '';
adjName := SetDirSeparators(AName);
if ( Pos(Copy(AName,1,1),'\/')>0 ) or (Copy(AName,2,1)=':') then
begin
//Filename with an absolute path
if FileExists(adjName) then
Result := adjName;
end
else
begin
//Filename without a path, use searchpath to locate it.
for I := 0 to SearchPath.Count - 1 do
begin
if FileExists(SearchPath[I] + adjName) then
begin
Result := SearchPath[I] + adjName;
Break;
end;
end;
end;
// Add the searchpath of the file to searchpaths.
// It will only be added if it doesn't already exist in searchpaths
P := ExtractFilePath(Result);
if (P <> '') and (SearchPath.IndexOf(P) < 0) then
SearchPath.Add(P);
end;
end.
|
unit ConverterClasses;
interface
type
TTemperature = class
private
FValue : Extended;
protected
class function ToCelsius(AValue: Extended): Extended; virtual; abstract;
class function FromCelsius(AValue: Extended): Extended; virtual; abstract;
public
constructor Create(AValue: Extended = 0.0);
procedure AssignTemperature(ATemperature: TTemperature);
property Value: Extended read FValue write FValue;
property Temperature: TTemperature write AssignTemperature;
end;
TCelsius = class(TTemperature)
protected
class function ToCelsius(AValue: Extended): Extended; override;
class function FromCelsius(AValue: Extended): Extended; override;
end;
TFahrenheit = class(TTemperature)
protected
class function ToCelsius(AValue: Extended): Extended; override;
class function FromCelsius(AValue: Extended): Extended; override;
end;
TKelvin = class(TTemperature)
protected
class function ToCelsius(AValue: Extended): Extended; override;
class function FromCelsius(AValue: Extended): Extended; override;
end;
implementation
// from Celsius to Celsius
// Fahrenheit [F] = [C] x 9/5 + 32 [C] = ([F] - 32) x 5/9
// Kelvin [K] = [C] + 273.15 [C] = [K] - 273.15
// Rankine [R] = ([C] + 273.15) x 9/5 [C] = ([R] - 491.67) x 5/9
constructor TTemperature.Create(AValue: Extended);
begin
FValue := AValue;
end;
procedure TTemperature.AssignTemperature(ATemperature: TTemperature);
var
lCelsius: Extended;
begin
lCelsius := ATemperature.ToCelsius(ATemperature.Value);
Value := Self.FromCelsius(lCelsius);
end;
class function TCelsius.ToCelsius(AValue: Extended): Extended;
begin
Result := AValue;
end;
class function TCelsius.FromCelsius(AValue: Extended): Extended;
begin
Result := AValue;
end;
class function TFahrenheit.ToCelsius(AValue: Extended): Extended;
begin
Result := (AValue - 32) * 5 / 9;
end;
class function TFahrenheit.FromCelsius(AValue: Extended): Extended;
begin
Result := AValue * 9 / 5 + 32;
end;
class function TKelvin.ToCelsius(AValue: Extended): Extended;
begin
Result := AValue + 273.15;
end;
class function TKelvin.FromCelsius(AValue: Extended): Extended;
begin
Result := AValue - 273.15;
end;
end. |
{*******************************************************}
{ }
{ ConditionTypeFrame.pas
{ Copyright @2014/5/15 10:31:43 by 姜梁
{ }
{ 功能描述:添加文件类型条件判断的导航Frame
{ 函数说明:
{*******************************************************}
unit ConditionTypeFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, dDataModelSearchCondition, hHelperFunc,FormSetType;
type
TFrameType = class(TFrame)
lblType: TLabel;
chkSafe: TCheckBox;
btnSafeSet: TButton;
btnTypeSet: TButton;
lvName: TListView;
chkSize: TCheckBox;
edtSkip: TEdit;
lblSkip: TLabel;
procedure btnTypeSetClick(Sender: TObject);
private
MySreachCondition:TMySreachCondition;
public
procedure InitData(data:TMySreachCondition);
procedure GetMessage();
end;
implementation
{$R *.dfm}
{ TFrameType }
/// <summary>
/// 获取窗体数据
/// </summary>
procedure TFrameType.btnTypeSetClick(Sender: TObject);
var
I:Integer;
formSet: TTFormSetType;
temp:TListItem;
begin
formSet:= TTFormSetType.Create(Self);
formSet.TypeString := lvName.Items;
formSet.ShowModal;
if formSet.ModalResult = mrOk then
begin
lvName.Items.Clear;
for I := 0 to formSet.NewString.Count - 1 do
begin
temp:= lvName.Items.Add;
temp.Caption:= formSet.NewString[I];
temp.Checked := True;
end;
end;
formSet.NewString.Free;
formSet.Free;
end;
procedure TFrameType.GetMessage;
var
I:Integer;
begin
for I := 0 to lvName.Items.Count - 1 do
begin
if lvName.Items[I].Checked
then MySreachCondition.FileTypeList.Add(lvName.Items[i].Caption );
end;
if chkSafe.Checked then
begin
MySreachCondition.FileSkip:= GetSkip;
end else
begin
MySreachCondition.FileSkip.Clear;
end;
if chkSize.Checked then
begin
MySreachCondition.IsSize := StrToInt(edtSkip.Text)*1024;
end else
begin
MySreachCondition.IsSize := 0;
end;
end;
/// <summary>
/// 初始化窗体数据
/// </summary>
procedure TFrameType.InitData(data: TMySreachCondition);
var
I:Integer;
temp:TListItem;
begin
MySreachCondition:= data;
for I := 0 to MySreachCondition.FileTypeList.Count - 1 do
begin
temp:= lvName.Items.Add;
temp.Caption:= MySreachCondition.FileTypeList[I];
temp.SubItems.Add(GetTypeInReg(MySreachCondition.FileTypeList[I]));
temp.Checked := True;
end;
end;
end.
|
unit Rel_ContaPagaAvista;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Rel_Exemplo, RLReport, Data_Module,
Data.FMTBcd, Data.DB, Data.SqlExpr, Datasnap.Provider, Datasnap.DBClient;
type
TFm_RelContaPagaAvista = class(TFm_Rel_Exemplo)
DsTabela: TDataSource;
CdTabela: TClientDataSet;
DpTabela: TDataSetProvider;
SQLTabela: TSQLQuery;
SQLTabelaCOP_COD: TIntegerField;
SQLTabelaCOP_DESC: TStringField;
SQLTabelaCOP_VALOR: TFloatField;
SQLTabelaCOP_DATA_PAG: TDateField;
SQLTabelaCOP_N_PARCELAS: TIntegerField;
SQLTabelaCOP_FORN_FK: TIntegerField;
SQLTabelaCOP_OBS: TStringField;
SQLTabelaCOP_PARCELA: TStringField;
SQLTabelaCOP_SITUACAO: TStringField;
SQLTabelaCOP_VALOR_PARCELA: TFloatField;
CdTabelaCOP_COD: TIntegerField;
CdTabelaCOP_DESC: TStringField;
CdTabelaCOP_VALOR: TFloatField;
CdTabelaCOP_DATA_PAG: TDateField;
CdTabelaCOP_N_PARCELAS: TIntegerField;
CdTabelaCOP_FORN_FK: TIntegerField;
CdTabelaCOP_OBS: TStringField;
CdTabelaCOP_PARCELA: TStringField;
CdTabelaCOP_SITUACAO: TStringField;
CdTabelaCOP_VALOR_PARCELA: TFloatField;
RLLabel2: TRLLabel;
RLDBText1: TRLDBText;
RLDBMemo1: TRLDBMemo;
RLLabel3: TRLLabel;
RLDBMemo4: TRLDBMemo;
RLLabel6: TRLLabel;
RLLabel7: TRLLabel;
RLDBMemo5: TRLDBMemo;
RLLabel10: TRLLabel;
RLDBMemo7: TRLDBMemo;
SQLTabelaCOP_DATA_PAG_EFETUADO: TDateField;
CdTabelaCOP_DATA_PAG_EFETUADO: TDateField;
RLLabel11: TRLLabel;
RLDBResult2: TRLDBResult;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Fm_RelContaPagaAvista: TFm_RelContaPagaAvista;
implementation
{$R *.dfm}
end.
|
function Gerapercentual(valor:real;Percent:Real):real;
// Retorna a porcentagem de um valor
begin
percent := percent / 100;
try
valor := valor * Percent;
finally
result := valor;
end;
end;
|
program PongCentipede;
uses
SwinGame, sgTypes, SysUtils, StrUtils;
const
PADDLE_HEIGHT_RATIO = 5;
PADDLE_WIDTH_RATIO = 35;
BALL_SPEED = 10;
MOVE_SPEED = 5;
BALL_PREFIX = 'BallData:';
DEL = ',';
type
Ball = record
circ : Circle;
v : Vector;
active : Boolean;
end;
//Players = record
Player = record
pos : Integer;
paddle : Rectangle;
con : Connection;
receivedUpdate : Boolean;
end;
Players = Array of Player;
Balls = Array [0..7] of Ball;
//----------------------------------------------------------------------------
// GUI
//----------------------------------------------------------------------------
procedure InitPanel(var aMenuPanel : Panel);
begin
GUISetForegroundColor(ColorBlack);
GUISetBackgroundColor(ColorWhite);
ShowPanel(aMenuPanel);
ActivatePanel(aMenuPanel);
DrawGUIAsVectors(True);
end;
procedure SetLabelText();
begin
LabelSetText('MyIPLbl', 'My IP:');
LabelSetText('MyIPVal', MyIP());
LabelSetText('MyPorttLbl', 'Port: ');
LabelSetText('HostStatusLbl', 'Status: ');
LabelSetText('ServerLbl', 'Server:');
LabelSetText('ServerPorttLbl', 'Port: ');
LabelSetText('ClientStatusLbl', 'Status: ');
LabelSetText('ServerVal', '127.0.0.1');
end;
//----------------------------------------------------------------------------
// Establishing Connection
//----------------------------------------------------------------------------
function CreateHost() : LongInt;
var
lPort : Integer;
begin
result := -1;
if TryStrToInt(TextBoxText('MyPortVal'), lPort) then
begin
result := CreateUDPHost(lPort);
LabelSetText('HostStatusVal', 'Listening...');
LabelSetText('HostLbl', 'Disconnect');
end;
end;
function ConnectToHost() : Connection;
var
lPort : Integer;
begin
result := nil;
if TryStrToInt(TextBoxText('ServerPortVal'), lPort) then
begin
result := CreateUDPConnection(TextBoxText('ServerVal'), lPort, 0);
SendUDPMessage('AcceptMe:', result);
if Assigned(result) then
begin
LabelSetText('ClientStatusVal', 'Connected');
LabelSetText('ConnLbl', 'Disconnect');
end;
end;
end;
function HandleGUIInput( var aConnected, aIsHost : Boolean) : Connection;
begin
//Server Connect and Disconnect
result := nil;
if (RegionClickedID() = 'HostBtn') then
begin
aConnected := CreateHost() <> -1;
aIsHost := aConnected;
end
//Client Connect and Disconnect
else if (RegionClickedID() = 'ConnectBtn') then
begin
result := ConnectToHost();
if not Assigned(result) then exit;
aConnected := True;
aIsHost := False;
end;
end;
function SetupConnection(var aHostConnection : Connection) : Boolean;
var
lHostPanel, lClientPanel : Panel;
lConnectionIsSet : Boolean = False;
begin
LoadResourceBundle('MainMenu.txt');
lHostPanel := LoadPanel('hostpanel.txt');
lClientPanel := LoadPanel('clientpanel.txt');
InitPanel(lHostPanel);
InitPanel(lClientPanel);
SetLabelText();
repeat
ProcessEvents();
ClearScreen();
aHostConnection := HandleGUIInput(lConnectionIsSet, result);
DrawInterface();
UpdateInterface();
RefreshScreen(60);
until WindowCloseRequested() or lConnectionIsSet;
HidePanel(lHostPanel);
HidePanel(lClientPanel);
end;
//----------------------------------------------------------------------------
// Init Game Code
//----------------------------------------------------------------------------
procedure InitPlayer(var aPlayer : Player; aSide : char; aConnection : Connection);
begin
aPlayer.paddle.height := ScreenHeight div PADDLE_HEIGHT_RATIO;
aPlayer.paddle.width := ScreenWidth div PADDLE_WIDTH_RATIO;
aPlayer.paddle.y := Round((ScreenHeight div 2) - (aPlayer.paddle.height div 2));
aPlayer.con := aConnection;
case aSide of
'l' : aPlayer.paddle.x := Round(aPlayer.paddle.width * 3);
'r' : aPlayer.paddle.x := Round(ScreenWidth - aPlayer.paddle.width * 2);
'm' : aPlayer.paddle.x := Round((ScreenWidth div 2) - (aPlayer.paddle.width div 2));
end;
end;
procedure InitBalls(var aBalls : Balls);
var
i : Integer;
begin
for i:= Low(aBalls) to High(aBalls) do
begin
aBalls[i].circ.center.x := Round(ScreenWidth div 2);
aBalls[i].circ.center.y := Round(ScreenHeight div 2);
aBalls[i].circ.radius := (ScreenWidth div PADDLE_WIDTH_RATIO) div 2;
aBalls[i].v.x := BALL_SPEED;
aBalls[i].v.y := BALL_SPEED;
end;
end;
procedure InitHost(var aPlayers : Players; var aBalls : Balls);
begin
SetLength(aPlayers, 1);
InitPlayer(aPlayers[0], 'l', nil);
InitBalls(aBalls);
end;
function BallToString(const aBall : Ball) : String;
begin
result := IntToStr(Round(aBall.circ.center.x)) + DEL +
IntToStr(Round(aBall.circ.center.y));
end;
procedure AddPlayer(const aConnection : Connection; var aPlayers : Players; out aPlayerCount : Integer);
var
i : Integer;
begin
SetLength(aPlayers, Length(aPlayers) + 1);
InitPlayer(aPlayers[High(aPlayers)], 'r', aConnection);
aPlayerCount := Length(aPlayers);
for i := 1 to High(aPlayers) do
aPlayers[i].receivedUpdate := False;
end;
//----------------------------------------------------------------------------
// Ball Update
//----------------------------------------------------------------------------
procedure CollideCircleLine(var aBall : Ball; const line: LineSegment);
var
npx, npy, dotPod: Single;
toLine: Vector;
intersect: Point2D;
begin
//TODO: fix collision pt.... cast back along velocity...
intersect := ClosestPointOnLine(CenterPoint(aBall.circ), line);
toLine := UnitVector(VectorFromPoints(CenterPoint(aBall.circ), intersect));
// Project velocity across to-line
dotPod := - DotProduct(toLine, aBall.v);
npx := dotPod * toLine.x;
npy := dotPod * toLine.y;
aBall.v.x := aBall.v.x + 2 * npx;
aBall.v.y := aBall.v.y + 2 * npy;
end;
procedure CollideCircleRectangle(var aBall : Ball; const rect: Rectangle; bounds: Boolean); overload;
var
hitIdx: Longint;
lines: LinesArray;
outVec, mvmt: Vector;
begin
mvmt := aBall.v;
hitIdx := -1;
// Get the line hit...
lines := LinesFrom(rect);
outVec := VectorOverLinesFromCircle(aBall.circ, lines, mvmt, hitIdx);
// back out of rectangle
aBall.circ.center.x += outVec.x; //aBall.circ.center.x + (pct * mvmt.x);
aBall.circ.center.y += outVec.y;// aBall.circ.center.y + (pct * mvmt.y);
// MoveSprite(aBall, outVec, 1.0);
// bounce...
CollideCircleLine(aBall, lines[hitIdx]);
end;
procedure KeepBallOnScreen(var aBall : Ball; aGameWidth, aGameHeight : Integer);
begin
if ((aBall.circ.center.x - aBall.circ.radius) <= 0) then
begin
aBall.v.x := -aBall.v.x;
aBall.circ.center.x := aBall.circ.radius;
end else if ((aBall.circ.center.x + aBall.circ.radius) >= aGameWidth) then
begin
aBall.v.x := -aBall.v.x;
aBall.circ.center.x := aGameWidth - aBall.circ.radius;
end;
if ((aBall.circ.center.y - aBall.circ.radius) <= 0) then
begin
aBall.v.y := -aBall.v.y;
aBall.circ.center.y := aBall.circ.radius;
end else if ((aBall.circ.center.y + aBall.circ.radius) >= aGameHeight) then
begin
aBall.v.y := -aBall.v.y;
aBall.circ.center.y := aGameHeight - aBall.circ.radius;
end;
end;
procedure CollideCircleCircle(var aBallA : Ball; const aBallB: Ball);
var
hitLine: LineSegment;
outVec, mvmt, normal, colVec: Vector;
mvmtMag, prop: Single;
spriteCenter, hitPt: Point2D;
begin
//TODO: what if height > width!!
spriteCenter := CenterPoint(aBallA.circ);
mvmt := aBallA.v;
outVec := VectorOutOfCircleFromCircle(aBallA.circ, aBallB.circ, mvmt);
// Back out of circle
aBallA.circ.center.x += outVec.x; //aBall.circ.center.x + (pct * mvmt.x);
aBallA.circ.center.y += outVec.y;// aBall.circ.center.y + (pct * mvmt.y);
// Normal of the collision...
colVec := UnitVector(VectorFromPoints(aBallB.circ.center, spriteCenter));
normal := VectorNormal(colVec);
hitPt := AddVectors(aBallB.circ.center, VectorMultiply(colVec, Single(aBallB.circ.radius + 1.42)));
hitLine := LineFromVector(AddVectors(hitPt, VectorMultiply(normal, 100)), VectorMultiply(normal, -200));
CollideCircleLine(aBallA, hitLine);
// do part velocity
// mvmtMag := VectorMagnitude(mvmt);
// prop := VectorMagnitude(outVec) / mvmtMag; //proportion of move "undone" by back out
// if prop > 0 then MoveSprite(s, prop); //TODO: Allow proportion of move to be passed in (overload)... then do velocity based on prop * pct
end;
procedure UpdateBall(var aBall : Ball; var aBalls: Balls; const aPlayers : Players; const aGameWidth, aGameHeight, aIdx : Integer);
var
i, j : Integer;
begin
KeepBallOnScreen(aBall, aGameWidth, aGameHeight);
for i := Low(aBalls) to Length(aPlayers) - 1 do
begin
if (i = aIdx) then continue;
if (CircleCircleCollision(aBall.circ, aBalls[i].circ)) then
CollideCircleCircle(aBall, aBalls[i]);
end;
for i := Low(aPlayers) to High(aPlayers) do
begin
if CircleRectCollision(aBall.circ, aPlayers[i].paddle) then
CollideCircleRectangle(aBall, aPlayers[i].paddle, FALSE);
end;
aBall.circ.center.x += aBall.v.x;
aBall.circ.center.y += aBall.v.y;
end;
//----------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------
function ColorMap(aIndex : Integer) : Color;
begin
result := 0;
case aIndex of
0: result := ColorWhite;
1: result := ColorRed;
2: result := ColorGreen;
3: result := ColorBlue;
4: result := ColorYellow;
5: result := ColorTurquoise;
6: result := ColorMagenta;
end;
end;
procedure Draw(const aPlayer1 : Player; const aBalls : Balls; const aPlayerCount, aMyIdx: Integer);
var
i : Integer;
lCenterX, lCenterY : Single;
begin
lCenterX := aPlayer1.paddle.x + (aPlayer1.paddle.width div 2);
lCenterY := aPlayer1.paddle.y + (aPlayer1.paddle.height div 2);
FillRectangle(ColorMap(aMyIdx - 1), aPlayer1.paddle);
for i := Low(aBalls) to aPlayerCount - 1 do
begin
FillCircle(ColorMap(i), aBalls[i].circ);
DrawLine(ColorMap(i), lCenterX, lCenterY, aBalls[i].circ.center.x, aBalls[i].circ.center.y);
end;
end;
//----------------------------------------------------------------------------
// Ball Update
//----------------------------------------------------------------------------
procedure MovePlayer(var aPlayer : Player; const aIsHost : Boolean);
const
PLAYER_PREFIX = 'PlayerData:';
var
lMousePosY : Integer;
lRectCenter : Integer;
begin
if not MouseDown(LeftButton) then exit;
lMousePosY := Round(MouseY());
lRectCenter := Round(aPlayer.paddle.y + (aPlayer.paddle.height div 2));
if (lMousePosY < lRectCenter) and (aPlayer.paddle.y > 0) then
begin
if (lRectCenter - lMousePosY) < MOVE_SPEED then
aPlayer.paddle.y := lMousePosY - (aPlayer.paddle.height div 2)
else
aPlayer.paddle.y -= MOVE_SPEED;
if not aIsHost then SendUDPMessage(PLAYER_PREFIX + IntToStr(Round(aPlayer.paddle.y)), aPlayer.con)
end else if (lMousePosY > lRectCenter) and ((aPlayer.paddle.y + aPlayer.paddle.height) < ScreenHeight) then
begin
if (lMousePosY - lRectCenter) < MOVE_SPEED then
aPlayer.paddle.y := lMousePosY - (aPlayer.paddle.height div 2)
else
aPlayer.paddle.y += MOVE_SPEED;
if not aIsHost then SendUDPMessage(PLAYER_PREFIX + IntToStr(Round(aPlayer.paddle.y)), aPlayer.con);
end;
end;
procedure SetPlayerPosition(var aPlayer : Player; const aMyIdx, aPlayerCount, aGameWidth : Integer);
begin
if (aMyIDx = aPlayerCount) then
aPlayer.paddle.x :=(aGameWidth * aPlayerCount) - Round(aPlayer.paddle.width * 3)
else
aPlayer.paddle.x :=(aGameWidth * aMyIdx) - Round(aPlayer.paddle.width div 2) - (aGameWidth div 2);
end;
procedure ObtainGameData(var aPlayer : Player; var aBalls : Balls; var aMyIdx : Integer; var aGameWidth, aGameHeight, aPlayerCount : Integer; var aConnected : Boolean);
var
lGameSet : Boolean = False;
lBallSet : Boolean = False;
lMessageID, lData : String;
i : Integer;
lMessageReceived : Boolean = False;
const
NUM_OF_PACKET_CHECKS = 20;
begin
for i := 0 to NUM_OF_PACKET_CHECKS do
begin
if UDPMessageReceived() then
lMessageReceived := True
else
break;
end;
if (lMessageReceived) then
begin
aConnected := True;
lMessageID := ReadLastMessage(aPlayer.con);
ClearMessageQueue(aPlayer.con);
if (ExtractDelimited(1, lMessageID, [':']) = 'GameData') then
begin
lData := ExtractDelimited(2, lMessageID, [':']);
aGameWidth := StrToInt(ExtractDelimited(1, lData, [',']));
aGameHeight := StrToInt(ExtractDelimited(2, lData, [',']));
aMyIdx := StrToInt(ExtractDelimited(3, lData, [',']));
//aPlayer.paddle.x := StrToInt(ExtractDelimited(4, lData, [',']));
SetCameraX(aGameWidth * (aMyIDx -1));
aPlayerCount := StrToInt(ExtractDelimited(4, lData, [',']));
SetPlayerPosition(aPlayer, aMyIdx, aPlayerCount, aGameWidth);
for i := Low(aBalls) to High(aBalls) do
begin
aBalls[i].circ.center.x := StrToInt(ExtractDelimited(5 + i * 2, lData, [',']));
aBalls[i].circ.center.y := StrToInt(ExtractDelimited(6 + i * 2, lData, [',']));
end;
end;
end;
end;
procedure UpdateClientPosition(var aPlayers : Players);
var
i : Integer;
lMsg : String;
begin
for i := 1 to High(aPlayers) do
begin
if MessageCount(aPlayers[i].con) > 0 then
begin
lMsg := ReadMessage(aPlayers[i].con);
WriteLn(lMsg);
if (ExtractDelimited(1, lMsg, [':']) = 'PlayerData') then
aPlayers[i].paddle.y := StrToInt(ExtractDelimited(2, lMsg, [':']));
if (ExtractDelimited(1, lMsg, [':']) = 'Received') then
begin
WriteLn('Received');
aPlayers[i].receivedUpdate := True;
end;
end;
end;
end;
procedure BroadcastGameData(var aPlayers : Players; aGameWidth, aGameHeight : Integer; const aBalls : Balls);
var
i : Integer;
lMsg : String;
lGameData, lBallData : String;
const
GAME_PREFIX = 'GameData:';
NEW_SIDE = 'RIGHT';
begin
lGameData := GAME_PREFIX + IntToStr(aGameWidth) + DEL + IntToStr(aGameHeight) + DEL;
lBallData := '';
for i := Low(aBalls) to High(aBalls) do
lBallData += DEL + BallToString(aBalls[i]);
for i := 1 to High(aPlayers) do
begin
lMsg := lGameData + IntToStr(i + 1);
lMsg := lMsg + DEL + IntToStr(Length(aPlayers)) + lBallData;
SetPlayerPosition(aPlayers[i], i+1, Length(aPlayers), aGameWidth);
SendUDPMessage(lMsg , aPlayers[i].con);
end;
end;
procedure HandleClient(var aPlayer : Player; var aBalls : Balls; const aPlayerCount, aMyIDX : Integer);
var
lPlayerMessage : String;
begin
MovePlayer(aPlayer, False);
Draw(aPlayer, aBalls, aPlayerCount, aMyIDX);
end;
procedure HandleHost(var aPlayers : Players; var aBalls : Balls; const aGameWidth, aGameHeight, aPlayerCount, aMyIDX : Integer);
var
i : Integer;
begin
for i := Low(Balls) to Length(aPlayers) - 1 do
UpdateBall(aBalls[i], aBalls, aPlayers, aGameWidth * Length(aPlayers), aGameHeight, i);
MovePlayer(aPlayers[0], True);
BroadcastGameData(aPlayers, aGameWidth, aGameHeight, aBalls);
Draw(aPlayers[0], aBalls, aPlayerCount, aMyIDX);
end;
procedure Main();
var
lBalls : Balls;
lPlayers : Players;
lHostConnection : Connection;
lIsHost : Boolean = True;
lConnected : Boolean = False;
lPlayer : Player;
lMyIDX, lGameWidth, lGameHeight, lPlayerCount : Integer;
begin
OpenGraphicsWindow('Pong Centipede', 960, 640);
LoadDefaultColors();
lPlayerCount := 1;
lIsHost := SetupConnection(lHostConnection);
if (lIsHost) then
begin
InitHost(lPlayers, lBalls);
lGameWidth := ScreenWidth;
lGameHeight:= ScreenHeight;
lMyIDX := 1;
end else begin
InitPlayer(lPlayer, 'r', lHostConnection);
InitBalls(lBalls);
end;
repeat
if lIsHost then
begin
UDPMessageReceived();
if (ConnectionQueueSize() > 0) then
AddPlayer(FetchConnection(), lPlayers, lPlayerCount);
UpdateClientPosition(lPlayers);
end else begin
ObtainGameData(lPlayer, lBalls, lMyIdx, lGameWidth, lGameHeight, lPlayerCount, lConnected);
end;
ProcessEvents();
ClearScreen();
if not lIsHost and not lConnected then
begin
SendUDPMessage('AcceptMe:', lHostConnection);
continue;
end;
if (lIsHost) then HandleHost(lPlayers, lBalls, lGameWidth, lGameHeight, lPlayerCount, lMyIDX)
else begin HandleClient(lPlayer, lBalls, lPlayerCount, lMyIDX); end;
DrawFrameRate(0,0);
RefreshScreen(60);
until WindowCloseRequested();
end;
begin
Main();
end. |
unit uModSO;
interface
uses
uModApp, uModSatuan, uModUnit, uModBarang, uModSuplier,
System.Generics.Collections, System.SysUtils;
type
TModSODetail = class;
TModSO = class(TModApp)
private
FAUTUNIT: TModUnit;
FSODetails: TObjectList<TModSODetail>;
FMerchandise: TModMerchandise;
FSO_DATE: TDatetime;
FSO_NO: string;
FSupplierMerchan: TModSuplierMerchanGroup;
function GetSODetails: TObjectList<TModSODetail>;
public
property SODetails: TObjectList<TModSODetail> read GetSODetails write
FSODetails;
published
[AttributeOfForeign('AUT$UNIT_ID')]
property AUTUNIT: TModUnit read FAUTUNIT write FAUTUNIT;
[AttributeOfForeign('REF$MERCHANDISE_ID')]
property Merchandise: TModMerchandise read FMerchandise write FMerchandise;
property SO_DATE: TDatetime read FSO_DATE write FSO_DATE;
[AttributeOfCode]
property SO_NO: string read FSO_NO write FSO_NO;
[AttributeOfForeign('SUPLIER_MERCHAN_GRUP_ID')]
property SupplierMerchan: TModSuplierMerchanGroup read FSupplierMerchan write
FSupplierMerchan;
end;
TModSODetail = class(TModApp)
private
FBARANG_SUPPLIER: TModBarangSupplier;
FBARANG: TModBarang;
FSO: TModSO;
FSOD_DISC1: Double;
FSOD_DISC2: Double;
FSOD_DISC3: Double;
FSOD_IS_BKP: Integer;
FSOD_IS_ORDERED: Integer;
FSOD_IS_REGULAR: Integer;
FSOD_PRICE: Double;
FSOD_QTY: Double;
FSOD_TOTAL: Double;
FSOD_TOTAL_DISC: Double;
FSatuan: TModSatuan;
FSOD_ADS: Double;
FSOD_IS_STOCK: Integer;
FSOD_QTYSO: Double;
FSOD_STOCK: Double;
FSOD_ROP: Double;
FSupplierMerchan: TModSuplierMerchanGroup;
public
class function GetTableName: String; override;
published
[AttributeOfForeign('BARANG_SUPLIER_ID')]
property BARANG_SUPPLIER: TModBarangSupplier read FBARANG_SUPPLIER write
FBARANG_SUPPLIER;
property BARANG: TModBarang read FBARANG write FBARANG;
[AttributeOfHeader('SO_ID')]
property SO: TModSO read FSO write FSO;
property SOD_DISC1: Double read FSOD_DISC1 write FSOD_DISC1;
property SOD_DISC2: Double read FSOD_DISC2 write FSOD_DISC2;
property SOD_DISC3: Double read FSOD_DISC3 write FSOD_DISC3;
property SOD_IS_BKP: Integer read FSOD_IS_BKP write FSOD_IS_BKP;
property SOD_IS_ORDERED: Integer read FSOD_IS_ORDERED write FSOD_IS_ORDERED;
property SOD_IS_REGULAR: Integer read FSOD_IS_REGULAR write FSOD_IS_REGULAR;
property SOD_PRICE: Double read FSOD_PRICE write FSOD_PRICE;
property SOD_QTY: Double read FSOD_QTY write FSOD_QTY;
//1 soD_PRICE * SOD_QTY
property SOD_TOTAL: Double read FSOD_TOTAL write FSOD_TOTAL;
property SOD_TOTAL_DISC: Double read FSOD_TOTAL_DISC write FSOD_TOTAL_DISC;
[AttributeOfForeign('Ref$Satuan_ID')]
property Satuan: TModSatuan read FSatuan write FSatuan;
property SOD_ADS: Double read FSOD_ADS write FSOD_ADS;
property SOD_IS_STOCK: Integer read FSOD_IS_STOCK write FSOD_IS_STOCK;
property SOD_QTYSO: Double read FSOD_QTYSO write FSOD_QTYSO;
property SOD_STOCK: Double read FSOD_STOCK write FSOD_STOCK;
property SOD_ROP: Double read FSOD_ROP write FSOD_ROP;
[AttributeOfForeign('SUPLIER_MERCHAN_GRUP_ID')]
property SupplierMerchan: TModSuplierMerchanGroup read FSupplierMerchan write
FSupplierMerchan;
end;
implementation
function TModSO.GetSODetails: TObjectList<TModSODetail>;
begin
If not Assigned(FSODetails) then
FSODetails := TObjectList<TModSODetail>.Create;
Result := FSODetails;
end;
class function TModSODetail.GetTableName: String;
begin
Result := 'SO_DETAIL';
end;
initialization
TModSO.RegisterRTTI;
TModSODetail.RegisterRTTI;
end.
|
unit CrudExampleHorseServer.Model.Entidade.Cadastro;
interface
uses
SimpleAttributes;
type
TCADASTRO = class
private
FID: Integer;
FNAME: string;
FEMAIL: string;
procedure SetID(const aValue: Integer);
procedure SetNAME(const aValue: string);
procedure SetEMAIL(const aValue: string);
function GetThis: TCADASTRO;
public
constructor Create;
destructor Destroy; override;
published
[PK]
property ID: Integer read FID write SetID;
property NAME: string read FNAME write SetName;
property EMAIL: string read FEMAIL write SetEmail;
end;
implementation
{ TCADASTRO }
constructor TCADASTRO.Create;
begin
end;
destructor TCADASTRO.Destroy;
begin
inherited;
end;
function TCADASTRO.GetThis: TCADASTRO;
begin
Result:=Self;
end;
procedure TCADASTRO.SetEmail(const aValue: string);
begin
FEmail := aValue;
end;
procedure TCADASTRO.SetID(const aValue: Integer);
begin
FID := aValue;
end;
procedure TCADASTRO.SetName(const aValue: string);
begin
FName := aValue;
end;
{
procedure TForm9.btnFindClick(Sender: TObject);
var
Pedidos : TList<TPEDIDO>;
Pedido : TPEDIDO;
begin
Pedidos := DAOPedido.SQL.OrderBy('ID').&End.Find;
try
for Pedido in Pedidos do
begin
Memo1.Lines.Add(Pedido.NOME + DateToStr(Pedido.DATA));
end;
finally
Pedidos.Free;
end;
end;
, DataSetConverter4D
, DataSetConverter4D.Util
, DataSetConverter4D.Helper
, DataSetConverter4D.Impl
}
end.
|
//**********************************************************************************************************************
// $Id: udFind.pas,v 1.7 2006-08-23 15:19:11 dale Exp $
//----------------------------------------------------------------------------------------------------------------------
// DKLang Translation Editor
// Copyright ęDK Software, http://www.dk-soft.org/
//**********************************************************************************************************************
unit udFind;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ConsVars,
DKLTranEdFrm, DKLang, TntExtCtrls, StdCtrls, TntStdCtrls;
type
TdFind = class(TDKLTranEdForm)
bAll: TTntButton;
bClose: TTntButton;
bHelp: TTntButton;
bOK: TTntButton;
cbCaseSensitive: TTntCheckBox;
cbPattern: TTntComboBox;
cbPrompt: TTntCheckBox;
cbReplace: TTntCheckBox;
cbReplacePattern: TTntComboBox;
cbSearchNames: TTntCheckBox;
cbSearchOriginal: TTntCheckBox;
cbSearchTranslated: TTntCheckBox;
cbSelOnly: TTntCheckBox;
cbWholeWords: TTntCheckBox;
dklcMain: TDKLanguageController;
gbOptions: TTntGroupBox;
gbScope: TTntGroupBox;
lPattern: TTntLabel;
rgDirection: TTntRadioGroup;
rgOrigin: TTntRadioGroup;
procedure bAllClick(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure cbReplaceClick(Sender: TObject);
procedure DlgDataChange(Sender: TObject);
private
// Procedure invoked when user starts search/replace
FFindCallback: TFindCallback;
// MRU lists
FSearchMRUStrings: TStrings;
FReplaceMRUStrings: TStrings;
// Called whenever dialog or its controls state changed
procedure StateChanged;
// Starts searching/replacement
procedure DoFind(bAll: Boolean);
protected
procedure DoCreate; override;
procedure ExecuteInitialize; override;
end;
function ShowFindDialog(AFindCallback: TFindCallback; ASearchMRUStrings, AReplaceMRUStrings: TStrings): Boolean;
implementation
{$R *.dfm}
function ShowFindDialog(AFindCallback: TFindCallback; ASearchMRUStrings, AReplaceMRUStrings: TStrings): Boolean;
begin
with TdFind.Create(Application) do
try
FFindCallback := AFindCallback;
FSearchMRUStrings := ASearchMRUStrings;
FReplaceMRUStrings := AReplaceMRUStrings;
Result := ExecuteModal;
finally
Free;
end;
end;
//===================================================================================================================
// TdFind
//===================================================================================================================
procedure TdFind.bAllClick(Sender: TObject);
begin
DoFind(True);
end;
procedure TdFind.bOKClick(Sender: TObject);
begin
DoFind(False);
end;
procedure TdFind.cbReplaceClick(Sender: TObject);
begin
if Visible then begin
StateChanged;
if cbReplacePattern.CanFocus then cbReplacePattern.SetFocus;
end;
end;
procedure TdFind.DlgDataChange(Sender: TObject);
begin
if Visible then StateChanged;
end;
procedure TdFind.DoCreate;
begin
inherited DoCreate;
// Initialize help context ID
HelpContext := IDH_iface_dlg_find;
end;
procedure TdFind.DoFind(bAll: Boolean);
begin
// Clear the search-from-the-next flag on invoke
Exclude(SearchParams.Flags, sfFromNext);
// Save search parameters
SearchParams.wsSearchPattern := cbPattern.Text;
SearchParams.wsReplacePattern := cbReplacePattern.Text;
SearchParams.Flags := [];
if cbReplace.Checked then Include(SearchParams.Flags, sfReplace);
if cbCaseSensitive.Checked then Include(SearchParams.Flags, sfCaseSensitive);
if cbWholeWords.Checked then Include(SearchParams.Flags, sfWholeWordsOnly);
if cbSelOnly.Checked then Include(SearchParams.Flags, sfSelectedOnly);
if cbPrompt.Checked then Include(SearchParams.Flags, sfPromptOnReplace);
if cbSearchNames.Checked then Include(SearchParams.Flags, sfSearchNames);
if cbSearchOriginal.Checked then Include(SearchParams.Flags, sfSearchOriginal);
if cbSearchTranslated.Checked then Include(SearchParams.Flags, sfSearchTranslated);
if rgOrigin.ItemIndex=1 then Include(SearchParams.Flags, sfEntireScope);
if rgDirection.ItemIndex=1 then Include(SearchParams.Flags, sfBackward);
if bAll then Include(SearchParams.Flags, sfReplaceAll);
// Invoke the search function
Hide;
try
if FFindCallback(SearchParams) then ModalResult := mrOK;
finally
if ModalResult<>mrOK then Show;
end;
end;
procedure TdFind.ExecuteInitialize;
begin
inherited ExecuteInitialize;
// Initialize the controls
cbPattern.Items.Assign(FSearchMRUStrings);
cbReplacePattern.Items.Assign(FReplaceMRUStrings);
cbPattern.Text := SearchParams.wsSearchPattern;
cbReplace.Checked := sfReplace in SearchParams.Flags;
cbReplacePattern.Text := SearchParams.wsReplacePattern;
cbCaseSensitive.Checked := sfCaseSensitive in SearchParams.Flags;
cbWholeWords.Checked := sfWholeWordsOnly in SearchParams.Flags;
cbSelOnly.Checked := sfSelectedOnly in SearchParams.Flags;
cbPrompt.Checked := sfPromptOnReplace in SearchParams.Flags;
cbSearchNames.Checked := sfSearchNames in SearchParams.Flags;
cbSearchOriginal.Checked := sfSearchOriginal in SearchParams.Flags;
cbSearchTranslated.Checked := sfSearchTranslated in SearchParams.Flags;
rgOrigin.ItemIndex := iif(sfEntireScope in SearchParams.Flags, 1, 0);
rgDirection.ItemIndex := iif(sfBackward in SearchParams.Flags, 1, 0);
StateChanged;
end;
procedure TdFind.StateChanged;
var bReplaceMode, bPattern, bScope: Boolean;
begin
bReplaceMode := cbReplace.Checked;
bPattern := cbPattern.Text<>'';
bScope := cbSearchTranslated.Checked or
(not bReplaceMode and (cbSearchNames.Checked or cbSearchOriginal.Checked));
EnableWndCtl(cbReplacePattern, bReplaceMode);
cbPrompt.Enabled := bReplaceMode;
cbSearchNames.Enabled := not bReplaceMode;
cbSearchOriginal.Enabled := not bReplaceMode;
bOK.Enabled := bPattern and bScope;
bOK.Caption := DKLangConstW(iif(bReplaceMode, 'SBtn_Replace', 'SBtn_Find'));
bAll.Enabled := bReplaceMode and bPattern and bScope;
end;
end.
|
unit Datapar.Conexao.FireDac;
interface
uses
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, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, Datapar.Conexao,
FireDAC.Phys.OracleDef, FireDAC.Phys.Oracle, FireDAC.FMXUI.Wait,
FireDAC.Comp.UI,
FireDAC.VCLUI.Wait;
type
TFireQuery = class(TDataparQuery)
strict private
FConnection : TFDConnection;
FQuery: TFDQuery;
public
constructor create(AProvider: TDataparProvider);
function executaSql(ACommand: TDataparCommand): TDataSet; override;
end;
implementation
{ TFireQuery }
constructor TFireQuery.create(AProvider: TDataparProvider);
begin
if FConnection = nil then
begin
FConnection := TFDConnection.Create(Nil);
FConnection.DriverName := 'ORA';
FConnection.Params.Database := AProvider.Host;
FConnection.Params.UserName := AProvider.User;
FConnection.Params.Password := Aprovider.Password;
end;
FConnection.Connected := True;
end;
function TFireQuery.executaSql(ACommand: TDataparCommand): TDataSet;
begin
FQuery:= TFDQuery.Create(Nil);
FQuery.Connection := FConnection;
FQuery.SQL.Add(ACommand.SQL);
FQuery.Active := True;
Result := FQuery;
end;
end.
|
unit uHelpButton;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, uHelpForm;
type
TFormOrientation = (fTopToBottom,fBottomToTop);
TOilHelpButton = class(TSpeedButton)
private
FLines: TStrings;
FHelpForm: THelpForm;
FOwner: TComponent;
FCaptionText: string;
FHeaderColor: TColor;
FHeaderFont: TFont;
FRichEditColor: TColor;
FAnimate: boolean;
FHelpFileName: string;
FUseCurrentDir: boolean;
FFormOrientation: TFormOrientation;
FAnimateTime: integer;
FImages: TImageList;
FImageIndex: integer;
FFormWidth: integer;
FFormHeight: integer;
procedure SetLines(const Value: TStrings);
procedure ShowHelpForm(Sender: TObject);
procedure SetFHeaderFont(const Value: TFont);
procedure SetHelpFileName(const Value: string);
procedure OnFormShow(Sender:TObject);
procedure OnFormClose(Sender: TObject; var Action: TCloseAction);
procedure SetImageIndex(const Value: integer);
procedure SetImages(const Value: TImageList);
protected
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
published
property AnimateTime : integer read FAnimateTime write FAnimateTime;
property Lines : TStrings read FLines write SetLines;
property HeaderColor: TColor read FHeaderColor write FHeaderColor default clSilver;
property HeaderText: string read FCaptionText write FCaptionText;
property HeaderFont: TFont read FHeaderFont write SetFHeaderFont;
property RichEditColor: TColor read FRichEditColor write FRichEditColor default clWhite;
property Animate : boolean read FAnimate write FAnimate;
property HelpFileName : string read FHelpFileName write SetHelpFileName;
property UseCurrentDir : boolean read FUseCurrentDir write FUseCurrentDir;
property FormOrientation : TFormOrientation read FFormOrientation write FFormOrientation;
property Images : TImageList read FImages write SetImages;
property ImageIndex : integer read FImageIndex write SetImageIndex;
end;
procedure Register;
implementation
uses URichEditFormat;
procedure Register;
begin
RegisterComponents('Oil', [TOilHelpButton]);
end;
{ TOilHelpButton }
//==============================================================================
constructor TOilHelpButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLines := TStringList.Create;
FHeaderFont := TFont.Create;
FOwner := AOwner;
OnClick := ShowHelpForm;
FHeaderColor := clSilver;
FRichEditColor := clWhite;
FFormOrientation:=fBottomToTop;
FAnimateTime := 200;
FCaptionText := Self.Name;
FImageIndex:=-1;
AllowAllUp:=TRUE;
GroupIndex:=1001;
Width:=25;
Height:=25;
end;
//==============================================================================
destructor TOilHelpButton.Destroy;
begin
FLines.Free;
FHeaderFont.Free;
inherited Destroy;
end;
//==============================================================================
procedure TOilHelpButton.SetFHeaderFont(const Value: TFont);
begin
if Assigned(Value)
then FHeaderFont := Value;
end;
//==============================================================================
procedure TOilHelpButton.SetLines(const Value: TStrings);
begin
if Assigned(Value)
then FLines.Assign(Value);
end;
//==============================================================================
procedure TOilHelpButton.ShowHelpForm(Sender: TObject);
var
P: TPoint;
begin
if Down then begin
FHelpForm := THelpForm.Create(FOwner);
with FHelpForm do
begin
GetCursorPos(P);
if FHelpFileName <> ''
then FLines.LoadFromFile(FHelpFileName);
SetRichEditText(FHelpForm.RichEdit,Lines.Text);
RichEdit.Color := Self.RichEditColor;
Caption:=Self.HeaderText;
//pnlTop.Color := Self.HeaderColor;
//pnlTop.Caption := Self.HeaderText;
if FormOrientation = fBottomToTop
then Top := P.y-Height
else Top := P.y;
Left := p.x;
OnShow := OnFormShow;
OnClose := OnFormClose;
Width := Screen.Width div 2;
Height := Screen.Height-100;
Top :=0;
Left := Screen.Width div 2;
Show;
end;
end else
FHelpForm.Free;
end;
//==============================================================================
procedure TOilHelpButton.SetHelpFileName(const Value: string);
begin
if not FileExists(Value)
then ShowMessage('File '+Value+' does not exists')
else FHelpFileName := Value;
end;
//==============================================================================
procedure TOilHelpButton.OnFormShow(Sender: TObject);
begin
{ if Animate then
if FormOrientation = fTopToBottom
then AnimateWindow(FHelpForm.Handle, AnimateTime, AW_HOR_POSITIVE or AW_VER_POSITIVE)
else AnimateWindow(FHelpForm.Handle, AnimateTime, AW_HOR_POSITIVE or AW_VER_NEGATIVE);}
FHelpForm.RichEdit.Repaint;
FHelpForm.pnlTop.Repaint;
end;
//==============================================================================
procedure TOilHelpButton.OnFormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
Down:=FALSE;
end;
//==============================================================================
procedure TOilHelpButton.SetImages(const Value: TImageList);
begin
FImages := Value;
if FImages <> nil then
FImages.FreeNotification(Self);
if (FImageIndex<>-1) and (FImages<>nil) then
FImages.GetBitmap(FImageIndex,Glyph);
end;
//==============================================================================
procedure TOilHelpButton.SetImageIndex(const Value: integer);
begin
FImageIndex := Value;
if (FImageIndex<>-1) and (FImages<>nil) then
FImages.GetBitmap(FImageIndex,Glyph);
end;
//==============================================================================
end.
|
unit LA.GramSchmidtProcess;
interface
uses
System.SysUtils,
LA.Matrix,
LA.Vector,
LA.ArrayList,
LA.LinearSystem;
type
TVecList = TArrayList<TVector>;
TQR = record
Q, R: PMatrix;
end;
function GramSchmidtProcess(basis: TVectorArr): TVecList;
function QR(a: TMatrix): TQR;
implementation
function GramSchmidtProcess(basis: TVectorArr): TVecList;
var
ret: TVecList;
mtx: TMatrix;
i, j: integer;
p: TVector;
begin
mtx := TMatrix.Create(basis);
if Rank(mtx) <> Length(basis) then
raise Exception.Create('Rank(mtx) <> Length(basis)');
ret := TVecList.Create(Length(basis));
ret.AddLast(basis[0]);
for i := 1 to Length(basis) - 1 do
begin
p := basis[i];
for j := 0 to ret.GetSize - 1 do
p := p - basis[i].Dot(ret[j]) / ret[j].Dot(ret[j]) * ret[j];
ret.AddLast(p);
end;
Result := ret;
end;
function QR(a: TMatrix): TQR;
var
p: TVecList;
basis, vecArr: TVectorArr;
ret: TQR;
i: integer;
Q, R: TMatrix;
begin
if a.Row_num <> a.Col_num then
raise Exception.Create('A must be square');
SetLength(basis, a.Col_num);
for i := 0 to a.Col_num - 1 do
basis[i] := a.Get_Col_vector(i);
p := GramSchmidtProcess(basis);
new(ret.Q);
new(ret.R);
SetLength(vecArr, p.GetSize);
for i := 0 to p.GetSize - 1 do
vecArr[i] := p[i] / p[i].Norm;
Q := TMatrix.Create(vecArr).Transpose;
R := Q.Transpose.Dot(a);
ret.Q^ := Q;
ret.R^ := R;
Result := ret;
end;
end.
|
unit Win32.AVIFMT;
(****************************************************************************)
(* *)
(* AVIFMT.H - Include file for working with AVI files *)
(* *)
(* Note: You must include WINDOWS.H and MMSYSTEM.H before *)
(* including this file. *)
(* *)
(* Copyright (c) 1991-1998, Microsoft Corp. All rights reserved. *)
(* *)
(* *)
(****************************************************************************)
{$mode delphi}
interface
uses
Windows, Classes, SysUtils;
const
_INC_AVIFMT = 100; (* version number * 100 + revision *)
formtypeAVI =
Ord('A') or (Ord('V') shl 8) or (Ord('I') shl 16) or (Ord(' ') shl 24);
formtypeAVIX = Ord('A') or (Ord('V') shl 8) or
(Ord('I') shl 16) or (Ord('X') shl 24);
listtypeAVIHEADER = Ord('h') or (Ord('d') shl 8) or
(Ord('r') shl 16) or (Ord('l') shl 24);
ckidAVIMAINHDR = Ord('a') or (Ord('v') shl 8) or
(Ord('i') shl 16) or (Ord('h') shl 24);
listtypeSTREAMHEADER =
Ord('s') or (Ord('t') shl 8) or (Ord('r') shl 16) or (Ord('l') shl 24);
ckidSTREAMHEADER = Ord('s') or (Ord('t') shl 8) or
(Ord('r') shl 16) or (Ord('h') shl 24);
ckidSTREAMFORMAT = Ord('s') or (Ord('t') shl 8) or
(Ord('r') shl 16) or (Ord('f') shl 24);
ckidSTREAMHANDLERDATA =
Ord('s') or (Ord('t') shl 8) or (Ord('r') shl 16) or (Ord('d') shl 24);
ckidSTREAMNAME = Ord('s') or (Ord('t') shl 8) or
(Ord('r') shl 16) or (Ord('n') shl 24);
listtypeAVIMOVIE = Ord('m') or (Ord('o') shl 8) or
(Ord('v') shl 16) or (Ord('i') shl 24);
listtypeAVIRECORD = Ord('r') or (Ord('e') shl 8) or
(Ord('c') shl 16) or (Ord(' ') shl 24);
ckidAVINEWINDEX = Ord('i') or (Ord('d') shl 8) or
(Ord('x') shl 16) or (Ord('1') shl 24);
(* Stream types for the <fccType> field of the stream header. *)
streamtypeVIDEO = Ord('v') or (Ord('i') shl 8) or
(Ord('d') shl 16) or (Ord('s') shl 24);
streamtypeAUDIO = Ord('a') or (Ord('u') shl 8) or
(Ord('d') shl 16) or (Ord('s') shl 24);
streamtypeMIDI = Ord('m') or (Ord('i') shl 8) or
(Ord('d') shl 16) or (Ord('s') shl 24);
streamtypeTEXT = Ord('t') or (Ord('x') shl 8) or
(Ord('t') shl 16) or (Ord('s') shl 24);
(* Basic chunk types *)
cktypeDIBbits = Ord('d') or (Ord('b') shl 8);
cktypeDIBcompressed = Ord('d') or (Ord('c') shl 8);
cktypePALchange = Ord('p') or (Ord('c') shl 8);
cktypeWAVEbytes = Ord('w') or (Ord('b') shl 8);
cktypeDVFrame = Ord('_') or (Ord('_') shl 8);
(* Chunk id to use for extra chunks for padding. *)
ckidAVIPADDING = Ord('J') or (Ord('U') shl 8) or
(Ord('N') shl 16) or (Ord('K') shl 24);
(* flags for use in <dwFlags> in AVIFileHdr *)
AVIF_HASINDEX = $00000010; // Index at end of file
AVIF_MUSTUSEINDEX = $00000020;
AVIF_ISINTERLEAVED = $00000100;
AVIF_TRUSTCKTYPE = $00000800; // Use CKType to find key frames
AVIF_WASCAPTUREFILE = $00010000;
AVIF_COPYRIGHTED = $00020000;
(* The AVI File Header LIST chunk should be padded to this size *)
AVI_HEADERSIZE = 2048; // size of AVI header list
AVISF_DISABLED = $00000001;
AVISF_VIDEO_PALCHANGES = $00010000;
(* Flags for index *)
AVIIF_LIST = $00000001; // chunk is a 'LIST'
AVIIF_KEYFRAME = $00000010; // this frame is a key frame.
AVIIF_FIRSTPART = $00000020; // this frame is the start of a partial frame.
AVIIF_LASTPART = $00000040; // this frame is the end of a partial frame.
AVIIF_MIDPART = (AVIIF_LASTPART or AVIIF_FIRSTPART);
AVIIF_NOTIME = $00000100; // this frame doesn't take any time
AVIIF_COMPUSE = $0FFF0000; // these bits are for compressor use
type
(* The following is a short description of the AVI file format. Please
* see the accompanying documentation for a full explanation.
*
* An AVI file is the following RIFF form:
*
* RIFF('AVI'
* LIST('hdrl'
* avih(<MainAVIHeader>)
* LIST ('strl'
* strh(<Stream header>)
* strf(<Stream format>)
* ... additional header data
* LIST('movi'
* { LIST('rec'
* SubChunk...
* )
* | SubChunk } ....
* )
* [ <AVIIndex> ]
* )
*
* The main file header specifies how many streams are present. For
* each one, there must be a stream header chunk and a stream format
* chunk, enlosed in a 'strl' LIST chunk. The 'strf' chunk contains
* type-specific format information; for a video stream, this should
* be a BITMAPINFO structure, including palette. For an audio stream,
* this should be a WAVEFORMAT (or PCMWAVEFORMAT) structure.
*
* The actual data is contained in subchunks within the 'movi' LIST
* chunk. The first two characters of each data chunk are the
* stream number with which that data is associated.
*
* Some defined chunk types:
* Video Streams:
* ##db: RGB DIB bits
* ##dc: RLE8 compressed DIB bits
* ##pc: Palette Change
*
* Audio Streams:
* ##wb: waveform audio bytes
*
* The grouping into LIST 'rec' chunks implies only that the contents of
* the chunk should be read into memory at the same time. This
* grouping is used for files specifically intended to be played from
* CD-ROM.
*
* The index chunk at the end of the file should contain one entry for
* each data chunk in the file.
*
* Limitations for the current software:
* Only one video stream and one audio stream are allowed.
* The streams must start at the beginning of the file.
*
*
* To register codec types please obtain a copy of the Multimedia
* Developer Registration Kit from:
*
* Microsoft Corporation
* Multimedia Systems Group
* Product Marketing
* One Microsoft Way
* Redmond, WA 98052-6399
*
*)
TWOCC = word;
(* Main AVI File Header *)
TMainAVIHeader = record
dwMicroSecPerFrame: DWORD; // frame display rate (or 0L)
dwMaxBytesPerSec: DWORD; // max. transfer rate
dwPaddingGranularity: DWORD; // pad to multiples of this
// size; normally 2K.
dwFlags: DWORD; // the ever-present flags
dwTotalFrames: DWORD; // # frames in file
dwInitialFrames: DWORD;
dwStreams: DWORD;
dwSuggestedBufferSize: DWORD;
dwWidth: DWORD;
dwHeight: DWORD;
dwReserved: array[0..3] of DWORD;
end;
TFOURCC = DWORD; (* a four character code *)
(* Stream header *)
TAVIStreamHeader = record
fccType: TFOURCC;
fccHandler: TFOURCC;
dwFlags: DWORD; (* Contains AVITF_* flags *)
wPriority: word;
wLanguage: word;
dwInitialFrames: DWORD;
dwScale: DWORD;
dwRate: DWORD; (* dwRate / dwScale == samples/second *)
dwStart: DWORD;
dwLength: DWORD; (* In units above... *)
dwSuggestedBufferSize: DWORD;
dwQuality: DWORD;
dwSampleSize: DWORD;
rcFrame: TRECT;
end;
TAVIINDEXENTRY = record
ckid: DWORD;
dwFlags: DWORD;
dwChunkOffset: DWORD; // Position of chunk
dwChunkLength: DWORD; // Length of chunk
end;
(* Palette change chunk Used in video streams. *)
TAVIPALCHANGE = record
bFirstEntry: byte; (* first entry to change *)
bNumEntries: byte; (* # entries to change (0 if 256) *)
wFlags: word; (* Mostly to preserve alignment... *)
peNew: PPALETTEENTRY; (* New color specifications *)
end;
implementation
function mmioFOURCC(ch0, ch1, ch2, ch3: byte): DWord;
begin
Result := (ch0) or (ch1 shl 8) or (ch2 shl 16) or (ch3 shl 24);
end;
(* Macro to make a TWOCC out of two characters *)
function aviTWOCC(ch0, ch1: byte): word;
begin
Result := (ch0) or (ch1 shl 8);
end;
(*
** Useful macros
**
** Warning: These are nasty macro, and MS C 6.0 compiles some of them
** incorrectly if optimizations are on. Ack.
*)
(* Macro to get stream number out of a FOURCC ckid *)
function FromHex(n: byte): byte;
begin
// #define FromHex(n) (((n) >= 'A') ? ((n) + 10 - 'A') : ((n) - '0'))
if (n >= Ord('A')) then
Result := (n + 10 - Ord('A'))
else
Result := (n - Ord('0'));
end;
function StreamFromFOURCC(fcc: TFOURCC): byte;
begin
// #define StreamFromFOURCC(fcc) ((WORD) ((FromHex(LOBYTE(LOWORD(fcc))) << 4) + (FromHex(HIBYTE(LOWORD(fcc))))))
Result := FromHex(LOBYTE(LOWORD(fcc))) shl 4 +
FromHex(HIBYTE(LOWORD(fcc)));
end;
(* Macro to get TWOCC chunk type out of a FOURCC ckid *)
function TWOCCFromFOURCC(fcc: TFOURCC): TWOCC;
begin
Result := HIWORD(fcc);
end;
(* Macro to make a ckid for a chunk out of a TWOCC and a stream number from 0-255. *)
function ToHex(n: byte): byte;
begin
// #define ToHex(n) ((BYTE) (((n) > 9) ? ((n) - 10 + 'A') : ((n) + '0')))
if (n > 9) then
Result := (n - 10 + Ord('A'))
else
Result := (n + Ord('0'));
end;
function MAKEAVICKID(tcc, stream: byte): long;
begin
Result := MAKELONG((ToHex(stream and $0f) shl 8) or
(ToHex(stream and $f0) shr 4), tcc);
end;
end.
|
unit NewFrontiers.GUI.Binding;
interface
uses Vcl.Controls, Generics.Collections, System.Rtti;
type
TBinding = class;
/// <summary>
/// Identifiziert den Teilnehmer eines Bindings eindeutig und stellt die
/// Kommunikation mit ihm her.
/// </summary>
TBindingTarget = class
protected
_binding: TBinding;
_target: TObject;
_bindingPath: string;
procedure setTarget(const Value: TObject); virtual; abstract;
public
property Binding: TBinding read _binding write _binding;
property BindingPath: string read _bindingPath write _bindingPath;
property Target: TObject read _target write setTarget;
function getValue: TValue; virtual; abstract;
procedure setValue(aValue: TValue); virtual; abstract;
/// <summary>
/// Gibt den eindeutigen Identifier zurück.
/// </summary>
/// <returns>
/// Identifier. Aktuell die Speicheradresse des Objekts sowie den
/// Propertynamen.
/// </returns>
function getIdentifier: string;
end;
/// <summary>
/// Definiert ein Quelle und Ziel eines Bindings. Aktuell handelt es sich
/// immer um ein bi-direktionales Binding.
/// </summary>
TBinding = class
protected
_target: TBindingTarget;
_source: TBindingTarget;
procedure setSource(const Value: TBindingTarget);
procedure setTarget(const Value: TBindingTarget);
public
destructor Destroy; override;
property Target: TBindingTarget read _target write setTarget;
property Source: TBindingTarget read _source write setSource;
procedure contentChanged(aSender: TBindingTarget); overload;
procedure contentChanged(aObject: TObject); overload;
procedure updateTarget;
procedure updateSource;
/// <summary>
/// Trägt dieses Binding im Dictionary ein. Nur eingetragene Bindings
/// werden tatsächlich ausgeführt
/// </summary>
procedure registerWithDictionary;
/// <summary>
/// Entfernt das BInding aus dem Dictionary
/// </summary>
procedure removeFromDictionary;
/// <summary>
/// Gibt zurück, ob eines der beiden Targets aktuell gegen nil
/// gebunden ist
/// </summary>
function isNilBinding: boolean;
end;
/// <summary>
/// Factory für die BindingTargets. Neue Implementierungen können über
/// den Initialization-Bereich der Quelldatei hinzugefügt werden.
/// </summary>
TBindingTargetFactory = class
protected
_registeredTargets: TDictionary<TClass, TClass>;
constructor Create;
public
property RegisteredTargets: TDictionary<TClass, TClass> read _registeredTargets;
destructor Destroy; override;
class function getInstance: TBindingTargetFactory;
/// <summary>
/// Registriert eine neue Zurdnung Klasse <-> erzeugtes Target.
/// </summary>
class procedure registerTargetClass(aControl: TClass; aTarget: TClass);
/// <summary>
/// Diese Methode erzeugt auf Basis eines übergebenen Controls sein
/// Standard-BindingTarget.
/// </summary>
class function createTarget(aControl: TControl): TBindingTarget; overload;
/// <summary>
/// Diese Methoder erzeugt auf Basis eines Objekts und eines
/// BindingPath ein neues Target.
/// </summary>
class function createTarget(aObject: TObject; aBindingPath: string): TBindingTarget; overload;
/// <summary>
/// Entspricht createTarget nur für Felder statt Properties. ACHTUNG:
/// Wird vor Produktionsreife noch entfernt
/// </summary>
class function createFieldTarget(aObject: TObject; aBindingPath: string): TBindingTarget;
end;
/// <summary>
/// Mit einer Binding-Group können mehrere Bindings in einer Gruppe
/// bearbeitet werden. Alle Bindings haben die gleiche Quelle. (z.B.
/// Entity für die GUI)
/// </summary>
TBindingGroup = class
protected
_context: TObject;
_bindings: TObjectlist<TBinding>;
procedure setContext(const Value: TObject);
public
/// <summary>
/// Legt den Kontext der Bindings fest. Wird der Kontext gewechselt
/// werden sämtliche Bindings neu aufgesetzt
/// </summary>
property Context: TObject read _context write setContext;
constructor Create;
destructor Destroy; override;
/// <summary>
/// Fügt der Grupp ein neues Binding hinzu
/// </summary>
procedure addBinding(aControl: TControl; aBindingExpression: string);
/// <summary>
/// Fügt der Grupp ein neues Feld-Binding hinzu.l ACHTUNG: Methode wird
/// bis zur Produktionsreife wieder verschwinden.
/// </summary>
procedure addFieldBinding(aControl: TControl; aBindingExpression: string);
/// <summary>
/// Erstellt eine Binding zwischen dem übergebenen Property und dem
/// Binding-Context der Gruppe
/// </summary>
procedure bindContextTo(aObject: TObject; aPropertyname: string);
end;
/// <summary>
/// Das Binding-Dictionary enthält Listen Bindings zu den jeweiligen
/// Endpunkten. Wird ein Endpunkt aktualisiert, beauftragt das Dictionary
/// alle abhängigen Bindings sich zu aktualisieren.
/// </summary>
TBindingDictionary = class (TDictionary<string, TList<TBinding>>)
public
class function getInstance: TBindingDictionary;
/// <summary>
/// Eine Property wurde aktualisiert. Das Dictionary sucht alle
/// abhängigen Bindings und aktualisiert diese.
/// </summary>
procedure propertyChanged(aObject: TObject; aProperty: string);
/// <summary>
/// Lässt sich nicht feststellen welche Eigenschaft eines Objekts
/// sich geändert hat, kann man mit dieser Methode alle diesem Objekt
/// zugeordneten Bindings auf einmal aktualisieren.
/// </summary>
procedure objectChanged(aObject: TObject);
/// <summary>
/// Fügt dem Dictionary ein neues Binding hinzu
/// </summary>
procedure addBinding(aIdentifier: string; aBinding: TBinding);
/// <summary>
/// Entfernt ein Binding aus dem Dictionary
/// </summary>
procedure removeBinding(aIdentifier: string; aBinding: TBinding);
end;
implementation
uses NewFrontiers.Reflection, SysUtils, NewFrontiers.GUI.BindingTarget, System.Generics.Defaults,
NewFrontiers.Utility.StringUtil;
var _targetFactoryInstance: TBindingTargetFactory;
var _dictionaryInstance: TBindingDictionary;
{ TBindingManager }
procedure TBindingGroup.addBinding(aControl: TControl;
aBindingExpression: string);
var
temp: TBinding;
begin
temp := TBinding.Create;
temp.Target := TBindingTargetFactory.createTarget(aControl);
temp.Source := TBindingTargetFactory.createTarget(_context, aBindingExpression);
temp.registerWithDictionary;
_bindings.Add(temp);
end;
procedure TBindingGroup.addFieldBinding(aControl: TControl;
aBindingExpression: string);
var
temp: TBinding;
begin
temp := TBinding.Create;
temp.Target := TBindingTargetFactory.createTarget(aControl);
temp.Source := TBindingTargetFactory.createFieldTarget(_context, aBindingExpression);
temp.registerWithDictionary;
_bindings.Add(temp);
end;
procedure TBindingGroup.bindContextTo(aObject: TObject; aPropertyname: string);
var binding: TBinding;
begin
binding := TBinding.Create;
binding.Target := TBindingTargetFactory.createTarget(self, 'Context');
binding.Source := TBindingTargetFactory.createTarget(aObject, aPropertyname);
binding.registerWithDictionary;
end;
constructor TBindingGroup.Create;
begin
_bindings := TObjectlist<TBinding>.Create(true);
end;
destructor TBindingGroup.Destroy;
begin
_bindings.Free;
inherited;
end;
procedure TBindingGroup.setContext(const Value: TObject);
var aktBinding: TBinding;
begin
if (_context <> Value) then
begin
for aktBinding in _bindings do
begin
aktBinding.removeFromDictionary;
aktBinding.Source.Target := Value;
aktBinding.registerWithDictionary;
aktBinding.updateTarget;
end;
end;
_context := Value;
end;
{ TBinding }
procedure TBinding.contentChanged(aSender: TBindingTarget);
begin
if (aSender = _target) then updateSource
else updateTarget;
end;
procedure TBinding.contentChanged(aObject: TObject);
begin
if (aObject = _source.Target) then contentChanged(_source)
else contentChanged(_target);
end;
destructor TBinding.Destroy;
begin
removeFromDictionary;
inherited;
end;
function TBinding.isNilBinding: boolean;
begin
result := (_source.getIdentifier = 'nil') or (_target.getIdentifier = 'nil');
end;
procedure TBinding.registerWithDictionary;
begin
TBindingDictionary.getInstance.addBinding(_source.getIdentifier, self);
TBindingDictionary.getInstance.addBinding(_target.getIdentifier, self);
end;
procedure TBinding.removeFromDictionary;
begin
TBindingDictionary.getInstance.removeBinding(_source.getIdentifier, self);
TBindingDictionary.getInstance.removeBinding(_target.getIdentifier, self);
end;
procedure TBinding.setSource(const Value: TBindingTarget);
begin
_source := Value;
_source.Binding := self;
if (_target <> nil) then
updateTarget;
end;
procedure TBinding.setTarget(const Value: TBindingTarget);
begin
_target := Value;
_target.Binding := self;
end;
procedure TBinding.updateSource;
begin
_source.setValue(_target.getValue);
end;
procedure TBinding.updateTarget;
begin
_target.setValue(_source.getValue);
end;
{ TBindingTargetFactory }
constructor TBindingTargetFactory.Create;
begin
_registeredTargets := TDictionary<TClass, TClass>.Create();
end;
class function TBindingTargetFactory.createTarget(
aControl: TControl): TBindingTarget;
begin
if (self.getInstance.RegisteredTargets.ContainsKey(aControl.ClassType)) then
begin
result := self.getInstance.RegisteredTargets.Items[aControl.ClassType].Create() as TBindingTarget;
result.Target := aControl;
end
else raise Exception.Create('Keine Target-Klasse für übergebenes Control gefunden');
end;
class function TBindingTargetFactory.createFieldTarget(aObject: TObject;
aBindingPath: string): TBindingTarget;
var fieldName, path: string;
temp: TObject;
begin
if (TStringUtil.Contains('.', aBindingPath)) then
begin
TStringUtil.stringParts(aBindingPath, '.', fieldName, path);
temp := TReflectionManager.getFieldValue(aObject, fieldName).AsObject;
if (temp <> nil) then
begin
aObject := temp;
aBindingPath := path;
end;
// TODO: Was machen wenn temp = nil?!
end;
result := TBindingTargetField.Create;
result.Target := aObject;
result.BindingPath := aBindingPath;
end;
class function TBindingTargetFactory.createTarget(aObject: TObject;
aBindingPath: string): TBindingTarget;
var propertyName, path: string;
temp: TObject;
begin
if (aObject <> nil) and (TStringUtil.Contains('.', aBindingPath)) then
begin
TStringUtil.stringParts(aBindingPath, '.', propertyName, path);
if (not TReflectionManager.hasProperty(aObject, propertyName)) then
begin
result := TBindingTargetFactory.createFieldTarget(aObject, aBindingPath);
exit;
end;
temp := TReflectionManager.getPropertyValue(aObject, propertyName).AsObject;
if (temp <> nil) then
begin
aObject := temp;
aBindingPath := path;
end
else begin
raise Exception.Create('not implemented yet');
end;
result := createTarget(aObject, aBindingPath); // Rekursion
end
else begin
result := TBindingTargetProperty.Create;
result.Target := aObject;
result.BindingPath := aBindingPath;
end;
// Das ist an dieser Stelle unter Umständen falsch. Es wird geprüft, ob
// es diese Property überhaupt gibt und wenn nicht, wird ein Field-Binding
// angelegt. Es wird aktuell aber nicht geprüft, ob es überhaupt ein passendes
// field gibt.
if (not TReflectionManager.hasProperty(aObject, aBindingPath)) then
begin
result := TBindingTargetFactory.createFieldTarget(aObject, aBindingPath);
exit;
end;
end;
destructor TBindingTargetFactory.Destroy;
begin
_registeredTargets.Free;
inherited;
end;
class function TBindingTargetFactory.getInstance: TBindingTargetFactory;
begin
if (_targetFactoryInstance = nil) then
_targetFactoryInstance := TBindingTargetFactory.Create;
result := _targetFactoryInstance;
end;
class procedure TBindingTargetFactory.registerTargetClass(aControl,
aTarget: TClass);
begin
self.getInstance.RegisteredTargets.Add(aControl, aTarget);
end;
{ TBindingTarget }
function TBindingTarget.getIdentifier: string;
begin
// Target kann nil sein. Z.B. wenn eine BindingGroup keinen Context hat
if (_target = nil) then
result := 'nil'
else
result := intToStr(_target.GetHashCode) + '_' + UpperCase(_bindingPath);
end;
{ TBindingDictionary }
procedure TBindingDictionary.addBinding(aIdentifier: string;
aBinding: TBinding);
begin
// Bindings gegen nil werden natürlich nicht aufgenommen
if (aBinding.isNilBinding) then exit;
// Ggf. eine Liste anlegen
if (not containsKey(aIdentifier)) then
begin
add(aIdentifier, TList<TBinding>.Create);
end;
Items[aIdentifier].Add(aBinding);
end;
class function TBindingDictionary.getInstance: TBindingDictionary;
begin
// Eigener Comparer, sonst wird die GLeichheit nicht erkannt
if (_dictionaryInstance = nil) then
_dictionaryInstance := TBindingDictionary.Create();
result := _dictionaryInstance;
end;
procedure TBindingDictionary.objectChanged(aObject: TObject);
var
binding: TBinding;
curKey: string;
begin
for curKey in self.Keys do
begin
if (TStringUtil.startsWith(intToStr(aObject.GetHashCode) + '_', curKey)) then
begin
for binding in Items[curKey] do
begin
binding.contentChanged(aObject);
end;
end;
end;
end;
procedure TBindingDictionary.propertyChanged(aObject: TObject;
aProperty: string);
var
identifier: string;
binding: TBinding;
begin
identifier := intToStr(aObject.GetHashCode) + '_' + UpperCase(aProperty);
if (self.Count > 0) and (self.ContainsKey(identifier)) then
begin
for binding in Items[identifier] do
begin
try
binding.contentChanged(aObject);
except
on E:Exception do
// TOOD: Logging;
end;
end;
end;
end;
procedure TBindingDictionary.removeBinding(aIdentifier: string;
aBinding: TBinding);
begin
// Wenn gegen nil gebunden wurde gibt es auch nichts zu entfernen
if (aBinding.isNilBinding) then exit;
if (containsKey(aIdentifier)) then
begin
Items[aIdentifier].Remove(aBinding);
if (Items[aIdentifier].Count = 0) then
begin
Items[aIdentifier].Free;
Remove(aIdentifier);
end;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.