text stringlengths 14 6.51M |
|---|
unit uServiceAttributeAllocationFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBaseEditFrm, DB, DBClient, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxContainer,
cxTextEdit, Buttons, ExtCtrls, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, StdCtrls, Menus, cxLookAndFeelPainters,
cxButtons, cxCheckBox, cxDropDownEdit, cxMaskEdit, cxButtonEdit;
type
TServiceAttributeAllocationFrm = class(TSTBaseEdit)
Panel1: TPanel;
Label1: TLabel;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
cxGridMaterial: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
Splitter1: TSplitter;
cxGrid2: TcxGrid;
cxGridBranch: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
Panel7: TPanel;
btn_Add: TSpeedButton;
btn_Del: TSpeedButton;
Label3: TLabel;
txtMaterial: TcxTextEdit;
btn_AllSelect: TcxButton;
btn_NotSelect: TcxButton;
Panel8: TPanel;
btn_Alter: TcxButton;
btn_Exit: TcxButton;
Label2: TLabel;
cdsMaterial: TClientDataSet;
dsMaterial: TDataSource;
cdsMaterialSELECTED: TFloatField;
cdsMaterialFID: TWideStringField;
cdsMaterialFNUMBER: TWideStringField;
cdsMaterialFNAME_L2: TWideStringField;
cdsMaterialBRANDNAME: TWideStringField;
cdsMaterialYEARSNAME: TWideStringField;
cdsMaterialATTRNAME: TWideStringField;
cdsMaterialSEASONNAME: TWideStringField;
cxGridMaterialSELECTED: TcxGridDBColumn;
cxGridMaterialFID: TcxGridDBColumn;
cxGridMaterialFNUMBER: TcxGridDBColumn;
cxGridMaterialFNAME_L2: TcxGridDBColumn;
cxGridMaterialBRANDNAME: TcxGridDBColumn;
cxGridMaterialYEARSNAME: TcxGridDBColumn;
cxGridMaterialATTRNAME: TcxGridDBColumn;
cxGridMaterialSEASONNAME: TcxGridDBColumn;
cdsBranch: TClientDataSet;
dsBranch: TDataSource;
cdsBranchFID: TStringField;
cdsBranchFBranchNumber: TStringField;
cdsBranchFBranchName: TStringField;
cxGridBranchFID: TcxGridDBColumn;
cxGridBranchFBranchNumber: TcxGridDBColumn;
cxGridBranchFBranchName: TcxGridDBColumn;
Label4: TLabel;
cdsCompany: TClientDataSet;
cdsInventory: TClientDataSet;
cdsPur: TClientDataSet;
cdsCost: TClientDataSet;
cdsSale: TClientDataSet;
cdsCompany_save: TClientDataSet;
cdsInventory_save: TClientDataSet;
cdsCost_save: TClientDataSet;
cdsPur_save: TClientDataSet;
cdsSale_save: TClientDataSet;
Label5: TLabel;
Label6: TLabel;
txt_Org: TcxButtonEdit;
Bevel1: TBevel;
cb_OrgType: TcxComboBox;
btn_Find: TcxButton;
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure txtMaterialPropertiesChange(Sender: TObject);
procedure cdsMaterialFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
procedure btn_AllSelectClick(Sender: TObject);
procedure btn_NotSelectClick(Sender: TObject);
procedure btn_ExitClick(Sender: TObject);
procedure btn_AddClick(Sender: TObject);
procedure btn_DelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btn_AlterClick(Sender: TObject);
procedure txt_OrgKeyPress(Sender: TObject; var Key: Char);
procedure txt_OrgPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure btn_FindClick(Sender: TObject);
procedure cdsInventory_saveNewRecord(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
FOrgFID:string;
Procedure GetMaterial;
procedure OpenData(mFID:string);
procedure OpenSaveData(mFID:string);
function GetBranchFIDs:string;
function ST_Save:Boolean;
procedure AllocationMaterial(mFID:string);
procedure setConventionFieldValue(cds:TClientDataSet;MaterFID,unitFID,bostypeFID:string);
procedure copyDataset(src,dec:TClientDataSet);
end;
var
ServiceAttributeAllocationFrm: TServiceAttributeAllocationFrm;
procedure OpenServiceAttributeAllocation;
implementation
uses FrmCliDM,Pub_Fun,uDrpHelperClase,StringUtilClass,uMaterDataSelectHelper;
{$R *.dfm}
procedure OpenServiceAttributeAllocation;
begin
Application.CreateForm(TServiceAttributeAllocationFrm,ServiceAttributeAllocationFrm);
ServiceAttributeAllocationFrm.ShowModal;
ServiceAttributeAllocationFrm.Free;
end;
{ TServiceAttributeAllocationFrm }
function getSqlStr(str: string): string;
var i: Integer;
rest: string;
list: Tstringlist;
begin
result := '';
try
list := Tstringlist.Create;
list.Delimiter := ',';
list.DelimitedText := str;
rest := '';
if List.Count = 0 then Exit;
for i := 0 to List.Count - 1 do
begin
rest := rest + QuotedStr(trim(List[i])) + ',';
end;
rest := Copy(rest, 1, Length(trim(rest)) - 1);
if rest <> '' then
result := rest;
finally
list.Free;
end;
end;
procedure TServiceAttributeAllocationFrm.GetMaterial;
var _SQL,ErrMsg,TableName,FieldName:string;
begin
inherited;
if cb_OrgType.Text = '财务资料' then
begin
TableName := 'T_BD_MATERIALCOMPANYINFO';FieldName := 'FCompanyID';
end;
if cb_OrgType.Text = '销售资料' then
begin
TableName := 'T_BD_MATERIALSALES'; FieldName := 'FORGUNIT';
end;
if cb_OrgType.Text = '采购资料' then
begin
TableName := 'T_BD_MATERIALPURCHASING'; FieldName := 'FORGUNIT';
end;
if cb_OrgType.Text = '库存资料' then
begin
TableName := 'T_BD_MATERIALINVENTORY';FieldName := 'FORGUNIT';
end;
if cb_OrgType.Text = '成本资料' then
begin
TableName := 'T_BD_MATERIALCOST'; FieldName := 'FORGUNIT';
end;
_SQL :=' select a.FSTATUS as Selected, m.fid,m.fnumber,m.fname_l2,brand.fname_l2 as BrandName,'
+' years.fname_l2 as yearsName,attr.fname_l2 as attrName,season.fname_l2 as seasonName '
+' from '+TableName+' a '
+' left join t_bd_material m on m.fid=a.fmaterialid '
+' left join ct_bas_brand brand on brand.fid=m.cfbrandid '
+' left join ct_bas_years years on years.fid=m.cfyearsid'
+' left join ct_bd_attribute attr on attr.fid=m.cfattributeid '
+' left join ct_bas_season season on season.fid=m.cfseasonid '
+' where a.'+FieldName+'='+Quotedstr(self.FOrgFID);
if not CliDM.Get_OpenSQL(cdsMaterial,_SQL,ErrMsg) then
begin
ShowMsg(Self.Handle,'查找物料出错!'+ErrMsg,[]);
Exit;
end;
if not cdsMaterial.IsEmpty then
begin
btn_AllSelect.Click;
end;
end;
procedure TServiceAttributeAllocationFrm.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
//inherited;
end;
procedure TServiceAttributeAllocationFrm.FormShow(Sender: TObject);
begin
inherited;
Self.FOrgFID := UserInfo.Branch_ID;
txt_Org.Text := UserInfo.Branch_Name;
end;
procedure TServiceAttributeAllocationFrm.txtMaterialPropertiesChange(
Sender: TObject);
var inputTxt:string;
begin
inputTxt := Trim(txtMaterial.Text);
cdsMaterial.Filtered := False;
if (inputTxt <> '' ) then
cdsMaterial.Filtered := True
else
cdsMaterial.Filtered := False;
end;
procedure TServiceAttributeAllocationFrm.cdsMaterialFilterRecord(
DataSet: TDataSet; var Accept: Boolean);
var inputTxt:string;
begin
inputTxt := Trim(txtMaterial.Text);
Accept:=((Pos(Trim(UpperCase(inputTxt)),UpperCase(DataSet.fieldbyname('fnumber').AsString))>0) or
(Pos(Trim(UpperCase(inputTxt)),UpperCase(DataSet.fieldbyname('fname_l2').AsString))>0) or
(Pos(Trim(UpperCase(inputTxt)),ChnToPY(UpperCase(DataSet.fieldbyname('fnumber').AsString)))>0) or
(Pos(Trim(UpperCase(inputTxt)),ChnToPY(UpperCase(DataSet.fieldbyname('fname_l2').AsString)))>0)
)
end;
procedure TServiceAttributeAllocationFrm.btn_AllSelectClick(
Sender: TObject);
begin
inherited;
try
cdsMaterial.DisableControls;
cdsMaterial.First;
while not cdsMaterial.Eof do
begin
cdsMaterial.Edit;
cdsMaterial.FieldByName('selected').AsInteger := 1;
cdsMaterial.Post;
cdsMaterial.Next;
end;
cdsMaterial.First;
finally
cdsMaterial.EnableControls;
end;
end;
procedure TServiceAttributeAllocationFrm.btn_NotSelectClick(
Sender: TObject);
begin
inherited;
try
cdsMaterial.DisableControls;
cdsMaterial.First;
while not cdsMaterial.Eof do
begin
cdsMaterial.Edit;
if cdsMaterial.FieldByName('selected').AsInteger = 1 then
cdsMaterial.FieldByName('selected').AsInteger := 0
else
cdsMaterial.FieldByName('selected').AsInteger := 1;
cdsMaterial.Post;
cdsMaterial.Next;
end;
finally
cdsMaterial.EnableControls;
end;
end;
procedure TServiceAttributeAllocationFrm.btn_ExitClick(Sender: TObject);
begin
inherited;
self.Close;
end;
procedure TServiceAttributeAllocationFrm.btn_AddClick(Sender: TObject);
var ForgType:Integer;
begin
//1 财务组织,2 销售组织 , 3 库存组织 ,4 采购组织 ,5 成本中心
if cb_OrgType.Text = '财务资料' then
ForgType := 1
else
if cb_OrgType.Text = '销售资料' then
ForgType := 2
else
if cb_OrgType.Text = '采购资料' then
ForgType := 4
else
if cb_OrgType.Text = '库存资料' then
ForgType := 3
else
if cb_OrgType.Text = '成本资料' then
ForgType := 5;
with Select_Branch(cb_OrgType.Text+'组织','',ForgType) do
begin
if not IsEmpty then
begin
First;
while not eof do
begin
if (not cdsBranch.Locate('FID',VarArrayOf([FieldByName('fid').AsString]),[]))
and (FieldByName('fid').AsString <> self.FOrgFID)
then
begin
cdsBranch.Append;
cdsBranch.FieldByName('FID').AsString := fieldbyname('FID').AsString;
cdsBranch.FieldByName('FBranchNumber').AsString := fieldbyname('Fnumber').AsString;
cdsBranch.FieldByName('FBranchName').AsString := fieldbyname('Fname_l2').AsString;
cdsBranch.Post;
end;
Next;
end;
end;
end;
end;
procedure TServiceAttributeAllocationFrm.btn_DelClick(Sender: TObject);
begin
inherited;
if not cdsBranch.IsEmpty then cdsBranch.Delete;
end;
procedure TServiceAttributeAllocationFrm.FormCreate(Sender: TObject);
begin
inherited;
cdsBranch.CreateDataSet;
end;
procedure TServiceAttributeAllocationFrm.OpenData(mFID: string);
var materSQL,ErrMsg:string;
_cds: array[0..4] of TClientDataSet;
_SQL: array[0..4] of String;
begin
try
Screen.Cursor := crHourGlass;
_cds[0] := cdsCompany;
_cds[1] := cdsPur;
_cds[2] := cdsInventory;
_cds[3] := cdsSale;
_cds[4] := cdsCost;
_SQL[0] := 'select * from T_BD_MATERIALCOMPANYINFO a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FCompanyID='+quotedstr(Self.FOrgFID);
_SQL[1] := 'select * from T_BD_MATERIALPURCHASING a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FOrgUnit='+quotedstr(Self.FOrgFID);
_SQL[2] := 'select * from T_BD_MATERIALINVENTORY a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FOrgUnit='+quotedstr(Self.FOrgFID);
_SQL[3] := 'select * from T_BD_MATERIALSALES a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FOrgUnit='+quotedstr(Self.FOrgFID);
_SQL[4] := 'select * from T_BD_MATERIALCOST a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FORGUNIT='+quotedstr(Self.FOrgFID);
if not (CliDM.Get_OpenClients_E(mFID,_cds,_SQL,ErrMsg)) then
begin
showmsg(self.Handle,'物料业务属性表打开出错:'+ErrMsg,[]);
Self.Close;
Abort;
end;
finally
Screen.Cursor := crDefault;
end;
end;
function TServiceAttributeAllocationFrm.GetBranchFIDs: string;
var Fids:string;
begin
try
cdsBranch.DisableControls;
Fids := '';
cdsBranch.First;
while not cdsBranch.Eof do
begin
if Fids = '' then
Fids := cdsBranch.fieldbyname('FID').AsString
else
Fids := Fids + ',' + cdsBranch.fieldbyname('FID').AsString;
cdsBranch.Next;
end;
Result := Fids;
finally
cdsBranch.EnableControls;
end;
end;
procedure TServiceAttributeAllocationFrm.OpenSaveData(mFID: string);
var materSQL,ErrMsg,bFID:string;
_cds: array[0..0] of TClientDataSet;
_SQL: array[0..0] of String;
begin
try
Screen.Cursor := crHourGlass;
bFID := getSqlStr(GetBranchFIDs);
if cb_OrgType.Text = '财务资料' then
begin
_cds[0] := cdsCompany_save;
_SQL[0] := 'select * from T_BD_MATERIALCOMPANYINFO a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FCompanyID in ('+bFID+')';
end
else
if cb_OrgType.Text = '销售资料' then
begin
_cds[0] := cdsSale_save;
_SQL[0] := 'select * from T_BD_MATERIALSALES a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FOrgUnit in ('+bFID+')';
end
else
if cb_OrgType.Text = '采购资料' then
begin
_cds[0] := cdsPur_save;
_SQL[0] := 'select * from T_BD_MATERIALPURCHASING a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FOrgUnit in ('+bFID+')';
end
else
if cb_OrgType.Text = '库存资料' then
begin
_cds[0] := cdsInventory_save;
_SQL[0] := 'select * from T_BD_MATERIALINVENTORY a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FOrgUnit in ('+bFID+')';
end
else
if cb_OrgType.Text = '成本资料' then
begin
_cds[0] := cdsCost_save;
_SQL[0] := 'select * from T_BD_MATERIALCOST a where a.fmaterialid = '+Quotedstr(mFID)+' and a.FORGUNIT in ('+bFID+')';
end;
if not (CliDM.Get_OpenClients_E(mFID,_cds,_SQL,ErrMsg)) then
begin
showmsg(self.Handle,'物料业务属性表打开出错:'+ErrMsg,[]);
Abort;
end;
finally
Screen.Cursor := crDefault;
end;
end;
function TServiceAttributeAllocationFrm.ST_Save: Boolean;
var _cds: array[0..0] of TClientDataSet;
error : string;
i:Integer;
cds:TClientDataSet;
TableName,FieldName:string;
begin
if cb_OrgType.Text = '财务资料' then
begin
TableName := 'T_BD_MATERIALCOMPANYINFO';FieldName := 'FCompanyID'; cds := cdsCompany_save;
end;
if cb_OrgType.Text = '销售资料' then
begin
TableName := 'T_BD_MATERIALSALES'; FieldName := 'FORGUNIT'; cds := cdsSale_save;
end;
if cb_OrgType.Text = '采购资料' then
begin
TableName := 'T_BD_MATERIALPURCHASING'; FieldName := 'FORGUNIT'; cds := cdsPur_save;
end;
if cb_OrgType.Text = '库存资料' then
begin
TableName := 'T_BD_MATERIALINVENTORY';FieldName := 'FORGUNIT'; cds := cdsInventory_save;
end;
if cb_OrgType.Text = '成本资料' then
begin
TableName := 'T_BD_MATERIALCOST'; FieldName := 'FORGUNIT'; cds := cdsCost_save;
end;
try
Screen.Cursor := crHourGlass;
Result := False;
_cds[0] := cds;
try
if CliDM.Apply_Delta_E(_cds,[TableName],error) then
begin
Result := True;
Gio.AddShow(TableName+'表提交成功!');
end
else
begin
ShowMsg(Handle, '业务属性保存失败! '+error,[]);
Gio.AddShow('物料业务属性保存失败!'+error);
Abort;
end;
except
on E: Exception do
begin
Gio.AddShow(TableName+'表提交失败!'+e.Message);
ShowMsg(Handle, '物料业务属性提交失败:'+e.Message,[]);
Abort;
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TServiceAttributeAllocationFrm.AllocationMaterial(mFID: string);
var BranchFID:string;
begin
OpenData(mFID);
OpenSaveData(mFID);
try
cdsBranch.DisableControls;
cxGridBranch.BeginUpdate;
cdsBranch.First;
while not cdsBranch.Eof do
begin
BranchFID := cdsBranch.fieldbyname('FID').AsString;
if cb_OrgType.Text = '财务资料' then
begin
//财务组织
if cdsCompany_save.Locate('FCOMPANYID',VarArrayOf([BranchFID]),[]) then
cdsCompany_save.Edit
else
cdsCompany_save.Append;
copyDataset(cdsCompany,cdsCompany_save);
self.setConventionFieldValue(cdsCompany_save,mFID,BranchFID,'D431F8BB');
cdsCompany_save.Post;
end
else
if cb_OrgType.Text = '销售资料' then
begin
//销售组织
if cdsSale_save.Locate('FORGUNIT',VarArrayOf([BranchFID]),[]) then
cdsSale_save.Edit
else
cdsSale_save.Append;
copyDataset(cdsSale,cdsSale_save);
self.setConventionFieldValue(cdsSale_save,mFID,BranchFID,'C84112CF');
cdsSale_save.Post;
end
else
if cb_OrgType.Text = '采购资料' then
begin
//采购组织
if cdsPur_save.Locate('FORGUNIT',VarArrayOf([BranchFID]),[]) then
cdsPur_save.Edit
else
cdsPur_save.Append;
copyDataset(cdsPur,cdsPur_save);
self.setConventionFieldValue(cdsPur_save,mFID,BranchFID,'0193BD9B');
cdsPur_save.Post;
end
else
if cb_OrgType.Text = '库存资料' then
begin
//库存组织
if cdsInventory_save.Locate('FORGUNIT',VarArrayOf([BranchFID]),[]) then
cdsInventory_save.Edit
else
cdsInventory_save.Append;
copyDataset(cdsInventory,cdsInventory_save);
self.setConventionFieldValue(cdsInventory_save,mFID,BranchFID,'557E499F');
cdsInventory_save.Post;
end
else
if cb_OrgType.Text = '成本资料' then
begin
//成本组织
if cdsCost_save.Locate('FORGUNIT',VarArrayOf([BranchFID]),[]) then
cdsCost_save.Edit
else
cdsCost_save.Append;
copyDataset(cdsCost,cdsCost_save);
self.setConventionFieldValue(cdsCost_save,mFID,BranchFID,'C45E21AA');
cdsCost_save.Post;
end;
//下一条
cdsBranch.Next;
end;
ST_Save;
finally
cdsBranch.EnableControls;
cxGridBranch.EndUpdate;
end;
end;
procedure TServiceAttributeAllocationFrm.btn_AlterClick(Sender: TObject);
var mFID:string;
begin
inherited;
if cdsMaterial.IsEmpty then
begin
ShowMsg(self.Handle,'没有可以分配的物料,当前机构没有对物料设置业务属性!',[]);
Exit;
end;
if cdsBranch.IsEmpty then
begin
ShowMsg(self.Handle,'请选择要分配到的机构! ',[]);
Exit;
end;
if cdsBranch.RecordCount > 1000 then
begin
ShowMsg(self.Handle,'一次性分配不能超过1000个机构! ',[]);
Exit;
end;
if MessageBox(Handle, PChar('确认开始分配业务属性(Y/N)?'), 'GA集团ERP提示', MB_YESNO) = IDNO then Exit;
try
if cdsMaterial.State in DB.dsEditModes then cdsMaterial.Post;
cdsMaterial.DisableControls;
cdsMaterial.First;
while not cdsMaterial.Eof do
begin
mFID := cdsMaterial.fieldbyname('FID').AsString;
if cdsMaterial.FieldByName('selected').AsInteger = 1 then
begin
AllocationMaterial(mFID);
end;
cdsMaterial.Next;
end;
ShowMsg(self.Handle,'分配业务属性成功! ',[]);
finally
cdsMaterial.EnableControls;
end;
end;
procedure TServiceAttributeAllocationFrm.setConventionFieldValue(
cds: TClientDataSet;MaterFID,unitFID,bostypeFID:string);
begin
cds.FieldByName('FID').AsString:=CliDM.GetEASSID(bostypeFID);
cds.FieldByName('FCREATORID').AsString:=UserInfo.LoginUser_FID;
cds.FieldByName('FCREATETIME').AsDateTime:=CliDM.Get_ServerTime;
cds.FieldByName('FLASTUPDATEUSERID').AsString:=UserInfo.LoginUser_FID;
cds.FieldByName('FLASTUPDATETIME').AsDateTime:=cds.FieldByName('FCREATETIME').AsDateTime;
//
cds.FieldByName('FControlUnitID').AsString :=UserInfo.Controlunitid;
if cds.FindField('FOrgUnit') <> nil then
cds.FieldByName('FOrgUnit').AsString := unitFID;
if cds.FindField('FCOMPANYID') <> nil then
cds.FieldByName('FCOMPANYID').AsString := unitFID;
cds.FieldByName('FMATERIALID').AsString:=MaterFID;
end;
procedure TServiceAttributeAllocationFrm.copyDataset(src,
dec: TClientDataSet);
var i:Integer;
fieldname:string;
begin
for i := 0 to dec.FieldCount -1 do
begin
fieldname := dec.Fields[i].FieldName;
if src.FindField(fieldname) <> nil then
dec.Fields[i].Value := src.fieldbyname(fieldname).Value;
end;
end;
procedure TServiceAttributeAllocationFrm.txt_OrgKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
self.FOrgFID := '';
txt_Org.Text := '';
end;
end;
procedure TServiceAttributeAllocationFrm.txt_OrgPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var ForgType:Integer;
begin
inherited;
// 财务资料
// 销售资料
// 采购资料
// 库存资料
// 成本资料
//1 财务组织,2 销售组织 , 3 库存组织 ,4 采购组织 ,5 成本中心
if cb_OrgType.Text = '财务资料' then
ForgType := 1
else
if cb_OrgType.Text = '销售资料' then
ForgType := 2
else
if cb_OrgType.Text = '采购资料' then
ForgType := 4
else
if cb_OrgType.Text = '库存资料' then
ForgType := 3
else
if cb_OrgType.Text = '成本资料' then
ForgType := 5;
with Select_Branch('','',ForgType) do
begin
if not IsEmpty then
begin
self.FOrgFID := fieldbyname('FID').AsString;
txt_Org.Text := fieldbyname('fname_l2').AsString;
end;
end;
end;
procedure TServiceAttributeAllocationFrm.btn_FindClick(Sender: TObject);
begin
inherited;
if self.FOrgFID = '' then
begin
ShowMsg(self.Handle,'请选择业务组织!',[]);
txt_Org.SetFocus;
Exit;
end;
GetMaterial;
end;
procedure TServiceAttributeAllocationFrm.cdsInventory_saveNewRecord(
DataSet: TDataSet);
begin
inherited;
DataSet.FieldByName('FEffectedStatus').AsInteger :=2; //保存或暂存
end;
end.
|
uses
fpjson, jsonparser;
procedure JSONTest;
var
jData : TJSONData;
jObject : TJSONObject;
jArray : TJSONArray;
s : String;
begin
// this is only a minimal sampling of what can be done with this API
// create from string
jData := GetJSON('{"Fld1" : "Hello", "Fld2" : 42, "Colors" : ["Red", "Green", "Blue"]}');
// output as a flat string
s := jData.AsJSON;
// output as nicely formatted JSON
s := jData.FormatJSON;
// cast as TJSONObject to make access easier
jObject := TJSONObject(jData);
// retrieve value of Fld1
s := jObject.Get('Fld1');
// change value of Fld2
jObject.Integers['Fld2'] := 123;
// retrieve the second color
s := jData.FindPath('Colors[1]').AsString;
// add a new element
jObject.Add('Happy', True);
// add a new sub-array
jArray := TJSONArray.Create;
jArray.Add('North');
jArray.Add('South');
jArray.Add('East');
jArray.Add('West');
jObject.Add('Directions', jArray);
end; |
unit imprNovo;
//---------------------------------------------------------------
// CharPrinter.pas - Tratamento de impressoras em modo caractere
//---------------------------------------------------------------
// Autor : Fernando Allen Marques de Oliveira
// Dezembro de 2000.
//
// TPrinterStream : classe derivada de TStream para enviar dados
// diretamente para o spool da impressora sele-
// cionada.
//
// TCharPrinter : Classe base para implementa??o de impressoras.
// n?o inclui personaliza??o para nenhuma impres-
// sora espec?fica, envia dados sem formata??o.
//
// Modificado em 20/05/2003 - Compatibiliza??o com diretivas padr?o do Delphi 7
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Printers, WinSpool;
type
{ Stream para enviar caracteres ? impressora atual }
TPrinterStream = class (TStream)
private
fPrinter : TPrinter;
fHandle : THandle;
fTitle : String;
procedure CreateHandle;
procedure FreeHandle;
public
constructor Create (aPrinter: TPrinter; aTitle : String);
destructor Destroy; override;
function Write (const Buffer; Count : Longint): Longint; override;
property Handle : THandle read fHandle;
end;
TCharPrinter = class(TObject)
private
{ Private declarations }
fStream : TStream;
protected
{ Protected declarations }
public
{ Public declarations }
published
{ Published declarations }
constructor Create; virtual;
destructor Destroy; override;
procedure OpenDoc (aTitle : String); virtual;
procedure SendData (aData : String);
procedure CloseDoc; virtual;
property PrintStream : TStream read fStream;
end;
// Defini??es para TAdvancedPrinter //
TprtLang = (lngEPFX,lngESCP2,lngHPPCL);
TprtFontSize = (pfs5cpi,pfs10cpi,pfs12cpi,pfs17cpi,pfs20cpi);
TprtTextStyle = (psBold,psItalic,psUnderline);
TprtTextStyles = set of TprtTextStyle;
TAdvancedPrinter = class (TCharPrinter)
private
fLang : TprtLang;
fFontSize : TprtFontSize;
fTextStyle : TprtTextStyles;
procedure SetLang (lang : TprtLang);
function GetLang : TprtLang;
procedure SetFontSize (size : TprtFontSize);
function GetFontSize : TprtFontSize;
procedure SetTextStyle (styles : TprtTextStyles);
function GetTextStyle : TprtTextStyles;
procedure UpdateStyle;
procedure Initialize;
function Convert (s : string) : string;
published
constructor Create; override;
procedure OpenDoc (aTitle : String); override;
property Language : TprtLang read GetLang write SetLang;
property FontSize : TprtFontSize read GetFontSize write SetFontSize;
property TextStyle : TprtTextStyles read GetTextStyle write SetTextStyle;
public
procedure CR;
procedure LF; overload;
procedure LF (Lines : integer); overload;
procedure CRLF;
procedure FF;
procedure Write (txt : string);
procedure WriteLeft (txt, fill : string; size : integer);
procedure WriteRight (txt, fill : string; size : integer);
procedure WriteCenter(txt, fill : string; size : integer);
procedure WriteRepeat(txt : string; quant : integer);
end;
procedure Register;
implementation
procedure Register;
begin
{RegisterComponents('AeF', [TCharPrinter]);}
end;
{ =================== }
{ = TPrinterStream = }
{ =================== }
constructor TPrinterStream.Create (aPrinter : TPrinter; aTitle : String);
begin
inherited Create;
fPrinter := aPrinter;
fTitle := aTitle;
CreateHandle;
end;
destructor TPrinterStream.Destroy;
begin
FreeHandle;
inherited;
end;
procedure TPrinterStream.FreeHandle;
begin
if fHandle <> 0 then
begin
EndPagePrinter (fHandle);
EndDocPrinter (fHandle);
ClosePrinter (Handle);
fHandle := 0;
end;
end;
procedure TPrinterStream.CreateHandle;
type
DOC_INFO_1 = packed record
pDocName : PChar;
pOutputFile : PChar;
pDataType : PChar;
end;
var
aDevice,
aDriver,
aPort : array[0..255] of Char;
aMode : NativeUInt;
DocInfo : DOC_INFO_1;
begin
DocInfo.pDocName := nil;
DocInfo.pOutputFile := nil;
DocInfo.pDataType := 'RAW';
FreeHandle;
if fHandle = 0 then
begin
fPrinter.GetPrinter(aDevice, aDriver, aPort, aMode);
if OpenPrinter (aDevice, fHandle, nil)
then begin
DocInfo.pDocName := PChar(fTitle);
if StartDocPrinter (fHandle, 1, @DocInfo) = 0
then begin
ClosePrinter (fHandle);
fHandle := 0;
end else
if not StartPagePrinter (fHandle)
then begin
EndDocPrinter (fHandle);
ClosePrinter (fHandle);
fHandle := 0;
end;
end;
end;
end;
function TPrinterStream.Write (const Buffer; Count : Longint) : Longint;
var
Bytes : Cardinal;
begin
WritePrinter (Handle, @Buffer, Count, Bytes);
Result := Bytes;
end;
{ ================= }
{ = TCharPrinter = }
{ ================= }
constructor TCharPrinter.Create;
begin
inherited Create;
fStream := nil;
end;
destructor TCharPrinter.Destroy;
begin
if fStream <> nil
then fStream.Free;
inherited;
end;
procedure TCharPrinter.OpenDoc (aTitle : String);
begin
if fStream = nil
then fStream := TPrinterStream.Create (Printer, aTitle);
end;
procedure TCharPrinter.CloseDoc;
begin
if fStream <> nil
then begin
fStream.Free;
fStream := nil;
end;
end;
procedure TCharPrinter.SendData (aData : String);
var
Data : array[0..255] of char;
cnt : integer;
begin
for cnt := 0 to length(aData) - 1
do Data[cnt] := aData[cnt+1];
fStream.Write (Data, length(aData));
end;
{ ===================== }
{ = TAdvancedPrinter = }
{ ===================== }
procedure TAdvancedPrinter.SetLang (lang : TprtLang);
begin
fLang := lang;
end;
function TAdvancedPrinter.GetLang : TprtLang;
begin
result := fLang;
end;
procedure TAdvancedPrinter.SetFontSize (size : TprtFontSize);
begin
fFontSize := size;
UpdateStyle;
end;
function TAdvancedPrinter.GetFontSize : TprtFontSize;
begin
result := fFontSize;
UpdateStyle;
end;
procedure TAdvancedPrinter.SetTextStyle (styles : TprtTextStyles);
begin
fTextStyle := styles;
UpdateStyle;
end;
function TAdvancedPrinter.GetTextStyle : TprtTextStyles;
begin
result := fTextStyle;
UpdateStyle;
end;
procedure TAdvancedPrinter.UpdateStyle;
var
cmd : string;
i : byte;
begin
cmd := '';
case fLang of
lngESCP2, lngEPFX : begin
i := 0;
Case fFontSize of
pfs5cpi : i := 32;
pfs10cpi : i := 0;
pfs12cpi : i := 1;
pfs17cpi : i := 4;
pfs20cpi : i := 5;
end;
if psBold in fTextStyle then i := i + 8;
if psItalic in fTextStyle then i := i + 64;
if psUnderline in fTextStyle then i := i + 128;
cmd := #27'!'+chr(i);
end;
lngHPPCL : begin
Case fFontSize of
pfs5cpi : cmd := #27'(s5H';
pfs10cpi : cmd := #27'(s10H';
pfs12cpi : cmd := #27'(s12H';
pfs17cpi : cmd := #27'(s17H';
pfs20cpi : cmd := #27'(s20H';
end;
if psBold in fTextStyle
then cmd := cmd + #27'(s3B'
else cmd := cmd + #27'(s0B';
if psItalic in fTextStyle
then cmd := cmd + #27'(s1S'
else cmd := cmd + #27'(s0S';
if psUnderline in fTextStyle
then cmd := cmd + #27'&d0D'
else cmd := cmd + #27'&d@';
end;
end;
SendData(cmd);
end;
procedure TAdvancedPrinter.Initialize;
begin
case fLang of
lngEPFX : SendData (#27'@'#27'2'#27'P'#18);
lngESCP2 : SendData (#27'@'#27'O'#27'2'#27'C0'#11#27'!'#0);
lngHPPCL : SendData (#27'E'#27'&l2A'#27'&l0O'#27'&l6D'#27'(s4099T'#27'(s0P'#27'&k0S'#27'(s0S');
end;
end;
function TAdvancedPrinter.Convert (s : string) : string;
const
accent : string = '??????????????????????????????????????????????';
noaccent : string = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
var
i : integer;
begin
for i := 1 to length(accent) do
While Pos(accent[i],s) > 0 do s[Pos(accent[i],s)] := noaccent[i];
result := s;
end;
constructor TAdvancedPrinter.Create;
begin
inherited Create;
fLang := lngESCP2;
fFontSize := pfs10cpi;
fTextStyle := [];
end;
procedure TAdvancedPrinter.OpenDoc (aTitle : String);
begin
inherited OpenDoc (aTitle);
Initialize;
end;
procedure TAdvancedPrinter.CR;
begin
SendData (#13);
end;
procedure TAdvancedPrinter.LF;
begin
SendData (#10);
end;
procedure TAdvancedPrinter.LF (Lines : integer);
begin
while lines > 0 do begin
SendData(#10); dec(lines);
end;
end;
procedure TAdvancedPrinter.CRLF;
begin
SendData (#13#10);
end;
procedure TAdvancedPrinter.FF;
begin
SendData(#12);
end;
procedure TAdvancedPrinter.Write (txt : string);
begin
txt := Convert (txt);
SendData (txt);
end;
procedure TAdvancedPrinter.WriteLeft (txt, fill : string; size : integer);
begin
txt := Convert(txt);
while Length(txt) < size do txt := txt + fill;
SendData (Copy(txt,1,size));
end;
procedure TAdvancedPrinter.WriteRight (txt, fill : string; size : integer);
begin
txt := Convert(txt);
while Length(txt) < size do txt := fill + txt;
SendData (Copy(txt,Length(txt)-size+1,size));
end;
procedure TAdvancedPrinter.WriteCenter(txt, fill : string; size : integer);
begin
txt := Convert(txt);
while Length(txt) < size do txt := fill + txt + fill;
SendData (Copy(txt,(Length(txt)-size) div 2 + 1,size));
end;
procedure TAdvancedPrinter.WriteRepeat(txt : string; quant : integer);
var
s : string;
begin
s := '';
txt := Convert(txt);
while quant > 0 do begin
s := s + txt;
dec(quant);
end;
SendData (s);
end;
end.
|
unit uDMRequisicaoWeb;
interface
uses
System.SysUtils, System.Classes, IPPeerClient, REST.Client,
Data.Bind.Components, Data.Bind.ObjectScope, System.JSON;
type
TRequisicaoWeb = class(TDataModule)
private
{ Private declarations }
FCEP: String;
RESTClient: TRESTClient;
RESTRequest: TRESTRequest;
RESTResponse: TRESTResponse;
procedure ConfigurarRequisicaoCEP;
function ExecutarRequisicaoCEP: TJsonObject;
procedure SetCEP(const Value: String);
public
{ Public declarations }
function BuscaRequisicaoCEP: TJsonObject;
constructor Create;
property CEP: String read FCEP write SetCEP;
end;
var
RequisicaoWeb: TRequisicaoWeb;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TRequisicaoWeb }
function TRequisicaoWeb.BuscaRequisicaoCEP: TJsonObject;
begin
try
ConfigurarRequisicaoCEP;
Result := ExecutarRequisicaoCEP;
except on E: Exception do
raise Exception.Create('Falha ao buscar CEP do servidor!');
end;
end;
procedure TRequisicaoWeb.ConfigurarRequisicaoCEP;
begin
RESTClient.BaseURL := 'https://api.postmon.com.br/v1/cep/'+CEP;
RESTRequest.Accept := 'application/json';
end;
constructor TRequisicaoWeb.Create;
begin
RESTClient := TRESTClient.Create(nil);
RESTRequest := TRESTRequest.Create(nil);
RESTResponse := TRESTResponse.Create(nil);
RESTRequest.Client := RESTClient;
RESTRequest.Response := RESTResponse;
end;
function TRequisicaoWeb.ExecutarRequisicaoCEP: TJsonObject;
begin
RESTRequest.Execute;
Result := RESTRequest.Response.JSONValue as TJSONObject;
end;
procedure TRequisicaoWeb.SetCEP(const Value: String);
begin
FCEP := Value;
end;
end.
|
unit SwMsg;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, uniGUITypes, uniGUIAbstractClasses,
uniGUIClasses, uniGUIForm, uniGUIBaseClasses, uniSweetAlert, siComp;
type
TSwMsgF = class(TUniForm)
SweetAlert: TUniSweetAlert;
procedure UniFormShow(Sender: TObject);
procedure SweetAlertConfirm(Sender: TObject);
procedure SweetAlertDismiss(Sender: TObject; const Reason: TDismissType);
private
{ Private declarations }
public
{ Public declarations }
end;
function SwMsgF: TSwMsgF;
implementation
{$R *.dfm}
uses
MainModule, uniGUIApplication;
function SwMsgF: TSwMsgF;
begin
Result := TSwMsgF(UniMainModule.GetFormInstance(TSwMsgF));
end;
//*************************************************
procedure TSwMsgF.SweetAlertConfirm(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TSwMsgF.SweetAlertDismiss(Sender: TObject;
const Reason: TDismissType);
begin
ModalResult := mrCancel;
end;
procedure TSwMsgF.UniFormShow(Sender: TObject);
begin
Hide;
SweetAlert.Show();
end;
end.
|
{$B-,I-,Q-,R-,S-}
{$M 16384,0,655360}
{8ž Extraer Subsecuencia. M‚xico 2006
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
Se tiene una secuencia de N nśmeros enteros positivos. Se quiere
extraer una subsecuencia del tal forma que en la subsecuencia
extraķda cada nśmero sea divisible por cada uno de los anteriores a él
en la subsecuencia.
Ejemplo:
Para la lista original: 8 3 2 4 6 6 8 10 15 9 25 12 13
- - - ---
Los elementos marcados forman la subsecuencia y cumplen
la propiedad de divisibilidad, o sea, el 6 es divisible por 3 y el
próximo 6 es divisible por 6 y por 3, el 12 es divisible por los
dos 6 y por 3.
Usted debe encontrar la subsecuencia que cumpla los requisitos de
divisibilidad expresados anteriormente y que la cantidad de elementos
de la misma sea mįxima.
Tarea
Hacer un programa que permita:
- Leer desde fichero de entrada SUB.IN la secuencia dada.
- Encontrar la mayor subsecuencia, segśn la definición anteriormente
explicada.
- Escribir hacia el fichero de salida SUB.OUT la cantidad de elementos
de la mayor subsecuencia encontrada y los elementos que la conforman.
Entrada
El fichero de entrada SUB.IN contiene:
Lķnea 1: N (1 <= N <= 2000), cantidad de elementos de la
secuencia.
Lķnea 2..N+1: En la lķnea i+1 se escribirį un valor Mi(0 <=Mi <=10000)
el cual representa al i-ésimo elemento de la secuencia.
Salida
El fichero de salida SUB.OUT contiene:
Lķnea 1: S, el cual representa la cantidad de elementos de la
subsecuencia encontrada.
Lķnea 2..S+1: En cada una de estas se escribirįn un elemento de la
subsecuencia encontrada en el mismo orden en que estos aparecen en
la secuencia original.
Ejemplo de Entrada y Salida
SUB.IN SUB.OUT
13 4
8 3
3 6
2 6
4 12
6
6
8
10
15
9
25
12
13
}
var
fe,fs : text;
n,sol,act : integer;
a,b,cam,res : array[0..2001] of integer;
procedure open;
var
t : integer;
begin
assign(fe,'sub.in'); reset(fe);
assign(fs,'sub.out'); rewrite(fs);
readln(fe,n);
for t:=1 to n do readln(fe,a[t]);
close(fe);
end;
procedure work;
var
i,j : integer;
begin
sol:=0; act:=0;
for i:=1 to n do
begin
for j:=1 to i-1 do
if (b[j] > b[i]) and (a[i] mod a[j] = 0) then
begin
b[i]:=b[j];
cam[i]:=j;
end;
inc(b[i]);
if b[i] > sol then
begin
sol:=b[i];
act:=i;
end;
end;
end;
procedure closer;
var
t : integer;
begin
t:=1; res[1]:=act;
while t < sol do
begin
act:=cam[act];
inc(t);
res[t]:=act;
end;
writeln(fs,sol);
for t:=sol downto 1 do writeln(fs,a[res[t]]);
close(fs);
end;
begin
open;
work;
closer;
end. |
unit kiwi.s3.bucket;
interface
uses
system.classes,
system.sysutils,
system.generics.collections,
data.cloud.amazonapi,
kiwi.s3.interfaces,
kiwi.s3.objects,
kiwi.s3.objectinfo,
kiwi.s3.consts;
type
tkiwiS3Bucket = class(tinterfacedobject, ikiwiS3Bucket)
private
{ private declarations }
[weak]
fkiwiS3: ikiwiS3;
fstrBucket: string;
fobject: ikiwiS3Object;
function getbucket: string;
public
{ public declarations }
constructor create(pkiwiS3: ikiwiS3; pstraccountName, pstraccountKey: string);
destructor destroy; override;
class function new(powner: ikiwiS3; pstraccountName, pstraccountKey: string): ikiwiS3Bucket;
property bucket: string read getbucket;
function name(pstrBucket: string): ikiwiS3Bucket;
function find(var pListFiles : tlist<ikiwiS3ObjectInfo>; pstrFilterOptions: string = ''; pstrFindFile: string = ''): ikiwiS3;
function &object(pstrobjectName: string): ikiwiS3Object;
end;
implementation
{ tkiwiS3Bucket }
constructor tkiwiS3Bucket.create(pkiwiS3: ikiwiS3; pstraccountName, pstraccountKey: string);
begin
fkiwiS3 := pkiwiS3;
fobject := tkiwiObject.new(pkiwiS3, self);
end;
destructor tkiwiS3Bucket.destroy;
begin
inherited;
end;
function tkiwiS3Bucket.find(var pListFiles: tlist<ikiwiS3ObjectInfo>; pstrFilterOptions, pstrFindFile: string): ikiwiS3;
var
lslamazonOptions: tstringList;
lamazonConnectionInfo : tamazonConnectionInfo;
lstorageService: tamazonStorageService;
lamazonBucketResult: tamazonBucketResult;
begin
result := fkiwiS3;
lslamazonOptions := nil;
lamazonConnectionInfo := nil;
lstorageService := nil;
lamazonBucketResult := nil;
try
try
{Verifica que se passado com parametro o filtro}
if pstrFilterOptions.trim <> '' then
begin
lslAmazonOptions := tstringList.create;
lslAmazonOptions.append(pstrFilterOptions);
end;
{ cria componente de conexao com o s3 }
lamazonConnectionInfo := tamazonConnectionInfo.Create(nil);
lamazonConnectionInfo.queueEndpoint := cstrKiwiS3QueueEndpoint;
lAmazonConnectionInfo.accountName := fkiwiS3.accountName;
lAmazonConnectionInfo.accountKey := fkiwiS3.accountKey;
lAmazonConnectionInfo.StorageEndpoint := cstrKiwiS3Endpoint;
lAmazonConnectionInfo.TableEndpoint := cstrKiwiS3TableEndpoint;
lAmazonConnectionInfo.UseDefaultEndpoints := False;
lstorageService := tamazonStorageService.create(lamazonConnectionInfo);
{ Carrega lista de arquivos e diretorios do backet com o filtro da Api}
lamazonBucketResult := lStorageService.GetBucket(fstrBucket, lslAmazonOptions, nil);
if lslAmazonOptions <> nil then
freeandnil(lslAmazonOptions);
{Procura entre os arquivos listado se existe arquivo de atualização e compara se existe atualização para realizar downloa}
if lamazonBucketResult <> nil then
begin
for var ivObject in lAmazonBucketResult.objects do
if (ivObject.Size > 0) and ((pstrFindFile.trim = '') or (pos(pstrFindFile, ivObject.name) > 0)) then
begin
if pListFiles = nil then
pListFiles := tlist<ikiwiS3ObjectInfo>.create;
pListFiles.Add(
tkiwiS3ObjectInfo.new(
ivObject.Name,
strToDateTime(ivObject.LastModified),
ivObject.ETag,
ivObject.Size,
ivObject.ownerid,
now()
)
);
end;
end;
except
on E: Exception do
raise Exception.Create(E.Message);
end;
finally
if lslAmazonOptions <> nil then
freeandnil(lslAmazonOptions);
if lAmazonConnectionInfo <> nil then
freeandnil(lAmazonConnectionInfo);
if lStorageService <> nil then
freeandnil(lStorageService);
if lAmazonBucketResult <> nil then
freeandnil(lAmazonBucketResult);
end;
end;
function tkiwiS3Bucket.getbucket: string;
begin
result := fstrBucket;
end;
function tkiwiS3Bucket.name(pstrBucket: string): ikiwiS3Bucket;
begin
fstrBucket := pstrBucket;
result := self;
end;
class function tkiwiS3Bucket.new(powner: ikiwiS3; pstraccountName, pstraccountKey: string): ikiwiS3Bucket;
begin
result := self.create(powner, pstraccountName, pstraccountKey);
end;
function tkiwiS3Bucket.&object(pstrobjectName: string): ikiwiS3Object;
begin
result := fobject.name(pstrobjectName);
end;
end.
|
unit Demo.LineChart.Bitcoin;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_LineChart_Bitcoin = class(TDemoBaseFrame)
private
public
procedure GenerateChart; override;
end;
implementation
uses
IdHTTP,
IdSSLOpenSSL,
System.SysUtils,
System.JSON,
System.Generics.Collections,
System.DateUtils;
procedure TDemo_LineChart_Bitcoin.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
procedure GetBitcoinData;
var
I: Integer;
IdHTTP: TIdHTTP;
IdSSL: TIdSSLIOHandlerSocketOpenSSL;
JSonValue: TJSonValue;
Value: TJSONObject;
BitcoinValues: TJSONArray;
DatePrice: TDateTime;
BitcoinPrice: Extended;
const
URL_BITCOIN_MARKET_PRICE = 'https://api.blockchain.info/charts/market-price';
begin
IdHTTP := TIdHTTP.Create(nil);
try
IdHTTP.HTTPOptions := IdHTTP.HTTPOptions + [hoForceEncodeParams];
IdHTTP.HandleRedirects := True;
IdSSL := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
IdSSL.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];
IdHTTP.IOHandler := IdSSL;
JsonValue := TJSonObject.ParseJSONValue(IdHTTP.Get(URL_BITCOIN_MARKET_PRICE));
try
BitcoinValues := (JsonValue as TJSONObject).Get('values').JsonValue as TJSONArray;
if Assigned(BitcoinValues) then
begin
for I := 0 to BitcoinValues.Count - 1 do
begin
Value := BitcoinValues.Items[I] as TJSONObject;
DatePrice := UnixToDateTime(StrToInt(Value.Get('x').JsonValue.Value));
BitcoinPrice := StrToFloat(Value.Get('y').JsonValue.Value);
Chart.Data.AddRow([DatePrice, BitcoinPrice]);
end;
end;
finally
JsonValue.Free;
end;
finally
IdHTTP.Free;
end;
end;
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_AREA_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Date'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Price')
]);
GetBitcoinData;
// Options
Chart.Options.Title('Historial Bitcoin price in US$');
Chart.Options.Legend('position', 'none');
Chart.Options.HAxis('title', 'Date');
Chart.Options.HAxis('format', 'MMM/yy');
//Chart.Options.HAxis('gridlines', 10);
Chart.Options.VAxis('title', 'Price');
Chart.Options.Animation('startup', True);
Chart.Options.Animation('duration', 1000);
Chart.Options.Animation('easing', 'out');
Chart.Options.Crosshair('trigger', 'selection');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_LineChart_Bitcoin);
end.
|
{: ProgressForm<p>
Progress form for the ManuCAD program<p>
<b>History :</b><font size=-1><ul>
<li>13/10/02 - DA - Unit creation
</ul></font>
}
unit ProgressForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;
type
TProgress = class(TForm)
LMessage: TLabel;
ProgressBar: TProgressBar;
private
public
//: update the form contents
procedure UpdateProgress(const Msg: String; ActualPosition, PositionMax: Longint);
end;
var
Progress: TProgress;
implementation
{$R *.dfm}
{ TProgress }
// UpdateProgress
//
{: @param Msg A message to show
@param ActualPosition The actual progress position
@param PositionMax The maximum progress position }
procedure TProgress.UpdateProgress(const Msg: String; ActualPosition,
PositionMax: Integer);
begin
LMessage.Caption := Msg;
ProgressBar.Max := PositionMax;
ProgressBar.Position := ActualPosition;
Application.ProcessMessages;
end;
end.
|
unit UListView;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, db, FileUtil, Forms, Controls, Graphics, Dialogs,
DBGrids, DbCtrls, Menus, StdCtrls, ExtCtrls, UMetaData, USQLRequest, Grids,
UEdit, UFilter;
type
TEvent = Procedure of Object;
{ TListViewForm }
TListViewForm = class(TForm)
AddFilterButton: TButton;
AddRecButton: TButton;
CancelFiltersButton: TButton;
DeleteFiltersButton: TButton;
ExecuteFiltersButton: TButton;
DataSource: TDataSource;
DBNavigator: TDBNavigator;
SQLQuery: TSQLQuery;
DBGrid: TDBGrid;
function KnowName(ATag: Integer): String;
procedure AddRecButtonClick(Sender: TObject);
procedure ChangeColumns(ATag: Integer);
procedure DBGridDblClick(Sender: TObject);
procedure DBGridTitleClick(Column: TColumn);
constructor CreateAndShowForm(ATag: Integer);
procedure MakeQuery;
procedure EditClose(Sender: TObject; var CloseAction: TCloseAction);
procedure ImportFilters(AXComboBox, AYComboBox: TComboBox;
AFilterListBox: TFilterListBox; AColValue, ARowValue: String);
private
FilterListBox: TFilterListBox;
SortFieldTag: Integer;
SortField, SortDesc: Boolean;
EditsForm: array of TEditForm;
end;
Const indent = 37;
Const NumberOfSigns = 6;
var
ListViewForm: array of TListViewForm;
s2: String;
implementation
{$R *.lfm}
{ TListViewForm }
constructor TListViewForm.CreateAndShowForm(ATag: Integer);
begin
Tag := ATag;
Caption := Tables.TablesInf[ATag].Caption;
With SQLQuery do
begin
Active := False;
SQL.Text := SQLRequest.CreateQuery(ATag);
Active := True;
end;
ChangeColumns(ATag);
FilterListBox := TFilterListBox.Create(Self);
With FilterListBox do
begin
Width := 624;
Height := 508;
Left := 610;
Top := 40;
Anchors := [akTop,akRight,akBottom];
Tag := ATag;
Parent := Self;
AddFilterButton.OnClick := @AddFilterButtonClick;
ExecuteFiltersButton.OnClick := @ExecuteFiltersButtonClick;
DeleteFiltersButton.OnClick := @DeleteFiltersButtonClick;
CancelFiltersButton.OnClick := @CancelFiltersButtonClick;
QueryEvent := @MakeQuery;
end;
Show;
end;
function TListViewForm.KnowName(ATag: Integer): String;
begin
With Tables.TablesInf[Self.Tag].Columns[ATag] do
if ReferenceTableName <> '' then
Result := ReferenceTableName + '.' + ReferenceColumnSName
else
Result := Tables.TablesInf[Self.Tag].Name + '.' + Name;
end;
procedure TListViewForm.MakeQuery;
var
AName: String;
begin
With SQLQuery do
begin
Active := False;
Prepare;
SQL.Text := SQLRequest.CreateQuery(Self.Tag) ;
SQLRequest.WriteFilters(SQLQuery, FilterListBox);
if SortField then
begin
AName := KnowName(SortFieldTag);
SQL.Text := SQLRequest.SortField(SQL.Text, AName, SortDesc);
end;
Active := True;
end;
ChangeColumns(Tag);
end;
procedure TListViewForm.ChangeColumns(ATag: Integer);
var
i: Integer = 0;
j: Integer = 0;
begin
With Tables.TablesInf[ATag] do
for i := 0 to High(Columns) do
begin
DBGrid.Columns[j].Visible := Columns[i].Visible;
DBGrid.Columns[j].FieldName := Columns[i].Name;
DBGrid.Columns[j].Title.Caption := Columns[i].Caption;
DBGrid.Columns[j].Width := Columns[i].Width;
DBGrid.Columns[j].Tag := i;
if Columns[j].ReferenceTableName <> '' then
begin
inc(j);
DBGrid.Columns[j].FieldName := Columns[i].ReferenceColumnSName;
DBGrid.Columns[j].Title.Caption := Columns[i].ReferenceColumnCaption;
DBGrid.Columns[j].Width := Columns[i].ReferenceColumnWidth;
DBGrid.Columns[j].Tag := i;
end;
inc(j);
end;
end;
procedure TListViewForm.DBGridDblClick(Sender: TObject);
var
i, IndexEdit: Integer;
BoolEdit: Boolean = False;
AStringList: TStringList;
begin
for i := 0 to High(EditsForm) do
if DBGrid.DataSource.DataSet.Fields[0].Value = EditsForm[i].RecID then
begin
IndexEdit := i;
BoolEdit := True;
end;
if not BoolEdit then
begin
SetLength(EditsForm, Length(EditsForm) + 1);
IndexEdit := High(EditsForm);
EditsForm[IndexEdit] := TEditForm.Create(Self);
EditsForm[IndexEdit].OnClose := @EditClose;
end;
AStringList := TStringList.Create;
With DBGrid.DataSource.DataSet do
for i := 0 to Fields.Count - 1 do
if DBGrid.Columns[i].Visible then
AStringList.Append(Fields[i].Value);
With EditsForm[IndexEdit] do
ShowForm(Self.Tag, DBGrid.DataSource.DataSet.Fields[0].Value, AStringList,
False).Show;
end;
procedure TListViewForm.DBGridTitleClick(Column: TColumn);
begin
if SortFieldTag <> Column.Tag then
begin
SortField := False;
SortDesc := False;
end;
if not SortField then
SortField := True
else
if SortDesc then
begin
SortField := False;
SortDesc := False
end
else
SortDesc := True;
SortFieldTag := Column.Tag;
MakeQuery;
end;
procedure TListViewForm.AddRecButtonClick(Sender: TObject);
var
i: Integer;
AStringList: TStringList;
begin
SetLength(EditsForm, Length(EditsForm) + 1);
EditsForm[High(EditsForm)] := TEditForm.Create(Self);
With EditsForm[High(EditsForm)] do
begin
OnClose := @EditClose;
Tag := High(EditsForm);
AStringList := TStringList.Create;
for i := 0 to DBGrid.Columns.Count - 1 do
if DBGrid.Columns[i].Visible then
AStringList.Append(DBGrid.DataSource.DataSet.Fields[i].Value);
ShowForm(Self.Tag, DBGrid.DataSource.DataSet.Fields[0].Value, AStringList,
True).Show;
end;
end;
procedure TListViewForm.EditClose(Sender: TObject; var CloseAction: TCloseAction);
var
i, j: Integer;
begin
for i := (Sender as TForm).Tag to High(EditsForm) - 1 do
EditsForm[i] := EditsForm[i + 1];
SetLength(EditsForm, Length(EditsForm) - 1);
for i := 0 to High(ListViewForm) do
if ListViewForm[i] <> nil then
begin
ListViewForm[i].MakeQuery;
for j := 0 to High(ListViewForm[i].EditsForm) do
ListViewForm[i].EditsForm[j].RefreshComboBox(ListViewForm[i].Tag);
end;
end;
procedure TListViewForm.ImportFilters(AXComboBox, AYComboBox: TComboBox;
AFilterListBox: TFilterListBox; AColValue, ARowValue: String);
var
i: Integer;
procedure FillFilter(AFilterPanel: TFilterPanel; AName, ASign:Integer;
AValue: String);
begin
With AFilterPanel do
begin
NameComboBox.Itemindex := AName;
ValueEdit.Text := AValue;
SignComboBox.ItemIndex := ASign;
end;
end;
begin
With FilterListBox, Tables.TablesInf[Self.Tag] do
begin
AddFilterButtonClick(Self);
FillFilter(FilterPanels[0], AXComboBox.ItemIndex, 2, AColValue);
AddFilterButtonClick(Self);
FillFilter(FilterPanels[1], AYComboBox.ItemIndex, 2, ARowValue);
for i := 2 to High(AFilterListBox.FilterPanels) + 2 do
begin
AddFilterButtonClick(Self);
With AFilterListBox.FilterPanels[i - 2] do
FillFilter(FilterPanels[i], NameComboBox.ItemIndex,
SignComboBox.ItemIndex, ValueEdit.Text);
end;
ExecuteFiltersButtonClick(Self);
end;
end;
end.
|
unit uTransparentEncryptor;
interface
uses
Windows,
SysUtils,
Generics.Collections,
uMemory,
SyncObjs,
uWinApiRuntime,
uTransparentEncryption;
procedure CloseFileHandle(Handle: THandle);
function IsEncryptedFileHandle(hFile: THandle): Boolean;
procedure InitEncryptedFile(FileName: string; hFile: THandle; AsyncHandle: Boolean);
procedure ReplaceBufferContent(hFile: THandle; var Buffer; dwCurrentFilePosition: Int64; nNumberOfBytesToRead: DWORD; var lpNumberOfBytesRead: DWORD; lpOverlapped: POverlapped; Result: PBOOL);
function FixFileSize(hFile: THandle; lDistanceToMove: DWORD; lpDistanceToMoveHigh: Pointer; dwMoveMethod: DWORD; SeekProc: TSetFilePointerNextHook): DWORD;
function FixFileSizeEx(hFile: THandle; liDistanceToMove: TLargeInteger; const lpNewFilePointer: PLargeInteger; dwMoveMethod: DWORD; SeekExProc: TSetFilePointerExNextHook): BOOL;
procedure StartLib;
procedure StopLib;
procedure AddFileMapping(FileHandle, MappingHandle: THandle);
function IsInternalFileMapping(MappingHandle: THandle): Boolean;
function GetInternalFileMapping(hFileMappingObject: THandle; dwFileOffsetHigh, dwFileOffsetLow: DWORD; dwNumberOfBytesToMap: SIZE_T): Pointer;
function IsEncryptedHandle(FileHandle: THandle): Boolean;
var
IsHookStarted: Boolean;
implementation
var
SyncObj: TCriticalSection = nil;
FFileMappings: TDictionary<Integer, Integer> = nil;
FData: TDictionary<Integer, TEncryptedFile> = nil;
procedure AddFileMapping(FileHandle, MappingHandle: THandle);
begin
if SyncObj = nil then
Exit;
SyncObj.Enter;
try
FFileMappings.Add(MappingHandle, FileHandle);
finally
SyncObj.Leave;
end;
end;
function IsInternalFileMapping(MappingHandle: THandle): Boolean;
begin
if SyncObj = nil then
Exit(False);
SyncObj.Enter;
try
Result := FFileMappings.ContainsKey(MappingHandle);
finally
SyncObj.Leave;
end;
end;
function GetInternalFileMapping(hFileMappingObject: THandle; dwFileOffsetHigh, dwFileOffsetLow: DWORD; dwNumberOfBytesToMap: SIZE_T): Pointer;
var
FileHandle: THandle;
Pos: Int64;
MS: TEncryptedFile;
begin
Result := nil;
if SyncObj = nil then
Exit;
if not IsInternalFileMapping(hFileMappingObject) then
Exit;
FileHandle := FFileMappings[hFileMappingObject];
if FData.ContainsKey(FileHandle) then
begin
Int64Rec(Pos).Hi := dwFileOffsetHigh;
Int64Rec(Pos).Lo := dwFileOffsetLow;
SyncObj.Enter;
try
MS := FData[FileHandle];
finally
SyncObj.Leave;
end;
Result := MS.GetBlock(dwFileOffsetLow, dwNumberOfBytesToMap);
end;
end;
function IsEncryptedHandle(FileHandle: THandle): Boolean;
begin
if SyncObj = nil then
Exit(False);
SyncObj.Enter;
try
Result := FData.ContainsKey(FileHandle);
finally
SyncObj.Leave;
end;
end;
procedure CloseFileHandle(Handle: THandle);
var
MS: TEncryptedFile;
begin
if SyncObj = nil then
Exit;
SyncObj.Enter;
try
if FData.ContainsKey(Handle) then
begin
MS := FData[Handle];
FData.Remove(Handle);
F(MS);
end;
finally
SyncObj.Leave;
end;
end;
procedure InitEncryptedFile(FileName: string; hFile: THandle; AsyncHandle: Boolean);
var
MS: TEncryptedFile;
begin
if hFile = Windows.INVALID_HANDLE_VALUE then
Exit;
if FData.ContainsKey(hFile) then
Exit;
MS := TEncryptedFile.Create(hFile, FileName, AsyncHandle);
try
if MS.CanDecryptWithPasswordRequest(FileName) then
begin
SyncObj.Enter;
try
FData.Add(hFile, MS);
MS := nil;
finally
SyncObj.Leave;
end;
end;
finally
F(MS);
end;
end;
function FixFileSize(hFile: THandle; lDistanceToMove: DWORD; lpDistanceToMoveHigh: Pointer; dwMoveMethod: DWORD; SeekProc: TSetFilePointerNextHook): DWORD;
var
MS: TEncryptedFile;
LastError: Cardinal;
begin
Result := SeekProc(hFile, lDistanceToMove, lpDistanceToMoveHigh, dwMoveMethod);
LastError := GetLastError;
if SyncObj = nil then
Exit;
if not FData.ContainsKey(hFile) then
Exit;
if dwMoveMethod = FILE_END then
begin
SyncObj.Enter;
try
MS := FData[hFile];
finally
SyncObj.Leave;
end;
PDWORD(lpDistanceToMoveHigh)^ := 0;
lDistanceToMove := MS.HeaderSize;
Result := SeekProc(hFile, lDistanceToMove, lpDistanceToMoveHigh, FILE_END);
end;
SetLastError(LastError);
end;
function FixFileSizeEx(hFile: THandle; liDistanceToMove: TLargeInteger; const lpNewFilePointer: PLargeInteger; dwMoveMethod: DWORD; SeekExProc: TSetFilePointerExNextHook): BOOL;
var
MS: TEncryptedFile;
LastError: Cardinal;
begin
Result := SeekExProc(hFile, liDistanceToMove, lpNewFilePointer, dwMoveMethod);
LastError := GetLastError;
if SyncObj = nil then
Exit;
if not FData.ContainsKey(hFile) then
Exit;
if dwMoveMethod = FILE_END then
begin
SyncObj.Enter;
try
MS := FData[hFile];
finally
SyncObj.Leave;
end;
liDistanceToMove := MS.HeaderSize;
Result := SeekExProc(hFile, liDistanceToMove, lpNewFilePointer, FILE_END);
end;
SetLastError(LastError);
end;
function IsEncryptedFileHandle(hFile: THandle): Boolean;
begin
Result := False;
if SyncObj = nil then
Exit;
SyncObj.Enter;
try
if not FData.ContainsKey(hFile) then
Exit;
Result := True;
finally
SyncObj.Leave;
end;
end;
procedure ReplaceBufferContent(hFile: THandle; var Buffer; dwCurrentFilePosition: Int64; nNumberOfBytesToRead: DWORD; var lpNumberOfBytesRead: DWORD; lpOverlapped: POverlapped; Result: PBOOL);
var
MS: TEncryptedFile;
Size: Int64;
begin
if SyncObj = nil then
Exit;
SyncObj.Enter;
try
if not FData.ContainsKey(hFile) then
Exit;
MS := FData[hFile];
finally
SyncObj.Leave;
end;
if not Assigned(lpOverlapped) then
begin
Size := MS.Size;
if dwCurrentFilePosition + lpNumberOfBytesRead > Size then
begin
if Size > dwCurrentFilePosition then
lpNumberOfBytesRead := MS.Size - dwCurrentFilePosition
else
lpNumberOfBytesRead := 0;
FileSeek(hFile, MS.HeaderSize, FILE_END);
//if Assigned(Result) then
// Result^ := False;
end;
end;
MS.ReadBlock(Buffer, dwCurrentFilePosition, nNumberOfBytesToRead, lpOverlapped);
end;
procedure StartLib;
begin
SyncObj := TCriticalSection.Create;
FData := TDictionary<Integer, TEncryptedFile>.Create;
FFileMappings := TDictionary<Integer, Integer>.Create;
IsHookStarted := True;
end;
procedure StopLib;
var
Pair: TPair<Integer, TEncryptedFile>;
begin
IsHookStarted := False;
F(SyncObj);
F(FFileMappings);
for Pair in FData do
Pair.Value.Free;
F(FData);
end;
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is ArrayList.pas. }
{ }
{ The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by }
{ Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) }
{ All rights reserved. }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
// Last modified: $Date: 2005/03/08 15:14:00 $
// For history see end of file
unit JclArrayLists;
{$I jcl.inc}
interface
uses
Classes,
JclBase, JclAbstractContainers, JclContainerIntf;
type
TJclIntfArrayList = class(TJclAbstractContainer, IJclIntfCollection,
IJclIntfList, IJclIntfArray, IJclIntfCloneable)
private
FElementData: TDynIInterfaceArray;
FSize: Integer;
FCapacity: Integer;
procedure SetCapacity(ACapacity: Integer);
protected
procedure Grow; virtual;
{ IJclIntfCollection }
function Add(AInterface: IInterface): Boolean; overload;
function AddAll(ACollection: IJclIntfCollection): Boolean; overload;
procedure Clear;
function Contains(AInterface: IInterface): Boolean;
function ContainsAll(ACollection: IJclIntfCollection): Boolean;
function Equals(ACollection: IJclIntfCollection): Boolean;
function First: IJclIntfIterator;
function IsEmpty: Boolean;
function Last: IJclIntfIterator;
function Remove(AInterface: IInterface): Boolean; overload;
function RemoveAll(ACollection: IJclIntfCollection): Boolean;
function RetainAll(ACollection: IJclIntfCollection): Boolean;
function Size: Integer;
{ IJclIntfList }
procedure Insert(Index: Integer; AInterface: IInterface); overload;
function InsertAll(Index: Integer; ACollection: IJclIntfCollection): Boolean; overload;
function GetObject(Index: Integer): IInterface;
function IndexOf(AInterface: IInterface): Integer;
function LastIndexOf(AInterface: IInterface): Integer;
function Remove(Index: Integer): IInterface; overload;
procedure SetObject(Index: Integer; AInterface: IInterface);
function SubList(First, Count: Integer): IJclIntfList;
{ IJclIntfCloneable }
function Clone: IInterface;
public
constructor Create(ACapacity: Integer = DefaultContainerCapacity); overload;
constructor Create(ACollection: IJclIntfCollection); overload;
destructor Destroy; override;
property Capacity: Integer read FCapacity write SetCapacity;
end;
//Daniele Teti 02/03/2005
TJclStrArrayList = class(TJclStrCollection, IJclStrList, IJclStrArray, IJclCloneable)
private
FCapacity: Integer;
FElementData: TDynStringArray;
FSize: Integer;
procedure SetCapacity(ACapacity: Integer);
protected
procedure Grow; virtual;
{ IJclStrCollection }
function Add(const AString: string): Boolean; overload; override;
function AddAll(ACollection: IJclStrCollection): Boolean; overload; override;
procedure Clear; override;
function Contains(const AString: string): Boolean; override;
function ContainsAll(ACollection: IJclStrCollection): Boolean; override;
function Equals(ACollection: IJclStrCollection): Boolean; override;
function First: IJclStrIterator; override;
function IsEmpty: Boolean; override;
function Last: IJclStrIterator; override;
function Remove(const AString: string): Boolean; overload; override;
function RemoveAll(ACollection: IJclStrCollection): Boolean; override;
function RetainAll(ACollection: IJclStrCollection): Boolean; override;
function Size: Integer; override;
{ IJclStrList }
procedure Insert(Index: Integer; const AString: string); overload;
function InsertAll(Index: Integer; ACollection: IJclStrCollection): Boolean; overload;
function GetString(Index: Integer): string;
function IndexOf(const AString: string): Integer;
function LastIndexOf(const AString: string): Integer;
function Remove(Index: Integer): string; overload;
procedure SetString(Index: Integer; const AString: string);
function SubList(First, Count: Integer): IJclStrList;
public
constructor Create(ACapacity: Integer = DefaultContainerCapacity); overload;
constructor Create(ACollection: IJclStrCollection); overload;
destructor Destroy; override;
{ IJclCloneable }
function Clone: TObject;
property Capacity: Integer read FCapacity write SetCapacity;
end;
TJclArrayList = class(TJclAbstractContainer, IJclCollection, IJclList,
IJclArray, IJclCloneable)
private
FCapacity: Integer;
FElementData: TDynObjectArray;
FOwnsObjects: Boolean;
FSize: Integer;
procedure SetCapacity(ACapacity: Integer);
protected
procedure Grow; virtual;
procedure FreeObject(var AObject: TObject);
{ IJclCollection }
function Add(AObject: TObject): Boolean; overload;
function AddAll(ACollection: IJclCollection): Boolean; overload;
procedure Clear;
function Contains(AObject: TObject): Boolean;
function ContainsAll(ACollection: IJclCollection): Boolean;
function Equals(ACollection: IJclCollection): Boolean;
function First: IJclIterator;
function IsEmpty: Boolean;
function Last: IJclIterator;
function Remove(AObject: TObject): Boolean; overload;
function RemoveAll(ACollection: IJclCollection): Boolean;
function RetainAll(ACollection: IJclCollection): Boolean;
function Size: Integer;
{ IJclList }
procedure Insert(Index: Integer; AObject: TObject); overload;
function InsertAll(Index: Integer; ACollection: IJclCollection): Boolean; overload;
function GetObject(Index: Integer): TObject;
function IndexOf(AObject: TObject): Integer;
function LastIndexOf(AObject: TObject): Integer;
function Remove(Index: Integer): TObject; overload;
procedure SetObject(Index: Integer; AObject: TObject);
function SubList(First, Count: Integer): IJclList;
{ IJclCloneable }
function Clone: TObject;
public
constructor Create(ACapacity: Integer = DefaultContainerCapacity; AOwnsObjects: Boolean = True); overload;
constructor Create(ACollection: IJclCollection; AOwnsObjects: Boolean = True); overload;
destructor Destroy; override;
property Capacity: Integer read FCapacity write SetCapacity;
property OwnsObjects: Boolean read FOwnsObjects;
end;
implementation
uses
SysUtils,
JclResources;
//=== { TIntfItr } ===========================================================
type
TIntfItr = class(TJclAbstractContainer, IJclIntfIterator)
private
FCursor: Integer;
FOwnList: TJclIntfArrayList;
//FLastRet: Integer;
FSize: Integer;
protected
{ IJclIntfIterator}
procedure Add(AInterface: IInterface);
function GetObject: IInterface;
function HasNext: Boolean;
function HasPrevious: Boolean;
function Next: IInterface;
function NextIndex: Integer;
function Previous: IInterface;
function PreviousIndex: Integer;
procedure Remove;
procedure SetObject(AInterface: IInterface);
public
constructor Create(AOwnList: TJclIntfArrayList);
destructor Destroy; override;
end;
constructor TIntfItr.Create(AOwnList: TJclIntfArrayList);
begin
inherited Create;
FCursor := 0;
FOwnList := AOwnList;
FOwnList._AddRef; // Add a ref because FOwnList is not an interface !
//FLastRet := -1;
FSize := FOwnList.Size;
end;
destructor TIntfItr.Destroy;
begin
FOwnList._Release;
inherited Destroy;
end;
procedure TIntfItr.Add(AInterface: IInterface);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
// inlined FOwnList.Add
if FOwnList.FSize = FOwnList.Capacity then
FOwnList.Grow;
if FOwnList.FSize <> FCursor then
System.Move(FOwnList.FElementData[FCursor], FOwnList.FElementData[FCursor + 1],
(FOwnList.FSize - FCursor) * SizeOf(IInterface));
// (rom) otherwise interface reference counting may crash
FillChar(FOwnList.FElementData[FCursor], SizeOf(IInterface), 0);
FOwnList.FElementData[FCursor] := AInterface;
Inc(FOwnList.FSize);
Inc(FSize);
Inc(FCursor);
//FLastRet := -1;
end;
function TIntfItr.GetObject: IInterface;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := FOwnList.FElementData[FCursor];
end;
function TIntfItr.HasNext: Boolean;
begin
Result := FCursor < FSize;
end;
function TIntfItr.HasPrevious: Boolean;
begin
Result := FCursor > 0;
end;
function TIntfItr.Next: IInterface;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := FOwnList.FElementData[FCursor];
//FLastRet := FCursor;
Inc(FCursor);
end;
function TIntfItr.NextIndex: Integer;
begin
Result := FCursor;
end;
function TIntfItr.Previous: IInterface;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Dec(FCursor);
//FLastRet := FCursor;
Result := FOwnList.FElementData[FCursor];
end;
function TIntfItr.PreviousIndex: Integer;
begin
Result := FCursor - 1;
end;
procedure TIntfItr.Remove;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
with FOwnList do
begin
FElementData[FCursor] := nil; // Force Release
if FSize <> FCursor then
System.Move(FElementData[FCursor + 1], FElementData[FCursor],
(FSize - FCursor) * SizeOf(IInterface));
end;
Dec(FOwnList.FSize);
Dec(FSize);
end;
procedure TIntfItr.SetObject(AInterface: IInterface);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{
if FLastRet = -1 then
raise EJclIllegalState.Create(SIllegalState);
}
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
FOwnList.FElementData[FCursor] := AInterface;
end;
//=== { TStrItr } ============================================================
type
TStrItr = class(TJclAbstractContainer, IJclStrIterator)
private
FCursor: Integer;
FOwnList: TJclStrArrayList;
//FLastRet: Integer;
FSize: Integer;
protected
{ IJclStrIterator}
procedure Add(const AString: string);
function GetString: string;
function HasNext: Boolean;
function HasPrevious: Boolean;
function Next: string;
function NextIndex: Integer;
function Previous: string;
function PreviousIndex: Integer;
procedure Remove;
procedure SetString(const AString: string);
public
constructor Create(AOwnList: TJclStrArrayList);
destructor Destroy; override;
end;
constructor TStrItr.Create(AOwnList: TJclStrArrayList);
begin
inherited Create;
FCursor := 0;
FOwnList := AOwnList;
FOwnList._AddRef; // Add a ref because FOwnList is not an interface !
//FLastRet := -1;
FSize := FOwnList.Size;
end;
destructor TStrItr.Destroy;
begin
FOwnList._Release;
inherited Destroy;
end;
procedure TStrItr.Add(const AString: string);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
// inlined FOwnList.Add
if FOwnList.FSize = FOwnList.Capacity then
FOwnList.Grow;
if FOwnList.FSize <> FCursor then
System.Move(FOwnList.FElementData[FCursor], FOwnList.FElementData[FCursor + 1],
(FOwnList.FSize - FCursor) * SizeOf(string));
// (rom) otherwise string reference counting may crash
FillChar(FOwnList.FElementData[FCursor], SizeOf(string), 0);
FOwnList.FElementData[FCursor] := AString;
Inc(FOwnList.FSize);
Inc(FSize);
Inc(FCursor);
//FLastRet := -1;
end;
function TStrItr.GetString: string;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := FOwnList.FElementData[FCursor];
end;
function TStrItr.HasNext: Boolean;
begin
Result := FCursor < FSize;
end;
function TStrItr.HasPrevious: Boolean;
begin
Result := FCursor > 0;
end;
function TStrItr.Next: string;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := FOwnList.FElementData[FCursor];
//FLastRet := FCursor;
Inc(FCursor);
end;
function TStrItr.NextIndex: Integer;
begin
Result := FCursor;
end;
function TStrItr.Previous: string;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Dec(FCursor);
//FLastRet := FCursor;
Result := FOwnList.FElementData[FCursor];
end;
function TStrItr.PreviousIndex: Integer;
begin
Result := FCursor - 1;
end;
procedure TStrItr.Remove;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
with FOwnList do
begin
FElementData[FCursor] := ''; // Force Release
if FSize <> FCursor then
System.Move(FElementData[FCursor + 1], FElementData[FCursor],
(FSize - FCursor) * SizeOf(string));
end;
Dec(FOwnList.FSize);
Dec(FSize);
end;
procedure TStrItr.SetString(const AString: string);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{
if FLastRet = -1 then
raise EJclIllegalState.Create(SIllegalState);
}
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
FOwnList.FElementData[FCursor] := AString;
end;
//=== { TItr } ===============================================================
type
TItr = class(TJclAbstractContainer, IJclIterator)
private
FCursor: Integer;
FOwnList: TJclArrayList;
//FLastRet: Integer;
FSize: Integer;
protected
{ IJclIterator}
procedure Add(AObject: TObject);
function GetObject: TObject;
function HasNext: Boolean;
function HasPrevious: Boolean;
function Next: TObject;
function NextIndex: Integer;
function Previous: TObject;
function PreviousIndex: Integer;
procedure Remove;
procedure SetObject(AObject: TObject);
public
constructor Create(AOwnList: TJclArrayList);
destructor Destroy; override;
end;
constructor TItr.Create(AOwnList: TJclArrayList);
begin
inherited Create;
FCursor := 0;
FOwnList := AOwnList;
FOwnList._AddRef; // Add a ref because FOwnList is not an interface !
//FLastRet := -1;
FSize := FOwnList.Size;
end;
destructor TItr.Destroy;
begin
FOwnList._Release;
inherited Destroy;
end;
procedure TItr.Add(AObject: TObject);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
// inlined FOwnList.Add
if FOwnList.FSize = FOwnList.Capacity then
FOwnList.Grow;
if FOwnList.FSize <> FCursor then
System.Move(FOwnList.FElementData[FCursor], FOwnList.FElementData[FCursor + 1],
(FOwnList.FSize - FCursor) * SizeOf(TObject));
FOwnList.FElementData[FCursor] := AObject;
Inc(FOwnList.FSize);
Inc(FSize);
Inc(FCursor);
//FLastRet := -1;
end;
function TItr.GetObject: TObject;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := FOwnList.FElementData[FCursor];
end;
function TItr.HasNext: Boolean;
begin
Result := FCursor <> FSize;
end;
function TItr.HasPrevious: Boolean;
begin
Result := FCursor > 0;
end;
function TItr.Next: TObject;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := FOwnList.FElementData[FCursor];
//FLastRet := FCursor;
Inc(FCursor);
end;
function TItr.NextIndex: Integer;
begin
Result := FCursor;
end;
function TItr.Previous: TObject;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Dec(FCursor);
//FLastRet := FCursor;
Result := FOwnList.FElementData[FCursor];
end;
function TItr.PreviousIndex: Integer;
begin
Result := FCursor - 1;
end;
procedure TItr.Remove;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
with FOwnList do
begin
FreeObject(FElementData[FCursor]);
if FSize <> FCursor then
System.Move(FElementData[FCursor + 1], FElementData[FCursor],
(FSize - FCursor) * SizeOf(TObject));
end;
Dec(FOwnList.FSize);
Dec(FSize);
end;
procedure TItr.SetObject(AObject: TObject);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
FOwnList.FElementData[FCursor] := AObject;
end;
//=== { TJclIntfArrayList } ==================================================
constructor TJclIntfArrayList.Create(ACapacity: Integer = DefaultContainerCapacity);
begin
inherited Create;
FSize := 0;
if ACapacity < 0 then
FCapacity := 0
else
FCapacity := ACapacity;
SetLength(FElementData, FCapacity);
end;
constructor TJclIntfArrayList.Create(ACollection: IJclIntfCollection);
begin
// (rom) disabled because the following Create already calls inherited
// inherited Create;
if ACollection = nil then
raise EJclIllegalArgumentError.CreateRes(@RsENoCollection);
Create(ACollection.Size);
AddAll(ACollection);
end;
destructor TJclIntfArrayList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TJclIntfArrayList.Insert(Index: Integer; AInterface: IInterface);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index > FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
if FSize = Capacity then
Grow;
if FSize <> Index then
System.Move(FElementData[Index], FElementData[Index + 1],
(FSize - Index) * SizeOf(IInterface));
// (rom) otherwise interface reference counting may crash
FillChar(FElementData[Index], SizeOf(IInterface), 0);
FElementData[Index] := AInterface;
Inc(FSize);
end;
function TJclIntfArrayList.InsertAll(Index: Integer; ACollection: IJclIntfCollection): Boolean;
var
It: IJclIntfIterator;
Size: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if (Index < 0) or (Index >= FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
if ACollection = nil then
Exit;
Size := ACollection.Size;
if FSize + Size >= Capacity then
Capacity := FSize + Size;
if Size <> 0 then
System.Move(FElementData[Index], FElementData[Index + Size],
Size * SizeOf(IInterface));
// (rom) otherwise interface reference counting may crash
FillChar(FElementData[Index], Size * SizeOf(IInterface), 0);
It := ACollection.First;
Result := It.HasNext;
while It.HasNext do
begin
FElementData[Index] := It.Next;
Inc(Index);
end;
end;
function TJclIntfArrayList.Add(AInterface: IInterface): Boolean;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if FSize = Capacity then
Grow;
FillChar(FElementData[FSize], SizeOf(IInterface), 0);
FElementData[FSize] := AInterface;
Inc(FSize);
Result := True;
end;
function TJclIntfArrayList.AddAll(ACollection: IJclIntfCollection): Boolean;
var
It: IJclIntfIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if ACollection = nil then
Exit;
It := ACollection.First;
while It.HasNext do
begin
// (rom) inlining Add() gives about 5 percent performance increase
if FSize = Capacity then
Grow;
FillChar(FElementData[FSize], SizeOf(IInterface), 0);
FElementData[FSize] := It.Next;
Inc(FSize);
end;
Result := True;
end;
procedure TJclIntfArrayList.Clear;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
for I := 0 to FSize - 1 do
FElementData[I] := nil;
FSize := 0;
end;
function TJclIntfArrayList.Clone: IInterface;
var
NewList: IJclIntfList;
begin
NewList := TJclIntfArrayList.Create(Capacity);
NewList.AddAll(Self);
Result := NewList;
end;
function TJclIntfArrayList.Contains(AInterface: IInterface): Boolean;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if AInterface = nil then
Exit;
for I := 0 to FSize - 1 do
if FElementData[I] = AInterface then
begin
Result := True;
Break;
end;
end;
function TJclIntfArrayList.ContainsAll(ACollection: IJclIntfCollection): Boolean;
var
It: IJclIntfIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := True;
if ACollection = nil then
Exit;
It := ACollection.First;
while Result and It.HasNext do
Result := contains(It.Next);
end;
function TJclIntfArrayList.Equals(ACollection: IJclIntfCollection): Boolean;
var
I: Integer;
It: IJclIntfIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if ACollection = nil then
Exit;
if FSize <> ACollection.Size then
Exit;
It := ACollection.First;
for I := 0 to FSize - 1 do
if FElementData[I] <> It.Next then
Exit;
Result := True;
end;
function TJclIntfArrayList.GetObject(Index: Integer): IInterface;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index >= FSize) then
Result := nil
else
Result := FElementData[Index];
end;
procedure TJclIntfArrayList.SetCapacity(ACapacity: Integer);
begin
if ACapacity >= FSize then
begin
SetLength(FElementData, ACapacity);
FCapacity := ACapacity;
end
else
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
end;
procedure TJclIntfArrayList.Grow;
begin
if Capacity > 64 then
Capacity := Capacity + Capacity div 4
else if FCapacity = 0 then
FCapacity := 64
else
Capacity := Capacity * 4;
end;
function TJclIntfArrayList.IndexOf(AInterface: IInterface): Integer;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := -1;
if AInterface = nil then
Exit;
for I := 0 to FSize - 1 do
if FElementData[I] = AInterface then
begin
Result := I;
Break;
end;
end;
function TJclIntfArrayList.First: IJclIntfIterator;
begin
Result := TIntfItr.Create(Self);
end;
function TJclIntfArrayList.IsEmpty: Boolean;
begin
Result := FSize = 0;
end;
function TJclIntfArrayList.Last: IJclIntfIterator;
var
NewIterator: TIntfItr;
begin
NewIterator := TIntfItr.Create(Self);
NewIterator.FCursor := NewIterator.FOwnList.FSize;
NewIterator.FSize := NewIterator.FOwnList.FSize;
Result := NewIterator;
end;
function TJclIntfArrayList.LastIndexOf(AInterface: IInterface): Integer;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := -1;
if AInterface = nil then
Exit;
for I := FSize - 1 downto 0 do
if FElementData[I] = AInterface then
begin
Result := I;
Break;
end;
end;
function TJclIntfArrayList.Remove(AInterface: IInterface): Boolean;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if AInterface = nil then
Exit;
for I := FSize - 1 downto 0 do
if FElementData[I] = AInterface then // Removes all AInterface
begin
FElementData[I] := nil; // Force Release
if FSize <> I then
System.Move(FElementData[I + 1], FElementData[I],
(FSize - I) * SizeOf(IInterface));
Dec(FSize);
Result := True;
end;
end;
function TJclIntfArrayList.Remove(Index: Integer): IInterface;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index >= FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
Result := FElementData[Index];
FElementData[Index] := nil;
if FSize <> Index then
System.Move(FElementData[Index + 1], FElementData[Index],
(FSize - Index) * SizeOf(IInterface));
Dec(FSize);
end;
function TJclIntfArrayList.RemoveAll(ACollection: IJclIntfCollection): Boolean;
var
It: IJclIntfIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := True;
if ACollection = nil then
Exit;
It := ACollection.First;
while It.HasNext do
Result := Remove(It.Next) and Result;
end;
function TJclIntfArrayList.RetainAll(ACollection: IJclIntfCollection): Boolean;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if ACollection = nil then
Exit;
for I := FSize - 1 downto 0 do
if not ACollection.Contains(FElementData[I]) then
Remove(I);
end;
procedure TJclIntfArrayList.SetObject(Index: Integer; AInterface: IInterface);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index >= FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
FElementData[Index] := AInterface;
end;
function TJclIntfArrayList.Size: Integer;
begin
Result := FSize;
end;
function TJclIntfArrayList.SubList(First, Count: Integer): IJclIntfList;
var
I: Integer;
Last: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Last := First + Count - 1;
if Last >= FSize then
Last := FSize - 1;
Result := TJclIntfArrayList.Create(Count);
for I := First to Last do
Result.Add(FElementData[I]);
end;
//=== { TJclStrArrayList } ===================================================
constructor TJclStrArrayList.Create(ACapacity: Integer = DefaultContainerCapacity);
begin
inherited Create;
FSize := 0;
if ACapacity < 0 then
FCapacity := 0
else
FCapacity := ACapacity;
SetLength(FElementData, FCapacity);
end;
constructor TJclStrArrayList.Create(ACollection: IJclStrCollection);
begin
// (rom) disabled because the following Create already calls inherited
// inherited Create;
if ACollection = nil then
raise EJclIllegalArgumentError.CreateRes(@RsENoCollection);
Create(ACollection.Size);
AddAll(ACollection);
end;
destructor TJclStrArrayList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TJclStrArrayList.Insert(Index: Integer; const AString: string);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index > FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
if FSize = Capacity then
Grow;
if FSize <> Index then
System.Move(FElementData[Index], FElementData[Index + 1],
(FSize - Index) * SizeOf(string));
// (rom) otherwise string reference counting would crash
FillChar(FElementData[Index], SizeOf(string), 0);
FElementData[Index] := AString;
Inc(FSize);
end;
function TJclStrArrayList.InsertAll(Index: Integer; ACollection: IJclStrCollection): Boolean;
var
It: IJclStrIterator;
Size: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if (Index < 0) or (Index >= FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
if ACollection = nil then
Exit;
Size := ACollection.Size;
if FSize + Size >= Capacity then
begin
Capacity := FSize + Size;
FSize := Capacity;
end;
if Size <> 0 then
System.Move(FElementData[Index], FElementData[Index + Size],
Size * SizeOf(string));
// (rom) otherwise string reference counting would crash
FillChar(FElementData[Index], Size * SizeOf(string), 0);
It := ACollection.First;
Result := It.HasNext;
while It.HasNext do
begin
FElementData[Index] := It.Next;
Inc(Index);
end;
end;
function TJclStrArrayList.Add(const AString: string): Boolean;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if FSize = Capacity then
Grow;
FillChar(FElementData[FSize], SizeOf(string), 0);
FElementData[FSize] := AString;
Inc(FSize);
Result := True;
end;
function TJclStrArrayList.AddAll(ACollection: IJclStrCollection): Boolean;
var
It: IJclStrIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if ACollection = nil then
Exit;
It := ACollection.First;
while It.HasNext do
begin
// (rom) inlining Add() gives about 5 percent performance increase
// without THREADSAFE and about 30 percent with THREADSAFE
if FSize = Capacity then
Grow;
FillChar(FElementData[FSize], SizeOf(string), 0);
FElementData[FSize] := It.Next;
Inc(FSize);
end;
Result := True;
end;
procedure TJclStrArrayList.Clear;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
for I := 0 to FSize - 1 do
FElementData[I] := '';
FSize := 0;
end;
function TJclStrArrayList.Clone: TObject;
var
NewList: TJclStrArrayList;
begin
NewList := TJclStrArrayList.Create(Capacity);
NewList.AddAll(Self);
Result := NewList;
end;
function TJclStrArrayList.Contains(const AString: string): Boolean;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if AString = '' then
Exit;
for I := 0 to FSize - 1 do
if FElementData[I] = AString then
begin
Result := True;
Break;
end;
end;
function TJclStrArrayList.ContainsAll(ACollection: IJclStrCollection): Boolean;
var
It: IJclStrIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := True;
if ACollection = nil then
Exit;
It := ACollection.First;
while Result and It.HasNext do
Result := contains(It.Next);
end;
function TJclStrArrayList.Equals(ACollection: IJclStrCollection): Boolean;
var
I: Integer;
It: IJclStrIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if ACollection = nil then
Exit;
if FSize <> ACollection.Size then
Exit;
It := ACollection.First;
for I := 0 to FSize - 1 do
if FElementData[I] <> It.Next then
Exit;
Result := True;
end;
function TJclStrArrayList.First: IJclStrIterator;
begin
Result := TStrItr.Create(Self);
end;
function TJclStrArrayList.GetString(Index: Integer): string;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index >= FSize) then
Result := ''
else
Result := FElementData[Index];
end;
procedure TJclStrArrayList.SetCapacity(ACapacity: Integer);
begin
if ACapacity >= FSize then
begin
SetLength(FElementData, ACapacity);
FCapacity := ACapacity;
end
else
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
end;
procedure TJclStrArrayList.Grow;
begin
if Capacity > 64 then
Capacity := Capacity + Capacity div 4
else if FCapacity = 0 then
FCapacity := 64
else
Capacity := Capacity * 4;
end;
function TJclStrArrayList.IndexOf(const AString: string): Integer;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := -1;
if AString = '' then
Exit;
for I := 0 to FSize - 1 do
if FElementData[I] = AString then
begin
Result := I;
Break;
end;
end;
function TJclStrArrayList.IsEmpty: Boolean;
begin
Result := FSize = 0;
end;
function TJclStrArrayList.Last: IJclStrIterator;
var
NewIterator: TStrItr;
begin
NewIterator := TStrItr.Create(Self);
NewIterator.FCursor := NewIterator.FOwnList.FSize;
NewIterator.FSize := NewIterator.FOwnList.FSize;
Result := NewIterator;
end;
function TJclStrArrayList.LastIndexOf(const AString: string): Integer;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := -1;
if AString = '' then
Exit;
for I := FSize - 1 downto 0 do
if FElementData[I] = AString then
begin
Result := I;
Break;
end;
end;
function TJclStrArrayList.Remove(const AString: string): Boolean;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if AString = '' then
Exit;
for I := FSize - 1 downto 0 do
if FElementData[I] = AString then // Removes all AString
begin
FElementData[I] := ''; // Force Release
if FSize <> I then
System.Move(FElementData[I + 1], FElementData[I],
(FSize - I) * SizeOf(IInterface));
Dec(FSize);
Result := True;
end;
end;
function TJclStrArrayList.Remove(Index: Integer): string;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index >= FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
Result := FElementData[Index];
FElementData[Index] := '';
if FSize <> Index then
System.Move(FElementData[Index + 1], FElementData[Index],
(FSize - Index) * SizeOf(IInterface));
Dec(FSize);
end;
function TJclStrArrayList.RemoveAll(ACollection: IJclStrCollection): Boolean;
var
It: IJclStrIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := True;
if ACollection = nil then
Exit;
It := ACollection.First;
while It.HasNext do
Result := Remove(It.Next) and Result;
end;
function TJclStrArrayList.RetainAll(ACollection: IJclStrCollection): Boolean;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if ACollection = nil then
Exit;
for I := FSize - 1 downto 0 do
if not ACollection.Contains(FElementData[I]) then
Remove(I);
end;
procedure TJclStrArrayList.SetString(Index: Integer; const AString: string);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index >= FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
FElementData[Index] := AString
end;
function TJclStrArrayList.Size: Integer;
begin
Result := FSize;
end;
function TJclStrArrayList.SubList(First, Count: Integer): IJclStrList;
var
I: Integer;
Last: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Last := First + Count - 1;
if Last >= FSize then
Last := FSize - 1;
Result := TJclStrArrayList.Create(Count);
for I := First to Last do
Result.Add(FElementData[I]);
end;
//=== { TJclArrayList } ======================================================
constructor TJclArrayList.Create(ACapacity: Integer = DefaultContainerCapacity;
AOwnsObjects: Boolean = True);
begin
inherited Create;
FSize := 0;
FOwnsObjects := AOwnsObjects;
if ACapacity < 0 then
FCapacity := 0
else
FCapacity := ACapacity;
SetLength(FElementData, FCapacity);
end;
constructor TJclArrayList.Create(ACollection: IJclCollection; AOwnsObjects: Boolean = True);
begin
// (rom) disabled because the following Create already calls inherited
// inherited Create;
if ACollection = nil then
raise EJclIllegalArgumentError.CreateRes(@RsENoCollection);
Create(ACollection.Size, AOwnsObjects);
AddAll(ACollection);
end;
destructor TJclArrayList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TJclArrayList.Insert(Index: Integer; AObject: TObject);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index > FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
if FSize = Capacity then
Grow;
if FSize <> Index then
System.Move(FElementData[Index], FElementData[Index + 1],
(FSize - Index) * SizeOf(TObject));
FElementData[Index] := AObject;
Inc(FSize);
end;
function TJclArrayList.InsertAll(Index: Integer; ACollection: IJclCollection): Boolean;
var
It: IJclIterator;
Size: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if (Index < 0) or (Index >= FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
if ACollection = nil then
Exit;
Size := ACollection.Size;
if FSize + Size >= Capacity then
Capacity := FSize + Size;
if Size <> 0 then
System.Move(FElementData[Index], FElementData[Index + Size],
Size * SizeOf(IInterface));
It := ACollection.First;
Result := It.HasNext;
while It.HasNext do
begin
FElementData[Index] := It.Next;
Inc(Index);
end;
end;
function TJclArrayList.Add(AObject: TObject): Boolean;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if FSize = Capacity then
Grow;
FElementData[FSize] := AObject;
Inc(FSize);
Result := True;
end;
function TJclArrayList.AddAll(ACollection: IJclCollection): Boolean;
var
It: IJclIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if ACollection = nil then
Exit;
It := ACollection.First;
while It.HasNext do
begin
// (rom) inlining Add() gives about 5 percent performance increase
if FSize = Capacity then
Grow;
FElementData[FSize] := It.Next;
Inc(FSize);
end;
Result := True;
end;
procedure TJclArrayList.Clear;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
for I := 0 to FSize - 1 do
FreeObject(FElementData[I]);
FSize := 0;
end;
function TJclArrayList.Clone: TObject;
var
NewList: TJclArrayList;
begin
NewList := TJclArrayList.Create(Capacity, False); // Only one can have FOwnsObject = True
NewList.AddAll(Self);
Result := NewList;
end;
function TJclArrayList.Contains(AObject: TObject): Boolean;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if AObject = nil then
Exit;
for I := 0 to FSize - 1 do
if FElementData[I] = AObject then
begin
Result := True;
Break;
end;
end;
function TJclArrayList.ContainsAll(ACollection: IJclCollection): Boolean;
var
It: IJclIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := True;
if ACollection = nil then
Exit;
It := ACollection.First;
while Result and It.HasNext do
Result := contains(It.Next);
end;
function TJclArrayList.Equals(ACollection: IJclCollection): Boolean;
var
I: Integer;
It: IJclIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if ACollection = nil then
Exit;
if FSize <> ACollection.Size then
Exit;
It := ACollection.First;
for I := 0 to FSize - 1 do
if FElementData[I] <> It.Next then
Exit;
Result := True;
end;
procedure TJclArrayList.FreeObject(var AObject: TObject);
begin
if FOwnsObjects then
begin
AObject.Free;
AObject := nil;
end;
end;
function TJclArrayList.GetObject(Index: Integer): TObject;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index >= FSize) then
Result := nil
else
Result := FElementData[Index];
end;
procedure TJclArrayList.SetCapacity(ACapacity: Integer);
begin
if ACapacity >= FSize then
begin
SetLength(FElementData, ACapacity);
FCapacity := ACapacity;
end
else
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
end;
procedure TJclArrayList.Grow;
begin
if Capacity > 64 then
Capacity := Capacity + Capacity div 4
else if FCapacity = 0 then
FCapacity := 64
else
Capacity := Capacity * 4;
end;
function TJclArrayList.IndexOf(AObject: TObject): Integer;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := -1;
if AObject = nil then
Exit;
for I := 0 to FSize - 1 do
if FElementData[I] = AObject then
begin
Result := I;
Break;
end;
end;
function TJclArrayList.First: IJclIterator;
begin
Result := TItr.Create(Self);
end;
function TJclArrayList.IsEmpty: Boolean;
begin
Result := FSize = 0;
end;
function TJclArrayList.Last: IJclIterator;
var
NewIterator: TItr;
begin
NewIterator := TItr.Create(Self);
NewIterator.FCursor := NewIterator.FOwnList.FSize;
NewIterator.FSize := NewIterator.FOwnList.FSize;
Result := NewIterator;
end;
function TJclArrayList.LastIndexOf(AObject: TObject): Integer;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := -1;
if AObject = nil then
Exit;
for I := FSize - 1 downto 0 do
if FElementData[I] = AObject then
begin
Result := I;
Break;
end;
end;
function TJclArrayList.Remove(AObject: TObject): Boolean;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if AObject = nil then
Exit;
for I := FSize - 1 downto 0 do
if FElementData[I] = AObject then // Removes all AObject
begin
FreeObject(FElementData[I]);
if FSize <> I then
System.Move(FElementData[I + 1], FElementData[I],
(FSize - I) * SizeOf(TObject));
Dec(FSize);
Result := True;
end;
end;
function TJclArrayList.Remove(Index: Integer): TObject;
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index >= FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
Result := nil;
FreeObject(FElementData[Index]);
if FSize <> Index then
System.Move(FElementData[Index + 1], FElementData[Index],
(FSize - Index) * SizeOf(TObject));
Dec(FSize);
end;
function TJclArrayList.RemoveAll(ACollection: IJclCollection): Boolean;
var
It: IJclIterator;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := True;
if ACollection = nil then
Exit;
It := ACollection.First;
while It.HasNext do
Result := Remove(It.Next) and Result;
end;
function TJclArrayList.RetainAll(ACollection: IJclCollection): Boolean;
var
I: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Result := False;
if ACollection = nil then
Exit;
for I := FSize - 1 to 0 do
if not ACollection.Contains(FElementData[I]) then
Remove(I);
end;
procedure TJclArrayList.SetObject(Index: Integer; AObject: TObject);
{$IFDEF THREADSAFE}
var
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
if (Index < 0) or (Index >= FSize) then
raise EJclOutOfBoundsError.CreateRes(@RsEOutOfBounds);
FElementData[Index] := AObject;
end;
function TJclArrayList.Size: Integer;
begin
Result := FSize;
end;
function TJclArrayList.SubList(First, Count: Integer): IJclList;
var
I: Integer;
Last: Integer;
{$IFDEF THREADSAFE}
CS: IInterface;
{$ENDIF THREADSAFE}
begin
{$IFDEF THREADSAFE}
CS := EnterCriticalSection;
{$ENDIF THREADSAFE}
Last := First + Count - 1;
if Last >= FSize then
Last := FSize - 1;
Result := TJclArrayList.Create(Count, FOwnsObjects);
for I := First to Last do
Result.Add(FElementData[I]);
end;
// History:
// $Log: JclArrayLists.pas,v $
// Revision 1.10 2005/03/08 15:14:00 dade2004
// Fixed some bug on
// IJclStrList.InsertAll implementation
//
// Revision 1.9 2005/03/08 15:03:08 dade2004
// Fixed some bug on
// IJclStrList.InsertAll implementation
//
// Revision 1.8 2005/03/08 08:33:15 marquardt
// overhaul of exceptions and resourcestrings, minor style cleaning
//
// Revision 1.7 2005/03/03 08:02:56 marquardt
// various style cleanings, bugfixes and improvements
//
// Revision 1.6 2005/03/02 17:51:24 rrossmair
// - removed DCLAppendDelimited from JclAlgorithms, changed uses clauses accordingly
//
// Revision 1.5 2005/03/02 09:59:30 dade2004
// Added
// -TJclStrCollection in JclContainerIntf
// Every common methods for IJclStrCollection are implemented here
//
// -Every class that implement IJclStrCollection now derive from TJclStrCollection instead of TJclAbstractContainer
// -Every abstract method in TJclStrCollection has been marked as "override" in descendent classes
//
// DCLAppendDelimited has been removed from JclAlgorothms, his body has been fixed for a bug and put into
// relative method in TJclStrCollection
//
// Revision 1.4 2005/02/27 11:36:19 marquardt
// fixed and secured Capacity/Grow mechanism, raise exceptions with efficient CreateResRec
//
// Revision 1.3 2005/02/27 07:27:47 marquardt
// changed interface names from I to IJcl, moved resourcestrings to JclResource.pas
//
// Revision 1.2 2005/02/24 07:36:24 marquardt
// resolved the compiler warnings, style cleanup, removed code from JclContainerIntf.pas
//
// Revision 1.1 2005/02/24 03:57:10 rrossmair
// - donated DCL code, initial check-in
//
end.
|
unit ojVirtualStringTreeDesign;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ojVirtualTrees, StdCtrls, CheckLst;
type
TojVirtualStringTreeDesignForm = class(TForm)
chAutoOptionsList: TCheckListBox;
Label1: TLabel;
Label2: TLabel;
chMiscOptionsList: TCheckListBox;
Label3: TLabel;
chPaintOptionsList: TCheckListBox;
Label4: TLabel;
chSelectionOptionsList: TCheckListBox;
lblInfo: TLabel;
Label5: TLabel;
chAnimationOptionsList: TCheckListBox;
chStringOptionsList: TCheckListBox;
Label6: TLabel;
btnRestoreAutoOptions: TButton;
btnRestoreSelectionOptions: TButton;
btnRestorePaintOptions: TButton;
btnRestoreMiscOptions: TButton;
btnRestoreAnimationOptions: TButton;
btnRestoreStringOptions: TButton;
procedure chAutoOptionsListClickCheck(Sender: TObject);
procedure chMiscOptionsListClickCheck(Sender: TObject);
procedure chPaintOptionsListClickCheck(Sender: TObject);
procedure chSelectionOptionsListClickCheck(Sender: TObject);
procedure chAutoOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure chAnimationOptionsListClickCheck(Sender: TObject);
procedure chStringOptionsListClickCheck(Sender: TObject);
procedure chAnimationOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure chStringOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure chMiscOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure chPaintOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure chSelectionOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure btnRestoreAutoOptionsClick(Sender: TObject);
procedure btnRestoreSelectionOptionsClick(Sender: TObject);
procedure btnRestorePaintOptionsClick(Sender: TObject);
procedure btnRestoreMiscOptionsClick(Sender: TObject);
procedure btnRestoreAnimationOptionsClick(Sender: TObject);
procedure btnRestoreStringOptionsClick(Sender: TObject);
private
FVirtualTree: TojCustomVirtualStringTree;
protected
procedure FillAutoOptionsList;
procedure FillMiscOptionsList;
procedure FillPaintOptionsList;
procedure FillSelectionOptionsList;
procedure FillStringOptionsList;
procedure FillAnimationOptionsList;
public
constructor Create(AOwner: TComponent; VirtualTree: TojCustomVirtualStringTree);reintroduce;overload;virtual;
function getVirtualTree: TojBaseVirtualTree;
public
class procedure ShowDesigner(p_VirtualTree: TojCustomVirtualStringTree);
end;
implementation
uses typInfo;
{$R *.dfm}
type
TFakeCustomVirtualStringTree = class(TojCustomVirtualStringTree);
TFakeCustomVirtualTreeOptions = class(TCustomVirtualTreeOptions);
TFakeCustomStringTreeOptions = class(TCustomStringTreeOptions);
{ TVirtualStringTreeDesignForm }
procedure TojVirtualStringTreeDesignForm.btnRestoreAnimationOptionsClick(Sender: TObject);
var v_tree: TFakeCustomVirtualStringTree;
begin
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AnimationOptions:= DefaultAnimationOptions;
FillAnimationOptionsList;
end;
procedure TojVirtualStringTreeDesignForm.btnRestoreAutoOptionsClick(Sender: TObject);
var v_tree: TFakeCustomVirtualStringTree;
begin
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AnimationOptions:= DefaultAnimationOptions;
FillAutoOptionsList;
end;
procedure TojVirtualStringTreeDesignForm.btnRestoreMiscOptionsClick(Sender: TObject);
var v_tree: TFakeCustomVirtualStringTree;
begin
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).MiscOptions:= DefaultMiscOptions;
FillMiscOptionsList;
end;
procedure TojVirtualStringTreeDesignForm.btnRestorePaintOptionsClick(Sender: TObject);
var v_tree: TFakeCustomVirtualStringTree;
begin
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).PaintOptions:= DefaultPaintOptions;
FillPaintOptionsList;
end;
procedure TojVirtualStringTreeDesignForm.btnRestoreSelectionOptionsClick(Sender: TObject);
var v_tree: TFakeCustomVirtualStringTree;
begin
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).SelectionOptions:= DefaultSelectionOptions;
FillSelectionOptionsList;
end;
procedure TojVirtualStringTreeDesignForm.btnRestoreStringOptionsClick(Sender: TObject);
var v_tree: TFakeCustomVirtualStringTree;
begin
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
TFakeCustomStringTreeOptions(TFakeCustomVirtualTreeOptions(v_tree.TreeOptions)).StringOptions:= DefaultStringOptions;
FillStringOptionsList;
end;
procedure TojVirtualStringTreeDesignForm.chAnimationOptionsListClickCheck(Sender: TObject);
var v_opt: TVTAnimationOption;
v_opts: TVTAnimationOptions;
v_tree: TFakeCustomVirtualStringTree;
i: integer;
begin
v_opts:= [];
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for i:= 0 to chAnimationOptionsList.Items.Count-1 do
if chAnimationOptionsList.Checked[i] then
begin
v_opt:= TVTAnimationOption(GetEnumValue(TypeInfo(TVTAnimationOption), chAnimationOptionsList.Items[i]));
v_opts:= v_opts + [v_opt];
end;
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AnimationOptions:= v_opts;
end;
procedure TojVirtualStringTreeDesignForm.chAnimationOptionsListMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
var v_idx: Integer;
v_opt: TVTAnimationOption;
begin
v_idx:= chAnimationOptionsList.ItemAtPos(Point(X, Y), TRUE);
if v_idx >= 0 then
begin
v_opt:= TVTAnimationOption(GetEnumValue(TypeInfo(TVTAnimationOption), chAnimationOptionsList.Items[v_idx]));
// lblInfo.Caption:= VTAutoOptionDescriptions[v_opt];
lblInfo.Caption:= chAnimationOptionsList.Items[v_idx] + ':' + sLineBreak +
VTAnimationOptionDescriptions[v_opt];
end
else
lblInfo.Caption:= '';
end;
procedure TojVirtualStringTreeDesignForm.chAutoOptionsListClickCheck(Sender: TObject);
var v_opt: TVTAutoOption;
v_opts: TVTAutoOptions;
v_tree: TFakeCustomVirtualStringTree;
i: integer;
begin
v_opts:= [];
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for i:= 0 to chAutoOptionsList.Items.Count-1 do
if chAutoOptionsList.Checked[i] then
begin
v_opt:= TVTAutoOption(GetEnumValue(TypeInfo(TVTAutoOption), chAutoOptionsList.Items[i]));
v_opts:= v_opts + [v_opt];
end;
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AutoOptions:= v_opts;
end;
procedure TojVirtualStringTreeDesignForm.chAutoOptionsListMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
var v_idx: Integer;
v_opt: TVTAutoOption;
begin
v_idx:= chAutoOptionsList.ItemAtPos(Point(X, Y), TRUE);
if v_idx >= 0 then
begin
v_opt:= TVTAutoOption(GetEnumValue(TypeInfo(TVTAutoOption), chAutoOptionsList.Items[v_idx]));
// lblInfo.Caption:= VTAutoOptionDescriptions[v_opt];
lblInfo.Caption:= chAutoOptionsList.Items[v_idx] + ':' + sLineBreak +
VTAutoOptionDescriptions[v_opt];
end
else
lblInfo.Caption:= '';
end;
procedure TojVirtualStringTreeDesignForm.chMiscOptionsListClickCheck(Sender: TObject);
var v_opt: TVTMiscOption;
v_opts: TVTMiscOptions;
v_tree: TFakeCustomVirtualStringTree;
i: integer;
begin
v_opts:= [];
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for i:= 0 to chMiscOptionsList.Items.Count-1 do
if chMiscOptionsList.Checked[i] then
begin
v_opt:= TVTMiscOption(GetEnumValue(TypeInfo(TVTMiscOption), chMiscOptionsList.Items[i]));
v_opts:= v_opts + [v_opt];
end;
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).MiscOptions:= v_opts;
end;
procedure TojVirtualStringTreeDesignForm.chMiscOptionsListMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
var v_idx: Integer;
v_opt: TVTMiscOption;
begin
v_idx:= chMiscOptionsList.ItemAtPos(Point(X, Y), TRUE);
if v_idx >= 0 then
begin
v_opt:= TVTMiscOption(GetEnumValue(TypeInfo(TVTMiscOption), chMiscOptionsList.Items[v_idx]));
// lblInfo.Caption:= VTAutoOptionDescriptions[v_opt];
lblInfo.Caption:= chMiscOptionsList.Items[v_idx] + ':' + sLineBreak +
VTMiscOptionDescriptions[v_opt];
end
else
lblInfo.Caption:= '';
end;
procedure TojVirtualStringTreeDesignForm.chPaintOptionsListClickCheck(Sender: TObject);
var v_opt: TVTPaintOption;
v_opts: TVTPaintOptions;
v_tree: TFakeCustomVirtualStringTree;
i: integer;
begin
v_opts:= [];
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for i:= 0 to chPaintOptionsList.Items.Count-1 do
if chPaintOptionsList.Checked[i] then
begin
v_opt:= TVTPaintOption(GetEnumValue(TypeInfo(TVTPaintOption), chPaintOptionsList.Items[i]));
v_opts:= v_opts + [v_opt];
end;
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).PaintOptions:= v_opts;
end;
procedure TojVirtualStringTreeDesignForm.chPaintOptionsListMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
var v_idx: Integer;
v_opt: TVTPaintOption;
begin
v_idx:= chPaintOptionsList.ItemAtPos(Point(X, Y), TRUE);
if v_idx >= 0 then
begin
v_opt:= TVTPaintOption(GetEnumValue(TypeInfo(TVTPaintOption), chPaintOptionsList.Items[v_idx]));
// lblInfo.Caption:= VTAutoOptionDescriptions[v_opt];
lblInfo.Caption:= chPaintOptionsList.Items[v_idx] + ':' + sLineBreak +
VTPaintOptionDescriptions[v_opt];
end
else
lblInfo.Caption:= '';
end;
procedure TojVirtualStringTreeDesignForm.chSelectionOptionsListClickCheck(Sender: TObject);
var v_opt: TVTSelectionOption;
v_opts: TVTSelectionOptions;
v_tree: TFakeCustomVirtualStringTree;
i: integer;
begin
v_opts:= [];
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for i:= 0 to chSelectionOptionsList.Items.Count-1 do
if chSelectionOptionsList.Checked[i] then
begin
v_opt:= TVTSelectionOption(GetEnumValue(TypeInfo(TVTSelectionOption), chSelectionOptionsList.Items[i]));
v_opts:= v_opts + [v_opt];
end;
TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).SelectionOptions:= v_opts;
end;
procedure TojVirtualStringTreeDesignForm.chSelectionOptionsListMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
var v_idx: Integer;
v_opt: TVTSelectionOption;
begin
v_idx:= chSelectionOptionsList.ItemAtPos(Point(X, Y), TRUE);
if v_idx >= 0 then
begin
v_opt:= TVTSelectionOption(GetEnumValue(TypeInfo(TVTSelectionOption), chSelectionOptionsList.Items[v_idx]));
// lblInfo.Caption:= VTAutoOptionDescriptions[v_opt];
lblInfo.Caption:= chSelectionOptionsList.Items[v_idx] + ':' + sLineBreak +
VTSelectionOptionDescriptions[v_opt];
end
else
lblInfo.Caption:= '';
end;
procedure TojVirtualStringTreeDesignForm.chStringOptionsListClickCheck(Sender: TObject);
var v_opt: TVTStringOption;
v_opts: TVTStringOptions;
v_tree: TFakeCustomVirtualStringTree;
i: integer;
begin
v_opts:= [];
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for i:= 0 to chStringOptionsList.Items.Count-1 do
if chStringOptionsList.Checked[i] then
begin
v_opt:= TVTStringOption(GetEnumValue(TypeInfo(TVTStringOption), chStringOptionsList.Items[i]));
v_opts:= v_opts + [v_opt];
end;
TFakeCustomStringTreeOptions(TFakeCustomVirtualTreeOptions(v_tree.TreeOptions)).StringOptions:= v_opts;
end;
procedure TojVirtualStringTreeDesignForm.chStringOptionsListMouseMove(
Sender: TObject; Shift: TShiftState; X, Y: Integer);
var v_idx: Integer;
v_opt: TVTStringOption;
begin
v_idx:= chStringOptionsList.ItemAtPos(Point(X, Y), TRUE);
if v_idx >= 0 then
begin
v_opt:= TVTStringOption(GetEnumValue(TypeInfo(TVTStringOption), chStringOptionsList.Items[v_idx]));
// lblInfo.Caption:= VTAutoOptionDescriptions[v_opt];
lblInfo.Caption:= chStringOptionsList.Items[v_idx] + ':' + sLineBreak +
VTStringOptionDescriptions[v_opt];
end
else
lblInfo.Caption:= '';
end;
constructor TojVirtualStringTreeDesignForm.Create(AOwner: TComponent; VirtualTree: TojCustomVirtualStringTree);
begin
inherited Create(AOwner);
FVirtualTree:= VirtualTree;
self.Caption:= 'TVirtualStringTreeDesignForm: '+ VirtualTree.Name;
FillAutoOptionsList;
FillMiscOptionsList;
FillPaintOptionsList;
FillSelectionOptionsList;
FillStringOptionsList;
FillAnimationOptionsList;
end;
procedure TojVirtualStringTreeDesignForm.FillAnimationOptionsList;
var v_tree: TFakeCustomVirtualStringTree;
v_opt: TVTAnimationOption;
v_idx: Integer;
begin
chAnimationOptionsList.Items.Clear;
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for v_opt:= Low(TVTAnimationOption) to High(TVTAnimationOption) do
begin
v_idx:= chAnimationOptionsList.Items.Add( GetEnumName(TypeInfo(TVTAnimationOption), Integer(v_opt)) );
chAnimationOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AnimationOptions);
end;
end;
procedure TojVirtualStringTreeDesignForm.FillAutoOptionsList;
var v_tree: TFakeCustomVirtualStringTree;
v_opt: TVTAutoOption;
v_idx: Integer;
begin
chAutoOptionsList.Items.Clear;
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for v_opt:= Low(TVTAutoOption) to High(TVTAutoOption) do
begin
v_idx:= chAutoOptionsList.Items.Add( GetEnumName(TypeInfo(TVTAutoOption), Integer(v_opt)) );
chAutoOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AutoOptions);
end;
end;
procedure TojVirtualStringTreeDesignForm.FillMiscOptionsList;
var v_tree: TFakeCustomVirtualStringTree;
v_opt: TVTMiscOption;
v_idx: Integer;
begin
chMiscOptionsList.Items.Clear;
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for v_opt:= Low(TVTMiscOption) to High(TVTMiscOption) do
begin
v_idx:= chMiscOptionsList.Items.Add( GetEnumName(TypeInfo(TVTMiscOption), Integer(v_opt)) );
chMiscOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).MiscOptions);
end;
end;
procedure TojVirtualStringTreeDesignForm.FillPaintOptionsList;
var v_tree: TFakeCustomVirtualStringTree;
v_opt: TVTPaintOption;
v_idx: Integer;
begin
chPaintOptionsList.Items.Clear;
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for v_opt:= Low(TVTPaintOption) to High(TVTPaintOption) do
begin
v_idx:= chPaintOptionsList.Items.Add( GetEnumName(TypeInfo(TVTPaintOption), Integer(v_opt)) );
chPaintOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).PaintOptions);
end;
end;
procedure TojVirtualStringTreeDesignForm.FillSelectionOptionsList;
var v_tree: TFakeCustomVirtualStringTree;
v_opt: TVTSelectionOption;
v_idx: Integer;
begin
chSelectionOptionsList.Items.Clear;
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
for v_opt:= Low(TVTSelectionOption) to High(TVTSelectionOption) do
begin
v_idx:= chSelectionOptionsList.Items.Add( GetEnumName(TypeInfo(TVTSelectionOption), Integer(v_opt)) );
chSelectionOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).SelectionOptions);
end;
end;
procedure TojVirtualStringTreeDesignForm.FillStringOptionsList;
var v_tree: TFakeCustomVirtualStringTree;
v_opt: TVTStringOption;
v_opts: TVTStringOptions;
v_idx: Integer;
begin
chStringOptionsList.Items.Clear;
v_tree:= TFakeCustomVirtualStringTree(getVirtualTree);
v_opts:= TFakeCustomStringTreeOptions(TFakeCustomVirtualTreeOptions(v_tree.TreeOptions)).StringOptions;
for v_opt:= Low(TVTStringOption) to High(TVTStringOption) do
begin
v_idx:= chStringOptionsList.Items.Add( GetEnumName(TypeInfo(TVTStringOption), Integer(v_opt)) );
chStringOptionsList.Checked[v_idx]:= (v_opt in v_opts);
end;
end;
function TojVirtualStringTreeDesignForm.getVirtualTree: TojBaseVirtualTree;
begin
result:= FVirtualTree;
end;
class procedure TojVirtualStringTreeDesignForm.ShowDesigner(p_VirtualTree: TojCustomVirtualStringTree);
var v_form: TojVirtualStringTreeDesignForm;
begin
v_form:= TojVirtualStringTreeDesignForm.Create(nil, p_VirtualTree);
try
v_form.ShowModal;
finally
FreeAndNil(v_form);
end;
end;
end.
|
unit PowerADOQuery;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DB,
{RCADOQuery,} ADODB;
type
TPowerADOQuery = class(TADODataSet)
private
{ Private declarations }
FOriginalSQl : String;
FKeyFields : String;
FFilterFields : TStringList; { campos do filtro }
FFilterValues : TStringList; { valores do filtro }
procedure SetFilterFields(Value : TStringList);
procedure SetFilterValues(Value : TStringList);
function GetOriginalSQL : String;
protected
{ Protected declarations }
procedure DoAfterOpen; override;
procedure DoOnNewRecord; override;
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
public
{ Public declarations }
ChangeOriginalSQL : Boolean;
procedure ClearFilters;
procedure AddFilter(aFields, aValues : array of string);
procedure Requery;
property OriginalSQL : String read GetOriginalSQl write FOriginalSQl;
published
{ Published declarations }
property FilterFields : TStringList read FFilterFields write SetFilterFields;
property FilterValues : TStringList read FFilterValues write SetFilterValues;
procedure ClearSuggest;
procedure AddSuggest(sField: String; aValue: variant);
property KeyFields : String read FKeyFields write FKeyFields;
end;
procedure Register;
implementation
constructor TPowerADOQuery.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FFilterFields := TStringList.Create;
FFilterValues := TStringList.Create;
FKeyFields := '';
FOriginalSQl := '';
end;
destructor TPowerADOQuery.Destroy;
begin
FFilterFields.Free;
FFilterValues.Free;
inherited Destroy;
end;
procedure TPowerADOQuery.Requery;
var
OldPos : Variant;
begin
// if FKeyFields <> '' then
// OldPos := FieldValues[FKeyFields];
Close;
Open;
// if FKeyFields <> '' then
// Locate(FKeyFields, OldPos, []);
end;
procedure TPowerADOQuery.DoAfterOpen;
begin
inherited DoAfterOpen;
FOriginalSQL := CommandText;
end;
function TPowerADOQuery.GetOriginalSQL : String;
begin
if FOriginalSQl = '' then
FOriginalSQl := CommandText;
Result := FOriginalSQl;
end;
procedure TPowerADOQuery.DoOnNewRecord;
var
i : byte;
begin
inherited DoOnNewRecord;
// no append deve ser mostrado o provável novo código
// Seta os campos defaults do filtro
with FFilterFields do
if Count > 0 then
for i := 0 to ( Count -1 ) do
begin
// Testa a troca de 0/1 por False/True
if FieldByName(Strings[i]).DataType = ftBoolean then
begin
if FFilterValues.Strings[i] = '0' then
FieldByName(Strings[i]).AsBoolean := False
else if FFilterValues.Strings[i] = '1' then
FieldByName(Strings[i]).AsBoolean := True
else
FieldByName(Strings[i]).AsString := FFilterValues.Strings[i];
end
else
begin
FieldByName(Strings[i]).AsString := FFilterValues.Strings[i];
end;
end;
end;
procedure TPowerADOQuery.SetFilterFields(Value : TStringList);
begin
if FFilterFields <> Value then
FFilterFields.Assign(Value);
end;
procedure TPowerADOQuery.SetFilterValues(Value : TStringList);
begin
if FFilterValues <> Value then
FFilterValues.Assign(Value);
end;
procedure TPowerADOQuery.ClearFilters;
begin
FFilterFields.Clear;
FFilterValues.Clear;
end;
procedure TPowerADOQuery.ClearSuggest;
begin
FFilterFields.Clear;
FFilterValues.Clear;
end;
procedure TPowerADOQuery.AddSuggest(sField: String; aValue: variant);
begin
FFilterFields.Add(sField);
FFilterValues.Add(VarToStr(aValue));
end;
procedure TPowerADOQuery.AddFilter(aFields, aValues : array of string);
var
i : integer;
begin
ClearFilters;
if High(aFields) <> High(aValues) then
raise exception.create('erro na passagem do filtro')
else
begin
for i := Low(aFields) to High(aFields) do
begin
FilterFields.Add(aFields[i]);
FilterValues.Add(aValues[i]);
end;
end;
end;
procedure Register;
begin
RegisterComponents('NewPower', [TPowerADOQuery]);
end;
end.
|
unit ufTarefa3;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufBase, Data.DB, Vcl.Grids, Vcl.DBGrids,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Datasnap.DBClient;
type
TfTarefa3 = class(TfBase)
gridProjetos: TDBGrid;
edtTotal: TLabeledEdit;
edtTotalDivisoes: TLabeledEdit;
btnObterTotal: TBitBtn;
btnObterTotalDivisoes: TBitBtn;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnObterTotalClick(Sender: TObject);
procedure btnObterTotalDivisoesClick(Sender: TObject);
private
{ Private declarations }
aClientDataSet : TClientDataSet;
aDataSource : TDataSource;
procedure PopularGridProjetos;
function TotalizarValorProjetos(aDataSet : TDataSet) : Currency;
function TotalizarValorDivisoes(aDataSet : TDataSet) : Double;
public
{ Public declarations }
end;
var
fTarefa3: TfTarefa3;
implementation
{$R *.dfm}
procedure TfTarefa3.btnObterTotalClick(Sender: TObject);
begin
edtTotal.Text := FormatFloat('0.00', TotalizarValorProjetos(gridProjetos.DataSource.DataSet));
end;
procedure TfTarefa3.btnObterTotalDivisoesClick(Sender: TObject);
begin
edtTotalDivisoes.Text := FormatFloat('0.00', TotalizarValorDivisoes(gridProjetos.DataSource.DataSet));
end;
procedure TfTarefa3.FormCreate(Sender: TObject);
begin
aClientDataSet := TClientDataSet.Create(nil);
aDataSource := TDataSource.Create(nil);
aDataSource.DataSet := aClientDataSet;
gridProjetos.DataSource := aDataSource;
aClientDataSet.IndexFieldNames := 'Codigo';
PopularGridProjetos;
end;
procedure TfTarefa3.FormDestroy(Sender: TObject);
begin
fTarefa3 := nil;
aClientDataSet.Free;
aDataSource.Free;
end;
procedure TfTarefa3.PopularGridProjetos;
var
aIndex: Integer;
begin
aClientDataSet.FieldDefs.Clear;
aClientDataSet.FieldDefs.Add('Codigo', ftInteger);
aClientDataSet.FieldDefs.Add('NomeProjeto', ftString, 50);
aClientDataSet.FieldDefs.Add('Valor', ftCurrency);
aClientDataSet.CreateDataSet;
aClientDataSet.DisableControls;
try
for aIndex := 1 to 10 do begin
aClientDataSet.Insert;
aClientDataSet.FieldByName('Codigo').AsInteger := aIndex;
aClientDataSet.FieldByName('NomeProjeto').AsString := 'Projeto ' + aIndex.ToString;
aClientDataSet.FieldByName('Valor').AsCurrency := aIndex * 10;
aClientDataSet.Post;
end;
aClientDataSet.First;
finally
aClientDataSet.EnableControls;
end;
end;
function TfTarefa3.TotalizarValorDivisoes(aDataSet: TDataSet): Double;
var
aDividendo, aDivisor : Double;
aFirst : Boolean;
aDatasetClone : TClientDataSet;
begin
Result := 0;
aDividendo := 0;
aDivisor := 0;
aFirst := True;
aDatasetClone := TClientDataSet.Create(nil);
aDatasetClone.CloneCursor(TClientDataSet(aDataSet), False, False);
try
while not aDatasetClone.Eof do begin
if aFirst then begin
aDivisor := aDatasetClone.FieldByName('Valor').AsCurrency;
aFirst := False;
end else begin
aDividendo := aDatasetClone.FieldByName('Valor').AsCurrency;
end;
if (aDividendo > 0) and (aDivisor > 0) then begin
Result := Result + (aDividendo / aDivisor);
aDivisor := aDividendo;
aDividendo := 0;
end;
aDatasetClone.Next;
end;
finally
aDatasetClone.Free;
end;
end;
function TfTarefa3.TotalizarValorProjetos(aDataSet: TDataSet): Currency;
var
aDatasetClone : TClientDataSet;
begin
Result := 0;
aDatasetClone := TClientDataSet.Create(nil);
aDatasetClone.CloneCursor(TClientDataSet(aDataSet), False, False);
try
while not aDatasetClone.Eof do begin
Result := Result + aDatasetClone.FieldByName('Valor').AsCurrency;
aDatasetClone.Next;
end;
finally
aDatasetClone.Free;
end;
end;
end.
|
unit frmUnitTests;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, frmIDEDockWin, JvComponentBase, JvDockControlForm, ExtCtrls, ImgList,
JvExControls, JvComponent, JvLinkLabel, TBXDkPanels, VirtualTrees,
JvExExtCtrls, JvNetscapeSplitter, TBXStatusBars, TB2Item, TBXExtItems,
TB2Dock, TB2Toolbar, TBX, StdCtrls, JvExStdCtrls, JvRichEdit, mbTBXJvRichEdit,
ActnList, TBXThemes;
type
TUnitTestWindowStatus = (utwEmpty, utwLoaded, utwRunning, utwRun);
TUnitTestWindow = class(TIDEDockWindow)
ExplorerDock: TTBXDock;
ExplorerToolbar: TTBXToolbar;
Panel1: TPanel;
RunImages: TImageList;
UnitTests: TVirtualStringTree;
DialogActions: TActionList;
actRun: TAction;
actStop: TAction;
actSelectAll: TAction;
actDeselectAll: TAction;
actSelectFailed: TAction;
actRefresh: TAction;
TBXItem1: TTBXItem;
TBXSeparatorItem1: TTBXSeparatorItem;
TBXItem2: TTBXItem;
TBXItem3: TTBXItem;
TBXItem4: TTBXItem;
TBXSeparatorItem2: TTBXSeparatorItem;
TBXItem6: TTBXItem;
TBXItem7: TTBXItem;
Panel2: TPanel;
ErrorText: TmbTBXJvRichEdit;
Label2: TLabel;
ModuleName: TLabel;
Splitter: TJvNetscapeSplitter;
actExpandAll: TAction;
actCollapseAll: TAction;
TBXItem10: TTBXItem;
TBXItem8: TTBXItem;
TBXSeparatorItem7: TTBXSeparatorItem;
actClearAll: TAction;
TBXItem5: TTBXItem;
lbFoundTests: TLabel;
lblRunTests: TLabel;
lblFailures: TLabel;
Bevel1: TBevel;
procedure UnitTestsDblClick(Sender: TObject);
procedure actStopExecute(Sender: TObject);
procedure actClearAllExecute(Sender: TObject);
procedure actSelectFailedExecute(Sender: TObject);
procedure UnitTestsChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure actRunExecute(Sender: TObject);
procedure UnitTestsChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure actDeselectAllExecute(Sender: TObject);
procedure actCollapseAllExecute(Sender: TObject);
procedure actExpandAllExecute(Sender: TObject);
procedure actSelectAllExecute(Sender: TObject);
procedure UnitTestsGetHint(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; var LineBreakStyle: TVTTooltipLineBreakStyle;
var HintText: WideString);
procedure UnitTestsGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure UnitTestsGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
procedure UnitTestsInitChildren(Sender: TBaseVirtualTree;
Node: PVirtualNode; var ChildCount: Cardinal);
procedure UnitTestsInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
private
{ Private declarations }
TestClasses : TStringList;
TestSuite, TestResult : Variant;
protected
procedure TBMThemeChange(var Message: TMessage); message TBM_THEMECHANGE;
procedure UpdateActions; override;
public
{ Public declarations }
Status : TUnitTestWindowStatus;
TestsRun, TestsFailed, TestErrors : integer;
ElapsedTime : double;
procedure ClearAll;
procedure StartTest(Test: Variant);
procedure StopTest(Test: Variant);
procedure AddError(Test, Err: Variant);
procedure AddFailure(Test, Err: Variant);
procedure AddSuccess(Test: Variant);
function SelectedTestCount : integer;
function FindTestNode(Test : Variant) : PVirtualNode;
end;
var
UnitTestWindow: TUnitTestWindow;
implementation
uses uCommonFunctions, uHighlighterProcs, frmPyIDEMain, VarPyth, JvJVCLUtils,
uEditAppIntfs, PythonEngine, frmPythonII, dmCommands, cPyBaseDebugger, JclSysUtils;
{$R *.dfm}
{ Indexes of the color images used in the test tree and failure list }
Type
TTestStatus = (tsNotRun, tsRunning, tsRun, tsFailed, tsError);
PNodeDataRec = ^TNodeDataRec;
TNodeDataRec = record
end;
Const
FoundTestsLabel = 'Found %d test%s';
RunTestsLabel = 'Ran %d test%s%s';
ElapsedTimeFormat = ' in %.3fs';
FailuresLabel = 'Failures/Errors : %d/%d';
{ TUnitTestWindow }
procedure TUnitTestWindow.TBMThemeChange(var Message: TMessage);
begin
inherited;
if Message.WParam = TSC_VIEWCHANGE then begin
FGPanel.Color := CurrentTheme.GetItemColor(GetItemInfo('inactive'));
Splitter.ButtonColor :=
CurrentTheme.GetItemColor(GetItemInfo('inactive'));
Splitter.ButtonHighlightColor :=
CurrentTheme.GetItemColor(GetItemInfo('active'));
end;
end;
procedure TUnitTestWindow.actRefreshExecute(Sender: TObject);
Var
i, j, Index : integer;
Editor : IEditor;
UnitTest, Module, InnerTestSuite,
TestCase : Variant;
ClassName, TestName : string;
SL : TStringList;
Cursor : IInterface;
PyTestCase : PPyObject;
TestCount : integer;
begin
ClearAll;
Editor := PyIDEMainForm.GetActiveEditor;
if Assigned(Editor) then begin
Cursor := WaitCursor;
ModuleName.Caption := 'Module: ' + Editor.FileTitle;
ModuleName.Hint := Editor.FileName;
Module := PyIDEMainForm.PyDebugger.ImportModule(Editor);
UnitTest := Import('unittest');
TestSuite := UnitTest.findTestCases(Module);
// This TestSuite contains a list of TestSuites
// each of which contains TestCases corresponding to
// a TestCase class in the module!!!
TestCount := 0;
for i := 0 to Len(TestSuite._tests) - 1 do begin
InnerTestSuite := TestSuite._tests[i];
for j := 0 to Len(InnerTestSuite._tests) - 1 do begin
TestCase := InnerTestSuite._tests[j];
// set the TestStatus
TestCase.testStatus := Ord(tsNotRun);
TestCase.errMsg := '';
TestCase.enabled := True;
ClassName := TestCase.__class__.__name__;
Index := TestClasses.IndexOf(ClassName);
if Index < 0 then begin
SL := TStringList.Create;
Index := TestClasses.AddObject(ClassName, SL);
end;
// hack to access a private variable!
TestName := TestCase._TestCase__testMethodName;
PyTestCase := ExtractPythonObjectFrom(TestCase); // Store the TestCase PPyObject
GetPythonEngine.Py_XINCREF(PyTestCase);
TStringList(TestClasses.Objects[Index]).AddObject(TestName, TObject(PyTestCase));
Inc(TestCount);
end;
end;
if TestCount = 0 then begin
MessageDlg('No tests found!', mtWarning, [mbOK], 0);
ClearAll;
end else begin
UnitTests.RootNodeCount := TestClasses.Count;
UnitTests.ReinitNode(UnitTests.RootNode, True);
lbFoundTests.Caption := Format(FoundTestsLabel, [TestCount, Iff(TestCount=1, '', 's')]);
Status := utwLoaded;
end;
end;
end;
procedure TUnitTestWindow.FormCreate(Sender: TObject);
begin
inherited;
UnitTests.NodeDataSize := SizeOf(TNodeDataRec);
TestClasses := TStringList.Create;
TestClasses.Sorted := True;
TestClasses.Duplicates := dupError;
Status := utwEmpty;
end;
procedure TUnitTestWindow.FormDestroy(Sender: TObject);
begin
ClearAll;
TestClasses.Free;
inherited;
end;
procedure TUnitTestWindow.ClearAll;
Var
i, j : integer;
SL : TStringList;
PyTestCase : PPyObject;
begin
UnitTests.Clear;
for i := 0 to TestClasses.Count - 1 do begin
SL := TStringList(TestClasses.Objects[i]);
for j := 0 to SL.Count - 1 do with GetPythonEngine do begin
PyTestCase := PPyObject(SL.Objects[j]);
Py_XDECREF(PyTestCase);
end;
SL.Free;
end;
TestClasses.Clear;
VarClear(TestSuite);
TestsRun := 0;
TestsFailed := 0;
TestErrors := 0;
ElapsedTime := 0;
lblRunTests.Caption := Format(RunTestsLabel, [TestsRun, Iff(TestsRun=1, '', 's'), '']);
lblFailures.Caption := Format(FailuresLabel, [TestsFailed, TestErrors]);
ModuleName.Caption := 'No Module Loaded';
ModuleName.Hint := '';
lbFoundTests.Caption := Format(FoundTestsLabel, [0, 's']);
Status := utwEmpty;
end;
procedure TUnitTestWindow.UnitTestsInitNode(Sender: TBaseVirtualTree;
ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
begin
if UnitTests.GetNodeLevel(Node) = 0 then begin
Node.CheckType := ctTriStateCheckBox;
if TStringList(TestClasses.Objects[Node.Index]).Count > 0 then
InitialStates := [ivsHasChildren, ivsExpanded]
else
InitialStates := []
end else begin
Node.CheckType := ctCheckBox;
InitialStates := [];
end;
Node.CheckState := csCheckedNormal;
end;
procedure TUnitTestWindow.UnitTestsInitChildren(Sender: TBaseVirtualTree;
Node: PVirtualNode; var ChildCount: Cardinal);
begin
if UnitTests.GetNodeLevel(Node) = 0 then
ChildCount := TStringList(TestClasses.Objects[Node.Index]).Count
else
ChildCount := 0;
end;
procedure TUnitTestWindow.UnitTestsGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
begin
if UnitTests.GetNodeLevel(Node) = 0 then
CellText := TestClasses[Node.Index]
else
CellText := TStringList(TestClasses.Objects[Node.Parent.Index])[Node.Index]
end;
procedure TUnitTestWindow.UnitTestsGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
var
PyTestCase, PytestStatus : PPyObject;
begin
if not (Kind in [ikNormal, ikSelected]) then exit;
if UnitTests.GetNodeLevel(Node) = 0 then begin
if vsExpanded in Node.States then
ImageIndex := 5
else
ImageIndex := 6;
end else with GetPythonEngine do begin
PyTestCase := PPyObject(TStringList(TestClasses.Objects[Node.Parent.Index]).Objects[Node.Index]);
PytestStatus := PyObject_GetAttrString(PyTestCase, 'testStatus');
CheckError;
ImageIndex := PyLong_AsLong(PytestStatus);
Py_XDECREF(PytestStatus);
end;
end;
procedure TUnitTestWindow.UnitTestsGetHint(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex;
var LineBreakStyle: TVTTooltipLineBreakStyle; var HintText: WideString);
var
PyTestCase : PPyObject;
TestCase : Variant;
begin
HintText := '';
if UnitTests.GetNodeLevel(Node) = 0 then begin
if Assigned(Node.FirstChild) then begin
PyTestCase := PPyObject(TStringList(TestClasses.Objects[Node.Index]).Objects[0]);
TestCase := VarPythonCreate(PyTestCase);
if not VarIsNone(TestCase.__doc__) then
HintText := FormatDocString(TestCase.__doc__);
end;
end else with GetPythonEngine do begin
PyTestCase := PPyObject(TStringList(TestClasses.Objects[Node.Parent.Index]).Objects[Node.Index]);
TestCase := VarPythonCreate(PyTestCase);
if not VarIsNone(TestCase.shortDescription()) then
HintText := TestCase.shortDescription();
end;
end;
procedure TUnitTestWindow.UnitTestsChecked(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
PyTestCase : PPyObject;
TestCase : Variant;
begin
if UnitTests.GetNodeLevel(Node) = 1 then begin
PyTestCase := PPyObject(TStringList(TestClasses.Objects[Node.Parent.Index]).Objects[Node.Index]);
TestCase := VarPythonCreate(PyTestCase);
TestCase.enabled := Node.CheckState in [csCheckedNormal, csCheckedPressed];
end;
end;
procedure TUnitTestWindow.actSelectAllExecute(Sender: TObject);
Var
Node : PVirtualNode;
begin
Node := UnitTests.RootNode^.FirstChild;
while Assigned(Node) do begin
UnitTests.CheckState[Node] := csCheckedNormal;
Node := Node.NextSibling;
end;
end;
procedure TUnitTestWindow.actDeselectAllExecute(Sender: TObject);
Var
Node : PVirtualNode;
begin
Node := UnitTests.RootNode^.FirstChild;
while Assigned(Node) do begin
UnitTests.CheckState[Node] := csUncheckedNormal;
Node := Node.NextSibling;
end;
end;
procedure TUnitTestWindow.actSelectFailedExecute(Sender: TObject);
Var
PyTestCase : PPyObject;
TestCase : Variant;
ClassNode, TestCaseNode : PVirtualNode;
begin
actDeselectAllExecute(Sender);
ClassNode := UnitTests.RootNode^.FirstChild;
while Assigned(ClassNode) do begin
TestCaseNode := ClassNode.FirstChild;
while Assigned(TestCaseNode) do begin
PyTestCase :=
PPyObject(TStringList(TestClasses.Objects[TestCaseNode.Parent.Index]).Objects[TestCaseNode.Index]);
TestCase := VarPythonCreate(PyTestCase);
if TTestStatus(TestCase.testStatus) in [tsFailed, tsError] then
UnitTests.CheckState[TestCaseNode] := csCheckedNormal;
TestCaseNode := TestCaseNode.NextSibling;
end;
ClassNode := ClassNode.NextSibling;
end;
end;
procedure TUnitTestWindow.actExpandAllExecute(Sender: TObject);
begin
UnitTests.FullExpand;
end;
procedure TUnitTestWindow.actCollapseAllExecute(Sender: TObject);
begin
UnitTests.FullCollapse;
end;
procedure TUnitTestWindow.actRunExecute(Sender: TObject);
Var
UnitTestModule, TempTestSuite : Variant;
PyTestCase : PPyObject;
TestCase : Variant;
ClassNode, TestCaseNode : PVirtualNode;
StartTime, StopTime, Freq : Int64;
begin
// Only allow when PyDebugger is inactive
if PyIDEMainForm.PyDebugger.DebuggerState <> dsInactive then Exit;
UnitTestModule := Import('unittest');
// Create a TempTestSuite that contains only the checked tests
TempTestSuite := UnitTestModule.TestSuite();
ClassNode := UnitTests.RootNode^.FirstChild;
while Assigned(ClassNode) do begin
TestCaseNode := ClassNode.FirstChild;
while Assigned(TestCaseNode) do begin
PyTestCase :=
PPyObject(TStringList(TestClasses.Objects[TestCaseNode.Parent.Index]).Objects[TestCaseNode.Index]);
TestCase := VarPythonCreate(PyTestCase);
TestCase.testStatus := Ord(tsNotRun);
TestCase.errMsg := '';
if TestCase.enabled then
TempTestSuite._tests.append(TestCase);
TestCaseNode := TestCaseNode.NextSibling;
end;
ClassNode := ClassNode.NextSibling;
end;
TestsRun := 0;
TestsFailed := 0;
TestErrors := 0;
ElapsedTime := 0;
lblRunTests.Caption := Format(RunTestsLabel, [TestsRun, Iff(TestsRun=1, '', 's'), '']);
lblFailures.Caption := Format(FailuresLabel, [TestsFailed, TestErrors]);
Status := utwRunning;
UpdateActions;
PyIDEMainForm.DebuggerStateChange(Self, dsInactive, dsRunningNoDebug);
Application.ProcessMessages;
TestResult := PythonIIForm.II.IDETestResult();
try
QueryPerformanceCounter(StartTime);
TempTestSuite.run(TestResult);
QueryPerformanceCounter(StopTime);
finally
if QueryPerformanceFrequency(Freq) then
ElapsedTime := (StopTime-StartTime) / Freq
else
ElapsedTime := 0;
VarClear(TestResult);
Status := utwRun;
PyIDEMainForm.DebuggerStateChange(Self, dsRunningNoDebug, dsInactive);
lblRunTests.Caption := Format(RunTestsLabel,
[TestsRun, Iff(TestsRun=1, '', 's'), Format(ElapsedTimeFormat, [ElapsedTime])]);
end;
end;
procedure TUnitTestWindow.AddFailure(Test, Err: Variant);
// Called from IDETestResult
Var
TestCaseNode : PVirtualNode;
begin
Test.testStatus := Ord(tsFailed);
Test.errMsg := Err;
TestCaseNode := FindTestNode(Test);
if Assigned(TestCaseNode) then begin
UnitTests.ScrollIntoView(TestCaseNode, True);
UnitTests.Refresh;
end;
Inc(TestsFailed);
lblFailures.Caption := Format(FailuresLabel, [TestsFailed, TestErrors]);
Application.ProcessMessages;
end;
procedure TUnitTestWindow.AddSuccess(Test: Variant);
// Called from IDETestResult
Var
TestCaseNode : PVirtualNode;
begin
Test.testStatus := Ord(tsRun);
TestCaseNode := FindTestNode(Test);
if Assigned(TestCaseNode) then begin
UnitTests.ScrollIntoView(TestCaseNode, True);
UnitTests.Refresh;
end;
Application.ProcessMessages;
end;
procedure TUnitTestWindow.StopTest(Test: Variant);
// Called from IDETestResult
begin
Inc(TestsRun);
lblRunTests.Caption := Format(RunTestsLabel, [TestsRun, Iff(TestsRun=1, '', 's'), '']);
Application.ProcessMessages;
end;
procedure TUnitTestWindow.StartTest(Test: Variant);
// Called from IDETestResult
Var
TestCaseNode : PVirtualNode;
begin
Test.testStatus := Ord(tsRunning);
TestCaseNode := FindTestNode(Test);
if Assigned(TestCaseNode) then begin
UnitTests.ScrollIntoView(TestCaseNode, True);
UnitTests.Refresh;
Application.ProcessMessages;
end;
end;
procedure TUnitTestWindow.AddError(Test, Err: Variant);
// Called from IDETestResult
Var
TestCaseNode : PVirtualNode;
begin
Test.testStatus := Ord(tsError);
Test.errMsg := Err;
TestCaseNode := FindTestNode(Test);
if Assigned(TestCaseNode) then begin
UnitTests.ScrollIntoView(TestCaseNode, True);
UnitTests.Refresh;
end;
Inc(TestErrors);
lblFailures.Caption := Format(FailuresLabel, [TestsFailed, TestErrors]);
Application.ProcessMessages;
end;
function TUnitTestWindow.FindTestNode(Test: Variant): PVirtualNode;
Var
PyTestCase : PPyObject;
TestCase : Variant;
ClassNode, TestCaseNode : PVirtualNode;
begin
Result := nil;
ClassNode := UnitTests.RootNode^.FirstChild;
while Assigned(ClassNode) do begin
TestCaseNode := ClassNode.FirstChild;
while Assigned(TestCaseNode) do begin
PyTestCase :=
PPyObject(TStringList(TestClasses.Objects[TestCaseNode.Parent.Index]).Objects[TestCaseNode.Index]);
TestCase := VarPythonCreate(PyTestCase);
if VarIsSame(Test, TestCase) then begin
Result := TestCaseNode;
Break;
end;
TestCaseNode := TestCaseNode.NextSibling;
end;
ClassNode := ClassNode.NextSibling;
end;
end;
procedure TUnitTestWindow.UnitTestsChange(Sender: TBaseVirtualTree;
Node: PVirtualNode);
Var
PyTestCase : PPyObject;
TestCase : Variant;
begin
if Assigned(Node) and (vsSelected in Node.States) and
(UnitTests.GetNodeLevel(Node) = 1) then
begin
PyTestCase := PPyObject(TStringList(TestClasses.Objects[Node.Parent.Index]).Objects[Node.Index]);
TestCase := VarPythonCreate(PyTestCase);
ErrorText.Text := TestCase.errMsg;
end else
ErrorText.Text := '';
end;
procedure TUnitTestWindow.actClearAllExecute(Sender: TObject);
begin
ClearAll;
end;
function TUnitTestWindow.SelectedTestCount: integer;
Var
ClassNode, TestCaseNode : PVirtualNode;
begin
Result := 0;
ClassNode := UnitTests.RootNode^.FirstChild;
while Assigned(ClassNode) do begin
TestCaseNode := ClassNode.FirstChild;
while Assigned(TestCaseNode) do begin
if TestCaseNode.CheckState in [csCheckedNormal, csCheckedPressed] then
Inc(Result);
TestCaseNode := TestCaseNode.NextSibling;
end;
ClassNode := ClassNode.NextSibling;
end;
end;
procedure TUnitTestWindow.UpdateActions;
Var
Count : integer;
begin
Count := SelectedTestCount;
actRun.Enabled := (Status in [utwLoaded, utwRun]) and (Count > 0) and
(PyIDEMainForm.PyDebugger.DebuggerState = dsInactive);
actSelectAll.Enabled := Status in [utwLoaded, utwRun];
actDeselectAll.Enabled := Status in [utwLoaded, utwRun];
actSelectFailed.Enabled := Status = utwRun;
actRefresh.Enabled := Status <> utwRunning;
actExpandAll.Enabled := Status <> utwEmpty;
actCollapseAll.Enabled := Status <> utwEmpty;
actClearAll.Enabled := not (Status in [utwEmpty, utwRunning]);
actStop.Enabled := Status = utwRunning;
inherited;
end;
procedure TUnitTestWindow.actStopExecute(Sender: TObject);
begin
if VarIsPython(TestResult) then
TestResult.stop();
end;
procedure TUnitTestWindow.UnitTestsDblClick(Sender: TObject);
var
InspectModule : Variant;
Node : PVirtualNode;
PyTestCase : PPyObject;
TestCase, PythonObject : Variant;
FileName : string;
NodeLevel, LineNo : integer;
begin
Node := UnitTests.HotNode;
if Assigned(Node) then begin
NodeLevel := UnitTests.GetNodeLevel(Node);
if NodeLevel = 0 then
Node := Node.FirstChild;
if (NodeLevel > 1) or not Assigned(Node) then Exit;
PyTestCase := PPyObject(TStringList(TestClasses.Objects[Node.Parent.Index]).Objects[Node.Index]);
TestCase := VarPythonCreate(PyTestCase);
if NodeLevel = 0 then
PythonObject := TestCase.__class__
else
PythonObject := BuiltinModule.getattr(TestCase, TestCase._TestCase__testMethodName);
if VarIsPython(PythonObject) then begin
InspectModule := Import('inspect');
if InspectModule.ismethod(PythonObject) then begin
FileName := InspectModule.getsourcefile(PythonObject);
if FileName = 'None' then begin
FileName := PythonObject.im_func.func_code.co_filename;
if ExtractFileExt(FileName) <> '' then
Exit;
// otherwise it should be an unsaved file
LineNo := PythonObject.im_func.func_code.co_firstlineno-1;
end else
LineNo := InspectModule.findsource(PythonObject).GetItem(1);
PyIDEMainForm.ShowFilePosition(FileName, Succ(LineNo), 1);
end;
end;
end;
end;
end.
|
{******************************************************************************}
{ }
{ Delphi OPENSSL Library }
{ Copyright (c) 2016 Luca Minuti }
{ https://bitbucket.org/lminuti/delphi-openssl }
{ }
{******************************************************************************}
{ }
{ 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 SSLDemo.RSABufferFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TRSABufferFrame = class(TFrame)
memPub: TMemo;
btnLoadPubKeyIntoMem: TButton;
edtPub: TEdit;
btnLoadPublicKey: TButton;
grpPublicKey: TGroupBox;
grpPrivateKey: TGroupBox;
btnLoadPrivKeyIntoMemo: TButton;
btnLoadPrivateKey: TButton;
edtPriv: TEdit;
memPriv: TMemo;
grpCertificate: TGroupBox;
btnLoadCertIntoMemo: TButton;
btnLoadCert: TButton;
edtCert: TEdit;
memCert: TMemo;
cmbPrivateKeyFormat: TComboBox;
cmbPublicKeyFormat: TComboBox;
procedure btnLoadPubKeyIntoMemClick(Sender: TObject);
procedure btnLoadPrivateKeyClick(Sender: TObject);
procedure btnLoadPrivKeyIntoMemoClick(Sender: TObject);
procedure btnLoadCertIntoMemoClick(Sender: TObject);
procedure btnLoadCertClick(Sender: TObject);
procedure btnLoadPublicKeyClick(Sender: TObject);
private
procedure PassphraseReader(Sender: TObject; var Passphrase: string);
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses
OpenSSL.RSAUtils;
{$R *.dfm}
{ TRSABufferFrame }
procedure TRSABufferFrame.btnLoadCertClick(Sender: TObject);
var
Buffer: TStream;
Cerificate: TX509Cerificate;
begin
Buffer := TStringStream.Create(memCert.Text);
try
Cerificate := TX509Cerificate.Create;
try
Cerificate.LoadFromStream(Buffer);
ShowMessage(Cerificate.Print);
finally
Cerificate.Free;
end;
finally
Buffer.Free;
end;
end;
procedure TRSABufferFrame.btnLoadCertIntoMemoClick(Sender: TObject);
begin
memCert.Lines.LoadFromFile(edtCert.Text);
end;
procedure TRSABufferFrame.btnLoadPrivKeyIntoMemoClick(Sender: TObject);
begin
memPriv.Lines.LoadFromFile(edtPriv.Text);
end;
procedure TRSABufferFrame.btnLoadPubKeyIntoMemClick(Sender: TObject);
begin
memPub.Lines.LoadFromFile(edtPub.Text);
end;
procedure TRSABufferFrame.btnLoadPublicKeyClick(Sender: TObject);
var
Buffer: TStream;
PublicKey: TRSAPublicKey;
begin
Buffer := TStringStream.Create(memPub.Text);
try
PublicKey := TRSAPublicKey.Create;
try
PublicKey.LoadFromStream(Buffer, TPublicKeyFormat(cmbPublicKeyFormat.ItemIndex));
ShowMessage(PublicKey.Print);
finally
PublicKey.Free;
end;
finally
Buffer.Free;
end;
end;
procedure TRSABufferFrame.btnLoadPrivateKeyClick(Sender: TObject);
var
Buffer: TStream;
PrivateKey: TRSAPrivateKey;
begin
Buffer := TStringStream.Create(memPriv.Text);
try
PrivateKey := TRSAPrivateKey.Create;
try
PrivateKey.OnNeedPassphrase := PassphraseReader;
PrivateKey.LoadFromStream(Buffer, TPrivateKeyFormat(cmbPrivateKeyFormat.ItemIndex));
ShowMessage(PrivateKey.Print);
finally
PrivateKey.Free;
end;
finally
Buffer.Free;
end;
end;
constructor TRSABufferFrame.Create(AOwner: TComponent);
var
TestFolder: string;
begin
inherited;
TestFolder := StringReplace(ExtractFilePath(ParamStr(0)), 'Samples\SSLDemo', 'TestData', [rfReplaceAll, rfIgnoreCase]);
edtCert.Text := TestFolder + 'publiccert.pem';
edtPriv.Text := TestFolder + 'privatekey.pem';
edtPub.Text := TestFolder + 'publickey.pem';
end;
procedure TRSABufferFrame.PassphraseReader(Sender: TObject; var Passphrase: string);
begin
Passphrase := InputBox(Name, 'Passphrase', '');
end;
end.
|
unit UnitFormMain;
{===============================================================================
CodeRage 9 - Demo responsive REST client using TTask
This code shows how to do REST calls without blocking the user interface
for the duration of the call. This code uses TTask to run the REST call
in parallel.
Please note that you could also use RESTRequest.ExecuteAsync.
This demo works with RAD Studio XE7.
The discogs API changes frequently, this REST request works with the current
api of October 2014. Please update the RESTRequest code if the api has changed.
Author: Danny Wind
===============================================================================}
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, Vcl.ExtCtrls,
Vcl.StdCtrls, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope,
Vcl.ComCtrls;
type
TFormMain = class(TForm)
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
RESTResponse1: TRESTResponse;
ProgressBar1: TProgressBar;
Timer1: TTimer;
Memo1: TMemo;
Memo2: TMemo;
Memo3: TMemo;
Memo4: TMemo;
Memo5: TMemo;
Memo6: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
CheckBoxUseThreading: TCheckBox;
procedure Button1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
{ Private declarations }
function DoRESTCall(aArtist: string): string;
public
{ Public declarations }
procedure ExecuteRESTCall(aMemo:TMemo;aArtist:string);
end;
var
FormMain: TFormMain;
implementation
uses
System.Diagnostics, System.Threading;
{$R *.dfm}
procedure TFormMain.Button1Click(Sender: TObject);
begin
ExecuteRESTCall(Memo1, (Sender as TButton).Tag.ToString);
end;
procedure TFormMain.Button2Click(Sender: TObject);
begin
ExecuteRESTCall(Memo2, (Sender as TButton).Tag.ToString);
end;
procedure TFormMain.Button3Click(Sender: TObject);
begin
ExecuteRESTCall(Memo3, (Sender as TButton).Tag.ToString);
end;
procedure TFormMain.Button4Click(Sender: TObject);
begin
ExecuteRESTCall(Memo4, (Sender as TButton).Tag.ToString);
end;
procedure TFormMain.Button5Click(Sender: TObject);
begin
ExecuteRESTCall(Memo5, (Sender as TButton).Tag.ToString);
end;
procedure TFormMain.Button6Click(Sender: TObject);
begin
ExecuteRESTCall(Memo6, (Sender as TButton).Tag.ToString);
end;
function TFormMain.DoRESTCall(aArtist: string): string;
var
lRESTClient: TRESTClient;
lRESTRequest: TRESTRequest;
lRESTResponse:TRESTResponse;
begin
lRESTClient := TRESTClient.Create('http://api.discogs.com');
lRESTRequest := TRESTRequest.Create(nil);
lRESTResponse := TRESTResponse.Create(nil);
lRESTRequest.Client := lRESTClient;
lRESTRequest.Response := lRESTResponse;
lRESTRequest.Resource := 'artists/{ID}';
lRESTRequest.Params[0].Value := aArtist;
try
lRESTRequest.Execute;
Result := lRESTResponse.Content;
finally {Free resources within thread execution}
lRESTResponse.Free;
lRESTRequest.Free;
lRESTClient.Free;
end;
end;
procedure TFormMain.ExecuteRESTCall(aMemo: TMemo; aArtist: string);
var
lStopWatch: TStopWatch;
begin
aMemo.Lines.Clear;
aMemo.Repaint;
if NOT CheckBoxUseThreading.Checked then
begin {Blocking REST call}
lStopWatch := TStopWatch.StartNew;
RESTRequest1.Params[0].Value := aArtist;
RESTRequest1.Execute;
lStopWatch.Stop;
aMemo.Lines.Add(RESTResponse1.Content);
aMemo.Lines.Add(lStopWatch.ElapsedMilliseconds.ToString + ' ms.');
end
else
begin
{TTask parallel REST call}
TTask.Run(procedure
var lResult: string;
begin
lResult := DoRESTCall(aArtist);
TThread.Synchronize(nil, procedure
begin
aMemo.Lines.Add(lResult);
end);
end);
end;
end;
procedure TFormMain.Timer1Timer(Sender: TObject);
begin
ProgressBar1.StepIt;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, Registry, StdCtrls, ComCtrls, ExtCtrls
{$IFDEF VER150}, XPMan{$ENDIF};
type
TfrmRegistryChecker = class(TForm)
gbParameters: TGroupBox;
lvResult: TListView;
edValue: TEdit;
lblValue: TLabel;
cbKeys: TCheckBox;
cbValues: TCheckBox;
cbData: TCheckBox;
btnFind: TButton;
sbCount: TStatusBar;
btnSave: TButton;
cbHKEY_CLASSES_ROOT: TCheckBox;
cbHKEY_CURRENT_USER: TCheckBox;
cbHKEY_LOCAL_MACHINE: TCheckBox;
cbHKEY_USERS: TCheckBox;
cbHKEY_PERFORMANCE_DATA: TCheckBox;
bvlSeparator: TBevel;
cbHKEY_CURRENT_CONFIG: TCheckBox;
cbHKEY_DYN_DATA: TCheckBox;
odSave: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnFindClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure edValueChange(Sender: TObject);
private
FReg: TRegistry;
FTotal, FLast: Integer;
FEnable: Boolean;
procedure Scan(Key: String);
procedure InitScan;
procedure IsValidData(const AKey, AValue, AData: String);
end;
var
frmRegistryChecker: TfrmRegistryChecker;
implementation
{$R *.dfm}
procedure TfrmRegistryChecker.FormCreate(Sender: TObject);
begin
FReg := TRegistry.Create;
end;
procedure TfrmRegistryChecker.FormDestroy(Sender: TObject);
begin
FReg.Free;
end;
procedure TfrmRegistryChecker.Scan(Key: String);
var
S: TStringList;
I: Integer;
begin
if FReg.OpenKeyReadOnly(Key) then
try
S := TStringList.Create;
try
FReg.GetValueNames(S);
for I := 0 to S.Count - 1 do
begin
IsValidData(Key, S.Strings[I], '');
if FReg.GetDataType(S.Strings[I]) in [rdString, rdExpandString] then
IsValidData(Key, S.Strings[I], FReg.ReadString(S.Strings[I]));
end;
S.Clear;
FReg.GetKeyNames(S);
for I := 0 to S.Count - 1 do
if S.Strings[I] <> '' then
Scan(Key + '\' + S.Strings[I]);
finally
S.Free;
end;
finally
FReg.CloseKey;
end;
end;
procedure TfrmRegistryChecker.btnFindClick(Sender: TObject);
begin
InitScan;
end;
procedure TfrmRegistryChecker.InitScan;
begin
FTotal := 0;
FLast := 0;
btnFind.Enabled := False;
edValue.Enabled := False;
try
if cbHKEY_CLASSES_ROOT.Checked then
begin
FReg.RootKey := HKEY_CLASSES_ROOT;
sbCount.Panels.Items[2].Text := 'HKEY_CLASSES_ROOT';
Scan('');
end;
if cbHKEY_CURRENT_USER.Checked then
begin
FReg.RootKey := HKEY_CURRENT_USER;
sbCount.Panels.Items[2].Text := 'HKEY_CURRENT_USER';
Scan('');
end;
if cbHKEY_LOCAL_MACHINE.Checked then
begin
FReg.RootKey := HKEY_LOCAL_MACHINE;
sbCount.Panels.Items[2].Text := 'HKEY_LOCAL_MACHINE';
Scan('');
end;
if cbHKEY_USERS.Checked then
begin
FReg.RootKey := HKEY_USERS;
sbCount.Panels.Items[2].Text := 'HKEY_USERS';
Scan('');
end;
if cbHKEY_PERFORMANCE_DATA.Checked then
begin
FReg.RootKey := HKEY_PERFORMANCE_DATA;
sbCount.Panels.Items[2].Text := 'HKEY_PERFORMANCE_DATA';
Scan('');
end;
if cbHKEY_CURRENT_CONFIG.Checked then
begin
FReg.RootKey := HKEY_CURRENT_CONFIG;
sbCount.Panels.Items[2].Text := 'HKEY_CURRENT_CONFIG';
Scan('');
end;
if cbHKEY_PERFORMANCE_DATA.Checked then
begin
FReg.RootKey := HKEY_DYN_DATA;
sbCount.Panels.Items[2].Text := 'HKEY_DYN_DATA';
Scan('');
end;
finally
sbCount.Panels.Items[2].Text := '';
sbCount.Panels.Items[3].Text := 'COMPLETE';
btnSave.Enabled := lvResult.Items.Count > 0;
btnFind.Enabled := True;
edValue.Enabled := True;
end;
end;
procedure TfrmRegistryChecker.IsValidData(const AKey, AValue, AData: String);
const
TOTAL = 'Total count: ';
FIND = 'Find count: ';
var
TmpStr: String;
begin
Inc(FTotal);
if FTotal - FLast > 500 then
begin
FLast := FTotal;
sbCount.Panels.Items[0].Text := TOTAL + IntToStr(FTotal);
sbCount.Panels.Items[1].Text := FIND + IntToStr(lvResult.Items.Count);
TmpStr := AKey;
if AValue <> '' then
TmpStr := TmpStr + ' {' + AValue + '}';
sbCount.Panels.Items[3].Text := TmpStr;
Application.ProcessMessages;
end;
if AKey <> '' then
if cbKeys.Checked then
if Pos(edValue.Text, AKey) > 0 then
with lvResult.Items.Add do
begin
Caption := sbCount.Panels.Items[2].Text;
SubItems.Add(AKey);
SubItems.Add('');
SubItems.Add('');
end;
if AValue <> '' then
if cbValues.Checked then
if Pos(edValue.Text, AValue) > 0 then
with lvResult.Items.Add do
begin
Caption := sbCount.Panels.Items[2].Text;
SubItems.Add(AKey);
SubItems.Add(AValue);
SubItems.Add('');
end;
if AData <> '' then
if cbData.Checked then
if Pos(edValue.Text, AData) > 0 then
with lvResult.Items.Add do
begin
Caption := sbCount.Panels.Items[2].Text;
SubItems.Add(AKey);
SubItems.Add(AValue);
SubItems.Add(AData);
end;
end;
procedure TfrmRegistryChecker.btnSaveClick(Sender: TObject);
var
I: Integer;
S: TStringList;
begin
if odSave.Execute then
begin
S := TStringList.Create;
try
for I := 0 to lvResult.Items.Count - 1 do
begin
S.Add('HKEY: ' + lvResult.Items.Item[I].Caption);
S.Add('Key: ' + lvResult.Items.Item[I].SubItems.Strings[0]);
S.Add('Value: ' + lvResult.Items.Item[I].SubItems.Strings[1]);
S.Add('Data: ' + lvResult.Items.Item[I].SubItems.Strings[2]);
S.Add('====================================================================');
S.Add('');
end;
S.SaveToFile(odSave.FileName);
finally
S.Free;
end;
end;
end;
procedure TfrmRegistryChecker.edValueChange(Sender: TObject);
begin
btnFind.Enabled := edValue.Text <> '';
end;
end.
|
unit ibSHUserManager;
interface
uses
SysUtils, Classes,
SHDesignIntf,
ibSHDesignIntf, ibSHDriverIntf, ibSHComponent, ibSHTool;
type
TibSHUserManager = class(TibBTTool, IibSHUserManager, IibSHBranch, IfbSHBranch)
private
FIntDatabase: TComponent;
FIntDatabaseIntf: IibSHDatabase;
FServer: string;
FUserNameList: TStrings;
FFirstNameList: TStrings;
FMiddleNameList: TStrings;
FLastNameList: TStrings;
FPasswordList: TStrings;
function GetServer: string;
procedure SetServer(Value: string);
// IibSHUserManager
procedure DisplayUsers;
function GetUserCount: Integer;
function GetUserName(AIndex: Integer): string;
function GetFirstName(AIndex: Integer): string;
function GetMiddleName(AIndex: Integer): string;
function GetLastName(AIndex: Integer): string;
function GetConnectCount(const UserName: string): Integer;
function AddUser(const UserName, Password, FirstName, MiddleName, LastName: string): Boolean;
function ModifyUser(const UserName, Password, FirstName, MiddleName, LastName: string): Boolean;
function DeleteUser(const UserName: string): Boolean;
protected
procedure SetOwnerIID(Value: TGUID); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Server: string read GetServer write SetServer;
property UserCount: Integer read GetUserCount;
end;
TibSHUserManagerFactory = class(TibBTToolFactory)
end;
TibSHUser = class(TibBTComponent, IibSHUser)
private
FUserName: string;
FPassword: string;
FFirstName: string;
FMiddleName: string;
FLastName: string;
function GetUserName: string;
procedure SetUserName(Value: string);
function GetPassword: string;
procedure SetPassword(Value: string);
function GetFirstName: string;
procedure SetFirstName(Value: string);
function GetMiddleName: string;
procedure SetMiddleName(Value: string);
function GetLastName: string;
procedure SetLastName(Value: string);
published
property UserName: string read GetUserName write SetUserName;
property Password: string read GetPassword write SetPassword;
property FirstName: string read GetFirstName write SetFirstName;
property MiddleName: string read GetMiddleName write SetMiddleName;
property LastName: string read GetLastName write SetLastName;
end;
procedure Register;
implementation
uses
ibSHConsts, ibSHSQLs, ibSHValues, ibSHPassword,
ibSHUserManagerActions,
ibSHUserManagerEditors;
procedure Register;
begin
SHRegisterImage(GUIDToString(IibSHUserManager), 'UserManager.bmp');
SHRegisterImage(GUIDToString(IibSHUser), 'User.bmp');
SHRegisterImage(TibSHUserManagerPaletteAction.ClassName, 'UserManager.bmp');
SHRegisterImage(TibSHUserManagerFormAction.ClassName, 'User.bmp');
SHRegisterImage(TibSHUserManagerToolbarAction_Create.ClassName, 'Button_Create.bmp');
SHRegisterImage(TibSHUserManagerToolbarAction_Alter.ClassName, 'Button_Alter.bmp');
SHRegisterImage(TibSHUserManagerToolbarAction_Drop.ClassName, 'Button_Drop.bmp');
SHRegisterImage(TibSHUserManagerToolbarAction_Refresh.ClassName, 'Button_Refresh.bmp');
SHRegisterImage(SCallUsers, 'User.bmp');
SHRegisterComponents([
TibSHUserManager,
TibSHUserManagerFactory,
TibSHUser]);
SHRegisterActions([
// Palette
TibSHUserManagerPaletteAction,
// Forms
TibSHUserManagerFormAction,
// Toolbar
TibSHUserManagerToolbarAction_Create,
TibSHUserManagerToolbarAction_Alter,
TibSHUserManagerToolbarAction_Drop,
TibSHUserManagerToolbarAction_Refresh]);
SHRegisterPropertyEditor(IUnknown, SCallAccessMode, TibBTAccessModePropEditor);
end;
{ TibSHUserManager }
constructor TibSHUserManager.Create(AOwner: TComponent);
var
vComponentClass: TSHComponentClass;
begin
inherited Create(AOwner);
FUserNameList := TStringList.Create;
FFirstNameList := TStringList.Create;
FMiddleNameList := TStringList.Create;
FLastNameList := TStringList.Create;
FPasswordList := TStringList.Create;
vComponentClass := Designer.GetComponent(IibSHDatabase);
if Assigned(vComponentClass) then
begin
FIntDatabase := vComponentClass.Create(Self);
Supports(FIntDatabase, IibSHDatabase, FIntDatabaseIntf);
end;
end;
destructor TibSHUserManager.Destroy;
begin
FUserNameList.Free;
FFirstNameList.Free;
FMiddleNameList.Free;
FLastNameList.Free;
FPasswordList.Free;
FIntDatabaseIntf := nil;
FreeAndNil(FIntDatabase);
inherited Destroy;
end;
function TibSHUserManager.GetServer: string;
begin
if Assigned(BTCLServer) then
Result := Format('%s (%s) ', [BTCLServer.Caption, BTCLServer.CaptionExt]);
end;
procedure TibSHUserManager.SetServer(Value: string);
begin
FServer := Value;
end;
procedure TibSHUserManager.SetOwnerIID(Value: TGUID);
begin
inherited SetOwnerIID(Value);
if Assigned(Designer.CurrentComponent) and Supports(Designer.CurrentComponent, IibSHUserManager) then
if Assigned(Designer.CurrentComponentForm) and Supports(Designer.CurrentComponentForm, ISHRunCommands) then
(Designer.CurrentComponentForm as ISHRunCommands).Refresh;
end;
procedure TibSHUserManager.DisplayUsers;
var
I: Integer;
DoSecurityConnect: Boolean;
begin
DoSecurityConnect := False;
FUserNameList.Clear;
FFirstNameList.Clear;
FMiddleNameList.Clear;
FLastNameList.Clear;
FPasswordList.Clear;
if Assigned(BTCLServer) then
begin
if Assigned(FIntDatabaseIntf) then
begin
FIntDatabaseIntf.OwnerIID := BTCLServer.InstanceIID;
FIntDatabaseIntf.Database := BTCLServer.SecurityDatabase;
FIntDatabaseIntf.StillConnect := True;
end;
if BTCLServer.PrepareDRVService and BTCLServer.DRVService.Attach(stSecurityService) then
begin
try
try
BTCLServer.DRVService.DisplayUsers;
except
DoSecurityConnect := True;
end;
for I := 0 to Pred(BTCLServer.DRVService.UserCount) do
begin
FUserNameList.Add(BTCLServer.DRVService.GetUserName(I));
FFirstNameList.Add(BTCLServer.DRVService.GetFirstName(I));
FMiddleNameList.Add(BTCLServer.DRVService.GetMiddleName(I));
FLastNameList.Add(BTCLServer.DRVService.GetLastName(I));
FPasswordList.Add('');
end;
finally
BTCLServer.DRVService.Detach;
end;
end else
DoSecurityConnect := True;
if DoSecurityConnect then
begin
try
if FIntDatabaseIntf.Connect then
if FIntDatabaseIntf.DRVQuery.ExecSQL(FormatSQL(SQL_GET_USERS_FROM_SECURITY), [], False) then
while not FIntDatabaseIntf.DRVQuery.Eof do
begin
FUserNameList.Add(FIntDatabaseIntf.DRVQuery.GetFieldStrValue('USER_NAME'));
FFirstNameList.Add(FIntDatabaseIntf.DRVQuery.GetFieldStrValue('FIRST_NAME'));
FMiddleNameList.Add(FIntDatabaseIntf.DRVQuery.GetFieldStrValue('MIDDLE_NAME'));
FLastNameList.Add(FIntDatabaseIntf.DRVQuery.GetFieldStrValue('LAST_NAME'));
FPasswordList.Add(FIntDatabaseIntf.DRVQuery.GetFieldStrValue('PASSWD'));
FIntDatabaseIntf.DRVQuery.Next;
end;
finally
FIntDatabaseIntf.DRVQuery.Transaction.Commit;
FIntDatabaseIntf.Disconnect;
end;
end;
end;
end;
function TibSHUserManager.GetUserCount: Integer;
begin
Result := FUserNameList.Count;
end;
function TibSHUserManager.GetUserName(AIndex: Integer): string;
begin
Result := FUserNameList[AIndex];
end;
function TibSHUserManager.GetFirstName(AIndex: Integer): string;
begin
Result := FFirstNameList[AIndex];
end;
function TibSHUserManager.GetMiddleName(AIndex: Integer): string;
begin
Result := FMiddleNameList[AIndex];
end;
function TibSHUserManager.GetLastName(AIndex: Integer): string;
begin
Result := FLastNameList[AIndex];
end;
function TibSHUserManager.GetConnectCount(const UserName: string): Integer;
var
I: Integer;
begin
Result := 0;
if Assigned(BTCLDatabase) then
begin
for I := 0 to Pred(BTCLDatabase.DRVQuery.Database.UserNames.Count) do
if AnsiSameText(BTCLDatabase.DRVQuery.Database.UserNames[I], UserName) then
Result := Result + 1;
end;
end;
function TibSHUserManager.AddUser(const UserName, Password, FirstName, MiddleName, LastName: string): Boolean;
var
DoSecurityConnect: Boolean;
begin
Result := False;
DoSecurityConnect := False;
if Assigned(BTCLServer) then
begin
if BTCLServer.PrepareDRVService and BTCLServer.DRVService.Attach(stSecurityService) then
begin
try
try
Result := BTCLServer.DRVService.AddUser(UserName, Password, FirstName, MiddleName, LastName);
except
DoSecurityConnect := True;
end;
finally
BTCLServer.DRVService.Detach;
end;
end else
DoSecurityConnect := True;
if DoSecurityConnect then
begin
try
if FIntDatabaseIntf.Connect then
begin
FIntDatabaseIntf.DRVQuery.Transaction.Params.Text := TRWriteParams;
Result := FIntDatabaseIntf.DRVQuery.ExecSQL(Format(FormatSQL(SQL_INSERT_SECURITY), [UserName, CreateInterbasePassword(Password), FirstName, MiddleName, LastName]), [], True);
end;
finally
FIntDatabaseIntf.DRVQuery.Transaction.Params.Text := TRReadParams;
FIntDatabaseIntf.Disconnect;
end;
end;
FUserNameList.Add(UserName);
FFirstNameList.Add(FirstName);
FMiddleNameList.Add(MiddleName);
FLastNameList.Add(LastName);
FPasswordList.Add('');
end;
end;
function TibSHUserManager.ModifyUser(const UserName, Password, FirstName, MiddleName, LastName: string): Boolean;
var
I: Integer;
DoSecurityConnect: Boolean;
begin
Result := False;
DoSecurityConnect := False;
if Assigned(BTCLServer) then
begin
if BTCLServer.PrepareDRVService and BTCLServer.DRVService.Attach(stSecurityService) then
begin
try
try
Result := BTCLServer.DRVService.ModifyUser(UserName, Password, FirstName, MiddleName, LastName);
except
DoSecurityConnect := True;
end;
finally
BTCLServer.DRVService.Detach;
end;
end else
DoSecurityConnect := True;
if DoSecurityConnect then
begin
try
if FIntDatabaseIntf.Connect then
begin
FIntDatabaseIntf.DRVQuery.Transaction.Params.Text := TRWriteParams;
Result := FIntDatabaseIntf.DRVQuery.ExecSQL(Format(FormatSQL(SQL_UPDATE_SECURITY), [CreateInterbasePassword(Password), FirstName, MiddleName, LastName, UserName]), [], True);
end;
finally
FIntDatabaseIntf.DRVQuery.Transaction.Params.Text := TRReadParams;
FIntDatabaseIntf.Disconnect;
end;
end;
I := FUserNameList.IndexOfName(UserName);
if I <> -1 then
begin
FFirstNameList[I] := FirstName;
FMiddleNameList[I] := MiddleName;
FLastNameList[I] := LastName;
end;
end;
end;
function TibSHUserManager.DeleteUser(const UserName: string): Boolean;
var
I: Integer;
DoSecurityConnect: Boolean;
begin
Result := False;
DoSecurityConnect := False;
if Assigned(BTCLServer) then
begin
if BTCLServer.PrepareDRVService and BTCLServer.DRVService.Attach(stSecurityService) then
begin
try
try
Result := BTCLServer.DRVService.DeleteUser(UserName);
except
DoSecurityConnect := True;
end;
finally
BTCLServer.DRVService.Detach;
end;
end else
DoSecurityConnect := True;
if DoSecurityConnect then
begin
try
if FIntDatabaseIntf.Connect then
begin
FIntDatabaseIntf.DRVQuery.Transaction.Params.Text := TRWriteParams;
Result := FIntDatabaseIntf.DRVQuery.ExecSQL(Format(FormatSQL(SQL_DELETE_SECURITY), [UserName]), [], True);
end;
finally
FIntDatabaseIntf.DRVQuery.Transaction.Params.Text := TRReadParams;
FIntDatabaseIntf.Disconnect;
end;
end;
I := FUserNameList.IndexOfName(UserName);
if I <> -1 then
begin
FUserNameList.Delete(I);
FFirstNameList.Delete(I);
FMiddleNameList.Delete(I);
FLastNameList.Delete(I);
FPasswordList.Delete(I);
end;
end;
end;
{ TibSHUser }
function TibSHUser.GetUserName: string;
begin
Result := FUserName;
end;
procedure TibSHUser.SetUserName(Value: string);
begin
FUserName := AnsiUpperCase(Value);
end;
function TibSHUser.GetPassword: string;
begin
Result := FPassword;
end;
procedure TibSHUser.SetPassword(Value: string);
begin
FPassword := Value;
end;
function TibSHUser.GetFirstName: string;
begin
Result := FFirstName;
end;
procedure TibSHUser.SetFirstName(Value: string);
begin
FFirstName := Value;
end;
function TibSHUser.GetMiddleName: string;
begin
Result := FMiddleName;
end;
procedure TibSHUser.SetMiddleName(Value: string);
begin
FMiddleName := Value;
end;
function TibSHUser.GetLastName: string;
begin
Result := FLastName;
end;
procedure TibSHUser.SetLastName(Value: string);
begin
FLastName := Value;
end;
initialization
Register;
end.
|
unit FScanProgress;
(*====================================================================
Progress window for scanning the disk or importing from QuickDir 4 format.
Implements the scan in the Run procedure
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
Windows,
{$ELSE}
LCLIntf, LCLType, LMessages, ExtCtrls,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ATGauge,
UTypes, UApiTypes;
type
{ TFormScanProgress }
TFormScanProgress = class(TForm)
Gauge: TGauge;
LabelInfo: TLabel;
//Gauge: TPanel;
ButtonCancel: TButton;
LabelDoing: TLabel;
procedure ButtonCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
CanRun : boolean;
function ScanQDir4Database: boolean;
public
LastPhase : Integer;
CancelledByUser: boolean;
{$ifdef mswindows}
Drive : char;
{$else}
Drive : ShortString;
{$endif}
ScanningQDir4: boolean;
DiskName : ShortString;
VolumeLabel : ShortString;
StartPath : ShortString;
DBaseHandle : PDBaseHandle;
Success : boolean;
procedure Run(var Info); message WM_User + 100;
procedure DefaultHandler(var Message); override;
end;
var
FormScanProgress: TFormScanProgress;
implementation
uses UApi, UCallbacks, FScanArchive, ULang, FSettings;
var
QLocalOptions : TLocalOptions; {record}
{$R *.dfm}
//=============================================================================
// callback - support of Central Point Backup archives - not used now
function IsTheLastCPB (FName: ShortString): boolean; far;
begin
{$ifdef CZECH}
if QLocalOptions.ScanArchives <> cfNoScan
then
case QLocalOptions.ScanCPB of
cfScan: IsTheLastCPB := true;
cfAsk: IsTheLastCPB := Application.MessageBox(
lsIsItLastCPBDisk, lsCPBFound, MB_YESNOCANCEL or MB_ICONQUESTION)
= IDYES;
else IsTheLastCPB := false;
end
else
{$endif}
IsTheLastCPB := false;
end;
//-----------------------------------------------------------------------------
// Callback - optionally displays a dialog box asking, whther to scan or skip
// the contents of this archive
function HowToContinue (FName: ShortString): word; far;
begin
Result := cmYesAll;
case QLocalOptions.ScanArchives of
cfScan: Result := cmYes;
cfAsk: begin
FormScanArchive.LabelMsg.Caption :=
lsScanArchive + FName + '?';
FormScanArchive.ShowModal;
Result := FormScanArchive.Response;
end;
cfNoScan: Result := cmNo;
end;
end;
//-----------------------------------------------------------------------------
// Callback - new text to the text info
procedure NewLineToIndicator (Line: ShortString); far;
begin
FormScanProgress.LabelInfo.Caption := Line;
Application.ProcessMessages;
end;
//-----------------------------------------------------------------------------
// Callback - append text to the text info
procedure AppendLineToIndicator (Line: ShortString); far;
begin
FormScanProgress.LabelInfo.Caption := FormScanProgress.LabelInfo.Caption + Line;
Application.ProcessMessages;
end;
//-----------------------------------------------------------------------------
// Callback - updates the progress gauge
procedure UpdateProgressIndicator (Phase, Progress: Integer); far;
begin
if FormScanProgress.LastPhase <> Phase then
begin
FormScanProgress.LastPhase := Phase;
case Phase of
1: FormScanProgress.LabelDoing.Caption :=
lsScanningTree;
2: FormScanProgress.LabelDoing.Caption :=
lsScanningFoldersAndFiles;
else FormScanProgress.LabelDoing.Caption := '';
end;
if Phase = 2
then FormScanProgress.Gauge.Show
else FormScanProgress.Gauge.Hide;
end;
if Phase = 2 then
FormScanProgress.Gauge.Progress := Progress;
Application.ProcessMessages;
end;
//-----------------------------------------------------------------------------
// Callback - returns true if the user presses the abort button
function AbortScan: boolean; far;
begin
AbortScan := FormScanProgress.CancelledByUser;
end;
//=============================================================================
procedure TFormScanProgress.FormShow(Sender: TObject);
begin
CancelledByUser := false;
CanRun := true;
Gauge.Hide;
LastPhase := 0;
// executes the Run procedure after the form is displayed
PostMessage(Self.Handle, WM_User + 100, 0, 0);
if StartPath = '' then StartPath := Drive + ':';
end;
//-----------------------------------------------------------------------------
procedure TFormScanProgress.ButtonCancelClick(Sender: TObject);
begin
CancelledByUser := true;
end;
//-----------------------------------------------------------------------------
procedure TFormScanProgress.FormCreate(Sender: TObject);
begin
CanRun := false;
ScanningQDir4 := false;
end;
//-----------------------------------------------------------------------------
function TFormScanProgress.ScanQDir4Database: boolean;
var
TmpKey: ShortString;
begin
Result := false;
while QI_ReadQDir4Entry(-1) do
begin
DiskName := QI_GetQDir4VolumeLabel;
TmpKey := AnsiUpperCase(DiskName);
if TmpKey = DiskName then
begin
DiskName := AnsiLowerCase(DiskName);
DiskName[1] := TmpKey[1];
end;
QI_ClearTreeStruct(DBaseHandle);
Success := QI_ScanQDir4Record(DBaseHandle, Drive + ':', DiskName);
if Success
then
begin
if not QI_AppendNewDBaseEntry(DBaseHandle) then // here is the change in the KeyField
begin
QI_ClearTreeStruct(DBaseHandle);
Result := true;
exit;
end
end
else
exit;
end;
end;
//-----------------------------------------------------------------------------
procedure TFormScanProgress.Run (var Info);
begin
if not CanRun then exit;
CanRun := false;
QI_GetLocalOptions (DBaseHandle, QLocalOptions);
QI_RegisterCallbacks (IsTheLastCPB,
HowToContinue, NewLineToIndicator,
AppendLineToIndicator,
UpdateProgressIndicator,
AbortScan);
try
if ScanningQDir4
then Success := ScanQDir4Database
else Success := QI_ScanDisk(DBaseHandle, StartPath, DiskName, VolumeLabel);
finally
QI_UnregisterCallBacks;
ModalResult := mrOk;
end;
end;
//-----------------------------------------------------------------------------
// Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay
// to the top window, so we must have this handler in all forms.
procedure TFormScanProgress.DefaultHandler(var Message);
begin
with TMessage(Message) do
if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and
g_CommonOptions.bDisableCdAutorun
then
Result := 1
else
inherited DefaultHandler(Message)
end;
end.
|
unit DesignImp;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics, Forms, ExtCtrls,
Contnrs,
DesignSurface;
const
cDesignDefaultHandleWidth = 8;
type
TDesignHandle = class(TCustomControl)
private
FResizeable: Boolean;
protected
function HandleRect(inIndex: Integer): TRect;
function HitRect(inPoint: TPoint): Integer;
procedure Paint; override;
procedure PaintEdge(const inRect: TRect);
procedure PaintHandle(const inRect: TRect);
procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND;
property Resizeable: Boolean read FResizeable write FResizeable;
end;
//
TDesignHandles = class(TComponent)
private
FContainer: TWinControl;
FSelected: TControl;
FResizeable: Boolean;
protected
function GetHandleWidth: Integer;
function GetSelectionRect: TRect;
function SelectedToScreenRect(const inRect: TRect): TRect;
procedure CreateHandles;
procedure SetContainer(const Value: TWinControl);
procedure SetHandleRects(const inRect: TRect);
procedure SetResizeable(const Value: Boolean);
procedure SetSelected(const Value: TControl);
procedure ShowHideHandles(inShow: Boolean);
public
Handles: array[0..3] of TDesignHandle;
constructor Create(inOwner: TComponent); override;
function HitRect(X, Y: Integer): TDesignHandleId;
function SelectedToContainer(const inPt: TPoint): TPoint;
procedure RepaintHandles;
procedure UpdateHandleRects;
procedure UpdateHandles;
property Container: TWinControl read FContainer write SetContainer;
property HandleWidth: Integer read GetHandleWidth;
property Resizeable: Boolean read FResizeable write SetResizeable;
property Selected: TControl read FSelected write SetSelected;
end;
//
TDesignSelector = class(TDesignCustomSelector)
private
FHandles: TObjectList;
FHandleWidth: Integer;
protected
function FindHandles(inValue: TControl): TDesignHandles;
function GetCount: Integer; override;
function GetHandles(inIndex: Integer): TDesignHandles;
function GetSelection(inIndex: Integer): TControl; override;
procedure SetHandles(inIndex: Integer; inValue: TDesignHandles);
procedure SetHandleWidth(inValue: Integer);
procedure SetSelection(inIndex: Integer; inValue: TControl); override;
procedure ShowHideResizeHandles;
property Handles[inIndex: Integer]: TDesignHandles read GetHandles
write SetHandles;
public
constructor Create(inSurface: TDesignSurface); override;
destructor Destroy; override;
function GetClientControl(inControl: TControl): TControl; override;
function GetCursor(inX, inY: Integer): TCursor; override;
function GetHitHandle(inX, inY: Integer): TDesignHandleId; override;
function IsSelected(inValue: TControl): Boolean; override;
procedure AddToSelection(inValue: TControl); override;
procedure ClearSelection; override;
procedure RemoveFromSelection(inValue: TControl); override;
procedure ShowHideSelection(inShow: Boolean); override;
procedure Update; override;
published
property HandleWidth: Integer read FHandleWidth
write SetHandleWidth default cDesignDefaultHandleWidth;
end;
//
TDesignCustomMouseTool = class
private
FDragRect: TRect;
FOnMouseMove: TNotifyEvent;
public
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); virtual; abstract;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); virtual; abstract;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); virtual; abstract;
property DragRect: TRect read FDragRect write FDragRect;
property OnMouseMove: TNotifyEvent read FOnMouseMove write FOnMouseMove;
end;
//
TDesignDragMode = ( dmNone, dmMove, dmResize, dmSelect, dmCreate );
//
TDesignAction = ( daSelectParent, daDelete, daCopy, daCut, daPaste,
daNudgeLeft, daNudgeRight, daNudgeUp, daNudgeDown, daGrowWidth,
daShrinkWidth, daGrowHeight, daShrinkHeight, daLastAction = MAXINT
);
//
TDesignController = class(TDesignCustomController)
private
FClicked: TControl;
FDragMode: TDesignDragMode;
FDragRect: TRect;
FKeyDownShift: TShiftState;
FMouseIsDown: Boolean;
FMouseTool: TDesignCustomMouseTool;
protected
function GetDragRect: TRect; override;
function KeyDown(inKeycode: Cardinal): Boolean; override;
function KeyUp(inKeycode: Cardinal): Boolean; override;
function MouseDown(Button: TMouseButton; X, Y: Integer): Boolean; override;
function MouseMove(X, Y: Integer): Boolean; override;
function MouseUp(Button: TMouseButton; X, Y: Integer): Boolean; override;
procedure Action(inAction: TDesignAction);
procedure MouseDrag(inSender: TObject);
end;
//
TDesignMouseTool = class(TDesignCustomMouseTool)
private
FSurface: TDesignSurface;
FMouseLast: TPoint;
FMouseStart: TPoint;
protected
function GetMouseDelta: TPoint; virtual;
public
constructor Create(AOwner: TDesignSurface); virtual;
property Surface: TDesignSurface read FSurface write FSurface;
end;
//
TDesignMover = class(TDesignMouseTool)
private
FDragRects: array of TRect;
protected
procedure ApplyDragRects;
procedure CalcDragRects;
procedure CalcPaintRects;
procedure PaintDragRects;
public
constructor Create(AOwner: TDesignSurface); 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;
end;
//
TDesignBander = class(TDesignMouseTool)
protected
function GetClient: TControl; virtual;
function GetPaintRect: TRect;
procedure CalcDragRect; virtual;
procedure PaintDragRect; virtual;
public
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;
end;
//
TDesignSizer = class(TDesignBander)
private
FHandleId: TDesignHandleId;
protected
function GetClient: TControl; override;
procedure ApplyDragRect;
procedure ApplyMouseDelta(X, Y: Integer);
procedure CalcDragRect; override;
public
constructor CreateSizer(AOwner: TDesignSurface;
inHandle: TDesignHandleId);
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
end;
//
TDesignDesigner = class(TComponent, IDesignerHook)
private
FMessenger: TDesignCustomMessenger;
public
constructor Create(inMessenger: TDesignCustomMessenger); reintroduce;
function GetCustomForm: TCustomForm;
function GetIsControl: Boolean;
function GetRoot: TComponent;
function IsDesignMsg(Sender: TControl; var Message: TMessage): Boolean;
function UniqueName(const BaseName: string): string;
procedure Modified;
procedure Notification(AnObject: TPersistent; Operation: TOperation); reintroduce;
procedure PaintGrid;
procedure SetCustomForm(Value: TCustomForm);
procedure SetIsControl(Value: Boolean);
procedure ValidateRename(AComponent: TComponent;
const CurName, NewName: string); reintroduce;
property IsControl: Boolean read GetIsControl write SetIsControl;
property Form: TCustomForm read GetCustomForm write SetCustomForm;
property Messenger: TDesignCustomMessenger read FMessenger write FMessenger;
end;
//
TDesignDesignerMessenger = class(TDesignCustomMessenger)
private
FDesignedForm: TCustomForm;
FDesigner: TDesignDesigner;
protected
procedure SetComponentDesigning(inComponent: TComponent;
inDesigning: Boolean);
procedure SetContainer(inValue: TWinControl); override;
procedure UndesignComponent(inComponent: TComponent);
public
constructor Create; override;
destructor Destroy; override;
procedure DesignComponent(inComponent: TComponent); override;
end;
//
TDesignMessageHookList = class(TComponent)
private
FHooks: TObjectList;
FUser: TDesignCustomMessenger;
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(inUser: TDesignCustomMessenger); reintroduce;
destructor Destroy; override;
procedure Clear;
procedure Hook(inClient: TWinControl);
procedure Unhook(inComponent: TComponent);
end;
//
TDesignWinControlHookMessenger = class(TDesignCustomMessenger)
private
FHooks: TDesignMessageHookList;
protected
procedure HookWinControl(inWinControl: TWinControl);
procedure SetContainer(inValue: TWinControl); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Clear; override;
procedure DesignComponent(inComponent: TComponent); override;
end;
implementation
uses
DesignUtils;
var
ShadedBits: TBitmap;
function NeedShadedBits: TBitmap;
begin
if ShadedBits = nil then
begin
ShadedBits := TBitmap.Create;
with ShadedBits do
begin
Width := 4;
Height := 2;
Canvas.Pixels[0, 0] := clGray;
Canvas.Pixels[1, 0] := clBtnFace;
Canvas.Pixels[2, 0] := clBtnFace;
Canvas.Pixels[3, 0] := clBtnFace;
Canvas.Pixels[0, 1] := clBtnFace;
Canvas.Pixels[1, 1] := clBtnFace;
Canvas.Pixels[2, 1] := clGray;
Canvas.Pixels[3, 1] := clBtnFace;
end;
end;
Result := ShadedBits;
end;
procedure FreeShadedBits;
begin
FreeAndNil(ShadedBits);
end;
{ TDesignHandle }
function TDesignHandle.HandleRect(inIndex: Integer): TRect;
var
w: Integer;
begin
w := TDesignHandles(Owner).HandleWidth;
case inIndex of
0: Result := Rect(0, 0, w, w); // left-top
1: Result := Rect((Width - w) div 2, 0, (Width + w) div 2, w); // middle-top
2: Result := Rect(Width - w, 0, Width, w); // right-top
3: Result := Rect(0, (Height - w) div 2, w, (Height + w) div 2); // left-center
end;
end;
procedure TDesignHandle.WMEraseBkgnd(var Message: TWmEraseBkgnd);
begin
Message.Result := 1;
end;
procedure TDesignHandle.PaintHandle(const inRect: TRect);
begin
Canvas.Rectangle(inRect);
end;
procedure TDesignHandle.PaintEdge(const inRect: TRect);
begin
Canvas.FillRect(ClientRect);
end;
procedure TDesignHandle.Paint;
begin
with Canvas do
begin
Brush.Bitmap := NeedShadedBits;
PaintEdge(ClientRect);
Brush.Bitmap := nil;
Brush.Color := clWhite;
Pen.Color := clBlack;
if Resizeable then
if (Width > Height) then
begin
PaintHandle(HandleRect(0));
PaintHandle(HandleRect(1));
PaintHandle(HandleRect(2));
end
else
PaintHandle(HandleRect(3));
end;
end;
function TDesignHandle.HitRect(inPoint: TPoint): Integer;
begin
Result := -1;
if Width > Height then
if PtInRect(HandleRect(0), inPoint) then
Result := 0
else if PtInRect(HandleRect(1), inPoint) then
Result := 1
else if PtInRect(HandleRect(2), inPoint) then
Result := 2;
if Result < 0 then
if PtInRect(HandleRect(3), inPoint) then
Result := 3;
end;
{ TDesignHandles }
constructor TDesignHandles.Create(inOwner: TComponent);
begin
inherited;
CreateHandles;
Resizeable := true;
end;
procedure TDesignHandles.CreateHandles;
var
i: Integer;
begin
for i := 0 to 3 do
Handles[i] := TDesignHandle.Create(Self);
end;
function TDesignHandles.GetHandleWidth: Integer;
begin
Result := TDesignSelector(Owner).HandleWidth;
end;
procedure TDesignHandles.SetContainer(const Value: TWinControl);
var
i: Integer;
begin
FContainer := Value;
for i := 0 to 3 do
with Handles[i] do
begin
Visible := false;
Parent := Container;
end;
end;
procedure TDesignHandles.SetSelected(const Value: TControl);
begin
if (Selected <> Value) then
begin
if (Value is TDesignHandle) then
FSelected := nil
else
FSelected := Value;
UpdateHandleRects;
//UpdateHandles;
end;
end;
procedure TDesignHandles.SetResizeable(const Value: Boolean);
var
i: Integer;
begin
FResizeable := Value;
for i := 0 to 3 do
Handles[i].Resizeable := Value;
end;
procedure TDesignHandles.ShowHideHandles(inShow: Boolean);
var
i: Integer;
begin
for i := 0 to 3 do
with Handles[i] do
begin
Visible := inShow;
if inShow then
begin
BringToFront;
//Update;
end;
end;
end;
procedure TDesignHandles.UpdateHandleRects;
begin
SetHandleRects(GetSelectionRect);
end;
procedure TDesignHandles.UpdateHandles;
begin
if (Selected <> nil) and (Container <> nil) and (Selected <> Container) then
begin
UpdateHandleRects;
ShowHideHandles(true);
Container.Update;
end else
ShowHideHandles(false)
end;
procedure TDesignHandles.RepaintHandles;
var
i: Integer;
begin
for i := 0 to 3 do
Handles[i].Repaint;
end;
function TDesignHandles.HitRect(X, Y: Integer): TDesignHandleId;
const
cRectIds: array[0..3, 0..3] of TDesignHandleId = (
( dhLeftTop, dhMiddleTop, dhRightTop, dhNone ),
( dhNone, dhNone, dhNone, dhLeftMiddle ),
( dhNone, dhNone, dhNone, dhRightMiddle ),
( dhLeftBottom, dhMiddleBottom, dhRightBottom, dhNone )
);
var
i, r: Integer;
begin
for i := 0 to 3 do
begin
with Handles[i] do
r := HitRect(Point(X - Left, Y - Top));
if (r >= 0) then
begin
Result := cRectIds[i][r];
exit;
end;
end;
Result := dhNone;
end;
function TDesignHandles.SelectedToContainer(const inPt: TPoint): TPoint;
var
c: TControl;
begin
Result := inPt;
c := Selected.Parent;
while (c <> Container) and (c <> nil) do
begin
Inc(Result.X, c.Left);
Inc(Result.Y, c.Top);
c := c.Parent;
end;
end;
function TDesignHandles.SelectedToScreenRect(const inRect: TRect): TRect;
var
p: TWinControl;
begin
if Selected = Container then
p := Container
else
p := Selected.Parent;
Result.topLeft := p.ClientToScreen(inRect.topLeft);
Result.bottomRight := p.ClientToScreen(inRect.bottomRight);
end;
function TDesignHandles.GetSelectionRect: TRect;
var
p: TPoint;
begin
if (Selected = Container) then
p := Point(0, 0)
else
p := SelectedToContainer(Selected.BoundsRect.topLeft);
Result := Rect(p.X, p.Y, p.X + Selected.Width, p.y + Selected.Height);
InflateRect(Result, -HandleWidth div 2, -HandleWidth div 2);
end;
procedure TDesignHandles.SetHandleRects(const inRect: TRect);
var
w: Integer;
begin
w := HandleWidth;
with inRect do
begin
Handles[0].BoundsRect := Rect(Left - w, Top - w, Right + w, Top);
Handles[1].BoundsRect := Rect(Left - w, Top, Left, Bottom);
Handles[2].BoundsRect := Rect(Right, Top, Right + w, Bottom);
Handles[3].BoundsRect := Rect(Left - w, Bottom, Right + w, Bottom + w);
end;
end;
{ TDesignSelector }
constructor TDesignSelector.Create(inSurface: TDesignSurface);
begin
inherited;
//ControllerClass := TDesignController;
FHandleWidth := cDesignDefaultHandleWidth;
FHandles := TObjectList.Create;
end;
destructor TDesignSelector.Destroy;
begin
FHandles.Free;
inherited;
end;
procedure TDesignSelector.SetHandleWidth(inValue: Integer);
begin
FHandleWidth := inValue;
Update;
end;
function TDesignSelector.GetCount: Integer;
begin
Result := FHandles.Count;
end;
function TDesignSelector.GetHandles(inIndex: Integer): TDesignHandles;
begin
Result := TDesignHandles(FHandles[inIndex]);
end;
procedure TDesignSelector.SetHandles(inIndex: Integer; inValue: TDesignHandles);
begin
FHandles[inIndex] := inValue;
end;
function TDesignSelector.GetSelection(inIndex: Integer): TControl;
begin
Result := Handles[inIndex].Selected;
end;
procedure TDesignSelector.SetSelection(inIndex: Integer; inValue: TControl);
begin
Handles[inIndex].Selected := inValue;
end;
function TDesignSelector.FindHandles(inValue: TControl): TDesignHandles;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
begin
Result := Handles[i];
if Result.Selected = inValue then
exit;
end;
Result := nil;
end;
function TDesignSelector.IsSelected(inValue: TControl): Boolean;
begin
Result := FindHandles(inValue) <> nil;
end;
procedure TDesignSelector.ClearSelection;
begin
//if not (csDestroying in ComponentState) then
FHandles.Clear;
end;
procedure TDesignSelector.ShowHideSelection(inShow: Boolean);
var
i: Integer;
begin
for i := 0 to Pred(Count) do
Handles[i].ShowHideHandles(inShow);
Surface.Container.Update;
end;
procedure TDesignSelector.ShowHideResizeHandles;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
with Handles[i] do
begin
Resizeable := (Count = 1);
RepaintHandles;
end;
end;
procedure TDesignSelector.AddToSelection(inValue: TControl);
var
h: TDesignHandles;
begin
if inValue = nil then
raise Exception.Create('Cannot add a nil selection.');
if not IsSelected(inValue) then
begin
h := TDesignHandles.Create(Self);
h.Container := Surface.Container;
h.Resizeable := Count = 0;
FHandles.Add(h);
h.Selected := inValue;
if (Count = 2) then
ShowHideResizeHandles;
//else
// h.UpdateHandleRects;
Surface.Messenger.DesignComponent(h.Handles[0]);
Surface.Messenger.DesignComponent(h.Handles[1]);
Surface.Messenger.DesignComponent(h.Handles[2]);
Surface.Messenger.DesignComponent(h.Handles[3]);
end;
end;
procedure TDesignSelector.RemoveFromSelection(inValue: TControl);
begin
if IsSelected(inValue) then
begin
FHandles.Remove(FindHandles(inValue));
Surface.SelectionChange;
end;
end;
function TDesignSelector.GetClientControl(inControl: TControl): TControl;
begin
if (inControl is TDesignHandle) then
Result := TDesignHandles(inControl.Owner).Selected
else
Result := inControl;
end;
procedure TDesignSelector.Update;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
Handles[i].UpdateHandles;
end;
function TDesignSelector.GetHitHandle(inX, inY: Integer): TDesignHandleId;
begin
if (Count > 0) then
Result := Handles[0].HitRect(inX, inY)
else
Result := dhNone;
end;
function TDesignSelector.GetCursor(inX, inY: Integer): TCursor;
const
cCurs: array[TDesignHandleId] of TCursor =
( crHandPoint, crSizeNWSE, crSizeNS, crSizeNESW, crSizeWE, crSizeWE,
crSizeNESW, crSizeNS, crSizeNWSE );
begin
Result := cCurs[GetHitHandle(inX, inY)]
end;
{ TDesignController }
procedure TDesignController.Action(inAction: TDesignAction);
begin
with Surface do
case inAction of
daSelectParent: SelectParent;
daDelete: DeleteComponents;
daCopy: CopyComponents;
daCut: CutComponents;
daPaste: PasteComponents;
daNudgeLeft: NudgeComponents(-1, 0);
daNudgeRight: NudgeComponents(1, 0);
daNudgeUp: NudgeComponents(0, -1);
daNudgeDown: NudgeComponents(0, 1);
daGrowWidth: GrowComponents(1, 0);
daShrinkWidth: GrowComponents(-1, 0);
daGrowHeight: GrowComponents(0, 1);
daShrinkHeight: GrowComponents(0, -1);
end;
Surface.UpdateDesigner;
end;
function TDesignController.GetDragRect: TRect;
begin
Result := FDragRect;
end;
function TDesignController.KeyDown(inKeycode: Cardinal): Boolean;
function CtrlKeys: Boolean;
begin
Result := true;
case inKeycode of
VK_LEFT: Action(daNudgeLeft);
VK_RIGHT: Action(daNudgeRight);
VK_UP: Action(daNudgeUp);
VK_DOWN: Action(daNudgeDown);
else Result := false;
end;
end;
function ShiftKeys: Boolean;
begin
Result := true;
case inKeycode of
VK_LEFT: Action(daShrinkWidth);
VK_RIGHT: Action(daGrowWidth);
VK_UP: Action(daShrinkHeight);
VK_DOWN: Action(daGrowHeight);
else Result := false;
end;
end;
function Keys: Boolean;
begin
Result := true;
case inKeycode of
VK_TAB: Surface.Selector.ShowHideSelection(false);
else Result := false;
end;
end;
begin
FKeyDownShift := Shift;
if ssCtrl in FKeyDownShift then
Result := CtrlKeys
else if ssShift in FKeyDownShift then
Result := ShiftKeys
else
Result := Keys;
end;
function TDesignController.KeyUp(inKeycode: Cardinal): Boolean;
function Keys: Boolean;
begin
Result := true;
case inKeycode of
VK_ESCAPE: Action(daSelectParent);
VK_DELETE: Action(daDelete);
else Result := false;
end;
end;
function CtrlKeys: Boolean;
begin
Result := true;
case inKeycode of
Ord('C'): Action(daCopy);
Ord('X'): Action(daCut);
Ord('V'): Action(daPaste);
else Result := false;
end;
end;
function ShiftKeys: Boolean;
begin
Result := false;
end;
begin
FKeyDownShift := FKeyDownShift + Shift;
if ssCtrl in FKeyDownShift then
Result := CtrlKeys
else if ssShift in FKeyDownShift then
Result := ShiftKeys
else
Result := Keys;
FKeyDownShift := [];
end;
function TDesignController.MouseDown(Button: TMouseButton;
X, Y: Integer): Boolean;
var
handleId: TDesignHandleId;
procedure CaptureMouse;
begin
FMouseIsDown := true;
Mouse.Capture := Surface.Container.Handle;
end;
procedure FocusSurface;
begin
if not Surface.Container.Focused and Surface.Container.CanFocus then
Surface.Container.SetFocus;
end;
procedure SelectDragMode;
begin
handleId := dhNone;
if (ssCtrl in Shift) then
// Ctrl-drag selection has highest priority
FDragMode := dmSelect
else begin
handleId := Surface.GetHitHandle(X, Y);
if (handleId <> dhNone) then
begin
FClicked := Surface.Selection[0];
FDragMode := dmResize;
end
else begin
FClicked := Surface.FindControl(X, Y);
if (FClicked = Surface.Container) or (FClicked is TDesignHandle) then
FClicked := nil;
Surface.GetAddClass;
if (Surface.AddClass <> '') then
// then object creation
FDragMode := dmCreate
else if FClicked <> nil then
// moving is last
FDragMode := dmMove
else
// select by default
FDragMode := dmSelect;
end;
end;
if FClicked = nil then
FClicked := Surface.Container;
FClicked.Parent.DisableAlign;
end;
procedure CreateMouseTool;
var
onDrag: TNotifyEvent;
begin
case FDragMode of
dmSelect, dmCreate:
begin
Surface.ClearSelection;
FMouseTool := TDesignBander.Create(Surface);
end;
//
dmMove:
begin
onDrag := nil;
if (ssShift in Shift) then
//begin
//onDrag := MouseDrag;
Surface.Selector.AddToSelection(FClicked)
//end
else begin
if not Surface.Selector.IsSelected(FClicked) then
Surface.Select(FClicked);
Surface.Selector.ShowHideSelection(false);
end;
FMouseTool := TDesignMover.Create(Surface);
//FMouseTool.OnMouseMove := onDrag;
end;
//
dmResize:
begin
if not Surface.Selector.IsSelected(FClicked) then
Surface.Select(FClicked);
FMouseTool := TDesignSizer.CreateSizer(Surface, handleId);
Surface.Selector.ShowHideSelection(false);
end;
end;
if FMouseTool <> nil then
FMouseTool.MouseDown(Button, Shift, X, Y);
end;
begin
FocusSurface;
CaptureMouse;
SelectDragMode;
CreateMouseTool;
Result := true;
end;
procedure TDesignController.MouseDrag(inSender: TObject);
begin
TDesignCustomMouseTool(inSender).OnMouseMove := nil;
Surface.Selector.ShowHideSelection(false);
end;
function TDesignController.MouseMove(X, Y: Integer): Boolean;
begin
if not FMouseIsDown then
Windows.SetCursor(Screen.Cursors[Surface.GetCursor(X, Y)])
else
if FMouseTool <> nil then
FMouseTool.MouseMove(Shift, X, Y);
Result := true;
end;
function TDesignController.MouseUp(Button: TMouseButton;
X, Y: Integer): Boolean;
procedure ReleaseMouse;
begin
FMouseIsDown := false;
Mouse.Capture := 0;
end;
procedure EnableAlign;
begin
// If the debugger breaks in during a mouse operation,
// AlignDisabled can become stuck.
// This routine is to aid debugging only.
if FClicked <> nil then
while FClicked.Parent.AlignDisabled do
FClicked.Parent.EnableAlign;
end;
procedure FinishMouseTool;
begin
if FMouseTool <> nil then
try
FMouseTool.MouseUp(Button, Shift, X, Y);
FDragRect := DesignValidateRect(FMouseTool.DragRect);
case FDragMode of
dmCreate:
begin
if FClicked <> nil then
Surface.Select(FClicked);
Surface.AddComponent;
end;
else Surface.SelectionChange;
end;
finally
FreeAndNil(FMouseTool);
end;
end;
begin
if FMouseIsDown then
begin
ReleaseMouse;
EnableAlign;
FinishMouseTool;
Surface.Selector.ShowHideSelection(true);
FClicked := nil;
end;
Result := true;
end;
{ TDesignMouseTool }
constructor TDesignMouseTool.Create(AOwner: TDesignSurface);
begin
Surface := AOwner;
end;
function TDesignMouseTool.GetMouseDelta: TPoint;
const
GridX = 4;
GridY = 4;
begin
with Result do
begin
X := FMouseLast.X - FMouseStart.X;
Dec(X, X mod GridX);
Y := FMouseLast.Y - FMouseStart.Y;
Dec(Y, Y mod GridY);
end;
end;
{ TDesignMover }
constructor TDesignMover.Create(AOwner: TDesignSurface);
begin
inherited;
SetLength(FDragRects, Surface.Count);
end;
procedure TDesignMover.CalcDragRects;
var
delta: TPoint;
i: Integer;
begin
delta := GetMouseDelta;
for i := 0 to Pred(Surface.Count) do
with Surface.Selection[i] do
begin
FDragRects[i] := BoundsRect;
OffsetRect(FDragRects[i], delta.X, delta.Y);
end;
end;
procedure TDesignMover.CalcPaintRects;
var
i: Integer;
begin
CalcDragRects;
for i := 0 to Pred(Surface.Count) do
with Surface.Selection[i] do
with Parent.ClientToScreen(Point(0, 0)) do
OffsetRect(FDragRects[i], X, Y);
end;
procedure TDesignMover.PaintDragRects;
var
i: Integer;
begin
for i := 0 to Pred(Surface.Count) do
DesignPaintRubberbandRect(FDragRects[i], psDot);
end;
procedure TDesignMover.ApplyDragRects;
var
i: Integer;
begin
if (GetMouseDelta.X <> 0) or (GetMouseDelta.Y <> 0) then
begin
CalcDragRects;
for i := 0 to Pred(Surface.Count) do
Surface.Selection[i].BoundsRect := FDragRects[i];
Surface.UpdateDesigner;
Surface.Change;
end;
end;
procedure TDesignMover.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
FMouseStart := Point(X, Y);
FMouseLast := FMouseStart;
CalcPaintRects;
PaintDragRects;
end;
procedure TDesignMover.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
PaintDragRects;
if Assigned(OnMouseMove) and ((FMouseLast.X <> X) or (FMouseLast.Y <> Y)) then
OnMouseMove(Self);
FMouseLast := Point(X, Y);
CalcPaintRects;
PaintDragRects;
end;
procedure TDesignMover.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
PaintDragRects;
FMouseLast := Point(X, Y);
ApplyDragRects;
end;
{ TDesignBander }
procedure TDesignBander.CalcDragRect;
begin
with GetMouseDelta do
begin
DragRect := Rect(0, 0, X, Y);
OffsetRect(FDragRect, FMouseStart.X, FMouseStart.Y);
end;
end;
function TDesignBander.GetClient: TControl;
begin
Result := Surface.Container;
end;
function TDesignBander.GetPaintRect: TRect;
begin
Result := FDragRect;
with GetClient.ClientToScreen(Point(0, 0)) do
OffsetRect(Result, X, Y);
end;
procedure TDesignBander.PaintDragRect;
begin
DesignPaintRubberbandRect(GetPaintRect, psDot);
end;
procedure TDesignBander.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
FMouseStart := Point(X, Y);
FMouseLast := FMouseStart;
CalcDragRect;
PaintDragRect;
end;
procedure TDesignBander.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
PaintDragRect;
FMouseLast := Point(X, Y);
CalcDragRect;
PaintDragRect;
end;
procedure TDesignBander.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
PaintDragRect;
CalcDragRect;
end;
{ TDesignSizer }
constructor TDesignSizer.CreateSizer(AOwner: TDesignSurface;
inHandle: TDesignHandleId);
begin
inherited Create(AOwner);
FHandleId := inHandle;
end;
procedure TDesignSizer.ApplyMouseDelta(X, Y: Integer);
begin
case FHandleId of
dhLeftTop, dhMiddleTop, dhRightTop: Inc(FDragRect.Top, Y);
dhLeftBottom, dhMiddleBottom, dhRightBottom: Inc(FDragRect.Bottom, Y);
end;
case FHandleId of
dhLeftTop, dhLeftMiddle, dhLeftBottom: Inc(FDragRect.Left, X);
dhRightTop, dhRightMiddle, dhRightBottom: Inc(FDragRect.Right, X);
end;
end;
procedure TDesignSizer.CalcDragRect;
begin
FDragRect := Surface.Selection[0].BoundsRect;
with GetMouseDelta do
ApplyMouseDelta(X, Y);
FDragRect := DesignValidateRect(FDragRect);
end;
function TDesignSizer.GetClient: TControl;
begin
Result := Surface.Selection[0].Parent;
end;
procedure TDesignSizer.ApplyDragRect;
begin
Surface.Selection[0].BoundsRect := FDragRect;
Surface.UpdateDesigner;
Surface.Change;
end;
procedure TDesignSizer.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
ApplyDragRect;
end;
{ TDesignDesigner }
constructor TDesignDesigner.Create(inMessenger: TDesignCustomMessenger);
begin
inherited Create(nil);
FMessenger := inMessenger;
end;
function TDesignDesigner.GetCustomForm: TCustomForm;
begin
Result := nil;
end;
function TDesignDesigner.GetIsControl: Boolean;
begin
Result := false;
end;
function TDesignDesigner.GetRoot: TComponent;
begin
Result := nil;
end;
function TDesignDesigner.IsDesignMsg(Sender: TControl;
var Message: TMessage): Boolean;
begin
Result := Messenger.IsDesignMessage(Sender, Message);
end;
procedure TDesignDesigner.Modified;
begin
//
end;
procedure TDesignDesigner.Notification(AnObject: TPersistent;
Operation: TOperation);
begin
//
end;
procedure TDesignDesigner.PaintGrid;
begin
//
end;
procedure TDesignDesigner.SetCustomForm(Value: TCustomForm);
begin
//
end;
procedure TDesignDesigner.SetIsControl(Value: Boolean);
begin
//
end;
function TDesignDesigner.UniqueName(const BaseName: string): string;
begin
//
end;
procedure TDesignDesigner.ValidateRename(AComponent: TComponent;
const CurName, NewName: string);
begin
//
end;
{ TDesignDesignerMessenger }
constructor TDesignDesignerMessenger.Create;
begin
FDesigner := TDesignDesigner.Create(Self);
end;
destructor TDesignDesignerMessenger.Destroy;
begin
if Container <> nil then
SetComponentDesigning(Container, false);
if (FDesignedForm <> nil) then
FDesignedForm.Designer := nil;
FDesigner.Free;
inherited;
end;
type
TCrackedComponent = class(TComponent)
end;
procedure TDesignDesignerMessenger.SetComponentDesigning(inComponent: TComponent;
inDesigning: Boolean);
begin
TCrackedComponent(inComponent).SetDesigning(inDesigning);
end;
procedure TDesignDesignerMessenger.UndesignComponent(inComponent: TComponent);
begin
SetComponentDesigning(inComponent, false);
end;
procedure TDesignDesignerMessenger.DesignComponent(inComponent: TComponent);
begin
SetComponentDesigning(inComponent, true);
end;
procedure TDesignDesignerMessenger.SetContainer(inValue: TWinControl);
function FindParentForm: TCustomForm;
var
p: TWinControl;
begin
p := Container;
while (p.Parent <> nil) do
p := p.Parent;
if not (p is TCustomForm) then
raise Exception.Create(ClassName + ': Oldest ancestor of Container must be a form.');
Result := TCustomForm(p);
end;
begin
inherited;
if (Container <> nil) then
begin
FDesignedForm := FindParentForm;
FDesignedForm.Designer := FDesigner;
DesignChildren(Container);
end;
end;
{ TDesignMessageHookList }
constructor TDesignMessageHookList.Create(inUser: TDesignCustomMessenger);
begin
inherited Create(nil);
FUser := inUser;
FHooks := TObjectList.Create;
FHooks.OwnsObjects := true;
end;
destructor TDesignMessageHookList.Destroy;
begin
FHooks.Free;
inherited;
end;
procedure TDesignMessageHookList.Clear;
begin
FHooks.Clear;
end;
procedure TDesignMessageHookList.Hook(inClient: TWinControl);
begin
inClient.FreeNotification(Self);
FHooks.Add(TDesignMessageHook.Create(FUser, inClient));
end;
procedure TDesignMessageHookList.Unhook(inComponent: TComponent);
var
i: Integer;
begin
for i := 0 to Pred(FHooks.Count) do
if TDesignMessageHook(FHooks[i]).Client = inComponent then
begin
FHooks.Delete(i);
break;
end;
end;
procedure TDesignMessageHookList.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
Unhook(AComponent);
end;
{ TDesignWinControlHookMessenger }
constructor TDesignWinControlHookMessenger.Create;
begin
FHooks := TDesignMessageHookList.Create(Self);
end;
destructor TDesignWinControlHookMessenger.Destroy;
begin
FHooks.Free;
inherited;
end;
procedure TDesignWinControlHookMessenger.Clear;
begin
FHooks.Clear;
end;
procedure TDesignWinControlHookMessenger.DesignComponent(inComponent: TComponent);
begin
if inComponent is TWinControl then
HookWinControl(TWinControl(inComponent));
end;
procedure TDesignWinControlHookMessenger.HookWinControl(inWinControl: TWinControl);
begin
FHooks.Hook(inWinControl);
DesignChildren(inWinControl);
end;
procedure TDesignWinControlHookMessenger.SetContainer(inValue: TWinControl);
begin
inherited;
if (Container <> nil) then
DesignChildren(Container);
end;
initialization
finalization
FreeShadedBits;
end.
|
unit ibSHDDLCommentatorEditors;
interface
uses
SysUtils, Classes, DesignIntf, TypInfo,
SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors;
type
// -> Property Editors
TibSHDDLCommentatorModePropEditor = class(TibBTPropertyEditor)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(AValues: TStrings); override;
procedure SetValue(const Value: string); override;
end;
implementation
uses
ibSHConsts, ibSHValues;
{ TibSHDDLCommentatorModePropEditor }
function TibSHDDLCommentatorModePropEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
procedure TibSHDDLCommentatorModePropEditor.GetValues(AValues: TStrings);
begin
AValues.Text := FormatProps(CommentModes);
end;
procedure TibSHDDLCommentatorModePropEditor.SetValue(const Value: string);
begin
if Assigned(Designer) and Designer.CheckPropValue(Value, FormatProps(CommentModes)) then
inherited SetStrValue(Value);
end;
end.
|
unit uFrmCreateJPEGSteno;
interface
uses
Windows,
Messages,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.Menus,
Vcl.Themes,
Vcl.Imaging.jpeg,
Vcl.PlatformDefaultStyleActnCtrls,
Vcl.ActnPopup,
Dmitry.Utils.Files,
Dmitry.Controls.Base,
Dmitry.Controls.WebLink,
Dmitry.Controls.WatermarkedEdit,
Dmitry.Controls.LoadingSign,
CCR.Exif,
DBCMenu,
UnitDBFileDialogs,
uFrameWizardBase,
uDBUtils,
uMemory,
uJpegUtils,
uShellIntegration,
uConstants,
uCryptUtils,
uDBBaseTypes,
uDBContext,
uDBEntities,
uDBManager,
uAssociations,
uStenography,
uTranslateUtils,
uPortableDeviceUtils,
uProgramStatInfo,
uFormInterfaces;
type
TFrmCreateJPEGSteno = class(TFrameWizardBase)
ImJpegFile: TImage;
LbJpegFileInfo: TLabel;
LbJpegFileSize: TLabel;
LbImageSize: TLabel;
EdDataFileName: TWatermarkedEdit;
LbSelectFile: TLabel;
BtnChooseFile: TButton;
LbFileSize: TLabel;
LbResultImageSize: TLabel;
GbOptions: TGroupBox;
CbEncryptdata: TCheckBox;
LbPassword: TLabel;
EdPassword: TWatermarkedEdit;
LbPasswordConfirm: TLabel;
EdPasswordConfirm: TWatermarkedEdit;
CbIncludeCRC: TCheckBox;
WblMethod: TWebLink;
PmCryptMethod: TPopupActionBar;
CbConvertImage: TCheckBox;
WblJpegOptions: TWebLink;
LsImage: TLoadingSign;
procedure ImJpegFileContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
procedure CbEncryptdataClick(Sender: TObject);
procedure BtnChooseFileClick(Sender: TObject);
procedure WblJpegOptionsClick(Sender: TObject);
procedure CbConvertImageClick(Sender: TObject);
private
{ Private declarations }
FImagePassword: string;
FImageFileSize: Int64;
FDataFileSize: Int64;
FMethodChanger: TPasswordMethodChanger;
FBitmapImage: TBitmap;
function GetFileName: string;
procedure CountResultFileSize;
procedure LoadOtherImageHandler(Sender: TObject);
procedure ErrorLoadingImageHandler(FileName: string);
procedure SetPreviewLoadingImageHandler(Width, Height: Integer; var Bitmap: TBitmap; Preview: TBitmap; Password: string);
protected
{ Protected declarations }
procedure LoadLanguage; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure Init(Manager: TWizardManagerBase; FirstInitialization: Boolean); override;
procedure Unload; override;
function IsFinal: Boolean; override;
function ValidateStep(Silent: Boolean): Boolean; override;
procedure Execute; override;
property ImageFileName: string read GetFileName;
end;
implementation
uses
uStenoLoadImageThread,
uFrmSteganographyLanding;
{$R *.dfm}
{ TFrmCreateJPEGSteno }
procedure TFrmCreateJPEGSteno.BtnChooseFileClick(Sender: TObject);
var
OpenDialog: DBOpenDialog;
begin
OpenDialog := DBOpenDialog.Create;
try
OpenDialog.Filter := L('All files (*.*)|*.*');
OpenDialog.FilterIndex := 1;
if OpenDialog.Execute then
begin
EdDataFileName.Text := OpenDialog.FileName;
FDataFileSize := GetFileSize(OpenDialog.FileName);
CountResultFileSize;
end;
finally
F(OpenDialog);
end;
end;
procedure TFrmCreateJPEGSteno.CbConvertImageClick(Sender: TObject);
begin
inherited;
WblJpegOptions.Enabled := CbConvertImage.Checked;
end;
procedure TFrmCreateJPEGSteno.CbEncryptdataClick(Sender: TObject);
begin
inherited;
EdPassword.Enabled := CbEncryptdata.Checked;
EdPasswordConfirm.Enabled := CbEncryptdata.Checked;
WblMethod.Enabled := CbEncryptdata.Checked;
end;
procedure TFrmCreateJPEGSteno.CountResultFileSize;
begin
LbFileSize.Caption := Format(L('File size: %s'), [SizeInText(FDataFileSize)]);
LbResultImageSize.Caption := Format(L('Result file size: %s'), [SizeInText(FImageFileSize + FDataFileSize)]);
end;
constructor TFrmCreateJPEGSteno.Create(AOwner: TComponent);
begin
inherited;
FBitmapImage := nil;
BtnChooseFile.Height := EdDataFileName.Height;
end;
procedure TFrmCreateJPEGSteno.ErrorLoadingImageHandler(FileName: string);
begin
IsBusy := False;
Changed;
Manager.PrevStep;
end;
procedure TFrmCreateJPEGSteno.Execute;
var
SavePictureDialog: DBSavePictureDialog;
J: TJpegImage;
EXIFSection: TExifData;
MS: TMemoryStream;
begin
inherited;
//statistics
ProgramStatistics.StegoUsed;
SavePictureDialog := DBSavePictureDialog.Create;
try
SavePictureDialog.Filter := TFileAssociations.Instance.GetFilter('.jpg', True, False);
SavePictureDialog.FilterIndex := 1;
SavePictureDialog.SetFileName(ChangeFileExt(ImageFileName, '.jpg'));
if SavePictureDialog.Execute then
begin
if TFileAssociations.Instance.GetGraphicClass(ExtractFileExt(SavePictureDialog.FileName)) <> TJPEGImage then
SavePictureDialog.SetFileName(SavePictureDialog.FileName + '.jpg');
if CbConvertImage.Checked then
begin
J := TJpegImage.Create;
try
J.Assign(FBitmapImage);
JpegOptionsForm.Execute('JpegSteganography');
SetJPEGGraphicSaveOptions('JpegSteganography', J);
J.Compress;
EXIFSection := TExifData.Create;
try
EXIFSection.LoadFromGraphic(ImageFileName);
MS := TMemoryStream.Create;
try
J.SaveToStream(MS);
MS.Seek(0, soFromBeginning);
if not CbEncryptdata.Checked then
begin
MessageBoxDB(Handle, L('Information in the file will not be encrypted!'), L('Information'), TD_BUTTON_OK, TD_ICON_WARNING);
CreateJPEGStenoEx(EdDataFileName.Text, SavePictureDialog.FileName, MS, '');
end else
CreateJPEGStenoEx(EdDataFileName.Text, SavePictureDialog.FileName, MS, EdPassword.Text);
if not EXIFSection.Empty then
EXIFSection.SaveToGraphic(SavePictureDialog.FileName);
IsStepComplete := True;
Changed;
finally
F(MS);
end;
finally
F(EXIFSection);
end;
finally
F(J);
end;
end else
begin
if not CbEncryptdata.Checked then
begin
MessageBoxDB(Handle, L('Information in the file will not be encrypted!'), L('Information'), TD_BUTTON_OK, TD_ICON_WARNING);
CreateJPEGSteno(EdDataFileName.Text, SavePictureDialog.FileName, ImageFileName, '');
end else
CreateJPEGSteno(EdDataFileName.Text, SavePictureDialog.FileName, ImageFileName, EdPassword.Text);
IsStepComplete := True;
Changed;
end;
end;
finally
F(SavePictureDialog);
end;
end;
function TFrmCreateJPEGSteno.GetFileName: string;
begin
Result := TFrmSteganographyLanding(Manager.GetStepByType(TFrmSteganographyLanding)).ImageFileName;
end;
procedure TFrmCreateJPEGSteno.ImJpegFileContextPopup(Sender: TObject;
MousePos: TPoint; var Handled: Boolean);
var
Info: TMediaItemCollection;
Rec: TMediaItem;
Menus: TArMenuItem;
Context: IDBContext;
MediaRepository: IMediaRepository;
begin
Info := TMediaItemCollection.Create;
try
Rec := TMediaItem.CreateFromFile(ImageFileName);
Context := DBManager.DBContext;
MediaRepository := Context.Media;
MediaRepository.UpdateMediaFromDB(Rec, False);
Rec.Selected := True;
Info.IsPlusMenu := False;
Info.IsListItem := False;
Info.Add(Rec);
Setlength(Menus, 1);
Menus[0] := TMenuItem.Create(nil);
Menus[0].Caption := L('Load other image');
Menus[0].ImageIndex := DB_IC_LOADFROMFILE;
Menus[0].OnClick := LoadOtherImageHandler;
TDBPopupMenu.Instance.ExecutePlus(Manager.Owner, ImJpegFile.ClientToScreen(MousePos).X, ImJpegFile.ClientToScreen(MousePos).Y, Info,
Menus);
finally
F(Info);
end;
end;
procedure TFrmCreateJPEGSteno.Init(Manager: TWizardManagerBase;
FirstInitialization: Boolean);
var
FPassIcon: HIcon;
GraphicClass: TGraphicClass;
begin
inherited;
FDataFileSize := 0;
if FirstInitialization then
begin
FMethodChanger := TPasswordMethodChanger.Create(WblMethod, PmCryptMethod);
FPassIcon := LoadIcon(HInstance, PChar('PASSWORD'));
try
WblMethod.LoadFromHIcon(FPassIcon);
finally
DestroyIcon(FPassIcon);
end;
if StyleServices.Enabled then
begin
ParentBackground := True;
ParentColor := True;
end;
end else
begin
if not IsDevicePath(ImageFileName) then
FImageFileSize := GetFileSize(ImageFileName)
else
FImageFileSize := GetDeviceItemSize(ImageFileName);
LbJpegFileSize.Caption := Format(L('File size: %s'), [SizeInText(FImageFileSize)]);
F(FBitmapImage);
if ImJpegFile.Picture.Graphic = nil then
LsImage.Show;
TStenoLoadImageThread.Create(Manager.Owner, ImageFileName, Color,
ErrorLoadingImageHandler, SetPreviewLoadingImageHandler);
GraphicClass := TFileAssociations.Instance.GetGraphicClass(ExtractFileExt(ImageFileName));
if GraphicClass = TJPEGImage then
begin
CbConvertImage.Checked := False;
CbConvertImage.Enabled := True;
end else
begin
CbConvertImage.Checked := True;
CbConvertImage.Enabled := False;
end;
CbConvertImageClick(Self);
IsBusy := True;
Changed;
end;
end;
function TFrmCreateJPEGSteno.IsFinal: Boolean;
begin
Result := True;
end;
procedure TFrmCreateJPEGSteno.LoadLanguage;
begin
inherited;
LbJpegFileInfo.Caption := L('Original image preview') + ':';
GbOptions.Caption := L('Options');
CbIncludeCRC.Caption := L('Add checksum (CRC)');
CbEncryptdata.Caption := L('Encrypt data');
LbPassword.Caption := L('Password') + ':';
EdPassword.WatermarkText := L('Password');
LbPasswordConfirm.Caption := L('Password confirm') + ':';
EdPasswordConfirm.WatermarkText := L('Password confirm');
LbSelectFile.Caption := L('File to hide') + ':';
EdDataFileName.WatermarkText := L('Please select a file');
WblJpegOptions.Text := L('JPEG Options');
CbConvertImage.Caption := L('Convert image');
CountResultFileSize;
end;
procedure TFrmCreateJPEGSteno.LoadOtherImageHandler(Sender: TObject);
var
OpenPictureDialog: DBOpenPictureDialog;
begin
OpenPictureDialog := DBOpenPictureDialog.Create;
try
OpenPictureDialog.Filter := TFileAssociations.Instance.FullFilter;
OpenPictureDialog.FilterIndex := 1;
if OpenPictureDialog.Execute then
begin
TFrmSteganographyLanding(Manager.GetStepByType(TFrmSteganographyLanding)).ImageFileName := OpenPictureDialog.FileName;
Init(Manager, False);
end;
finally
F(OpenPictureDialog);
end;
end;
procedure TFrmCreateJPEGSteno.SetPreviewLoadingImageHandler(Width,
Height: Integer; var Bitmap: TBitmap; Preview: TBitmap; Password: string);
begin
F(FBitmapImage);
FBitmapImage := Bitmap;
Bitmap := nil;
ImJpegFile.Picture.Graphic := Preview;
LbImageSize.Caption := Format(L('Image size: %dx%d px.'), [Width, Height]);
LbImageSize.Show;
FImagePassword := Password;
LsImage.Hide;
IsBusy := False;
Changed;
end;
procedure TFrmCreateJPEGSteno.Unload;
begin
inherited;
F(FMethodChanger);
F(FBitmapImage);
end;
function TFrmCreateJPEGSteno.ValidateStep(Silent: Boolean): Boolean;
begin
Result := FileExistsSafe(EdDataFileName.Text) and (ImJpegFile.Picture.Graphic <> nil);
if CbEncryptdata.Checked then
begin
Result := Result and (EdPassword.Text = EdPasswordConfirm.Text) and
(EdPassword.Text <> '');
end;
if not Silent and (ImJpegFile.Picture.Graphic = nil) then
LoadOtherImageHandler(Self)
else if not Silent and not FileExistsSafe(EdDataFileName.Text) then
BtnChooseFileClick(Self);
end;
procedure TFrmCreateJPEGSteno.WblJpegOptionsClick(Sender: TObject);
begin
inherited;
JpegOptionsForm.Execute('JpegSteganography');
end;
end.
|
unit Orcamento.Controller;
interface
uses Orcamento.Controller.interf, Orcamento.Model.interf,
OrcamentoItens.Model.interf, TESTORCAMENTOITENS.Entidade.Model,
Generics.Collections, TESTORCAMENTO.Entidade.Model, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FBDef,
FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.IBBase, FireDAC.Phys.FB,
Data.DB, FireDAC.Comp.Client, System.SysUtils, OrcamentoFornecedores.Model.Interf;
type
TOrcamentoController = class(TInterfacedObject, IOrcamentoController)
private
FOrcamentoModel: IOrcamentoModel;
FOrcamentoItensModel: IOrcamentoItensModel;
FOrcamentoFornecedoresModel: IOrcamentoFornecedoresModel;
FRegistro: TTESTORCAMENTO;
FItens: TList<TOrcamentoItens>;
FFornecedores: TList<TOrcamentoFornecedores>;
FQueryItens: TFDQuery;
FQueryFornecedores: TFDQuery;
public
constructor Create;
destructor Destroy; override;
class function New: IOrcamentoController;
function Incluir: IOrcamentoOperacaoIncluirController;
function Alterar: IOrcamentoOperacaoAlterarController;
function Excluir: IOrcamentoOperacaoExcluirController;
function Duplicar: IOrcamentoOperacaoDuplicarController;
function localizar(AValue: string): IOrcamentoController;
function idOrcamento: string;
function descricao: string;
function itens: TList<TOrcamentoItens>;
procedure AddItem(AValue: TOrcamentoItens);
function fornecedores: TList<TOrcamentoFornecedores>;
procedure AddFornecedor(AValue: TOrcamentoFornecedores);
procedure removerTodosOsItens;
procedure removerTodosOsFornecedores;
end;
implementation
{ TOrcamentoController }
uses FacadeController, FacadeModel, OrcamentoOperacaoIncluir.Controller,
OrcamentoOperacaoAlterar.Controller, OrcamentoOperacaoExcluir.Controller,
OrcamentoOperacaoDuplicar.Controller;
procedure TOrcamentoController.AddFornecedor(AValue: TOrcamentoFornecedores);
begin
FFornecedores.Add(AValue);
end;
procedure TOrcamentoController.AddItem(AValue: TOrcamentoItens);
begin
FItens.Add(AValue);
end;
function TOrcamentoController.Alterar: IOrcamentoOperacaoAlterarController;
begin
Result := TOrcamentoOperacaoAlterarController.New
.orcamentoModel(FOrcamentoModel)
.orcamentoItensModel(FOrcamentoItensModel)
.orcamentoFornecedoresModel(FOrcamentoFornecedoresModel)
.orcamentoSelecionado(FRegistro)
.itens(FItens)
.fornecedores(FFornecedores)
end;
constructor TOrcamentoController.Create;
begin
FOrcamentoModel := TFacadeModel.New.ModulosFacadeModel.
estoqueFactoryModel.Orcamento;
FOrcamentoItensModel := TFacadeModel.New.ModulosFacadeModel.
estoqueFactoryModel.OrcamentoItens;
FOrcamentoFornecedoresModel := TFacadeModel.New.ModulosFacadeModel.
estoqueFactoryModel.orcamentoFornecedores;
FItens := TList<TOrcamentoItens>.Create;
FFornecedores := TList<TOrcamentoFornecedores>.Create;
end;
function TOrcamentoController.descricao: string;
begin
Result := FRegistro.descricao;
end;
destructor TOrcamentoController.Destroy;
begin
FItens.Free;
inherited;
end;
function TOrcamentoController.Duplicar: IOrcamentoOperacaoDuplicarController;
begin
Result := TOrcamentoOperacaoDuplicarController.New
.orcamentoModel(FOrcamentoModel)
.orcamentoItensModel(FOrcamentoItensModel)
.orcamentoFornecedoresModel(FOrcamentoFornecedoresModel)
.itens(FItens)
.fornecedores(FFornecedores)
end;
function TOrcamentoController.Excluir: IOrcamentoOperacaoExcluirController;
begin
Result := TOrcamentoOperacaoExcluirController.New
.orcamentoModel(FOrcamentoModel)
.orcamentoItensModel(FOrcamentoItensModel)
.orcamentoSelecionado(FRegistro)
end;
function TOrcamentoController.fornecedores: TList<TOrcamentoFornecedores>;
var VFornecedor: TOrcamentoFornecedores;
begin
FFornecedores.Clear;
FQueryFornecedores.First;
while not(FQueryFornecedores.Eof) do
begin
VFornecedor.codigo := FQueryFornecedores.FieldByName('CODIGO').AsString;
FFornecedores.Add(VFornecedor);
FQueryFornecedores.Next;
end;
Result := FFornecedores;
end;
function TOrcamentoController.idOrcamento: string;
begin
Result := IntToStr(FRegistro.idOrcamento);
end;
function TOrcamentoController.Incluir: IOrcamentoOperacaoIncluirController;
begin
Result := TOrcamentoOperacaoIncluirController.New
.orcamentoModel(FOrcamentoModel)
.orcamentoItensModel(FOrcamentoItensModel)
.orcamentoFornecedoresModel(FOrcamentoFornecedoresModel)
.itens(FItens)
.fornecedores(FFornecedores)
end;
function TOrcamentoController.itens: TList<TOrcamentoItens>;
var VItem: TOrcamentoItens;
begin
FItens.Clear;
FQueryItens.First;
while not(FQueryItens.Eof) do
begin
VItem.codigo := FQueryItens.FieldByName('CODIGO').AsString;
VItem.qtde := FQueryItens.FieldByName('QTDE').AsFloat;
FItens.Add(VItem);
FQueryItens.Next;
end;
Result := FItens;
end;
function TOrcamentoController.localizar(AValue: string): IOrcamentoController;
begin
Result := Self;
FRegistro := FOrcamentoModel.DAO.FindWhere('CODIGO=' + QuotedStr(AValue),
'DATA_CADASTRO').Items[0];
FQueryItens := FOrcamentoModel.queryItensOrcamento(FRegistro.CODIGO);
FQueryFornecedores := FOrcamentoModel.queryFornecedoresOrcamento(FRegistro.CODIGO);
end;
class function TOrcamentoController.New: IOrcamentoController;
begin
Result := Self.Create;
end;
procedure TOrcamentoController.removerTodosOsFornecedores;
begin
FFornecedores.Clear;
end;
procedure TOrcamentoController.removerTodosOsItens;
begin
FItens.Clear;
end;
end.
|
unit GLDUtils;
interface
uses
GL, Classes, GLDTypes, GLDConst, GLDClasses, GLDObjects, GLDRepository;
procedure GLDURealloc(var WordArray: TGLDWordArrayData; Size: GLuint); overload;
procedure GLDURealloc(var Vector3fArrayData: TGLDVector3fArrayData; Size: GLuint); overload;
function GLDUGetOwnerRepository(AObject: TGLDVisualObject): TGLDRepository;
implementation
procedure GLDURealloc(var WordArray: TGLDWordArrayData; Size: GLuint); overload;
begin
if Size > GLD_MAX_LISTITEMS then Exit;
ReallocMem(WordArray.Data, Size * SizeOf(GLushort));
WordArray.Count := Size;
end;
procedure GLDURealloc(var Vector3fArrayData: TGLDVector3fArrayData; Size: GLuint); overload;
begin
if Size > GLD_MAX_LISTITEMS then Exit;
ReallocMem(Vector3fArrayData.Data, Size * SizeOf(TGLDVector3f));
Vector3fArrayData.Count := Size;
end;
function GLDUGetOwnerRepository(AObject: TGLDVisualObject): TGLDRepository;
var
AOwner: TPersistent;
begin
Result := nil;
if AObject = nil then Exit;
AOwner := AObject;
repeat
if AOwner is TGLDSysClass then
AOwner := TGLDSysClass(AOwner).Owner else
if AOwner is TGLDSysComponent then
AOwner := TGLDSysComponent(AOwner).Owner;
if AOwner = nil then Exit;
until (AOwner is TGLDRepository) or (AOwner = nil);
Result := TGLDRepository(AOwner);
end;
end.
|
unit Qstream;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses Classes;
const
HFILE_ERROR = -1;
stCreate = 1;
stOpenExclusive = 2;
stOpenReadNonExclusive = 3;
{ TQStream error codes }
stOk = 0;
stError = -1;
stInitError = -2;
stReadError = -3;
stWriteError = -4;
stSeekError = -5;
type
TQBufStream = object
Status : Integer;
{$ifdef mswindows}
Handle : Integer;
{$else}
Stream : TFileStream;
{$endif}
StreamMode : Integer;
CurrentPos : longint;
CurrentSize: longint;
CheckReading: boolean; {pokud true, bude se kontrolovat seek and read, zda
nejde mimo soubor - ale soubor se neuzavira}
FileName : array [0..255] of char;
constructor Init (aFileName: PChar; aStreamMode: Integer);
destructor Done;
procedure Error (Code: Integer);
procedure ReadExt (var Buf; Count: longint; var WasRead: longint);
procedure Read (var Buf; Count: longint);
procedure Write (var Buf; Count: longint);
function GetPos : Longint;
function GetSize: Longint;
procedure Seek (Pos: Longint);
procedure SeekToEnd;
procedure Flush;
function Eof : boolean;
private
procedure StreamOpen;
procedure StreamClose;
end;
{==================================================================}
implementation
uses
SysUtils, Qexcept;
{$R-}
const
stStreamClosed = 0;
lsFileAccessError = 'File access error.';
lsFileCreationError = 'File creation or open error.';
lsFileReadingError = 'File reading error.';
lsFileWritingError = 'File writing error.';
lsFileSeekingError = 'File seeking error.';
lsFileError = 'File error: ';
lsDBaseStructError = 'Error in database structure found. Close the database and call Repair from the File menu. ';
{------------------------------------------------------------------}
procedure TQBufStream.Error(Code: Integer);
var
ErrorMsg: ShortString;
SaveStreamMode : Integer;
begin
Status := Code;
case Status of
stOk : exit;
stError : ErrorMsg := lsFileAccessError;
stInitError : ErrorMsg := lsFileCreationError;
stReadError : ErrorMsg := lsFileReadingError;
stWriteError: ErrorMsg := lsFileWritingError;
stSeekError : ErrorMsg := lsFileSeekingError;
else ErrorMsg := lsFileError + IntToStr(Status);
end;
SaveStreamMode := StreamMode;
StreamMode := stStreamClosed;
StreamClose;
if SaveStreamMode = stOpenReadNonExclusive
then raise EQDirNormalException.Create(ErrorMsg)
else raise EQDirFatalException.Create(ErrorMsg);
end;
{------------------------------------------------------------------}
procedure TQBufStream.StreamOpen;
var
LastError: longint;
szBuffer: array[0..200] of char;
begin
{$ifndef mswindows}
case StreamMode of
stCreate:
begin
Stream := TFileStream.Create(FileName, fmCreate);
end;
stOpenExclusive:
begin
Stream := TFileStream.Create(FileName, fmOpenReadWrite or fmShareExclusive);
end;
stOpenReadNonExclusive:
begin
Stream := TFileStream.Create(FileName, fmOpenRead);
end;
end;
CurrentSize := Stream.Size;
if CurrentSize = $FFFFFFFF then Error(stSeekError);
CurrentPos := Stream.Seek(0,0);
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$else}
{$ifdef WIN32}
case StreamMode of
stCreate:
Handle := CreateFile(FileName, GENERIC_READ or GENERIC_WRITE,
0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
stOpenExclusive:
Handle := CreateFile(FileName, GENERIC_READ or GENERIC_WRITE,
0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
stOpenReadNonExclusive:
Handle := CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ,
nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
end;
if Handle = INVALID_HANDLE_VALUE
then
begin
{
LastError := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, LastError,
0, szBuffer, 200, nil);
}
Error(stInitError);
end
else
begin
CurrentSize := SetFilePointer(Handle, 0, nil, FILE_END);
if CurrentSize = $FFFFFFFF then Error(stSeekError);
CurrentPos := SetFilePointer(Handle, 0, nil, FILE_BEGIN);
if CurrentPos = $FFFFFFFF then Error(stSeekError);
end;
{$else}
case StreamMode of
stCreate:
Handle := _lcreat(FileName, 0);
stOpenExclusive:
Handle := _lopen(FileName, OF_READWRITE or OF_SHARE_EXCLUSIVE);
stOpenReadNonExclusive:
Handle := _lopen(FileName, OF_READ or OF_SHARE_DENY_NONE);
end;
if Handle = HFILE_ERROR
then
Error(stInitError)
else
begin
CurrentSize := _llseek(Handle, 0, 2);
CurrentPos := _llseek(Handle, 0, 0);
end;
{$endif}
{$endif}
end;
{------------------------------------------------------------------}
procedure TQBufStream.StreamClose;
begin
{$ifdef mswindows}
{$ifdef WIN32}
if Handle <> INVALID_HANDLE_VALUE then FileClose(Handle);{ *Převedeno z CloseHandle* }
Handle := INVALID_HANDLE_VALUE;
{$else}
if Handle <> HFILE_ERROR then _lclose(Handle);
Handle := HFILE_ERROR;
{$endif}
{$else}
if Stream <> nil then
try
Stream.Free;
except
end;
{$endif}
end;
{------------------------------------------------------------------}
constructor TQBufStream.Init(aFileName: PChar; aStreamMode: Integer);
begin
Status := stOK;
StreamMode := aStreamMode;
CurrentPos := 0;
CurrentSize := 0;
CheckReading := false;
StrCopy(FileName, aFileName);
StreamOpen;
end;
{------------------------------------------------------------------}
destructor TQBufStream.Done;
begin
if StreamMode = stStreamClosed then exit;
StreamClose;
StreamMode := stStreamClosed;
end;
{------------------------------------------------------------------}
procedure TQBufStream.Flush;
begin
if StreamMode = stStreamClosed then exit;
{$ifdef mswindows}
{$ifdef WIN32}
FlushFileBuffers(Handle);
{$else}
StreamClose;
StreamOpen;
{$endif}
{$endif}
end;
{------------------------------------------------------------------}
function TQBufStream.GetPos: Longint;
begin
Result := 0;
if StreamMode = stStreamClosed then exit;
Result := CurrentPos;
end;
{------------------------------------------------------------------}
function TQBufStream.GetSize: Longint;
begin
Result := 0;
if StreamMode = stStreamClosed then exit;
Result := CurrentSize;
end;
{------------------------------------------------------------------}
function TQBufStream.Eof: boolean;
begin
Result := true;
if StreamMode = stStreamClosed then exit;
Result := CurrentPos >= CurrentSize;
end;
{------------------------------------------------------------------}
procedure TQBufStream.Seek(Pos: Longint);
begin
{pokud kontrola cteni, pak chyba nezpusobi zavreni databaze}
if CheckReading then
if (Pos < 0) or (Pos > CurrentSize) then
raise EQDirDBaseStructException.Create(lsDBaseStructError + ' (001)');
if StreamMode = stStreamClosed then exit;
{$ifdef mswindows}
{$ifdef WIN32}
CurrentPos := SetFilePointer(Handle, Pos, nil, FILE_BEGIN);
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$else}
CurrentPos := _llseek(Handle, Pos, 0);
if CurrentPos = HFILE_ERROR then Error(stSeekError);
{$endif}
{$else}
///DistanceHigh := 0;
Stream.Seek(pos,0);
CurrentPos := Stream.Position;
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$endif}
end;
{------------------------------------------------------------------}
procedure TQBufStream.SeekToEnd;
begin
if StreamMode = stStreamClosed then exit;
{$ifdef mswindows}
{$ifdef WIN32}
if CurrentPos <> CurrentSize then
CurrentPos := SetFilePointer(Handle, 0, nil, FILE_END);
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$else}
if CurrentPos <> CurrentSize then
CurrentPos := _llseek(Handle, 0, 2);
if CurrentPos = HFILE_ERROR then Error(stSeekError);
{$endif}
{$else}
if CurrentPos <> CurrentSize then
begin
Stream.Seek(Stream.Size,0);
CurrentPos := Stream.Position;
end;
if CurrentPos = $FFFFFFFF then Error(stSeekError);
{$endif}
end;
{------------------------------------------------------------------}
procedure TQBufStream.ReadExt(var Buf; Count: longint; var WasRead: longint);
begin
{pokud kontrola cteni, pak chyba nezpusobi zavreni databaze}
if CheckReading then
if (CurrentPos+Count) > CurrentSize then
raise EQDirDBaseStructException.Create(lsDBaseStructError + ' (002)');
if StreamMode = stStreamClosed then Error(stReadError);
{$ifdef mswindows}
{$ifdef WIN32}
if not ReadFile(Handle, Buf, Count, DWORD(WasRead), nil) then
Error(stReadError);
{$else}
WasRead := _lread(Handle, @Buf, Count);
if Integer(WasRead) = HFILE_ERROR then Error(stReadError);
{$endif}
{$else}
WasRead := Stream.Read(Buf,Count);
{$endif}
inc(CurrentPos, WasRead);
end;
{------------------------------------------------------------------}
procedure TQBufStream.Read(var Buf; Count: longint);
var
WasRead: longint;
begin
ReadExt(Buf, Count, WasRead);
if WasRead <> Count then Error(stReadError);
end;
{------------------------------------------------------------------}
procedure TQBufStream.Write(var Buf; Count: longint);
var
WasWritten: longint;
begin
if (StreamMode = stStreamClosed) or
(StreamMode = stOpenReadNonExclusive) then exit;
{$ifdef mswindows}
{$ifdef WIN32}
if not WriteFile(Handle, Buf, Count, DWORD(WasWritten), nil) then
Error(stWriteError);
if WasWritten <> Count then Error(stWriteError);
{$else}
WasWritten := _lwrite(Handle, @Buf, Count);
if Integer(WasWritten) = HFILE_ERROR then Error(stWriteError);
if WasWritten <> Count then Error(stWriteError);
{$endif}
{$else}
WasWritten := Stream.Write(buf,Count);
if WasWritten <> Count then Error(stWriteError);
{$endif}
inc(CurrentPos, WasWritten);
if CurrentPos > CurrentSize then CurrentSize := CurrentPos;
end;
{------------------------------------------------------------------}
end.
|
{ *************************************************************************** }
{ }
{ Audio Tools Library (Freeware) }
{ Class TMPEGaudio - for manipulating with MPEG audio file information }
{ }
{ Uses: }
{ - Class TID3v1 }
{ - Class TID3v2 }
{ }
{ Copyright (c) 2001 by Jurgen Faul }
{ E-mail: jfaul@gmx.de }
{ http://jfaul.de/atl }
{ }
{ Version 1.0 (31 August 2001) }
{ - Support for MPEG audio (versions 1, 2, 2.5, layers I, II, III) }
{ - Support for Xing & FhG VBR }
{ - Ability to guess audio encoder (Xing, FhG, LAME, Blade, GoGo, Shine) }
{ - Class TID3v1: reading & writing support for ID3v1.x tags }
{ - Class TID3v2: reading support for ID3v2.3.x tags }
{ }
{ 11 mar 2007 - Add ReadFromStream mathod by DelphiFlash.com }
{ 10 mar 2008 - some bugs fixed }
{ }
{ *************************************************************************** }
unit MPEGaudio;
interface
uses
Windows, Classes, SysUtils, Contnrs;
const
{ Table for bit rates }
MPEG_BIT_RATE: array [0..3, 0..3, 0..15] of Word =
(
{ For MPEG 2.5 }
((0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0),
(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0),
(0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0)),
{ Reserved }
((0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)),
{ For MPEG 2 }
((0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0),
(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0),
(0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0)),
{ For MPEG 1 }
((0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0),
(0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0),
(0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0))
);
{ Sample rate codes }
MPEG_SAMPLE_RATE_LEVEL_3 = 0; { Level 3 }
MPEG_SAMPLE_RATE_LEVEL_2 = 1; { Level 2 }
MPEG_SAMPLE_RATE_LEVEL_1 = 2; { Level 1 }
MPEG_SAMPLE_RATE_UNKNOWN = 3; { Unknown value }
{ Table for sample rates }
MPEG_SAMPLE_RATE: array [0..3, 0..3] of Word =
(
(11025, 12000, 8000, 0), { For MPEG 2.5 }
(0, 0, 0, 0), { Reserved }
(22050, 24000, 16000, 0), { For MPEG 2 }
(44100, 48000, 32000, 0) { For MPEG 1 }
);
{ VBR header ID for Xing/FhG }
VBR_ID_XING = 'Xing'; { Xing VBR ID }
VBR_ID_FHG = 'VBRI'; { FhG VBR ID }
VBR_ID_INFO = 'Info';
{ MPEG version codes }
MPEG_VERSION_2_5 = 0; { MPEG 2.5 }
MPEG_VERSION_UNKNOWN = 1; { Unknown version }
MPEG_VERSION_2 = 2; { MPEG 2 }
MPEG_VERSION_1 = 3; { MPEG 1 }
{ MPEG version names }
MPEG_VERSION: array [0..3] of string =
('MPEG 2.5', 'MPEG ?', 'MPEG 2', 'MPEG 1');
{ MPEG layer codes }
MPEG_LAYER_UNKNOWN = 0; { Unknown layer }
MPEG_LAYER_III = 1; { Layer III }
MPEG_LAYER_II = 2; { Layer II }
MPEG_LAYER_I = 3; { Layer I }
{ MPEG layer names }
MPEG_LAYER: array [0..3] of string =
('Layer ?', 'Layer III', 'Layer II', 'Layer I');
{ Channel mode codes }
MPEG_CM_STEREO = 0; { Stereo }
MPEG_CM_JOINT_STEREO = 1; { Joint Stereo }
MPEG_CM_DUAL_CHANNEL = 2; { Dual Channel }
MPEG_CM_MONO = 3; { Mono }
MPEG_CM_UNKNOWN = 4; { Unknown mode }
{ Channel mode names }
MPEG_CM_MODE: array [0..4] of string =
('Stereo', 'Joint Stereo', 'Dual Channel', 'Mono', 'Unknown');
{ Extension mode codes (for Joint Stereo) }
MPEG_CM_EXTENSION_OFF = 0; { IS and MS modes set off }
MPEG_CM_EXTENSION_IS = 1; { Only IS mode set on }
MPEG_CM_EXTENSION_MS = 2; { Only MS mode set on }
MPEG_CM_EXTENSION_ON = 3; { IS and MS modes set on }
MPEG_CM_EXTENSION_UNKNOWN = 4; { Unknown extension mode }
{ Emphasis mode codes }
MPEG_EMPHASIS_NONE = 0; { None }
MPEG_EMPHASIS_5015 = 1; { 50/15 ms }
MPEG_EMPHASIS_UNKNOWN = 2; { Unknown emphasis }
MPEG_EMPHASIS_CCIT = 3; { CCIT J.17 }
{ Emphasis names }
MPEG_EMPHASIS: array [0..3] of string =
('None', '50/15 ms', 'Unknown', 'CCIT J.17');
{ Encoder codes }
MPEG_ENCODER_UNKNOWN = 0; { Unknown encoder }
MPEG_ENCODER_XING = 1; { Xing }
MPEG_ENCODER_FHG = 2; { FhG }
MPEG_ENCODER_LAME = 3; { LAME }
MPEG_ENCODER_BLADE = 4; { Blade }
MPEG_ENCODER_GOGO = 5; { GoGo }
MPEG_ENCODER_SHINE = 6; { Shine }
{ Encoder names }
MPEG_ENCODER: array [0..6] of string =
('Unknown', 'Xing', 'FhG', 'LAME', 'Blade', 'GoGo', 'Shine');
TAG_VERSION_1_0 = 1; { Index for ID3v1.0 tag }
TAG_VERSION_1_1 = 2; { Index for ID3v1.1 tag }
TAG_VERSION_2_3 = 3; { Code for ID3v2.3.0 tag }
{ Max. number of supported tag frames }
ID3V2_FRAME_COUNT = 7;
{ Names of supported tag frames }
ID3V2_FRAME: array [1..ID3V2_FRAME_COUNT] of string =
('TIT2', 'TPE1', 'TALB', 'TRCK', 'TYER', 'TCON', 'COMM');
MAX_MUSIC_GENRES = 148; { Max. number of music genres }
DEFAULT_GENRE = 255; { Index for default genre }
var
MusicGenre: array [0..MAX_MUSIC_GENRES - 1] of PChar = { Genre names }
({ Standard genres }
'Blues', 'Classic Rock', 'Country', 'Dance', 'Disco', 'Funk', 'Grunge', 'Hip-Hop', 'Jazz', 'Metal',
'New Age', 'Oldies', 'Other', 'Pop', 'R&B', 'Rap', 'Reggae', 'Rock', 'Techno', 'Industrial',
'Alternative', 'Ska', 'Death Metal', 'Pranks', 'Soundtrack', 'Euro-Techno', 'Ambient', 'Trip-Hop',
'Vocal', 'Jazz+Funk', 'Fusion', 'Trance', 'Classical', 'Instrumental', 'Acid', 'House', 'Game',
'Sound Clip', 'Gospel', 'Noise', 'AlternRock', 'Bass', 'Soul', 'Punk', 'Space', 'Meditative',
'Instrumental Pop', 'Instrumental Rock', 'Ethnic', 'Gothic', 'Darkwave', 'Techno-Industrial',
'Electronic', 'Pop-Folk', 'Eurodance', 'Dream', 'Southern Rock', 'Comedy', 'Cult', 'Gangsta',
'Top 40', 'Christian Rap', 'Pop/Funk', 'Jungle', 'Native American', 'Cabaret', 'New Wave',
'Psychadelic', 'Rave', 'Showtunes', 'Trailer', 'Lo-Fi', 'Tribal', 'Acid Punk', 'Acid Jazz',
'Polka', 'Retro', 'Musical', 'Rock & Roll', 'Hard Rock',
{ Extended genres }
'Folk', 'Folk-Rock', 'National Folk', 'Swing', 'Fast Fusion', 'Bebob', 'Latin', 'Revival',
'Celtic', 'Bluegrass', 'Avantgarde', 'Gothic Rock', 'Progessive Rock', 'Psychedelic Rock',
'Symphonic Rock', 'Slow Rock', 'Big Band', 'Chorus', 'Easy Listening', 'Acoustic', 'Humour',
'Speech', 'Chanson', 'Opera', 'Chamber Music', 'Sonata', 'Symphony', 'Booty Bass', 'Primus',
'Porn Groove', 'Satire', 'Slow Jam', 'Club', 'Tango', 'Samba', 'Folklore', 'Ballad', 'Power Ballad',
'Rhythmic Soul', 'Freestyle', 'Duet', 'Punk Rock', 'Drum Solo', 'A capella', 'Euro-House',
'Dance Hall', 'Goa', 'Drum & Bass', 'Club-House', 'Hardcore', 'Terror', 'Indie', 'BritPop',
'Negerpunk', 'Polsk Punk', 'Beat', 'Christian Gangsta Rap', 'Heavy Metal', 'Black Metal',
'Crossover', 'Contemporary Christian', 'Christian Rock', 'Merengue', 'Salsa', 'Trash Metal',
'Anime', 'JPop', 'Synthpop');
type
{ Used in TID3v1 class }
String04 = string[4]; { String with max. 4 symbols }
String30 = string[30]; { String with max. 30 symbols }
{ Xing/FhG VBR header data }
VBRData = record
Found: Boolean; { True if VBR header found }
ID: array [1..4] of Char; { Header ID: "Xing" or "VBRI" }
Frames: longint; { Total number of frames }
Bytes: longint; { Total number of bytes }
Scale: Byte; { VBR scale (1..100) }
VendorID: array [1..8] of Char; { Vendor ID (if present) }
end;
{ MPEG frame header data}
FrameData = record
Found: Boolean; { True if frame found }
Position: Integer; { Frame position in the file }
Size: Word; { Frame size (bytes) }
Empty: Boolean; { True if no significant frame data }
Data: array [1..4] of Byte; { The whole frame header data }
VersionID: Byte; { MPEG version ID }
LayerID: Byte; { MPEG layer ID }
ProtectionBit: Boolean; { True if protected by CRC }
BitRateID: Word; { Bit rate ID }
SampleRateID: Word; { Sample rate ID }
PaddingBit: Boolean; { True if frame padded }
PrivateBit: Boolean; { Extra information }
ModeID: Byte; { Channel mode ID }
ModeExtensionID: Byte; { Mode extension ID (for Joint Stereo) }
CopyrightBit: Boolean; { True if audio copyrighted }
OriginalBit: Boolean; { True if original media }
EmphasisID: Byte; { Emphasis ID }
end;
{ Real structure of ID3v1 tag }
TagID3v1 = record
Header: array [1..3] of Char; { Tag header - must be "TAG" }
Title: array [1..30] of Char; { Title data }
Artist: array [1..30] of Char; { Artist data }
Album: array [1..30] of Char; { Album data }
Year: array [1..4] of Char; { Year data }
Comment: array [1..30] of Char; { Comment data }
Genre: Byte; { Genre data }
end;
{ ID3v2 header data - for internal use }
TagID3v2 = record
{ Real structure of ID3v2 header }
ID: array [1..3] of Char; { Always "ID3" }
Version: Byte; { Version number }
Revision: Byte; { Revision number }
Flags: Byte; { Flags of tag }
Size: array [1..4] of Byte; { Tag size excluding header }
{ Extended data }
FileSize: Integer; { File size (bytes) }
Frame: array [1..ID3V2_FRAME_COUNT] of string; { Information from frames }
end;
TID3v1 = class(TObject)
private
{ Private declarations }
FExists: Boolean;
FVersionID: Byte;
FTitle: String30;
FArtist: String30;
FAlbum: String30;
FYear: String04;
FComment: String30;
FTrack: Byte;
FGenreID: Byte;
FSize: longint;
procedure FSetTitle(const NewTitle: String30);
procedure FSetArtist(const NewArtist: String30);
procedure FSetAlbum(const NewAlbum: String30);
procedure FSetYear(const NewYear: String04);
procedure FSetComment(const NewComment: String30);
procedure FSetTrack(const NewTrack: Byte);
procedure FSetGenreID(const NewGenreID: Byte);
function FGetGenre: string;
public
{ Public declarations }
constructor Create; { Create object }
procedure ResetData; { Reset all data }
function ReadFromFile(const FileName: string): Boolean; { Load tag }
function ReadFromStream(Src: TStream): Boolean;
property Size: longint read FSize;
property Exists: Boolean read FExists; { True if tag found }
property VersionID: Byte read FVersionID; { Version code }
property Title: String30 read FTitle write FSetTitle; { Song title }
property Artist: String30 read FArtist write FSetArtist; { Artist name }
property Album: String30 read FAlbum write FSetAlbum; { Album name }
property Year: String04 read FYear write FSetYear; { Year }
property Comment: String30 read FComment write FSetComment; { Comment }
property Track: Byte read FTrack write FSetTrack; { Track number }
property GenreID: Byte read FGenreID write FSetGenreID; { Genre code }
property Genre: string read FGetGenre; { Genre name }
end;
TID3v2 = class(TObject)
private
{ Private declarations }
FExists: Boolean;
FVersionID: Byte;
FSize: Integer;
FTitle: string;
FArtist: string;
FAlbum: string;
FTrack: Byte;
FYear: string;
FGenre: string;
FComment: string;
public
{ Public declarations }
constructor Create; { Create object }
procedure ResetData; { Reset all data }
function ReadFromStream(Src: TStream): boolean;
function ReadFromFile(const FileName: string): Boolean; { Load tag }
property Exists: Boolean read FExists; { True if tag found }
property VersionID: Byte read FVersionID; { Version code }
property Size: Integer read FSize; { Total tag size }
property Title: string read FTitle; { Song title }
property Artist: string read FArtist; { Artist name }
property Album: string read FAlbum; { Album name }
property Track: Byte read FTrack; { Track number }
property Year: string read FYear; { Year }
property Genre: string read FGenre; { Genre name }
property Comment: string read FComment; { Comment }
end;
TMP3FrameInfo = class (TObject)
private
FPosition: longint;
FSize: Word;
FisSound: boolean;
FHeader: DWord;
public
property Header: DWord read FHeader write FHeader;
property Position: longint read FPosition write FPosition;
property Size: Word read FSize write FSize;
property isSound: boolean read FisSound write FisSound;
end;
{ Class TMPEGaudio }
TMPEGaudio = class(TObject)
private
{ Private declarations }
FFramesPos: TObjectList;
FFileLength: Integer;
FWaveHeader: Boolean;
FVBR: VBRData;
FFrame: FrameData;
FID3v1: TID3v1;
FID3v2: TID3v2;
FSoundFrameCount: longint;
procedure FResetData;
function FGetVersion: string;
function FGetLayer: string;
function FGetBitRate: Word;
function FGetSampleRate: Word;
function FGetChannelMode: string;
function FGetEmphasis: string;
function FGetFrames: Integer;
function FGetDuration: Double;
function FGetVBREncoderID: Byte;
function FGetCBREncoderID: Byte;
function FGetEncoderID: Byte;
function FGetEncoder: string;
function FGetValid: Boolean;
function GetMP3FrameInfo(index: Integer): TMP3FrameInfo;
protected
procedure EnumFrames(Src: TStream);
public
SkipCount: integer;
{ Public declarations }
constructor Create; { Create object }
destructor Destroy; override; { Destroy object }
function ReadFromFile(const FileName: string): Boolean; { Load data }
function ReadFromStream(Src: TStream): boolean;
function isMP3File(const FileName: string): Boolean; {check MP3 format}
property FileLength: Integer read FFileLength; { File length (bytes) }
property FrameInfo[index: longint]: TMP3FrameInfo read GetMP3FrameInfo;
property VBR: VBRData read FVBR; { VBR header data }
property FirstFrame: FrameData read FFrame; { Frame header data }
property ID3v1: TID3v1 read FID3v1; { ID3v1 tag data }
property ID3v2: TID3v2 read FID3v2; { ID3v2 tag data }
property Version: string read FGetVersion; { MPEG version name }
property Layer: string read FGetLayer; { MPEG layer name }
property BitRate: Word read FGetBitRate; { Bit rate (kbit/s) }
property SampleRate: Word read FGetSampleRate; { Sample rate (hz) }
property ChannelMode: string read FGetChannelMode; { Channel mode name }
property Emphasis: string read FGetEmphasis; { Emphasis name }
property FrameCount: longint read FGetFrames; { Total number of frames }
property SoundFrameCount: longint read FSoundFrameCount;
property Duration: Double read FGetDuration; { Song duration (sec) }
property EncoderID: Byte read FGetEncoderID; { Guessed encoder ID }
property Encoder: string read FGetEncoder; { Guessed encoder name }
property Valid: Boolean read FGetValid; { True if MPEG file valid }
end;
procedure DecodeHeader(const HeaderData: array of Byte; var Frame: FrameData);
function GetFrameLength(const Frame: FrameData): Word;
implementation
type
MP3FrameHeader = record
ID: array [1..4] of Char; { Frame ID }
Size: Integer; { Size excluding header }
Flags: Word; { Flags }
end;
const
{ Limitation constants }
MAX_MPEG_FRAME_LENGTH = 1729; { Max. MPEG frame length }
MIN_MPEG_BIT_RATE = 8; { Min. bit rate value }
MAX_MPEG_BIT_RATE = 448; { Max. bit rate value }
MIN_ALLOWED_DURATION = 0.1; { Min. song duration value }
{ VBR Vendor ID strings }
VBR_VENDOR_ID_LAME = 'LAME'; { For LAME }
VBR_VENDOR_ID_GOGO_NEW = 'GOGO'; { For GoGo (New) }
VBR_VENDOR_ID_GOGO_OLD = 'MPGE'; { For GoGo (Old) }
VBR_Lame_Track = 'UUUU';
{ ********************* Auxiliary functions & procedures ******************** }
function WaveHeaderPresent(const Index: Integer; Data: array of Byte): Boolean;
begin
{ Check for WAV header }
Result :=
(Chr(Data[Index + 8]) = 'W') and
(Chr(Data[Index + 9]) = 'A') and
(Chr(Data[Index + 10]) = 'V') and
(Chr(Data[Index + 11]) = 'E');
end;
{ --------------------------------------------------------------------------- }
function IsFrameHeader(const HeaderData: array of Byte): Boolean;
begin
{ Check for valid frame header }
if ((HeaderData[0] and $FF) <> $FF) or
((HeaderData[1] and $E0) <> $E0) or
(((HeaderData[1] shr 3) and 3) = 1) or
(((HeaderData[1] shr 1) and 3) = 0) or
((HeaderData[2] and $F0) = $F0) or
((HeaderData[2] and $F0) = 0) or
(((HeaderData[2] shr 2) and 3) = 3) or
((HeaderData[3] and 3) = 2) then
Result := false
else
Result := true;
end;
{ --------------------------------------------------------------------------- }
procedure DecodeHeader(const HeaderData: array of Byte; var Frame: FrameData);
begin
{ Decode frame header data }
Move(HeaderData, Frame.Data, SizeOf(Frame.Data));
Frame.VersionID := (HeaderData[1] shr 3) and 3;
Frame.LayerID := (HeaderData[1] shr 1) and 3;
Frame.ProtectionBit := (HeaderData[1] and 1) <> 1;
Frame.BitRateID := HeaderData[2] shr 4;
Frame.SampleRateID := (HeaderData[2] shr 2) and 3;
Frame.PaddingBit := ((HeaderData[2] shr 1) and 1) = 1;
Frame.PrivateBit := (HeaderData[2] and 1) = 1;
Frame.ModeID := (HeaderData[3] shr 6) and 3;
Frame.ModeExtensionID := (HeaderData[3] shr 4) and 3;
Frame.CopyrightBit := ((HeaderData[3] shr 3) and 1) = 1;
Frame.OriginalBit := ((HeaderData[3] shr 2) and 1) = 1;
Frame.EmphasisID := HeaderData[3] and 3;
end;
{ --------------------------------------------------------------------------- }
function ValidFrameAt(const Index: Word; Data: array of Byte): Boolean;
var
HeaderData: array [1..4] of Byte;
begin
{ Check for frame at given position }
HeaderData[1] := Data[Index];
HeaderData[2] := Data[Index + 1];
HeaderData[3] := Data[Index + 2];
HeaderData[4] := Data[Index + 3];
if IsFrameHeader(HeaderData) then Result := true
else Result := false;
end;
{ --------------------------------------------------------------------------- }
function GetCoefficient(const Frame: FrameData): Byte;
begin
{ Get frame coefficient }
if Frame.VersionID = MPEG_VERSION_1 then
if Frame.LayerID = MPEG_LAYER_I then Result := 48
else Result := 144
else
if Frame.LayerID = MPEG_LAYER_I then Result := 24
else Result := 72;
end;
{ --------------------------------------------------------------------------- }
function GetBitRate(const Frame: FrameData): Word;
begin
{ Get bit rate }
Result := MPEG_BIT_RATE[Frame.VersionID, Frame.LayerID, Frame.BitRateID];
end;
{ --------------------------------------------------------------------------- }
function GetSampleRate(const Frame: FrameData): Word;
begin
{ Get sample rate }
Result := MPEG_SAMPLE_RATE[Frame.VersionID, Frame.SampleRateID];
end;
{ --------------------------------------------------------------------------- }
function GetPadding(const Frame: FrameData): Byte;
begin
{ Get frame padding }
if Frame.PaddingBit then
if Frame.LayerID = MPEG_LAYER_I then Result := 4
else Result := 1
else Result := 0;
end;
{ --------------------------------------------------------------------------- }
function GetFrameLength(const Frame: FrameData): Word;
var
Coefficient, BitRate, SampleRate, Padding: Word;
begin
{ Calculate MPEG frame length }
Coefficient := GetCoefficient(Frame);
BitRate := GetBitRate(Frame);
SampleRate := GetSampleRate(Frame);
Padding := GetPadding(Frame);
Result := Trunc(Coefficient * BitRate * 1000 / SampleRate) + Padding;
{ if Frame.LayerID = MPEG_LAYER_I then
Result := Trunc((12 * BitRate * 1000 / SampleRate + Padding) * 4)
else
Result := trunc(144 * BitRate * 1000 / SampleRate) + Padding;
}
end;
{ --------------------------------------------------------------------------- }
function FrameIsEmpty(const Index: Word; Data: array of Byte): Boolean;
begin
{ Get true if frame has no significant data }
Result :=
(Data[Index] = 0) and
(Data[Index + 1] = 0) and
(Data[Index + 2] = 0) and
(Data[Index + 3] = 0) and
(Data[Index + 4] = 0) and
(Data[Index + 5] = 0);
end;
{ --------------------------------------------------------------------------- }
function GetXingInfo(const Index: Word; Data: array of Byte): VBRData;
begin
{ Extract Xing VBR info at given position }
FillChar(Result, SizeOf(Result), 0);
Result.Found := true;
Result.ID := VBR_ID_XING;
Result.Frames := Data[Index + 8] shl 24 + Data[Index + 9] shl 16 +
Data[Index + 10] shl 8 + Data[Index + 11];
Result.Bytes := Data[Index + 12] shl 24 + Data[Index + 13] shl 16 +
Data[Index + 14] shl 8 + Data[Index + 15];
Result.Scale := Data[Index + 119];
{ Encoder ID can be not present }
Result.VendorID[1] := Chr(Data[Index + 120]);
Result.VendorID[2] := Chr(Data[Index + 121]);
Result.VendorID[3] := Chr(Data[Index + 122]);
Result.VendorID[4] := Chr(Data[Index + 123]);
Result.VendorID[5] := Chr(Data[Index + 124]);
Result.VendorID[6] := Chr(Data[Index + 125]);
Result.VendorID[7] := Chr(Data[Index + 126]);
Result.VendorID[8] := Chr(Data[Index + 127]);
end;
{ --------------------------------------------------------------------------- }
function GetFhGInfo(const Index: Word; Data: array of Byte): VBRData;
begin
{ Extract FhG VBR info at given position }
FillChar(Result, SizeOf(Result), 0);
Result.Found := true;
Result.ID := VBR_ID_FHG;
Result.Scale := Data[Index + 9];
Result.Bytes := Data[Index + 10] shl 24 + Data[Index + 11] shl 16 +
Data[Index + 12] shl 8 + Data[Index + 13];
Result.Frames := Data[Index + 14] shl 24 + Data[Index + 15] shl 16 +
Data[Index + 16] shl 8 + Data[Index + 17];
end;
{ --------------------------------------------------------------------------- }
function GetVbrInfo(const Index: Word; Data: array of Byte): VBRData;
var
PSize: PLongint;
PPos: PByte absolute PSize;
Flags: byte;
begin
FillChar(Result, SizeOf(Result), 0);
Result.Found := true;
Result.ID := VBR_ID_INFO;
Flags := Data[Index + 7];
if (Flags and 1) = 1 then
Result.Frames := Data[Index + 8] shl 24 + Data[Index + 9] shl 16 +
Data[Index + 10] shl 8 + Data[Index + 11];
if (Flags and 2) = 2 then
Result.Bytes := Data[Index + 12] shl 24 + Data[Index + 13] shl 16 +
Data[Index + 14] shl 8 + Data[Index + 15];
if (Flags and 8) = 8 then
Result.Scale := Data[Index + 119];
end;
{ --------------------------------------------------------------------------- }
function FindVBR(const Index: Word; Data: array of Byte): VBRData;
begin
{ Check for VBR header at given position }
FillChar(Result, SizeOf(Result), 0);
if Chr(Data[Index]) +
Chr(Data[Index + 1]) +
Chr(Data[Index + 2]) +
Chr(Data[Index + 3]) = VBR_ID_XING then Result := GetXingInfo(Index, Data);
if Chr(Data[Index]) +
Chr(Data[Index + 1]) +
Chr(Data[Index + 2]) +
Chr(Data[Index + 3]) = VBR_ID_FHG then Result := GetFhGInfo(Index, Data);
if Chr(Data[Index]) +
Chr(Data[Index + 1]) +
Chr(Data[Index + 2]) +
Chr(Data[Index + 3]) = VBR_ID_INFO then Result := GetVbrInfo(Index, Data);
end;
{ --------------------------------------------------------------------------- }
function GetVBRDeviation(const Frame: FrameData): Byte;
begin
{ Calculate VBR deviation }
if Frame.VersionID = MPEG_VERSION_1 then
if Frame.ModeID <> MPEG_CM_MONO then Result := 36
else Result := 21
else
if Frame.ModeID <> MPEG_CM_MONO then Result := 21
else Result := 13;
end;
{ --------------------------------------------------------------------------- }
function FindFrame(const Data: array of Byte; var VBR: VBRData): FrameData;
var
HeaderData: array [1..4] of Byte;
Iterator: Integer;
// isDecode: boolean;
begin
{ Search for valid frame }
FillChar(Result, SizeOf(Result), 0);
Move(Data, HeaderData, SizeOf(HeaderData));
for Iterator := 0 to SizeOf(Data) - MAX_MPEG_FRAME_LENGTH do
begin
{ Decode data if frame header found }
if IsFrameHeader(HeaderData) then
begin
DecodeHeader(HeaderData, Result);
// if not isDecode then
// begin
// DecodeHeader(HeaderData, Result);
// isDecode := true;
// Result.Found := true;
// Result.Size := GetFrameLength(Result);
// Result.Empty := FrameIsEmpty(Iterator + SizeOf(HeaderData), Data);
// end;
{ Check for next frame and try to find VBR header }
if ValidFrameAt(Iterator + GetFrameLength(Result), Data) then
begin
Result.Found := true;
Result.Position := Iterator;
Result.Size := GetFrameLength(Result);
Result.Empty := FrameIsEmpty(Iterator + SizeOf(HeaderData), Data);
VBR := FindVBR(Iterator + GetVBRDeviation(Result), Data);
break;
end;
end;
{ Prepare next data block }
HeaderData[1] := HeaderData[2];
HeaderData[2] := HeaderData[3];
HeaderData[3] := HeaderData[4];
HeaderData[4] := Data[Iterator + SizeOf(HeaderData)];
end;
end;
{ --------------------------------------------------------------------------- }
function GetTrack(const TrackString: string): Byte;
var
Index, Value, Code: Integer;
begin
{ Extract track from string }
Index := Pos('/', TrackString);
if Index = 0 then Val(Trim(TrackString), Value, Code)
else Val(Copy(Trim(TrackString), 1, Index), Value, Code);
if Code = 0 then Result := Value
else Result := 0;
end;
{ ********************** Private functions & procedures ********************* }
procedure TMPEGaudio.FResetData;
begin
{ Reset all variables }
FFileLength := 0;
FillChar(FVBR, SizeOf(FVBR), 0);
FillChar(FFrame, SizeOf(FFrame), 0);
FFrame.VersionID := MPEG_VERSION_UNKNOWN;
FFrame.SampleRateID := MPEG_SAMPLE_RATE_UNKNOWN;
FFrame.ModeID := MPEG_CM_UNKNOWN;
FFrame.ModeExtensionID := MPEG_CM_EXTENSION_UNKNOWN;
FFrame.EmphasisID := MPEG_EMPHASIS_UNKNOWN;
FID3v1.ResetData;
FID3v2.ResetData;
end;
function TMPEGaudio.GetMP3FrameInfo(index: longint): TMP3FrameInfo;
begin
result := TMP3FrameInfo(FFramesPos[index]);
end;
function TMPEGaudio.isMP3File(const FileName: string): Boolean;
var
F: TFileStream;
Data: array [1..MAX_MPEG_FRAME_LENGTH * 2] of Byte;
begin
F := TFileStream.Create(FileName, fmOpenRead + fmShareDenyWrite);
Result := false;
FResetData;
if (FID3v1.ReadFromStream(F)) and (FID3v2.ReadFromStream(F)) then
begin
F.Position := FID3v2.Size;
F.Read(Data, SizeOf(Data));
FWaveHeader := WaveHeaderPresent(FID3v2.Size, Data);
FFrame := FindFrame(Data, FVBR);
Result := FFrame.Found;
end;
F.Free;
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetVersion: string;
begin
{ Get MPEG version name }
Result := MPEG_VERSION[FFrame.VersionID];
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetLayer: string;
begin
{ Get MPEG layer name }
Result := MPEG_LAYER[FFrame.LayerID];
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetBitRate: Word;
begin
{ Get bit rate, calculate average bit rate if VBR header found }
if (FVBR.Found) and (FVBR.Frames > 0) then
Result := Round((FVBR.Bytes / FVBR.Frames - GetPadding(FFrame)) *
GetSampleRate(FFrame) / GetCoefficient(FFrame) / 1000)
else
Result := GetBitRate(FFrame);
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetSampleRate: Word;
begin
{ Get sample rate }
Result := GetSampleRate(FFrame);
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetChannelMode: string;
begin
{ Get channel mode name }
Result := MPEG_CM_MODE[FFrame.ModeID];
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetEmphasis: string;
begin
{ Get emphasis name }
Result := MPEG_EMPHASIS[FFrame.EmphasisID];
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetFrames: LongInt;
begin
{ Get total number of frames, calculate if VBR header not found }
if FFramesPos.Count > 0 then
Result := FFramesPos.Count else
if FVBR.Found then
Result := FVBR.Frames
else
Result := (FFileLength - FID3v2.Size - FFrame.Position) div
GetFrameLength(FFrame);
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetDuration: Double;
begin
{ Calculate song duration }
if FFrame.Found then
if (FVBR.Found) and (FVBR.Frames > 0) then
Result := FVBR.Frames * GetCoefficient(FFrame) * 8 /
GetSampleRate(FFrame)
else
Result := (FFileLength - FID3v2.Size - FFrame.Position) * 8 /
GetBitRate(FFrame) / 1000
else
Result := 0;
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetVBREncoderID: Byte;
begin
{ Guess VBR encoder and get ID }
Result := 0;
if Copy(FVBR.VendorID, 1, 4) = VBR_VENDOR_ID_LAME then
Result := MPEG_ENCODER_LAME;
if Copy(FVBR.VendorID, 1, 4) = VBR_VENDOR_ID_GOGO_NEW then
Result := MPEG_ENCODER_GOGO;
if Copy(FVBR.VendorID, 1, 4) = VBR_VENDOR_ID_GOGO_OLD then
Result := MPEG_ENCODER_GOGO;
if (FVBR.ID = VBR_ID_XING) and
(Copy(FVBR.VendorID, 1, 4) <> VBR_VENDOR_ID_LAME) and
(Copy(FVBR.VendorID, 1, 4) <> VBR_VENDOR_ID_GOGO_NEW) and
(Copy(FVBR.VendorID, 1, 4) <> VBR_VENDOR_ID_GOGO_OLD) then
Result := MPEG_ENCODER_XING;
if FVBR.ID = VBR_ID_FHG then
Result := MPEG_ENCODER_FHG;
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetCBREncoderID: Byte;
begin
{ Guess CBR encoder and get ID }
Result := 0;
if (FFrame.OriginalBit) and
(FFrame.ProtectionBit) then
Result := MPEG_ENCODER_LAME;
if (FFrame.ModeID = MPEG_CM_JOINT_STEREO) and
(not FFrame.CopyrightBit) and
(not FFrame.OriginalBit) then
Result := MPEG_ENCODER_FHG;
if (GetBitRate(FFrame) <= 112) and
(FFrame.ModeID = MPEG_CM_STEREO) then
Result := MPEG_ENCODER_BLADE;
if (FFrame.CopyrightBit) and
(FFrame.OriginalBit) and
(not FFrame.ProtectionBit) then
Result := MPEG_ENCODER_XING;
if (FFrame.Empty) and
(FFrame.OriginalBit) then
Result := MPEG_ENCODER_XING;
if (FWaveHeader) then
Result := MPEG_ENCODER_FHG;
if (FFrame.ModeID = MPEG_CM_DUAL_CHANNEL) and
(FFrame.ProtectionBit) then
Result := MPEG_ENCODER_SHINE;
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetEncoderID: Byte;
begin
{ Get guessed encoder ID }
if FFrame.Found then
if FVBR.Found then Result := FGetVBREncoderID
else Result := FGetCBREncoderID
else
Result := 0;
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetEncoder: string;
begin
{ Get guessed encoder name }
Result := MPEG_ENCODER[FGetEncoderID];
if (FVBR.Found) and
(FGetEncoderID = MPEG_ENCODER_LAME) and
(FVBR.VendorID[5] in ['0'..'9']) and
(FVBR.VendorID[6] = '.') and
(FVBR.VendorID[7] in ['0'..'9']) and
(FVBR.VendorID[8] in ['0'..'9']) then
Result :=
Result + #32 +
FVBR.VendorID[5] +
FVBR.VendorID[6] +
FVBR.VendorID[7] +
FVBR.VendorID[8];
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.FGetValid: Boolean;
begin
{ Check for right MPEG file data }
Result :=
(FFrame.Found) and
(FGetBitRate >= MIN_MPEG_BIT_RATE) and
(FGetBitRate <= MAX_MPEG_BIT_RATE) and
(FGetDuration >= MIN_ALLOWED_DURATION);
end;
{ ********************** Public functions & procedures ********************** }
constructor TMPEGaudio.Create;
begin
inherited;
FID3v1 := TID3v1.Create;
FID3v2 := TID3v2.Create;
FResetData;
FFramesPos := TObjectList.Create;
end;
{ --------------------------------------------------------------------------- }
destructor TMPEGaudio.Destroy;
begin
FFramesPos.Free;
FID3v1.Free;
FID3v2.Free;
inherited;
end;
{ --------------------------------------------------------------------------- }
function TMPEGaudio.ReadFromFile(const FileName: string): Boolean;
var
F: TFileStream;
begin
F := TFileStream.Create(FileName, fmOpenRead + fmShareDenyWrite);
Result := ReadFromStream(F);
F.Free;
end;
function TMPEGaudio.ReadFromStream(Src: TStream): boolean;
var
Data: array [1..MAX_MPEG_FRAME_LENGTH * 2] of Byte;
begin
Result := false;
FResetData;
if (FID3v1.ReadFromStream(Src)) and (FID3v2.ReadFromStream(Src)) then
try
{ Open file, read first block of data and search for a frame }
FFileLength := Src.Size;
Src.Position := FID3v2.Size;
Src.Read(Data, SizeOf(Data));
// BlockRead(SourceFile, Data, SizeOf(Data), Transferred);
FWaveHeader := WaveHeaderPresent(FID3v2.Size, Data);
FFrame := FindFrame(Data, FVBR);
{ Try to search in the middle if no frame at the beginning found }
if (not FFrame.Found) {and (Transferred = SizeOf(Data))} then
begin
Src.Position := (FFileLength - FID3v2.Size) div 2;
Src.Read(Data, SizeOf(Data));
FFrame := FindFrame(Data, FVBR);
end;
Result := true;
if FFrame.Found then
EnumFrames(Src);
except
end;
if not FFrame.Found then FResetData;
end;
procedure TMPEGaudio.EnumFrames(Src: TStream);
var HeaderData: array [1..4] of Byte;
DW: dword absolute HeaderData;
CFrame: FrameData;
FI: TMP3FrameInfo;
vbrflag: array [0..3] of char;
begin
CFrame := FirstFrame;
FSoundFrameCount := 0;
CFrame.Position := FirstFrame.Position + ID3v2.Size;
Src.Position := CFrame.Position;
while (Src.Position + ID3v1.Size) < Src.Size do
begin
Src.Read(HeaderData, 4);
if IsFrameHeader(HeaderData) then
begin
FI := TMP3FrameInfo.Create;
FI.Header := DW;
FI.Position := Src.Position - 4;
DecodeHeader(HeaderData, CFrame);
FI.Size := GetFrameLength(CFrame);
Src.Seek(32, 1);
Src.Read(vbrflag, 4);
FI.isSound := not((vbrflag = VBR_ID_INFO) or (vbrflag = VBR_Lame_Track) or
(vbrflag = VBR_ID_XING) or (vbrflag = MPEG_ENCODER[3]));
if FI.isSound then inc(FSoundFrameCount);
FFramesPos.Add(FI);
Src.Position := FI.Position + Fi.Size;
end else
Src.Position := Src.Size;
end;
end;
function GetTagVersion(const TagData: TagID3v1): Byte;
begin
Result := TAG_VERSION_1_0;
{ Terms for ID3v1.1 }
if ((TagData.Comment[29] = #0) and (TagData.Comment[30] <> #0)) or
((TagData.Comment[29] = #32) and (TagData.Comment[30] <> #32)) then
Result := TAG_VERSION_1_1;
end;
function Swap32(const Figure: Integer): Integer;
var
ByteArray: array [1..4] of Byte absolute Figure;
begin
{ Swap 4 bytes }
Result :=
ByteArray[1] * $100000000 +
ByteArray[2] * $10000 +
ByteArray[3] * $100 +
ByteArray[4];
end;
{ ********************** TID3v1 ********************* }
constructor TID3v1.Create;
begin
inherited;
ResetData;
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.ResetData;
begin
FExists := false;
FVersionID := TAG_VERSION_1_0;
FTitle := '';
FArtist := '';
FAlbum := '';
FYear := '';
FComment := '';
FTrack := 0;
FGenreID := DEFAULT_GENRE;
end;
{ --------------------------------------------------------------------------- }
function TID3v1.ReadFromFile(const FileName: string): Boolean;
var
F: TFileStream;
begin
F := TFileStream.Create(FileName, fmOpenRead + fmShareDenyWrite);
Result := ReadFromStream(F);
F.Free;
end;
{ --------------------------------------------------------------------------- }
function TID3v1.ReadFromStream(Src: TStream): Boolean;
var
TagData: TagID3v1;
begin
Result := true;
Src.Position := Src.Size - 128;
Src.Read(TagData, 128);
FSize := 0;
if (TagData.Header = 'TAG') then
begin
FSize := 128;
FExists := true;
FVersionID := GetTagVersion(TagData);
{ Fill properties with tag data }
FTitle := TrimRight(TagData.Title);
FArtist := TrimRight(TagData.Artist);
FAlbum := TrimRight(TagData.Album);
FYear := TrimRight(TagData.Year);
if FVersionID = TAG_VERSION_1_0 then
FComment := TrimRight(TagData.Comment)
else
begin
FComment := TrimRight(Copy(TagData.Comment, 1, 28));
FTrack := Ord(TagData.Comment[30]);
end;
FGenreID := TagData.Genre;
Result := true;
end;
end;
procedure TID3v1.FSetTitle(const NewTitle: String30);
begin
FTitle := TrimRight(NewTitle);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetArtist(const NewArtist: String30);
begin
FArtist := TrimRight(NewArtist);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetAlbum(const NewAlbum: String30);
begin
FAlbum := TrimRight(NewAlbum);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetYear(const NewYear: String04);
begin
FYear := TrimRight(NewYear);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetComment(const NewComment: String30);
begin
FComment := TrimRight(NewComment);
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetTrack(const NewTrack: Byte);
begin
FTrack := NewTrack;
end;
{ --------------------------------------------------------------------------- }
procedure TID3v1.FSetGenreID(const NewGenreID: Byte);
begin
if NewGenreID >= MAX_MUSIC_GENRES
then FGenreID := MAX_MUSIC_GENRES - 1
else FGenreID := NewGenreID;
end;
{ --------------------------------------------------------------------------- }
function TID3v1.FGetGenre: string;
begin
Result := '';
{ Return an empty string if the current GenreID is not valid }
if FGenreID in [0..MAX_MUSIC_GENRES - 1] then Result := MusicGenre[FGenreID];
end;
{ ********************************** TID3v2 ******************************** }
constructor TID3v2.Create;
begin
inherited;
ResetData;
end;
{ --------------------------------------------------------------------------- }
procedure TID3v2.ResetData;
begin
FExists := false;
FVersionID := 0;
FSize := 0;
FTitle := '';
FArtist := '';
FAlbum := '';
FTrack := 0;
FYear := '';
FGenre := '';
FComment := '';
end;
{ --------------------------------------------------------------------------- }
function TID3v2.ReadFromFile(const FileName: string): Boolean;
var
F: TFileStream;
begin
F := TFileStream.Create(FileName, fmOpenRead + fmShareDenyWrite);
Result := ReadFromStream(F);
F.Free;
end;
function TID3v2.ReadFromStream(Src: TStream): boolean;
var
TagData: TagID3v2;
Frame: MP3FrameHeader;
DataPosition: longint;
Data: array [1..250] of Char;
Iterator: Byte;
begin
ResetData;
Result := true;
Src.Position := 0;
Src.Read(TagData, 10);
if TagData.ID = 'ID3' then
begin
FExists := true;
TagData.FileSize := Src.Size;
{ Fill properties with header data }
FVersionID := TagData.Version;
FSize := TagData.Size[1] * $200000 + TagData.Size[2] * $4000 + TagData.Size[3] * $80 + TagData.Size[4] + 10;
if FSize > TagData.FileSize then FSize := 0;;
{ Get information from frames if version supported }
if (FVersionID = TAG_VERSION_2_3) and (FSize > 0) then
begin
while (Src.Position < FSize) and (Src.Position < Src.Size) do
begin
FillChar(Data, SizeOf(Data), 0);
Src.Read(Frame, 10);
DataPosition := Src.Position;
Src.Read(Data, Swap32(Frame.Size) mod SizeOf(Data));
for Iterator := 1 to ID3V2_FRAME_COUNT do
if ID3V2_FRAME[Iterator] = Frame.ID then TagData.Frame[Iterator] := Data;
Src.Seek(DataPosition + Swap32(Frame.Size), 0);
end;
{ Fill properties with data from frames }
FTitle := Trim(TagData.Frame[1]);
FArtist := Trim(TagData.Frame[2]);
FAlbum := Trim(TagData.Frame[3]);
FTrack := GetTrack(TagData.Frame[4]);
FYear := Trim(TagData.Frame[5]);
FGenre := Trim(TagData.Frame[6]);
if Pos(')', FGenre) > 0 then Delete(FGenre, 1, LastDelimiter(')', FGenre));
FComment := Trim(Copy(TagData.Frame[7], 5, Length(TagData.Frame[7]) - 4));
end;
end;
end;
{ TMP3FrameInfo }
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 180843
////////////////////////////////////////////////////////////////////////////////
unit org.apache.http.auth.AuthSchemeRegistry;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
org.apache.http.auth.AuthSchemeFactory,
org.apache.http.auth.AuthScheme,
org.apache.http.params.HttpParams;
type
JAuthSchemeRegistry = interface;
JAuthSchemeRegistryClass = interface(JObjectClass)
['{4707D24F-9E52-4D59-9DA7-4741C66B3DB0}']
function getAuthScheme(&name : JString; params : JHttpParams) : JAuthScheme; cdecl;// (Ljava/lang/String;Lorg/apache/http/params/HttpParams;)Lorg/apache/http/auth/AuthScheme; A: $21
function getSchemeNames : JList; cdecl; // ()Ljava/util/List; A: $21
function init : JAuthSchemeRegistry; cdecl; // ()V A: $1
procedure ®ister(&name : JString; factory : JAuthSchemeFactory) ; cdecl; // (Ljava/lang/String;Lorg/apache/http/auth/AuthSchemeFactory;)V A: $21
procedure setItems(map : JMap) ; cdecl; // (Ljava/util/Map;)V A: $21
procedure unregister(&name : JString) ; cdecl; // (Ljava/lang/String;)V A: $21
end;
[JavaSignature('org/apache/http/auth/AuthSchemeRegistry')]
JAuthSchemeRegistry = interface(JObject)
['{8565549C-1B00-43E2-804E-DC49CD43F441}']
end;
TJAuthSchemeRegistry = class(TJavaGenericImport<JAuthSchemeRegistryClass, JAuthSchemeRegistry>)
end;
implementation
end.
|
unit mrSuperCombo;
interface
uses
Windows, Classes, cxDBLookupComboBox, cxEdit, DB, DBClient, uNTDataSetControl,
SysUtils, mrBoundLabel, ExtCtrls, Types, Graphics, StdCtrls, Controls,
Messages, Menus, cxDBEdit, cxDBLookupEdit, uNTUpdateControl, uNTTraceControl,
uUserObj, Variants, uSystemTypes;
type
TmrSuperCombo = class;
TmrDependentLookUp = class(TCollectionItem)
private
FName: String;
FLookUp: TmrSuperCombo;
public
constructor Create(Collection: TCollection); override;
published
property Name: String read FName write FName;
property LookUp: TmrSuperCombo read FLookUp write FLookUp;
end;
TmrDependentLookUps = class(TCollection)
private
FOwner: TPersistent;
FOnChange: TNotifyEvent;
function GetItem(Index: Integer): TmrDependentLookUp;
procedure SetItem(Index: Integer; Value: TmrDependentLookUp);
protected
function GetOwner: TPersistent; override;
procedure Update(Item: TCollectionItem); override;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
public
constructor Create(AOwner: TPersistent); virtual;
property Items[Index: Integer]: TmrDependentLookUp read GetItem write SetItem; default;
end;
TmrSuperComboProperties = class(TcxLookupComboBoxProperties)
published
property Buttons;
end;
TmrSuperCombo = class(TcxLookupComboBox)
private
FProviderListName: String;
FConnectionListName: String;
FSession: TmrSession;
FDataSetList: TClientDataSet;
FDataSourceList: TDataSource;
FEditLabel: TmrBoundLabel;
FPopupMenuButton: TPopupMenu;
FRequiredLabel: TmrBoundLabel;
FLabelPosition: TLabelPosition;
FLocked: Boolean;
FRequired: Boolean;
FLabelSpacing: Integer;
FDisableButtons: Boolean;
FFchClassName: String;
FProviderSourceName: String;
FConnectionSourceName: String;
FDataSetControl: TmrDataSetControl;
FTraceControl: TmrTraceControl;
FUpdateControl: TmrUpdateControl;
FSystemUser : TUser;
FOnBeforeGetRecordsList: TRemoteEvent;
FParams: String;
FDependentLookUps: TmrDependentLookUps;
FSchClassName: String;
FOnStartSearch: TOnGetParams;
procedure PopupClick(Sender: TObject);
function GetProperties: TmrSuperComboProperties;
procedure SetProperties(const Value: TmrSuperComboProperties);
procedure SetLabelPosition(const Value: TLabelPosition);
procedure SetLabelSpacing(const Value: Integer);
procedure SetLocked(const Value: Boolean);
procedure SetRequired(const Value: Boolean);
procedure SetupInternalLabel;
procedure SetInternalButtons;
procedure SetCommandButtons;
procedure SetInternalList;
procedure SetInternalPopup;
procedure SetConfigFch;
procedure OpenListSource;
procedure DoBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant);
procedure DoBeforeGetRecordsSource(Sender: TObject; var OwnerData: OleVariant);
procedure InsertRecord(AParams: String = '');
procedure OpenRecord(AParams: String = '');
procedure DeleteRecord;
procedure SearchRecord;
procedure SetDependentLookUps(const Value: TmrDependentLookUps);
procedure RefreshDependentLookups;
procedure SetSchClassName(const Value: String);
protected
procedure ClearValue; virtual;
procedure SetDBValues(DataSet: TDataSet); overload; virtual;
procedure SetDBValues(AFieldValue : Variant); overload; virtual;
procedure SetParent(AParent: TWinControl); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetName(const Value: TComponentName); override;
procedure CMVisiblechanged(var Message: TMessage); message CM_VISIBLECHANGED;
procedure CMEnabledchanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMBidimodechanged(var Message: TMessage); message CM_BIDIMODECHANGED;
procedure DoButtonUp(Index: Integer); override;
property TraceControl: TmrTraceControl read FTraceControl write FTraceControl;
property DataSetControl: TmrDataSetControl read FDataSetControl write FDataSetControl;
property UpdateControl: TmrUpdateControl read FUpdateControl write FUpdateControl;
property Session: TmrSession read FSession write FSession;
property DataSetList: TClientDataSet read FDataSetList write FDataSetList;
property DataSourceList: TDataSource read FDataSourceList write FDataSourceList;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetPropertiesClass: TcxCustomEditPropertiesClass; override;
procedure SetBounds(ALeft: Integer; ATop: Integer; AWidth: Integer; AHeight: Integer); override;
procedure CreateListSource(ATraceControl: TmrTraceControl; ADataSetControl: TmrDataSetControl;
AUpdateControl: TmrUpdateControl; ASession: TmrSession; ASystemUser : TUser; AParams : String = '');
procedure ApplyFilters(AFilter : String);
function GetFieldValue(AFieldName: String): Variant;
published
property OnBeforeGetRecordsList : TRemoteEvent read FOnBeforeGetRecordsList write FOnBeforeGetRecordsList;
property Properties: TmrSuperComboProperties read GetProperties write SetProperties;
property DisableButtons: Boolean read FDisableButtons write FDisableButtons;
property ConnectionListName: String read FConnectionListName write FConnectionListName;
property ConnectionSourceName: String read FConnectionSourceName write FConnectionSourceName;
property ProviderListName: String read FProviderListName write FProviderListName;
property ProviderSourceName: String read FProviderSourceName write FProviderSourceName;
property FchClassName: String read FFchClassName write FFchClassName;
property SchClassName: String read FSchClassName write SetSchClassName;
property EditLabel: TmrBoundLabel read FEditLabel;
property LabelPosition: TLabelPosition read FLabelPosition write SetLabelPosition;
property LabelSpacing: Integer read FLabelSpacing write SetLabelSpacing;
property Required: Boolean read FRequired write SetRequired;
property Locked: Boolean read FLocked write SetLocked;
property Params : String read FParams write FParams;
property DependentLookUps: TmrDependentLookUps read FDependentLookUps write SetDependentLookUps;
property OnStartSearch : TOnGetParams read FOnStartSearch write FOnStartSearch;
end;
TmrDBSuperCombo = class(TmrSuperCombo)
private
function GetDataBinding: TcxDBTextEditDataBinding;
procedure SetDataBinding(Value: TcxDBTextEditDataBinding);
procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK;
protected
procedure ClearValue; override;
procedure SetDBValues(DataSet: TDataSet); overload; override;
procedure SetDBValues(AFieldValue : Variant); overload; override;
class function GetDataBindingClass: TcxEditDataBindingClass; override;
published
property DataBinding: TcxDBTextEditDataBinding read GetDataBinding write SetDataBinding;
end;
procedure Register;
implementation
uses cxLookupDBGrid, cxDropDownEdit, mrMsgBox, uParentCustomFch,
uClasseFunctions, uMRSQLParam, uParentSearchForm;
procedure Register;
begin
RegisterComponents('MultiTierDataControls', [TmrSuperCombo]);
RegisterComponents('MultiTierDataControls', [TmrDBSuperCombo]);
end;
{ TmrSuperCombo }
constructor TmrSuperCombo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLabelPosition := lpLeft;
FLabelSpacing := 6;
Properties.ListOptions.ShowHeader := False;
SetupInternalLabel;
SetInternalButtons;
SetInternalPopup;
FDependentLookUps := TmrDependentLookUps.Create(Self);
FDependentLookUps.OnChange := Properties.OnChange;
end;
procedure TmrSuperCombo.CreateListSource(ATraceControl: TmrTraceControl; ADataSetControl: TmrDataSetControl;
AUpdateControl: TmrUpdateControl; ASession: TmrSession; ASystemUser : TUser; AParams : String);
begin
TraceControl := ATraceControl;
DataSetControl := ADataSetControl;
UpdateControl := AUpdateControl;
FSystemUser := ASystemUser;
FParams := AParams;
// Get Session if necesary
if not Assigned(ASession) then
Session := FDataSetControl.CreateSession
else
Session := ASession;
// Get DataSource if necesary
if DataSourceList = nil then
begin
DataSourceList := TDataSource.Create(Self);
Properties.ListSource := DataSourceList;
end;
// Get Dataset if necesary
if DataSetList = nil then
begin
DataSetList := Session.CreateDataSet(ConnectionListName, ProviderListName);
// Set combo filter event
DataSetList.BeforeGetRecords := DoBeforeGetRecordsList;
// Set DataSource
Properties.ListSource.DataSet := DataSetList;
OpenListSource;
SetConfigFch;
SetInternalList;
SetCommandButtons;
end;
end;
destructor TmrSuperCombo.Destroy;
begin
FPopupMenuButton.Free;
FreeAndNil(FDependentLookUps);
inherited Destroy;
end;
procedure TmrSuperCombo.DoBeforeGetRecordsList(Sender: TObject;
var OwnerData: OleVariant);
begin
if Assigned(FOnBeforeGetRecordsList) then
OnBeforeGetRecordsList(Sender, OwnerData);
end;
procedure TmrSuperCombo.DoBeforeGetRecordsSource(Sender: TObject;
var OwnerData: OleVariant);
begin
with TMRSQLParam.Create do
try
AddKey(Properties.KeyFieldNames).AsString := EditValue;
KeyByName(Properties.KeyFieldNames).Condition := tcEquals;
OwnerData := ParamString;
finally
Free;
end;
end;
function TmrSuperCombo.GetProperties: TmrSuperComboProperties;
begin
Result := TmrSuperComboProperties(FProperties);
end;
class function TmrSuperCombo.GetPropertiesClass: TcxCustomEditPropertiesClass;
begin
Result := TmrSuperComboProperties;
end;
procedure TmrSuperCombo.OpenListSource;
begin
with DataSetList do
begin
if Active then
Close;
Open;
end;
end;
procedure TmrSuperCombo.SetInternalList;
begin
if Properties.ListFieldNames = '' then
Properties.ListFieldNames := UpperCase(DataSetList.GetOptionalParam('ListFieldNames'));
if Properties.KeyFieldNames = '' then
Properties.KeyFieldNames := UpperCase(DataSetList.GetOptionalParam('KeyFieldName'));
end;
procedure TmrSuperCombo.SetLabelPosition(const Value: TLabelPosition);
var
P: TPoint;
begin
if Assigned(FEditLabel) then
begin
FLabelPosition := Value;
case Value of
lpAbove: P := Point(Left, Top - FEditLabel.Height - FLabelSpacing);
lpBelow: P := Point(Left, Top + Height + FLabelSpacing);
lpLeft : P := Point(Left - FEditLabel.Width - FLabelSpacing,
Top + ((Height - FEditLabel.Height) div 2));
lpRight: P := Point(Left + Width + FLabelSpacing,
Top + ((Height - FEditLabel.Height) div 2));
end;
FEditLabel.SetBounds(P.x, P.y, FEditLabel.Width, FEditLabel.Height);
end;
if Assigned(FRequiredLabel) then
FRequiredLabel.SetBounds(Left + Width + 3, Top + 1, FRequiredLabel.Width, FRequiredLabel.Height);
end;
procedure TmrSuperCombo.SetLocked(const Value: Boolean);
begin
FLocked := Value;
Properties.ReadOnly := Value;
ParentColor := Value;
if not Value then
Color := clWindow;
end;
procedure TmrSuperCombo.SetLabelSpacing(const Value: Integer);
begin
FLabelSpacing := Value;
SetLabelPosition(FLabelPosition);
end;
procedure TmrSuperCombo.SetProperties(const Value: TmrSuperComboProperties);
begin
FProperties.Assign(Value);
end;
procedure TmrSuperCombo.SetRequired(const Value: Boolean);
begin
FRequired := Value;
if Value then
FRequiredLabel.Parent := Self.Parent
else
FRequiredLabel.Parent := nil;
end;
procedure TmrSuperCombo.SetupInternalLabel;
begin
if not Assigned(FEditLabel) then
begin
FEditLabel := TmrBoundLabel.Create(Self);
FEditLabel.Name := 'SubEditLabel';
FEditLabel.SetSubComponent(True);
FEditLabel.FreeNotification(Self);
TLabel(FEditLabel).FocusControl := Self;
end;
if not Assigned(FRequiredLabel) then
begin
FRequiredLabel := TmrBoundLabel.Create(Self);
with FRequiredLabel do
begin
Name := 'SubRequiredLabel';
SetSubComponent(True);
FreeNotification(Self);
Caption := '*';
Font.Color := $00804000;
Font.Style := [fsBold];
Font.Size := 15;
Font.Name := 'Verdana';
Transparent := True;
end;
end;
end;
procedure TmrSuperCombo.SetName(const Value: TComponentName);
begin
inherited;
if (csDesigning in ComponentState) and ((FEditlabel.GetTextLen = 0) or
(CompareText(FEditLabel.Caption, Name) = 0)) then
FEditLabel.Caption := Value;
inherited SetName(Value);
if csDesigning in ComponentState then
Text := '';
end;
procedure TmrSuperCombo.CMBidimodechanged(var Message: TMessage);
begin
FEditLabel.BiDiMode := BiDiMode;
FRequiredLabel.BiDiMode := BiDiMode;
end;
procedure TmrSuperCombo.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FEditLabel) and (Operation = opRemove) then
FEditLabel := nil;
if (AComponent = FRequiredLabel) and (Operation = opRemove) then
FRequiredLabel := nil;
end;
procedure TmrSuperCombo.SetParent(AParent: TWinControl);
begin
inherited SetParent(AParent);
if Assigned(FEditLabel) then
begin
FEditLabel.Parent := AParent;
FEditLabel.Visible := True;
end;
end;
procedure TmrSuperCombo.CMEnabledchanged(var Message: TMessage);
begin
FEditLabel.Enabled := Enabled;
FRequiredLabel.Enabled := Enabled;
end;
procedure TmrSuperCombo.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
SetLabelPosition(FLabelPosition);
end;
procedure TmrSuperCombo.CMVisiblechanged(var Message: TMessage);
begin
inherited;
FEditLabel.Visible := Visible;
FRequiredLabel.Visible := Visible;
if Visible and Required then
FRequiredLabel.Parent := Self.Parent
else
FRequiredLabel.Parent := nil;
end;
procedure TmrSuperCombo.SetInternalButtons;
begin
Properties.Buttons.Add;
Properties.Buttons[1].Kind := bkEllipsis;
end;
procedure TmrSuperCombo.SetInternalPopup;
procedure CreateMenuItem(Caption: String);
var
MenuItem: TMenuItem;
begin
MenuItem := TMenuItem.Create(FPopupMenuButton);
FPopupMenuButton.Items.Add(MenuItem);
MenuItem.Caption := Caption;
MenuItem.OnClick := PopupClick;
end;
begin
// Create and config the PoppuMenu
if not Assigned(FPopupMenuButton) then
begin
// I like to use the statemant "with", but it does not function
FPopupMenuButton := TPopupMenu.Create(Self);
FPopupMenuButton.Name := 'SubPopupMenu';
FPopupMenuButton.SetSubComponent(True);
FPopupMenuButton.FreeNotification(Self);
CreateMenuItem('&New...');
CreateMenuItem('&Open...');
CreateMenuItem('&Delete...');
CreateMenuItem('-');
CreateMenuItem('Clear');
end;
end;
procedure TmrSuperCombo.PopupClick(Sender: TObject);
begin
case TMenuItem(Sender).MenuIndex of
0: InsertRecord(Self.Params);
1: OpenRecord(Self.Params);
2: if MsgBox('Delete [' + Text + '] ?', vbQuestion + vbYesNo) = mrYes then
DeleteRecord;
4: ClearValue;
end;
end;
procedure TmrSuperCombo.DoButtonUp(Index: Integer);
var
CursorPos: TPoint;
begin
if not Locked then
case Index of
1: begin
SetCommandButtons;
GetCursorPos(CursorPos);
FPopupMenuButton.Popup(CursorPos.X, CursorPos.Y);
end;
2: begin
SearchRecord;
end;
end;
EditButtonClick;
end;
procedure TmrSuperCombo.SetCommandButtons;
var
CommandButtonsList: String;
begin
CommandButtonsList := UpperCase(DataSetList.GetOptionalParam('CommandButtons'));
FPopupMenuButton.Items[0].Visible := (Pos('CBNEW', CommandButtonsList) > 0) and not DisableButtons and not Locked;
FPopupMenuButton.Items[1].Visible := (Pos('CBOPEN', CommandButtonsList) > 0) and not DisableButtons;
FPopupMenuButton.Items[2].Visible := (Pos('CBDELETE', CommandButtonsList) > 0) and not DisableButtons and not Locked;
FPopupMenuButton.Items[4].Visible := (Pos('CBCLEAR', CommandButtonsList) > 0) and not Locked;
FPopupMenuButton.Items[1].Enabled := (Trim(Text) <> '');
FPopupMenuButton.Items[2].Enabled := (Trim(Text) <> '');
end;
procedure TmrSuperCombo.InsertRecord(AParams: String);
var
NewSession: TmrSession;
NewDataSet: TClientDataSet;
Records : Integer;
NewKey : Variant;
begin
NewKey := -1;
NewSession := nil;
with TParentCustomFch(CreateForm(Self, FchClassName)) do
try
NewSession := Self.DataSetControl.CreateSession;
NewDataSet := NewSession.CreateDataSet(ConnectionSourceName, ProviderSourceName);
NewDataSet.Open;
Records := NewDataSet.RecordCount;
Init(Self.TraceControl, Self.DataSetControl, Self.UpdateControl, NewSession, NewDataSet, Self.FSystemUser, AParams);
Append;
ShowFch;
NewKey := NewDataSet.FieldByName(Properties.KeyFieldNames).Value;
if NewDataSet.RecordCount > Records then
begin
SetDBValues(NewDataSet);
RefreshDependentLookups;
end;
finally
Free;
NewSession.Terminate;
OpenListSource;
SetEditValue(NewKey);
end;
end;
procedure TmrSuperCombo.OpenRecord(AParams: String);
var
NewSession: TmrSession;
NewDataSet: TClientDataSet;
ChangedKey: Variant;
begin
ChangedKey := -1;
NewSession := nil;
with TParentCustomFch(CreateForm(Self, FchClassName)) do
try
NewSession := Self.DataSetControl.CreateSession;
NewDataSet := NewSession.CreateDataSet(ConnectionSourceName, ProviderSourceName);
NewDataSet.BeforeGetRecords := DoBeforeGetRecordsSource;
NewDataSet.Open;
Init(Self.TraceControl, Self.DataSetControl, Self.UpdateControl, NewSession, NewDataSet, Self.FSystemUser, AParams);
Open(AParams);
ShowFch;
ChangedKey := EditValue;
RefreshDependentLookups;
finally
Free;
NewSession.Terminate;
OpenListSource;
SetEditValue(ChangedKey);
end;
end;
procedure TmrSuperCombo.DeleteRecord;
begin
with DataSetList do
try
if Locate(Properties.KeyFieldNames, EditValue, []) then
begin
Delete;
if ApplyUpdates(0) = 0 then
RefreshDependentLookups;
end;
finally
ClearValue;
OpenListSource;
end;
end;
procedure TmrSuperCombo.SetConfigFch;
begin
if FFchClassName = '' then
FFchClassName := UpperCase(DataSetList.GetOptionalParam('FchClassName'));
if FConnectionSourceName = '' then
FConnectionSourceName := UpperCase(DataSetList.GetOptionalParam('ConnectionSourceName'));
if FProviderSourceName = '' then
FProviderSourceName := UpperCase(DataSetList.GetOptionalParam('ProviderSourceName'));
end;
procedure TmrSuperCombo.ClearValue;
begin
Self.Clear;
end;
procedure TmrSuperCombo.SetDBValues(DataSet: TDataSet);
begin
// para ser herdado
end;
procedure TmrSuperCombo.ApplyFilters(AFilter: String);
begin
if (DataSetList <> nil) then
begin
DataSetList.Filtered := False;
DataSetList.Filter := AFilter;
if AFilter <> '' then
DataSetList.Filtered := True;
end;
end;
procedure TmrSuperCombo.SetDependentLookUps(const Value: TmrDependentLookUps);
begin
FDependentLookUps.Assign(Value);
end;
procedure TmrSuperCombo.RefreshDependentLookups;
var
i: Integer;
begin
for i := 0 to Pred(FDependentLookUps.Count) do
FDependentLookUps[i].LookUp.OpenListSource;
end;
procedure TmrSuperCombo.SetSchClassName(const Value: String);
begin
FSchClassName := Value;
if (Value <> '') and (Properties.Buttons.Count = 2) then
begin
Properties.Buttons.Add;
Properties.Buttons[2].Kind := bkGlyph;
end;
end;
procedure TmrSuperCombo.SearchRecord;
var
NewKey : Variant;
SearchParam : String;
begin
NewKey := Null;
with TParentSearchForm(CreateForm(Self, SchClassName)) do
try
if Assigned(FOnStartSearch) then
FOnStartSearch(Self, SearchParam);
NewKey := Search(SearchParam);
finally
Free;
end;
if NewKey <> Null then
begin
SetDBValues(NewKey);
SetEditValue(NewKey);
end;
end;
procedure TmrSuperCombo.SetDBValues(AFieldValue: Variant);
begin
//Para ser herdado
end;
function TmrSuperCombo.GetFieldValue(AFieldName: String): Variant;
begin
Result := Null;
if FDataSetList.Locate(Properties.KeyFieldNames, EditValue, []) then
Result := FDataSetList.FieldByName(AFieldName).Value;
end;
{ TmrDBSuperCombo }
procedure TmrDBSuperCombo.ClearValue;
begin
inherited;
if DataBinding <> nil then
begin
DataBinding.DataSource.DataSet.Edit;
DataBinding.DataSource.DataSet.FieldByName(DataBinding.DataField).Clear;
end;
end;
procedure TmrDBSuperCombo.CMGetDataLink(var Message: TMessage);
begin
if not IsInplace then
Message.Result := Integer(TcxDBEditDataBinding(DataBinding).DataLink);
end;
function TmrDBSuperCombo.GetDataBinding: TcxDBTextEditDataBinding;
begin
Result := TcxDBTextEditDataBinding(FDataBinding);
end;
class function TmrDBSuperCombo.GetDataBindingClass: TcxEditDataBindingClass;
begin
Result := TcxDBEditDataBinding;
end;
procedure TmrDBSuperCombo.SetDataBinding(Value: TcxDBTextEditDataBinding);
begin
FDataBinding.Assign(Value);
end;
procedure TmrDBSuperCombo.SetDBValues(DataSet: TDataSet);
begin
if DataBinding <> nil then
begin
DataBinding.DataSource.Edit;
DataBinding.DataLink.Field.Value := DataSet.FieldByName(Properties.KeyFieldNames).AsString;
end;
end;
procedure TmrDBSuperCombo.SetDBValues(AFieldValue: Variant);
begin
inherited;
if DataBinding <> nil then
begin
DataBinding.DataSource.Edit;
DataBinding.DataLink.Field.Value := AFieldValue;
end;
end;
{ TmrDependentLookUps }
constructor TmrDependentLookUps.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
inherited Create(TmrDependentLookUp);
end;
function TmrDependentLookUps.GetItem(Index: Integer): TmrDependentLookUp;
begin
Result := TmrDependentLookUp(inherited GetItem(Index));
end;
function TmrDependentLookUps.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TmrDependentLookUps.SetItem(Index: Integer;
Value: TmrDependentLookUp);
begin
inherited SetItem(Index, Value);
end;
procedure TmrDependentLookUps.Update(Item: TCollectionItem);
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
{ TmrDependentLookUp }
constructor TmrDependentLookUp.Create(Collection: TCollection);
begin
inherited Create(Collection);
end;
end.
|
unit uprocessos;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Process,Math,uglobal,FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls;
type
{Class RunnableScripts }
{ RunnableScripts }
RunnableScripts = Class
private
args:TStringList;
exitCode : integer; //code exit program
exitStatus : integer; // signal of system kill process, segmentation fault ...
strError : TStringList;
debug: boolean;
public
strOut: TStringList;
ref_memo: TMemo;
procedure RunProcess();
procedure RunProcessAsConsole();
procedure RunProcessAsRoot();
procedure RunProcessAsRootNoConsole();
procedure RunProcessAsPoliceKit();
function getExitCode() : integer;
function getExitStatus():integer;
function getStrOut(): TstringList;
function getStrError(): TStringList ;
constructor Create (c_args:TStringList);
constructor Create(c_args: TStringList; flag_debug :boolean);
procedure setStrOut (ref_strout : TStringList);
end;
implementation
procedure RunnableScripts.RunProcessAsConsole();
var
hprocess: TProcess;
i : integer;
Begin
i := 0;
DetectXTerm(); //função importante! Detecta o tipo de emulador de terminal
try //tente executar o processo
hprocess := TProcess.Create(nil);
hprocess.Executable := '/bin/bash';
if ( self.args <> nil ) then begin
while (i < (args.Count) ) do
begin
write(args[i] + ' ');
hprocess.Parameters.Add(args[i]);
i := i + 1;
end;
writeln('');
// writeln('Exit CODE = ',hprocess.ExitCode,'EXIT_STATUS = ',hprocess.ExitStatus);
hprocess.Options:= hprocess.Options + [poWaitOnExit,poUsePipes,poNewConsole];
// hprocess.Options := hProcess.Options + [poWaitOnExit, poUsePipes, poNewConsole]; // poNewConsole é para terminais
hprocess.Execute; // Execute o comando
Self.exitCode:= hprocess.ExitCode;
Self.exitStatus:= hprocess.ExitStatus;
//Self.strError := TStringList.Create;
Self.strError.LoadFromStream(hprocess.Stderr);
Self.strError.SaveToFile('err.txt');
Self.strOut := TStringList.Create;
Self.strOut.LoadFromStream(hprocess.Output);
Self.strOut.SaveToFile('out.txt');
// writeln('Exit CODE = ',hprocess.ExitCode,'EXIT_STATUS = ',hprocess.ExitStatus);
//Sleep(2000);
end else
Writeln('args is null');
finally
hprocess.Free;
end;
end;
procedure RunnableScripts.RunProcess();
var
hprocess: TProcess;
i : integer;
Begin
i := 0;
DetectXTerm(); //função importante! Detecta o tipo de emulador de terminal
try //tente executar o processo
hprocess := TProcess.Create(nil);
hprocess.Executable := '/bin/bash';
if ( self.args <> nil ) then begin
while (i < (args.Count) ) do
begin
write(args[i] + ' ');
hprocess.Parameters.Add(args[i]);
i := i + 1;
end;
writeln('');
// writeln('Exit CODE = ',hprocess.ExitCode,'EXIT_STATUS = ',hprocess.ExitStatus);
hprocess.Options:= hprocess.Options + [poWaitOnExit,poUsePipes,poNoConsole];
// hprocess.Options := hProcess.Options + [poWaitOnExit, poUsePipes, poNewConsole]; // poNewConsole é para terminais
hprocess.Execute; // Execute o comando
Self.exitCode:= hprocess.ExitCode;
Self.exitStatus:= hprocess.ExitStatus;
//Self.strError := TStringList.Create;
Self.strError.LoadFromStream(hprocess.Stderr);
Self.strError.SaveToFile('err.txt');
Self.strOut := TStringList.Create;
Self.strOut.LoadFromStream(hprocess.Output);
Self.strOut.SaveToFile('out.txt');
// writeln('Exit CODE = ',hprocess.ExitCode,'EXIT_STATUS = ',hprocess.ExitStatus);
//Sleep(2000);
end else
Writeln('args is null');
finally
hprocess.Free;
end;
end;
constructor RunnableScripts.Create ( c_args : TStringList);
begin
//proc := c_proc;
Self.args := c_args;
Self.exitCode:= -1;
Self.exitStatus:= -1;
Self.strError:= TStringList.Create;
// Self.strOut := TStringList.Create;
Self.debug := false;
end;
constructor RunnableScripts.Create(c_args: TStringList; flag_debug: boolean);
begin
Self.args := c_args;
Self.debug := flag_debug;
Self.exitCode := -1;
Self.exitStatus:= -1;
Self.strError := nil;
Self.strOut := nil;
end;
procedure RunnableScripts.setStrOut(ref_strout : TStringList);
begin
Self.strOut :=ref_strout;
end;
{
Procedure para executar processos com o pkexec
PoliceKit
No entanto, use esta função apenas se não precisar de $DISPLAY
$XAUTHORITY
}
procedure RunnableScripts.RunProcessAsPoliceKit();
var
hprocess: TProcess;
i : integer;
begin
writeln('Running in root mode');
i := 0;
DetectXTerm();
try
hprocess := TProcess.Create(nil);
hprocess.Executable := 'pkexec'; //pkexec é o processo com super poderes
hprocess.Parameters.Add('/bin/bash');
if ( Self.args <> nil ) then begin //verifica se args não é nulo
while (i < (Self.args.Count) ) do begin
hprocess.Parameters.Add(args[i]); //adiciona cada um dos parametros de linha de comando
i := i + 1;
end;
if ( Self.debug = False ) then
hprocess.Options := hProcess.Options + [poWaitOnExit, poUsePipes, poNoConsole]
else
hprocess.Options := hProcess.Options + [poWaitOnExit, poUsePipes, poNewConsole];
hprocess.Execute;
Self.strError := TStringList.Create;
Self.strOut := TStringList.Create;
Self.exitCode:= hprocess.ExitCode;
Self.exitStatus:= hprocess.ExitStatus;
Self.strError.LoadFromStream(hprocess.Stderr);
Self.strOut.LoadFromStream(hprocess.Output);
if ( Self.debug = False ) then
begin
// if ( Self.strError <> nil ) then
Self.strError.SaveToFile('err.txt');
Self.strOut.SaveToFile('out.txt');
end;
//hprocess.Free;
end else
WriteLn('from from runasRoot : args is null');
finally
WriteLn('Terminei o processo');
hprocess.Free;
end;
end;
function RunnableScripts.getExitCode(): integer;
begin
Result:= Self.exitCode;
end;
function RunnableScripts.getExitStatus(): integer;
begin
Result := Self.exitStatus;
end;
function RunnableScripts.getStrOut(): TstringList;
begin
Result := Self.strOut;
end;
function RunnableScripts.getStrError(): TStringList;
begin
Result:= Self.strError;
end;
{
Procedimento para executar o processo em root
usando uma bridge (ponte)
}
procedure RunnableScripts.RunProcessAsRoot();
var
hprocess: TProcess;
i : integer;
begin
i := 0;
writeln('Run as bridge root');
DetectXTerm(); //função importante! Detecta o tipo de emulador de terminal
hprocess := TProcess.Create(nil);
hprocess.Executable := '/bin/bash';
hprocess.Parameters.Add(uglobal.BRIDGE_ROOT); //caminho do script bridge
hprocess.Parameters.Add('/bin/bash');
while (i < (args.Count) ) do begin
write(args[i] + ' ');
hprocess.Parameters.Add(args[i]);
i := i + 1;
end;
writeln('');
if ( Self.debug = False ) then
hprocess.Options := hProcess.Options + [poWaitOnExit, poUsePipes, poNoConsole]
else
hprocess.Options := hProcess.Options + [poWaitOnExit, poUsePipes, poNewConsole]; //poNewConsole é par terminais;
hprocess.Execute; // Execute o comando
if ( hprocess.Running = false ) then
writeln('Terminei de executar');
Self.exitCode:= hprocess.ExitCode;
Self.exitStatus:= hprocess.ExitStatus;
//Self.strError := TStringList.Create;
Self.strError.LoadFromStream(hprocess.Stderr);
Self.strError.SaveToFile('err.txt');
Self.strOut := TStringList.Create;
Self.strOut.LoadFromStream(hprocess.Output);
Self.strOut.SaveToFile('out.txt');
hprocess.Free;
end;
procedure RunnableScripts.RunProcessAsRootNoConsole();
var
hprocess: TProcess;
i : integer;
CharBuffer: array [0..511] of char;
p, ReadCount: integer;
strExt, strTemp: string;
begin
i := 0;
writeln('Run as bridge root');
DetectXTerm(); //função importante! Detecta o tipo de emulador de terminal
hprocess := TProcess.Create(nil);
hprocess.Executable := '/bin/bash';
hprocess.Parameters.Add(uglobal.BRIDGE_ROOT); //caminho do script bridge
hprocess.Parameters.Add('/bin/bash');
while (i < (args.Count) ) do begin
write(args[i] + ' ');
hprocess.Parameters.Add(args[i]);
i := i + 1;
end;
writeln('');
hprocess.Options := hProcess.Options + [poWaitOnExit, poUsePipes, poNoConsole]; // poNewConsole é para terminais
hprocess.Execute; // Execute o comando
Self.exitCode:= hprocess.ExitCode;
Self.exitStatus:= hprocess.ExitStatus;
while ( hprocess.Running ) do
begin
while (hprocess.Output.NumBytesAvailable > 0 ) do
begin
ReadCount := Min(512, hprocess.Output.NumBytesAvailable); //Read up to buffer, not more
hprocess.Output.Read(CharBuffer, ReadCount);
strTemp:= Copy(CharBuffer, 0, ReadCount);
end
end;
//Sleep(2000);
hprocess.Free;
end;
end.
|
unit uServiceOrderFinalize;
interface
uses
ADODB, uMRTraceControl, Contnrs, uDMServiceOrder;
type
TServiceOrderFinalize = class
private
FADOConnection : TADOConnection;
FTraceControl : TMRTraceControl;
FIDServiceOrder : Integer;
FSQLCommand : TADOCommand;
FIDUser : Integer;
FIDStore : Integer;
function UpdateserviceOrderItems : Boolean;
function UpdateServiceOrder : Boolean;
public
constructor Create(AADOConnection: TADOConnection; ATraceControl: TMrTraceControl);
destructor Destroy; Override;
property IDServiceOrder : Integer read FIDServiceOrder write FIDServiceOrder;
property IDUser : Integer read FIDUser write FIDUser;
property IDStore : Integer read FIDStore write FIDStore;
function ProccessServiceOrder(var AError : String) : Boolean;
end;
implementation
uses SysUtils;
{ TServiceOrderFinalize }
constructor TServiceOrderFinalize.Create(AADOConnection: TADOConnection;
ATraceControl: TMrTraceControl);
begin
FADOConnection := AADOConnection;
FTraceControl := ATraceControl;
FSQLCommand := TADOCommand.Create(nil);
FSQLCommand.Connection := FADOConnection;
end;
destructor TServiceOrderFinalize.Destroy;
begin
FreeAndNil(FSQLCommand);
inherited;
end;
function TServiceOrderFinalize.ProccessServiceOrder(var AError: String): Boolean;
begin
Result := False;
FTraceControl.TraceIn('TSaleFinalize.ProccessServiceOrder');
FADOConnection.BeginTrans;
try
//1 - Atualiza os campos do Service Order
UpdateServiceOrder;
//2 - Atualiza os itens do Service Order
UpdateserviceOrderItems;
FADOConnection.CommitTrans;
Result := True;
except
on E: Exception do
begin
FADOConnection.RollbackTrans;
Result := False;
AError := E.Message;
FTraceControl.SaveTrace(IDUser, AError, 'TSaleFinalize');
end;
end;
FTraceControl.TraceOut;
end;
function TServiceOrderFinalize.UpdateServiceOrder: Boolean;
begin
Result := False;
FTraceControl.TraceIn('TServiceOrderFinalize.UpdateServiceOrder');
try
with FSQLCommand do
begin
CommandText := 'UPDATE Ser_Serviceorder ' +
'SET SOCloseDate = :SOCloseDate, IDSOStatus = :IDSOStatus ' +
'WHERE IDServiceOrder = :IDServiceOrder';
Parameters.ParamByName('SOCloseDate').Value := Now;
Parameters.ParamByName('IDSOStatus').Value := SO_STATUS_CLOSE;
Parameters.ParamByName('IDServiceOrder').Value := IDServiceOrder;
Execute;
end;
except
on E: Exception do
raise Exception.Create('-100: ' + E.Message);
end;
FTraceControl.TraceOut;
end;
function TServiceOrderFinalize.UpdateserviceOrderItems: Boolean;
begin
Result := False;
FTraceControl.TraceIn('TServiceOrderFinalize.UpdateserviceOrderItems');
try
with FSQLCommand do
begin
CommandText := 'UPDATE Ser_SOItem ' +
'SET EndDate = :EndDate ' +
'WHERE IDServiceOrder = :IDServiceOrder AND EndDate IS NULL ';
Parameters.ParamByName('EndDate').Value := Now;
Parameters.ParamByName('IDServiceOrder').Value := IDServiceOrder;
Execute;
end;
except
on E: Exception do
raise Exception.Create('-101: ' + E.Message);
end;
FTraceControl.TraceOut;
end;
end.
|
unit Odontologia.Modelo.Agenda;
interface
uses
Data.DB,
SimpleDAO,
SimpleInterface,
SimpleQueryRestDW,
System.SysUtils,
Odontologia.Modelo.Estado.Cita,
Odontologia.Modelo.Estado.Cita.Interfaces,
Odontologia.Modelo.Medico,
Odontologia.Modelo.Medico.Interfaces,
Odontologia.Modelo.Conexion.RestDW,
Odontologia.Modelo.Agenda.Interfaces,
Odontologia.Modelo.Paciente,
Odontologia.Modelo.Paciente.Interfaces,
Odontologia.Modelo.Entidades.Agenda;
type
TModelAgenda = class(TInterfacedOBject, iModelAgenda)
private
FEntidad : TDAGENDA;
FDAO : iSimpleDao<TDAGENDA>;
FDataSource : TDataSource;
FMedico : iModelMedico;
FPaciente : iModelPaciente;
FEstadoCita : iModelEstadoCita;
public
constructor Create;
destructor Destroy; override;
class function New : iModelAgenda;
function Entidad : TDAGENDA; overload;
function Entidad(aEntidad: TDAGENDA) : iModelAgenda; overload;
function DAO : iSimpleDAO<TDAGENDA>;
function DataSource(aDataSource: TDataSource) : iModelAgenda;
function Medico : iModelMedico;
function Paciente : iModelPaciente;
function EstadoCita : iModelEstadoCita;
end;
implementation
{ TModelAgenda }
constructor TModelAgenda.Create;
begin
FEntidad := TDAGENDA.Create;
FDAO := TSimpleDAO<TDAGENDA>.New(TSimpleQueryRestDW<TDAGENDA>
.New(ModelConexion.RESTDWDataBase1));
FMedico := TModelMedico.New;
FPaciente := TModelPaciente.New;
FEstadoCita := TModelEstadoCita.New
end;
function TModelAgenda.DAO: iSimpleDao<TDAGENDA>;
begin
Result := FDAO;
end;
function TModelAgenda.DataSource(aDataSource: TDataSource): iModelAgenda;
begin
Result := Self;
FDataSource := aDataSource;
FDAO.DataSource(FDataSource);
end;
destructor TModelAgenda.Destroy;
begin
FreeAndNil(FEntidad);
inherited;
end;
function TModelAgenda.Entidad(aEntidad: TDAGENDA): iModelAgenda;
begin
Result := Self;
FEntidad := aEntidad;
end;
function TModelAgenda.EstadoCita: iModelEstadoCita;
begin
Result := FEstadoCita;
end;
function TModelAgenda.Medico: iModelMedico;
begin
Result := FMedico;
end;
function TModelAgenda.Entidad: TDAGENDA;
begin
Result := FEntidad;
end;
class function TModelAgenda.New: iModelAgenda;
begin
Result := Self.Create;
end;
function TModelAgenda.Paciente: iModelPaciente;
begin
Result := FPaciente ;
end;
end.
|
unit NodeRect;
interface
Uses
Classes, TaskNodeInfo, Graphics, Windows;
type
TDragBox = (dbNone,dbDrag,dbTopLeft,dbTopMid,dbTopRight,dbMidLeft,dbMidRight,dbBottomLeft,dbBottomMid,dbBottomRight,dbLink);
//TOnPaintEvent = procedure (Sender: TObject; Canvas: TCanvas; Rect: TRect) of object;
TRectBox = class(TObject)
private
FHasFocus: Boolean;
FWidth: Integer;
FHeight: Integer;
FTop: Integer;
FLeft: Integer;
FCaption: String;
FContent: TStrings;
FTaskInfo: TTaskNodeinfo;
FFrameColor:TColor;
FCanvas :TCanvas;
procedure SetContent(const Value: TStrings);
procedure SetHasFocus(const Value: Boolean);
procedure SetHeight(const Value: Integer);
procedure SetLeft(const Value: Integer);
procedure SetTop(const Value: Integer);
procedure SetWidth(const Value: Integer);
procedure SetTaskInfo(const Value: TTaskNodeinfo);
procedure SetFrameColor(const Value: TColor);
procedure DrawContent;
protected
Procedure Paint;
public
constructor Create(ACanvas:TCanvas);
destructor Destroy; override;
//Procedure Paint(Canvas:TCanvas);
published
Property FrameColor:TColor Read FFrameColor Write SetFrameColor Default clBlack;
Property Caption :String Read FCaption Write FCaption;
Property Content :TStrings Read FContent Write SetContent;
Property Left:Integer Read FLeft Write SetLeft;
Property Top:Integer read FTop Write SetTop;
Property Height:Integer Read FHeight Write SetHeight;
Property Width:Integer Read FWidth Write SetWidth;
Property HasFocus:Boolean Read FHasFocus Write SetHasFocus;
Property TaskInfo:TTaskNodeinfo Read FTaskInfo Write SetTaskInfo;
Property Canvas:TCanvas Read FCanvas;
end;
implementation
{ TRectBox }
constructor TRectBox.Create(ACanvas:TCanvas);
begin
inherited Create;
FContent := TStringList.Create;
FTaskInfo := TTaskNodeinfo.Create;
FCanvas := ACanvas;
end;
destructor TRectBox.Destroy;
begin
FContent.Free;
FTaskInfo.Free;
inherited Destroy;
end;
procedure TRectBox.Paint;
Const BOXSIZE = 5;
var
LHalfBox: Integer;
LRect: TRect;
LClient: TRect;
begin
LRect := Rect(Left,Top,Width+Left,Top+Height);
LHalfBox := (BOXSIZE div 2);
//Calculate Client area that does not intercept the drag boxes;
LRect.Left := LRect.Left + LHalfBox + 1;
LRect.Right := LRect.Right - LHalfBox - 1;
LRect.Top := LRect.Top - LHalfBox;
LRect.Bottom := LRect.Bottom - LHalfBox - 1;
//client Area as defined by the frame drawn
{
LClient.Left := LHalfBox;
LClient.Top := LHalfBox;
LClient.right := width-1 - LHalfBox;
LClient.Bottom := Height - 1 - LHalfBox;
}
LClient := LRect;
//draw the frame
Canvas.Brush.Color := clWhite;
Canvas.FillRect(LClient);
Canvas.Pen.Color := FFrameColor;
Canvas.MoveTo(LClient.Left,LClient.Top);
Canvas.LineTo(LClient.Right,LClient.Top);
Canvas.LineTo(LClient.Right,LClient.Bottom);
Canvas.LineTo(LClient.Left,LClient.Bottom);
Canvas.LineTo(LClient.Left,LClient.Top);
{
//Draw the drag boxes
if HasFocus then
Begin
Canvas.Brush.Color := clBlack;
Canvas.FillRect(rect(0,0,FBoxSize,FBoxSize));
Canvas.FillRect(rect((width div 2) - LHalfBox,0,(width div 2) - LHalfBox + FBoxSize,FBoxSize));
Canvas.FillRect(rect(width - FBoxSize,0,width,FBoxSize));
Canvas.FillRect(rect(width - FBoxSize,Height div 2 - LHalfBox,width,Height div 2 - LHalfBox + FBoxSize));
Canvas.FillRect(rect(width - FBoxSize,Height - FBoxSize,width,Height));
Canvas.FillRect(rect((width div 2) - LHalfBox,Height - FBoxSize,(width div 2) - LHalfBox + FBoxSize,Height));
Canvas.FillRect(rect(0,Height - FBoxSize,FBoxSize,Height));
Canvas.FillRect(rect(0,Height div 2 - LHalfBox,FBoxSize,Height div 2 - LHalfBox + FBoxSize));
end;
//Set the fixed font for the optional position information
if FShowPos and FHasFocus then
Canvas.Brush.style := bsClear;
//Draw caption content and des content
DrawContent;
}
end;
Procedure TRectBox.DrawContent;
Const
VSPACE = 5 ;
HSPACE = 5;
Var
UHAuto:Integer;
I:Integer;
Str:Pchar;
StrCount:Integer;
OutRect:TRect;
VerticallySpace :Integer;
SavePenWidth:Integer;
begin
{
if FHasFocus then
Canvas.Brush.Color := FActiveFrameColor
else
Canvas.Brush.Color := FPassiveFrameColor;
Canvas.Pen.Color := FTextColor;
VerticallySpace := VSPACE + Canvas.Pen.Width;
SavePenWidth := Canvas.Pen.Width;
UHAuto := VerticallySpace;
OutRect:= Rect(HSPACE,UHAuto,Width-HSPACE,Height-VerticallySpace);
UHAuto := UHAuto +VerticallySpace+ DrawText(Canvas.Handle,Pchar(FCaption),Length(FCaption),OutRect,
DT_CENTER or DT_WORDBREAK );
if UHAuto > (Height - VerticallySpace) then Exit;
Canvas.Pen.Width := 1;
Canvas.MoveTo(0,UHAuto);
Canvas.LineTo(Width,UHAuto);
Inc(UHAuto,VSPACE+1);
Canvas.Pen.Width := SavePenWidth;
StrCount := FContent.Count -1;
I := 0;
while (UHAuto < (Height - VerticallySpace)) and (I <= StrCount) do
begin
Str := Pchar(FContent.Strings[I]);
if Str = ContentCompartSymbol then
Begin
Inc(UHAuto,3);
Canvas.Pen.Width := 1;
Canvas.MoveTo(0,UHAuto);
Canvas.LineTo(Width,UHAuto);
Inc(UHAuto,VSPACE+1);
Canvas.Pen.Width := SavePenWidth;
end
else
Begin
OutRect:= Rect(HSPACE,UHAuto,Width-HSPACE,Height-VerticallySpace);
UHAuto := UHAuto +DrawText(Canvas.Handle,Str,Length(Str),OutRect, DT_WORDBREAK );
end;
Inc(I);
end;
}
end;
procedure TRectBox.SetContent(const Value: TStrings);
begin
FContent.Assign(Value);
end;
procedure TRectBox.SetFrameColor(const Value: TColor);
begin
FFrameColor := Value;
end;
procedure TRectBox.SetHasFocus(const Value: Boolean);
begin
if FHasFocus = Value then Exit;
FHasFocus := Value;
end;
procedure TRectBox.SetHeight(const Value: Integer);
begin
if FHeight = Value then Exit;
FHeight := Value;
end;
procedure TRectBox.SetLeft(const Value: Integer);
begin
if FLeft = Value then Exit;
FLeft := Value;
end;
procedure TRectBox.SetTaskInfo(const Value: TTaskNodeinfo);
begin
FTaskInfo.Assign(Value);
Caption := Value.Title;
Content.Text := Value.Describe;
end;
procedure TRectBox.SetWidth(const Value: Integer);
begin
if FWidth = Value then Exit;
FWidth := Value;
end;
procedure TRectBox.SetTop(const Value: Integer);
begin
if FTop = Value then Exit;
FTop := Value;
end;
end.
|
unit Allgemein.Types;
interface
const
cCSIDL_DESKTOP = $0000; { <desktop> }
cCSIDL_INTERNET = $0001; { Internet Explorer (icon on desktop) }
cCSIDL_PROGRAMS = $0002; { Start Menu\Programs }
cCSIDL_CONTROLS = $0003; { My Computer\Control Panel }
cCSIDL_PRINTERS = $0004; { My Computer\Printers }
cCSIDL_PERSONAL = $0005; { My Documents. This is equivalent to CSIDL_MYDOCUMENTS in XP and above }
cCSIDL_FAVORITES = $0006; { <user name>\Favorites }
cCSIDL_STARTUP = $0007; { Start Menu\Programs\Startup }
cCSIDL_RECENT = $0008; { <user name>\Recent }
cCSIDL_SENDTO = $0009; { <user name>\SendTo }
cCSIDL_BITBUCKET = $000a; { <desktop>\Recycle Bin }
cCSIDL_STARTMENU = $000b; { <user name>\Start Menu }
cCSIDL_MYDOCUMENTS = $000c; { logical "My Documents" desktop icon }
cCSIDL_MYMUSIC = $000d; { "My Music" folder }
cCSIDL_MYVIDEO = $000e; { "My Video" folder }
cCSIDL_DESKTOPDIRECTORY = $0010; { <user name>\Desktop }
cCSIDL_DRIVES = $0011; { My Computer }
cCSIDL_NETWORK = $0012; { Network Neighborhood (My Network Places) }
cCSIDL_NETHOOD = $0013; { <user name>\nethood }
cCSIDL_FONTS = $0014; { windows\fonts }
cCSIDL_TEMPLATES = $0015;
cCSIDL_COMMON_STARTMENU = $0016; { All Users\Start Menu }
cCSIDL_COMMON_PROGRAMS = $0017; { All Users\Start Menu\Programs }
cCSIDL_COMMON_STARTUP = $0018; { All Users\Startup }
cCSIDL_COMMON_DESKTOPDIRECTORY = $0019; { All Users\Desktop }
cCSIDL_APPDATA = $001a; { <user name>\Application Data }
cCSIDL_PRINTHOOD = $001b; { <user name>\PrintHood }
cCSIDL_LOCAL_APPDATA = $001c; { <user name>\Local Settings\Application Data (non roaming) }
cCSIDL_ALTSTARTUP = $001d; { non localized startup }
cCSIDL_COMMON_ALTSTARTUP = $001e; { non localized common startup }
cCSIDL_COMMON_FAVORITES = $001f;
cCSIDL_INTERNET_CACHE = $0020;
cCSIDL_COOKIES = $0021;
cCSIDL_HISTORY = $0022;
cCSIDL_COMMON_APPDATA = $0023; { All Users\Application Data }
cCSIDL_WINDOWS = $0024; { GetWindowsDirectory() }
cCSIDL_SYSTEM = $0025; { GetSystemDirectory() }
cCSIDL_PROGRAM_FILES = $0026; { C:\Program Files }
cCSIDL_MYPICTURES = $0027; { C:\Program Files\My Pictures }
cCSIDL_PROFILE = $0028; { USERPROFILE }
cCSIDL_SYSTEMX86 = $0029; { x86 system directory on RISC }
cCSIDL_PROGRAM_FILESX86 = $002a; { x86 C:\Program Files on RISC }
cCSIDL_PROGRAM_FILES_COMMON = $002b; { C:\Program Files\Common }
cCSIDL_PROGRAM_FILES_COMMONX86 = $002c; { x86 C:\Program Files\Common on RISC }
cCSIDL_COMMON_TEMPLATES = $002d; { All Users\Templates }
cCSIDL_COMMON_DOCUMENTS = $002e; { All Users\Documents }
cCSIDL_COMMON_ADMINTOOLS = $002f; { All Users\Start Menu\Programs\Administrative Tools }
cCSIDL_ADMINTOOLS = $0030; { <user name>\Start Menu\Programs\Administrative Tools }
cCSIDL_CONNECTIONS = $0031; { Network and Dial-up Connections }
cCSIDL_COMMON_MUSIC = $0035; { All Users\My Music }
cCSIDL_COMMON_PICTURES = $0036; { All Users\My Pictures }
cCSIDL_COMMON_VIDEO = $0037; { All Users\My Video }
cCSIDL_RESOURCES = $0038; { Resource Directory }
cCSIDL_RESOURCES_LOCALIZED = $0039; { Localized Resource Directory }
cCSIDL_COMMON_OEM_LINKS = $003a; { Links to All Users OEM specific apps }
cCSIDL_CDBURN_AREA = $003b; { USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning }
cCSIDL_COMPUTERSNEARME = $003d; { Computers Near Me (computered from Workgroup membership) }
cCSIDL_PROFILES = $003e;
type
TAusgabeArt = (c_KeineAusgabe, c_Drucken, c_Mail, c_PDF);
implementation
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado à tabela [NFCE_MOVIMENTO]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
Albert Eije (T2Ti.COM)
@version 2.0
*******************************************************************************}
unit NfceMovimentoController;
interface
uses
Classes, SysUtils, Windows, Forms, Controller,
VO, NfceMovimentoVO;
type
TNfceMovimentoController = class(TController)
private
public
class function ConsultaObjeto(pFiltro: String): TNfceMovimentoVO;
class function Altera(pObjeto: TNfceMovimentoVO): Boolean;
class function Exclui(pId: Integer): Boolean;
class function IniciaMovimento(pObjeto: TNfceMovimentoVO): TNfceMovimentoVO;
end;
implementation
uses T2TiORM,
NfceCaixaVO, EmpresaVO, NfceTurnoVO, NfceOperadorVO,
NfceFechamentoVO, NfceSuprimentoVO, NfceSangriaVO;
var
ObjetoLocal: TNfceMovimentoVO;
class function TNfceMovimentoController.ConsultaObjeto(pFiltro: String): TNfceMovimentoVO;
var
Filtro: String;
begin
try
Result := TNfceMovimentoVO.Create;
Result := TNfceMovimentoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
Result.NfceCaixaVO := TNfceCaixaVO(TT2TiORM.ConsultarUmObjeto(Result.NfceCaixaVO, 'ID='+IntToStr(Result.IdNfceCaixa), True));
Result.EmpresaVO := TEmpresaVO(TT2TiORM.ConsultarUmObjeto(Result.EmpresaVO, 'ID='+IntToStr(Result.IdEmpresa), True));
Result.NfceTurnoVO := TNfceTurnoVO(TT2TiORM.ConsultarUmObjeto(Result.NfceTurnoVO, 'ID='+IntToStr(Result.IdNfceTurno), True));
Result.NfceOperadorVO := TNfceOperadorVO(TT2TiORM.ConsultarUmObjeto(Result.NfceOperadorVO, 'ID='+IntToStr(Result.IdNfceOperador), True));
Result.NfceGerenteVO := TNfceOperadorVO(TT2TiORM.ConsultarUmObjeto(Result.NfceOperadorVO, 'ID='+IntToStr(Result.IdGerenteSupervisor), True));
Filtro := 'ID_NFCE_MOVIMENTO = ' + IntToStr(Result.Id);
Result.ListaNfceFechamentoVO := TListaNfceFechamentoVO(TT2TiORM.Consultar(TNfceFechamentoVO.Create, Filtro, True));
Result.ListaNfceSuprimentoVO := TListaNfceSuprimentoVO(TT2TiORM.Consultar(TNfceSuprimentoVO.Create, Filtro, True));
Result.ListaNfceSangriaVO := TListaNfceSangriaVO(TT2TiORM.Consultar(TNfceSangriaVO.Create, Filtro, True));
finally
end;
end;
class function TNfceMovimentoController.Altera(pObjeto: TNfceMovimentoVO): Boolean;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
finally
end;
end;
class function TNfceMovimentoController.Exclui(pId: Integer): Boolean;
begin
try
ObjetoLocal := TNfceMovimentoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal);
end;
end;
class function TNfceMovimentoController.IniciaMovimento(pObjeto: TNfceMovimentoVO): TNfceMovimentoVO;
var
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
Result := ConsultaObjeto('ID = ' + IntToStr(UltimoID));
finally
end;
end;
end.
|
unit TpDbEdit;
interface
uses
Windows, SysUtils, Classes, Controls, Graphics,
Types,
ThWebControl, ThTag, ThDbEdit,
TpControls, TpDb;
type
TTpDbEdit = class(TThCustomDbEdit)
private
FDataSource: TTpDataSource;
FOnGenerate: TTpEvent;
FOnInput: TTpEvent;
protected
procedure SetDataSource(const Value: TTpDataSource);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure Tag(inTag: TThTag); override;
published
property FieldName;
property DataSource: TTpDataSource read FDataSource write SetDataSource;
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
property OnInput: TTpEvent read FOnInput write FOnInput;
end;
implementation
{ TTpDbEdit }
procedure TTpDbEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FDataSource) then
begin
FDataSource := nil;
Data.DataSource := nil;
end;
end;
procedure TTpDbEdit.SetDataSource(const Value: TTpDataSource);
begin
TpSetDataSource(Self, Value, FDataSource, Data);
{
if FDataSource <> nil then
FDataSource.RemoveFreeNotification(Self);
//
FDataSource := Value;
//
if FDataSource <> nil then
FDataSource.FreeNotification(Self);
//
if FDataSource <> nil then
Data.DataSource := FDataSource.DataSource
else
Data.DataSource := nil;
}
end;
procedure TTpDbEdit.Tag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Add('tpClass', 'TTpDbEdit');
Add('tpName', Name);
if (DataSource <> nil) and not DataSource.DesignOnly then
Add('tpDataSource', DataSource.Name);
Add('tpField', FieldName);
Add('tpOnSubmit', OnInput);
Add('tpOnGenerate', OnGenerate);
end;
end;
end.
|
unit FullScreen;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls;
type
TfmFullScreen = class(TForm)
imgPhoto: TImage;
procedure FormShow(Sender: TObject);
procedure imgPhotoDblClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmFullScreen: TfmFullScreen;
implementation
{$R *.dfm}
procedure TfmFullScreen.FormShow(Sender: TObject);
begin
Width:=Screen.Width;
Height:=Screen.Height;
end;
procedure TfmFullScreen.imgPhotoDblClick(Sender: TObject);
begin
Hide;
end;
procedure TfmFullScreen.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key=VK_ESCAPE Then Hide;
end;
end.
|
unit uFrmInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Buttons;
const
SV_SERVER = '#SRV#=';
SV_DATABASE = '#DB#=';
SV_USER = '#USER#=';
SV_PASSWORD = '#PW#=';
SV_WIN_LOGIN = '#WIN#=';
SV_USE_NETLIB = '#NLIB#=';
type
TFrmInfo = class(TForm)
Label1: TLabel;
Label4: TLabel;
edtServer: TEdit;
edtDatabase: TEdit;
GroupBox1: TGroupBox;
lbPW: TLabel;
edtUser: TEdit;
edtPassword: TEdit;
rbWin: TRadioButton;
rbSQL: TRadioButton;
chkUseLib: TCheckBox;
btnAbort: TBitBtn;
btnOK: TBitBtn;
pnlServer: TPanel;
Image1: TImage;
lbDisplay: TLabel;
Bevel1: TBevel;
private
{ Private declarations }
public
{ Public declarations }
function Start(StrConn:String):String;
function DecodeStr(StrEncoded:String):String;
end;
implementation
uses uEncryptFunctions, uParamFunctions;
{$R *.dfm}
function TFrmInfo.DecodeStr(StrEncoded:String):String;
begin
Result := DecodeServerInfo(StrEncoded, 'Server', CIPHER_TEXT_STEALING, FMT_UU);
end;
function TFrmInfo.Start(StrConn:String):String;
var
sPW, sUser, sDBAlias, sServer, sWinLogin, sLib : String;
begin
if StrConn <> '' then
begin
StrConn := DecodeStr(StrConn);
edtServer.Text := ParseParam(StrConn, SV_SERVER);
edtDatabase.Text := ParseParam(StrConn, SV_DATABASE);
edtUser.Text := ParseParam(StrConn, SV_USER);
edtPassword.Text := ParseParam(StrConn, SV_PASSWORD);
rbSQL.Checked := (ParseParam(StrConn, SV_WIN_LOGIN)[1]='N');
chkUseLib.Checked := (ParseParam(StrConn, SV_USE_NETLIB)[1]='Y');
end;
ShowModal;
if (ModalResult = mrAbort) then
begin
Result := '';
Exit;
end;
//Encriptografar os dados;
sServer := SV_SERVER +edtServer.Text +';';
sDBAlias := SV_DATABASE +edtDatabase.Text+';';
sUser := SV_USER +edtUser.Text +';';
sPW := SV_PASSWORD +edtPassword.Text+';';
if rbWin.Checked then
sWinLogin := SV_WIN_LOGIN + 'Y;'
else
sWinLogin := SV_WIN_LOGIN + 'N;';
if chkUseLib.Checked then
sLib := SV_USE_NETLIB + 'Y;'
else
sLib := SV_USE_NETLIB + 'N;';
Result := EncodeServerInfo(sServer+sDBAlias+sUser+sPW+sWinLogin+sLib, 'Server', CIPHER_TEXT_STEALING, FMT_UU);
//Create Connection
end;
end.
|
unit uShtatBonusFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Buttons, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridTableView,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridDBTableView, cxGrid, uShtatData,
uActionControl, ActnList;
type
TfrmShtatBonus = class(TFrame)
Panel1: TPanel;
AddButton: TSpeedButton;
ModifyButton: TSpeedButton;
DeleteButton: TSpeedButton;
RefreshButton: TSpeedButton;
ShtatBonusView: TcxGridDBTableView;
BonusGridLevel1: TcxGridLevel;
BonusGrid: TcxGrid;
StyleRepository: TcxStyleRepository;
stBackground: TcxStyle;
stContent: TcxStyle;
stContentEven: TcxStyle;
stContentOdd: TcxStyle;
stFilterBox: TcxStyle;
stFooter: TcxStyle;
stGroup: TcxStyle;
stGroupByBox: TcxStyle;
stHeader: TcxStyle;
stInactive: TcxStyle;
stIncSearch: TcxStyle;
stIndicator: TcxStyle;
stPreview: TcxStyle;
stSelection: TcxStyle;
stHotTrack: TcxStyle;
qizzStyle: TcxGridTableViewStyleSheet;
CancelButton: TSpeedButton;
ActionControl: TqFActionControl;
ActionList1: TActionList;
AddAction: TAction;
ModifyAction: TAction;
DeleteAction: TAction;
RefreshAction: TAction;
ShtatBonusViewRAISE_NAME: TcxGridDBColumn;
ShtatBonusViewPERCENT: TcxGridDBColumn;
ShtatBonusViewSUMMA: TcxGridDBColumn;
ShtatBonusViewSMETA_KOD: TcxGridDBColumn;
ShtatBonusViewPPS_SMETA_KOD: TcxGridDBColumn;
ShtatBonusViewDATE_BEG: TcxGridDBColumn;
ShtatBonusViewDATE_END: TcxGridDBColumn;
ShtatBonusViewID_SHTAT_BONUS: TcxGridDBColumn;
ShtatBonusViewID_RAISE: TcxGridDBColumn;
ShtatBonusViewIS_PERCENT: TcxGridDBColumn;
ShtatBonusViewKOD_SM: TcxGridDBColumn;
ShtatBonusViewKOD_SM_PPS: TcxGridDBColumn;
ShtatBonusViewSMETA_TITLE: TcxGridDBColumn;
ShtatBonusViewPPS_SMETA_TITLE: TcxGridDBColumn;
ShtatBonusViewBONUS_SUM: TcxGridDBColumn;
ShtatBonusViewBONUS_PPS: TcxGridDBColumn;
ShtatBonusViewBONUS_MAIN: TcxGridDBColumn;
procedure ActionControlBeforePrepare(Sender: TObject; Form: TForm);
procedure ShtatBonusViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
Id_ShtatRas_Smet: Integer;
DM: TdmShtatView;
public
procedure Prepare(DM: TdmShtatView; Id_ShtatRas_Smet: Integer);
end;
implementation
{$R *.dfm}
uses uShtatBonusAdd, uShtatConsts;
procedure TfrmShtatBonus.Prepare(DM: TdmShtatView; Id_ShtatRas_Smet: Integer);
begin
Self.DM := DM;
Self.Id_ShtatRas_Smet := Id_ShtatRas_Smet;
DM.BonusSelect.Close;
DM.BonusSelect.ParamByName('Id_ShtatRas_Smet').AsInteger := Id_ShtatRas_Smet;
DM.BonusSelect.ParamByName('Actual_Date').AsDate := ActualDate;
DM.BonusSelect.Open;
DM.BonusSelect.First;
ShtatBonusView.DataController.DataSource := DM.BonusSource;
//ShtatBonusView.DataController.CreateAllItems;
ActionControl.SelectDataSet := DM.BonusSelect;
ActionControl.Database := DM.DB;
ActionControl.AddKeys := IntToStr(Id_ShtatRas_Smet);
end;
procedure TfrmShtatBonus.ActionControlBeforePrepare(Sender: TObject;
Form: TForm);
begin
if Form is TfmShtatBonusAdd then
begin
(Form as TfmShtatBonusAdd).DM := DM;
(Form as TfmShtatBonusAdd).Id_ShtatRas_Smet := Id_ShtatRas_Smet;
end;
end;
procedure TfrmShtatBonus.ShtatBonusViewKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (ord(Key) = ord('Z')) and (ssAlt in Shift) and (ssShift in Shift)
and (ssCtrl in Shift) then
try
ShowMessage('Id_Shtat_Bonus: ' +
IntToStr(DM.BonusSelect['Id_Shtat_Bonus']));
except
end;
end;
end.
|
unit AddTagModelView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmPromoItem, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxEdit, DB, cxDBData, DBClient, ADODB, siComp, siLangRT, Buttons,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxClasses, cxControls, cxGridCustomView, cxGrid, Mask, SuperComboADO,
StdCtrls, LblEffct, ExtCtrls;
type
TfrmAddTagModel = class(TFrmPromoItem)
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btSaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btCloseClick(Sender: TObject);
private
{ Private declarations }
sysRegistry: TClientDataset;
procedure Save;
public
{ Public declarations }
cdsItemsToDropDown: TClientDataset;
function start(AID, AIDPromoItem, APromoType :Integer): Boolean;
end;
implementation
uses uDM, SysRegistryDAO;
{$R *.dfm}
procedure TfrmAddTagModel.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
// inherited;
end;
procedure TfrmAddTagModel.btSaveClick(Sender: TObject);
begin
// inherited;
save;
end;
procedure TfrmAddTagModel.Save;
begin
cdsItemsToDropDown := cdsPromoItems;
// save state component to system_registry
try
if ( not sysRegistry.FieldByName('Id').IsNull ) then begin
dm.updateTagModelRegistryAttName(intToStr(cbTypeSearch.itemIndex), sysRegistry.fieldByName('Id').Value);
end;
except
on e: Exception do begin
raise e.Create(format('Erro found: %s', [e.Message]));
end;
end;
end;
procedure TfrmAddTagModel.FormCreate(Sender: TObject);
begin
// inherited;
end;
procedure TfrmAddTagModel.FormDestroy(Sender: TObject);
begin
// inherited;
end;
procedure TfrmAddTagModel.FormShow(Sender: TObject);
var
attName: String;
begin
// inherited;
// read from system_registry
attName := 'TagModel.cbTypeSearch.ItemIndex';
sysRegistry := dm.getTagModelRegistryAttName(attName);
if (trim(attName) = trim(sysRegistry.fieldByName('AttributeName').asstring) ) then
cbTypeSearch.ItemIndex := strToInt(sysRegistry.fieldByName('AttributeValue').Value)
else
dm.insertTagModelRegistryAttName(intToStr(cbTypeSearch.itemIndex));
end;
function TfrmAddTagModel.start(AID, AIDPromoItem,
APromoType: Integer): Boolean;
begin
lblUserName.Caption := DM.fUser.UserName;
lblUserName.Left := Label15.Left + Label15.Width + 3;
lblUserName.Top := Label15.Top;
cdsPromoItems.CreateDataSet;
ShowModal;
ModalResult := mrOk;
end;
procedure TfrmAddTagModel.btCloseClick(Sender: TObject);
begin
//inherited;
freeAndNil(sysRegistry);
close;
end;
end.
|
namespace proholz.xsdparser;
interface
type
AttributeValidations = public partial class
private
constructor;
// *
// * Validates if a given String is a positive {@link Integer}. Throws an exception if the {@link String} isn't a
// * positive {@link Integer}.
// * @param elementName The element name containing the field with the {@link Integer} value.
// * @param attributeName The name of the attribute with the {@link Integer} type.
// * @param value The value to be parsed to a {@link Integer} object.
// * @return The parsed {@link Integer} value.
class method validatePositiveInteger(elementName: String; attributeName: String; value: String): Integer;
// *
// * Validates if a given {@link String} is a {@link Double}. Throws an exception if the {@link String} isn't a
// * {@link Double}.
// * @param elementName The element name containing the field with the {@link Double} value.
// * @param attributeName The name of the attribute with the type {@link Double}.
// * @param value The value to be parsed to a {@link Double} object.
// * @return The parsed {@link Double} value.
class method validateDouble(elementName: String; attributeName: String; value: String): Double;
class method attributeMissingMessage(elementName: String; attributeName: String): String;
assembly
// *
// * Checks if the maxOccurs attribute is unbounded or an {@link Integer} value.
// * @param value The possible maxOccurs value.
// * @param elementName The name of the element containing the maxOccurs attribute.
// * @return The validated maxOccurs value.
class method maxOccursValidation(elementName: String; value: String): String;
// *
// * Validates if a given String is a non negative {@link Integer}. Throws an exception if the {@link String} isn't a non
// * negative {@link Integer}.
// * @param elementName The element name containing the field with the {@link Integer} value.
// * @param attributeName The name of the attribute with the {@link Integer}.
// * @param value The value to be parsed to a {@link Integer} object.
// * @return The parsed {@link Integer} value.
class method validateNonNegativeInteger(elementName: String; attributeName: String; value: String): Integer;
// *
// * Obtains the default value of the {@link XsdSchema#attributeFormDefault} attribute by iterating in the element tree
// * by going from {@link XsdAbstractElement#parent} to {@link XsdAbstractElement#parent} until reaching the top level
// * element.
// * @param parent The parent of the element requesting the default form value.
// * @return The default value for the form attribute.
class method getFormDefaultValue(parent: XsdAbstractElement): String;
// *
// * Obtains the default value of the {@link XsdSchema#finalDefault} attribute by iterating in the element tree by
// * going from {@link XsdAbstractElement#parent} to {@link XsdAbstractElement#parent} until reaching the top level
// * element.
// * @param parent The parent of the element requesting the default final value.
// * @return The default value for the final attribute.
class method getFinalDefaultValue(parent: XsdAbstractElement): String;
// *
// * Obtains the default value of the {@link XsdSchema#blockDefault} attribute by iterating in the element tree by
// * going from {@link XsdAbstractElement#parent} to {@link XsdAbstractElement#parent} until reaching the top level
// * element.
// * @param parent The parent of the element requesting the default block value.
// * @return The default value for the block attribute.
class method getBlockDefaultValue(parent: XsdAbstractElement): String;
public
// *
// * Validates if a given String is a non negative {@link Integer}. Throws an exception if the {@link String} isn't a
// * non negative {@link Integer}.
// * @param elementName The element name containing the field with the {@link Integer} value.
// * @param attributeName The name of the attribute with the {@link Integer}.
// * @param value The value to be parsed to a {@link Integer} object.
// * @return The parsed {@link Integer} value.
class method validateRequiredNonNegativeInteger(elementName: String; attributeName: String; value: String): Integer;
// *
// * Validates if a given String is a positive {@link Integer}. Throws an exception if the {@link String} isn't a
// * positive {@link Integer}.
// * @param elementName The element name containing the field with the {@link Integer} value.
// * @param attributeName The name of the attribute with the {@link Integer} type.
// * @param value The value to be parsed to a {@link Integer} object.
// * @return The parsed {@link Integer} value.
class method validateRequiredPositiveInteger(elementName: String; attributeName: String; value: String): Integer;
class method validateBoolean(value: String): Boolean;
// *
// * Validates if a given {@link String} is a {@link Double}. Throws an exception if the {@link String} isn't a {@link Double}.
// * @param elementName The element name containing the field with the {@link Double} value.
// * @param attributeName The name of the attribute with the type {@link Double}.
// * @param value The value to be parsed to a {@link Double} object.
// * @return The parsed {@link Double} value.
class method validateRequiredDouble(elementName: String; attributeName: String; value: String): Double;
end;
implementation
constructor AttributeValidations;
begin
end;
class method AttributeValidations.maxOccursValidation(elementName: String; value: String): String;
begin
if value.Equals('unbounded') then begin
exit value;
end;
validateNonNegativeInteger(elementName, XsdAbstractElement.MAX_OCCURS_TAG, value);
exit value;
end;
class method AttributeValidations.validateNonNegativeInteger(elementName: String; attributeName: String; value: String): Integer;
begin
try
var intValue: Integer := Convert.ToInt32(value);
if intValue < 0 then begin
raise new ParsingException('The ' + elementName + ' ' + attributeName + ' attribute should be a non negative integer. (greater or equal than 0)');
end;
exit intValue;
except
on e: Exception do begin
raise new ParsingException('The ' + elementName + ' ' + attributeName + ' attribute should be a non negative integer.');
end;
end;
end;
class method AttributeValidations.validateRequiredNonNegativeInteger(elementName: String; attributeName: String; value: String): Integer;
begin
if value = nil then begin
raise new ParsingException(attributeMissingMessage(elementName, attributeName));
end;
exit validateNonNegativeInteger(elementName, attributeName, value);
end;
class method AttributeValidations.validatePositiveInteger(elementName: String; attributeName: String; value: String): Integer;
begin
try
var intValue: Integer := Convert.ToInt32(value);
if intValue ≤ 0 then begin
raise new ParsingException('The ' + elementName + ' ' + attributeName + ' attribute should be a positive integer. (greater than 0)');
end;
exit intValue;
except
on e: Exception do begin
raise new ParsingException('The ' + elementName + ' ' + attributeName + ' attribute should be a positive integer.');
end;
end;
end;
class method AttributeValidations.validateRequiredPositiveInteger(elementName: String; attributeName: String; value: String): Integer;
begin
if value = nil then begin
raise new ParsingException(attributeMissingMessage(elementName, attributeName));
end;
exit validatePositiveInteger(elementName, attributeName, value);
end;
class method AttributeValidations.validateBoolean(value: String): Boolean;
begin
exit Convert.ToBoolean(value);
end;
class method AttributeValidations.validateDouble(elementName: String; attributeName: String; value: String): Double;
begin
try
exit Convert.ToDoubleInvariant(value);
except
on e: Exception do begin
raise new ParsingException('The ' + elementName + ' ' + attributeName + ' attribute should be a numeric value.');
end;
end;
end;
class method AttributeValidations.validateRequiredDouble(elementName: String; attributeName: String; value: String): Double;
begin
if value = nil then begin
raise new ParsingException(attributeMissingMessage(elementName, attributeName));
end;
exit validateDouble(elementName, attributeName, value);
end;
class method AttributeValidations.getFormDefaultValue(parent: XsdAbstractElement): String;
begin
if parent = nil then begin
exit nil;
end;
if parent is XsdSchema then begin
exit XsdSchema(parent).getElementFormDefault();
end;
exit getFormDefaultValue(parent.getParent());
end;
class method AttributeValidations.getFinalDefaultValue(parent: XsdAbstractElement): String;
begin
if parent = nil then begin
exit nil;
end;
if parent is XsdSchema then begin
exit XsdSchema(parent).getFinalDefault();
end;
exit getFinalDefaultValue(parent.getParent());
end;
class method AttributeValidations.getBlockDefaultValue(parent: XsdAbstractElement): String;
begin
if parent = nil then begin
exit nil;
end;
if parent is XsdSchema then begin
exit XsdSchema(parent).getBlockDefault();
end;
exit getBlockDefaultValue(parent.getParent());
end;
class method AttributeValidations.attributeMissingMessage(elementName: String; attributeName: String): String;
begin
exit 'The ' + elementName + ' ' + attributeName + ' is required to have a value attribute.';
end;
end. |
unit uHttp;
interface
uses Classes, WinINet,Sysutils,windows, IDURI;
procedure Get(url: string;res: TStream); overload;
procedure Post(url, data:string;res:TStream); overload;
function Get(url: string): string; overload;
function Post(url, data: string): string; overload;
implementation
function Get(url: string): string;
var
s: TStringStream;
begin
s := TStringStream.Create('');
try
Get(url, s);
result := s.DataString;
finally
s.Free;
end;
end;
function Post(url, data: string): string;
var
s: TStringStream;
begin
s := TStringStream.Create('');
try
Get(url, s);
result := s.DataString;
finally
s.Free;
end;
end;
procedure Post(url, data:string;res:TStream);
var
hInt,hConn,hreq:HINTERNET;
buffer:PChar;
dwRead, dwFlags:cardinal;
port: Word;
uri: TIdURI;
proto, host, path: string;
begin
uri := TIdURI.Create(url);
host := uri.Host;
path := uri.Path + uri.Document;
proto := uri.Protocol;
uri.Free;
if UpperCase(proto) = 'HTTPS' then
begin
port := INTERNET_DEFAULT_HTTPS_PORT;
dwFlags := INTERNET_FLAG_SECURE;
end
else
begin
port := INTERNET_INVALID_PORT_NUMBER;
dwFlags := INTERNET_FLAG_RELOAD;
end;
hInt := InternetOpen('Delphi',INTERNET_OPEN_TYPE_PRECONFIG,nil,nil,0);
hConn := InternetConnect(hInt,PChar(host),port,nil,nil,INTERNET_SERVICE_HTTP,0,0);
hreq := HttpOpenRequest(hConn,'POST',PChar(Path),'HTTP/1.1',nil,nil,dwFlags,0);
GetMem(buffer, 65536);
if HttpSendRequest(hReq,nil,0,PChar(data),Length(data)) then
begin
dwRead:=0;
repeat
InternetReadFile(hreq,buffer,65536,dwRead);
if dwRead<>0 then
res.Write(buffer^, dwRead);
until dwRead=0;
end;
InternetCloseHandle(hreq);
InternetCloseHandle(hConn);
InternetCloseHandle(hInt);
FreeMem(buffer);
end;
procedure Get(url: string;res: TStream);
var
hInt,hUrl:HINTERNET;
buffer:PChar;
dwRead:cardinal;
begin
GetMem(buffer, 65536);
hInt := InternetOpen('Delphi',INTERNET_OPEN_TYPE_PRECONFIG,nil,nil,0);
dwRead:=0;
hurl:=InternetOpenUrl(hInt,PChar(url),nil,0,INTERNET_FLAG_RELOAD,0);
repeat
InternetReadFile(hUrl,buffer,1000,dwRead);
if dwRead<>0 then
res.Write(buffer^, dwRead);
until dwRead=0;
InternetCloseHandle(hUrl);
InternetCloseHandle(hInt);
FreeMem(buffer);
end;
end.
|
unit Amazon.Storage.Service.Config;
interface
uses Amazon.Storage.Service.API, Amazon.Storage.Service.Types;
type
TAmazonStorageServiceConfig = class
private
FAccessKey: string;
FSecretKey: string;
FRegion: TAmazonRegion;
FMainBucketName: string;
FProtocol: TAmazonProtocol;
public
property AccessKey: string read FAccessKey write FAccessKey;
property SecretKey: string read FSecretKey write FSecretKey;
property Region: TAmazonRegion read FRegion write FRegion;
property Protocol: TAmazonProtocol read FProtocol write FProtocol;
property MainBucketName: string read FMainBucketName write FMainBucketName;
function GetNewStorage: TAmazonStorageService;
class function NewInstance: TObject; override;
class function GetInstance: TAmazonStorageServiceConfig;
end;
var
AmazonStorageServiceConfig: TAmazonStorageServiceConfig;
implementation
function TAmazonStorageServiceConfig.GetNewStorage: TAmazonStorageService;
var
LAmazonConnectionInfo: TAmazonConnectionInfo;
begin
LAmazonConnectionInfo := TAmazonConnectionInfo.Create(nil);
LAmazonConnectionInfo.Protocol := FProtocol.GetValue;
LAmazonConnectionInfo.UseDefaultEndpoints := False;
LAmazonConnectionInfo.AccountName := FAccessKey;
LAmazonConnectionInfo.AccountKey := FSecretKey;
LAmazonConnectionInfo.Region := FRegion;
Result := TAmazonStorageService.Create(LAmazonConnectionInfo);
end;
class function TAmazonStorageServiceConfig.GetInstance: TAmazonStorageServiceConfig;
begin
Result := TAmazonStorageServiceConfig.Create;
end;
class function TAmazonStorageServiceConfig.NewInstance: TObject;
begin
if not (Assigned(AmazonStorageServiceConfig)) then
begin
AmazonStorageServiceConfig := TAmazonStorageServiceConfig(inherited NewInstance);
AmazonStorageServiceConfig.Protocol := TAmazonProtocol.http;
end;
Result := AmazonStorageServiceConfig;
end;
initialization
finalization
if Assigned(AmazonStorageServiceConfig) then
AmazonStorageServiceConfig.Free;
end.
|
unit eaterRun;
interface
type
TEaterRunner=class(TObject)
private
NewFeedEvent:THandle;
StartRun,LastRun,LastDone:TDateTime;
LastFeedCount,LastPostCount:integer;
//configuration
SaveData:boolean;
RunContinuous,SpecificFeedID:integer;
FeedLike:string;
procedure FlagNewFeed(Sender:TObject);
function CheckRunDone:boolean;
public
procedure RunFeedEater;
constructor Create;
end;
implementation
uses Windows, SysUtils, Classes, eaterSanitize, eaterFeeds, eaterUtils, LibPQ;
{ TEaterRunner }
constructor TEaterRunner.Create;
var
s,t:string;
i:integer;
begin
inherited Create;
//defaults
SaveData:=false;
RunContinuous:=0;
SpecificFeedID:=0;
FeedLike:='';
NewFeedEvent:=0;
StartRun:=UtcNow;//?
LastFeedCount:=0;
LastPostCount:=0;
//process command line arguments
for i:=1 to ParamCount do
begin
s:=ParamStr(i);
if s='/s' then SaveData:=true
else
if s='/n' then SpecificFeedID:=Specific_NewFeeds
else
if s='/c' then RunContinuous:=15
else
if StartsWithX(s,'/c',t) then RunContinuous:=StrToInt(t)
else
if StartsWithX(s,'/f',t) then SpecificFeedID:=StrToInt(t)
else
if StartsWithX(s,'/g',t) then FeedLike:=t
else
if s='/x' then SpecificFeedID:=Specific_AllFeeds
else
raise Exception.Create('Unknown parameter #'+IntToStr(i));
end;
//other initialization
SanitizeInit;
s:=ExtractFilePath(ParamStr(0))+'blacklist.txt';
if FileExists(s) then BlackList.LoadFromFile(s);
end;
procedure TEaterRunner.FlagNewFeed(Sender: TObject);
begin
if NewFeedEvent<>0 then
SetEvent(NewFeedEvent);
end;
procedure TEaterRunner.RunFeedEater;
var
f:TFeedEater;
r:TFeedEatResult;
n:boolean;
begin
repeat
LastRun:=UtcNow;
n:=SpecificFeedID=0;
f:=TFeedEater.Create;
try
IUnknown(f)._AddRef;//prevent destruction on first _Release
f.DoCleanup;
f.DoAutoUnread;
f.SaveData:=SaveData;
f.ForceLoadAll:=SpecificFeedID=Specific_AllFeeds;
f.OnFeedURLUpdate:=FlagNewFeed;
r:=f.DoUpdateFeeds(SpecificFeedID,FeedLike,(RunContinuous+5)/1440.0);
LastDone:=UtcNow;
LastFeedCount:=r.FeedCount;
LastPostCount:=r.PostCount;
if n then f.RenderGraphs;
finally
IUnknown(f)._Release;//f.Free;
end;
//DoAnalyze;
until CheckRunDone;
end;
function TEaterRunner.CheckRunDone: boolean;
var
RunNext,d:TDateTime;
i,id:integer;
h:array[0..1] of THandle;
b:TInputRecord;
c:cardinal;
checking:boolean;
c0,c1:AnsiChar;
begin
if RunContinuous=0 then
Result:=true
else
begin
RunNext:=LastRun+RunContinuous/1440.0;
SpecificFeedID:=0;//only once
id:=0;
d:=UtcNow;
while d<RunNext do
begin
i:=Round((RunNext-d)*86400.0);
if id=0 then
Write(Format(#13'Waiting %.2d:%.2d ',[i div 60,i mod 60]))
else
Write(Format(#13'Waiting %.2d:%.2d ? %d ',[i div 60,i mod 60,id]));
//TODO: check std-in?
//Result:=Eof(Input);
Sleep(1000);//?
d:=UtcNow;
if NewFeedEvent=0 then
NewFeedEvent:=CreateEvent(nil,true,false,'Global\FeederEaterNewFeed');
checking:=true;
c1:=#0;
h[0]:=GetStdHandle(STD_INPUT_HANDLE);
h[1]:=NewFeedEvent;
while checking do
case WaitForMultipleObjects(2,@h[0],false,0) of
WAIT_OBJECT_0://STD_INPUT_HANDLE
begin
if not ReadConsoleInput(h[0],b,1,c) then
RaiseLastOSError;
if (c<>0) and (b.EventType=KEY_EVENT) and b.Event.KeyEvent.bKeyDown then
begin
c0:=c1;
c1:=b.Event.KeyEvent.AsciiChar;
case c1 of
's'://skip
begin
Writeln(#13'Manual skip ');
d:=RunNext;
checking:=false;
end;
'n'://skip + new
begin
Writeln(#13'Skip + new feeds ');
d:=RunNext;
SpecificFeedID:=Specific_NewFeeds;
checking:=false;
end;
'x'://skip + run all
begin
Writeln(#13'Skip + all feeds ');
d:=RunNext;
SpecificFeedID:=Specific_AllFeeds;
checking:=false;
end;
{
'a'://analyze on next
if NextAnalyze then
begin
NextAnalyze:=false;
Writeln(#13'Analyze after next load: disabled');
end
else
begin
NextAnalyze:=true;
Writeln(#13'Analyze after next load: enabled');
end;
}
'i'://reset instagram
if c0='i' then
begin
Writeln(#13'Reset Instagram timers');
InstagramLastTC:=GetTickCount-InstagramIntervalMS;
InstagramFailed:=0.0;
end
else
begin
Writeln(#13'Instagram timers: (press "i" again to reset)');
Writeln(' Instagram last (UTC) '+DateTimeToStr(UtcNow-
cardinal(GetTickCount-InstagramLastTC)/MSecsPerDay));
if InstagramFailed<>0.0 then
Writeln(' Instagram failed (UTC) '+DateTimeToStr(InstagramFailed));
end;
'0'..'9':
id:=id*10+(byte(c1) and $F);
'c'://clear
id:=0;
#8:
id:=id div 10;
'f'://feed
if id=0 then
begin
Writeln(#13'No feed id entered ');
end
else
begin
Writeln(#13'Skip + feed #'+IntToStr(id)+' ');
d:=RunNext;
SpecificFeedID:=id;
checking:=false;
end;
#13:
if id=0 then
if c0=#13 then
begin
Writeln(#13'Manual skip ');
d:=RunNext;
checking:=false;
end
else
begin
Writeln(#13'Press enter again to skip wait');
//TODO: list of commands?
end
else
begin
Writeln(#13'Skip + feed #'+IntToStr(id)+' ');
d:=RunNext;
SpecificFeedID:=id;
checking:=false;
end;
'd'://diagnostics
begin
Writeln(#13'Diagnostics: ');
Writeln(' Running since (UTC) '+DateTimeToStr(StartRun));
Writeln(' Last load (UTC) '+DateTimeToStr(LastRun));
i:=Round((LastDone-LastRun)*86400.0);
Writeln(Format(' %d posts from %d feeds (%d''%d")',
[LastPostCount,LastFeedCount,i div 60,i mod 60]));
//TODO: more?
end;
'v'://version
begin
Writeln(#13'Versions: ');
//Writeln(SelfVersion);
i:=PQlibVersion;
Writeln(Format('PQlibVersion: %d.%d',[i div 10000,i mod 10000]));
if PGVersion<>'' then
Writeln('PostgreSQL version: '+PGVersion);
end;
'q'://quit
begin
Writeln(#13'User abort ');
raise Exception.Create('User abort');
end;
else
Writeln(#13'Unknown code "'+c1+'"');
end;
end;
end;
WAIT_OBJECT_0+1://NewFeed event
begin
ResetEvent(h[1]);
Writeln(#13'Signal from front-end: new feeds ');
d:=RunNext;
SpecificFeedID:=Specific_NewFeeds;
checking:=false;
end;
else
checking:=false;
end;
end;
Writeln(#13'>>> '+FormatDateTime('yyyy-mm-dd hh:nn:ss',d));
Result:=false;
end;
end;
end.
|
unit uPrKKlass_VL_Edit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxControls, cxContainer, cxEdit, cxLabel,
StdCtrls, cxButtons, ActnList, ExtCtrls,AArray;
type
TFormPrKKlass_VL_Edit = class(TForm)
ImageSpravEdit: TImage;
ActionListKlassSpravEdit: TActionList;
ActionOK: TAction;
ActionCansel: TAction;
cxButtonOK: TcxButton;
cxButtonCansel: TcxButton;
cxLabelFormCaption: TcxLabel;
cxButtonCloseForm: TcxButton;
procedure FormShow(Sender: TObject);
procedure cxLabelFormCaptionMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ActionCanselExecute(Sender: TObject);
private
Layout: array[0.. KL_NAMELENGTH] of char;
public
VLLangEdit :integer;
DataVL: TAArray;
procedure inicCaption;virtual;
constructor Create(aOwner: TComponent;aDataVL :TAArray);overload;
end;
var
FormPrKKlass_VL_Edit: TFormPrKKlass_VL_Edit;
implementation
uses
uPrK_Resources,uConstants;
{$R *.dfm}
constructor TFormPrKKlass_VL_Edit.Create(aOwner: TComponent;
aDataVL: TAArray);
begin
DataVL :=aDataVL;
VLLangEdit:=SelectLanguage;
inherited Create(aOwner);
cxLabelFormCaption.Top :=0;
inicCaption;
end;
procedure TFormPrKKlass_VL_Edit.FormShow(Sender: TObject);
begin
{422-урк, 409-англ, 419-рус}
LoadKeyboardLayout( StrCopy(Layout,nLayoutLang[VLLangEdit]),KLF_ACTIVATE);
end;
procedure TFormPrKKlass_VL_Edit.inicCaption;
begin
ActionOK.Caption :=nActiont_OK[VLLangEdit];
ActionCansel.Caption :=nActiont_Cansel[VLLangEdit];
ActionOK.Hint :=nHintActiont_OK[VLLangEdit];
ActionCansel.Hint :=nHintActiont_Cansel[VLLangEdit];
end;
procedure TFormPrKKlass_VL_Edit.cxLabelFormCaptionMouseDown(
Sender: TObject; Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
const SC_DragMove = $F012;
begin
ReleaseCapture;
perform(WM_SysCommand, SC_DragMove, 0);
end;
procedure TFormPrKKlass_VL_Edit.ActionCanselExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls,
SDUForms, SDUGraphics;
type
TForm1 = class(TSDUForm)
Image_Original: TImage;
Image_Flip_None: TImage;
Image_Flip_H: TImage;
Image_Flip_V: TImage;
Image_Flip_HV: TImage;
Image_Rotate_0: TImage;
Image_Rotate_90: TImage;
Image_Rotate_180: TImage;
Image_Rotate_270: TImage;
pbLoad: TButton;
OpenDialog1: TOpenDialog;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Image_Grayscale: TImage;
Label12: TLabel;
Label13: TLabel;
pnlSplitOne: TPanel;
pnlSplitTwo: TPanel;
pnlSplitThree: TPanel;
procedure pbLoadClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
procedure DemoImage(filename: string);
procedure DemoImage_Flip(filename: string; flip: TImageFlip; dispImage: TImage);
procedure DemoImage_Rotate(filename: string; rotate: TImageRotate; dispImage: TImage);
procedure DemoImage_Grayscale(filename: string; dispImage: TImage);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
const
// Files containing test images
TEST_IMAGE_FILE_pf1bit = 'TestImages\pf1bit.bmp';
TEST_IMAGE_FILE_pf4bit = 'TestImages\pf4bit.bmp';
TEST_IMAGE_FILE_pf8bit = 'TestImages\pf8bit.bmp';
TEST_IMAGE_FILE_pf24bit = 'TestImages\pf24bit.bmp';
procedure TForm1.DemoImage(filename: string);
begin
Image_Original.Picture.Bitmap.LoadFromFile(filename);
DemoImage_Flip(filename, ifNone, Image_Flip_None);
DemoImage_Flip(filename, ifHorizontal, Image_Flip_H);
DemoImage_Flip(filename, ifVertical, Image_Flip_V);
DemoImage_Flip(filename, ifBoth, Image_Flip_HV);
DemoImage_Rotate(filename, rot0, Image_Rotate_0);
DemoImage_Rotate(filename, rot90, Image_Rotate_90);
DemoImage_Rotate(filename, rot180, Image_Rotate_180);
DemoImage_Rotate(filename, rot270, Image_Rotate_270);
DemoImage_Grayscale(filename, Image_Grayscale);
end;
procedure TForm1.DemoImage_Flip(filename: string; flip: TImageFlip; dispImage: TImage);
var
t: TBitmap;
begin
t:= TBitmap.Create();
try
t.LoadFromFile(filename);
SDUImageFlip(t, flip);
dispImage.Picture.Assign(t);
finally
t.Free();
end;
end;
procedure TForm1.DemoImage_Rotate(filename: string; rotate: TImageRotate; dispImage: TImage);
var
t: TBitmap;
begin
t:= TBitmap.Create();
try
t.LoadFromFile(filename);
SDUImageRotate(t, rotate);
dispImage.Picture.Assign(t);
finally
t.Free();
end;
end;
procedure TForm1.DemoImage_Grayscale(filename: string; dispImage: TImage);
var
t: TBitmap;
begin
t:= TBitmap.Create();
try
t.LoadFromFile(filename);
SDUImageGrayscale(t);
dispImage.Picture.Assign(t);
finally
t.Free();
end;
end;
procedure TForm1.pbLoadClick(Sender: TObject);
begin
if OpenDialog1.Execute() then
begin
DemoImage(OpenDialog1.Filename);
end;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
pnlSplitOne.Height := 3;
pnlSplitOne.Caption := '';
pnlSplitOne.bevelouter := bvLowered;
pnlSplitTwo.Height := 3;
pnlSplitTwo.Caption := '';
pnlSplitTwo.bevelouter := bvLowered;
pnlSplitThree.Height := 3;
pnlSplitThree.Caption := '';
pnlSplitThree.bevelouter := bvLowered;
self.caption := Application.Title;
// Load and demo some initial imagef
DemoImage(TEST_IMAGE_FILE_pf24bit);
end;
END.
|
unit ibSHDDLCommentatorActions;
interface
uses
SysUtils, Classes, Menus,
SHDesignIntf, ibSHDesignIntf;
type
TibSHDDLCommentatorPaletteAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDDLCommentatorFormAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDDLCommentatorToolbarAction_ = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDDLCommentatorToolbarAction_Run = class(TibSHDDLCommentatorToolbarAction_)
end;
TibSHDDLCommentatorToolbarAction_Pause = class(TibSHDDLCommentatorToolbarAction_)
end;
TibSHDDLCommentatorToolbarAction_Refresh = class(TibSHDDLCommentatorToolbarAction_)
end;
implementation
uses
ibSHConsts,
ibSHDDLCommentatorFrm;
{ TibSHDDLCommentatorPaletteAction }
constructor TibSHDDLCommentatorPaletteAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallPalette;
Category := Format('%s', ['Tools']);
Caption := Format('%s', ['DDL Commentator']);
// ShortCut := TextToShortCut('Shift+Ctrl+F4');
end;
function TibSHDDLCommentatorPaletteAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID);
end;
procedure TibSHDDLCommentatorPaletteAction.EventExecute(Sender: TObject);
begin
Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHDDLCommentator, EmptyStr);
end;
procedure TibSHDDLCommentatorPaletteAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDDLCommentatorPaletteAction.EventUpdate(Sender: TObject);
begin
Enabled := Assigned(Designer.CurrentDatabase) and
(Designer.CurrentDatabase as ISHRegistration).Connected and
SupportComponent(Designer.CurrentDatabase.BranchIID);
end;
{ TibSHDDLCommentatorFormAction }
constructor TibSHDDLCommentatorFormAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallForm;
Caption := SCallDescriptions;
SHRegisterComponentForm(IibSHDDLCommentator, Caption, TibSHDDLCommentatorForm);
end;
function TibSHDDLCommentatorFormAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDDLCommentator);
end;
procedure TibSHDDLCommentatorFormAction.EventExecute(Sender: TObject);
begin
Designer.ChangeNotification(Designer.CurrentComponent, Caption, opInsert);
end;
procedure TibSHDDLCommentatorFormAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDDLCommentatorFormAction.EventUpdate(Sender: TObject);
begin
FDefault := Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, Caption);
end;
{ TibSHDDLCommentatorToolbarAction_ }
constructor TibSHDDLCommentatorToolbarAction_.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
Caption := '-'; // Separator
if Self is TibSHDDLCommentatorToolbarAction_Run then Tag := 1;
if Self is TibSHDDLCommentatorToolbarAction_Pause then Tag := 2;
if Self is TibSHDDLCommentatorToolbarAction_Refresh then Tag := 3;
case Tag of
1:
begin
Caption := Format('%s', ['Run']);
ShortCut := TextToShortCut('Ctrl+Enter');
SecondaryShortCuts.Add('F9');
end;
2:
begin
Caption := Format('%s', ['Stop']);
ShortCut := TextToShortCut('Ctrl+BkSp');
end;
3:
begin
Caption := Format('%s', ['Refresh']);
ShortCut := TextToShortCut('F5');
end;
end;
if Tag <> 0 then Hint := Caption;
end;
function TibSHDDLCommentatorToolbarAction_.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDDLCommentator);
end;
procedure TibSHDDLCommentatorToolbarAction_.EventExecute(Sender: TObject);
begin
case Tag of
// Run
1: (Designer.CurrentComponentForm as ISHRunCommands).Run;
// Pause
2: (Designer.CurrentComponentForm as ISHRunCommands).Pause;
// Refresh
3: (Designer.CurrentComponentForm as ISHRunCommands).Refresh;
end;
end;
procedure TibSHDDLCommentatorToolbarAction_.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDDLCommentatorToolbarAction_.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDescriptions) then
begin
Visible := True;
case Tag of
// Separator
0: ;
// Run
1: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun;
// Pause
2: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause;
// Refresh
3: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRefresh;
end;
end else
Visible := False;
end;
end.
|
unit UProprietarioUnidadeController;
interface
uses
Classes, SQLExpr, SysUtils, Generics.Collections, DBXJSON, DBXCommon,
ConexaoBD,
UPessoasVO, UController, DBClient, DB, UCondominioVO, UProprietarioUnidadeVO,
UPessoasCOntroller, UCondominioController, UUnidadeController, UUnidadeVO;
type
TProprietarioUnidadeController = class(TController<TProprietarioUnidadeVO>)
private
public
function ConsultarPorId(id: integer): TProprietarioUnidadeVO;
procedure ValidarDados(Objeto:TProprietarioUnidadeVO);override;
end;
implementation
uses
UDao, Constantes, Vcl.Dialogs;
function TProprietarioUnidadeController.ConsultarPorId(id: integer): TProprietarioUnidadeVO;
var
P: TProprietarioUnidadeVO;
pessoaController : TPessoasController;
begin
P := TDAO.ConsultarPorId<TProprietarioUnidadeVO>(id);
pessoaController := TPessoasController.Create;
if (P <> nil) then
begin
p.PessoaVo := pessoacontroller.ConsultarPorId(p.idPessoa);
end;
pessoaController.Free;
result := P;
end;
procedure TProprietarioUnidadeController.ValidarDados(
Objeto: TProprietarioUnidadeVO);
var
query, data, idProprietario : string;
listaProprietario :TObjectList<TProprietarioUnidadeVO>;
UnidadeVo : TUnidadeVo;
unidadeController : TUnidadeController;
begin
data := DateToStr(Objeto.dtInicio);
idProprietario := IntToStr(Objeto.idProprietarioUnidade);
unidadeController := TUnidadeController.Create;
UnidadeVo := UnidadeController.ConsultarPorId(Objeto.IdUnidade);
Query := ' dtInicio = ' +QuotedStr(Data) + 'and idProprietarioUnidade <> '+QuotedStr(idProprietario) + 'and ProprietarioUnidade.idunidade = ' + IntToStr(UnidadeVo.idUnidade);
listaProprietario := self.Consultar(query);
if (listaProprietario.Count > 0) then
raise Exception.Create('Ja existe Proprietário informado nessa data');
end;
begin
end.
|
unit nosodebug;
{
Nosodebug 1.2
December 20th, 2022
Unit to implement debug functionalities on noso project apps.
}
{$mode ObjFPC}{$H+}
INTERFACE
uses
Classes, SysUtils;
type
Tperformance = Record
tag : string;
Start : int64;
Average : int64;
Max : int64;
Min : int64;
Count : int64;
Total : int64;
end;
TLogND = record
tag : string;
Count : integer;
ToDisk : boolean;
Filename : string;
end;
TCoreManager = record
ThName : string;
ThStart : int64;
ThLast : int64;
end;
TFileManager = Record
FiType : string;
FiFile : string;
FiPeer : string;
FiLast : int64;
end;
TProcessCopy = array of TCoreManager;
TFileMCopy = array of TFileManager;
Procedure BeginPerformance(Tag:String);
Function EndPerformance(Tag:String):int64;
Procedure CreateNewLog(LogName: string; LogFileName:String = '');
Procedure AddLineToDebugLog(LogTag,NewLine : String);
Function GetLogLine(LogTag:string;out LineContent:string):boolean;
Procedure AddNewOpenThread(ThName:String;TimeStamp:int64);
Procedure UpdateOpenThread(ThName:String;TimeStamp:int64);
Procedure CloseOpenThread(ThName:String);
Function GetProcessCopy():TProcessCopy;
Procedure AddFileProcess(FiType, FiFile, FiPeer:String;TimeStamp:int64);
Function CloseFileProcess(FiType, FiFile, FiPeer:String;TimeStamp:int64):int64;
Function GetFileProcessCopy():TFileMCopy;
var
ArrPerformance : array of TPerformance;
NosoDebug_UsePerformance : boolean = false;
ArrNDLogs : Array of TLogND;
ArrNDCSs : array of TRTLCriticalSection;
ArrNDSLs : array of TStringList;
ArrProcess : Array of TCoreManager;
CS_ThManager : TRTLCriticalSection;
ArrFileMgr : Array of TFileManager;
CS_FileManager : TRTLCriticalSection;
IMPLEMENTATION
{$REGION Performance}
{Starts a performance measure}
Procedure BeginPerformance(Tag:String);
var
counter : integer;
NewData : TPerformance;
Begin
if not NosoDebug_UsePerformance then exit;
for counter := 0 to high(ArrPerformance) do
begin
if Tag = ArrPerformance[counter].tag then
begin
ArrPerformance[counter].Start:=GetTickCount64;
Inc(ArrPerformance[counter].Count);
exit;
end;
end;
NewData := default(TPerformance);
NewData.tag :=tag;
NewData.Min :=99999;
NewData.Start :=GetTickCount64;
NewData.Count :=1;
Insert(NewData,ArrPerformance,length(ArrPerformance));
End;
{Ends a performance}
Function EndPerformance(Tag:String):int64;
var
counter : integer;
duration : int64 = 0;
Begin
result := 0;
if not NosoDebug_UsePerformance then exit;
for counter := 0 to high(ArrPerformance) do
begin
if tag = ArrPerformance[counter].tag then
begin
duration :=GetTickCount64-ArrPerformance[counter].Start;
ArrPerformance[counter].Total := ArrPerformance[counter].Total+Duration;
ArrPerformance[counter].Average:=ArrPerformance[counter].Total div ArrPerformance[counter].Count;
if duration>ArrPerformance[counter].Max then
ArrPerformance[counter].Max := duration;
if duration < ArrPerformance[counter].Min then
ArrPerformance[counter].Min := duration;
break;
end;
end;
Result := duration;
End;
{$ENDREGION}
{$REGION Logs}
{private: verify that the file for the log exists}
Procedure InitializeLogFile(Filename:String);
var
LFile : textfile;
Begin
if not fileexists(Filename) then
begin
TRY
Assignfile(LFile, Filename);
rewrite(LFile);
Closefile(LFile);
EXCEPT on E:Exception do
END; {Try}
end;
End;
{private: if enabled, saves the line to the log file}
Procedure SaveTextToDisk(TextLine, Filename:String);
var
LFile : textfile;
IOCode : integer;
Begin
Assignfile(LFile, Filename);
{$I-}Append(LFile){$I+};
IOCode := IOResult;
If IOCode = 0 then
begin
TRY
Writeln(LFile, TextLine);
Except on E:Exception do
END; {Try}
Closefile(LFile);
end
else if IOCode = 5 then
{$I-}Closefile(LFile){$I+};
End;
{creates a new block and assigns an optional file to save it}
Procedure CreateNewLog(LogName: string; LogFileName:String = '');
var
NewData : TLogND;
Begin
NewData := Default(TLogND);
NewData.tag:=Uppercase(Logname);
NewData.Filename:=LogFileName;
SetLength(ArrNDCSs,length(ArrNDCSs)+1);
InitCriticalSection(ArrNDCSs[length(ArrNDCSs)-1]);
SetLEngth(ArrNDSLs,length(ArrNDSLs)+1);
ArrNDSLs[length(ArrNDSLs)-1] := TStringlist.Create;
if LogFileName <> '' then
begin
InitializeLogFile(LogFileName);
NewData.ToDisk:=true;
end;
Insert(NewData,ArrNDLogs,length(ArrNDLogs));
End;
{Adds one line to the specified log}
Procedure AddLineToDebugLog(LogTag,NewLine : String);
var
counter : integer;
Begin
for counter := 0 to length(ArrNDLogs)-1 do
begin
if ArrNDLogs[counter].tag = Uppercase(LogTag) then
begin
EnterCriticalSection(ArrNDCSs[counter]);
ArrNDSLs[counter].Add(NewLine);
Inc(ArrNDLogs[counter].Count);
LeaveCriticalSection(ArrNDCSs[counter]);
end;
end;
End;
{Retireves the oldest line in the specified log, assigning value to LineContent}
Function GetLogLine(LogTag:string;out LineContent:string):boolean;
var
counter : integer;
Begin
Result:= False;
For counter := 0 to length(ArrNDLogs)-1 do
begin
if ArrNDLogs[counter].tag = Uppercase(LogTag) then
begin
if ArrNDSLs[counter].Count>0 then
begin
EnterCriticalSection(ArrNDCSs[counter]);
LineContent := ArrNDSLs[counter][0];
Result := true;
ArrNDSLs[counter].Delete(0);
if ArrNDLogs[counter].ToDisk then SaveTextToDisk(LineContent,ArrNDLogs[counter].Filename);
LeaveCriticalSection(ArrNDCSs[counter]);
break;
end;
end;
end;
End;
{Private: Free all data at close}
Procedure FreeAllLogs;
var
counter : integer;
Begin
for counter := 0 to length(ArrNDLogs)-1 do
begin
ArrNDSLs[counter].Free;
DoneCriticalsection(ArrNDCSs[counter]);
end;
End;
{$ENDREGION}
{$REGION Thread manager}
Procedure AddNewOpenThread(ThName:String;TimeStamp:int64);
var
NewValue : TCoreManager;
Begin
NewValue := Default(TCoreManager);
NewValue.ThName := ThName;
NewValue.ThStart := TimeStamp;
NewValue.ThLast := TimeStamp;
EnterCriticalSection(CS_ThManager);
Insert(NewValue,ArrProcess,Length(ArrProcess));
LeaveCriticalSection(CS_ThManager);
End;
Procedure UpdateOpenThread(ThName:String;TimeStamp:int64);
var
counter : integer;
Begin
EnterCriticalSection(CS_ThManager);
for counter := 0 to High(ArrProcess) do
begin
if UpperCase(ArrProcess[counter].ThName) = UpperCase(ThName) then
begin
ArrProcess[counter].ThLast:=TimeStamp;
Break;
end;
end;
LeaveCriticalSection(CS_ThManager);
End;
Procedure CloseOpenThread(ThName:String);
var
counter : integer;
Begin
EnterCriticalSection(CS_ThManager);
for counter := 0 to High(ArrProcess) do
begin
if UpperCase(ArrProcess[counter].ThName) = UpperCase(ThName) then
begin
Delete(ArrProcess,Counter,1);
Break;
end;
end;
LeaveCriticalSection(CS_ThManager);
End;
Function GetProcessCopy():TProcessCopy;
Begin
Setlength(Result,0);
EnterCriticalSection(CS_ThManager);
Result := copy(ArrProcess,0,length(ArrProcess));
LeaveCriticalSection(CS_ThManager);
End;
{$ENDREGION}
{$REGION Files manager}
Procedure AddFileProcess(FiType, FiFile, FiPeer:String;TimeStamp:int64);
var
NewValue : TFileManager;
Begin
NewValue := Default(TFileManager);
NewValue.FiType := FiType;
NewValue.FiFile := FiFile;
NewValue.FiPeer := FiPeer;
NewValue.FiLast := TimeStamp;
EnterCriticalSection(CS_FileManager);
Insert(NewValue,ArrFileMgr,Length(ArrFileMgr));
LeaveCriticalSection(CS_FileManager);
End;
Function CloseFileProcess(FiType, FiFile, FiPeer:String;TimeStamp:int64):int64;
var
counter : integer;
Begin
Result := 0;
EnterCriticalSection(CS_FileManager);
for counter := 0 to High(ArrFileMgr) do
begin
if ( (UpperCase(ArrFileMgr[counter].FiType) = UpperCase(FiType)) and
(UpperCase(ArrFileMgr[counter].FiFile) = UpperCase(FiFile)) and
(UpperCase(ArrFileMgr[counter].FiPeer) = UpperCase(FiPeer)) ) then
begin
Result := TimeStamp - ArrFileMgr[counter].FiLast;
Delete(ArrFileMgr,Counter,1);
Break;
end;
end;
LeaveCriticalSection(CS_FileManager);
End;
Function GetFileProcessCopy():TFileMCopy;
Begin
Setlength(Result,0);
EnterCriticalSection(CS_FileManager);
Result := copy(ArrFileMgr,0,length(ArrFileMgr));
LeaveCriticalSection(CS_FileManager);
End;
{$ENDREGION}
INITIALIZATION
Setlength(ArrPerformance,0);
Setlength(ArrNDLogs,0);
Setlength(ArrNDCSs,0);
Setlength(ArrNDSLs,0);
Setlength(ArrProcess,0);
Setlength(ArrFileMgr,0);
InitCriticalSection(CS_ThManager);
InitCriticalSection(CS_FileManager);
FINALIZATION
DoneCriticalSection(CS_ThManager);
DoneCriticalSection(CS_FileManager);
FreeAllLogs;
END. {END UNIT}
|
Unit Crt;
Interface
Const
{ CRT Modes }
BW40 = 0; { 40 x 25 B/W on a Color Adapter }
C40 = 1; { 40 x 25 on Color Adapter }
BW80 = 2; { 80 x 25 B/W on a Color Adapter }
C80 = 3; { 80 x 25 on Color Adapter }
Mono = 7; { 80 x 25 on a Monochrome Adapter }
Last = -1; { Last Active Text Mode }
{ ForeGround and BackGround Color Constants }
Black = 0;
Blue = 1;
Green = 2;
Cyan = 3;
Red = 4;
Magenta = 5;
Brown = 6;
LightGray = 7;
{ Foreground color constants }
DarkGray = 8;
LightBlue = 9;
LightGreen = 10;
LightCyan = 11;
LightRed = 12;
LightMagenta = 13;
Yellow = 14;
White = 15;
{ Add-in For Blinking }
Blink = 128;
Var
{ Interface Variables }
CheckBreak:Boolean; { Enable Ctrl-Break }
CheckEOF:Boolean; { Enable Ctrl-Z }
DirectVideo:Boolean; { Enable direct Video addressing }
CheckSnow:Boolean; { Enable Snow Filtering }
TextAttr:Byte; { Current Text attribute }
WindMin:Word; { Window Upper Left Cordinates }
WindMax:Word; { Window Lower Right Coordinates }
{ Interface Procedures }
Procedure AssignCrt(Var F:Text};
Function KeyPressed:Boolean;
Function ReadKey:Char;
Procedure TextMode(Mode:Integer);
Procedure Window(X1,Y1,X2,Y2:Integer);
Procedure GotoXY(X,Y:Integer);
Function WhereX:Integer;
Function WhereY:Integer;
Procedure ClrScr;
Procedure ClrEol;
Procedure InsLine;
Procedure DelLine;
Procedure TextColor(Color:Integer);
Procedure TextBackGround(Color:Integer);
Procedure LowVideo;
Procedure HighVideo;
Procedure NormVideo;
Procedure Delay(MS:Integer);
Procedure Sound(Hz:Integer);
Procedure NoSound; |
unit LitePathSelector;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, LiteButton, uUtils;
type PathSelectEvent = procedure(path, name: String) of object;
{
Lite Path selector
}
type TLitePathSelector = class(TLiteButton)
private
opener: TOpenDialog;
pathList: StringList;
pathSelected: PathSelectEvent;
protected
public
path: String;
name: String;
constructor Create(AOwner: TComponent); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
{
Opens selection dialog
}
function select(): boolean;
{
Returns true if file hasbeen selected
}
function isSelected(): boolean;
published
property OnPathSelected: PathSelectEvent read pathSelected write pathSelected;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Lite', [TLitePathSelector]);
end;
// Override
procedure TLitePathSelector.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if select() then
Caption := path;
MouseUp(Button, Shift, X, Y);
if Assigned(pathSelected) then
pathSelected(path, name);
end;
// Override
constructor TLitePathSelector.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
opener := TOpenDialog.Create(nil);
Alignment := taRightJustify;
Height := 24;
Width := 160;
Font.Size := 12;
path := '';
name := '';
SetLength(pathList, 0);
end;
// TLitePathSelector
function TLitePathSelector.select(): boolean;
begin
if opener.Execute then begin
select := true;
path := opener.FileName;
pathList := split(path, '\');
name := extractFileName(path);
end else
select := false;
end;
// TLitePathSelector
function TLitePathSelector.isSelected(): boolean;
begin
isSelected := Length(name) > 0;
end;
end.
|
unit MyCat.BackEnd;
interface
uses
System.SysUtils, MyCat.Net.CrossSocket.Base, MyCat.BackEnd.Interfaces,
MyCat.BackEnd.Generics.BackEndConnection,
MyCat.BackEnd.Generics.HeartBeatConnection, MyCat.Statistic,
MyCat.Config.Model;
type
// *
// * heartbeat check for mysql connections
// *
TConnectionHeartBeatHandler = class(TInterfacedObject, IResponseHandler)
private
FAllConnections: IHeartBeatConnectionMap;
private void executeException(BackendConnection c, Throwable e) {
removeFinished(c);
LOGGER.warn("executeException ", e);
c.close("heatbeat exception:" + e);
}
public
constructor Create;
procedure DoHeartBeat(Connection: IBackEndConnection; sql: string);
// *
// * remove timeout connections
// *
procedure AbandTimeOuttedConns();
// *
// * 无法获取连接
// *
// * @param e
// * @param conn
// *
procedure ConnectionError(E: Exception; Connection: IBackEndConnection);
// *
// * 已获得有效连接的响应处理
// *
procedure ConnectionAcquired(Connection: IBackEndConnection);
// *
// * 收到错误数据包的响应处理
// *
procedure ErrorResponse(Err: TBytes; Connection: IBackEndConnection);
// *
// * 收到OK数据包的响应处理
// *
procedure OkResponse(OK: TBytes; Connection: IBackEndConnection);
// *
// * 收到字段数据包结束的响应处理
// *
procedure FieldEofResponse(Header: TBytes; Fields: TArray<TBytes>;
Eof: TBytes; Connection: IBackEndConnection);
// *
// * 收到行数据包的响应处理
// *
procedure RowResponse(Row: TBytes; Connection: IBackEndConnection);
// *
// * 收到行数据包结束的响应处理
// *
procedure RowEofResponse(Eof: TBytes; Connection: IBackEndConnection);
// *
// * 写队列为空,可以写数据了
// *
procedure WriteQueueAvailable;
// *
// * on connetion close event
// *
procedure ConnectionClose(Connection: IBackEndConnection; reason: string);
end;
// public class ConnectionHeartBeatHandler implements ResponseHandler {
//
// public void doHeartBeat(BackendConnection conn, String sql) {
// }
//
// /**
// * remove timeout connections
// */
// public void abandTimeOuttedConns() {
// }
//
// @Override
// public void connectionAcquired(BackendConnection conn) {
// // not called
// }
//
// @Override
// public void connectionError(Throwable e, BackendConnection conn) {
// // not called
//
// }
//
// @Override
// public void errorResponse(byte[] data, BackendConnection conn) {
// removeFinished(conn);
// ErrorPacket err = new ErrorPacket();
// err.read(data);
// LOGGER.warn("errorResponse " + err.errno + " "
// + new String(err.message));
// conn.release();
//
// }
//
// @Override
// public void okResponse(byte[] ok, BackendConnection conn) {
// boolean executeResponse = conn.syncAndExcute();
// if (executeResponse) {
// removeFinished(conn);
// conn.release();
// }
//
// }
//
// @Override
// public void rowResponse(byte[] row, BackendConnection conn) {
// }
//
// @Override
// public void rowEofResponse(byte[] eof, BackendConnection conn) {
// removeFinished(conn);
// conn.release();
// }
//
//
// private void removeFinished(BackendConnection con) {
// Long id = ((BackendConnection) con).getId();
// this.allCons.remove(id);
// }
//
// @Override
// public void writeQueueAvailable() {
//
// }
//
// @Override
// public void connectionClose(BackendConnection conn, String reason) {
// removeFinished(conn);
// LOGGER.warn("connection closed " + conn + " reason:" + reason);
// }
//
// @Override
// public void fieldEofResponse(byte[] header, List<byte[]> fields,
// byte[] eof, BackendConnection conn) {
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("received field eof from " + conn);
// }
// }
//
// }
//
TConnectionQueue = class
private
FAutoCommitCons: TBackEndConnectionList;
FManCommitCons: TBackEndConnectionList;
FExecuteCount: Int64;
public
constructor Create;
function TakeIdleCon(AutoCommit: Boolean): IBackEndConnection;
function GetExecuteCount: Int64;
procedure IncExecuteCount;
function RemoveConnection(Connection: IBackEndConnection): Boolean;
end;
// public class ConQueue {
//
// public BackendConnection takeIdleCon(boolean autoCommit) {
// }
//
// public long getExecuteCount() {
// }
//
// public void incExecuteCount() {
// }
//
// public boolean removeCon(BackendConnection con) {
// }
//
// public boolean isSameCon(BackendConnection con) {
// if (autoCommitCons.contains(con)) {
// return true;
// } else if (manCommitCons.contains(con)) {
// return true;
// }
// return false;
// }
//
// public ConcurrentLinkedQueue<BackendConnection> getAutoCommitCons() {
// return autoCommitCons;
// }
//
// public ConcurrentLinkedQueue<BackendConnection> getManCommitCons() {
// return manCommitCons;
// }
//
// public ArrayList<BackendConnection> getIdleConsToClose(int count) {
// ArrayList<BackendConnection> readyCloseCons = new ArrayList<BackendConnection>(
// count);
// while (!manCommitCons.isEmpty() && readyCloseCons.size() < count) {
// BackendConnection theCon = manCommitCons.poll();
// if (theCon != null&&!theCon.isBorrowed()) {
// readyCloseCons.add(theCon);
// }
// }
// while (!autoCommitCons.isEmpty() && readyCloseCons.size() < count) {
// BackendConnection theCon = autoCommitCons.poll();
// if (theCon != null&&!theCon.isBorrowed()) {
// readyCloseCons.add(theCon);
// }
//
// }
// return readyCloseCons;
// }
//
// }
TConMap = class
private
public
end;
// public class ConMap {
//
// // key -schema
// private final ConcurrentHashMap<String, ConQueue> items = new ConcurrentHashMap<String, ConQueue>();
//
// public ConQueue getSchemaConQueue(String schema) {
// ConQueue queue = items.get(schema);
// if (queue == null) {
// ConQueue newQueue = new ConQueue();
// queue = items.putIfAbsent(schema, newQueue);
// return (queue == null) ? newQueue : queue;
// }
// return queue;
// }
//
// public BackendConnection tryTakeCon(final String schema, boolean autoCommit) {
// final ConQueue queue = items.get(schema);
// BackendConnection con = tryTakeCon(queue, autoCommit);
// if (con != null) {
// return con;
// } else {
// for (ConQueue queue2 : items.values()) {
// if (queue != queue2) {
// con = tryTakeCon(queue2, autoCommit);
// if (con != null) {
// return con;
// }
// }
// }
// }
// return null;
//
// }
//
// private BackendConnection tryTakeCon(ConQueue queue, boolean autoCommit) {
//
// BackendConnection con = null;
// if (queue != null && ((con = queue.takeIdleCon(autoCommit)) != null)) {
// return con;
// } else {
// return null;
// }
//
// }
//
// public Collection<ConQueue> getAllConQueue() {
// return items.values();
// }
//
// public int getActiveCountForSchema(String schema,
// PhysicalDatasource dataSouce) {
// int total = 0;
// for (NIOProcessor processor : MycatServer.getInstance().getProcessors()) {
// for (BackendConnection con : processor.getBackends().values()) {
// if (con instanceof MySQLConnection) {
// MySQLConnection mysqlCon = (MySQLConnection) con;
//
// if (mysqlCon.getSchema().equals(schema)
// && mysqlCon.getPool() == dataSouce
// && mysqlCon.isBorrowed()) {
// total++;
// }
//
// }else if (con instanceof JDBCConnection) {
// JDBCConnection jdbcCon = (JDBCConnection) con;
// if (jdbcCon.getSchema().equals(schema) && jdbcCon.getPool() == dataSouce
// && jdbcCon.isBorrowed()) {
// total++;
// }
// }
// }
// }
// return total;
// }
//
// public int getActiveCountForDs(PhysicalDatasource dataSouce) {
// int total = 0;
// for (NIOProcessor processor : MycatServer.getInstance().getProcessors()) {
// for (BackendConnection con : processor.getBackends().values()) {
// if (con instanceof MySQLConnection) {
// MySQLConnection mysqlCon = (MySQLConnection) con;
//
// if (mysqlCon.getPool() == dataSouce
// && mysqlCon.isBorrowed() && !mysqlCon.isClosed()) {
// total++;
// }
//
// } else if (con instanceof JDBCConnection) {
// JDBCConnection jdbcCon = (JDBCConnection) con;
// if (jdbcCon.getPool() == dataSouce
// && jdbcCon.isBorrowed() && !jdbcCon.isClosed()) {
// total++;
// }
// }
// }
// }
// return total;
// }
//
// public void clearConnections(String reason, PhysicalDatasource dataSouce) {
// for (NIOProcessor processor : MycatServer.getInstance().getProcessors()) {
// ConcurrentMap<Long, BackendConnection> map = processor.getBackends();
// Iterator<Entry<Long, BackendConnection>> itor = map.entrySet().iterator();
// while (itor.hasNext()) {
// Entry<Long, BackendConnection> entry = itor.next();
// BackendConnection con = entry.getValue();
// if (con instanceof MySQLConnection) {
// if (((MySQLConnection) con).getPool() == dataSouce) {
// con.close(reason);
// itor.remove();
// }
// }else if((con instanceof JDBCConnection)
// && (((JDBCConnection) con).getPool() == dataSouce)){
// con.close(reason);
// itor.remove();
// }
// }
//
// }
// items.clear();
// }
// }
type
TDBHeartbeat = class
public const
DB_SYN_ERROR: Integer = -1;
DB_SYN_NORMAL: Integer = 1;
OK_STATUS: Integer = 1;
ERROR_STATUS: Integer = -1;
TIMEOUT_STATUS: Integer = -2;
INIT_STATUS: Integer = 0;
private const
DEFAULT_HEARTBEAT_TIMEOUT: Int64 = 30 * 1000;
DEFAULT_HEARTBEAT_RETRY: Integer = 10;
protected
// heartbeat config
FHeartbeatTimeout: Int64; // 心跳超时时间
FHeartbeatRetry: Integer; // 检查连接发生异常到切换,重试次数
FHeartbeatSQL: string; // 静态心跳语句
FIsStop: Boolean;
FIsChecking: Boolean;
FErrorCount: Integer;
FStatus: Integer;
FRecorder: THeartbeatRecorder;
FAsynRecorder: TDataSourceSyncRecorder;
public
constructor Create;
end;
//
// private volatile Integer slaveBehindMaster;
// private volatile int dbSynStatus = DB_SYN_NORMAL;
//
// public Integer getSlaveBehindMaster() {
// return slaveBehindMaster;
// }
//
// public int getDbSynStatus() {
// return dbSynStatus;
// }
//
// public void setDbSynStatus(int dbSynStatus) {
// this.dbSynStatus = dbSynStatus;
// }
//
// public void setSlaveBehindMaster(Integer slaveBehindMaster) {
// this.slaveBehindMaster = slaveBehindMaster;
// }
//
// public int getStatus() {
// return status;
// }
//
// public boolean isChecking() {
// return isChecking.get();
// }
//
// public abstract void start();
//
// public abstract void stop();
//
// public boolean isStop() {
// return isStop.get();
// }
//
// public int getErrorCount() {
// return errorCount.get();
// }
//
// public HeartbeatRecorder getRecorder() {
// return recorder;
// }
//
// public abstract String getLastActiveTime();
//
// public abstract long getTimeout();
//
// public abstract void heartbeat();
//
// public long getHeartbeatTimeout() {
// return heartbeatTimeout;
// }
//
// public void setHeartbeatTimeout(long heartbeatTimeout) {
// this.heartbeatTimeout = heartbeatTimeout;
// }
//
// public int getHeartbeatRetry() {
// return heartbeatRetry;
// }
//
// public void setHeartbeatRetry(int heartbeatRetry) {
// this.heartbeatRetry = heartbeatRetry;
// }
//
// public String getHeartbeatSQL() {
// return heartbeatSQL;
// }
//
// public void setHeartbeatSQL(String heartbeatSQL) {
// this.heartbeatSQL = heartbeatSQL;
// }
//
// public boolean isNeedHeartbeat() {
// return heartbeatSQL != null;
// }
//
// public DataSourceSyncRecorder getAsynRecorder() {
// return this.asynRecorder;
// }
TPhysicalDBPool = class
public const
BALANCE_NONE: Integer = 0;
BALANCE_ALL_BACK: Integer = 1;
BALANCE_ALL: Integer = 2;
BALANCE_ALL_READ: Integer = 3;
WRITE_ONLYONE_NODE: Integer = 0;
WRITE_RANDOM_NODE: Integer = 1;
WRITE_ALL_NODE: Integer = 2;
LONG_TIME: Int64 = 300000;
WEIGHT: Integer = 0;
end;
// public class PhysicalDBPool {
//
// protected static final Logger LOGGER = LoggerFactory.getLogger(PhysicalDBPool.class);
//
// public static final int BALANCE_NONE = 0;
// public static final int BALANCE_ALL_BACK = 1;
// public static final int BALANCE_ALL = 2;
// public static final int BALANCE_ALL_READ = 3;
//
// public static final int WRITE_ONLYONE_NODE = 0;
// public static final int WRITE_RANDOM_NODE = 1;
// public static final int WRITE_ALL_NODE = 2;
//
// public static final long LONG_TIME = 300000;
// public static final int WEIGHT = 0;
//
// private final String hostName;
//
// protected PhysicalDatasource[] writeSources;
// protected Map<Integer, PhysicalDatasource[]> readSources;
//
// protected volatile int activedIndex;
// protected volatile boolean initSuccess;
//
// protected final ReentrantLock switchLock = new ReentrantLock();
// private final Collection<PhysicalDatasource> allDs;
// private final int banlance;
// private final int writeType;
// private final Random random = new Random();
// private final Random wnrandom = new Random();
// private String[] schemas;
// private final DataHostConfig dataHostConfig;
// private String slaveIDs;
//
// public PhysicalDBPool(String name, DataHostConfig conf,
// PhysicalDatasource[] writeSources,
// Map<Integer, PhysicalDatasource[]> readSources, int balance,
// int writeType) {
//
// this.hostName = name;
// this.dataHostConfig = conf;
// this.writeSources = writeSources;
// this.banlance = balance;
// this.writeType = writeType;
//
// Iterator<Map.Entry<Integer, PhysicalDatasource[]>> entryItor = readSources.entrySet().iterator();
// while (entryItor.hasNext()) {
// PhysicalDatasource[] values = entryItor.next().getValue();
// if (values.length == 0) {
// entryItor.remove();
// }
// }
//
// this.readSources = readSources;
// this.allDs = this.genAllDataSources();
//
// LOGGER.info("total resouces of dataHost " + this.hostName + " is :" + allDs.size());
//
// setDataSourceProps();
// }
//
// public int getWriteType() {
// return writeType;
// }
//
// private void setDataSourceProps() {
// for (PhysicalDatasource ds : this.allDs) {
// ds.setDbPool(this);
// }
// }
//
// public PhysicalDatasource findDatasouce(BackendConnection exitsCon) {
// for (PhysicalDatasource ds : this.allDs) {
// if ((ds.isReadNode() == exitsCon.isFromSlaveDB())
// && ds.isMyConnection(exitsCon)) {
// return ds;
// }
// }
//
// LOGGER.warn("can't find connection in pool " + this.hostName + " con:" + exitsCon);
// return null;
// }
//
// public String getSlaveIDs() {
// return slaveIDs;
// }
//
// public void setSlaveIDs(String slaveIDs) {
// this.slaveIDs = slaveIDs;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// /**
// * all write datanodes
// * @return
// */
// public PhysicalDatasource[] getSources() {
// return writeSources;
// }
//
// public PhysicalDatasource getSource() {
//
// switch (writeType) {
// case WRITE_ONLYONE_NODE: {
// return writeSources[activedIndex];
// }
// case WRITE_RANDOM_NODE: {
//
// int index = Math.abs(wnrandom.nextInt(Integer.MAX_VALUE)) % writeSources.length;
// PhysicalDatasource result = writeSources[index];
// if (!this.isAlive(result)) {
//
// // find all live nodes
// ArrayList<Integer> alives = new ArrayList<Integer>(writeSources.length - 1);
// for (int i = 0; i < writeSources.length; i++) {
// if (i != index
// && this.isAlive(writeSources[i])) {
// alives.add(i);
// }
// }
//
// if (alives.isEmpty()) {
// result = writeSources[0];
// } else {
// // random select one
// index = Math.abs(wnrandom.nextInt(Integer.MAX_VALUE)) % alives.size();
// result = writeSources[alives.get(index)];
//
// }
// }
//
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("select write source " + result.getName()
// + " for dataHost:" + this.getHostName());
// }
// return result;
// }
// default: {
// throw new java.lang.IllegalArgumentException("writeType is "
// + writeType + " ,so can't return one write datasource ");
// }
// }
//
// }
//
// public int getActivedIndex() {
// return activedIndex;
// }
//
// public boolean isInitSuccess() {
// return initSuccess;
// }
//
// public int next(int i) {
// if (checkIndex(i)) {
// return (++i == writeSources.length) ? 0 : i;
// } else {
// return 0;
// }
// }
//
// public boolean switchSource(int newIndex, boolean isAlarm, String reason) {
// if (this.writeType != PhysicalDBPool.WRITE_ONLYONE_NODE || !checkIndex(newIndex)) {
// return false;
// }
//
// final ReentrantLock lock = this.switchLock;
// lock.lock();
// try {
// int current = activedIndex;
// if (current != newIndex) {
//
// // switch index
// activedIndex = newIndex;
//
// // init again
// this.init(activedIndex);
//
// // clear all connections
// this.getSources()[current].clearCons("switch datasource");
//
// // write log
// LOGGER.warn(switchMessage(current, newIndex, false, reason));
//
// return true;
// }
// } finally {
// lock.unlock();
// }
// return false;
// }
//
// private String switchMessage(int current, int newIndex, boolean alarm, String reason) {
// StringBuilder s = new StringBuilder();
// if (alarm) {
// s.append(Alarms.DATANODE_SWITCH);
// }
// s.append("[Host=").append(hostName).append(",result=[").append(current).append("->");
// s.append(newIndex).append("],reason=").append(reason).append(']');
// return s.toString();
// }
//
// private int loop(int i) {
// return i < writeSources.length ? i : (i - writeSources.length);
// }
//
// public void init(int index) {
//
// if (!checkIndex(index)) {
// index = 0;
// }
//
// int active = -1;
// for (int i = 0; i < writeSources.length; i++) {
// int j = loop(i + index);
// if ( initSource(j, writeSources[j]) ) {
//
// //不切换-1时,如果主写挂了 不允许切换过去
// boolean isNotSwitchDs = ( dataHostConfig.getSwitchType() == DataHostConfig.NOT_SWITCH_DS );
// if ( isNotSwitchDs && j > 0 ) {
// break;
// }
//
// active = j;
// activedIndex = active;
// initSuccess = true;
// LOGGER.info(getMessage(active, " init success"));
//
// if (this.writeType == WRITE_ONLYONE_NODE) {
// // only init one write datasource
// MycatServer.getInstance().saveDataHostIndex(hostName, activedIndex);
// break;
// }
// }
// }
//
// if (!checkIndex(active)) {
// initSuccess = false;
// StringBuilder s = new StringBuilder();
// s.append(Alarms.DEFAULT).append(hostName).append(" init failure");
// LOGGER.error(s.toString());
// }
// }
//
// private boolean checkIndex(int i) {
// return i >= 0 && i < writeSources.length;
// }
//
// private String getMessage(int index, String info) {
// return new StringBuilder().append(hostName).append(" index:").append(index).append(info).toString();
// }
//
// private boolean initSource(int index, PhysicalDatasource ds) {
// int initSize = ds.getConfig().getMinCon();
//
// LOGGER.info("init backend myqsl source ,create connections total " + initSize + " for " + ds.getName() + " index :" + index);
//
// CopyOnWriteArrayList<BackendConnection> list = new CopyOnWriteArrayList<BackendConnection>();
// GetConnectionHandler getConHandler = new GetConnectionHandler(list, initSize);
// // long start = System.currentTimeMillis();
// // long timeOut = start + 5000 * 1000L;
//
// for (int i = 0; i < initSize; i++) {
// try {
// ds.getConnection(this.schemas[i % schemas.length], true, getConHandler, null);
// } catch (Exception e) {
// LOGGER.warn(getMessage(index, " init connection error."), e);
// }
// }
// long timeOut = System.currentTimeMillis() + 60 * 1000;
//
// // waiting for finish
// while (!getConHandler.finished() && (System.currentTimeMillis() < timeOut)) {
// try {
// Thread.sleep(100);
//
// } catch (InterruptedException e) {
// LOGGER.error("initError", e);
// }
// }
// LOGGER.info("init result :" + getConHandler.getStatusInfo());
/// / for (BackendConnection c : list) {
/// / c.release();
/// / }
// return !list.isEmpty();
// }
//
// public void doHeartbeat() {
//
//
// if (writeSources == null || writeSources.length == 0) {
// return;
// }
//
// for (PhysicalDatasource source : this.allDs) {
//
// if (source != null) {
// source.doHeartbeat();
// } else {
// StringBuilder s = new StringBuilder();
// s.append(Alarms.DEFAULT).append(hostName).append(" current dataSource is null!");
// LOGGER.error(s.toString());
// }
// }
//
// }
//
// /**
// * back physical connection heartbeat check
// */
// public void heartbeatCheck(long ildCheckPeriod) {
//
// for (PhysicalDatasource ds : allDs) {
// // only readnode or all write node or writetype=WRITE_ONLYONE_NODE
// // and current write node will check
// if (ds != null
// && (ds.getHeartbeat().getStatus() == DBHeartbeat.OK_STATUS)
// && (ds.isReadNode()
// || (this.writeType != WRITE_ONLYONE_NODE)
// || (this.writeType == WRITE_ONLYONE_NODE
// && ds == this.getSource()))) {
//
// ds.heatBeatCheck(ds.getConfig().getIdleTimeout(), ildCheckPeriod);
// }
// }
// }
//
// public void startHeartbeat() {
// for (PhysicalDatasource source : this.allDs) {
// source.startHeartbeat();
// }
// }
//
// public void stopHeartbeat() {
// for (PhysicalDatasource source : this.allDs) {
// source.stopHeartbeat();
// }
// }
//
// /**
// * 强制清除 dataSources
// * @param reason
// */
// public void clearDataSources(String reason) {
// LOGGER.info("clear datasours of pool " + this.hostName);
// for (PhysicalDatasource source : this.allDs) {
// LOGGER.info("clear datasoure of pool " + this.hostName + " ds:" + source.getConfig());
// source.clearCons(reason);
// source.stopHeartbeat();
// }
// }
//
// public Collection<PhysicalDatasource> genAllDataSources() {
//
// LinkedList<PhysicalDatasource> allSources = new LinkedList<PhysicalDatasource>();
// for (PhysicalDatasource ds : writeSources) {
// if (ds != null) {
// allSources.add(ds);
// }
// }
//
// for (PhysicalDatasource[] dataSources : this.readSources.values()) {
// for (PhysicalDatasource ds : dataSources) {
// if (ds != null) {
// allSources.add(ds);
// }
// }
// }
// return allSources;
// }
//
// public Collection<PhysicalDatasource> getAllDataSources() {
// return this.allDs;
// }
//
// /**
// * return connection for read balance
// *
// * @param handler
// * @param attachment
// * @param database
// * @throws Exception
// */
// public void getRWBanlanceCon(String schema, boolean autocommit,
// ResponseHandler handler, Object attachment, String database) throws Exception {
//
// PhysicalDatasource theNode = null;
// ArrayList<PhysicalDatasource> okSources = null;
// switch (banlance) {
// case BALANCE_ALL_BACK: {
// // all read nodes and the standard by masters
// okSources = getAllActiveRWSources(true, false, checkSlaveSynStatus());
// if (okSources.isEmpty()) {
// theNode = this.getSource();
//
// } else {
// theNode = randomSelect(okSources);
// }
// break;
// }
// case BALANCE_ALL: {
// okSources = getAllActiveRWSources(true, true, checkSlaveSynStatus());
// theNode = randomSelect(okSources);
// break;
// }
// case BALANCE_ALL_READ: {
// okSources = getAllActiveRWSources(false, false, checkSlaveSynStatus());
// theNode = randomSelect(okSources);
// break;
// }
// case BALANCE_NONE:
// default:
// // return default write data source
// theNode = this.getSource();
// }
//
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("select read source " + theNode.getName() + " for dataHost:" + this.getHostName());
// }
// //统计节点读操作次数
// theNode.setReadCount();
// theNode.getConnection(schema, autocommit, handler, attachment);
// }
//
// /**
// * slave 读负载均衡,也就是 readSource 之间实现负载均衡
// * @param schema
// * @param autocommit
// * @param handler
// * @param attachment
// * @param database
// * @throws Exception
// */
// public void getReadBanlanceCon(String schema, boolean autocommit, ResponseHandler handler,
// Object attachment, String database)throws Exception {
// PhysicalDatasource theNode = null;
// ArrayList<PhysicalDatasource> okSources = null;
// okSources = getAllActiveRWSources(false, false, checkSlaveSynStatus());
// theNode = randomSelect(okSources);
// //统计节点读操作次数
// theNode.setReadCount();
// theNode.getConnection(schema, autocommit, handler, attachment);
// }
//
// /**
// * 从 writeHost 下面的 readHost中随机获取一个 connection, 用于slave注解
// * @param schema
// * @param autocommit
// * @param handler
// * @param attachment
// * @param database
// * @return
// * @throws Exception
// */
// public boolean getReadCon(String schema, boolean autocommit, ResponseHandler handler,
// Object attachment, String database)throws Exception {
// PhysicalDatasource theNode = null;
//
// LOGGER.debug("!readSources.isEmpty() " + !readSources.isEmpty());
// if (!readSources.isEmpty()) {
// int index = Math.abs(random.nextInt(Integer.MAX_VALUE)) % readSources.size();
// PhysicalDatasource[] allSlaves = this.readSources.get(index);
/// / System.out.println("allSlaves.length " + allSlaves.length);
// if (allSlaves != null) {
// index = Math.abs(random.nextInt(Integer.MAX_VALUE)) % readSources.size();
// PhysicalDatasource slave = allSlaves[index];
//
// for (int i=0; i<allSlaves.length; i++) {
// LOGGER.debug("allSlaves.length i:::::: " + i);
// if (isAlive(slave)) {
// if (checkSlaveSynStatus()) {
// if (canSelectAsReadNode(slave)) {
// theNode = slave;
// break;
// } else {
// continue;
// }
// } else {
// theNode = slave;
// break;
// }
// }
/// / index = Math.abs(random.nextInt()) % readSources.size();
// }
// }
// //统计节点读操作次数
// if(theNode != null) {
// theNode.setReadCount();
// theNode.getConnection(schema, autocommit, handler, attachment);
// return true;
// } else {
// LOGGER.warn("readhost is notavailable.");
// return false;
// }
// }else{
// LOGGER.warn("readhost is empty, readSources is empty.");
// return false;
// }
// }
//
// private boolean checkSlaveSynStatus() {
// return ( dataHostConfig.getSlaveThreshold() != -1 )
// && (dataHostConfig.getSwitchType() == DataHostConfig.SYN_STATUS_SWITCH_DS);
// }
//
//
// /**
// * TODO: modify by zhuam
// *
// * 随机选择,按权重设置随机概率。
// * 在一个截面上碰撞的概率高,但调用量越大分布越均匀,而且按概率使用权重后也比较均匀,有利于动态调整提供者权重。
// * @param okSources
// * @return
// */
// public PhysicalDatasource randomSelect(ArrayList<PhysicalDatasource> okSources) {
//
// if (okSources.isEmpty()) {
// return this.getSource();
//
// } else {
//
// int length = okSources.size(); // 总个数
// int totalWeight = 0; // 总权重
// boolean sameWeight = true; // 权重是否都一样
// for (int i = 0; i < length; i++) {
// int weight = okSources.get(i).getConfig().getWeight();
// totalWeight += weight; // 累计总权重
// if (sameWeight && i > 0
// && weight != okSources.get(i-1).getConfig().getWeight() ) { // 计算所有权重是否一样
// sameWeight = false;
// }
// }
//
// if (totalWeight > 0 && !sameWeight ) {
//
// // 如果权重不相同且权重大于0则按总权重数随机
// int offset = random.nextInt(totalWeight);
//
// // 并确定随机值落在哪个片断上
// for (int i = 0; i < length; i++) {
// offset -= okSources.get(i).getConfig().getWeight();
// if (offset < 0) {
// return okSources.get(i);
// }
// }
// }
//
// // 如果权重相同或权重为0则均等随机
// return okSources.get( random.nextInt(length) );
//
// //int index = Math.abs(random.nextInt()) % okSources.size();
// //return okSources.get(index);
// }
// }
//
// //
// public int getBalance() {
// return banlance;
// }
//
// private boolean isAlive(PhysicalDatasource theSource) {
// return (theSource.getHeartbeat().getStatus() == DBHeartbeat.OK_STATUS);
// }
//
// private boolean canSelectAsReadNode(PhysicalDatasource theSource) {
//
// Integer slaveBehindMaster = theSource.getHeartbeat().getSlaveBehindMaster();
// int dbSynStatus = theSource.getHeartbeat().getDbSynStatus();
//
// if ( slaveBehindMaster == null || dbSynStatus == DBHeartbeat.DB_SYN_ERROR) {
// return false;
// }
// boolean isSync = dbSynStatus == DBHeartbeat.DB_SYN_NORMAL;
// boolean isNotDelay = slaveBehindMaster < this.dataHostConfig.getSlaveThreshold();
// return isSync && isNotDelay;
// }
//
// /**
// * return all backup write sources
// *
// * @param includeWriteNode if include write nodes
// * @param includeCurWriteNode if include current active write node. invalid when <code>includeWriteNode<code> is false
// * @param filterWithSlaveThreshold
// *
// * @return
// */
// private ArrayList<PhysicalDatasource> getAllActiveRWSources(
// boolean includeWriteNode, boolean includeCurWriteNode, boolean filterWithSlaveThreshold) {
//
// int curActive = activedIndex;
// ArrayList<PhysicalDatasource> okSources = new ArrayList<PhysicalDatasource>(this.allDs.size());
//
// for (int i = 0; i < this.writeSources.length; i++) {
// PhysicalDatasource theSource = writeSources[i];
// if (isAlive(theSource)) {// write node is active
//
// if (includeWriteNode) {
// boolean isCurWriteNode = ( i == curActive );
// if ( isCurWriteNode && includeCurWriteNode == false) {
// // not include cur active source
// } else if (filterWithSlaveThreshold && theSource.isSalveOrRead() ) {
// boolean selected = canSelectAsReadNode(theSource);
// if ( selected ) {
// okSources.add(theSource);
// } else {
// continue;
// }
// } else {
// okSources.add(theSource);
// }
// }
//
// if (!readSources.isEmpty()) {
// // check all slave nodes
// PhysicalDatasource[] allSlaves = this.readSources.get(i);
// if (allSlaves != null) {
// for (PhysicalDatasource slave : allSlaves) {
// if (isAlive(slave)) {
// if (filterWithSlaveThreshold) {
// boolean selected = canSelectAsReadNode(slave);
// if ( selected ) {
// okSources.add(slave);
// } else {
// continue;
// }
// } else {
// okSources.add(slave);
// }
// }
// }
// }
// }
//
// } else {
//
// // TODO : add by zhuam
// // 如果写节点不OK, 也要保证临时的读服务正常
// if ( this.dataHostConfig.isTempReadHostAvailable()
// && !readSources.isEmpty()) {
//
// // check all slave nodes
// PhysicalDatasource[] allSlaves = this.readSources.get(i);
// if (allSlaves != null) {
// for (PhysicalDatasource slave : allSlaves) {
// if (isAlive(slave)) {
//
// if (filterWithSlaveThreshold) {
// if (canSelectAsReadNode(slave)) {
// okSources.add(slave);
// } else {
// continue;
// }
//
// } else {
// okSources.add(slave);
// }
// }
// }
// }
// }
// }
//
// }
// return okSources;
// }
//
// public String[] getSchemas() {
// return schemas;
// }
//
// public void setSchemas(String[] mySchemas) {
// this.schemas = mySchemas;
// }
// }
TPhysicalDatasource = class
private
FName: String;
FSize: Integer;
FConfig: TDBHostConfig;
FConMap: TConMap;
FHeartbeat: TDBHeartbeat;
FReadNode: Boolean;
FHeartbeatRecoveryTime: Int64;
FHostConfig: TDataHostConfig;
FConnHeartBeatHanler: TConnectionHeartBeatHandler;
FDBPool: TPhysicalDBPool;
// 添加DataSource读计数
FReadCount: Int64; // = new AtomicLong(0);
// 添加DataSource写计数
FWriteCount: Int64; // = new AtomicLong(0);
public
constructor Create(Config: TDBHostConfig; HostConfig: TDataHostConfig;
IsReadNode: Boolean);
end;
// = new ConMap();
// public abstract class PhysicalDatasource {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(PhysicalDatasource.class);
//
// private final String name;
// private final int size;
// private final DBHostConfig config;
// private final ConMap conMap = new ConMap();
// private DBHeartbeat heartbeat;
// private final boolean readNode;
// private volatile long heartbeatRecoveryTime;
// private final DataHostConfig hostConfig;
// private final ConnectionHeartBeatHandler conHeartBeatHanler = new ConnectionHeartBeatHandler();
// private PhysicalDBPool dbPool;
//
// // 添加DataSource读计数
// private AtomicLong readCount = new AtomicLong(0);
//
// // 添加DataSource写计数
// private AtomicLong writeCount = new AtomicLong(0);
//
//
// /**
// * edit by dingw at 2017.06.08
// * @see https://github.com/MyCATApache/Mycat-Server/issues/1524
// *
// */
// // 当前活动连接
// //private volatile AtomicInteger activeCount = new AtomicInteger(0);
//
// // 当前存活的总连接数,为什么不直接使用activeCount,主要是因为连接的创建是异步完成的
// //private volatile AtomicInteger totalConnection = new AtomicInteger(0);
//
// /**
// * 由于在Mycat中,returnCon被多次调用(与takeCon并没有成对调用)导致activeCount、totalConnection容易出现负数
// */
// //private static final String TAKE_CONNECTION_FLAG = "1";
// //private ConcurrentMap<Long /* ConnectionId */, String /* 常量1*/> takeConnectionContext = new ConcurrentHashMap<>();
//
//
//
// public PhysicalDatasource(DBHostConfig config, DataHostConfig hostConfig,
// boolean isReadNode) {
// this.size = config.getMaxCon();
// this.config = config;
// this.name = config.getHostName();
// this.hostConfig = hostConfig;
// heartbeat = this.createHeartBeat();
// this.readNode = isReadNode;
// }
//
// public boolean isMyConnection(BackendConnection con) {
// if (con instanceof MySQLConnection) {
// return ((MySQLConnection) con).getPool() == this;
// } else {
// return false;
// }
//
// }
//
// public long getReadCount() {
// return readCount.get();
// }
//
// public void setReadCount() {
// readCount.addAndGet(1);
// }
//
// public long getWriteCount() {
// return writeCount.get();
// }
//
// public void setWriteCount() {
// writeCount.addAndGet(1);
// }
//
// public DataHostConfig getHostConfig() {
// return hostConfig;
// }
//
// public boolean isReadNode() {
// return readNode;
// }
//
// public int getSize() {
// return size;
// }
//
// public void setDbPool(PhysicalDBPool dbPool) {
// this.dbPool = dbPool;
// }
//
// public PhysicalDBPool getDbPool() {
// return dbPool;
// }
//
// public abstract DBHeartbeat createHeartBeat();
//
// public String getName() {
// return name;
// }
//
// public long getExecuteCount() {
// long executeCount = 0;
// for (ConQueue queue : conMap.getAllConQueue()) {
// executeCount += queue.getExecuteCount();
//
// }
// return executeCount;
// }
//
// public long getExecuteCountForSchema(String schema) {
// return conMap.getSchemaConQueue(schema).getExecuteCount();
//
// }
//
// public int getActiveCountForSchema(String schema) {
// return conMap.getActiveCountForSchema(schema, this);
// }
//
// public int getIdleCountForSchema(String schema) {
// ConQueue queue = conMap.getSchemaConQueue(schema);
// int total = 0;
// total += queue.getAutoCommitCons().size()
// + queue.getManCommitCons().size();
// return total;
// }
//
// public DBHeartbeat getHeartbeat() {
// return heartbeat;
// }
//
// public int getIdleCount() {
// int total = 0;
// for (ConQueue queue : conMap.getAllConQueue()) {
// total += queue.getAutoCommitCons().size()
// + queue.getManCommitCons().size();
// }
// return total;
// }
//
// /**
// * 该方法也不是非常精确,因为该操作也不是一个原子操作,相对getIdleCount高效与准确一些
// * @return
// */
/// / public int getIdleCountSafe() {
/// / return getTotalConnectionsSafe() - getActiveCountSafe();
/// / }
//
// /**
// * 是否需要继续关闭空闲连接
// * @return
// */
/// / private boolean needCloseIdleConnection() {
/// / return getIdleCountSafe() > hostConfig.getMinCon();
/// / }
//
// private boolean validSchema(String schema) {
// String theSchema = schema;
// return theSchema != null && !"".equals(theSchema)
// && !"snyn...".equals(theSchema);
// }
//
// private void checkIfNeedHeartBeat(
// LinkedList<BackendConnection> heartBeatCons, ConQueue queue,
// ConcurrentLinkedQueue<BackendConnection> checkLis,
// long hearBeatTime, long hearBeatTime2) {
// int maxConsInOneCheck = 10;
// Iterator<BackendConnection> checkListItor = checkLis.iterator();
// while (checkListItor.hasNext()) {
// BackendConnection con = checkListItor.next();
// if (con.isClosedOrQuit()) {
// checkListItor.remove();
// continue;
// }
// if (validSchema(con.getSchema())) {
// if (con.getLastTime() < hearBeatTime
// && heartBeatCons.size() < maxConsInOneCheck) {
// if(checkLis.remove(con)) {
// //如果移除成功,则放入到心跳连接中,如果移除失败,说明该连接已经被其他线程使用,忽略本次心跳检测
// con.setBorrowed(true);
// heartBeatCons.add(con);
// }
// }
// } else if (con.getLastTime() < hearBeatTime2) {
// // not valid schema conntion should close for idle
// // exceed 2*conHeartBeatPeriod
// // 同样,这里也需要先移除,避免被业务连接
// if(checkLis.remove(con)) {
// con.close(" heart beate idle ");
// }
// }
//
// }
//
// }
//
// public int getIndex() {
// int currentIndex = 0;
// for (int i = 0; i < dbPool.getSources().length; i++) {
// PhysicalDatasource writeHostDatasource = dbPool.getSources()[i];
// if (writeHostDatasource.getName().equals(getName())) {
// currentIndex = i;
// break;
// }
// }
// return currentIndex;
// }
//
// public boolean isSalveOrRead() {
// int currentIndex = getIndex();
// if (currentIndex != dbPool.activedIndex || this.readNode) {
// return true;
// }
// return false;
// }
//
// public void heatBeatCheck(long timeout, long conHeartBeatPeriod) {
/// / int ildeCloseCount = hostConfig.getMinCon() * 3;
// int maxConsInOneCheck = 5;
// LinkedList<BackendConnection> heartBeatCons = new LinkedList<BackendConnection>();
//
// long hearBeatTime = TimeUtil.currentTimeMillis() - conHeartBeatPeriod;
// long hearBeatTime2 = TimeUtil.currentTimeMillis() - 2
// * conHeartBeatPeriod;
// for (ConQueue queue : conMap.getAllConQueue()) {
// checkIfNeedHeartBeat(heartBeatCons, queue,
// queue.getAutoCommitCons(), hearBeatTime, hearBeatTime2);
// if (heartBeatCons.size() < maxConsInOneCheck) {
// checkIfNeedHeartBeat(heartBeatCons, queue,
// queue.getManCommitCons(), hearBeatTime, hearBeatTime2);
// } else if (heartBeatCons.size() >= maxConsInOneCheck) {
// break;
// }
// }
//
// if (!heartBeatCons.isEmpty()) {
// for (BackendConnection con : heartBeatCons) {
// conHeartBeatHanler
// .doHeartBeat(con, hostConfig.getHearbeatSQL());
// }
// }
//
// // check if there has timeouted heatbeat cons
// conHeartBeatHanler.abandTimeOuttedConns();
// int idleCons = getIdleCount();
// int activeCons = this.getActiveCount();
// int createCount = (hostConfig.getMinCon() - idleCons) / 3;
// // create if idle too little
// if ((createCount > 0) && (idleCons + activeCons < size)
// && (idleCons < hostConfig.getMinCon())) {
// createByIdleLitte(idleCons, createCount);
// } else if (idleCons > hostConfig.getMinCon()) {
// closeByIdleMany(idleCons - hostConfig.getMinCon());
// } else {
// int activeCount = this.getActiveCount();
// if (activeCount > size) {
// StringBuilder s = new StringBuilder();
// s.append(Alarms.DEFAULT).append("DATASOURCE EXCEED [name=")
// .append(name).append(",active=");
// s.append(activeCount).append(",size=").append(size).append(']');
// LOGGER.warn(s.toString());
// }
// }
// }
//
// /**
// *
// * @param ildeCloseCount
// * 首先,从已创建的连接中选择本次心跳需要关闭的空闲连接数(由当前连接连接数-减去配置的最小连接数。
// * 然后依次关闭这些连接。由于连接空闲心跳检测与业务是同时并发的,在心跳关闭阶段,可能有连接被使用,导致需要关闭的空闲连接数减少.
// *
// * 所以每次关闭新连接时,先判断当前空闲连接数是否大于配置的最少空闲连接,如果为否,则结束本次关闭空闲连接操作。
// * 该方法修改之前:
// * 首先从ConnMap中获取 ildeCloseCount 个连接,然后关闭;在关闭中,可能又有连接被使用,导致可能多关闭一些链接,
// * 导致相对频繁的创建新连接和关闭连接
// *
// * 该方法修改之后:
// * ildeCloseCount 为预期要关闭的连接
// * 使用循环操作,首先在关闭之前,先再一次判断是否需要关闭连接,然后每次从ConnMap中获取一个空闲连接,然后进行关闭
// * edit by dingw at 2017.06.16
// */
// private void closeByIdleMany(int ildeCloseCount) {
// LOGGER.info("too many ilde cons ,close some for datasouce " + name);
// List<BackendConnection> readyCloseCons = new ArrayList<BackendConnection>(
// ildeCloseCount);
// for (ConQueue queue : conMap.getAllConQueue()) {
// readyCloseCons.addAll(queue.getIdleConsToClose(ildeCloseCount));
// if (readyCloseCons.size() >= ildeCloseCount) {
// break;
// }
// }
//
// for (BackendConnection idleCon : readyCloseCons) {
// if (idleCon.isBorrowed()) {
// LOGGER.warn("find idle con is using " + idleCon);
// }
// idleCon.close("too many idle con");
// }
//
/// / LOGGER.info("too many ilde cons ,close some for datasouce " + name);
/// /
/// / Iterator<ConQueue> conQueueIt = conMap.getAllConQueue().iterator();
/// / ConQueue queue = null;
/// / if(conQueueIt.hasNext()) {
/// / queue = conQueueIt.next();
/// / }
/// /
/// / for(int i = 0; i < ildeCloseCount; i ++ ) {
/// /
/// / if(!needCloseIdleConnection() || queue == null) {
/// / break; //如果当时空闲连接数没有超过最小配置连接数,则结束本次连接关闭
/// / }
/// /
/// / LOGGER.info("cur conns:" + getTotalConnectionsSafe() );
/// /
/// / BackendConnection idleCon = queue.takeIdleCon(false);
/// /
/// / while(idleCon == null && conQueueIt.hasNext()) {
/// / queue = conQueueIt.next();
/// / idleCon = queue.takeIdleCon(false);
/// / }
/// /
/// / if(idleCon == null) {
/// / break;
/// / }
/// /
/// / if (idleCon.isBorrowed() ) {
/// / LOGGER.warn("find idle con is using " + idleCon);
/// / }
/// / idleCon.close("too many idle con");
/// /
/// / }
//
// }
//
// private void createByIdleLitte(int idleCons, int createCount) {
// LOGGER.info("create connections ,because idle connection not enough ,cur is "
// + idleCons
// + ", minCon is "
// + hostConfig.getMinCon()
// + " for "
// + name);
// NewConnectionRespHandler simpleHandler = new NewConnectionRespHandler();
//
// final String[] schemas = dbPool.getSchemas();
// for (int i = 0; i < createCount; i++) {
// if (this.getActiveCount() + this.getIdleCount() >= size) {
// break;
// }
// try {
// // creat new connection
// this.createNewConnection(simpleHandler, null, schemas[i
// % schemas.length]);
// } catch (IOException e) {
// LOGGER.warn("create connection err " + e);
// }
//
// }
// }
//
// public int getActiveCount() {
// return this.conMap.getActiveCountForDs(this);
// }
//
//
//
// public void clearCons(String reason) {
// this.conMap.clearConnections(reason, this);
// }
//
// public void startHeartbeat() {
// heartbeat.start();
// }
//
// public void stopHeartbeat() {
// heartbeat.stop();
// }
//
// public void doHeartbeat() {
// // 未到预定恢复时间,不执行心跳检测。
// if (TimeUtil.currentTimeMillis() < heartbeatRecoveryTime) {
// return;
// }
//
// if (!heartbeat.isStop()) {
// try {
// heartbeat.heartbeat();
// } catch (Exception e) {
// LOGGER.error(name + " heartbeat error.", e);
// }
// }
// }
//
// private BackendConnection takeCon(BackendConnection conn,
// final ResponseHandler handler, final Object attachment,
// String schema) {
//
// conn.setBorrowed(true);
//
/// / if(takeConnectionContext.putIfAbsent(conn.getId(), TAKE_CONNECTION_FLAG) == null) {
/// / incrementActiveCountSafe();
/// / }
//
//
// if (!conn.getSchema().equals(schema)) {
// // need do schema syn in before sql send
// conn.setSchema(schema);
// }
// ConQueue queue = conMap.getSchemaConQueue(schema);
// queue.incExecuteCount();
// conn.setAttachment(attachment);
// conn.setLastTime(System.currentTimeMillis()); // 每次取连接的时候,更新下lasttime,防止在前端连接检查的时候,关闭连接,导致sql执行失败
// handler.connectionAcquired(conn);
// return conn;
// }
//
// private void createNewConnection(final ResponseHandler handler,
// final Object attachment, final String schema) throws IOException {
// // aysn create connection
// MycatServer.getInstance().getBusinessExecutor().execute(new Runnable() {
// public void run() {
// try {
// createNewConnection(new DelegateResponseHandler(handler) {
// @Override
// public void connectionError(Throwable e, BackendConnection conn) {
// //decrementTotalConnectionsSafe(); // 如果创建连接失败,将当前连接数减1
// handler.connectionError(e, conn);
// }
//
// @Override
// public void connectionAcquired(BackendConnection conn) {
// takeCon(conn, handler, attachment, schema);
// }
// }, schema);
// } catch (IOException e) {
// handler.connectionError(e, null);
// }
// }
// });
// }
//
// public void getConnection(String schema, boolean autocommit,
// final ResponseHandler handler, final Object attachment)
// throws IOException {
//
// // 从当前连接map中拿取已建立好的后端连接
// BackendConnection con = this.conMap.tryTakeCon(schema, autocommit);
// if (con != null) {
// //如果不为空,则绑定对应前端请求的handler
// takeCon(con, handler, attachment, schema);
// return;
//
// } else { // this.getActiveCount并不是线程安全的(严格上说该方法获取数量不准确),
/// / int curTotalConnection = this.totalConnection.get();
/// / while(curTotalConnection + 1 <= size) {
/// /
/// / if (this.totalConnection.compareAndSet(curTotalConnection, curTotalConnection + 1)) {
/// / LOGGER.info("no ilde connection in pool,create new connection for " + this.name + " of schema " + schema);
/// / createNewConnection(handler, attachment, schema);
/// / return;
/// / }
/// /
/// / curTotalConnection = this.totalConnection.get(); //CAS更新失败,则重新判断当前连接是否超过最大连接数
/// /
/// / }
/// /
/// / // 如果后端连接不足,立即失败,故直接抛出连接数超过最大连接异常
/// / LOGGER.error("the max activeConnnections size can not be max than maxconnections:" + curTotalConnection);
/// / throw new IOException("the max activeConnnections size can not be max than maxconnections:" + curTotalConnection);
//
// int activeCons = this.getActiveCount();// 当前最大活动连接
// if (activeCons + 1 > size) {// 下一个连接大于最大连接数
// LOGGER.error("the max activeConnnections size can not be max than maxconnections");
// throw new IOException("the max activeConnnections size can not be max than maxconnections");
// } else { // create connection
// LOGGER.info("no ilde connection in pool,create new connection for " + this.name + " of schema " + schema);
// createNewConnection(handler, attachment, schema);
// }
// }
// }
//
// /**
// * 是否超过最大连接数
// * @return
// */
/// / private boolean exceedMaxConnections() {
/// / return this.totalConnection.get() + 1 > size;
/// / }
/// /
/// / public int decrementActiveCountSafe() {
/// / return this.activeCount.decrementAndGet();
/// / }
/// /
/// / public int incrementActiveCountSafe() {
/// / return this.activeCount.incrementAndGet();
/// / }
/// /
/// / public int getActiveCountSafe() {
/// / return this.activeCount.get();
/// / }
/// /
/// / public int getTotalConnectionsSafe() {
/// / return this.totalConnection.get();
/// / }
/// /
/// / public int decrementTotalConnectionsSafe() {
/// / return this.totalConnection.decrementAndGet();
/// / }
/// /
/// / public int incrementTotalConnectionSafe() {
/// / return this.totalConnection.incrementAndGet();
/// / }
//
// private void returnCon(BackendConnection c) {
//
// c.setAttachment(null);
// c.setBorrowed(false);
// c.setLastTime(TimeUtil.currentTimeMillis());
// ConQueue queue = this.conMap.getSchemaConQueue(c.getSchema());
//
// boolean ok = false;
// if (c.isAutocommit()) {
// ok = queue.getAutoCommitCons().offer(c);
// } else {
// ok = queue.getManCommitCons().offer(c);
// }
//
/// / if(c.getId() > 0 && takeConnectionContext.remove(c.getId(), TAKE_CONNECTION_FLAG) ) {
/// / decrementActiveCountSafe();
/// / }
//
// if(!ok) {
// LOGGER.warn("can't return to pool ,so close con " + c);
// c.close("can't return to pool ");
//
// }
//
// }
//
// public void releaseChannel(BackendConnection c) {
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("release channel " + c);
// }
// // release connection
// returnCon(c);
// }
//
// public void connectionClosed(BackendConnection conn) {
// ConQueue queue = this.conMap.getSchemaConQueue(conn.getSchema());
// if (queue != null ) {
// queue.removeCon(conn);
// }
//
/// / decrementTotalConnectionsSafe();
// }
//
// /**
// * 创建新连接
// */
// public abstract void createNewConnection(ResponseHandler handler, String schema) throws IOException;
//
// /**
// * 测试连接,用于初始化及热更新配置检测
// */
// public abstract boolean testConnection(String schema) throws IOException;
//
// public long getHeartbeatRecoveryTime() {
// return heartbeatRecoveryTime;
// }
//
// public void setHeartbeatRecoveryTime(long heartbeatRecoveryTime) {
// this.heartbeatRecoveryTime = heartbeatRecoveryTime;
// }
//
// public DBHostConfig getConfig() {
// return config;
// }
//
// public boolean isAlive() {
// return getHeartbeat().getStatus() == DBHeartbeat.OK_STATUS;
// }
// }
implementation
uses
MyCat.Util, MyCat.Util.Logger;
{ TConQueue }
constructor TConnectionQueue.Create;
begin
FAutoCommitCons := TBackEndConnectionList.Create;
FManCommitCons := TBackEndConnectionList.Create;
end;
function TConnectionQueue.GetExecuteCount: Int64;
begin
Result := FExecuteCount;
end;
procedure TConnectionQueue.IncExecuteCount;
begin
Inc(FExecuteCount);
end;
function TConnectionQueue.RemoveConnection(Connection
: IBackEndConnection): Boolean;
var
Count: Integer;
begin
TMonitor.Enter(FAutoCommitCons);
try
Count := FAutoCommitCons.EraseValue(Connection);
finally
TMonitor.Exit(FAutoCommitCons);
end;
if Count = 0 then
begin
TMonitor.Enter(FManCommitCons);
try
Count := FManCommitCons.EraseValue(Connection);
finally
TMonitor.Exit(FManCommitCons);
end;
end;
Result := Count <> 0;
end;
function TConnectionQueue.TakeIdleCon(AutoCommit: Boolean): IBackEndConnection;
var
List1: TBackEndConnectionList;
List2: TBackEndConnectionList;
begin
if AutoCommit then
begin
List1 := FAutoCommitCons;
List2 := FManCommitCons;
end
else
begin
List1 := FManCommitCons;
List2 := FAutoCommitCons;
end;
TMonitor.Enter(List1);
try
Result := List1.Front;
List1.PopFront;
finally
TMonitor.Exit(List1);
end;
if (Result = nil) or (Result.ConnectStatus in [csDisconnected, csClosed]) then
begin
TMonitor.Enter(List2);
try
Result := List2.Front;
List2.PopFront;
finally
TMonitor.Exit(List2);
end;
end;
if Result.ConnectStatus in [csDisconnected, csClosed] then
begin
Result := nil;
end;
end;
{ TConnectionHeartBeatHandler }
procedure TConnectionHeartBeatHandler.AbandTimeOuttedConns;
var
AbandConnections: IBackEndConnectionList;
CurTime: Int64;
Iterator: IHeartBeatConnectionMapIterator;
HeartBeatConnection: THeartBeatConnection;
Connection: IBackEndConnection;
begin
if FAllConnections.IsEmpty then
begin
Exit;
end;
AbandConnections := TBackEndConnectionList.Create;
CurTime := TTimeUtil.CurrentTimeMillis;
Iterator := FAllConnections.ItBegin;
while not Iterator.IsEqual(FAllConnections.ItEnd) do
begin
HeartBeatConnection := Iterator.Value;
if HeartBeatConnection.TimeOutTimestamp < CurTime then
begin
AbandConnections.Insert(HeartBeatConnection.Connection);
FAllConnections.Erase(Iterator);
end;
Iterator.Next;
end;
if not AbandConnections.IsEmpty then
begin
for Connection in AbandConnections do
begin
try
// if(con.isBorrowed())
Connection.Close;
AppendLog('heartbeat timeout');
except
on E: Exception do
begin
AppendLog('close Err: %s', [E.Message], ltWarning);
end;
end;
end;
end;
end;
constructor TConnectionHeartBeatHandler.Create;
begin
FAllConnections := THeartBeatConnectionHashMap.Create;
end;
procedure TConnectionHeartBeatHandler.DoHeartBeat
(Connection: IBackEndConnection; sql: string);
begin
AppendLog('do heartbeat for con ' + Connection.PeerAddr);
try
if FAllConnections.Find(Connection.UID).IsEqual(FAllConnections.ItEnd) then
begin
FAllConnections.Insert(Connection.UID,
THeartBeatConnection.Create(Connection));
Connection.SetResponseHandler(Self);
Connection.Query(sql);
end;
except
on E: Exception do
begin
ExecuteException(conn, E);
end;
end;
end;
{ TDBHeartbeat }
constructor TDBHeartbeat.Create;
begin
FHeartbeatTimeout := DEFAULT_HEARTBEAT_TIMEOUT; // 心跳超时时间
FHeartbeatRetry := DEFAULT_HEARTBEAT_RETRY; // 检查连接发生异常到切换,重试次数
FIsStop := true;
FIsChecking := false;
FErrorCount := 0;
FRecorder := THeartbeatRecorder.Create;
FAsynRecorder := TDataSourceSyncRecorder.Create;
end;
{ TPhysicalDatasource }
constructor TPhysicalDatasource.Create(Config: TDBHostConfig;
HostConfig: TDataHostConfig; IsReadNode: Boolean);
begin
FConnHeartBeatHanler:
TConnectionHeartBeatHandler = new ConnectionHeartBeatHandler();
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus, Vcl.Buttons,
Vcl.ExtCtrls, IniFiles,
uControllerThread;
type
TfmMain = class(TForm)
GroupBox1: TGroupBox;
lbTurn: TListBox;
PopupMenu1: TPopupMenu;
btnTurnAdd: TMenuItem;
btnTurnDel: TMenuItem;
GroupBox2: TGroupBox;
lbCode: TListBox;
PopupMenu2: TPopupMenu;
btnCodeAdd: TMenuItem;
btnCodeDel: TMenuItem;
btnStart: TBitBtn;
Label1: TLabel;
cbPort: TComboBox;
procedure btnTurnAddClick(Sender: TObject);
procedure btnTurnDelClick(Sender: TObject);
procedure btnCodeAddClick(Sender: TObject);
procedure btnCodeDelClick(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure JobError(AMessage: string);
private
FControllerThread: TControllerThread;
public
{ Public declarations }
end;
var
fmMain: TfmMain;
implementation
{$R *.dfm}
procedure TfmMain.btnCodeAddClick(Sender: TObject);
var
n: string;
begin
if InputQuery('Добавление кода', 'Код', n) then
lbCode.Items.Add(n);
end;
procedure TfmMain.btnCodeDelClick(Sender: TObject);
begin
if lbCode.ItemIndex < 0 then
exit;
if MessageDlg('Вы действительно хотите удалить запись?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
lbCode.Items.Delete(lbCode.ItemIndex);
end;
procedure TfmMain.btnStartClick(Sender: TObject);
begin
if lbTurn.Items.Count = 0 then
begin
MessageDlg('Список адресов пуст', mtError, [mbOk], 0);
exit;
end;
if btnStart.Caption = 'Отключиться' then
begin
FControllerThread.Terminate;
btnStart.Caption := 'Подключиться';
btnTurnAdd.Enabled := true;
btnTurnDel.Enabled := true;
btnCodeAdd.Enabled := true;
btnCodeDel.Enabled := true;
end
else
begin
FControllerThread := TControllerThread.Create(cbPort.ItemIndex + 1, lbTurn.Items, lbCode.Items);
FControllerThread.OnJobError := JobError;
btnStart.Caption := 'Отключиться';
btnTurnAdd.Enabled := false;
btnTurnDel.Enabled := false;
btnCodeAdd.Enabled := false;
btnCodeDel.Enabled := false;
end;
end;
procedure TfmMain.btnTurnAddClick(Sender: TObject);
var
n: string;
begin
if InputQuery('Добавление турникета', 'Номер турникета', n) then
lbTurn.Items.Add(n);
end;
procedure TfmMain.btnTurnDelClick(Sender: TObject);
begin
if lbTurn.ItemIndex < 0 then
exit;
if MessageDlg('Вы действительно хотите удалить запись?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
lbTurn.Items.Delete(lbTurn.ItemIndex);
end;
procedure TfmMain.FormClose(Sender: TObject; var Action: TCloseAction);
var
ini: TIniFile;
i: integer;
begin
ini := TIniFile.Create(ExtractFilePath(Application.Exename) + 'Settings.ini');
try
ini.EraseSection('Turn');
ini.EraseSection('Code');
if lbTurn.Items.Count > 0 then
begin
for i := 0 to lbTurn.Items.Count - 1 do
ini.WriteString('Turn', IntToStr(i), lbTurn.Items[i]);
end;
if lbCode.Items.Count > 0 then
begin
for i := 0 to lbCode.Items.Count - 1 do
ini.WriteString('Code', IntToStr(i), lbCode.Items[i]);
end;
finally
ini.Free;
end;
end;
procedure TfmMain.FormShow(Sender: TObject);
var
ini: TIniFile;
sl: TStringList;
i: integer;
s: string;
begin
ini := TIniFile.Create(ExtractFilePath(Application.Exename) + 'Settings.ini');
sl := TStringList.Create;
try
if ini.SectionExists('Turn') then
begin
ini.ReadSection('Turn', sl);
if sl.Count > 0 then
for i := 0 to sl.Count - 1 do
begin
s := ini.ReadString('Turn', sl[i], '0');
lbTurn.Items.Add(s);
end;
end;
if ini.SectionExists('Code') then
begin
ini.ReadSection('Code', sl);
if sl.Count > 0 then
for i := 0 to sl.Count - 1 do
begin
s := ini.ReadString('Code', sl[i], '0');
lbCode.Items.Add(s);
end;
end;
finally
ini.Free;
sl.Free;
end;
end;
procedure TfmMain.JobError(AMessage: string);
begin
MessageDlg(AMessage, mtError, [mbOk], 0);
btnStart.OnClick(fmMain);
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ImgList, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
ImageList1: TImageList;
Image1: TImage;
NextButton: TButton;
Label1: TLabel;
procedure NextButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FCurrentImage: Integer;
procedure UpdateImage;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.UpdateImage;
resourcestring
SBook = 'Book';
SSign = 'Sign';
SPlane = 'Plane';
var
bitmap: TBitmap;
begin
// Update text
case FCurrentImage of
0: Label1.Caption := SBook;
1: Label1.Caption := SSign;
2: Label1.Caption := SPlane;
else
Label1.Caption := '';
end;
// Update image
bitmap := TBitmap.Create;
try
ImageList1.GetBitmap(FCurrentImage, bitmap);
Image1.Picture.Graphic := bitmap;
finally
bitmap.Free;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
UpdateImage;
end;
procedure TForm1.NextButtonClick(Sender: TObject);
begin
FCurrentImage := (FCurrentImage + 1) mod ImageList1.Count;
UpdateImage;
end;
end.
|
Program min_array;
const N=1000;
type TArray=array[1..N]of integer;
procedure Readarr(var x:tarray;var z:integer);
var i:integer;
begin
i:=0;
repeat
inc(i);
Readln(x[i]);
until x[i]=0;
z:=i-1;
end;
procedure Writearr(c:tarray; z:integer);
var i:integer;
begin
for i:=1 to z do
begin
Write(c[i], ' ');
end;
Writeln;
end;
procedure Swap(var x,y:integer);
var tp:integer;
begin
tp:=x;
x:=y;
y:=tp;
end;
function IndexMin(numbers:Tarray; start,finish:integer):integer;
var x,i:integer;
begin
x:=start;
for i:=start to finish do
begin
if(numbers[i]<numbers[x]) then
x:=i;
end;
IndexMin:=x;
end;
procedure Sort(var numbers:tarray; len:integer);
var i:integer;
begin
for i:=1 to len-1 do
Swap(numbers[i], numbers[IndexMin(numbers,i,len)]);
end;
var len:integer;
z:tarray;
begin
Readarr(z,len);
Sort(z,len);
Writearr(z,len);
Readln;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLCameraController<p>
Component for animating camera movement.
Can be used to zoom in/out, for linear movement, orbiting and Google Earth - like "fly-to"
Main purpose was the SafeOrbitAndZoomToPos method, the others are usable as well
<b>History : </b><font size=-1><ul>
<li>24/07/09 - DaStr - Got rid of compiler hints
<li>20/03/09 - DanB - Donated to GLScene by Bogdan Deaky.
</ul></font>
}
// ######## NOTE: *MAY* STILL BE WORK IN PROGRESS ON THIS COMPONENT ##########
//GLCameraController v1.1
//Bogdan Deaky / Bluemind Software
//Bluemind Software allows free usage and distribution of this component
//Do let the author know if you do code changes/improvements
//bogdan@bluemind-software.ro
//v1.0 2007
//v1.1 2009 (for GLScene, ships with glscene_icon_TGLCameraController.bmp)
//IMPORTANT!
//You should block user GUI access to the GLSceneViewer
//while movement is being done, check the AllowUserAction property!
//Block user GUI access while AllowUserAction is false to avoid behaviour errors
//simply put
//if GLCameraController1.AllowUserAction then
// //do whatever you want on mouse move, form wheel etc
// methods and properties are explained in the interface section (through comments)
// additional comments might apear in implementation section where needed
unit GLCameraController;
interface
uses GLScene, Classes, GLCadencer;
type
TGLCameraController = class(TComponent)
private
//private variables - explained at the respective properties
FAllowUserAction:boolean;
FCamera:TGLCamera;
FCadencer:TGLCadencer;
//fields used by SafeOrbitAndZoomToPos
FsoSafeDist,FsoTimeToSafePlacement,FsoTimeToOrbit,FsoTimeToZoomBackIn:double;
//used to break current movement
Stopped:boolean;
//private methods
//used to test whether camera and cadencer are assigned
//TestExtendedPremises = true -> will test also for Camera.TargetObject
function TestPremises(TestExtendedPremises:boolean):boolean;
//this adjusts camera depth of view after each movement
//contains a call to Application.Processmessages for not blocking the app
procedure AdjustScene;
//after AdjustScene the Camera.DepthofView will be modified
//if you want to zoom back in from GUI
//you should use something like
// Camera.DepthOfView:=2*Camera.DistanceToTarget+2*camera.TargetObject.BoundingSphereRadius;
public
//constructor
constructor Create(AOwner:TComponent); override;
//methods
//linear movement from current pos
procedure MoveToPos(x,y,z,time:double);
//orbiting from current pos to the pos where
//the camera points at the camera.targetObject TROUGH the given point
//it will not move to the given point(!), use SafeOrbitAndZoomToPos instead
//there has to be a camera.targetObject assigned!
procedure OrbitToPos(x,y,z,time:double);
//old commented prov with vectors - it's here only for reference
//procedure OrbitToPosVector(x,y,z,time:double);
//zooms in/out by moving to the given distance from camera.targetObject
//there has to be a camera.targetObject assigned!
procedure ZoomToDistance(Distance,Time:double);
//google earth - like "fly-to"
// = zoom out to safe distance, orbit, and then zoom in to the given point
//there has to be a camera.targetObject assigned!
procedure SafeOrbitAndZoomToPos(x,y,z:double);
//Dan Bartlett said in the GLScene newsgroup that it might be a good idea
//to introduce ability to stop movement and return control to user
//here it is
procedure StopMovement;
published
//properties
//assign a TGLCamera instance to this
property Camera:TGLCamera read FCamera write FCamera;
//assign a TGLCadencer instance to this
property Cadencer:TGLCadencer read FCadencer write FCadencer;
//specifies whether user should be able interract with the GLSceneViewer
//it is set to false while the camera is moving and
//coders should check this value and block GUI access to GLSceneViewer
property AllowUserAction:boolean read FAllowUserAction;
//safe distance to avoid moving the camera trough the camera.targetObject
//while performing SafeOrbitAndZoomToPos
property soSafeDistance:double read FsoSafeDist write FsoSafeDist;
//time to zoom in/out to the safe position while performing SafeOrbitAndZoomToPos
property soTimeToSafePlacement:double read FsoTimeToSafePlacement write FsoTimeToSafePlacement;
//time to orbit while performing SafeOrbitAndZoomToPos
property soTimeToOrbit:double read FsoTimeToOrbit write FsoTimeToOrbit;
//time to zoom in/out to the given final position while performing SafeOrbitAndZoomToPos
property soTimeToZoomBackIn:double read FsoTimeToZoomBackIn write FsoTimeToZoomBackIn;
end;
implementation
uses SysUtils, Forms, GLVectorTypes, GLVectorGeometry{, Dialogs};
//---TGLCameraMover
function TGLCameraController.TestPremises(TestExtendedPremises:boolean):boolean;
begin
result:=true;
//check camera assignament
if not assigned(Camera) then
begin
// result:=false;
raise Exception.Create('CameraMover needs to have camera assigned');
exit;
end;
//check cadencer assignament
if not assigned(Cadencer) then
begin
// result:=false;
raise Exception.Create('CameraMover needs to have Cadencer assigned');
exit;
end;
if TestExtendedPremises then
//TestExtendedPremises = check camera.TargetObject assignament
if not assigned(Camera.TargetObject) then
begin
// result:=false;
raise Exception.Create('This movement needs needs to have Camera.TargetObject assigned');
end;
end;
procedure TGLCameraController.AdjustScene;
begin
Camera.DepthOfView:=2*Camera.DistanceToTarget+2*camera.TargetObject.BoundingSphereRadius;
Camera.TransformationChanged;
Application.ProcessMessages; //I call this for not blocking the app while moving the camera
end;
procedure TGLCameraController.StopMovement;
begin
Stopped:=true;
end;
procedure TGLCameraController.MoveToPos(x,y,z,time:double);
var InitialCameraPos, FinalCameraPos, Vect: TVector;
StartTime, TimeElapsed :double;
begin
if not TestPremises(true) then exit;
FAllowUserAction:=false;
//assign initial and final positions
InitialCameraPos:=VectorSubtract(Camera.AbsolutePosition, Camera.TargetObject.AbsolutePosition);
MakeVector(FinalCameraPos, x, y, z);
//movement
StartTime:=Cadencer.GetCurrentTime;
TimeElapsed:=Cadencer.GetCurrentTime-StartTime;
while TimeElapsed<time do
begin
TimeElapsed:=Cadencer.GetCurrentTime-StartTime;
Vect:=VectorLerp(InitialCameraPos,FinalCameraPos,TimeElapsed/time);
if Assigned(Camera.Parent) then
Vect:=Camera.Parent.AbsoluteToLocal(Vect);
Camera.Position.AsVector:=Vect;
AdjustScene;
if Stopped then begin Stopped:=false; break; end;
end;
//finish movement - adjust to final point
vect:=FinalCameraPos;
if Assigned(Camera.Parent) then
Vect:=Camera.Parent.AbsoluteToLocal(Vect);
Camera.Position.AsVector:=Vect;
AdjustScene;
FAllowUserAction:=true;
end;
procedure TGLCameraController.OrbitToPos(x,y,z,time:double);
var pitchangle0,pitchangle1,turnangle0,turnangle1,
pitchangledif,turnangledif,
dx0,dy0,dz0,dx1,dy1,dz1,speedx,speedz,
StartTime,LastTime,TimeElapsed:double;
sign:shortint;
InitialCameraPos, AbsFinalCameraPos, FinalCameraPos, Vect: TVector;
Radius: double;
begin
//all vector approaches have failed
//some problems with VectorAngleLerp which internally uses Quaterinion Slerp
//that is known to be problematic in a couple of particular cases
//but I think the implementation is also wrong
//also, a method where vectorlerp + normalize + scale was developed (OrbitToPosVector)
//but the velocity is not constant (of course) + other problems in particular cases
//this method works superbly, as long as the camera position is
//a combination of two 0s and one 1(or even -1)
//the final adjustment is done with vectors and
//the display is cleared for some reason in you position the camera on the Up axis.
//this method does not have the problems of Slerp or general spherical interpolation
//it computes the difference between Pitch and Turn Angles and rotates the camera around the target
//it will never try to go over the blocking upper/lower points! - this cause error in the mentioned algorithms
if not TestPremises(true) then exit;
FAllowUserAction:=false;
//determine relative positions to determine the lines which form the angles
//distances from initial camera pos to target object
dx0:=Camera.Position.X-Camera.TargetObject.Position.x;
dy0:=Camera.Position.Y-Camera.TargetObject.Position.Y;
dz0:=Camera.Position.Z-Camera.TargetObject.Position.Z;
//distances from final camera pos to target object
dx1:=X-Camera.TargetObject.Position.x;
dy1:=Y-Camera.TargetObject.Position.Y;
dz1:=Z-Camera.TargetObject.Position.Z;
//just to make sure we don't get division by 0 exceptions
if dx0=0 then dx0:=0.001;
if dy0=0 then dy0:=0.001;
if dz0=0 then dz0:=0.001;
if dx1=0 then dx1:=0.001;
if dy1=0 then dy1:=0.001;
if dz1=0 then dz1:=0.001;
//determine "pitch" and "turn" angles for the initial and final camera position
//the formulas differ depending on the camera.Up vector
//I tested all quadrants for all possible integer Camera.Up directions
if abs(Camera.Up.AsAffineVector[2])=1 then //Z=1/-1
begin
sign:= round(Camera.Up.AsAffineVector[2]/abs(Camera.Up.AsAffineVector[2]));
pitchangle0:=arctan(dz0/sqrt(sqr(dx0)+sqr(dy0)));
pitchangle1:=arctan(dz1/sqrt(sqr(dx1)+sqr(dy1)));
turnangle0:=arctan(dy0/dx0);
if (dx0<0) and (dy0<0) then turnangle0:=-(pi-turnangle0)
else if (dx0<0) and (dy0>0) then turnangle0:=-(pi-turnangle0);
turnangle1:=arctan(dy1/dx1);
if (dx1<0) and (dy1<0) then turnangle1:=-(pi-turnangle1)
else if (dx1<0) and (dy1>0) then turnangle1:=-(pi-turnangle1);
end
else if abs(Camera.Up.AsAffineVector[1])=1 then //Y=1/-1
begin
sign:= round(Camera.Up.AsAffineVector[1]/abs(Camera.Up.AsAffineVector[1]));
pitchangle0:=arctan(dy0/sqrt(sqr(dx0)+sqr(dz0)));
pitchangle1:=arctan(dy1/sqrt(sqr(dx1)+sqr(dz1)));
turnangle0:=-arctan(dz0/dx0);
if (dx0<0) and (dz0<0) then turnangle0:=-(pi-turnangle0)
else if (dx0<0) and (dz0>0) then turnangle0:=-(pi-turnangle0);
turnangle1:=-arctan(dz1/dx1);
if (dx1<0) and (dz1<0) then turnangle1:=-(pi-turnangle1)
else if (dx1<0) and (dz1>0) then turnangle1:=-(pi-turnangle1);
end
else if abs(Camera.Up.AsAffineVector[0])=1 then //X=1/-1
begin
sign:= round(Camera.Up.AsAffineVector[0]/abs(Camera.Up.AsAffineVector[0]));
pitchangle0:=arctan(dx0/sqrt(sqr(dz0)+sqr(dy0)));
pitchangle1:=arctan(dx1/sqrt(sqr(dz1)+sqr(dy1)));
turnangle0:=arctan(dz0/dy0);
if (dz0>0) and (dy0>0) then turnangle0:=-(pi-turnangle0)
else if (dz0<0) and (dy0>0) then turnangle0:=-(pi-turnangle0);
turnangle1:=arctan(dz1/dy1);
if (dz1>0) and (dy1>0) then turnangle1:=-(pi-turnangle1)
else if (dz1<0) and (dy1>0) then turnangle1:=-(pi-turnangle1);
end
else
begin
raise Exception.Create('The Camera.Up vector may contain only -1, 0 or 1');
exit;
end;
//determine pitch and turn angle differences
pitchangledif:=sign*(pitchangle1-pitchangle0);
turnangledif:=sign*(turnangle1-turnangle0);
if abs(turnangledif)>pi then turnangledif:=-abs(turnangledif)/turnangledif*(2*pi-abs(turnangledif));
//determine rotation speeds
speedx:=-pitchangledif/time;
speedz:=turnangledif/time;
StartTime:=Cadencer.GetCurrentTime;
LastTime:=StartTime;
//make the actual movement
while Cadencer.GetCurrentTime-StartTime<time do
begin
TimeElapsed:=(Cadencer.GetCurrentTime-LastTime);
LastTime:=Cadencer.GetCurrentTime;
Camera.MoveAroundTarget(radtodeg(speedx)*TimeElapsed,radtodeg(speedz)*TimeElapsed);
AdjustScene;
if Stopped then begin Stopped:=false; break; end;
end;
//finish movement - init vectors
InitialCameraPos:=VectorSubtract(Camera.AbsolutePosition, Camera.TargetObject.AbsolutePosition);
Radius:=VectorLength(InitialCameraPos);
MakeVector(AbsFinalCameraPos, x, y, z);
FinalCameraPos:=VectorSubtract(AbsFinalCameraPos, Camera.TargetObject.AbsolutePosition);
NormalizeVector(FinalCameraPos);
ScaleVector(FinalCameraPos, Radius);
//finish movement - adjust to final point
Vect:=FinalCameraPos;
if Assigned(Camera.Parent) then
Vect:=Camera.Parent.AbsoluteToLocal(Vect);
Camera.Position.AsVector:=Vect;
AdjustScene;
FAllowUserAction:=true;
end;
//OrbitToPosVector - old vector implementation - not working well
//I left it here for reference
//the try with VectorAngleLerp was deleted as it proved
//uselles at the time of development
{procedure TGLCameraController.OrbitToPosVector(x,y,z,time:double);
var InitialCameraPos, AbsFinalCameraPos, FinalCameraPos, Vect, MidWayVector: TVector;
StartTime, TimeElapsed, Radius :double;
begin
//I have tried VectorAngleLerp but it does not seem to work correctly
if not TestPremises(true) then exit;
FAllowUserAction:=false;
//assign initial and final positions
InitialCameraPos:=VectorSubtract(Camera.AbsolutePosition, Camera.TargetObject.AbsolutePosition);
Radius:=VectorLength(InitialCameraPos);
MakeVector(AbsFinalCameraPos, x, y, z);
FinalCameraPos:=VectorSubtract(AbsFinalCameraPos, Camera.TargetObject.AbsolutePosition);
NormalizeVector(FinalCameraPos);
ScaleVector(FinalCameraPos, Radius);
MidWayVector:=VectorLerp(InitialCameraPos,FinalCameraPos,0.499); //0.5 is more probable to give sometimes the 0 point
NormalizeVector(MidWayVector);
ScaleVector(MidWayVector, Radius);
//movement
StartTime:=Cadencer.GetCurrentTime;
TimeElapsed:=Cadencer.GetCurrentTime-StartTime;
while TimeElapsed<time*0.499 do
begin
TimeElapsed:=Cadencer.GetCurrentTime-StartTime;
Vect:=VectorLerp(InitialCameraPos,MidWayVector,TimeElapsed/(time*0.499));
NormalizeVector(Vect);
ScaleVector(Vect, Radius);
if Assigned(Camera.Parent) then
Vect:=Camera.Parent.AbsoluteToLocal(Vect);
Camera.Position.AsVector:=Vect;
AdjustScene;
end;
//finish half movement - adjust to mid point
vect:=MidWayVector;
if Assigned(Camera.Parent) then
Vect:=Camera.Parent.AbsoluteToLocal(Vect);
Camera.Position.AsVector:=Vect;
AdjustScene;
//showmessage(floattostr(Camera.Position.AsVector[0])+'/'+floattostr(Camera.Position.AsVector[1])+'/'+floattostr(Camera.Position.AsVector[2]));
StartTime:=Cadencer.GetCurrentTime;
TimeElapsed:=Cadencer.GetCurrentTime-StartTime;
while TimeElapsed<time*0.501 do
begin
TimeElapsed:=Cadencer.GetCurrentTime-StartTime;
Vect:=VectorLerp(MidWayVector,FinalCameraPos,TimeElapsed/(time*0.501));
NormalizeVector(Vect);
ScaleVector(Vect, Radius);
if Assigned(Camera.Parent) then
Vect:=Camera.Parent.AbsoluteToLocal(Vect);
Camera.Position.AsVector:=Vect;
AdjustScene;
end;
//finish movement - adjust to final point
vect:=FinalCameraPos;
if Assigned(Camera.Parent) then
Vect:=Camera.Parent.AbsoluteToLocal(Vect);
Camera.Position.AsVector:=Vect;
AdjustScene;
FAllowUserAction:=true;
end; }
procedure TGLCameraController.ZoomToDistance(Distance,Time:double);
var InitialCameraPos, FinalCameraPos, Vect: TVector;
StartTime, TimeElapsed :double;
begin
if not TestPremises(true) then exit;
FAllowUserAction:=false;
InitialCameraPos:=VectorSubtract(Camera.AbsolutePosition, Camera.TargetObject.AbsolutePosition);
//to determine final positon we normalize original pos and scale it with final distance
SetVector(FinalCameraPos, InitialCameraPos);
NormalizeVector(FinalCameraPos);
ScaleVector(FinalCameraPos,Distance);
//movement
StartTime:=Cadencer.GetCurrentTime;
TimeElapsed:=Cadencer.GetCurrentTime-StartTime;
while TimeElapsed<time do
begin
TimeElapsed:=Cadencer.GetCurrentTime-StartTime;
Vect:=VectorLerp(InitialCameraPos,FinalCameraPos,TimeElapsed/time);
if Assigned(Camera.Parent) then
Vect:=Camera.Parent.AbsoluteToLocal(Vect);
Camera.Position.AsVector:=Vect;
AdjustScene;
if Stopped then begin Stopped:=false; break; end;
end;
//finish movement - adjust to final point
vect:=FinalCameraPos;
if Assigned(Camera.Parent) then
Vect:=Camera.Parent.AbsoluteToLocal(Vect);
Camera.Position.AsVector:=Vect;
AdjustScene;
FAllowUserAction:=true;
end;
procedure TGLCameraController.SafeOrbitAndZoomToPos(x,y,z:double);
begin
//this was the main purpose of this component
//as you can see, it actually is a combination of the other 3 methods
if not TestPremises(true) then exit;
ZoomToDistance(soSafeDistance,soTimeToSafePlacement);
OrbitToPos(x,y,z,soTimeToOrbit);
MoveToPos(x,y,z,soTimeToZoomBackIn);
end;
constructor TGLCameraController.Create(AOwner:TComponent);
begin
inherited;
//initialize values
soSafeDistance:=10;
soTimeToSafePlacement:=1;
soTimeToOrbit:=2;
soTimeToZoomBackIn:=1;
FAllowUserAction:=true;
Stopped:=false;
end;
end.
|
(*
Category: SWAG Title: SORTING ROUTINES
Original name: 0055.PAS
Description: 8 Different Sorting Methods
Author: WAYEL A. AL-WOHAIBI
Date: 05-26-95 22:57
*)
{ Updated SORTING.SWG on May 26, 1995 }
{
>I've been programming for a couple years now, but there are certain things
>that you seldom just figure out on your own. One of them is the multitude
>of standard sorting techniques. I did learn these, however, in a class I
>took last year in Turbo Pascal. Let's see, Bubble Sort, Selection Sort,
>Quick Sort.. I think that's what they were called. Anyway, if anyone
>has the time and desire I'd appreciate a quick run-down of each and if
>possible some source for using them on a linked list. I remember most of
>the code to do them on arrays, but I forget which are the most efficient
>for each type of data.
Here is a program that I was given to demonstrate 8 different types of sorts.
I don't claim to know how they work, but it does shed some light on what the
best type probably is. BTW, it can be modified to allow for a random number
of sort elements (up to maxint div 10 I believe).
ALLSORT.PAS: Demonstration of various sorting methods.
Released to the public domain by Wayel A. Al-Wohaibi.
ALLSORT.PAS was written in Turbo Pascal 3.0 (but compatible with
TP6.0) while taking a pascal course in 1988. It is provided as is,
to demonstrate how sorting algorithms work. Sorry, no documentation
(didn't imagine it would be worth releasing) but bugs are included
too!
ALLSORT simply shows you how elements are rearranged in each
iteration of each of the eight popular sorting methods.
}
program SORTINGMETHODS;
uses
Crt;
const
N = 14; (* NO. OF DATA TO BE SORTED *)
Digits = 3; (* DIGITAL SIZE OF THE DATA *)
Range = 1000; (* RANGE FOR THE RANDOM GENERATOR *)
type
ArrayType = array[1..N] of integer;
TwoDimension = array[0..9, 1..N] of integer; (* FOR RADIX SORT ONLY *)
var
Data : ArrayType;
D : integer;
(*--------------------------------------------------------------------*)
procedure GetSortMethod;
begin
clrscr;
writeln;
writeln(' CHOOSE: ');
writeln(' ');
writeln(' 1 FOR SELECT SORT ');
writeln(' 2 FOR INSERT SORT ');
writeln(' 3 FOR BUBBLE SORT ');
writeln(' 4 FOR SHAKE SORT ');
writeln(' 5 FOR HEAP SORT ');
writeln(' 6 FOR QUICK SORT ');
writeln(' 7 FOR SHELL SORT ');
writeln(' 8 FOR RADIX SORT ');
writeln(' 9 TO EXIT ALLSORT ');
writeln(' ');
writeln;
readln(D)
end;
procedure LoadList;
var
I : integer;
begin
for I := 1 to N do
Data[I] := random(Range)
end;
procedure ShowInput;
var
I : integer;
begin
clrscr;
write('INPUT :');
for I := 1 to N do
write(Data[I]:5);
writeln
end;
procedure ShowOutput;
var
I : integer;
begin
write('OUTPUT:');
for I := 1 to N do
write(Data[I]:5)
end;
procedure Swap(var X, Y : integer);
var
Temp : integer;
begin
Temp := X;
X := Y;
Y := Temp
end;
(*-------------------------- R A D I X S O R T ---------------------*)
function Hash(Number, H : integer) : integer;
begin
case H of
3 : Hash := Number mod 10;
2 : Hash := (Number mod 100) div 10;
1 : Hash := Number div 100
end
end;
procedure CleanArray(var TwoD : TwoDimension);
var
I, J : integer;
begin
for I := 0 to 9 do
for J := 1 to N do
TwoD[I, J] := 0
end;
procedure PlaceIt(var X : TwoDimension; Number, I : integer);
var
J : integer;
Empty : boolean;
begin
J := 1;
Empty := false;
repeat
if (X[I, J] > 0) then
J := J + 1
else
Empty := true;
until (Empty) or (J = N);
X[I, J] := Number
end;
procedure UnLoadIt(X : TwoDimension; var Passed : ArrayType);
var
I,
J,
K : integer;
begin
K := 1;
for I := 0 to 9 do
for J := 1 to N do
begin
if (X[I, J] > 0) then
begin
Passed[K] := X[I, J];
K := K + 1
end
end
end;
procedure RadixSort(var Pass : ArrayType; N : integer);
var
Temp : TwoDimension;
Element,
Key,
Digit,
I : integer;
begin
for Digit := Digits downto 1 do
begin
CleanArray(Temp);
for I := 1 to N do
begin
Element := Pass[I];
Key := Hash(Element, Digit);
PlaceIt(Temp, Element, Key)
end;
UnLoadIt(Temp, Pass);
ShowOutput;
readln
end
end;
(*-------------------------- H E A P S O R T -----------------------*)
procedure ReHeapDown(var HEAPData : ArrayType; Root, Bottom : integer);
var
HeapOk : boolean;
MaxChild : integer;
begin
HeapOk := false;
while (Root * 2 <= Bottom)
and not HeapOk do
begin
if (Root * 2 = Bottom) then
MaxChild := Root * 2
else
if (HEAPData[Root * 2] > HEAPData[Root * 2 + 1]) then
MaxChild := Root * 2
else
MaxChild := Root * 2 + 1;
if (HEAPData[Root] < HEAPData[MaxChild]) then
begin
Swap(HEAPData[Root], HEAPData[MaxChild]);
Root := MaxChild
end
else
HeapOk := true
end
end;
procedure HeapSort(var Data : ArrayType; NUMElementS : integer);
var
NodeIndex : integer;
begin
for NodeIndex := (NUMElementS div 2) downto 1 do
ReHeapDown(Data, NodeIndex, NUMElementS);
for NodeIndex := NUMElementS downto 2 do
begin
Swap(Data[1], Data[NodeIndex]);
ReHeapDown(Data, 1, NodeIndex - 1);
ShowOutput;
readln;
end
end;
(*-------------------------- I N S E R T S O R T -------------------*)
procedure StrInsert(var X : ArrayType; N : integer);
var
J,
K,
Y : integer;
Found : boolean;
begin
for J := 2 to N do
begin
Y := X[J];
K := J - 1;
Found := false;
while (K >= 1)
and (not Found) do
if (Y < X[K]) then
begin
X[K + 1] := X[K];
K := K - 1
end
else
Found := true;
X[K + 1] := Y;
ShowOutput;
readln
end
end;
(*-------------------------- S H E L L S O R T ---------------------*)
procedure ShellSort(var A : ArrayType; N : integer);
var
Done : boolean;
Jump,
I,
J : integer;
begin
Jump := N;
while (Jump > 1) do
begin
Jump := Jump div 2;
repeat
Done := true;
for J := 1 to (N - Jump) do
begin
I := J + Jump;
if (A[J] > A[I]) then
begin
Swap(A[J], A[I]);
Done := false
end;
end;
until Done;
ShowOutput;
readln
end
end;
(*-------------------------- B U B B L E S O R T -------------------*)
procedure BubbleSort(var X : ArrayType; N : integer);
var
I,
J : integer;
begin
for I := 2 to N do
begin
for J := N downto I do
if (X[J] < X[J - 1]) then
Swap(X[J - 1], X[J]);
ShowOutput;
readln
end
end;
(*-------------------------- S H A K E S O R T ---------------------*)
procedure ShakeSort(var X : ArrayType; N : integer);
var
L,
R,
K,
J : integer;
begin
L := 2;
R := N;
K := N;
repeat
for J := R downto L do
if (X[J] < X[J - 1]) then
begin
Swap(X[J], X[J - 1]);
K := J
end;
L := K + 1;
for J := L to R do
if (X[J] < X[J - 1]) then
begin
Swap(X[J], X[J - 1]);
K := J
end;
R := K - 1;
ShowOutput;
readln;
until L >= R
end;
(*-------------------------- Q W I C K S O R T ---------------------*)
procedure Partition(var A : ArrayType; First, Last : integer);
var
Right,
Left : integer;
V : integer;
begin
V := A[(First + Last) div 2];
Right := First;
Left := Last;
repeat
while (A[Right] < V) do
Right := Right + 1;
while (A[Left] > V) do
Left := Left - 1;
if (Right <= Left) then
begin
Swap(A[Right], A[Left]);
Right := Right + 1;
Left := Left - 1
end;
until Right > Left;
ShowOutput;
readln;
if (First < Left) then
Partition(A, First, Left);
if (Right < Last) then
Partition(A, Right, Last)
end;
procedure QuickSort(var List : ArrayType; N : integer);
var
First,
Last : integer;
begin
First := 1;
Last := N;
if (First < Last) then
Partition(List, First, Last)
end;
(*-------------------------- S E L E C T S O R T -------------------*)
procedure StrSelectSort(var X : ArrayType; N : integer);
var
I,
J,
K,
Y : integer;
begin
for I := 1 to N - 1 do
begin
K := I;
Y := X[I];
for J := (I + 1) to N do
if (X[J] < Y) then
begin
K := J;
Y := X[J]
end;
X[K] := X[J];
X[I] := Y;
ShowOutput;
readln
end
end;
(*--------------------------------------------------------------------*)
procedure Sort;
begin
case D of
1 : StrSelectSort(Data, N);
2 : StrInsert(Data, N);
3 : BubbleSort(Data, N);
4 : ShakeSort(Data, N);
5 : HeapSort(Data, N);
6 : QuickSort(Data, N);
7 : ShellSort(Data, N);
8 : RadixSort(Data, N);
else
writeln('BAD INPUT')
end
end;
(*-------------------------------------------------------------------*)
BEGIN
GetSortMethod;
while (D <> 9) do
begin
LoadList;
ShowInput;
Sort;
writeln('PRESS ENTER TO RETURN');
readln;
GetSortMethod
end
END.
|
namespace org.me.openglapplication;
//The animated cube code was based on, and enhanced from, an example from
//"Hello, Android" by Ed Burnette, published by Pragmatic Bookshelf, 2010
{$define LOG_FPS}
{$define SEETHRU}
{$define TEXTURES} //also in GLCube
{$define ACTION}
{$define LIGHTING}
{$define MATERIALS}
interface
uses
android.content,
android.opengl,
android.util,
javax.microedition.khronos.opengles,
javax.microedition.khronos.egl;
type
GLCubeRenderer = public class(GLSurfaceView.Renderer)
private
const Tag = 'GLCubeRenderer';
var ctx: Context;
var cube: GLCube := new GLCube;
var startTime, fpsStartTime, numFrames: Int64;
public
constructor (aContext: Context);
method OnSurfaceCreated(gl: GL10; config: EGLConfig);
method OnSurfaceChanged(gl: GL10; width, height: Integer);
method OnDrawFrame(gl: GL10);
end;
implementation
constructor GLCubeRenderer(aContext: Context);
begin
ctx := aContext;
end;
method GLCubeRenderer.OnSurfaceCreated(gl: GL10; config: EGLConfig);
begin
//Set up any OpenGL options we need
{$ifdef SEETHRU}
var SEE_THRU := true;
{$endif}
startTime := System.currentTimeMillis();
fpsStartTime := startTime;
numFrames := 0;
// Set up any OpenGL options we need
//Enable depth-testing
gl.glEnable(GL10.GL_DEPTH_TEST);
//Specifically only show items at less or same depth than others
gl.glDepthFunc(GL10.GL_LEQUAL);
//Set background colour to black
gl.glClearColor(0, 0, 0, 0.5);
// Optional: disable dither to boost performance
// gl.glDisable(GL10.GL_DITHER);
{$ifdef LIGHTING}
//Enable lighting in general and light 0 specifically
gl.glEnable(GL10.GL_LIGHTING);
gl.glEnable(GL10.GL_LIGHT0);
//Specify ambient RGBA light intensity. Default is (0,0,0,1)
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, [0.2, 0.2, 0.2, 1], 0);
//Specify diffuse RGBA light intensity to be (1,1,1,1), which is the default
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, [1, 1, 1, 1], 0);
//Specify where light is. Default is (0,0,1,0)
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, [1, 1, 1, 1], 0);
{$endif}
{$ifdef MATERIALS}
// What is the cube made of?
//Specify ambient RGBA reflectance. Default is (0.2,0.2,0.2,1)
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, [1, 1, 1, 1], 0);
//Specify diffuse RGBA reflectance. Default is (0.8,0.8,0.8,1)
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, [1, 1, 1, 1], 0);
{$endif}
{$ifdef SEETHRU}
if SEE_THRU then
begin
//Disable depth testing
gl.glDisable(GL10.GL_DEPTH_TEST);
//Enable colour blending
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE)
end;
{$endif}
{$ifdef TEXTURES}
// Enable textures
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL10.GL_TEXTURE_2D);
// Load the cube's texture from a bitmap
GLCube.loadTexture(gl, ctx, R.drawable.eye)
{$endif}
end;
//Called e.g. if device rotated
method GLCubeRenderer.OnSurfaceChanged(gl: GL10; width, height: Integer);
begin
//Set current view port to new size
gl.glViewport(0, 0, width, height);
//Select projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
//Reset projection matrix
gl.glLoadIdentity();
var ratio := Single(width) / height;
//Calculate window aspect ratio
//gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); //OpenGL version
GLU.gluPerspective(gl, 45, ratio, 1, 100); //GLU version
end;
method GLCubeRenderer.OnDrawFrame(gl: GL10);
begin
// Clear the screen and depth buffer
gl.glClear(GL10.GL_COLOR_BUFFER_BIT or GL10.GL_DEPTH_BUFFER_BIT);
// Position model so we can see it
//Select model view matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
//Reset model view matrix
gl.glLoadIdentity();
//Move viewpoint 4 units out of the screen
gl.glTranslatef(0, 0, -4);
// Other drawing commands go here...
// Set rotation angle based on the time
var elapsed := System.currentTimeMillis() - startTime;
{$ifdef ACTION}
//Rotate around X & Y axes 30 degrees/sec and 15 degrees/sec respectively
gl.glRotatef(elapsed * (30.0 / 1000), 0, 1, 0);
gl.glRotatef(elapsed * (15.0 / 1000), 1, 0, 0);
{$endif}
// Draw the model
cube.Draw(gl);
{$ifdef LOG_FPS}
// Keep track of number of frames drawn
inc(numFrames);
var fpsElapsed := System.currentTimeMillis() - fpsStartTime;
if fpsElapsed > 5 * 1000 then
begin
// every 5 seconds
var fps := (numFrames * 1000) / fpsElapsed;
Log.i(Tag, 'Frames per second: ' + fps + ' (' + numFrames + ' frames in ' + fpsElapsed + ' ms)');
fpsStartTime := System.currentTimeMillis();
numFrames := 0
end
{$endif}
end;
end. |
unit FreeOTFEExplorerfrmPropertiesDlg_Directory;
interface
uses
Classes, ComCtrls, Controls, Dialogs, ExtCtrls, Forms,
FreeOTFEExplorerfrmPropertiesDlg_Base, Graphics, Messages, StdCtrls, SysUtils, Variants, Windows;
type
TfrmPropertiesDialog_Directory = class (TfrmPropertiesDialog)
edContains: TLabel;
Label1: TLabel;
edTimestampCreated: TLabel;
Label4: TLabel;
Panel1: TPanel;
procedure FormShow(Sender: TObject);
PRIVATE
{ Private declarations }
PUBLIC
PathAndFilename: WideString;
end;
implementation
{$R *.dfm}
uses
SDFilesystem_FAT, SDUGeneral,
SDUGraphics,
SDUi18n;
procedure TfrmPropertiesDialog_Directory.FormShow(Sender: TObject);
var
totalSize: ULONGLONG;
dirCnt: Integer;
fileCnt: Integer;
item: TSDDirItem_FAT;
DLLFilename: String;
DLLIconIdx: Integer;
tmpIcon: TIcon;
begin
inherited;
self.Caption := SDUParamSubstitute(_('%1 Properties'), [ExtractFilename(PathAndFilename)]);
SetupCtlSeparatorPanel(Panel1);
if Filesystem.ItemSize(PathAndFilename, totalSize, dirCnt, fileCnt) then begin
edFilename.Text := ExtractFilename(PathAndFilename);
edFileType.Caption := SDUGetFileType_Description(FILE_TYPE_DIRECTORY);
edLocation.Caption := ExcludeTrailingPathDelimiter(ExtractFilePath(PathAndFilename));
if (edLocation.Caption = '') then begin
// Don't strip off trailing "\" if it's just "\"
edLocation.Caption := ExtractFilePath(PathAndFilename);
end;
edSize.Caption := SDUParamSubstitute(_('%1 (%2 bytes)'),
[SDUFormatAsBytesUnits(totalSize, 2), SDUIntToStrThousands(totalSize)]);
edContains.Caption := SDUParamSubstitute(_('%1 Files, %2 Folders'), [fileCnt, dirCnt]);
end;
item := TSDDirItem_FAT.Create();
try
if Filesystem.GetItem_FAT(PathAndFilename, item) then begin
edTimestampCreated.Caption := '';
try
edTimestampCreated.Caption := DateTimeToStr(TimeStampToDateTime(item.TimestampCreation));
except
// Swallow exception - if processing for the root dir, this will be set
// to zero, raising an exception
end;
ckReadOnly.Checked := item.IsReadonly;
ckHidden.Checked := item.IsHidden;
ckArchive.Checked := item.IsArchive;
end;
finally
item.Free();
end;
tmpIcon := TIcon.Create();
try
SDUGetFileType_Icon(FILE_TYPE_DIRECTORY, DLLFilename, DLLIconIdx);
if (DLLFilename = '') then begin
DLLFilename := DLL_SHELL32;
DLLIconIdx := DLL_SHELL32_FOLDER_CLOSED;
end;
if SDULoadDLLIcon(DLLFilename, False, DLLIconIdx, tmpIcon) then begin
imgFileType.Picture.Assign(tmpIcon);
end;
finally
tmpIcon.Free();
end;
end;
end.
|
unit UnitGroupsTools;
interface
uses
Windows,
SysUtils,
Classes,
DB,
Forms,
ProgressActionUnit,
uConstants,
uMemory,
uMemoryEx,
uTranslate,
uShellIntegration,
uRuntime,
uDBConnection,
uDBContext,
uDBEntities;
procedure MoveGroup(Context: IDBContext; GroupToMove, IntoGroup: TGroup); overload;
procedure MoveGroup(Context: IDBContext; GroupToMove, IntoGroup: string); overload;
procedure RenameGroup(Context: IDBContext; GroupToRename, NewName: string); overload;
procedure RenameGroup(Context: IDBContext; GroupToRename: TGroup; NewName: string); overload;
procedure DeleteGroup(Context: IDBContext; GroupToDelete: TGroup); overload;
procedure DeleteGroup(Context: IDBContext; GroupToDelete: string); overload;
implementation
procedure DeleteGroup(Context: IDBContext; GroupToDelete: string);
var
Groups: TGroups;
begin
Groups := TGroups.CreateFromString(GroupToDelete);
try
if Groups.Count > 0 then
DeleteGroup(Context, Groups[0]);
finally
F(Groups);
end;
end;
procedure DeleteGroup(Context: IDBContext; GroupToDelete: TGroup);
var
I: Integer;
Table: TDataSet;
Error: string;
Groups: string;
SGroupToDelete: string;
ProgressWindow: TProgressActionForm;
begin
SGroupToDelete := GroupToDelete.ToString;
Table := GetTable(Context.CollectionFileName, DB_TABLE_IMAGES);
try
ProgressWindow := GetProgressWindow;
try
ProgressWindow.OneOperation := True;
ProgressWindow.Show;
try
Table.Open;
Table.First;
ProgressWindow.MaxPosCurrentOperation := Table.RecordCount;
for I := 1 to Table.RecordCount do
begin
ProgressWindow.XPosition := I;
Application.ProcessMessages;
Groups := Table.FieldByName('Groups').AsString;
if TGroups.GroupWithCodeExistsInString(GroupToDelete.GroupCode, Groups) then
begin
TGroups.ReplaceGroups(SGroupToDelete, '', Groups);
Table.Edit;
Table.FieldByName('Groups').AsString := Groups;
Table.Post;
end;
Table.Next;
end;
Table.Close;
except
on E: Exception do
begin
Error := E.message;
MessageBoxDB(0, Format(TA('An error occurred during the delete group %s', 'Groups'), [Error]), TA('Error'),
TD_BUTTON_OK, TD_ICON_ERROR)
end;
end;
ProgressWindow.Close;
finally
R(ProgressWindow);
end;
finally
FreeDS(Table);
end;
end;
procedure RenameGroup(Context: IDBContext; GroupToRename, NewName: string);
var
Groups: TGroups;
begin
Groups := TGroups.CreateFromString(GroupToRename);
try
if Groups.Count > 0 then
RenameGroup(Context, Groups[0], NewName);
finally
F(Groups);
end;
end;
procedure RenameGroup(Context: IDBContext; GroupToRename: TGroup; NewName: string);
var
I: Integer;
Table: TDataSet;
FQuery: TDataSet;
Error: string;
Groups: string;
SGroupToDelete, SGroupToAdd: string;
ProgressWindow: TProgressActionForm;
begin
SGroupToDelete := GroupToRename.ToString;
GroupToRename.GroupName := NewName;
SGroupToAdd := GroupToRename.ToString;
Table := Context.CreateQuery;
try
SetSQL(Table, 'Select ID, Groups from $DB$');
ProgressWindow := GetProgressWindow;
try
ProgressWindow.OneOperation := True;
ProgressWindow.Show;
ProgressWindow.CanClosedByUser := False;
try
Table.Open;
Table.First;
ProgressWindow.MaxPosCurrentOperation := Table.RecordCount;
for I := 1 to Table.RecordCount do
begin
ProgressWindow.XPosition := I;
Application.ProcessMessages;
Groups := Table.FieldByName('Groups').AsString;
if TGroups.GroupWithCodeExistsInString(GroupToRename.GroupCode, Groups) then
begin
TGroups.ReplaceGroups(SGroupToDelete, SGroupToAdd, Groups);
FQuery := Context.CreateQuery;
try
SetSQL(FQuery, 'UPDATE $DB$ SET Groups=:Groups where ID=' + IntToStr(Table.FieldByName('ID').AsInteger));
SetStrParam(FQuery, 0, Groups);
ExecSQL(FQuery);
finally
FreeDS(FQuery);
end;
end;
Table.Next;
end;
except
on E: Exception do
begin
Error := E.message;
MessageBoxDB(0, Format(TA('An error occurred during the rename group %s', 'Groups'), [Error]), TA('Error'),
TD_BUTTON_OK, TD_ICON_ERROR);
end;
end;
ProgressWindow.Close;
finally
R(ProgressWindow);
end;
finally
FreeDS(Table);
end;
end;
procedure MoveGroup(Context: IDBContext; GroupToMove, IntoGroup: string);
var
GroupSource, GroupDestination: TGroups;
begin
GroupSource := TGroups.CreateFromString(GroupToMove);
GroupDestination := TGroups.CreateFromString(IntoGroup);
try
if (GroupSource.Count > 0) and (GroupDestination.Count > 0) then
MoveGroup(Context, GroupSource[0], GroupDestination[0]);
finally
F(GroupSource);
F(GroupDestination);
end;
end;
procedure MoveGroup(Context: IDBContext; GroupToMove, IntoGroup: TGroup);
var
I: Integer;
Table: TDataSet;
FQuery: TDataSet;
Error: string;
Groups: string;
SGroupToMove, SIntoGroup: string;
ProgressWindow: TProgressActionForm;
begin
SGroupToMove := GroupToMove.ToString;
SIntoGroup := IntoGroup.ToString;
Table := Context.CreateQuery;
SetSQL(Table, 'Select ID, Groups from $DB$');
ProgressWindow := GetProgressWindow;
ProgressWindow.OneOperation := True;
ProgressWindow.Show;
try
Table.Open;
Table.First;
ProgressWindow.MaxPosCurrentOperation := Table.RecordCount;
for I := 1 to Table.RecordCount do
begin
ProgressWindow.XPosition := I;
Application.ProcessMessages;
Groups := Table.FieldByName('Groups').AsString;
if TGroups.GroupWithCodeExistsInString(GroupToMove.GroupCode, Groups) then
begin
TGroups.ReplaceGroups(SGroupToMove, SIntoGroup, Groups);
FQuery := Context.CreateQuery;
try
SetSQL(FQuery, 'UPDATE $DB$ SET Groups=:Groups where ID=' + IntToStr(Table.FieldByName('ID').AsInteger));
SetStrParam(FQuery, 0, Groups);
ExecSQL(FQuery);
// checking
SetSQL(FQuery, 'Select Groups from $DB$ where ID=' + IntToStr(Table.FieldByName('ID').AsInteger));
FQuery.Open;
if Groups <> FQuery.FieldByName('Groups').AsString then
MessageBoxDB(0, Format(TA('An error occurred during the move group %s to group %s (%s)', 'Groups'), [GroupToMove.GroupName,
GroupToMove.GroupCode, IntoGroup.GroupName, IntoGroup.GroupCode]), TA('Error'), TD_BUTTON_OK,
TD_ICON_ERROR);
finally
FreeDS(FQuery);
end;
end;
Table.Next;
end;
except
on E: Exception do
begin
if Error = '' then
Error := E.message;
MessageBoxDB(0, Format(TA('An error occurred during the move group %s', 'Groups'), [Error]), TA('Error'), TD_BUTTON_OK,
TD_ICON_ERROR);
end;
end;
ProgressWindow.Close;
ProgressWindow.Release;
ProgressWindow.Free;
FreeDS(Table);
end;
end.
|
unit SDFilesystem;
interface
uses
Classes, Contnrs, SDPartitionImage,
SDUGeneral, SyncObjs,
SysUtils, Windows;
const
PATH_SEPARATOR: Widechar = '\';
DIR_CURRENT_DIR: WideString = '.';
DIR_PARENT_DIR: WideString = '..';
type
EFileSystemError = class (Exception);
EFileSystemNotMounted = class (EFileSystemError);
EFileSystemNoPartition = class (EFileSystemError);
EFileSystemNotRecognised = class (EFileSystemError);
{$M+}// Required to get rid of compiler warning "W1055 PUBLISHED caused RTTI ($M+) to be added to type '%s'"
TSDDirItem = class
private
FIsFile: Boolean;
FIsDirectory: Boolean;
FIsReadonly: Boolean;
FIsHidden: Boolean;
protected
function GetIsFile(): Boolean; virtual;
procedure SetIsFile(Value: Boolean); virtual;
function GetIsDirectory(): Boolean; virtual;
procedure SetIsDirectory(Value: Boolean); virtual;
function GetIsReadonly(): Boolean; virtual;
procedure SetIsReadonly(Value: Boolean); virtual;
function GetIsHidden(): Boolean; virtual;
procedure SetIsHidden(Value: Boolean); virtual;
public
// IMPORTANT: IF THESE ARE ADDED TO; ADD THEM TO Assign(...)
// implementation as well!
FFilename: String;
FSize: ULONGLONG;
FTimestampLastModified: TTimeStamp;
procedure Assign(srcItem: TSDDirItem); overload; virtual;
published
// IMPORTANT: IF THESE ARE ADDED TO; ADD THEM TO Assign(...)
// implementation as well!
property Filename: String Read FFilename Write FFilename;
property Size: ULONGLONG Read FSize Write FSize;
property TimestampLastModified: TTimeStamp Read FTimestampLastModified
Write FTimestampLastModified;
// Flags
property IsFile: Boolean Read GetIsFile Write SetIsFile;
property IsDirectory: Boolean Read GetIsDirectory Write SetIsDirectory;
property IsReadonly: Boolean Read GetIsReadonly Write SetIsReadonly;
property IsHidden: Boolean Read GetIsHidden Write SetIsHidden;
end;
TSDDirItemList = class (TObjectList)
protected
function GetItem(Index: Integer): TSDDirItem;
procedure SetItem(Index: Integer; AObject: TSDDirItem);
public
property Items[Index: Integer]: TSDDirItem Read GetItem Write SetItem; default;
procedure AddAsCopy(src: TSDDirItem);
procedure Assign(list: TSDDirItemList); overload;
end;
TSDCustomFilesystem = class
protected
FMounted: Boolean;
FReadOnly: Boolean;
FSerializeCS: TCriticalSection; // Protect by serializing read/write
// operations in multithreaded operations
procedure AssertMounted();
procedure SetMounted(newMounted: Boolean);
function DoMount(): Boolean; virtual; abstract;
procedure DoDismount(); virtual; abstract;
// Returns TRUE/FALSE, depending on whether we treat filenames as case
// sensitive or not
// This is filesytem dependant
function GetCaseSensitive(): Boolean; virtual; abstract;
function GetFreeSpace(): ULONGLONG; virtual; abstract;
function GetSize(): ULONGLONG; virtual; abstract;
procedure LastErrorClear(); virtual;
procedure LastErrorSet(errMsg: String); virtual;
function CheckWritable(): Boolean;
public
LastError: String;
constructor Create(); virtual;
destructor Destroy(); override;
function FilesystemTitle(): String; virtual; abstract;
function Format(): Boolean; virtual; abstract;
function CheckFilesystem(): Boolean; virtual;
function LoadContentsFromDisk(path: String; items: TSDDirItemList): Boolean;
virtual; abstract;
function ExtractFile(srcPath: WideString; extractToFilename: String): Boolean;
virtual; abstract;
function GetItem(path: WideString; item: TSDDirItem): Boolean; virtual; abstract;
function ItemSize(Path: WideString; out TotalSize: ULONGLONG;
out DirectoryCount: Integer; out FilesCount: Integer): Boolean;
function FileExists(fullPathToItem: WideString): Boolean;
function DirectoryExists(fullPathToItem: WideString): Boolean;
function DirectoryOrFileExists(fullPathToItem: WideString): Boolean;
published
property Mounted: Boolean Read FMounted Write SetMounted default False;
property CaseSensitive: Boolean Read GetCaseSensitive;
property ReadOnly: Boolean Read FReadOnly Write FReadOnly;
property FreeSpace: ULONGLONG Read GetFreeSpace;
property Size: ULONGLONG Read GetSize;
end;
TSDCustomFilesystemPartitionBased = class (TSDCustomFilesystem)
protected
FPartitionImage: TSDPartitionImage;
function DoMount(): Boolean; override;
procedure DoDismount(); override;
public
constructor Create(); override;
destructor Destroy(); override;
published
property PartitionImage: TSDPartitionImage
Read FPartitionImage Write FPartitionImage default nil;
end;
implementation
uses
SDUClasses,
SDUi18n;
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
function TSDDirItem.GetIsFile(): Boolean;
begin
Result := FIsFile;
end;
procedure TSDDirItem.SetIsFile(Value: Boolean);
begin
FIsFile := Value;
end;
function TSDDirItem.GetIsDirectory(): Boolean;
begin
Result := FIsDirectory;
end;
procedure TSDDirItem.SetIsDirectory(Value: Boolean);
begin
FIsDirectory := Value;
end;
function TSDDirItem.GetIsReadonly(): Boolean;
begin
Result := FIsReadonly;
end;
procedure TSDDirItem.SetIsReadonly(Value: Boolean);
begin
FIsReadonly := Value;
end;
function TSDDirItem.GetIsHidden(): Boolean;
begin
Result := FIsHidden;
end;
procedure TSDDirItem.SetIsHidden(Value: Boolean);
begin
FIsHidden := Value;
end;
function TSDDirItemList.GetItem(Index: Integer): TSDDirItem;
begin
Result := TSDDirItem(inherited Items[Index]);
end;
procedure TSDDirItemList.SetItem(Index: Integer; AObject: TSDDirItem);
begin
inherited Items[Index] := AObject;
end;
procedure TSDDirItemList.AddAsCopy(src: TSDDirItem);
var
tmpItem: TSDDirItem;
begin
tmpItem := TSDDirItem.Create();
tmpItem.Assign(src);
self.Add(tmpItem);
end;
procedure TSDDirItemList.Assign(list: TSDDirItemList);
var
i: Integer;
begin
self.Clear();
for i := 0 to (list.Count - 1) do begin
AddAsCopy(list.Items[i]);
end;
end;
procedure TSDDirItem.Assign(srcItem: TSDDirItem);
begin
self.Filename := srcItem.Filename;
self.Size := srcItem.Size;
self.IsFile := srcItem.IsFile;
self.IsDirectory := srcItem.IsDirectory;
self.IsReadonly := srcItem.IsReadonly;
self.IsHidden := srcItem.IsHidden;
self.TimestampLastModified := srcItem.TimestampLastModified;
end;
// ----------------------------------------------------------------------------
constructor TSDCustomFilesystem.Create();
begin
inherited;
LastError := '';
FMounted := False;
FSerializeCS := TCriticalSection.Create();
end;
destructor TSDCustomFilesystem.Destroy();
begin
Mounted := False;
FSerializeCS.Free();
inherited;
end;
function TSDCustomFilesystem.CheckFilesystem(): Boolean;
begin
Result := True;
end;
function TSDCustomFilesystem.ItemSize(Path: WideString; out TotalSize: ULONGLONG;
out DirectoryCount: Integer; out FilesCount: Integer): Boolean;
var
dirItems: TSDDirItemList;
item: TSDDirItem;
subdirsSize: ULONGLONG;
subdirsDirsCnt: Integer;
subditsFileCnt: Integer;
i: Integer;
begin
TotalSize := 0;
DirectoryCount := 0;
FilesCount := 0;
// Short circuit...
if ((ExtractFilename(Path) = DIR_CURRENT_DIR) or (ExtractFilename(Path) = DIR_PARENT_DIR))
then begin
Result := True;
exit;
end;
item := TSDDirItem.Create();
try
Result := GetItem(Path, item);
if Result then begin
if item.IsFile then begin
TotalSize := TotalSize + item.Size;
Inc(FilesCount);
end else
if item.IsDirectory then begin
Inc(DirectoryCount);
dirItems := TSDDirItemList.Create();
try
Result := LoadContentsFromDisk(Path, dirItems);
if Result then begin
for i := 0 to (dirItems.Count - 1) do begin
if (dirItems[i].IsDirectory or dirItems[i].IsFile) then begin
Result := ItemSize(IncludeTrailingPathDelimiter(Path) +
dirItems[i].Filename, subdirsSize, subdirsDirsCnt,
subditsFileCnt);
if Result then begin
TotalSize := TotalSize + subdirsSize;
DirectoryCount := DirectoryCount + subdirsDirsCnt;
FilesCount := FilesCount + subditsFileCnt;
end else begin
// Bail out...
break;
end;
end;
end;
end;
finally
dirItems.Free();
end;
end;
end;
finally
item.Free();
end;
end;
function TSDCustomFilesystem.FileExists(fullPathToItem: WideString): Boolean;
var
item: TSDDirItem;
begin
Result := False;
item := TSDDirItem.Create();
try
if GetItem(fullPathToItem, item) then begin
Result := item.IsFile;
end;
finally
item.Free();
end;
end;
function TSDCustomFilesystem.DirectoryExists(fullPathToItem: WideString): Boolean;
var
item: TSDDirItem;
begin
Result := False;
item := TSDDirItem.Create();
try
if GetItem(fullPathToItem, item) then begin
Result := item.IsDirectory;
end;
finally
item.Free();
end;
end;
function TSDCustomFilesystem.DirectoryOrFileExists(fullPathToItem: WideString): Boolean;
begin
Result := (FileExists(fullPathToItem) or DirectoryExists(fullPathToItem));
end;
procedure TSDCustomFilesystem.LastErrorClear();
begin
LastErrorSet('');
end;
procedure TSDCustomFilesystem.LastErrorSet(errMsg: String);
begin
LastError := errMsg;
end;
function TSDCustomFilesystem.CheckWritable(): Boolean;
begin
Result := True;
if self.ReadOnly then begin
LastErrorSet(_('Filesystem mounted readonly'));
Result := False;
end;
end;
procedure TSDCustomFilesystem.SetMounted(newMounted: Boolean);
var
oldMounted: Boolean;
begin
inherited;
if (newMounted <> Mounted) then begin
oldMounted := Mounted;
try
if newMounted then begin
FMounted := DoMount();
end else begin
DoDismount();
FMounted := False;
end;
except
on E: Exception do begin
FMounted := oldMounted;
raise;
end;
end;
end;
end;
procedure TSDCustomFilesystem.AssertMounted();
begin
inherited;
if not (Mounted) then begin
raise EFileSystemNotMounted.Create('Filesystem not mounted');
end;
end;
constructor TSDCustomFilesystemPartitionBased.Create();
begin
inherited;
FPartitionImage := nil;
end;
// ----------------------------------------------------------------------------
destructor TSDCustomFilesystemPartitionBased.Destroy();
begin
inherited;
end;
function TSDCustomFilesystemPartitionBased.DoMount(): Boolean;
begin
if (PartitionImage = nil) then begin
raise EFileSystemNoPartition.Create('Partition not specified');
end;
Result := inherited DoMount();
end;
procedure TSDCustomFilesystemPartitionBased.DoDismount();
begin
inherited;
end;
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
end.
|
unit version;
{
Get version of an application.
}
interface
uses Windows, SysUtils, Forms, jclPEImage;
function GetVersion(const FileName: string):string;
function GetLastBuildDate():string;
function GetLastBuildTime():string;
implementation
function GetVersion(const FileName: string): string;
var
size, len: longword;
handle: THandle;
buffer: pchar;
pinfo: ^VS_FIXEDFILEINFO;
Major, Minor: word;
begin
Result := 'Není dostupná';
size := GetFileVersionInfoSize(Pointer(FileName), handle);
if size > 0 then begin
GetMem(buffer, size);
if GetFileVersionInfo(Pointer(FileName), 0, size, buffer)
then
if VerQueryValue(buffer, '\', pointer(pinfo), len) then begin
Major := HiWord(pinfo.dwFileVersionMS);
Minor := LoWord(pinfo.dwFileVersionMS);
Result := Format('%d.%d',[Major, Minor]);
end;
FreeMem(buffer);
end;
end;
function GetLastBuildDate():string;
begin
DateTimeToString(Result, 'dd.mm.yyyy', jclPEImage.PeReadLinkerTimeStamp(Application.ExeName));
end;//function
function GetLastBuildTime():string;
begin
DateTimeToString(Result, 'hh:mm:ss', jclPEImage.PeReadLinkerTimeStamp(Application.ExeName));
end;//function
end.//unit
|
unit rtti_broker_uData;
interface
uses
rtti_broker_iBroker, TypInfo, SysUtils, Classes, StrUtils, fgl, contnrs;
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;
function FindCounter: IRBDataItem;
function GetCounter: IRBDataItem;
protected
property PropInfo: PPropInfo read GetPropInfo;
property PropName: string read GetPropName;
procedure CheckDataKind(AKind: integer);
protected
// IRBDataItem
function GetName: string;
function GetClassName: string;
function GetIsObject: Boolean;
function GetIsList: Boolean;
function GetIsListCounter: Boolean;
function GetIsReference: Boolean;
function GetIsNotStored: Boolean;
function GetIsMemo: Boolean;
function GetDataKind: integer;
function GetTypeKind: TTypeKind;
function GetListCount: integer;
procedure SetListCount(ACount: integer);
function GetAsPersist: string; virtual;
function GetAsPersistList(AIndex: integer): string; virtual;
procedure SetAsPersist(AValue: string); virtual;
procedure SetAsPersistList(AIndex: integer; AValue: string); virtual;
function GetAsString: string; virtual;
function GetAsStringList(AIndex: integer): string; virtual;
procedure SetAsString(AValue: string); virtual;
procedure SetAsStringList(AIndex: integer; AValue: string); virtual;
function GetAsInteger: integer; virtual;
function GetAsIntegerList(AIndex: integer): integer; virtual;
procedure SetAsInteger(AValue: integer); virtual;
procedure SetAsIntegerList(AIndex: integer; AValue: integer); virtual;
function GetAsBoolean: Boolean; virtual;
function GetAsBooleanList(AIndex: integer): Boolean; virtual;
procedure SetAsBoolean(AValue: Boolean); virtual;
procedure SetAsBooleanList(AIndex: integer; AValue: Boolean); virtual;
function GetAsObject: TObject; virtual;
function GetAsObjectList(AIndex: integer): TObject; virtual;
procedure SetAsObject(AValue: TObject); virtual;
procedure SetAsObjectList(AIndex: integer; AValue: TObject); virtual;
function GetAsVariant: Variant; virtual;
function GetAsVariantList(AIndex: integer): Variant; virtual;
procedure SetAsVariant(AValue: Variant); virtual;
procedure SetAsVariantList(AIndex: integer; 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 IsList: Boolean read GetIsList;
property IsListCounter: Boolean read GetIsListCounter;
property IsReference: Boolean read GetIsReference;
property IsNotStored: Boolean read GetIsNotStored;
property IsMemo: Boolean read GetIsMemo;
property DataKind: integer read GetDataKind;
property TypeKind: TTypeKind read GetTypeKind;
property ListCount: Integer read GetListCount write SetListCount;
property AsPersist: string read GetAsPersist write SetAsPersist;
property AsPersistList[AIndex: integer]: string read GetAsPersistList write SetAsPersistList;
property AsString: string read GetAsString write SetAsString;
property AsStringList[AIndex: integer]: string read GetAsStringList write SetAsStringList;
property AsInteger: integer read GetAsInteger write SetAsInteger;
property AsIntegerList[AIndex: integer]: integer read GetAsIntegerList write SetAsIntegerList;
property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean;
property AsBooleanList[AIndex: integer]: Boolean read GetAsBooleanList write SetAsBooleanList;
property AsObject: TObject read GetAsObject write SetAsObject;
property AsObjectList[AIndex: integer]: TObject read GetAsObjectList write SetAsObjectList;
property AsVariant: variant read GetAsVariant write SetAsVariant;
property AsVariantList[AIndex: integer]: variant read GetAsVariantList write SetAsVariantList;
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, IRBDataText)
protected
function GetAsPersist: string; override;
function GetAsPersistList(AIndex: integer): string; override;
procedure SetAsPersist(AValue: string); override;
procedure SetAsPersistList(AIndex: integer; AValue: string); override;
function GetAsString: string; override;
function GetAsStringList(AIndex: integer): string; override;
procedure SetAsString(AValue: string); override;
procedure SetAsStringList(AIndex: integer; AValue: string); override;
function GetAsInteger: integer; override;
function GetAsIntegerList(AIndex: integer): integer; override;
procedure SetAsInteger(AValue: integer); override;
procedure SetAsIntegerList(AIndex: integer; AValue: integer); override;
function GetAsVariant: Variant; override;
function GetAsVariantList(AIndex: integer): Variant; override;
procedure SetAsVariant(AValue: Variant); override;
procedure SetAsVariantList(AIndex: integer; AValue: Variant); override;
end;
{ TRBIntegerDataItem }
TRBIntegerDataItem = class(TRBDataItem)
protected
function GetAsPersist: string; override;
function GetAsPersistList(AIndex: integer): string; override;
procedure SetAsPersist(AValue: string); override;
procedure SetAsPersistList(AIndex: integer; AValue: string); override;
function GetAsString: string; override;
function GetAsStringList(AIndex: integer): string; override;
procedure SetAsString(AValue: string); override;
procedure SetAsStringList(AIndex: integer; AValue: string); override;
function GetAsInteger: integer; override;
function GetAsCounter: integer;
function GetAsIntegerList(AIndex: integer): integer; override;
procedure SetAsInteger(AValue: integer); override;
procedure SetAsCounter(AValue: integer);
procedure SetAsIntegerList(AIndex: integer; AValue: integer); override;
function GetAsBoolean: Boolean; override;
function GetAsBooleanList(AIndex: integer): Boolean; override;
procedure SetAsBoolean(AValue: Boolean); override;
procedure SetAsBooleanList(AIndex: integer; AValue: Boolean); override;
function GetAsVariant: Variant; override;
function GetAsVariantList(AIndex: integer): Variant; override;
procedure SetAsVariant(AValue: Variant); override;
procedure SetAsVariantList(AIndex: integer; AValue: Variant); override;
function GetAsPtrInt: PtrInt; override;
procedure SetAsPtrInt(AValue: PtrInt); override;
end;
{ TRBObjectDataItem }
TRBObjectDataItem = class(TRBDataItem)
protected
function GetAsObject: TObject; override;
function GetAsObjectList(AIndex: integer): TObject; override;
procedure SetAsObject(AValue: TObject); override;
procedure SetAsObjectList(AIndex: integer; AValue: TObject); override;
function GetAsVariant: Variant; override;
function GetAsVariantList(AIndex: integer): Variant; override;
procedure SetAsVariant(AValue: Variant); override;
procedure SetAsVariantList(AIndex: integer; AValue: Variant); override;
function GetAsClass: TClass; override;
end;
{ TRBEnumerationDataItem }
TRBEnumerationDataItem = class(TRBDataItem)
protected
function GetAsPersist: string; override;
function GetAsPersistList(AIndex: integer): string; override;
procedure SetAsPersist(AValue: string); override;
procedure SetAsPersistList(AIndex: integer; AValue: string); override;
function GetAsString: string; override;
function GetAsStringList(AIndex: integer): string; override;
procedure SetAsString(AValue: string); override;
procedure SetAsStringList(AIndex: integer; AValue: string); override;
function GetEnumName(AValue: integer): string; override;
function GetEnumNameCount: integer; override;
function GetAsVariant: Variant; override;
function GetAsVariantList(AIndex: integer): Variant; override;
procedure SetAsVariant(AValue: Variant); override;
procedure SetAsVariantList(AIndex: integer; AValue: Variant); override;
end;
{ TRBVariantDataItem }
TRBVariantDataItem = class(TRBDataItem, IRBDataText)
protected
function GetAsPersist: string; override;
function GetAsPersistList(AIndex: integer): string; override;
procedure SetAsPersist(AValue: string); override;
procedure SetAsPersistList(AIndex: integer; AValue: string); override;
function GetAsString: string; override;
function GetAsStringList(AIndex: integer): string; override;
procedure SetAsString(AValue: string); override;
procedure SetAsStringList(AIndex: integer; AValue: string); override;
function GetAsInteger: integer; override;
function GetAsIntegerList(AIndex: integer): integer; override;
procedure SetAsInteger(AValue: integer); override;
procedure SetAsIntegerList(AIndex: integer; AValue: integer); override;
function GetAsVariant: Variant; override;
function GetAsVariantList(AIndex: integer): Variant; override;
procedure SetAsVariant(AValue: Variant); override;
procedure SetAsVariantList(AIndex: integer; 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;
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;
property UnderObject: TObject read GetUnderObject;
end;
{ TRBDataList }
TRBDataList = class(TInterfacedObject, IRBDataList)
private type
TInternalList = specialize TFPGInterfacedObjectList<IRBData>;
private
fList: TInternalList;
function RetrieveData(const AObject: TObject): IRBData;
protected
function GetCount: integer;
function GetItems(AIndex: integer): TObject;
function GetAsData(AIndex: integer): IRBData;
procedure Add(AObject: TObject);
procedure Insert(ARow: integer; AObject: TObject);
procedure AddData(AData: IRBData);
procedure InsertData(ARow: integer; AData: IRBData);
procedure Delete(AIndex: integer);
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
property Items[AIndex: integer]: TObject read GetItems; default;
property AsData[AIndex: integer]: IRBData read GetAsData;
property Count: integer read GetCount;
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;
function TRBVariantDataItem.GetAsPersistList(AIndex: integer): string;
begin
Result := GetAsVariantList(AIndex);
end;
procedure TRBVariantDataItem.SetAsPersist(AValue: string);
begin
SetAsVariant(AValue);
end;
procedure TRBVariantDataItem.SetAsPersistList(AIndex: integer; AValue: string);
begin
SetAsVariantList(AIndex, AValue);
end;
function TRBVariantDataItem.GetAsString: string;
begin
Result := GetAsVariant;
end;
function TRBVariantDataItem.GetAsStringList(AIndex: integer): string;
begin
Result := GetAsVariantList(AIndex);
end;
procedure TRBVariantDataItem.SetAsString(AValue: string);
begin
SetAsVariant(AValue);
end;
procedure TRBVariantDataItem.SetAsStringList(AIndex: integer; AValue: string);
begin
SetAsVariantList(AIndex, AValue);
end;
function TRBVariantDataItem.GetAsInteger: integer;
begin
Result := GetAsVariant;
end;
function TRBVariantDataItem.GetAsIntegerList(AIndex: integer): integer;
begin
Result := GetAsVariantList(AIndex);
end;
procedure TRBVariantDataItem.SetAsInteger(AValue: integer);
begin
SetAsVariant(AValue);
end;
procedure TRBVariantDataItem.SetAsIntegerList(AIndex: integer; AValue: integer);
begin
SetAsVariantList(AIndex, AValue);
end;
function TRBVariantDataItem.GetAsVariant: Variant;
begin
Result := GetVariantProp(fParent.fObject, PropInfo);
end;
function TRBVariantDataItem.GetAsVariantList(AIndex: integer): Variant;
type
TGetProcIndex = function(AAccessIndex, APropIndex: integer): variant of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbList);
mMethod.Code := PropInfo^.GetProc;
mMethod.Data := fParent.fObject;
Result := TGetProcIndex(mMethod)(AIndex, PropInfo^.Index);
end;
procedure TRBVariantDataItem.SetAsVariant(AValue: Variant);
begin
SetVariantProp(fParent.fObject, PropInfo, AValue);
end;
procedure TRBVariantDataItem.SetAsVariantList(AIndex: integer; AValue: Variant);
type
TSetProcIndex = procedure(AAccessIndex, APropIndex: integer; const AValue: variant) of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbList);
mMethod.Code := PropInfo^.SetProc;
mMethod.Data := fParent.fObject;
TSetProcIndex(mMethod)(AIndex, PropInfo^.Index, AValue);
end;
{ TRBEnumerationDataItem }
function TRBEnumerationDataItem.GetAsPersist: string;
begin
Result := GetAsString;
end;
function TRBEnumerationDataItem.GetAsPersistList(AIndex: integer): string;
begin
Result := AsStringList[AIndex];
end;
procedure TRBEnumerationDataItem.SetAsPersist(AValue: string);
begin
AsString := AValue;
end;
procedure TRBEnumerationDataItem.SetAsPersistList(AIndex: integer;
AValue: string);
begin
AsStringList[AIndex] := AValue;
end;
function TRBEnumerationDataItem.GetAsString: string;
begin
CheckDataKind(crbNone);
Result := GetEnumProp(fParent.fObject, PropInfo);
end;
function TRBEnumerationDataItem.GetAsStringList(AIndex: integer): string;
type
TGetProcIndex = function(AAccessIndex, APropIndex: integer): byte of object;
var
mMethod : TMethod;
mEnumValue: byte;
begin
CheckDataKind(crbList);
mMethod.Code := PropInfo^.GetProc;
mMethod.Data := fParent.fObject;
mEnumValue := TGetProcIndex(mMethod)(AIndex, PropInfo^.Index);
Result := typinfo.GetEnumName(PropInfo^.PropType, mEnumValue);
end;
procedure TRBEnumerationDataItem.SetAsString(AValue: string);
begin
CheckDataKind(crbNone);
if AValue <> '' then
SetEnumProp(fParent.fObject, PropInfo, AValue);
end;
procedure TRBEnumerationDataItem.SetAsStringList(AIndex: integer; AValue: string
);
type
TSetProcIndex = procedure(AAccessIndex, APropIndex: integer; const AValue: byte) of object;
var
mMethod : TMethod;
mPropValue: integer;
begin
CheckDataKind(crbList);
if AValue = '' then
Exit;
mMethod.Code := PropInfo^.SetProc;
mMethod.Data := fParent.fObject;
//
mPropValue := GetEnumValue(PropInfo^.PropType, AValue);
if (mPropValue < 0) then
ERBException.EnumerationValueNotFound(ClassName, PropName, AValue);
TSetProcIndex(mMethod)(AIndex, PropInfo^.Index, mPropValue);
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;
function TRBEnumerationDataItem.GetAsVariantList(AIndex: integer): Variant;
begin
Result := GetAsStringList(AIndex);
end;
procedure TRBEnumerationDataItem.SetAsVariant(AValue: Variant);
begin
SetAsString(AValue);
end;
procedure TRBEnumerationDataItem.SetAsVariantList(AIndex: integer;
AValue: Variant);
begin
SetAsStringList(AIndex, 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
CheckDataKind(crbObject);
Result := GetObjectProp(fParent.fObject, PropInfo);
end;
function TRBObjectDataItem.GetAsObjectList(AIndex: integer): TObject;
type
TGetProcIndex = function(AAccessIndex, APropIndex: integer): TObject of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbList);
mMethod.Code := PropInfo^.GetProc;
mMethod.Data := fParent.fObject;
Result := TGetProcIndex(mMethod)(AIndex, PropInfo^.Index);
end;
procedure TRBObjectDataItem.SetAsObject(AValue: TObject);
begin
CheckDataKind(crbObject);
SetObjectProp(fParent.fObject, PropInfo, AValue);
end;
procedure TRBObjectDataItem.SetAsObjectList(AIndex: integer; AValue: TObject);
type
TSetProcIndex = procedure(AAccessIndex, APropIndex: integer; AValue: TObject) of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbList);
mMethod.Code := PropInfo^.SetProc;
mMethod.Data := fParent.fObject;
TSetProcIndex(mMethod)(AIndex, PropInfo^.Index, AValue);
end;
function TRBObjectDataItem.GetAsVariant: Variant;
var
mP: Pointer;
begin
mP := GetAsObject;
Result := mP;
end;
function TRBObjectDataItem.GetAsVariantList(AIndex: integer): Variant;
begin
Result := Pointer(GetAsObjectList(AIndex));
end;
procedure TRBObjectDataItem.SetAsVariant(AValue: Variant);
var
mP: Pointer;
begin
//mP := AValue;
//SetAsObject(mP);
end;
procedure TRBObjectDataItem.SetAsVariantList(AIndex: integer; AValue: Variant);
begin
//SetAsObjectList(AIndex, AValue);
end;
function TRBObjectDataItem.GetAsClass: TClass;
begin
CheckDataKind(crbObject);
Result := GetObjectPropClass(fParent.fClass, PropInfo^.Name);
end;
{ TIRBStringData }
function TRBStringDataItem.GetAsPersist: string;
begin
Result := AsString;
end;
function TRBStringDataItem.GetAsPersistList(AIndex: integer): string;
begin
Result := AsStringList[AIndex];
end;
procedure TRBStringDataItem.SetAsPersist(AValue: string);
begin
AsString := AValue;
end;
procedure TRBStringDataItem.SetAsPersistList(AIndex: integer; AValue: string);
begin
AsStringList[AIndex] := AValue;
end;
function TRBStringDataItem.GetAsString: string;
begin
//CheckDataKind(crbNone);
Result := GetStrProp(fParent.fObject, PropInfo);
end;
function TRBStringDataItem.GetAsStringList(AIndex: integer): string;
type
TGetProcIndex = function(AAccessIndex, APropIndex: integer): string of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbList);
mMethod.Code := PropInfo^.GetProc;
mMethod.Data := fParent.fObject;
Result := TGetProcIndex(mMethod)(AIndex, PropInfo^.Index);
end;
procedure TRBStringDataItem.SetAsString(AValue: string);
begin
//CheckDataKind(crbNone);
SetStrProp(fParent.fObject, PropInfo, AValue);
end;
procedure TRBStringDataItem.SetAsStringList(AIndex: integer; AValue: string);
type
TSetProcIndex = procedure(AAccessIndex, APropIndex: integer; const AValue: string) of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbList);
mMethod.Code := PropInfo^.SetProc;
mMethod.Data := fParent.fObject;
TSetProcIndex(mMethod)(AIndex, PropInfo^.Index, AValue);
end;
function TRBStringDataItem.GetAsInteger: integer;
begin
Result := StrToInt(AsString);
end;
function TRBStringDataItem.GetAsIntegerList(AIndex: integer): integer;
begin
Result := StrToInt(AsString[AIndex]);
end;
procedure TRBStringDataItem.SetAsInteger(AValue: integer);
begin
AsString := IntToStr(AValue);
end;
procedure TRBStringDataItem.SetAsIntegerList(AIndex: integer; AValue: integer);
begin
AsStringList[AIndex] := IntToStr(AValue);
end;
function TRBStringDataItem.GetAsVariant: Variant;
begin
Result := AsString;
end;
function TRBStringDataItem.GetAsVariantList(AIndex: integer): Variant;
begin
Result := AsStringList[AIndex];
end;
procedure TRBStringDataItem.SetAsVariant(AValue: Variant);
begin
SetAsString(AValue);
end;
procedure TRBStringDataItem.SetAsVariantList(AIndex: integer; AValue: Variant);
begin
SetAsStringList(AIndex, AValue);
end;
{ TIRBIntegerData }
function TRBIntegerDataItem.GetAsPersist: string;
begin
Result := IfThen(AsInteger = 0, '', AsString);
end;
function TRBIntegerDataItem.GetAsPersistList(AIndex: integer): string;
begin
Result := IfThen(AsIntegerList[AIndex] = 0, '', AsStringList[AIndex]);
end;
procedure TRBIntegerDataItem.SetAsPersist(AValue: string);
begin
if AValue = '' then
AsInteger := 0
else
AsString := AValue;
end;
procedure TRBIntegerDataItem.SetAsPersistList(AIndex: integer; AValue: string);
begin
if AValue = '' then
AsIntegerList[AIndex] := 0
else
AsStringList[AIndex] := AValue;
end;
function TRBIntegerDataItem.GetAsString: string;
begin
Result := IntToStr(AsInteger);
end;
function TRBIntegerDataItem.GetAsStringList(AIndex: integer): string;
begin
Result := IntToStr(AsIntegerList[AIndex]);
end;
procedure TRBIntegerDataItem.SetAsString(AValue: string);
begin
AsInteger := StrToInt(AValue);
end;
procedure TRBIntegerDataItem.SetAsStringList(AIndex: integer; AValue: string);
begin
AsIntegerList[AIndex] := StrToInt(AValue);
end;
function TRBIntegerDataItem.GetAsInteger: integer;
begin
if IsListCounter then
Result := GetAsCounter
else
begin
CheckDataKind(crbNone);
Result := GetOrdProp(fParent.fObject, PropInfo);
end;
end;
function TRBIntegerDataItem.GetAsCounter: integer;
type
TGetProcIndex = function(APropIndex: integer): integer of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbListCounter);
mMethod.Code := PropInfo^.GetProc;
mMethod.Data := fParent.fObject;
Result := TGetProcIndex(mMethod)(PropInfo^.Index);
end;
function TRBIntegerDataItem.GetAsIntegerList(AIndex: integer): integer;
type
TGetProcIndex = function(AAccessIndex, APropIndex: integer): integer of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbList);
mMethod.Code := PropInfo^.GetProc;
mMethod.Data := fParent.fObject;
Result := TGetProcIndex(mMethod)(AIndex, PropInfo^.Index);
end;
procedure TRBIntegerDataItem.SetAsInteger(AValue: integer);
begin
if IsListCounter then
SetAsCounter(AValue)
else
begin
CheckDataKind(crbNone);
SetOrdProp(fParent.fObject, PropInfo, AValue);
end;
end;
procedure TRBIntegerDataItem.SetAsCounter(AValue: integer);
type
TSetProcIndex = procedure(APropIndex: integer; AValue: integer) of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbListCounter);
mMethod.Code := PropInfo^.SetProc;
mMethod.Data := fParent.fObject;
TSetProcIndex(mMethod)(PropInfo^.Index, AValue);
end;
procedure TRBIntegerDataItem.SetAsIntegerList(AIndex: integer; AValue: integer);
type
TSetProcIndex = procedure(AAccessIndex, APropIndex: integer; AValue: integer) of object;
var
mMethod : TMethod;
begin
CheckDataKind(crbList);
mMethod.Code := PropInfo^.SetProc;
mMethod.Data := fParent.fObject;
TSetProcIndex(mMethod)(AIndex, PropInfo^.Index, AValue);
end;
function TRBIntegerDataItem.GetAsBoolean: Boolean;
begin
Result := AsInteger <> 0;
end;
function TRBIntegerDataItem.GetAsBooleanList(AIndex: integer): Boolean;
begin
Result := AsIntegerList[AIndex] <> 0;
end;
procedure TRBIntegerDataItem.SetAsBoolean(AValue: Boolean);
begin
if AValue then
AsInteger := 1
else
AsInteger := 0;
end;
procedure TRBIntegerDataItem.SetAsBooleanList(AIndex: integer; AValue: Boolean);
begin
if AValue then
AsIntegerList[AIndex] := 1
else
AsIntegerList[AIndex] := 0;
end;
function TRBIntegerDataItem.GetAsVariant: Variant;
begin
Result := GetAsBoolean;
end;
function TRBIntegerDataItem.GetAsVariantList(AIndex: integer): Variant;
begin
Result := GetAsBooleanList(AIndex);
end;
procedure TRBIntegerDataItem.SetAsVariant(AValue: Variant);
begin
SetAsBoolean(AValue);
end;
procedure TRBIntegerDataItem.SetAsVariantList(AIndex: integer; AValue: Variant);
begin
SetAsBooleanList(AIndex, 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;
function TRBDataItem.FindCounter: IRBDataItem;
var
mCountPropName: string;
begin
CheckDataKind(crbList);
mCountPropName := Name + 'Count';
Result := fParent.FindItem(mCountPropName);
end;
function TRBDataItem.GetCounter: IRBDataItem;
begin
Result := FindCounter;
if Result = nil then
ERBException.Collection_NoCountPropertySpecified(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.GetDataKind: integer;
begin
Result := crbNone;
if ((PropInfo^.PropProcs shr 6) and 1) <> 0 then
begin
Result := PropInfo^.Index;
end;
end;
function TRBDataItem.GetTypeKind: TTypeKind;
begin
Result := fPropInfo^.PropType^.Kind;
end;
function TRBDataItem.GetListCount: integer;
begin
Result := GetCounter.AsInteger;
end;
procedure TRBDataItem.SetListCount(ACount: integer);
begin
GetCounter.AsInteger := ACount;
end;
function TRBDataItem.GetAsPersist: string;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsPersistList(AIndex: integer): string;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsPersist(AValue: string);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsPersistList(AIndex: integer; AValue: string);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.CheckDataKind(AKind: integer);
begin
//if (AKind = 0) and (DataKind <> 0) then
// ERBException.UnexpectedDataKind(ClassName, PropName, AKind);
//if not ((DataKind and AKind) = AKind) then
// ERBException.UnexpectedDataKind(ClassName, PropName, AKind);
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 := (DataKind and crbObject) = crbObject;
Result := TypeKind in [tkClass, tkObject];
end;
function TRBDataItem.GetIsList: Boolean;
begin
Result := (DataKind and crbList) = crbList;
end;
function TRBDataItem.GetIsListCounter: Boolean;
begin
Result := (DataKind and crbListCounter) = crbListCounter;
end;
function TRBDataItem.GetIsReference: Boolean;
begin
Result := (DataKind and crbRef) = crbRef;
end;
function TRBDataItem.GetIsNotStored: Boolean;
begin
Result := (DataKind and crbNotStored) = crbNotStored;
end;
function TRBDataItem.GetIsMemo: Boolean;
begin
Result := (DataKind and crbMemo) = crbMemo;
end;
function TRBDataItem.GetAsString: string;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsStringList(AIndex: integer): string;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsString(AValue: string);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsStringList(AIndex: integer; AValue: string);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsInteger: integer;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsIntegerList(AIndex: integer): integer;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsInteger(AValue: integer);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsIntegerList(AIndex: integer; AValue: integer);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsBoolean: Boolean;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsBooleanList(AIndex: integer): Boolean;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsBoolean(AValue: Boolean);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsBooleanList(AIndex: integer; AValue: Boolean);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsObject: TObject;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsObjectList(AIndex: integer): TObject;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsObject(AValue: TObject);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsObjectList(AIndex: integer; AValue: TObject);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsVariant: Variant;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
function TRBDataItem.GetAsVariantList(AIndex: integer): Variant;
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsVariant(AValue: Variant);
begin
ERBException.UnsupportedDataAccess(PropName);
end;
procedure TRBDataItem.SetAsVariantList(AIndex: integer; 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.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;
begin
for i := 0 to Count - 1 do begin
if Items[i].IsList then
begin
Items[i].ListCount := AData[i].ListCount;
for j := 0 to Items[i].ListCount - 1 do
begin
if Items[i].IsObject then
begin
if Items[i].IsReference then
Items[i].AsObjectList[j] := AData[i].AsObjectList[j]
else
AssignObject(AData[i].AsObjectList[j], Items[i].AsObjectList[j]);
end
else
begin
Items[i].AsPersistList[j] := AData[i].AsPersistList[j];
end;
end;
end
else
if Items[i].IsObject then
begin
if Items[i].IsReference then
Items[i].AsObject := AData[i].AsObject
else
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;
{ TRBDataList }
function TRBDataList.RetrieveData(const AObject: TObject): IRBData;
var
m: LongInt;
begin
if Supports(AObject, IRBData) then
Result := AObject as IRBData
else begin
Result := TRBData.Create(AObject, True);
end;
end;
function TRBDataList.GetAsData(AIndex: integer): IRBData;
begin
Result := fList[AIndex];
end;
function TRBDataList.GetCount: integer;
begin
Result := fList.Count;
end;
function TRBDataList.GetItems(AIndex: integer): TObject;
begin
Result := fList[AIndex].UnderObject;
end;
procedure TRBDataList.Add(AObject: TObject);
begin
fList.Add(RetrieveData(AObject));
end;
procedure TRBDataList.Insert(ARow: integer; AObject: TObject);
begin
fList.Insert(ARow, RetrieveData(AObject));
end;
procedure TRBDataList.AddData(AData: IRBData);
begin
fList.Add(AData);
end;
procedure TRBDataList.InsertData(ARow: integer; AData: IRBData);
begin
fList.Insert(ARow, AData);
end;
procedure TRBDataList.Delete(AIndex: integer);
begin
fList.Delete(AIndex);
end;
procedure TRBDataList.AfterConstruction;
begin
inherited AfterConstruction;
fList := TInternalList.Create;
end;
procedure TRBDataList.BeforeDestruction;
begin
FreeAndNil(fList);
inherited BeforeDestruction;
end;
end.
|
//------------------------------------------------------------------------------
//MapTypes UNIT
//------------------------------------------------------------------------------
// What it does-
// Contains Map related Types
//
// Changes -
// January 22d, 2007 - RaX - Created.
//
//------------------------------------------------------------------------------
unit MapTypes;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
Types,
{Project}
PointList,
{Third Party}
List32
;
const
{[2007/03/24] CR - Max length that a .pms map name in file can be. }
MAX_PMS_HEADER_LENGTH = 13; //Length of 'PrometheusMap'
const
{[2007/04/29] CR - Borrowed from Prometheus' constants we used long ago.
And then... corrected - our logic was reversed, for naming the constants.
:P~~~~~~~
Expanded explanation:
Even numbered codes are unwalkable (but sometimes pathable for attacks)
Odd numbered codes are walkable.
Map GAT Bit values (can be combined - ANDs or ORs...) }
GAT_WALKABLE = $00; // unwalkable terrain (land, cliffs, obstacles)
GAT_UNWALKABLE = $01; // bit1 = walkable point (land)
GAT_PUDDLE = $02; // bit2 = Puddle (water)
GAT_W_PUDDLE = $03; // (walkable + water)
GAT_WARP = $04; // bit3 = Warp
GAT_W_WARP = $05; // (walkable + warp)
type
TMapMode = (UNLOADED,LOADING,LOADED);
TFlags = record
//Warping
Memo : Boolean;
NoReturnOnDC : Boolean;
Teleport : Boolean;
//Items/Skills
FlyWings : Boolean;
ButterflyWings: Boolean;
DeadBranches : Boolean;
Skill : Boolean;
Items : Boolean;
//PVP
PvP : Boolean;
GuildPvP : Boolean;
PvPNightmare : Boolean;
ExpLoss : Boolean;
ItemDrop : Boolean;
//Guilds + Parties
NoGuild : Boolean;
NoParty : Boolean;
//Turbo Track
TurboTrack : Boolean;
//Weather
Rain : Boolean;
Snow : Boolean;
Sakura : Boolean;
Fog : Boolean;
Leaves : Boolean;
Smog : Boolean;
//Objects tracking
AutoId : LongWord;
end;
//graph related types
TCell = record
//The place in a graph the cell is
Position : TPoint;
//what kind of tile is it
Attribute : Byte;
//Tsusai 11/09/06: Keep track of the number of things in the way, like icewall(s)
ObstructionCount: Byte;
//TBeings in this cell (NPC/Mob/Chara)
Beings : TIntList32;
//Items!!
Items : TIntList32;
end;
TGraph = array of array of TCell;
TFloodItem = class
public
Path : TPointList;
Position : TPoint;
Cost : LongWord;
Constructor Create;
Destructor Destroy; override;
function ManhattanCost(
const
GoalPt : TPoint
) : Word;
function DiagonalCost(
const
GoalPt : TPoint
) : Word;
end;
implementation
//------------------------------------------------------------------------------
//Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Creates this object with empty Path
//
// Changes -
// March 13th, 2007 - Aeomin - Created Header
//
//------------------------------------------------------------------------------
Constructor TFloodItem.Create;
begin
inherited;
Path := TPointList.Create;
Cost := 0;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy DESTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Destroy this object and its path
//
// Changes -
// March 13th, 2007 - RaX - Created Header
//
//------------------------------------------------------------------------------
Destructor TFloodItem.Destroy;
begin
Path.Free;
inherited;
end;
//------------------------------------------------------------------------------
(*- Function ------------------------------------------------------------------*
TFloodItem.ManhattanCost
--------------------------------------------------------------------------------
Overview:
--
Computes the Manhattan distance (like travelling in a grid of blocks in
downtown Manhattan) from the Position to the GoalPt. Simple, easy to compute,
but not preferred when Diagonal pathing is allowed.
--
Revisions:
--
[2007/04/30] CR - Added Routine
*-----------------------------------------------------------------------------*)
Function TFloodItem.ManhattanCost(
const
GoalPt : TPoint
) : Word;
Begin
Result := 5 * (
Abs(GoalPt.X - Position.X) + Abs(GoalPt.Y - Position.Y)
);
End;(* Func TFloodItem.ManhattanCost
*-----------------------------------------------------------------------------*)
(*- Function ------------------------------------------------------------------*
TFloodItem.DiagonalCost
--------------------------------------------------------------------------------
Overview:
--
Computes the diagonal cost from the Position point to the supplied GoalPt.
This heuristic distance is usually prefered to the Manhattan distance when
diagonal moves are allowed.
In our case, diagonal moves ARE allowed on RO maps.
The 5's and 7's are the integer equivalents of 1.0 and 2^(1/2) for the true
distance cost for straight line and diagonal moves.
--
Revisions:
--
[2007/04/30] CR - Added Routine
*-----------------------------------------------------------------------------*)
Function TFloodItem.DiagonalCost(
const
GoalPt : TPoint
) : Word;
Var
AbsX : Integer;
AbsY : Integer;
Begin
AbsX := Abs(GoalPt.X - Position.X);
AbsY := Abs(GoalPt.Y - Position.Y);
if (AbsX > AbsY) then
begin
if (AbsY > 0) then
begin
Dec(AbsX);
end;
Result := 7 * AbsY + 5 * AbsX;
end else begin
if (AbsX > 0) then
begin
Dec(AbsY);
end;
Result := 7 * AbsX + 5* AbsY;
end;
End;(* Func TFloodItem.DiagonalCost
*-----------------------------------------------------------------------------*)
end.
|
unit BaseTestUnit;
interface
uses
UnitTestForm,
TestFramework, ThCanvasEditor, ThothController, ThCanvasController,
System.Types, System.Classes, FMX.Types, FMX.Forms, System.SysUtils, ThItem;
type
// Test methods for class TThCanvasEditor
TThCanvasBaseTestUnit = class(TTestCase)
protected
FClosing: Boolean;
FForm: TfrmUnitTest;
FCanvas: TThCanvasEditor;
procedure CreateObject; virtual;
procedure DestroyObject; virtual;
function GetInitialPoint: TPointF;
procedure SetTestControl(var FormRect, CanvasRect: TRectF); virtual;
procedure FormDestroy(Sender: TObject);
function GetCenterPos: TPointF;
public
procedure SetUp; override;
procedure TearDown; override;
procedure Fail(msg: string; ErrorAddrs: Pointer = nil); override;
procedure ShowForm;
function DistanceSize(R: TRectF; D: Single): TPointF;
function DrawRectangle(Left, Top, Right, Bottom: Single; AName: string = ''): TThItem; overload;
function DrawRectangle(TopLeft, BottomRight: TPointF; AName: string = ''): TThItem; overload;
function DrawRectangle(R: TRectF; AName: string = ''): TThItem; overload;
function DrawLine(Left, Top, Right, Bottom: Single; AName: string = ''): TThItem; overload;
function DrawLine(R: TRectF; AName: string = ''): TThItem; overload;
function DrawCircle(Left, Top, Right, Bottom: Single; AName: string = ''): TThItem; overload;
function DrawCircle(R: TRectF; AName: string = ''): TThItem; overload;
function GetItem(X, Y: Single): TThItem; overload;
function GetItem(Pt: TPointF): TThItem; overload;
function GetImagePath: string;
property CenterPos: TPointF read GetCenterPos;
end;
TBaseCommandHistoryTestUnit = class(TThCanvasBaseTestUnit)
protected
FThothController: TThothController;
FCanvasController: TThCanvasEditorController;
procedure CreateObject; override;
procedure DestroyObject; override;
end;
implementation
uses
FMX.Platform, FMX.Graphics, FMX.TestLib, ThConsts;
{ TBastTestUnit }
function TThCanvasBaseTestUnit.GetCenterPos: TPointF;
begin
Result := FCanvas.BoundsRect.CenterPoint;
end;
function TThCanvasBaseTestUnit.GetImagePath: string;
var
Bitmap: TBitmap;
Stream: TResourceStream;
begin
Result := ExtractFilePath(ParamStr(0)) + 'TEST_IMAGE.PNG';
// Create Image file from resource
if not FileExists(Result) then
begin
Bitmap := TBitmap.Create(0, 0);
Stream := TResourceStream.Create(HInstance, 'TEST_IMAGE', RT_RCDATA);
try
Bitmap.LoadFromStream(Stream);
Bitmap.SaveToFile(Result);
finally
Bitmap.Free;
Stream.Free;
end;
end;
end;
function TThCanvasBaseTestUnit.GetInitialPoint: TPointF;
begin
Result := IControl(FCanvas).LocalToScreen(PointF(0, 0));
end;
function TThCanvasBaseTestUnit.GetItem(Pt: TPointF): TThItem;
begin
Result := GetItem(Pt.X, Pt.Y);
end;
function TThCanvasBaseTestUnit.GetItem(X, Y: Single): TThItem;
begin
TestLib.RunMouseClick(X, Y);
Result := FCanvas.SelectedItem;
end;
procedure TThCanvasBaseTestUnit.SetTestControl(var FormRect, CanvasRect: TRectF);
begin
FormRect.Top := 300;
FormRect.Left := 300;
FormRect.Width := 600;
FormRect.Height := 600;
CanvasRect := RectF(50, 50, 350, 350);
end;
procedure TThCanvasBaseTestUnit.SetUp;
var
FormRect, CanvasRect: TRectF;
begin
FClosing := True;
SetTestControl(FormRect, CanvasRect);
FForm := TfrmUnitTest.Create(Application);
FForm.Top := Round(FormRect.Top);
FForm.Left := Round(FormRect.Left);
FForm.Width := Round(FormRect.Width);
FForm.Height := Round(FormRect.Height);
FForm.OnDestroy := FormDestroy;
FForm.Show;
FCanvas := TThCanvasEditor.Create(FForm);
FCanvas.Parent := FForm.Panel1;
FCanvas.Position.Point := CanvasRect.TopLeft;
// FCanvas.Align := TAlignLayout.Client;
FCanvas.Width := CanvasRect.Width;
FCanvas.Height := CanvasRect.Height;
FCanvas.Initialize;
CreateObject;
TestLib.SetInitialMousePoint(GetInitialPoint);
Application.ProcessMessages;
end;
procedure TThCanvasBaseTestUnit.TearDown;
begin
if not FClosing then
Exit;
FForm.Free;
end;
procedure TThCanvasBaseTestUnit.Fail(msg: string; ErrorAddrs: Pointer);
begin
ShowForm;
inherited;
end;
procedure TThCanvasBaseTestUnit.FormDestroy(Sender: TObject);
begin
DestroyObject;
end;
procedure TThCanvasBaseTestUnit.CreateObject;
begin
end;
procedure TThCanvasBaseTestUnit.DestroyObject;
begin
if Assigned(FCanvas) then
begin
FCanvas.Free;
FCanvas := nil;
end;
end;
procedure TThCanvasBaseTestUnit.ShowForm;
begin
FClosing := False;
end;
function TThCanvasBaseTestUnit.DistanceSize(R: TRectF; D: Single): TPointF;
var
Rad: Single;
begin
Rad := ArcTan(R.Height / R.Width);
Result := PointF(Cos(Rad) * D, Sin(Rad) * D);
end;
function TThCanvasBaseTestUnit.DrawCircle(Left, Top, Right, Bottom: Single; AName: string = ''): TThItem;
begin
Result := DrawCircle(RectF(Left, Top, Right, Bottom), AName);
end;
function TThCanvasBaseTestUnit.DrawCircle(R: TRectF; AName: string = ''): TThItem;
begin
FCanvas.DrawItemID := ItemFactoryIDCircle;
MousePath.New
.Add(R.TopLeft)
.Add(R.CenterPoint)
.Add(R.BottomRight);
TestLib.RunMousePath(MousePath.Path);
Result := GetItem(R.CenterPoint);
if Assigned(Result) then
Result.Name := AName;
end;
function TThCanvasBaseTestUnit.DrawLine(Left, Top, Right, Bottom: Single; AName: string = ''): TThItem;
begin
Result := DrawLine(RectF(Left, Top, Right, Bottom), AName);
end;
function TThCanvasBaseTestUnit.DrawLine(R: TRectF; AName: string = ''): TThItem;
begin
FCanvas.DrawItemID := ItemFactoryIDLine; // 1100 is Rectangles ID
MousePath.New
.Add(R.TopLeft)
.Add(R.Left + 1, R.Top)
.Add(R.CenterPoint)
.Add(R.Left, R.Top + 1)
.Add(R.BottomRight);
TestLib.RunMousePath(MousePath.Path);
Result := GetItem(R.CenterPoint);
if Assigned(Result) then
Result.Name := AName;
end;
function TThCanvasBaseTestUnit.DrawRectangle(TopLeft, BottomRight: TPointF;
AName: string): TThItem;
begin
Result := DrawRectangle(RectF(TopLeft.X, TopLeft.Y, BottomRight.X, BottomRight.Y), AName);
end;
function TThCanvasBaseTestUnit.DrawRectangle(Left, Top, Right, Bottom: Single; AName: string = ''): TThItem;
begin
Result := DrawRectangle(RectF(Left, Top, Right, Bottom), AName);
end;
function TThCanvasBaseTestUnit.DrawRectangle(R: TRectF; AName: string = ''): TThItem;
begin
FCanvas.DrawItemID := ItemFactoryIDRectangle;
MousePath.New
.Add(R.TopLeft)
.Add(R.CenterPoint)
.Add(R.BottomRight);
TestLib.RunMousePath(MousePath.Path);
// Result := GetItem(R.CenterPoint);
Result := FCanvas.SelectedItem;
if Assigned(Result) then
Result.Name := AName;
end;
{ TBaseCommandTestUnit }
procedure TBaseCommandHistoryTestUnit.CreateObject;
begin
inherited;
FThothController := TThothController.Create;
FCanvasController := TThCanvasEditorController.Create(FCanvas);
FCanvasController.SetSubject(FThothController);
// FCanvasController.SetThCanvas(FCanvas);
end;
procedure TBaseCommandHistoryTestUnit.DestroyObject;
begin
inherited;
FCanvasController.Free;
FThothController.Free;
end;
end.
|
(*
Il existe deux modes de réception des caractères provenant du modem GSM.
Le mode texte et le mode PDU.
Le mode texte étant le plus aisé a manipulé car les données arrivent
sous forme de texte immédiatement compréhensible et exploitable.
Malheureusement il n'est pas pris en charge par la plupart des
téléphones GSM.
Reste donc le mode PDU! Cette source peut crypter un texte en PDU comme
le décrypter aussi, avec 0 fautes plus de rapidité.
*)
unit TdjPDUCrypt;
interface
function EncodePDU7bits(const Source: String): String;
function DecodePDU7bits(const CodedStr: String): String;
implementation
procedure Bin2Hex(Buffer, Text: PChar; BufSize: Integer); assembler;
const
Convert: array[0..15] of Char = '0123456789ABCDEF';
p: array[1..7] of Byte = ($1, $3, $7, $F, $1F, $3F, $7F);
var
i, Count: Integer;
c, Tmp, r: Byte;
begin
r:= Byte(Buffer[0]);
Count:= 1;
for i := 0 to BufSize - 1 do
if Count < 8 then
begin
c:= r;
if i < (BufSize - 1) then
begin
Tmp:= Byte(Buffer[I + 1]);
r:= Tmp shr Count;
c:= c or ((Tmp and p[Count]) shl (8 - Count));
Inc(Count);
end;
Text[0] := Convert[c shr 4];
Text[1] := Convert[c and $F];
Inc(Text, 2);
end
else
begin
Count:= 1;
if i < BufSize then
r:= Byte(Buffer[i + 1]);
end;
end;
function Hex2Bin(Text, Buffer: PChar; BufSize: Integer): Integer; assembler;
const
Convert: array['0'..'f'] of SmallInt =
( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15);
p: array[1..7] of Byte = ($7F, $3F, $1F, $F, $7, $3, $1);
var
i, Count: Integer;
Tmp, c, r: Byte;
begin
I := BufSize;
Count:= 1;
while i > 0 do
begin
if not (Text[0] in ['0'..'f']) or not (Text[1] in ['0'..'f']) then Break;
c:= (Convert[Text[0]] shl 4) + Convert[Text[1]];
tmp:= c shr (8 - Count);
c:= c and p[Count];
if Count > 1 then
c:= (c shl (Count - 1)) or r;
r:= Tmp;
Buffer[0] := Char(c);
if Count = 7 then
begin
Inc(Buffer);
Buffer[0] := Char(r);
Count:= 1;
end
else
Inc(Count);
Inc(Buffer);
Inc(Text, 2);
Dec(i);
end;
Result := BufSize - i;
end;
function EncodePDU7bits(const Source: String): String;
var Leng: Integer;
begin
Leng:= Length(Source);
Leng:= (Leng * 2)- ((Leng div 8) * 2); {!! Débordement de mémoire: Résolu } ; //
SetLength(Result, Leng);
Bin2Hex(PChar(Source), PChar(Result), Length(Source));
end;
function DecodePDU7bits(const CodedStr: String): String;
var Leng: Integer;
begin
Leng:= Length(CodedStr) div 2;
SetLength(Result, Leng+ (Leng div 7));
Hex2Bin(PChar(CodedStr), PChar(Result), Leng);
end;
end. |
unit Utilities;
interface
uses
Windows, Classes, Graphics, Forms;
function IsNumeric(Value: string): boolean;
function IsFloating(Value: string): boolean;
function IsQuoted(Value: string): boolean;
function AddBackSlash(const sPath: string): string;
function RemoveBackSlash(const sPath: string): string;
function GetStrFromRsc(RscNum: integer): string;
function GetToken(var s: string; const sDelimiter: string): string;
function GetVersionInfo(const Filename: string; const Key: string; var sVersion: string): DWord;
function BooleanToStr(bTmp: boolean): string;
function CrStrToBoolean (const sValue: string): boolean;
function CrBooleanToStr (const bValue: boolean; ResultAsNum: boolean): string;
function CrStrToInteger (const sValue: string): integer;
function CrStrToFloating (const sValue: string): double;
function CrFloatingToStr (const fValue: double): string;
function IsStrEmpty (const sValue: string): boolean;
function IsStringListEmpty (const sList : TStrings): boolean;
function TruncStr (sValue: string): string;
function RTrimList (const sList: TStrings): string;
function RemoveSpaces (const sValue: string): string;
function ReplaceString (sOld,sNew: string; var sMain: string): boolean;
function ColorState(Enable: boolean): TColor;
{Form Position}
procedure LoadFormPos(frmTemp: TForm);
procedure SaveFormPos(frmTemp: TForm);
procedure LoadFormSize(frmTemp: TForm);
procedure SaveFormSize(frmTemp: TForm);
implementation
uses SysUtils, Registry;
{******************************************************************************}
{ Utility Functions }
{******************************************************************************}
{------------------------------------------------------------------------------}
{ IsNumeric }
{------------------------------------------------------------------------------}
function IsNumeric(Value: string): boolean;
var
i : integer;
s : string;
hasNumbers : boolean;
begin
Result := True;
hasNumbers := False;
s := Trim(Value);
if Length(s) = 0 then
begin
Result := False;
Exit;
end;
for i := 1 to Length(s) do
begin
case Ord(s[i]) of
36 : {"$" for currency numbers};
45 : {- for negative numbers};
40,41 : {() for negative specified by brackets};
48..57 : hasNumbers := True; {0 to 9}
else
begin
Result := False;
Exit;
end;
end;
end;
if not hasNumbers then
Result := False;
end;
{------------------------------------------------------------------------------}
{ IsFloating }
{------------------------------------------------------------------------------}
function IsFloating(Value: string): boolean;
var
hasNumbers : boolean;
hasDecimal : boolean;
s : string;
i : integer;
begin
Result := True;
hasDecimal := False;
hasNumbers := False;
s := Trim(Value);
if Length(s) = 0 then
begin
Result := False;
Exit;
end;
for i := 1 to Length(s) do
begin
case Ord(s[i]) of
36 : {"$" for currency numbers};
45 : {- for negative numbers};
40,41 : {() for negative specified by brackets};
46 : begin {Decimal}
if hasDecimal then
begin
Result := False;
Exit;
end
else
begin
hasDecimal := True;
Continue;
end;
end;
48..57 : hasNumbers := True; {Numbers}
else
begin
Result := False;
Exit;
end;
end;
end;
if not hasNumbers then
Result := False;
end;
{------------------------------------------------------------------------------}
{ IsQuoted }
{------------------------------------------------------------------------------}
function IsQuoted(Value: string): boolean;
var
s : string;
bSingle : boolean;
begin
Result := False;
s := Trim(Value);
if Length(s) = 0 then
begin
Result := True;
Exit;
end;
if Length(s) = 1 then
Exit;
{First Quote}
if (Ord(s[1]) = 34) {double quote} or (Ord(s[1]) = 39) {single quote} then
begin
bSingle := (Ord(s[1]) = 39);
{Last Quote}
if bSingle then
begin
if (Ord(s[Length(s)]) = 39) then Result := True;
end
else
begin
if (Ord(s[Length(s)]) = 34) then Result := True;
end;
end;
end;
{------------------------------------------------------------------------------}
{ AddBackSlash }
{------------------------------------------------------------------------------}
function AddBackSlash(const sPath: string): string;
var
L: Integer;
begin
Result := Trim(sPath);
L := Length(Result);
if (L > 3) then
begin
if not (Result[L] = '\') then
Result := Result + '\';
end;
end;
{------------------------------------------------------------------------------}
{ RemoveBackSlash }
{------------------------------------------------------------------------------}
function RemoveBackSlash(const sPath: string): string;
var
S : string;
L : Integer;
begin
Result := Trim(sPath);
S := Trim(sPath);
L := Length(S);
if L > 3 then
begin
if S[L] = '\' then
Result := Copy(S, 1, L-1);
end;
end;
{------------------------------------------------------------------------------}
{ GetToken }
{ - Searches a string for a delimiter }
{ - The string before the delimiter is returned }
{ - The original string has the substring and delimiter removed }
{------------------------------------------------------------------------------}
function GetToken(var s: string; const sDelimiter: string): string;
var
nPos, nOfs, nLen : Byte;
sTmp : string;
begin
{Get the position of the Delimiter}
nPos := Pos(sDelimiter, s);
{Get the length of the Delimiter}
nLen := Length(sDelimiter);
nOfs := nLen - 1;
if (IsStrEmpty(s)) or ((nPos = 0) and (Length(s) > 0)) then
begin
Result := s;
s := '';
end
else
begin
sTmp := Copy(s, 1, nPos + nOfs);
s := Copy(s, nPos + nLen, Length(s));
Result := Copy(sTmp, 1, Length(sTmp) - nLen);
end;
end; { GetToken }
{------------------------------------------------------------------------------}
{ GetStrFromRsc function : Get String from Resource File }
{------------------------------------------------------------------------------}
function GetStrFromRsc(RscNum: integer): string;
var
ErrorBuf : array[0..255] of Char;
begin
Result := '';
if LoadString(hInstance, RscNum, Addr(ErrorBuf), 256) <> 0 then
Result := StrPas(ErrorBuf);
end;
{------------------------------------------------------------------------------}
{ Extract information from a file's VERSIONINFO resource }
{------------------------------------------------------------------------------}
function GetVersionInfo(const Filename: string; const Key: string;
var sVersion: string): DWord;
type
{Translation table: specifies languages & character sets}
VerLangCharSet = record
Lang : Word;
CharSet : Word;
end;
VerTranslationTable = array[0..MaxListSize] of VerLangCharSet;
pVerTranslationTable = ^VerTranslationTable;
var
sFileName : string;
Size : DWord;
InfoHandle : DWord;
fHandle : THandle;
pData : Pointer;
Buffer : Pointer;
Len : DWord;
pTable : pVerTranslationTable;
sLangCharSet : string;
Path : string;
sTmp : string;
begin
Result := 0;
sVersion := '7,0,0,0';
sFileName := FileName;
{GetFileVersionInfoSize}
Size := GetFileVersionInfoSize(PChar(sFileName), InfoHandle);
if Size = 0 then
begin
Result := GetLastError;
Exit;
end;
{GlobalAlloc}
fHandle := GlobalAlloc(GMEM_FIXED, Size);
if fHandle = 0 then
begin
Result := GetLastError;
Exit;
end;
{GlobalLock}
pData := GlobalLock(fHandle);
if pData = nil then
begin
if fHandle <> 0 then
GlobalFree(fHandle);
Result := GetLastError;
Exit;
end;
{GetFileVersionInfo}
if not GetFileVersionInfo(PChar(Filename), InfoHandle, Size, pData) then
begin
if fHandle <> 0 then
GlobalFree(fHandle);
Result := GetLastError;
Exit;
end;
{Load Translation Table}
sTmp := '\VarFileInfo\Translation';
{VerQueryValue}
if not VerQueryValue(pData, PChar(sTmp), Buffer, Len) then
begin
if fHandle <> 0 then
GlobalFree(fHandle);
Result := GetLastError;
Exit;
end;
{Establish default Lang-Char set}
pTable := Buffer;
sLangCharSet := Format('%4.4x%4.4x', [pTable^[0].Lang, pTable^[0].CharSet]);
{Format the Path String}
Path := Format('\StringFileInfo\%s\%s', [sLangCharSet, Key]);
{Get the Version Info}
if not VerQueryValue(pData, PChar(Path), Buffer, Len) then
begin
if fHandle <> 0 then
GlobalFree(fHandle);
Result := GetLastError;
Exit;
end;
sVersion := String(PChar(Buffer));
{Clean up}
if fHandle <> 0 then
GlobalFree(fHandle);
end;
{------------------------------------------------------------------------------}
{ CrStrToBoolean }
{------------------------------------------------------------------------------}
function CrStrToBoolean (const sValue: string): boolean;
var
sTmp : string;
begin
sTmp := UpperCase(Trim(sValue));
if Length(sTmp) > 0 then
sTmp := sTmp[1]
else
sTmp := 'F';
if (sTmp = '1') or (sTmp = 'T') or (sTmp = 'Y') then
Result := True
else
Result := False;
end;
{------------------------------------------------------------------------------}
{ CrBooleanToStr }
{------------------------------------------------------------------------------}
function CrBooleanToStr (const bValue: boolean; ResultAsNum: boolean): string;
begin
if bValue = True then
begin
if ResultAsNum then
Result := '1'
else
Result := 'True';
end
else
begin
if ResultAsNum then
Result := '0'
else
Result := 'False';
end;
end;
{------------------------------------------------------------------------------}
{ BooleanToStr }
{------------------------------------------------------------------------------}
function BooleanToStr(bTmp: boolean): string;
begin
if bTmp = True then
Result := 'True'
else
Result := 'False';
end;
{------------------------------------------------------------------------------}
{ CrStrToInteger }
{------------------------------------------------------------------------------}
function CrStrToInteger (const sValue: string): integer;
var
s : string;
begin
Result := 0;
s := Trim(sValue);
if IsNumeric(s) then
Result := StrToInt(s);
end;
{------------------------------------------------------------------------------}
{ CrStrToFloating }
{------------------------------------------------------------------------------}
function CrStrToFloating (const sValue: string): double;
var
s : string;
begin
Result := 0;
s := Trim(sValue);
if IsFloating(s) then
Result := StrToFloat(s);
end;
{------------------------------------------------------------------------------}
{ CrFloatingToStr }
{------------------------------------------------------------------------------}
function CrFloatingToStr (const fValue: double): string;
var
sTmp : string;
begin
sTmp := '0';
sTmp := FloatToStrF(fValue, ffGeneral, 15, 2);
if (sTmp = 'NAN') or (sTmp = 'INF') or (sTmp = '-INF') then
sTmp := '0';
Result := sTmp;
end;
{------------------------------------------------------------------------------}
{ TruncStr }
{------------------------------------------------------------------------------}
function TruncStr (sValue: string): string;
var
i : integer;
begin
Result := sValue;
i := Pos('.', sValue);
if i > 0 then
Result := Copy(sValue, 1, i-1);
end;
{------------------------------------------------------------------------------}
{ RemoveSpaces }
{------------------------------------------------------------------------------}
function RemoveSpaces (const sValue: string): string;
var
i : integer;
s : string;
begin
Result := '';
s := sValue;
i := 1;
while i > 0 do
begin
i := Pos(' ', s);
if i > 0 then
s := Copy(s, 1, i-1) + Copy(s, i+1, Length(s));
end;
Result := s;
end;
{------------------------------------------------------------------------------}
{ ReplaceString }
{------------------------------------------------------------------------------}
function ReplaceString (sOld,sNew:string; var sMain: string): boolean;
var
i : integer;
s1,s2 : string;
begin
Result := False;
i := Pos(sOld, sMain);
if i = -1 then Exit;
s1 := Copy(sMain, 1, i-1);
s2 := Copy(sMain, i+Length(sOld), Length(sMain));
sMain := s1 + sNew + s2;
Result := True;
end;
{------------------------------------------------------------------------------}
{ RTrimList }
{ - Get rid of any LF's (line feeds) and the CR at the end of the Stringlist }
{------------------------------------------------------------------------------}
function RTrimList (const sList: TStrings): string;
var
s1 : string;
begin
s1 := '';
if sList = nil then Exit;
s1 := sList.Text;
{Remove any trailing LF/CR}
while True do
begin
if Length(s1) = 0 then
Break;
if (s1[Length(s1)] = #10) then
s1 := Copy(s1, 1, Length(s1) - 1)
else if (s1[Length(s1)] = #13) then
s1 := Copy(s1, 1, Length(s1) - 1)
else
Break;
end;
Result := s1;
end;
{------------------------------------------------------------------------------}
{ IsStrEmpty }
{------------------------------------------------------------------------------}
function IsStrEmpty(const sValue: string): boolean;
var
sTmp : string;
begin
Result := True;
sTmp := Trim(sValue);
if Length(sTmp) > 0 then
Result := False;
end; { IsStrEmpty }
{------------------------------------------------------------------------------}
{ IsStringListEmpty }
{------------------------------------------------------------------------------}
function IsStringListEmpty (const sList : TStrings): boolean;
var
sTmp : string;
begin
Result := True;
sTmp := RTrimList(sList);
if Length(sTmp) > 0 then
Result := False;
end;
{------------------------------------------------------------------------------}
{ ColorState }
{ - Returns the active/inactive color of a component }
{------------------------------------------------------------------------------}
function ColorState(Enable: boolean): TColor;
begin
Result := clInactiveCaptionText;
if Enable then
Result := clWindow;
end;
{------------------------------------------------------------------------------}
{ LoadFormPos }
{------------------------------------------------------------------------------}
procedure LoadFormPos(frmTemp: TForm);
var
RegIni : TRegIniFile;
begin
{Read the Registry}
RegIni := TRegIniFile.Create('Software\Crystal Decisions\10.0\CrystalVCL\');
try
frmTemp.Left := RegIni.ReadInteger(frmTemp.Name,'Left',-1);
frmTemp.Top := RegIni.ReadInteger(frmTemp.Name,'Top',-1);
finally
RegIni.Free;
end;
if (frmTemp.Top < 0) or (frmTemp.Left < 0) or
((frmTemp.Top + frmTemp.Height) > Screen.Height) or
((frmTemp.Left + frmTemp.Width) > Screen.Width) then
frmTemp.Position := poScreenCenter;
end;
{------------------------------------------------------------------------------}
{ SaveFormPos }
{------------------------------------------------------------------------------}
procedure SaveFormPos(frmTemp: TForm);
var
RegIni : TRegIniFile;
begin
{Read the Registry}
RegIni := TRegIniFile.Create('Software\Crystal Decisions\10.0\CrystalVCL\');
try
RegIni.WriteInteger(frmTemp.Name,'Left',frmTemp.Left);
RegIni.WriteInteger(frmTemp.Name,'Top',frmTemp.Top);
finally
RegIni.Free;
end;
end;
{------------------------------------------------------------------------------}
{ LoadFormSize }
{------------------------------------------------------------------------------}
procedure LoadFormSize(frmTemp: TForm);
var
RegIni : TRegIniFile;
begin
{Read the Registry}
RegIni := TRegIniFile.Create('Software\Crystal Decisions\10.0\CrystalVCL\');
try
frmTemp.Left := RegIni.ReadInteger(frmTemp.Name,'Left',-1);
frmTemp.Top := RegIni.ReadInteger(frmTemp.Name,'Top',-1);
frmTemp.Width := RegIni.ReadInteger(frmTemp.Name,'Width',-1);
frmTemp.Height := RegIni.ReadInteger(frmTemp.Name,'Height',-1);
finally
RegIni.Free;
end;
if (frmTemp.Top < 0) or (frmTemp.Left < 0) or
((frmTemp.Top + frmTemp.Height) > Screen.Height) or
((frmTemp.Left + frmTemp.Width) > Screen.Width) then
frmTemp.Position := poScreenCenter;
if (frmTemp.Width < 289) or (frmTemp.Height < 300) then
begin
frmTemp.Width := 289;
frmTemp.Height := 300;
end;
end;
{------------------------------------------------------------------------------}
{ SaveFormSize }
{------------------------------------------------------------------------------}
procedure SaveFormSize(frmTemp: TForm);
var
RegIni : TRegIniFile;
begin
{Read the Registry}
RegIni := TRegIniFile.Create('Software\Crystal Decisions\10.0\CrystalVCL\');
try
RegIni.WriteInteger(frmTemp.Name,'Left',frmTemp.Left);
RegIni.WriteInteger(frmTemp.Name,'Top',frmTemp.Top);
RegIni.WriteInteger(frmTemp.Name,'Width',frmTemp.Width);
RegIni.WriteInteger(frmTemp.Name,'Height',frmTemp.Height);
finally
RegIni.Free;
end;
end;
end.
|
unit PAG0001P.View;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, PesquisaBase.View, cxGraphics,
cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, cxControls, cxContainer,
cxEdit, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator,
cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData,
FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxClasses,
cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, cxTextEdit,
dxGDIPlusClasses, Vcl.ExtCtrls, cxLabel, Vcl.StdCtrls, cxButtons,
Base.View.Interf, ormbr.container.DataSet.interfaces,
TPAGFORNECEDOR.Entidade.Model, ormbr.container.fdmemtable, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver,
dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinBlack, dxSkinDarkRoom, dxSkinSilver;
type
TFPAG0001PView = class(TFPesquisaView, IBasePesquisaView)
FdDadosCODIGO: TStringField;
FdDadosIDFORNECEDOR: TIntegerField;
FdDadosNOMEFANTASIA: TStringField;
FdDadosCNPJ: TStringField;
FdDadosIE: TStringField;
FdDadosTELEFONE: TStringField;
FdDadosEMAIL: TStringField;
VwDadosIDFORNECEDOR: TcxGridDBColumn;
VwDadosNOMEFANTASIA: TcxGridDBColumn;
VwDadosCNPJ: TcxGridDBColumn;
VwDadosIE: TcxGridDBColumn;
VwDadosTELEFONE: TcxGridDBColumn;
VwDadosEMAIL: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BtNovoClick(Sender: TObject);
procedure BtAlterarClick(Sender: TObject);
procedure BtConsultarClick(Sender: TObject);
procedure BtExcluirClick(Sender: TObject);
procedure BtDuplicarClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FContainer: IContainerDataSet<TTPAGFORNECEDOR>;
procedure listarRegistros;
public
{ Public declarations }
class function New: IBasePesquisaView;
function incluirRegistro: IBasePesquisaView;
function alterarRegistro: IBasePesquisaView;
function consultarRegistro: IBasePesquisaView;
function excluirRegistro: IBasePesquisaView;
function duplicarRegistro: IBasePesquisaView;
procedure &executar;
end;
var
FPAG0001PView: TFPAG0001PView;
implementation
{$R *.dfm}
uses FacadeView, Tipos.Controller.Interf;
{ TFPAG0001PView }
function TFPAG0001PView.alterarRegistro: IBasePesquisaView;
begin
Result := Self;
TFacadeView.New
.ModulosFacadeView
.PagarFactoryView
.exibirTelaCadastro(tcFornecedor)
.operacao(FOperacao)
.registroSelecionado(FdDadosCODIGO.AsString)
.executar;
end;
procedure TFPAG0001PView.BtAlterarClick(Sender: TObject);
begin
inherited;
alterarRegistro;
listarRegistros;
end;
procedure TFPAG0001PView.BtConsultarClick(Sender: TObject);
begin
inherited;
consultarRegistro;
listarRegistros;
end;
procedure TFPAG0001PView.BtDuplicarClick(Sender: TObject);
begin
inherited;
duplicarRegistro;
listarRegistros;
end;
procedure TFPAG0001PView.BtExcluirClick(Sender: TObject);
begin
inherited;
excluirRegistro;
listarRegistros;
end;
procedure TFPAG0001PView.BtNovoClick(Sender: TObject);
begin
inherited;
incluirRegistro;
listarRegistros;
end;
function TFPAG0001PView.consultarRegistro: IBasePesquisaView;
begin
Result := Self;
TFacadeView.New
.ModulosFacadeView
.PagarFactoryView
.exibirTelaCadastro(tcFornecedor)
.operacao(FOperacao)
.registroSelecionado(FdDadosCODIGO.AsString)
.executar;
end;
function TFPAG0001PView.duplicarRegistro: IBasePesquisaView;
begin
Result := Self;
TFacadeView.New
.ModulosFacadeView
.PagarFactoryView
.exibirTelaCadastro(tcFornecedor)
.operacao(FOperacao)
.registroSelecionado(FdDadosCODIGO.AsString)
.executar;
end;
function TFPAG0001PView.excluirRegistro: IBasePesquisaView;
begin
Result := Self;
TFacadeView.New
.ModulosFacadeView
.PagarFactoryView
.exibirTelaCadastro(tcFornecedor)
.operacao(FOperacao)
.registroSelecionado(FdDadosCODIGO.AsString)
.executar;
end;
procedure TFPAG0001PView.executar;
begin
Show;
end;
procedure TFPAG0001PView.FormCreate(Sender: TObject);
begin
inherited;
FContainer := TContainerFDMemTable<TTPAGFORNECEDOR>.Create(FConexao, FdDados);
end;
procedure TFPAG0001PView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
inherited;
case Key of
VK_F5:
begin
incluirRegistro;
listarRegistros;
end;
VK_F6:
begin
alterarRegistro;
listarRegistros;
end;
VK_F7:
begin
consultarRegistro;
listarRegistros;
end;
VK_F8:
begin
excluirRegistro;
listarRegistros;
end;
VK_F9:
begin
duplicarRegistro;
listarRegistros;
end;
end;end;
procedure TFPAG0001PView.FormShow(Sender: TObject);
begin
inherited;
FCampoOrdem := 'NOMEFANTASIA';
listarRegistros;
end;
function TFPAG0001PView.incluirRegistro: IBasePesquisaView;
begin
Result := Self;
TFacadeView.New
.ModulosFacadeView
.PagarFactoryView
.exibirTelaCadastro(tcFornecedor)
.operacao(FOperacao)
.executar
end;
procedure TFPAG0001PView.listarRegistros;
begin
FContainer.OpenWhere('', FCampoOrdem);
controlaBotoesAtivos;
end;
class function TFPAG0001PView.New: IBasePesquisaView;
begin
Result := Self.Create(nil);
end;
end.
|
namespace GlHelper;
{ Helper Class for read *.Shape Files
These Files are from a internal Software with a own Format
These internal Software is based on OpenCascade and not public
}
{$IF TOFFEE OR ISLAND}
interface
uses
RemObjects.Elements.RTL;
type
ShapeReader = public class
private
stream : FileHandle;
method ReadBuff(Buffer: ^Void; Count: LongInt): LongInt;
method ReadInteger : Integer;
method ReadVec3Array : array of TVector3;
method ReadIntArray: array of Int32;
public
constructor ();
method load(const aFilename: String) : Shape;
end;
implementation
constructor ShapeReader();
begin
inherited ();
end;
method ShapeReader.load(const aFilename: String): Shape;
begin
result := nil;
if aFilename.FileExists then
begin
{Open the File}
stream := new FileHandle(aFilename, FileOpenMode.ReadOnly);
{Read the Version must be 1 at these point }
try
if ReadInteger = 1 then
begin
var Faces : Integer := ReadInteger;
result := new Shape(Faces);
// Start Points of Faces
for i:Integer := 0 to Faces-1 do
begin
var temp := ReadVec3Array;
if temp <> nil then
result.addFaceVecs(i, temp);
end;
// Start Normals
Faces := ReadInteger;
for i: Integer := 0 to Faces-1 do
begin
var temp := ReadVec3Array;
if temp <> nil then
result.addNormales(i, temp);
end;
// Start Indexes
Faces := ReadInteger;
for i : Integer := 0 to Faces-1 do
begin
var temp := ReadIntArray;
if temp <> nil then
result.addIndexes(i, temp);
end;
end;
finally
stream.Close;
end;
end;
end;
method ShapeReader.ReadBuff(Buffer: ^Void; Count: LongInt): LongInt;
begin
var lBuf := new Byte[Count];
result := stream.&Read(lBuf, 0, Count);
{$IF ISLAND}
{$IF WINDOWS}ExternalCalls.memcpy(Buffer, @lBuf[0], Count){$ELSEIF POSIX}rtl.memcpy(Buffer, @lBuf[0], Count){$ENDIF};
{$ELSEIF TOFFEE}
memcpy(Buffer, @lBuf[0], Count);
{$ENDIF}
end;
method ShapeReader.ReadInteger: Integer;
begin
ReadBuff(var result, 4);
end;
method ShapeReader.ReadVec3Array: array of TVector3;
begin
result := nil;
Var fCountVecs : Integer := ReadInteger;
if fCountVecs > 0 then
begin
result := new TVector3[fCountVecs];
ReadBuff(var result[0], 12*fCountVecs);
end;
end;
method ShapeReader.ReadIntArray: array of Int32;
begin
result := nil;
Var fCount : Integer := ReadInteger;
if fCount > 0 then
begin
result := new Int32[fCount];
ReadBuff(var result[0], 4*fCount);
end;
end;
{$ENDIF}
end. |
unit Analyse;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Transfer, XMLIntf;
type
/// <summary>
/// 分析事件,当分析器分析返回的更新呢内容时会触发。
/// </summary>
TOnAnalyse = procedure (Sender: TObject; Count, Current: Integer) of object;
TOnResult = procedure (str: TStrings) of object;
/// <summary>
/// 分析器基类
/// </summary>
/// <remarks>
/// 通过调用GetUpdateList方法获取一个UpdateList列表。列表中的每个对象是TUpdate对象
/// </remarks>
TAnalyse = class(TPersistent)
private
FOnAnalyse: TOnAnalyse;
FTransfer: TTransfer;
FUpdateList: string;
procedure Analyse(Sender: TObject; Count, Current: Integer);
protected
function AnalyseData(AStream: TStream): TStrings; virtual; abstract;
public
/// <summary>
/// 析构方法
/// </summary>
destructor Destroy; override;
/// <summary>
/// 获取Update对象列表的方法。该方法是一个纯虚方法,需要后面的继承类实现该方法。
/// </summary>
function GetUpdateList: TStrings; virtual;
/// <summary>
/// 传输对象。每一个分析器自带一个传输对象。
/// </summary>
/// <seealso cref="TTransfer">
/// TTransfer
/// </seealso>
property Transfer: TTransfer read FTransfer write FTransfer;
/// <summary>
/// UpdateList网络更新文件的URL地址
/// </summary>
property UpdateList: string read FUpdateList write FUpdateList;
published
/// <summary>
/// 分析事件,分析时会触发该事件,方便客户端显示。
/// </summary>
property OnAnalyse: TOnAnalyse read FOnAnalyse write FOnAnalyse;
end;
type userarray=array of string;
/// <summary>
/// 对返回的XML对象进行分析的类。该类主要是针对返回的数据是XML的时候对其进行分析。
/// </summary>
TXMLAnalyse = class(TAnalyse)
private
Fstr: array of string;
procedure CreateFileDir(path: string);
procedure arrayString(s:string; dot:char);
protected
function AnalyseData(Stream: TStream): TStrings; override;
public
end;
TTestThread = class(TThread)
private
FAn: TAnalyse;
FOnRe: TOnResult;
public
constructor Create(an: TAnalyse);
destructor Destroy; override;
property OnRe: TOnResult write FOnRe;
protected
procedure Execute; override;
end;
implementation
uses
IdUri, XMLDoc, JGWUpdate, ActiveX;
{
********************************* TXMLAnalyse **********************************
}
procedure TXMLAnalyse.arrayString(s:string;dot:char);
var
i,j: Integer;
begin
i := 1;
j := 0;
SetLength(Fstr, 50);
while Pos(dot, s) > 0 do
begin
Fstr[j] := copy(s, i, pos(dot,s) - i);
i := pos(dot,s) + 1;
s[i-1] := chr(ord(dot) + 1);
j:=j+1;
end;
Fstr[j] := copy(s, i, strlen(pchar(s)) - i + 1);
end;
procedure TXMLAnalyse.CreateFileDir(path: string);
var
i: integer;
temp: string;
begin
arrayString(path,'/');
for i := 0 to length(Fstr) - 1 do
begin
if Fstr[i] <> '' then
begin
if POS('.',Fstr[i]) > 0 then
begin
break;
end;
temp := ExtractFilePath(Application.ExeName);
temp := temp + Fstr[i];
if not (DirectoryExists(temp)) then
begin
forcedirectories(temp);
end;
end
else
break;
end;
end;
function TXMLAnalyse.AnalyseData(Stream: TStream): TStrings;
var
Xml: IXMLDocument;
RootNode, Node: IXMLNode;
i: Integer;
Update: TUpdate;
tmpUpdate: TUpdate;
RetList: TStringList;
dateTimeFormat: TFormatSettings;
temp: string;
begin
// TODO -cMM: TXMLAnalyse.AnalyseData default body inserted
CoInitialize(nil);
Xml := NewXmlDocument();
Xml.LoadFromStream(Stream);
RootNode := Xml.DocumentElement;
RetList := TStringList.Create;
// GetLocaleFormatSettings(0, dateTimeFormat);
dateTimeFormat := TFormatSettings.Create;
dateTimeFormat.DateSeparator := '-';
dateTimeFormat.LongDateFormat := 'YYYY-MM-DD';
Update := TFileUpdate.Create;
for i := 0 to RootNode.ChildNodes.Count - 1 do
begin
if (Assigned(OnAnalyse)) then
OnAnalyse(self, RootNode.ChildNodes.Count, i);
Node := RootNode.ChildNodes[i];
// ShowMessage(Node.ChildNodes['chkType'].Text);
Update.ChkType := TChkType(StrToInt(Node.ChildNodes['chkType'].Text));
temp := Node.ChildNodes['DeskFile'].text;
CreateFileDir(temp);
UPdate.LocalFile := Node.ChildNodes['DeskFile'].text;
Update.NewDate := StrToDateTime(Node.ChildNodes['DateTime'].text, dateTimeFormat);
Update.NewVersion := Node.ChildNodes['Version'].Text;
//Update.TempPath := GetSystemTempPath();
Update.UpdateType := TUpdateType(StrToInt(Node.ChildNodes['UpdateType'].Text));
Update.UpdateURL := Node.ChildNodes['FileURL'].Text;
Update.FileName := Node.ChildNodes['FileName'].Text;
Update.NewSize := strtoInt64(Node.ChildNodes['FileSize'].Text);
tmpUpdate := Update.Analyse;
if (Assigned(tmpUpdate)) then
begin
RetList.AddObject(Format('%s 文件大小:[%dK]', [tmpUpdate.FileName, tmpUpdate.NewSize div 1024]), tmpUpdate);
end;
end;
Xml := nil;
Result := RetList;
FreeAndNil(Update);
end;
{
*********************************** TAnalyse ***********************************
}
destructor TAnalyse.Destroy;
begin
// TODO -cMM: TAnalyse.Destory default body inserted
FTransfer := nil;
inherited;
end;
procedure TAnalyse.Analyse(Sender: TObject; Count, Current: Integer);
begin
if Assigned(FOnAnalyse) then
FOnAnalyse(Sender, Count, Current);
end;
function TAnalyse.GetUpdateList: TStrings;
var
Mem: TMemoryStream;
URI: TIdURI;
begin
Result := nil;
if (Assigned(Transfer)) then
begin
URI := TIdURI.Create(UpdateList);
Mem := TMemoryStream.Create;
Transfer.URI := URI;
try
Transfer.Get(Mem);
Result := AnalyseData(Mem);
finally
FreeAndNil(Mem);
FreeAndNil(URI);
end;
end;
end;
constructor TTestThread.Create(an: TAnalyse);
begin
inherited Create(True);
FAn := an;
end;
destructor TTestThread.Destroy;
begin
if Assigned(FAn) then
FreeAndNil(FAn);
inherited;
// TODO -cMM: TTestThread.Destroy default body inserted
end;
procedure TTestThread.Execute;
var
temp: TStrings;
begin
inherited;
try
temp := FAn.GetUpdateList;
if Assigned(FOnRe) then
begin
FOnRe(temp);
FreeAndNil(FAn);
end;
except
temp := nil;
FOnRe(temp);
FreeAndNil(FAn);
end;
end;
end.
|
unit uWizImportVendorCatalog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentWizImp, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxEdit, DB, cxDBData, DBClient, ImgList, ExtCtrls, StdCtrls,
Buttons, Grids, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
ComCtrls, cxCurrencyEdit;
type
TVendor = class
IDVendor: Variant;
public
constructor Create(IDPessoa : Variant);
end;
TWizImportVendorCatalog = class(TParentWizImp)
grdValidateModelFile: TcxGrid;
grdValidateModelFileTableView: TcxGridDBTableView;
cbxCostIncCaseCost: TCheckBox;
GroupBox1: TGroupBox;
cbVendorList: TComboBox;
Label3: TLabel;
Label21: TLabel;
Update: TcxGridDBColumn;
btnSelectAll: TBitBtn;
CbCostChange: TComboBox;
Label2: TLabel;
Label4: TLabel;
TbItemsOption: TTabControl;
BtnConfirmCostChange: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure grdValidateModelFileTableViewCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
procedure btnSelectAllClick(Sender: TObject);
procedure CbCostChangeChange(Sender: TObject);
procedure TbItemsOptionChange(Sender: TObject);
procedure cdsFileBeforePost(DataSet: TDataSet);
procedure grdValidateModelFileExit(Sender: TObject);
private
{ Private declarations }
FIndiceColumnValidation : Integer;
function OnAfterChangePage:Boolean; override;
function DoFinish:Integer; override;
function AddSpecificFieldsToCDS(Position : Integer): Integer; override;
function SaveGridColumns: String;
function TestBeforeNavigate:Boolean; override;
function VerifyFieldsRequired: Boolean;
procedure GetConfigImport;
procedure GetGridColumn(ACrosColumn : String);
procedure AddComboVendor;
procedure ClearComboVendor;
procedure FillColumnsGrid; override;
procedure AddColumnsToImport; override;
procedure AddColumnsToValidateModelGrid;
procedure AddSpecificFriendFieldsToCDS(Position : Integer); override;
procedure FilterCdsFile;
procedure CalculateCostChange( Sender: TObject );
public
{ Public declarations }
end;
var
WizImportVendorCatalog: TWizImportVendorCatalog;
implementation
uses uMsgBox, uDMImportExport, uParamFunctions, uCDSFunctions, uSystemConst,
uParentWizard;
{$R *.dfm}
{==============================================================================}
{ Vendor control }
constructor TVendor.Create(IDPessoa : Variant);
begin
IDVendor := IDPessoa;
end;
procedure TWizImportVendorCatalog.AddComboVendor;
begin
ClearComboVendor;
DMImportExport.cdsLookupVendor.First;
while not DMImportExport.cdsLookupVendor.Eof do
begin
cbVendorList.Items.AddObject(DMImportExport.cdsLookupVendor.Fields.FieldByName('Vendor').AsString,
TVendor.Create(DMImportExport.cdsLookupVendor.Fields.FieldByName('IDVendor').AsVariant));
DMImportExport.cdsLookupVendor.Next;
end;
end;
procedure TWizImportVendorCatalog.ClearComboVendor;
var
Vendor : TVendor;
begin
while cbVendorList.Items.Count > 0 do
begin
Vendor := TVendor(cbVendorList.Items.Objects[0]);
FreeAndNil(Vendor);
cbVendorList.Items.Delete(0);
end;
cbVendorList.Clear;
end;
{------------------------------------------------------------------------------}
{==============================================================================}
{ Cross column control }
procedure TWizImportVendorCatalog.AddColumnsToImport;
begin
inherited;
sgColumns.Cells[0,1] := 'BarCode';
sgColumns.Cells[0,2] := 'VendorCode';
sgColumns.Cells[0,3] := 'Description';
sgColumns.Cells[0,4] := 'Cost';
sgColumns.Cells[0,5] := 'CaseCost';
sgColumns.Cells[0,6] := 'CaseQty';
sgColumns.Cells[0,7] := 'MinQty';
sgColumns.RowCount := 08;
end;
procedure TWizImportVendorCatalog.FillColumnsGrid;
begin
inherited;
sgColumns.Cells[0,0] := 'Main Retail';
sgColumns.Cells[1,0] := 'Vendor Catalog';
AddColumnsToImport;
{ Adds the columns of the file to the cross column control }
AddComboColumnsToImport;
end;
function TWizImportVendorCatalog.AddSpecificFieldsToCDS(Position: Integer): Integer;
begin
CreateCDSField(cdsFile, 'Update', ftString, Position+1, True);
CreateCDSField(cdsFile, 'OldCost', ftFloat, Position+2, True);
CreateCDSField(cdsFile, 'OldCaseQty', ftString, Position+3, True);
CreateCDSField(cdsFile, 'OldMinQty', ftString, Position+4, True);
Result := Position + 5;
end;
procedure TWizImportVendorCatalog.AddSpecificFriendFieldsToCDS(Position: Integer);
begin
CreateCDSField(cdsFile, 'IdModel', ftFloat, Position+1, True);
CreateCDSField(cdsFile, 'CostChange', ftFloat, Position+2, True);
CreateCDSField(cdsFile, 'FieldCostCalc', ftFloat, Position+3, True);
CreateCDSField(cdsFile, 'AbsCostChange', ftFloat, Position+4, True);
CreateCDSField(cdsFile, 'ChangeType', ftString, Position+5, True);
end;
{------------------------------------------------------------------------------}
{==============================================================================}
{ Form control }
procedure TWizImportVendorCatalog.AddColumnsToValidateModelGrid;
var
i: Integer;
NewColumn: TcxGridDBColumn;
FieldBarcode, FieldDescription, FieldNewCost,
FieldCaseCost, FieldVendorCode, FieldNewCaseQty,
FieldNewMinQty : String;
begin
if (LinkedColumns.Values['Barcode'] <> '') then
begin
FieldBarcode := cdsFile.FieldByName(LinkedColumns.Values['Barcode']).FieldName;
cdsFile.FieldByName(FieldBarcode).ReadOnly := True;
end;
if (LinkedColumns.Values['VendorCode'] <> '') then
begin
FieldVendorCode := cdsFile.FieldByName(LinkedColumns.Values['VendorCode']).FieldName;
cdsFile.FieldByName(FieldVendorCode).ReadOnly := True;
end;
if (LinkedColumns.Values['Description'] <> '') then
begin
FieldDescription := cdsFile.FieldByName(LinkedColumns.Values['Description']).FieldName;
cdsFile.FieldByName(FieldDescription).ReadOnly := True;
end;
if (LinkedColumns.Values['Cost'] <> '') then
begin
FieldNewCost := cdsFile.FieldByName(LinkedColumns.Values['Cost']).FieldName;
cdsFile.FieldByName(FieldNewCost).ReadOnly := False;
end;
if (LinkedColumns.Values['CaseCost'] <> '') then
begin
FieldCaseCost := cdsFile.FieldByName(LinkedColumns.Values['CaseCost']).FieldName;
cdsFile.FieldByName(FieldCaseCost).ReadOnly := False;
end;
if (LinkedColumns.Values['CaseQty'] <> '') then
begin
FieldNewCaseQty := cdsFile.FieldByName(LinkedColumns.Values['CaseQty']).FieldName;
cdsFile.FieldByName(FieldNewCaseQty).ReadOnly := False;
end;
if (LinkedColumns.Values['MinQty'] <> '') then
begin
FieldNewMinQty := cdsFile.FieldByName(LinkedColumns.Values['MinQty']).FieldName;
cdsFile.FieldByName(FieldNewMinQty).ReadOnly := False;
end;
i := 0;
while grdValidateModelFileTableView.ColumnCount > 1 do
begin
if ( (grdValidateModelFileTableView.Columns[i].Caption = 'Update') )
then begin
inc(i);
end else begin
grdValidateModelFileTableView.Columns[i].DataBinding.FieldName := '';
grdValidateModelFileTableView.Columns[i].Free;
end;
end;
for i := 0 to Pred(cdsFile.FieldDefs.Count) do
begin
if (cdsFile.FieldDefs[i].DisplayName = FieldBarcode) or
(cdsFile.FieldDefs[i].DisplayName = FieldVendorCode) or
(cdsFile.FieldDefs[i].DisplayName = FieldDescription) or
(cdsFile.FieldDefs[i].DisplayName = FieldNewCost) or
(cdsFile.FieldDefs[i].DisplayName = FieldCaseCost) or
(cdsFile.FieldDefs[i].DisplayName = FieldNewCaseQty) or
(cdsFile.FieldDefs[i].DisplayName = FieldNewMinQty) or
(cdsFile.FieldDefs[i].DisplayName = 'OldCost') or
(cdsFile.FieldDefs[i].DisplayName = 'OldCaseQty') or
(cdsFile.FieldDefs[i].DisplayName = 'OldMinQty') or
(cdsFile.FieldDefs[i].DisplayName = 'CostChange')
//or (cdsFile.FieldDefs[i].DisplayName = 'Warning')
then begin
NewColumn := grdValidateModelFileTableView.CreateColumn;
with NewColumn do
begin
Caption := cdsFile.FieldDefs[i].DisplayName;
Name := 'grdValidateModelFileTableViewDB' + cdsFile.FieldDefs[i].DisplayName;
DataBinding.FieldName := cdsFile.FieldDefs[i].Name;
end;
end;
If ( Pos( UpperCase( cdsFile.FieldDefs[i].DisplayName ), 'DESCRIPTIONVENDORCODEBARCODE'+
FieldBarcode+FieldDescription+FieldVendorCode ) <= 0 )
Then cdsFile.Fields[I].Alignment := taRightJustify;
If ( Pos( UpperCase( cdsFile.FieldDefs[i].DisplayName ), 'OLDCOSTCOSTCHANGE'+
FieldNewCost+FieldCaseCost ) > 0 )
Then Begin
NewColumn.PropertiesClassName := 'TcxCurrencyEditProperties';
TcxCurrencyEditProperties( NewColumn.Properties).DisplayFormat := '0.00;0.00';
If ( cdsFile.FieldDefs[i].DisplayName = 'CostChange' ) Then Begin
NewColumn.Options.Editing := False;
End;
End;
If ( cdsFile.FieldDefs[i].DisplayName = 'OldCost' ) Then cdsFile.Fields[I].ReadOnly := True;
If ( cdsFile.FieldDefs[i].DisplayName = 'OldCaseQty' ) Then cdsFile.Fields[I].ReadOnly := True;
If ( cdsFile.FieldDefs[i].DisplayName = 'OldMinQty' ) Then cdsFile.Fields[I].ReadOnly := True;
end;
grdValidateModelFileTableView.GetColumnByFieldName( FieldBarcode ).Index := 1;
grdValidateModelFileTableView.GetColumnByFieldName( FieldBarcode ).Caption := 'BarCode';
grdValidateModelFileTableView.GetColumnByFieldName( FieldBarcode ).Width := 90;
grdValidateModelFileTableView.GetColumnByFieldName( FieldVendorCode ).Index := 2;
grdValidateModelFileTableView.GetColumnByFieldName( FieldVendorCode ).Caption := 'VendorCode';
grdValidateModelFileTableView.GetColumnByFieldName( FieldVendorCode ).Width := 90;
grdValidateModelFileTableView.GetColumnByFieldName( FieldDescription ).Index := 3;
grdValidateModelFileTableView.GetColumnByFieldName( FieldDescription ).Caption := 'Description';
grdValidateModelFileTableView.GetColumnByFieldName( FieldNewCost ).Index := 4;
grdValidateModelFileTableView.GetColumnByFieldName( FieldNewCost ).Caption := 'New Cost';
grdValidateModelFileTableView.GetColumnByFieldName( FieldNewCost ).Width := 80;
grdValidateModelFileTableView.GetColumnByFieldName( 'OldCost' ).Index := 5;
grdValidateModelFileTableView.GetColumnByFieldName( 'OldCost' ).Width := 80;
grdValidateModelFileTableView.GetColumnByFieldName( 'CostChange' ).Index := 6;
grdValidateModelFileTableView.GetColumnByFieldName( 'CostChange' ).Caption := '% Change';
grdValidateModelFileTableView.GetColumnByFieldName( 'CostChange' ).Width := 80;
grdValidateModelFileTableView.GetColumnByFieldName( FieldCaseCost ).Index := 7;
grdValidateModelFileTableView.GetColumnByFieldName( FieldCaseCost ).Caption := 'New Case Cost';
grdValidateModelFileTableView.GetColumnByFieldName( FieldCaseCost ).Width := 80;
grdValidateModelFileTableView.GetColumnByFieldName( FieldNewCaseQty ).Index := 8;
grdValidateModelFileTableView.GetColumnByFieldName( FieldNewCaseQty ).Caption := 'New Case Qty';
grdValidateModelFileTableView.GetColumnByFieldName( FieldNewCaseQty ).Width := 80;
grdValidateModelFileTableView.GetColumnByFieldName( 'OldCaseQty' ).Index := 9;
grdValidateModelFileTableView.GetColumnByFieldName( 'OldCaseQty' ).Caption := 'Old Case Qty';
grdValidateModelFileTableView.GetColumnByFieldName( 'OldCaseQty' ).Width := 80;
grdValidateModelFileTableView.GetColumnByFieldName( FieldNewMinQty ).Index := 10;
grdValidateModelFileTableView.GetColumnByFieldName( FieldNewMinQty ).Caption := 'New Min Qty';
grdValidateModelFileTableView.GetColumnByFieldName( FieldNewMinQty ).Width := 80;
grdValidateModelFileTableView.GetColumnByFieldName( 'OldMinQty' ).Index := 11;
grdValidateModelFileTableView.GetColumnByFieldName( 'OldMinQty' ).Caption := 'Old Min Qty';
grdValidateModelFileTableView.GetColumnByFieldName( 'OldMinQty' ).Width := 80;
//grdValidateModelFileTableView.GetColumnByFieldName( 'Warning' ).Index := 12;
end; { AddColumnsToValidateModelGrid }
function TWizImportVendorCatalog.SaveGridColumns: String;
var
sColumn : String;
i : integer;
begin
for i:=1 to sgColumns.RowCount-1 do
if Trim(sgColumns.Cells[0,i]) <> '' then
sColumn := sColumn + sgColumns.Cells[0,i] + '=' + sgColumns.Cells[1,i] + ';';
Result := sColumn;
end;
procedure TWizImportVendorCatalog.FilterCDSFile;
Var
sFiltro : String;
begin
If ( Trim( CbCostChange.Text ) <> '' ) Then Begin
sFiltro := 'AbsCostChange > ' + CbCostChange.Text;
End Else Begin
sFiltro := '1 = 1 ';
End;
Case TbItemsOption.TabIndex Of
0 : Begin
sFiltro := sFiltro + ' AND ChangeType = ''U''';
End;
1 : Begin
sFiltro := sFiltro + ' AND ChangeType = ''N''';
End;
2 : Begin
sFiltro := sFiltro + ' AND ChangeType = ''R''';
End;
End;
If ( Trim( sFiltro ) <> '' ) Then Begin
cdsFile.Filter := sFiltro;
cdsFile.Filtered := True;
End Else Begin
cdsFile.Filtered := False;
End;
end;
function TWizImportVendorCatalog.TestBeforeNavigate: Boolean;
begin
Result := inherited TestBeforeNavigate;
if pgOption.ActivePage.Name = 'tsSpecificConfig' then
begin
if not(VerifyFieldsRequired) then
begin
MsgBox('Field Required!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
AddSpecificConfigList('Vendor',cbVendorList.Text);
end
else if pgOption.ActivePage.Name = 'tsCrossColumn' then
begin
if (LinkedColumns.Values['Barcode'] = '') then
begin
MsgBox('Please select Barcode!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if cbxCostIncCaseCost.Checked then
AddSpecificConfigList('CostIsCaseCost','True')
else
AddSpecificConfigList('CostIsCaseCost','False');
end
else if pgOption.ActivePage.Name = 'tsValidModel' then
begin
If ( cdsFile.State = dsEdit ) Then cdsFile.Post();
grdValidateModelFileTableView.DataController.DataSource := nil;
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
SaveGridToRegistry;
end
else if pgOption.ActivePage.Name = 'tsList' then begin
SaveGridToRegistry;
end;
end;
procedure TWizImportVendorCatalog.FormCreate(Sender: TObject);
begin
inherited;
DMImportExport.ImportConn.Connected := True;
DMImportExport.OpenUser;
DMImportExport.OpenVendor;
AddComboVendor;
end;
function TWizImportVendorCatalog.OnAfterChangePage: Boolean;
var
sError: String;
Passed: Boolean;
CrossColumns: String;
message: String;
begin
Result := inherited OnAfterChangePage;
Passed := False;
lbEditDescription.Font.color := clWindowText;
if pgOption.ActivePage.Name = 'tsDatabase' then
begin
cdsFile.First();
end
else if pgOption.ActivePage.Name = 'tsCrossColumn' then
begin
cbColumns.Visible := False;
FillColumnsGrid;
GetConfigImport;
end
else if pgOption.ActivePage.Name = 'tsValidModel' then
begin
//amfsouza July 19, 2012
self.Caption := pgOption.ActivePage.Hint;
lbEditDescription.Font.color := clRed;
lbEditDescription.Caption :=
'The "Update Items" tab lists models already associated with this vendor. The "New Items" tab lists models that where not previously associated with this vendor.'+
'The "Removed Items" tab lists models no longer available from this vendor.';
ScreenStatusWait;
SetGridToRegistryValues(MR_BRW_REG_PATH + 'MRImportExport\ImpPO\Vendor_' + SpecificConfig.Values['Vendor']+ '_ValidateModel', grdValidateModelFile);
cdsFile.Data := (DMImportExport.ImportConn.AppServer.ValidateVCTextFile(cdsFile.Data,
LinkedColumns.Text,
SpecificConfig.Text,
LogError.Text,
Passed));
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
AddColumnsToValidateModelGrid;
FilterCDSFile;
ScreenStatusOk;
//Salva as Configurações de Importação do Fornecedor na tabela ConfigImport
CrossColumns := SaveGridColumns;
sError := DMImportExport.InsertConfigImport(TVendor(cbVendorList.Items.Objects[cbVendorList.Items.IndexOf(SpecificConfig.Values['Vendor'])]).IDVendor,
IMPORT_TYPE_VC,
CrossColumns,
cbxCostIncCaseCost.Checked);
LogError.Text := sError;
if LogError.Text <> '' then
begin
MsgBox(LogError.Text, vbCritical + vbOkOnly);
end;
end;
end;
function TWizImportVendorCatalog.DoFinish: Integer;
var
sError: String;
begin
ScreenStatusWait;
If ( cdsFile.State = dsEdit ) Then cdsFile.Post();
DMImportExport.ImportConn.AppServer.ImportVCTextFile(cdsFile.Data, LinkedColumns.Text, SpecificConfig.Text, sError);
LogError.Text := sError;
if sError <> '' then
ShowError(sError)
else
MsgBox('Import Success!', vbInformation + vbOKOnly);
ScreenStatusOK;
Result := inherited DoFinish();
end;
function TWizImportVendorCatalog.VerifyFieldsRequired: Boolean;
begin
Result := True;
if (cbVendorList.Text = '')
then Result := False;
end;
procedure TWizImportVendorCatalog.GetConfigImport;
var
sCrossColumns, sError : String;
sCaseCost : WordBool;
begin
sError := DMImportExport.GetConfigImport( TVendor(cbVendorList.Items.Objects[cbVendorList.Items.IndexOf(SpecificConfig.Values['Vendor'])]).IDVendor,
IMPORT_TYPE_VC,
sCrossColumns,
sCaseCost);
LogError.Text := sError;
if LogError.Text = '' then
begin
GetGridColumn(sCrossColumns);
cbxCostIncCaseCost.Checked := sCaseCost;
end
else
begin
MsgBox(LogError.Text, vbCritical + vbOkOnly);
end;
end;
procedure TWizImportVendorCatalog.GetGridColumn(ACrosColumn: String);
var
sColumn, sResult : String;
i : integer;
begin
sColumn := ACrosColumn;
if sColumn = '' then
Exit;
for i:=1 to sgColumns.RowCount-1 do
begin
sResult := ParseParam(sColumn, Trim(sgColumns.Cells[0,i]));
if sResult <> '' then
begin
if cbColumns.Items.IndexOf(sResult) >= 0 then
sgColumns.Cells[1,i] := sResult;
end;
sColumn := DeleteParam(sColumn, Trim(sgColumns.Cells[0,i]));
end;
end;
procedure TWizImportVendorCatalog.grdValidateModelFileTableViewCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var
bValidation : Boolean;
begin
inherited;
{
if (AViewInfo.Item.Caption = 'Warning') then
begin
bValidation := VarAsType(AViewInfo.GridRecord.Values[FIndiceColumnValidation], varBoolean);
if not bValidation then
ACanvas.Font.Color := clRed;
end;
}
end;
procedure TWizImportVendorCatalog.btnSelectAllClick(Sender: TObject);
begin
inherited;
ScreenStatusWait;
cdsFile.DisableControls();
cdsFile.First();
While ( Not cdsFile.Eof ) Do Begin
CdsFile.Edit();
CdsFile.FieldByName('UPDATE').AsInteger := btnSelectAll.Tag;
cdsFile.Post();
cdsFile.Next();
End;
If btnSelectAll.Tag = 0 Then Begin
btnSelectAll.Caption := 'Select All';
btnSelectAll.Tag := 1
End Else Begin
btnSelectAll.Caption := 'Unselect All';
btnSelectAll.Tag := 0;
End;
cdsFile.First();
cdsFile.EnableControls();
ScreenStatusOk;
end;
procedure TWizImportVendorCatalog.CbCostChangeChange(Sender: TObject);
begin
inherited;
FilterCdsFile();
end;
procedure TWizImportVendorCatalog.TbItemsOptionChange(Sender: TObject);
begin
inherited;
FilterCdsFile();
end;
procedure TWizImportVendorCatalog.CalculateCostChange(Sender: TObject);
begin
cdsFile.FieldByname( 'CostChange' ).AsFloat := cdsFile.FieldByname(LinkedColumns.Values['Cost']).AsFloat;
end;
procedure TWizImportVendorCatalog.cdsFileBeforePost(DataSet: TDataSet);
begin
inherited;
If ( ( pgOption.ActivePage.Name <> 'tsValidModel' ) And ( Trim( LinkedColumns.Values['Cost'] ) = '' ) )
Then Exit;
cdsFile.FieldByname( 'CostChange' ).AsFloat := ( ( ( cdsFile.FieldByname(LinkedColumns.Values['Cost']).AsFloat -
cdsFile.FieldByName('OldCost').AsFloat ) /
cdsFile.FieldByName('OldCost').AsFloat ) * 100 );
end;
procedure TWizImportVendorCatalog.grdValidateModelFileExit(Sender: TObject);
begin
inherited;
If ( cdsFile.State = dsEdit ) Then cdsFile.Post();
end;
end.
|
unit uNewFornecedorCode;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls,
Mask, SuperComboADO, DB, ADODB;
type
TNewFornecedorCode = class(TFrmParentAll)
btOK: TButton;
Label1: TLabel;
cmbFornecedor: TSuperComboADO;
Label2: TLabel;
edtCode: TEdit;
quVendorCode: TADOQuery;
quVendorCodeIDVendorModelCode: TIntegerField;
procedure btOKClick(Sender: TObject);
private
fIDModel : Integer;
fIDVendor : Integer;
fResultVendor : Boolean;
function ValidadeVendorCode:Boolean;
procedure InsertVendor;
public
function Start(IDModel, IDVendor:Integer):Boolean;
function NewVendor : Integer;
end;
implementation
uses uDM, uMsgBox, uMsgConstant, uDMGlobal, uSystemConst;
{$R *.dfm}
{ TNewFornecedorCode }
procedure TNewFornecedorCode.InsertVendor;
var
sSQL: String;
begin
sSQL := 'Insert VendorModelCode (IDVendorModelCode, IDPessoa, IDModel, VendorCode) VALUES ' +
'(' + IntToStr(DM.GetNextID(MR_VENDOR_MODEL_CODE)) + ',' +
cmbFornecedor.LookUpValue + ' ,' +
IntToStr(fIDModel) + ' ,' + QuotedStr(edtCode.Text) + ' )';
DM.RunSQL(sSQL);
end;
function TNewFornecedorCode.Start(IDModel, IDVendor:Integer): Boolean;
begin
fIDModel := IDModel;
fIDVendor := IDVendor;
fResultVendor := False;
if (fIDVendor <> -1) then
begin
cmbFornecedor.LookUpValue := IntToStr(fIDVendor);
cmbFornecedor.ReadOnly := True;
cmbFornecedor.Enabled := False;
end;
ShowModal;
Result := (ModalResult = mrOK);
end;
function TNewFornecedorCode.ValidadeVendorCode: Boolean;
var
HasCode: Boolean;
begin
Result := True;
if cmbFornecedor.LookUpValue = '' then
begin
MsgBox(MSG_CRT_NO_VENDOR, vbInformation + vbOkOnly);
cmbFornecedor.SetFocus;
Result := False;
Exit;
end;
if Trim(edtCode.Text) = '' then
begin
MsgBox(MSG_CRT_NO_VENDOR_CODE, vbInformation + vbOkOnly);
edtCode.SetFocus;
Result := False;
Exit;
end;
with quVendorCode do
begin
if Active then
Close;
Parameters.ParamByName('IDPessoa').Value := StrToInt(cmbFornecedor.LookUpValue);
Parameters.ParamByName('VendorCode').Value := edtCode.Text;
Parameters.ParamByName('IDModel').Value := fIDModel;
Open;
HasCode := (not IsEmpty);
Close;
end;
if HasCode then
begin
MsgBox(MSG_CRT_NO_VENDOR_CODE_EXIST, vbInformation + vbOkOnly);
Result := False;
end;
end;
procedure TNewFornecedorCode.btOKClick(Sender: TObject);
begin
inherited;
if not fResultVendor then
if ValidadeVendorCode then
InsertVendor
else
ModalResult := mrNone;
end;
function TNewFornecedorCode.NewVendor: Integer;
begin
fResultVendor := True;
Label2.Visible := False;
edtCode.Visible := False;
ShowModal;
if cmbFornecedor.LookUpValue <> '' then
Result := StrToInt(cmbFornecedor.LookUpValue)
else
Result := 0;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{
Implements a HDS Filter that generates HeightData tiles in a seperate thread.
This component is a TGLHeightDataSourceFilter, which uses a TGLHeightDataSourceThread,
to asyncronously search the HeightData cache for any queued tiles.
When found, it then prepares the queued tile in its own TGLHeightDataThread.
This allows the GUI to remain responsive, and prevents freezes when new tiles are
being prepared. Although this keeps the framerate up, it may cause holes in the
terrain to show, if the HeightDataThreads cant keep up with the TerrainRenderer's
requests for new tiles.
}
unit GLAsyncHDS;
interface
{$I GLScene.inc}
uses
System.Classes,
System.SysUtils,
GLHeightData;
type
TGLAsyncHDS = class;
TIdleEvent = procedure(Sender:TGLAsyncHDS;TilesUpdated:boolean) of object;
TNewTilePreparedEvent = procedure (Sender : TGLAsyncHDS;
HeightData : TGLHeightData) of object; //a tile was updated (called INSIDE the sub-thread?)
(* Determines if/how dirty tiles are displayed and when they are released.
When a tile is maked as dirty, a replacement is queued immediately.
However, the replacement cant be used until the HDThread has finished preparing it.
Dirty tiles can be deleted as soon as they are no longer used/displayed.
Possible states for a TUseDirtyTiles.
hdsNever : Dirty tiles get released immediately, leaving a hole in the terrain, until the replacement is hdsReady.
hdsUntilReplaced : Dirty tiles are used, until the HDThread has finished preparing the queued replacement.
hdsUntilAllReplaced : Waits until the HDSThread has finished preparing ALL queued tiles,
before allowing the renderer to switch over to the new set of tiles.
(This prevents a fading checkerbox effect.) *)
TUseDirtyTiles=(dtNever,dtUntilReplaced,dtUntilAllReplaced);
TGLAsyncHDS = class (TGLHeightDataSourceFilter)
private
FOnIdleEvent :TIdleEvent;
FOnNewTilePrepared : TNewTilePreparedEvent;
FUseDirtyTiles:TUseDirtyTiles;
FTilesUpdated:boolean;
public
//TilesUpdated:boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BeforePreparingData(HeightData : TGLHeightData); override;
procedure StartPreparingData(HeightData : TGLHeightData); override;
procedure ThreadIsIdle; override;
procedure NewTilePrepared(HeightData:TGLHeightData);
function ThreadCount:integer;
(* Wait for all running threads to finish.
Should only be called after setting Active to false,
to prevent new threads from starting. *)
procedure WaitFor(TimeOut: integer = 2000);
// procedure NotifyChange(Sender : TObject); override;
(* This function prevents the user from trying to write directly to this variable.
FTilesUpdated if NOT threadsafe and should only be reset with TilesUpdatedFlagReset. *)
function TilesUpdated:boolean; //Returns true if tiles have been updated since the flag was last reset
procedure TilesUpdatedFlagReset; //sets the TilesUpdatedFlag to false; (is ThreadSafe)
published
property OnIdle : TIdleEvent read FOnIdleEvent write FOnIdleEvent;
property OnNewTilePrepared : TNewTilePreparedEvent read FOnNewTilePrepared write FOnNewTilePrepared;
property UseDirtyTiles :TUseDirtyTiles read FUseDirtyTiles write FUseDirtyTiles;
property MaxThreads; //sets the maximum number of simultaineous threads that will prepare tiles.(>1 is rarely needed)
property Active; //set to false, to ignore new queued tiles.(Partially processed tiles will still be completed)
end;
TGLAsyncHDThread = class(TGLHeightDataThread)
public
Owner : TGLAsyncHDS;
HDS : TGLHeightDataSource;
Procedure Execute; override;
Procedure Sync;
end;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLAsyncHDS ------------------
// ------------------
constructor TGLAsyncHDS.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
MaxThreads := 1;
FUseDirtyTiles := dtNever;
FTilesUpdated := true;
end;
destructor TGLAsyncHDS.Destroy;
begin
inherited Destroy;
end;
procedure TGLAsyncHDS.BeforePreparingData(HeightData: TGLHeightData);
begin
if FUseDirtyTiles = dtNever then
begin
if HeightData.OldVersion <> nil then
begin
HeightData.OldVersion.DontUse := true;
HeightData.DontUse := false;
end;
end;
if assigned(HeightDataSource) then
HeightDataSource.BeforePreparingData(HeightData);
end;
procedure TGLAsyncHDS.StartPreparingData(HeightData: TGLHeightData);
var
HDThread: TGLAsyncHDThread;
HDS: TGLHeightDataSource;
begin
HDS := HeightDataSource;
// ---if there is no linked HDS then return an empty tile--
if not assigned(HDS) then
begin
HeightData.DataState := hdsNone;
exit;
end;
if (Active = false) then
exit;
// ---If not using threads then prepare the HD tile directly--- (everything else freezes until done)
if MaxThreads = 0 then
begin
HDS.StartPreparingData(HeightData);
if HeightData.DataState = hdsPreparing then
HeightData.DataState := hdsReady
else
HeightData.DataState := hdsNone;
end
else
begin // --MaxThreads>0 : start the thread and go back to start the next one--
HeightData.DataState := hdsPreparing; // prevent other threads from preparing this HD.
HDThread := TGLAsyncHDThread.Create(true);
HDThread.Owner := self;
HDThread.HDS := self.HeightDataSource;
HDThread.HeightData := HeightData;
HeightData.Thread := HDThread;
HDThread.FreeOnTerminate := false;
HDThread.Start;
end;
end;
procedure TGLAsyncHDS.ThreadIsIdle;
var
i: integer;
lst: TList;
HD: TGLHeightData;
begin
// ----------- dtUntilAllReplaced -------------
// Switch to the new version of ALL dirty tiles
lst := self.Data.LockList;
try
if FUseDirtyTiles = dtUntilAllReplaced then
begin
i := lst.Count;
while (i > 0) do
begin
dec(i);
HD := TGLHeightData(lst.Items[i]);
if (HD.DataState in [hdsReady, hdsNone]) and (HD.DontUse) and (HD.OldVersion <> nil) then
begin
HD.DontUse := false;
HD.OldVersion.DontUse := true;
FTilesUpdated := true;
end;
end;
end; // Until All Replaced
if assigned(FOnIdleEvent) then
FOnIdleEvent(self, FTilesUpdated);
finally
self.Data.UnlockList;
end;
// --------------------------------------------
end;
procedure TGLAsyncHDS.NewTilePrepared(HeightData: TGLHeightData);
var
HD: TGLHeightData;
begin
if assigned(HeightDataSource) then
HeightDataSource.AfterPreparingData(HeightData);
with self.Data.LockList do
begin
try
HD := HeightData;
// --------------- dtUntilReplaced -------------
// Tell terrain renderer to display the new tile
if (FUseDirtyTiles = dtUntilReplaced) and (HD.DontUse) and (HD.OldVersion <> nil) then
begin
HD.DontUse := false; // No longer ignore the new tile
HD.OldVersion.DontUse := true; // Start ignoring the old tile
end;
// ---------------------------------------------
if HD.DontUse = false then
FTilesUpdated := true;
if assigned(FOnNewTilePrepared) then
FOnNewTilePrepared(self, HeightData); // OnNewTilePrepared Event
finally
self.Data.UnlockList;
end;
end;
end;
function TGLAsyncHDS.ThreadCount: integer;
var
lst: TList;
i, TdCtr: integer;
HD: TGLHeightData;
begin
lst := self.Data.LockList;
i := 0;
TdCtr := 0;
while (i < lst.Count) and (TdCtr < self.MaxThreads) do
begin
HD := TGLHeightData(lst.Items[i]);
if HD.Thread <> nil then
Inc(TdCtr);
Inc(i);
end;
self.Data.UnlockList;
result := TdCtr;
end;
procedure TGLAsyncHDS.WaitFor(TimeOut: integer = 2000);
var
OutTime: TDateTime;
begin
Assert(not self.Active);
OutTime := now + TimeOut;
While ((now < OutTime) and (ThreadCount > 0)) do
begin
sleep(0);
end;
Assert(ThreadCount = 0);
end;
{
procedure TGLAsyncHDS.NotifyChange(Sender : TObject);
begin
TilesChanged:=true;
end;
}
function TGLAsyncHDS.TilesUpdated: boolean;
begin
result := FTilesUpdated;
end;
// Set the TilesUpdatedFlag to false. (is Threadsafe)
procedure TGLAsyncHDS.TilesUpdatedFlagReset;
begin
if not assigned(self) then
exit; // prevents AV on Application termination.
with Data.LockList do
try
FTilesUpdated := false;
finally
Data.UnlockList;
end;
end;
// -------------------HD Thread----------------
Procedure TGLAsyncHDThread.Execute;
Begin
HDS.StartPreparingData(HeightData);
HeightData.Thread := nil;
Synchronize(Sync);
end;
Procedure TGLAsyncHDThread.Sync;
begin
Owner.NewTilePrepared(HeightData);
if HeightData.DataState = hdsPreparing then
HeightData.DataState := hdsReady;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterClass(TGLAsyncHDS);
end.
|
unit uWizImportPO;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentWizImp, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxEdit, DB, cxDBData, Provider, DBClient, ImgList, StdCtrls,
ExtCtrls, Grids, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
Buttons, ComCtrls, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, Mask, DateBox;
type
TVendor = class
IDVendor: Variant;
public
constructor Create(IDPessoa : Variant);
end;
TWizImportPO = class(TParentWizImp)
gbSupplier: TGroupBox;
Label3: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
Freight: TLabel;
Label17: TLabel;
Label19: TLabel;
Label18: TLabel;
Label21: TLabel;
cbVendorList: TComboBox;
edPONumber: TEdit;
edPurchaseNumber: TEdit;
dbRecordDate: TDateBox;
dbDueDate: TDateBox;
edFreight: TEdit;
edOtherCost: TEdit;
cbxStore: TcxLookupComboBox;
cbxUser: TcxLookupComboBox;
tsList: TTabSheet;
grdListFile: TcxGrid;
grdListFileTableView: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
Label2: TLabel;
Label4: TLabel;
tsValidModel: TTabSheet;
grdValidateModelFile: TcxGrid;
grdValidateModelFileTableView: TcxGridDBTableView;
cxGridLevel2: TcxGridLevel;
grdValidateModelFileTableViewDBCategory: TcxGridDBColumn;
cbxCostIncCaseCost: TCheckBox;
Panel2: TPanel;
btnExport: TBitBtn;
Panel3: TPanel;
btnExport2: TBitBtn;
grdValidateModelFileTableViewDBSubCategory: TcxGridDBColumn;
grdValidateModelFileTableViewDBGroup: TcxGridDBColumn;
procedure sgColumnsExit(Sender: TObject);
procedure btnExportClick(Sender: TObject);
procedure btnExport2Click(Sender: TObject);
procedure tsSpecificConfigShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btBackClick(Sender: TObject);
procedure grdListFileTableViewCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
private
FIndiceColumnValidation : Integer;
procedure AddComboVendor;
procedure ClearComboVendor;
procedure AddColumnsToListGrid;
function SaveGridColumns: String;
procedure GetGridColumn(ACrosColumn : String);
procedure FilterCDSFileNewModel;
procedure AddColumnsToValidateModelGrid;
function ExistsEmptyModels: Boolean;
function ExistsEmptyCategory: Boolean;
function ExistsExactlyModel: Boolean;
function ExistsExactlyBarcodes: Boolean;
function ExistsEmptyDescriptions: Boolean;
Procedure GetConfigImport;
protected
procedure AddColumnsToImport; override;
procedure FillColumnsGrid; override;
function TestBeforeNavigate:Boolean; override;
function OnAfterChangePage:Boolean; override;
function VerifyFieldsRequired: Boolean;
function AddSpecificFieldsToCDS(Position : Integer): Integer; override;
procedure AddSpecificFriendFieldsToCDS(Position : Integer); override;
procedure OnBeforeBackClick; override;
end;
implementation
uses uMsgBox, uDMGlobalNTier, uParamFunctions, uDMImportExport, uNumericFunctions, uSystemConst,
uParentWizard, uCDSFunctions, uDMGlobal;
{$R *.dfm}
{ TWizImportPO }
function TWizImportPO.OnAfterChangePage: Boolean;
var
sError: String;
Passed: Boolean;
CrossColumns: String;
begin
Result := inherited OnAfterChangePage;
Passed := False;
if pgOption.ActivePage.Name = 'tsCrossColumn' then
begin
cbColumns.Visible := False;
FillColumnsGrid;
GetConfigImport;
//GetGridColumn;
//cbxCostIncCaseCost.Checked := (DMImportExport.GetAppProperty('CaseCostOption', SpecificConfig.Values['Vendor']) = 'True');
end
else if pgOption.ActivePage.Name = 'tsSpecificConfig' then
begin
DMImportExport.ImportConn.Connected := True;
DMImportExport.OpenStore;
DMImportExport.OpenUser;
DMImportExport.OpenVendor;
dbRecordDate.Date := Now;
dbDueDate.Date := Now + 7;
AddComboVendor;
end
else if pgOption.ActivePage.Name = 'tsValidModel' then
begin
ScreenStatusWait;
SetGridToRegistryValues(MR_BRW_REG_PATH + 'MRImportExport\ImpPO\Vendor_' + SpecificConfig.Values['Vendor']+ '_ValidateModel', grdValidateModelFile);
DMImportExport.OpenCategory;
DMImportExport.OpenSubCategory;
DMImportExport.OpenGroup;
cdsFile.Data := (DMImportExport.ImportConn.AppServer.ValidateModelsPOTextFile(cdsFile.Data,
LinkedColumns.Text, SpecificConfig.Text, LogError.Text, Passed));
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
AddColumnsToValidateModelGrid;
FilterCDSFileNewModel;
RestoreGridFromRegistry;
ScreenStatusOk;
//Salva as Confiurações de Importação do Fornecedor na tabela ConfigImport
CrossColumns := SaveGridColumns;
sError := DMImportExport.InsertConfigImport(
TVendor(cbVendorList.Items.Objects[cbVendorList.Items.IndexOf(SpecificConfig.Values['Vendor'])]).IDVendor,
IMPORT_TYPE_PO,
CrossColumns,
cbxCostIncCaseCost.Checked);
LogError.Text := sError;
if LogError.Text <> '' then
begin
MsgBox(LogError.Text, vbCritical + vbOkOnly);
end;
{
if cbxCostIncCaseCost.Checked then
DMImportExport.SetAppProperty('CaseCostOption', SpecificConfig.Values['Vendor'], 'True')
else
DMImportExport.SetAppProperty('CaseCostOption', SpecificConfig.Values['Vendor'], 'False');
}
end
else if pgOption.ActivePage.Name = 'tsList' then
begin
ScreenStatusWait;
SetGridToRegistryValues(MR_BRW_REG_PATH + 'MRImportExport\ImpPO\Vendor_' + SpecificConfig.Values['Vendor'] + '_List', grdListFile);
cdsFile.Filtered := False;
cdsFile.Filter := '';
cdsFile.Data := (DMImportExport.ImportConn.AppServer.ValidatePOTextFile(cdsFile.Data,
LinkedColumns.Text,SpecificConfig.Text,LogError.Text,Passed));
grdListFileTableView.DataController.DataSource := dtsFile;
AddColumnsToListGrid;
RestoreGridFromRegistry;
ScreenStatusOk;
end
else if pgOption.ActivePage.Name = 'tsImport' then
begin
ScreenStatusWait;
DMImportExport.ImportConn.AppServer.ImportPOTextFile(cdsFile.Data,
LinkedColumns.Text, SpecificConfig.Text, sError);
LogError.Text := sError;
if sError <> '' then
ShowError(sError)
else
MsgBox('Import Success!', vbInformation + vbOKOnly);
ScreenStatusOK;
end;
end;
function TWizImportPO.TestBeforeNavigate: Boolean;
begin
Result := inherited TestBeforeNavigate;
if pgOption.ActivePage.Name = 'tsSpecificConfig' then
begin
if not(VerifyFieldsRequired) then
begin
MsgBox('Field Required!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if (edPurchaseNumber.Text <> '') then
if not(DMImportExport.ImportConn.AppServer.ValidatePurchaseNum(edPurchaseNumber.Text,cbVendorList.Text)) then
begin
MsgBox('Purchase number already exists!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if (edPONumber.Text <> '') then
if not(DMImportExport.ImportConn.AppServer.ExistsPONum(edPONumber.Text)) then
begin
MsgBox('PO does not exist!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
AddSpecificConfigList('PONumber',edPONumber.Text);
AddSpecificConfigList('Store',cbxStore.EditValue);
AddSpecificConfigList('User',cbxUser.EditValue);
AddSpecificConfigList('Vendor',cbVendorList.Text);
AddSpecificConfigList('Purchase_Number',edPurchaseNumber.Text);
AddSpecificConfigList('Freight',edFreight.Text);
AddSpecificConfigList('OtherCost',edOtherCost.Text);
//AddSpecificConfigList('IDUser', IntToStr(DMImportExport.FUser.ID));
if dbRecordDate.Text = '' then
AddSpecificConfigList('RecordDate','')
else
AddSpecificConfigList('RecordDate',DatetoStr(dbRecordDate.Date));
if dbDueDate.Text = '' then
AddSpecificConfigList('DueDate','')
else
AddSpecificConfigList('DueDate',DatetoStr(dbDueDate.Date));
end
else if pgOption.ActivePage.Name = 'tsValidModel' then
begin
grdValidateModelFileTableView.DataController.DataSource := nil;
if ExistsEmptyModels then
begin
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
MsgBox('Model can not be empty!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if ExistsEmptyDescriptions then
begin
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
MsgBox('Description can not be empty!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if ExistsEmptyCategory then
begin
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
MsgBox('Category can not be empty!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if ExistsExactlyBarcodes then
begin
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
MsgBox('Barcode already exists!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if ExistsExactlyModel then
begin
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
MsgBox('Model already exists!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
SaveGridToRegistry;
end
else if pgOption.ActivePage.Name = 'tsCrossColumn' then
begin
if (LinkedColumns.Values['Barcode'] = '') then
begin
MsgBox('Please select Barcode!_Required fields: Barcode, Qty, NewCostPrice.', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if (LinkedColumns.Values['Qty'] = '') then
begin
MsgBox('Please select Qty!_Required fields: Barcode, Qty, NewCostPrice.', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if (LinkedColumns.Values['NewCostPrice'] = '') then
begin
MsgBox('Please select New Cost Price!_Required fields: Barcode, Qty, NewCostPrice.', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
if cbxCostIncCaseCost.Checked then
AddSpecificConfigList('CostIsCaseCost','True')
else
AddSpecificConfigList('CostIsCaseCost','False');
end
else if pgOption.ActivePage.Name = 'tsList' then
SaveGridToRegistry;
end;
function TWizImportPO.ExistsEmptyModels: Boolean;
begin
Result := False;
with cdsFile do
begin
First;
while not Eof do
begin
if cdsFile.FieldByName('Model').AsString = '' then
begin
Result := True;
break;
end;
Next;
end;
end;
end;
function TWizImportPO.ExistsEmptyDescriptions: Boolean;
begin
Result := False;
with cdsFile do
begin
First;
while not Eof do
begin
if cdsFile.FieldByName('Description').AsString = '' then
begin
Result := True;
break;
end;
Next;
end;
end;
end;
function TWizImportPO.ExistsExactlyBarcodes: Boolean;
var
cdsSupport: TClientDataSet;
begin
Result := False;
cdsSupport := TClientDataSet.Create(self);
try
cdsSupport.CloneCursor(cdsFile,true);
with cdsFile do
begin
First;
while not Eof do
begin
cdsSupport.Filter := LinkedColumns.Values['Barcode'] + ' = ' + QuotedStr(cdsFile.FieldByName(LinkedColumns.Values['Barcode']).AsString);
cdsSupport.Filtered := True;
if cdsSupport.RecordCount > 1 then
begin
Result := True;
break;
end;
cdsSupport.Filter := '';
cdsSupport.Filtered := False;
Next;
end;
end;
finally
FreeAndNil(cdsSupport);
end;
end;
function TWizImportPO.ExistsExactlyModel: Boolean;
var
cdsSupport: TClientDataSet;
begin
Result := False;
cdsSupport := TClientDataSet.Create(self);
try
cdsSupport.CloneCursor(cdsFile,true);
with cdsFile do
begin
First;
while not Eof do
begin
cdsSupport.Filter := 'Model = ' + QuotedStr(cdsFile.FieldByName('Model').AsString);
cdsSupport.Filtered := True;
if cdsSupport.RecordCount > 1 then
begin
Result := True;
break;
end;
cdsSupport.Filter := '';
cdsSupport.Filtered := False;
Next;
end;
end;
finally
FreeAndNil(cdsSupport);
end;
end;
function TWizImportPO.ExistsEmptyCategory: Boolean;
begin
Result := False;
with cdsFile do
begin
First;
while not Eof do
begin
if (cdsFile.FieldByName('IDGroup').AsString = '') OR
(cdsFile.FieldByName('IDGroup').AsInteger = 0) then
begin
Result := True;
break;
end;
Next;
end;
end;
end;
function TWizImportPO.VerifyFieldsRequired: Boolean;
begin
Result := True;
if (cbxStore.EditingText = '') or (cbxUser.EditingText = '') or
(cbVendorList.Text = '') or
(dbRecordDate.Text = '') or (dbDueDate.Text = '') then
Result := False;
end;
procedure TWizImportPO.AddColumnsToImport;
begin
sgColumns.Cells[0,1] := 'BarCode';
sgColumns.Cells[0,2] := 'VendorCode';
sgColumns.Cells[0,3] := 'Qty';
sgColumns.Cells[0,4] := 'NewCostPrice';
sgColumns.Cells[0,5] := 'FreightCost';
sgColumns.Cells[0,6] := 'OtherCost';
sgColumns.Cells[0,7] := 'Description';
sgColumns.Cells[0,8] := 'CaseQty';
sgColumns.Cells[0,9] := 'CaseCost';
sgColumns.Cells[0,10] := 'MinQty';
sgColumns.Cells[0,11] := 'PromoFlag';
sgColumns.RowCount := 12;
end;
procedure TWizImportPO.FillColumnsGrid;
begin
sgColumns.Cells[0,0] := 'Main Retail';
sgColumns.Cells[1,0] := 'File PO';
AddColumnsToImport;
AddComboColumnsToImport;
end;
procedure TWizImportPO.AddComboVendor;
begin
//Limpar os Obetos Tvendor da Combo
ClearComboVendor;
DMImportExport.cdsLookupVendor.First;
while not DMImportExport.cdsLookupVendor.Eof do
begin
//cbVendorList.Items.Add(DMImportExport.cdsLookupVendor.Fields.FieldByName('Vendor').AsString);
cbVendorList.Items.AddObject(DMImportExport.cdsLookupVendor.Fields.FieldByName('Vendor').AsString,
TVendor.Create(DMImportExport.cdsLookupVendor.Fields.FieldByName('IDVendor').AsVariant));
DMImportExport.cdsLookupVendor.Next;
end;
end;
procedure TWizImportPO.AddColumnsToValidateModelGrid;
var
i: Integer;
NewColumn: TcxGridDBColumn;
FieldBarcode, FieldDescription: String;
begin
if (LinkedColumns.Values['Barcode'] <> '') then
begin
FieldBarcode := cdsFile.FieldByName(LinkedColumns.Values['Barcode']).FieldName;
cdsFile.FieldByName(FieldBarcode).ReadOnly := True;
end;
if (LinkedColumns.Values['Description'] <> '') then
begin
FieldDescription := cdsFile.FieldByName(LinkedColumns.Values['Description']).FieldName;
cdsFile.FieldByName(FieldDescription).ReadOnly := False;
end;
i := 0;
while grdValidateModelFileTableView.ColumnCount > 3 do
if (grdValidateModelFileTableView.Columns[i].Caption <> 'Category') and
(grdValidateModelFileTableView.Columns[i].Caption <> 'SubCategory') and
(grdValidateModelFileTableView.Columns[i].Caption <> 'Group') then
begin
grdValidateModelFileTableView.Columns[i].DataBinding.FieldName := '';
grdValidateModelFileTableView.Columns[i].Free;
end
else
inc(i);
for i := 0 to Pred(cdsFile.FieldDefs.Count) do
if (cdsFile.FieldDefs[i].DisplayName = FieldBarcode) or
(cdsFile.FieldDefs[i].DisplayName = FieldDescription) or
(cdsFile.FieldDefs[i].DisplayName = 'Description') or
(cdsFile.FieldDefs[i].DisplayName = 'Model') or
(cdsFile.FieldDefs[i].DisplayName = 'Warning') or
(cdsFile.FieldDefs[i].DisplayName = 'OldCostPrice') then
begin
NewColumn := grdValidateModelFileTableView.CreateColumn;
with NewColumn do
begin
Caption := cdsFile.FieldDefs[i].DisplayName;
Name := 'grdValidateModelFileTableViewDB' + cdsFile.FieldDefs[i].DisplayName;
DataBinding.FieldName := cdsFile.FieldDefs[i].Name;
end;
end;
for i := 0 to grdValidateModelFileTableView.ColumnCount - 1 do
begin
if grdValidateModelFileTableView.Columns[i].Caption = FieldBarcode then
grdValidateModelFileTableView.Columns[i].Index := 0;
if grdValidateModelFileTableView.Columns[i].Caption = 'Model' then
grdValidateModelFileTableView.Columns[i].Index := 1;
if (grdValidateModelFileTableView.Columns[i].Caption = FieldDescription) or
(grdValidateModelFileTableView.Columns[i].Caption = 'Description') then
grdValidateModelFileTableView.Columns[i].Index := 2;
if grdValidateModelFileTableView.Columns[i].Caption = 'Category' then
grdValidateModelFileTableView.Columns[i].Index := 3;
if grdValidateModelFileTableView.Columns[i].Caption = 'SubCategory' then
grdValidateModelFileTableView.Columns[i].Index := 4;
if grdValidateModelFileTableView.Columns[i].Caption = 'Group' then
grdValidateModelFileTableView.Columns[i].Index := 5;
if grdValidateModelFileTableView.Columns[i].Caption = 'OldCostPrice' then
begin
grdValidateModelFileTableView.Columns[i].Caption := 'CostPrice';
grdValidateModelFileTableView.Columns[i].Index := 6;
end;
if grdValidateModelFileTableView.Columns[i].Caption = 'Warning' then
grdValidateModelFileTableView.Columns[i].Index := 7;
end;
end;
procedure TWizImportPO.AddColumnsToListGrid;
var
i: Integer;
NewColumn: TcxGridDBColumn;
sDisplayName: String;
begin
grdListFileTableView.ClearItems;
cdsFile.FieldByName('NewSalePrice').ReadOnly := False;
for i := 0 to (iValidateColumns - 1) do
begin
if (cdsFile.FieldDefs[i].DisplayName <> 'OldCostPrice') and
(cdsFile.FieldDefs[i].DisplayName <> 'FieldCostCalc') then
begin
NewColumn := grdListFileTableView.CreateColumn;
with NewColumn do
begin
sDisplayName := StringReplace(cdsFile.FieldDefs[i].DisplayName, '.', '', [rfReplaceAll]);
sDisplayName := StringReplace(sDisplayName, ',', '', [rfReplaceAll]);
sDisplayName := StringReplace(sDisplayName, ';', '', [rfReplaceAll]);
Caption := sDisplayName;
Name := 'grdListFileTableView' + sDisplayName;
DataBinding.FieldName := StringReplace(cdsFile.FieldDefs[i].Name, '.', '',[rfReplaceAll]);
if NewColumn.Caption <> 'NewSalePrice' then
begin
NewColumn.Options.Editing := False;
NewColumn.Editing := False;
NewColumn.Width := GetColumnWidth(cdsFile.FieldDefs[i].DataType);
end;
if cdsFile.FieldDefs[i].Name = 'Warning' then
begin
NewColumn.IsPreview := True;
//NewColumn.Properties.
grdListFileTableView.Preview.Column := NewColumn;
end;
if cdsFile.FieldDefs[i].Name = 'Validation' then
FIndiceColumnValidation := NewColumn.Index;
end;
end;
end;
end;
procedure TWizImportPO.sgColumnsExit(Sender: TObject);
begin
inherited;
// SaveGridColumns;
end;
function TWizImportPO.SaveGridColumns: String;
var
sColumn : String;
i : integer;
begin
for i:=1 to sgColumns.RowCount-1 do
if Trim(sgColumns.Cells[0,i]) <> '' then
//if Pos(Trim(sgColumns.Cells[1,i]), sColumn) = 0 then
sColumn := sColumn + sgColumns.Cells[0,i] + '=' + sgColumns.Cells[1,i] + ';';
Result := sColumn;
// if sColumn = '' then
// Exit;
//DMImportExport.SetAppProperty('ColumnImportPOSetup', SpecificConfig.Values['Vendor'], sColumn);
end;
procedure TWizImportPO.GetGridColumn(ACrosColumn : String);
var
sColumn, sResult : String;
i : integer;
begin
//sColumn := DMImportExport.GetAppProperty('ColumnImportPOSetup', SpecificConfig.Values['Vendor']);
sColumn := ACrosColumn;
if sColumn = '' then
Exit;
for i:=1 to sgColumns.RowCount-1 do
begin
sResult := ParseParam(sColumn, Trim(sgColumns.Cells[0,i]));
if sResult <> '' then
begin
if cbColumns.Items.IndexOf(sResult) >= 0 then
sgColumns.Cells[1,i] := sResult;
end;
sColumn := DeleteParam(sColumn, Trim(sgColumns.Cells[0,i]));
end;
end;
function TWizImportPO.AddSpecificFieldsToCDS(Position: Integer): Integer;
begin
CreateCDSField(cdsFile, 'OldSalePrice', ftCurrency, Position+1, True);
CreateCDSField(cdsFile, 'NewSalePrice', ftCurrency, Position+2, True);
CreateCDSField(cdsFile, 'OldCostPrice', ftCurrency, Position+3, True);
CreateCDSField(cdsFile, 'QtyType', ftString, Position+4, True);
CreateCDSField(cdsFile, 'NewMSRP', ftCurrency, Position+5, True);
CreateCDSField(cdsFile, 'FieldCostCalc', ftString, Position+6, True);
Result := Position + 6;
end;
procedure TWizImportPO.AddSpecificFriendFieldsToCDS(Position: Integer);
begin
CreateCDSField(cdsFile, 'IDGroup', ftInteger, Position+1, True);
CreateCDSField(cdsFile, 'IDModel', ftInteger, Position+2, True);
CreateCDSField(cdsFile, 'IDModelGroup', ftInteger, Position+3, True);
CreateCDSField(cdsFile, 'IDModelSubGroup', ftInteger, Position+4, True);
CreateCDSField(cdsFile, 'CaseQty', ftCurrency, Position+5, True);
CreateCDSField(cdsFile, 'CaseCost', ftCurrency, Position+6, True);
CreateCDSField(cdsFile, 'Model', ftString, Position+7, True);
CreateCDSField(cdsFile, 'NewModel', ftBoolean, Position+8, True);
CreateCDSField(cdsFile, 'Description', ftString, Position+9, True, 50);
CreateCDSField(cdsFile, 'VendorModelCode', ftString, Position+10, True, 20);
CreateCDSField(cdsFile, 'MinQtyPO', ftFloat, Position+11, True);
CreateCDSField(cdsFile, 'VendorCaseQty', ftFloat, Position+12, True);
end;
procedure TWizImportPO.FilterCDSFileNewModel;
begin
cdsFile.Filter := 'Validation = True and NewModel = True';
cdsFile.Filtered := true;
end;
procedure TWizImportPO.OnBeforeBackClick;
begin
inherited;
if pgOption.ActivePage.Name = 'tsList' then
begin
ScreenStatusWait;
grdValidateModelFileTableView.DataController.DataSource := nil;
cdsFile.Filtered := false;
cdsFile.Filter := 'NewModel = True and Model <> '''' ';
cdsFile.Filtered := true;
grdValidateModelFileTableView.DataController.DataSource := dtsFile;
ScreenStatusOk;
end
end;
procedure TWizImportPO.btnExportClick(Sender: TObject);
begin
ExportGridToExcel(grdValidateModelFile);
end;
procedure TWizImportPO.btnExport2Click(Sender: TObject);
begin
inherited;
ExportGridToExcel(grdListFile);
end;
procedure TWizImportPO.tsSpecificConfigShow(Sender: TObject);
begin
inherited;
cbxUser.EditValue := DMImportExport.FUser.ID;
cbxStore.EditValue := DMImportExport.IDDefaulStore;
end;
procedure TWizImportPO.ClearComboVendor;
var
Vendor : TVendor;
begin
while cbVendorList.Items.Count > 0 do
begin
Vendor := TVendor(cbVendorList.Items.Objects[0]);
FreeAndNil(Vendor);
cbVendorList.Items.Delete(0);
end;
cbVendorList.Clear;
end;
Procedure TWizImportPO.GetConfigImport;
var
sCrossColumns, sError : String;
sCaseCost : WordBool;
begin
sError := DMImportExport.GetConfigImport(
TVendor(cbVendorList.Items.Objects[cbVendorList.Items.IndexOf(SpecificConfig.Values['Vendor'])]).IDVendor,
IMPORT_TYPE_PO,
sCrossColumns,
sCaseCost);
LogError.Text := sError;
if LogError.Text = '' then
begin
GetGridColumn(sCrossColumns);
cbxCostIncCaseCost.Checked := sCaseCost;
end
else
begin
MsgBox(LogError.Text, vbCritical + vbOkOnly);
end;
end;
{ TVendor }
constructor TVendor.Create(IDPessoa : Variant);
begin
IDVendor := IDPessoa;
end;
procedure TWizImportPO.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
//Limpar os Obetos Tvendor da Combo
ClearComboVendor;
end;
procedure TWizImportPO.btBackClick(Sender: TObject);
begin
if pgOption.ActivePage.Name = 'tsValidModel' then
begin
if MsgBox('Warning: Going back to the configuration screen will result in the loss of changes made to this PO.', vbQuestion + vbOKCancel) = vbCancel then
Exit;
end;
inherited;
end;
procedure TWizImportPO.grdListFileTableViewCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var
bValidation : Boolean;
begin
inherited;
if (AViewInfo.Item.Caption = 'Warning') then
begin
bValidation := VarAsType(AViewInfo.GridRecord.Values[FIndiceColumnValidation], varBoolean);
if not bValidation then
ACanvas.Font.Color := clRed;
end;
end;
end.
|
program convert;
var b7,b6,b5,b4,b3,b2,b1,b0: Boolean;
var d : integer;
(*procedure mit call by reference*)
procedure Convert2Binary(d : Integer; var b7,b6,b5,b4,b3,b2,b1,b0: Boolean );
var count : Integer;
var result : Boolean;
begin
count := 0;
while d > 0 do
begin
if d mod 2 > 0 then
result := True
else
result := False;
(*b7 bis b1 auf True oder False setzen*)
case count of
0: b0 := result;
1: b1 := result;
2: b2 := result;
3: b3 := result;
4: b4 := result;
5: b5 := result;
6: b6 := result;
7: b7 := result;
end;
(*Zahl verkleinern für die nächste Iteration*)
d := d DIV 2;
count := count +1;
end;
end;
begin
WriteLn('-- Convert2Binary --');
Write('Zahl: ');
Read(d);
if(d <= 255) and (d >= 0) then begin
Convert2Binary(d,b7,b6,b5,b4,b3,b2,b1,b0);
WriteLn('Dezimal: ',d,' Binaer: ',b7,' ',b6,' ',b5,' ',b4,' ',b3,' ',b2,' ',b1,' ',b0,' ');
end
else
WriteLn('Falsche Eingabe');
end. |
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvUtil, Vcl.ExtCtrls, Vcl.Grids, AdvObj, BaseGrid, AdvGrid,
DBAdvGrid, Modules.Data, Data.DB, Vcl.StdCtrls, VCL.TMSFNCCustomComponent, VCL.TMSFNCCloudBase,
VCL.TMSFNCGeocoding, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics,
VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser,
VCL.TMSFNCMaps, Vcl.ComCtrls, 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, FireDAC.Comp.Client, AdvCombo, AdvStyleIF, AdvAppStyler,
Modules.Resources, AdvGlowButton, AdvToolBar;
type
TFrmMain = class(TForm)
Map: TTMSFNCMaps;
AdvFormStyler1: TAdvFormStyler;
Geocoder: TTMSFNCGeocoding;
AdvDockPanel1: TAdvDockPanel;
AdvToolBar1: TAdvToolBar;
btnGeocode: TAdvGlowButton;
btnSelectState: TAdvGlowButton;
btnAbout: TAdvGlowButton;
AdvToolBarSeparator1: TAdvToolBarSeparator;
AdvToolBarSeparator2: TAdvToolBarSeparator;
procedure FormCreate(Sender: TObject);
procedure MapPolyElementClick(Sender: TObject; AEventData: TTMSFNCMapsEventData);
procedure GeocoderRequestsComplete(Sender: TObject);
procedure btnAboutClick(Sender: TObject);
procedure btnSelectStateClick(Sender: TObject);
procedure btnGeocodeClick(Sender: TObject);
private
{ Private declarations }
FCurrentState : String;
procedure StartGeocoding( AState, ACounty: String );
procedure Calculate;
procedure ShowData( AState: String );
procedure ShowDetails( AId: Integer );
procedure UpdateProgress;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses Flix.Utils.Maps,
IOUtils,
Threading,
Forms.Details,
Forms.Progress,
Forms.SelectState,
Forms.About;
procedure TFrmMain.btnAboutClick(Sender: TObject);
var
LFrm: TFrmAbout;
begin
LFrm := TFrmAbout.Create(nil);
try
LFrm.ShowModal;
finally
LFrm.Free;
end;
end;
procedure TFrmMain.btnGeocodeClick(Sender: TObject);
begin
Calculate;
end;
procedure TFrmMain.btnSelectStateClick(Sender: TObject);
var
LFrm: TFrmSelectState;
LState : String;
begin
LFrm := TFrmSelectState.Create(nil);
try
LState := LFrm.SelectState( FCurrentState );
if LState <> '' then
begin
FCurrentState := LState;
ShowData(LState);
end;
finally
LFrm.Free;
end;
end;
procedure TFrmMain.Calculate;
var
LCounties: TStringlist;
LQuCounties: TDataSet;
LQuCoords : TDataSet;
LState,
LCounty: String;
i: Integer;
LSplits: TArray<string>;
begin
LCounties := TStringlist.Create;
try
LQuCounties := DBController.QuCounties;
LQuCoords := DBController.QuCoordinates;
LQuCoords.DisableControls;
LQuCounties.DisableControls;
LQuCoords.Open;
try
LQuCounties.First;
while not LQuCounties.Eof do
begin
LState := LQuCounties.FieldByName('State').AsString;
LCounty := LQuCounties.FieldByName('County').AsString;
if LCounty.ToLower <> 'unknown' then
begin
// find county in coordinates
if not LQuCoords.Locate( 'State;County',
VarArrayOf( [LState, LCounty] ), [] ) then
begin
// not found, add to list
LCounties.Add( LState + '|' + LCounty );
end;
end;
LQuCounties.Next;
end;
finally
LQuCoords.EnableControls;
LQuCounties.EnableControls;
end;
LQuCoords.Close;
if LCounties.Count > 0 then
begin
if MessageDlg( Format( '%d counties need to be updated.' +
'Do you want to continue?',
[ LCounties.Count ] ), mtConfirmation, [mbYes,mbNo], 0 ) = mrYes then
begin
FrmProgress.Start( 'Geocoding counties...', LCounties.Count);
// issue geocoding for all items in list
for i := 0 to LCounties.Count -1 do
begin
LSplits := LCounties[i].Split(['|']);
LState := LSplits[0];
LCounty := LSplits[1];
StartGeocoding( LState, LCounty );
end;
end;
end
else
begin
MessageDlg( 'No updates needed.', mtInformation, [mbOK], 0 );
end;
finally
LCounties.Free;
end;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
var LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) );
try
Geocoder.APIKey := LKeys.GetKey( msGoogleMaps );
Map.APIKey := LKeys.GetKey( msGoogleMaps );
finally
LKeys.Free;
end;
end;
procedure TFrmMain.GeocoderRequestsComplete(Sender: TObject);
begin
FrmProgress.Close;
end;
procedure TFrmMain.MapPolyElementClick(Sender: TObject; AEventData: TTMSFNCMapsEventData);
begin
ShowDetails( AEventData.PolyElement.DataInteger );
end;
procedure TFrmMain.ShowData(AState: String);
var
LQuery: TFDQuery;
LQuNumbers: TFDQuery;
begin
LQuery := TFDQuery.Create(nil);
LQuNumbers := TFDQuery.Create( nil );
Map.BeginUpdate;
try
// select numbers for state and county
LQuNumbers.Connection := DBController.Connection;
LQuNumbers.SQL.Text := 'SELECT * FROM counties WHERE state = :state ' +
'AND county = :county ORDER BY date DESC LIMIT 1';
// get coordinates for all counties
LQuery.Connection := DBController.Connection;
LQuery.SQL.Text := 'SELECT * FROM coordinates where state = :state';
LQuery.ParamByName('state').AsString := AState;
LQuery.Open;
// remove all map annotations
Map.Clear;
while not LQuery.Eof do
begin
// set parameters
LQuNumbers.ParamByName('state').AsString := LQuery['state'];
LQuNumbers.ParamByName('county').AsString := LQuery['county'];
LQuNumbers.Open;
// add circle with radius depending on number of cases
var LCircle := Map.AddCircle(
CreateCoordinate( LQuery['Lat'], LQuery['Lon'] ),
LQuNumbers['cases'] * 2
);
// adjust style of circle
LCircle.FillColor := clNavy;
LCircle.FillOpacity := 0.3;
LCircle.StrokeColor := clBlue;
LCircle.StrokeOpacity := 0.5;
LCircle.StrokeWidth := 1;
// link record id to circle
LCircle.DataInteger := LQuery['Id'];
LQuNumbers.Close;
LQuery.Next;
end;
// zoom to area that shows all counties
Map.ZoomToBounds( Map.Circles.ToCoordinateArray );
finally
LQuNumbers.Free;
LQuery.Free;
Map.EndUpdate;
end;
end;
procedure TFrmMain.ShowDetails(AId: Integer);
var
LFrm : TFrmDetail;
begin
LFrm := TFrmDetail.Create(self);
LFrm.CoordId := AId;
LFrm.Show;
end;
procedure TFrmMain.StartGeocoding(AState, ACounty: String);
begin
Geocoder.GetGeocoding( ACounty + ' County,' + AState + ',USA',
procedure (const ARequest: TTMSFNCGeocodingRequest;
const ARequestResult: TTMSFNCCloudBaseRequestResult)
var
i : Integer;
LItem: TTMSFNCGeocodingItem;
LSplits: TArray<string>;
LState: String;
LCounty: String;
LCoord: TTMSFNCMapsCoordinateRec;
LQuery : TFDQuery;
begin
UpdateProgress;
if ARequestResult.Success then
begin
LQuery := TFDQuery.Create(nil);
LQuery.Connection := DBController.Connection;
if ARequest.Items.Count > 0 then
begin
LItem := ARequest.Items[0];
LSplits := ARequest.ID.Split(['|']);
LState := LSplits[0];
LCounty := LSplits[1];
LCoord := LItem.Coordinate.ToRec;
LQuery.SQL.Text := 'INSERT INTO coordinates ( State, County, Lat, Lon ) ' +
'VALUES ( :State, :County, :Lat, :Lon )';
LQuery.ParamByName('State').AsString := LState;
LQuery.ParamByName('County').AsString := LCounty;
LQuery.ParamByName('Lat').AsFloat := LCoord.Latitude;
LQuery.ParamByName('Lon').AsFloat := LCoord.Longitude;
LQuery.ExecSQL;
end;
end;
end,
AState + '|' + ACounty
);
end;
procedure TFrmMain.UpdateProgress;
begin
TThread.Synchronize( nil,
procedure
begin
FrmProgress.UpdateProgress( Geocoder.RunningRequests.Count );
end);
end;
end.
|
program Cradle;
const TAB = ^I;
var Look: char;
procedure GetChar;
begin
Read(Look);
end;
procedure Error(s: string);
begin
writeln;
writeln(^G, 'Error: ', s, '.');
end;
procedure Abort(s: string);
begin
Error(s);
Halt;
end;
procedure Expected(s: string);
begin
Abort(s + 'Expected');
end;
procedure Match(x: char);
begin
if Look = x then GetChar
else Expected('''' + x + '''');
end;
function IsAlpha(c: char): boolean;
begin
IsAlpha := upcase(c) in ['A'..'Z'];
end;
function IsDigit(c: char): boolean;
begin
IsDigit := c in ['0'..'9'];
end;
function GetName: char;
begin
if not IsAlpha(Look) then Expected('Name');
GetName := upcase(Look);
GetChar;
end;
function GetNum: char;
begin
if not IsDigit(Look) then Expected('Integer');
GetNum := Look;
GetChar;
end;
procedure Emit(s: string);
begin
write(TAB, s);
end;
procedure EmitLn(s: string);
begin
Emit(s);
writeln;
end;
procedure Init;
begin
GetChar;
end;
procedure Term;
begin
EmitLn('Move # ' + GetNum + ',D0');
end;
procedure Add;
begin
Match('+');
Term;
EmitLn('ADD D1, D0');
end;
procedure Subtract;
begin
Match('-');
Term;
EmitLn('SUB D1, D0');
end;
procedure Expression;
begin
Term;
EmitLn('Move D0, D1');
case Look of
'+': Add;
'-': Subtract;
else Expected('Addop');
end;
end;
begin
Init;
Expression;
end.
|
unit GLDRenderOptionsForm;
interface
uses
Windows, SysUtils, Classes, Controls, Forms,
Dialogs, StdCtrls, Buttons, GL, GLDTypes;
type
TGLDRenderOptionsForm = class(TForm)
GB_RenderMode: TGroupBox;
RB_Smooth: TRadioButton;
CB_DrawEdges: TCheckBox;
RB_Wireframe: TRadioButton;
RB_BoundingBox: TRadioButton;
GB_Lighting: TGroupBox;
CB_EnableLighting: TCheckBox;
CB_TwoSidedLighting: TCheckBox;
GB_CullFace: TGroupBox;
CB_CullFacing: TCheckBox;
L_CullFace: TLabel;
CB_CullFace: TComboBox;
BB_Ok: TBitBtn;
BB_Cancel: TBitBtn;
procedure RB_Click(Sender: TObject);
procedure BB_Click(Sender: TObject);
private
function GetParams: TGLDSystemRenderOptionsParams;
procedure SetParams(Value: TGLDSystemRenderOptionsParams);
public
property Params: TGLDSystemRenderOptionsParams read GetParams write SetParams;
end;
function GLDGetRenderOptionsForm: TGLDRenderOptionsForm;
procedure GLDReleaseRenderOptionsForm;
implementation
{$R *.dfm}
uses
GLDX;
var
vRenderOptionsForm: TGLDRenderOptionsForm = nil;
function GLDGetRenderOptionsForm: TGLDRenderOptionsForm;
begin
if not Assigned(vRenderOptionsForm) then
vRenderOptionsForm := TGLDRenderOptionsForm.Create(nil);
Result := vRenderOptionsForm;
end;
procedure GLDReleaseRenderOptionsForm;
begin
if Assigned(vRenderOptionsForm) then
vRenderOptionsForm.Free;
vRenderOptionsForm := nil;
end;
procedure TGLDRenderOptionsForm.RB_Click(Sender: TObject);
begin
CB_DrawEdges.Enabled := RB_Smooth.Checked;
end;
function TGLDRenderOptionsForm.GetParams: TGLDSystemRenderOptionsParams;
var
RenderMode: TGLDSystemRenderMode;
begin
if RB_Smooth.Checked then
RenderMode := rmSmooth else
if RB_Wireframe.Checked then
RenderMode := rmWireframe else
if RB_BoundingBox.Checked then
RenderMode := rmBoundingBox;
Result := GLDXSystemRenderOptionsParams(
RenderMode, CB_DrawEdges.Checked,
CB_EnableLighting.Checked, CB_TwoSidedLighting.Checked,
CB_CullFacing.Checked, TGLDCullFace(CB_CullFace.ItemIndex));
end;
procedure TGLDRenderOptionsForm.SetParams(Value: TGLDSystemRenderOptionsParams);
begin
if GLDXSystemRenderOptionsParamsEqual(GetParams, Value) then Exit;
CB_DrawEdges.Enabled := True;
case Value.RenderMode of
rmSmooth: RB_Smooth.Checked := True;
rmWireframe: RB_Wireframe.Checked := True;
rmBoundingBox: RB_BoundingBox.Checked := True;
end;
CB_DrawEdges.Checked := Value.DrawEdges;
CB_EnableLighting.Checked := Value.EnableLighting;
CB_TwoSidedLighting.Checked := Value.TwoSidedLighting;
CB_CullFacing.Checked := Value.CullFacing;
CB_CullFace.ItemIndex := Integer(Value.CullFace);
if Value.RenderMode <> rmSmooth then
CB_DrawEdges.Enabled := False;
end;
procedure TGLDRenderOptionsForm.BB_Click(Sender: TObject);
begin
Close;
end;
initialization
finalization
GLDReleaseRenderOptionsForm;
end.
|
unit uStringMapOfString;
interface
uses uStringMap, uArrayListOfString;
{
Automatic dynamic str map that contains strs
}
type StringMapOfString = class(StringMap)
public
constructor Create(); override;
procedure add(key, value: String); overload;
function remove(key: String): String; overload;
function get(key: String): String; overload;
function getValues(): ArrayListOfString; overload;
end;
implementation
// StringMapOfString
constructor StringMapOfString.Create();
begin
keys := ArrayListOfString.Create();
vals := ArrayListOfString.Create();
end;
// StringMapOfString
procedure StringMapOfString.add(key, value: String);
begin
(keys as ArrayListOfString).add(key);
(vals as ArrayListOfString).add(value);
end;
// StringMapOfString
function StringMapOfString.remove(key: String): String;
var
index: integer;
begin
remove := '';
index := find(key);
if index > -1 then begin
keys.remove(index);
remove := (vals as ArrayListOfString).remove(index);
end;
end;
// StringMapOfString
function StringMapOfString.get(key: String): String;
var index: integer;
begin
get := '';
index := find(key);
if index > -1 then
get := (vals as ArrayListOfString).get(index);
end;
// StringMapOfString
function StringMapOfString.getValues(): ArrayListOfString;
begin
getValues := (vals as ArrayListOfString);
end;
end.
|
unit DBModels;
interface
uses
util1,
stmObj,
stmPG,
stmDataBase2,
stmMemo1,
Ncdef2,
SysUtils,
Classes,
ZDbcIntfs;
type
TArrayString = array of String;
TDBModel = class(typeUO)
private
_table,_application,_application_table:String;
_fields,_field_types,_field_constraints,_pkeys,_fkeys,_field_lookups,_field_foreign_fields,_field_is_serial:TStringList;
_n_fields,_n_pkeys,_n_fkeys:Integer;
_connection:IZconnection;
public
constructor Create;overload;
constructor Create(table:String;application:String='';view_on:String='');overload;
destructor Destroy;override;
procedure initModel(table:String;application:String='';view_on:String='');
function has_key(key:String):Boolean;
function is_pkey(key:String):Boolean;
function is_fkey(key:String):Boolean;
function getPk:String;
function getFk:String;
property pkeys:TStringList read _pkeys;
property fkeys:TStringList read _fkeys;
property nfields:Integer read _n_fields;
property npkeys:Integer read _n_pkeys;
property nfkeys:Integer read _n_fkeys;
property table:String read _table;
property application:String read _application;
property application_table:String read _application_table;
property fields:TStringList read _fields;
property types:TStringList read _field_types;
property constraints:TStringList read _field_constraints;
property lookups:TStringList read _field_lookups;
property references:TStringList read _field_foreign_fields;
property connection:IZConnection read _connection;
class function stmClassName:string;override;
end;
procedure proTDBModel_Create(table:String;var pu:typeUO);pascal;
function fonctionTDBModel_hasKey(key:String;var pu:typeUO):Boolean;pascal;
function fonctionTDBModel_isPKey(key:String;var pu:typeUO):Boolean;pascal;
function fonctionTDBModel_isFKey(key:String;var pu:typeUO):Boolean;pascal;
function fonctionTDBModel_nPKeys(var pu:typeUO):Integer;pascal;
function fonctionTDBModel_nFKeys(var pu:typeUO):Integer;pascal;
function fonctionTDBModel_getTable(var pu:typeUO):String;pascal;
function fonctionTDBModel_getConstraint(key:String;var pu:typeUO):String;pascal;
function fonctionTDBModel_getType(key:String;var pu:typeUO):String;pascal;
procedure proTDBModel_getFields(var memo:TstmMemo;var pu:typeUO);pascal;
procedure proTDBModel_getPKeys(var memo:TstmMemo;var pu:typeUO);pascal;
procedure proTDBModel_getFKeys(var memo:TstmMemo;var pu:typeUO);pascal;
procedure proTDBModel_getLookup(key:String;var memo:TstmMemo;var pu:typeUO);pascal;
implementation
uses
DBCache;
constructor TDBModel.Create;
begin
notPublished := True;
inherited Create;
end;
constructor TDBModel.Create(table:String;application:String='';view_on:String='');
begin
notPublished := True;
inherited Create;
initModel(table,application,view_on);
end;
procedure TDBModel.initModel(table:String;application:String='';view_on:String='');
var
statement,statement_constraint:IZStatement;
resultset,resultset_constraint,resultset_constraints,resultset_constraint_unique,resultset_constraint_usage:IZResultSet;
default,query,constraint,constraint_type,foreign_constraint,foreign_table,foreign_field,fd,tp:String;
model_exists:Boolean;
n,index:Integer;
begin
model_exists := False;
_connection := DBCONNECTION.connection;
if not assigned(_fields) then _fields := TStringList.Create else _fields.Clear;
if not assigned(_field_types) then _field_types := TStringList.Create else _field_types.Clear;
if not assigned(_field_constraints) then _field_constraints := TStringList.Create else _field_constraints.Clear;
if not assigned(_pkeys) then _pkeys := TStringList.Create else _pkeys.Clear;
if not assigned(_field_lookups) then _field_lookups := TStringList.Create else _field_lookups.Clear;
if not assigned(_field_foreign_fields) then _field_foreign_fields := TStringList.Create else _field_foreign_fields.Clear;
if not assigned(_fkeys) then _fkeys := TStringList.Create else _fkeys.Clear;
if not assigned(_field_is_serial) then _field_is_serial := TStringList.Create else _field_is_serial.Clear;
_table := table;
_application := application;
if _application <> '' then _application_table := _application + '_' + table else _application_table := table;
statement := _connection.createStatement;
query := 'SELECT %s,%s,%s,%s,%s FROM %s WHERE table_name = ''%s'' ORDER BY %s';
query := Format(query, ['table_name', 'column_name', 'data_type', 'udt_name','column_default', 'information_schema.columns', _application_table, 'ordinal_position']);
resultset := statement.ExecuteQuery(query);
while resultset.Next do
begin
default := resultset.getStringByName('column_default');
fd := resultset.getStringByName('column_name');
_fields.Add(fd);
if Pos('nextval',default) > 0 then _field_is_serial.Values[fd] := 'True' else _field_is_serial.Values[fd] := 'False';
tp := resultset.getStringByName('udt_name');
_field_types.Values[fd] := tp;
statement_constraint := _connection.CreateStatement;
query := 'SELECT constraint_name FROM information_schema.key_column_usage WHERE table_name = ''%s'' AND column_name = ''%s''';
query := Format(query, [_application_table, fd]);
resultset_constraint := statement_constraint.ExecuteQuery(query);
_field_constraints.Values[fd] := 'None';
_field_lookups.Values[fd] := 'None';
_field_foreign_fields.Values[fd] := 'None';
while resultset_constraint.Next do
begin
constraint := resultset_constraint.getStringByName('constraint_name');
query := 'SELECT constraint_type FROM information_schema.table_constraints WHERE table_name = ''%s'' AND constraint_name = ''%s''';
query := Format(query, [_application_table, constraint]);
resultset_constraints := statement_constraint.ExecuteQuery(query);
resultset_constraints.First;
constraint_type := resultset_constraints.getStringByName('constraint_type');
_field_constraints.Values[fd] := constraint_type;
if constraint_type = 'FOREIGN KEY' then
begin
_fkeys.Add(fd);
query := 'SELECT unique_constraint_name FROM information_schema.referential_constraints WHERE constraint_name = ''%s''';
query := Format(query, [constraint]);
resultset_constraint_unique := statement_constraint.ExecuteQuery(query);
resultset_constraint_unique.First;
foreign_constraint := resultset_constraint_unique.getStringByName('unique_constraint_name');
query := 'SELECT table_name,column_name FROM information_schema.key_column_usage WHERE constraint_name = ''%s''';
query := Format(query,[foreign_constraint]);
resultset_constraint_usage := statement_constraint.ExecuteQuery(query);
resultset_constraint_usage.First;
foreign_table := resultset_constraint_usage.getStringByName('table_name');
foreign_field := resultset_constraint_usage.getStringByName('column_name');
_field_lookups.Values[fd] := foreign_table;
_field_foreign_fields.Values[fd] := foreign_field;
end
else
begin
{
_field_lookups.Values[fd] := 'None';
_field_foreign_fields.Values[fd] := 'None';
}
if constraint_type = 'PRIMARY KEY' then _pkeys.Add(fd);
end;
end;
{
if resultset_constraint.First then
begin
end
else
begin
end;
}
end;
{make a fake model for analysis to interact with analyses as a classic table}
if (_application_table = 'analysis_analysis') and (view_on <> '') then
begin
{index := _fields.IndexOf('component');
_fields[index] := 'analysis_type';}
resultset := statement.ExecuteQuery('SELECT * FROM analysis_pin WHERE component =''' + view_on + '''');
while resultset.Next do _fields.Add(resultset.GetStringByName('name'));
end;
_n_fields := _fields.Count;
_n_pkeys := _pkeys.Count;
_n_fkeys := _fkeys.Count;
if _n_fields < 1 then
raise Exception.Create('table ' + _application_table + ' does not exist');
end;
function TDBModel.has_key(key:String):Boolean;
begin
if _fields.IndexOf(key) > 0 then Result := True else Result := False;
end;
function TDBModel.is_pkey(key:String):Boolean;
begin
if has_key(key) then
if _field_constraints.Values[key] = 'PRIMARY KEY' then Result := True else Result := False
else
Result := False;
end;
function TDBModel.is_fkey(key:String):Boolean;
begin
if has_key(key) then
if _field_constraints.Values[key] = 'FOREIGN KEY' then Result := True else Result := False
else
Result := False;
end;
function TDBModel.getPk:String;
var
i:integer;
st,separator:String;
begin
st := '';
for i:=1 to _fields.Count do
begin
if st <> '' then separator := '__' else separator := '';
if is_pkey(_fields[i-1]) then st := st + separator + _fields[i-1];
end;
Result := st;
end;
function TDBModel.getFk:String;
var
i:integer;
st,separator,field:String;
begin
st := '';
for i := 1 to _fields.Count do
begin
if st <> '' then separator := '_' else separator := '';
if is_fkey(_fields[i-1]) then
begin
field := _fields[i-1];
st := st + separator + _field_lookups.Values[field] + '____' + _field_foreign_fields.Values[field];
end;
end;
Result := st;
end;
destructor TDBModel.Destroy;
begin
_fields.Free;
_field_types.Free;
_field_constraints.Free;
_field_lookups.Free;
_field_foreign_fields.Free;
_field_is_serial.Free;
_pkeys.Free;
_fkeys.Free;
messageToRef(UOmsg_destroy,nil);
inherited Destroy;
end;
class function TDBModel.stmClassName:string;
begin
result:='DBModel';
end;
procedure proTDBModel_Create(table:String;var pu:typeUO);pascal;
begin
createPgObject('',pu,TDBModel);
TDBModel(pu).initModel(table);
end;
function fonctionTDBModel_hasKey(key:String;var pu:typeUO):Boolean;pascal;
begin
verifierObjet(pu);
Result := TDBModel(pu).has_key(key);
end;
function fonctionTDBModel_isPKey(key:String;var pu:typeUO):Boolean;pascal;
begin
verifierObjet(pu);
Result := TDBModel(pu).is_pkey(key);
end;
function fonctionTDBModel_isFKey(key:String;var pu:typeUO):Boolean;pascal;
begin
verifierObjet(pu);
Result := TDBModel(pu).is_fkey(key);
end;
function fonctionTDBModel_nFields(var pu:typeUO):Integer;pascal;
begin
verifierObjet(pu);
Result := TDBModel(pu).nfields;
end;
function fonctionTDBModel_nPKeys(var pu:typeUO):Integer;pascal;
begin
verifierObjet(pu);
Result := TDBModel(pu).npkeys;
end;
function fonctionTDBModel_nFKeys(var pu:typeUO):Integer;pascal;
begin
verifierObjet(pu);
Result := TDBModel(pu).nfkeys;
end;
function fonctionTDBModel_getTable(var pu:typeUO):String;pascal;
begin
verifierObjet(pu);
Result := TDBModel(pu).application_table;
end;
function fonctionTDBModel_getConstraint(key:String;var pu:typeUO):String;pascal;
var
model:TDBModel;
begin
verifierObjet(pu);
model := TDBModel(pu);
if model.has_key(key) then Result := model.constraints.Values[key] else Result := '';
end;
function fonctionTDBModel_getType(key:String;var pu:typeUO):String;pascal;
var
model:TDBModel;
begin
verifierObjet(pu);
model := TDBModel(pu);
if model.has_key(key) then Result := model.types.Values[key] else Result := '';
end;
procedure proTDBModel_getFields(var memo:TstmMemo;var pu:typeUO);pascal;
var
astr:TArrayString;
model:TDBModel;
i:Integer;
st:String;
begin
verifierObjet(pu);
model := TDBModel(pu);
verifierObjet(typeUO(memo));
memo.memo.Clear;
for i:=1 to model.fields.Count do memo.memo.Lines.add(model.fields[i-1]);
end;
procedure proTDBModel_getPKeys(var memo:TstmMemo;var pu:typeUO);pascal;
var
astr:TArrayString;
model:TDBModel;
i:Integer;
st:String;
begin
verifierObjet(pu);
model := TDBModel(pu);
verifierObjet(typeUO(memo));
memo.memo.Clear;
for i:=1 to model.pkeys.Count do memo.memo.Lines.add(model.pkeys[i-1]);
end;
procedure proTDBModel_getFKeys(var memo:TstmMemo;var pu:typeUO);pascal;
var
astr:TArrayString;
model:TDBModel;
i:Integer;
st:String;
begin
verifierObjet(pu);
model := TDBModel(pu);
verifierObjet(typeUO(memo));
memo.memo.Clear;
for i:=1 to model.fkeys.Count do memo.memo.Lines.add(model.fkeys[i-1]);
end;
procedure proTDBModel_getLookup(key:String;var memo:TstmMemo;var pu:typeUO);pascal;
var
astr:TArrayString;
model:TDBModel;
begin
verifierObjet(pu);
model := TDBModel(pu);
verifierObjet(typeUO(memo));
memo.memo.Clear;
if model.is_fkey(key) then memo.memo.Lines.Add(model.lookups.Values[key] + '.' + model.references.Values[key]);
end;
initialization
registerObject(TDBModel,sys);
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
GTS (GNU Triangulated Surface) vector file format implementation.
}
unit VXS.FileGTS;
interface
{$I VXScene.inc}
uses
System.Classes,
VXS.VectorFileObjects,
VXS.ApplicationFileIO;
type
{ The GTS vector file (GNU Triangulated Surface library).
It is a simple text format, with indexed vertices. The first line contains
the number of vertices, the number of edges and the number of faces separated
by spaces.
Following lines contain the x/y/z coordinates of vertices, then the edges
(two indices) and the faces (three indices).
http://gts.sourceforge.net/ }
TVXGTSVectorFile = class(TVXVectorFile)
public
class function Capabilities: TVXDataFileCapabilities; override;
procedure LoadFromStream(aStream: TStream); override;
end;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
uses
System.SysUtils,
VXS.Utils;
// ------------------
// ------------------ TVXGTSVectorFile ------------------
// ------------------
class function TVXGTSVectorFile.Capabilities: TVXDataFileCapabilities;
begin
Result := [dfcRead];
end;
procedure TVXGTSVectorFile.LoadFromStream(aStream: TStream);
var
i, nv, ne, nf, k, ei: Integer;
sl: TStringList;
mesh: TVXMeshObject;
fg: TFGVertexIndexList;
vertIndices: array [0 .. 5] of Integer;
pEdge, pTri, p: PChar;
begin
sl := TStringList.Create;
try
sl.LoadFromStream(aStream{$IFDEF Unicode}, TEncoding.ASCII{$ENDIF});
mesh := TVXMeshObject.CreateOwned(Owner.MeshObjects);
mesh.Mode := momFaceGroups;
if sl.Count > 0 then
begin
p := PChar(sl[0]);
nv := ParseInteger(p);
ne := ParseInteger(p);
nf := ParseInteger(p);
if (nv or nf or ne) = 0 then
Exit;
for i := 1 to nv do
begin
p := PChar(sl[i]);
mesh.Vertices.Add(ParseFloat(p), ParseFloat(p), ParseFloat(p));
end;
fg := TFGVertexIndexList.CreateOwned(mesh.FaceGroups);
for i := 1 + nv + ne to nv + ne + nf do
begin
pTri := PChar(sl[i]);
for k := 0 to 2 do
begin
ei := ParseInteger(pTri);
pEdge := PChar(sl[nv + ei]);
vertIndices[k * 2 + 0] := ParseInteger(pEdge);
vertIndices[k * 2 + 1] := ParseInteger(pEdge);
end;
if (vertIndices[0] = vertIndices[2]) or (vertIndices[0] = vertIndices[3])
then
fg.VertexIndices.Add(vertIndices[0] - 1)
else
fg.VertexIndices.Add(vertIndices[1] - 1);
if (vertIndices[2] = vertIndices[4]) or (vertIndices[2] = vertIndices[5])
then
fg.VertexIndices.Add(vertIndices[2] - 1)
else
fg.VertexIndices.Add(vertIndices[3] - 1);
if (vertIndices[4] = vertIndices[0]) or (vertIndices[4] = vertIndices[1])
then
fg.VertexIndices.Add(vertIndices[4] - 1)
else
fg.VertexIndices.Add(vertIndices[5] - 1);
end;
mesh.BuildNormals(fg.VertexIndices, momTriangles);
end;
finally
sl.Free;
end;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterVectorFileFormat('gts', 'GNU Triangulated Surface', TVXGTSVectorFile);
end.
|
unit Nullpobug.Example.Spring4d.CalculatorGUIForm;
interface
uses
System.SysUtils
, System.Types
, System.UITypes
, System.Rtti
, System.Classes
, System.Variants
, FMX.Types
, FMX.Controls
, FMX.Forms
, FMX.Dialogs
, FMX.StdCtrls
, FMX.Layouts
, FMX.Memo
;
type
TCalculatorGUIForm = class(TForm)
DisplayArea: TMemo;
procedure FormCreate(Sender: TObject);
public
procedure WriteLine(S: String);
end;
var
CalculatorGUIForm: TCalculatorGUIForm;
implementation
{$R *.fmx}
procedure TCalculatorGUIForm.FormCreate(Sender: TObject);
begin
DisplayArea.Lines.Clear;
end;
procedure TCalculatorGUIForm.WriteLine(S: String);
begin
DisplayArea.Lines.Add(S);
end;
end.
|
unit LogMessage;
interface
uses
System.Sysutils, System.Classes, System.DateUtils, System.JSON, WinApi.Windows;
type
TLogMessage = record
MessageType:String;
Facility:String;
Severity:String;
TimeStamp:String;
Host:String;
Process:String;
ProcessID: DWORD;
Logmessage: String;
class function Create: TLogMessage; overload; static;
class function Create(AJson: String): TLogMessage; overload; static;
end;
implementation
class function TLogMessage.Create: TLogMessage;
begin
Result.MessageType := String.Empty;
Result.Facility := String.Empty;
Result.Severity := String.Empty;
Result.TimeStamp := String.Empty;
Result.Host := String.Empty;
Result.Process := String.Empty;
Result.ProcessID := 0;
Result.LogMessage := String.Empty;
end;
class function TLogMessage.Create(AJson: String): TLogMessage;
begin
var LJson := TJSONObject.ParseJSONValue(AJson) as TJSONObject;
try
if nil <> LJson.Values['type'] then
Result.MessageType := LJson.Values['type'].Value;
if nil <> LJson.Values['facility'] then
Result.Facility := LJson.Values['facility'].Value;
if nil <> LJson.Values['severity'] then
Result.Severity := LJson.Values['severity'].Value;
if nil <> LJson.Values['timeStamp'] then
Result.TimeStamp := LJson.Values['timeStamp'].Value;
if nil <> LJson.Values['host'] then
Result.Host := LJson.Values['host'].Value;
if nil <> LJson.Values['process'] then
Result.Process := LJson.Values['process'].Value;
if nil <> LJson.Values['logMessage'] then
Result.LogMessage := LJson.Values['logMessage'].Value;
finally
LJson.Free;
end;
end;
end.
|
unit uXMLLkjRunTimeFile;
interface
uses
SysUtils,Forms,xmldom, XMLIntf, msxmldom, XMLDoc,uLKJRuntimeFile,Windows;
type
////////////////////////////////////////////////////////////////////////////////
/// TXmlLkjRunTimeFile 功能:实现 TLKJRuntimeFile 与XML文件相互转换
////////////////////////////////////////////////////////////////////////////////
TXmlLkjRunTimeFile = class
private
procedure AddHeadInfoToXML(NewNode : IXMLNode;HeadInfo: RLKJRTFileHeadInfo);
procedure AddRewListToXML(NewNode : IXMLNode;LkjFile : TLKJRuntimeFile);
procedure AddHeadInfoToLkjFile(NewNode : IXMLNode;LkjFile : TLKJRuntimeFile);
procedure AddRewListToLkjFile(NewNode : IXMLNode;LkjFile : TLKJRuntimeFile);
public
//功能:把TLKJRuntimeFile转换为Xml文件
procedure ConvertLkjRuntimeFileToXml(LkjFile : TLKJRuntimeFile;XmlFileName : string);
//功能:把Xml文件转换为TLKJRuntimeFile
procedure ConvertXmlToLkjRunTimeFile(XmlFileName: string;var LkjRuntimeFile: TLKJRuntimeFile);
end;
implementation
{ TVirtualFile }
procedure TXmlLkjRunTimeFile.AddHeadInfoToLkjFile(NewNode: IXMLNode;
LkjFile: TLKJRuntimeFile);
var
subNode : IXMLNode;
begin
subNode := NewNode.ChildNodes['HeadInfo'];
with LkjFile.HeadInfo do
begin
nLocoID := subNode.Attributes['机车编号'];
nLocoType := subNode.Attributes['机车型号'];
strTrainHead := subNode.Attributes['车次头'];
nTrainNo := subNode.Attributes['车次'];
nDistance := subNode.Attributes['走行距离'];
nJKLineID := subNode.Attributes['交路号'];
nDataLineID := subNode.Attributes['数据交路号'];
nFirstDriverNO := subNode.Attributes['司机工号'];
nSecondDriverNO := subNode.Attributes['副司机号'];
nStartStation := subNode.Attributes['始发站'];
nEndStation := subNode.Attributes['终点站'];
nLocoJie := subNode.Attributes['机车单节'];
nDeviceNo := subNode.Attributes['装置号'];
nTotalWeight := subNode.Attributes['总重'];
nSum := subNode.Attributes['合计'];
nLoadWeight := subNode.Attributes['载重'];
nJKVersion := subNode.Attributes['监控版本'];
nDataVersion := subNode.Attributes['数据版本'];
DTFileHeadDt := StrToDateTime(subNode.Attributes['文件头时间']);
Factory := subNode.Attributes['软件厂家'];
TrainType := subNode.Attributes['客货类型'];
BenBu := subNode.Attributes['本补'];
nStandardPressure := subNode.Attributes['标准管压'];
nMaxLmtSpd := subNode.Attributes['输入最高限速'];
end;
end;
procedure TXmlLkjRunTimeFile.AddHeadInfoToXML(NewNode: IXMLNode;
HeadInfo: RLKJRTFileHeadInfo);
begin
with HeadInfo do
begin
NewNode.Attributes['机车编号'] := nLocoID;
NewNode.Attributes['机车型号'] := nLocoType;
NewNode.Attributes['车次头'] := strTrainHead;
NewNode.Attributes['车次'] := nTrainNo ;
NewNode.Attributes['走行距离'] := nDistance ;
NewNode.Attributes['交路号'] := nJKLineID ;
NewNode.Attributes['数据交路号'] := nDataLineID ;
NewNode.Attributes['司机工号'] := nFirstDriverNO ;
NewNode.Attributes['副司机号'] := nSecondDriverNO ;
NewNode.Attributes['始发站'] := nStartStation ;
NewNode.Attributes['终点站'] := nEndStation ;
NewNode.Attributes['机车单节'] := nLocoJie ;
NewNode.Attributes['装置号'] := nDeviceNo ;
NewNode.Attributes['总重'] := nTotalWeight ;
NewNode.Attributes['合计'] := nSum ;
NewNode.Attributes['载重'] := nLoadWeight ;
NewNode.Attributes['监控版本'] := nJKVersion ;
NewNode.Attributes['数据版本'] := nDataVersion ;
NewNode.Attributes['文件头时间'] := DTFileHeadDt ;
NewNode.Attributes['软件厂家'] := Factory ;
NewNode.Attributes['客货类型'] := TrainType ;
NewNode.Attributes['本补'] := BenBu ;
NewNode.Attributes['标准管压'] := nStandardPressure ;
NewNode.Attributes['输入最高限速'] := nMaxLmtSpd ;
end;
end;
procedure TXmlLkjRunTimeFile.AddRewListToLkjFile(NewNode: IXMLNode;
LkjFile: TLKJRuntimeFile);
var
i : Integer;
rec : RCommonRec;
subNode : IXMLNode;
lkjCommonrec : TLKJCommonRec;
begin
for I := 0 to NewNode.ChildNodes['RewList'].ChildNodes.Count - 1 do
begin
subNode := NewNode.ChildNodes['RewList'].ChildNodes[i];
rec.nRow := subNode.Attributes['行号'];
rec.nEvent := subNode.Attributes['事件代码'];
rec.DTEvent := StrToDateTime(subNode.Attributes['事件时间']);
rec.nCoord := subNode.Attributes['公里标'];
rec.nDistance := subNode.Attributes['距离'];
rec.LampSign := subNode.Attributes['机车信号'];
rec.nLampNo := subNode.Attributes['信号机编号'];
rec.SignType := subNode.Attributes['信号机类型'];
rec.nSpeed := subNode.Attributes['速度'];
rec.nLimitSpeed := subNode.Attributes['限速'];
rec.WorkZero := subNode.Attributes['零非工况'];
rec.HandPos := subNode.Attributes['前后工况'];
rec.WorkDrag :=subNode.Attributes['牵制工况'];
rec.nLieGuanPressure := subNode.Attributes['管压'];
rec.nGangPressure := subNode.Attributes['缸压'];
rec.nRotate := subNode.Attributes['柴速'];
rec.nJG1Pressure := subNode.Attributes['均缸1'];
rec.nJG2Pressure := subNode.Attributes['均缸2'];
rec.strOther := subNode.Attributes['其它'];
rec.nJKLineID := subNode.Attributes['当前交路号'];
rec.nDataLineID := subNode.Attributes['当前数据交路号'];
rec.nStation := subNode.Attributes['已过车站号'];
rec.nToJKLineID := subNode.Attributes['上一个站的交路号'];
rec.nToDataLineID := subNode.Attributes['上一个站的数据交路号'];
rec.nToStation := subNode.Attributes['上一个站编号'];
rec.nStationIndex := subNode.Attributes['车站编号'];
lkjCommonrec := TLKJCommonRec.Create;
lkjCommonrec.CommonRec := rec;
LkjFile.Records.Add(lkjCommonrec);
end;
end;
procedure TXmlLkjRunTimeFile.AddRewListToXML(NewNode: IXMLNode; LkjFile: TLKJRuntimeFile);
var
i : Integer;
rec : RCommonRec;
subNode : IXMLNode;
begin
for I := 0 to LkjFile.Records.Count - 1 do
begin
rec := TLKJCommonRec(LkjFile.Records.Items[i]).CommonRec;
subNode := NewNode.AddChild('记录' + IntToStr(i));
subNode.Attributes['行号'] := rec.nRow;
subNode.Attributes['事件代码'] := rec.nEvent;
subNode.Attributes['事件时间'] := rec.DTEvent;
subNode.Attributes['公里标'] := rec.nCoord;
subNode.Attributes['距离'] := rec.nDistance;
subNode.Attributes['机车信号'] := rec.LampSign;
subNode.Attributes['信号机编号'] := rec.nLampNo;
subNode.Attributes['信号机类型'] := rec.SignType;
subNode.Attributes['速度'] := rec.nSpeed;
subNode.Attributes['限速'] := rec.nLimitSpeed;
subNode.Attributes['零非工况'] := rec.WorkZero;
subNode.Attributes['前后工况'] := rec.HandPos;
subNode.Attributes['牵制工况'] := rec.WorkDrag;
subNode.Attributes['管压'] := rec.nLieGuanPressure;
subNode.Attributes['缸压'] := rec.nGangPressure;
subNode.Attributes['柴速'] := rec.nRotate;
subNode.Attributes['均缸1'] := rec.nJG1Pressure;
subNode.Attributes['均缸2'] := rec.nJG2Pressure;
subNode.Attributes['其它'] := rec.strOther;
subNode.Attributes['当前交路号'] := rec.nJKLineID;
subNode.Attributes['当前数据交路号'] := rec.nDataLineID;
subNode.Attributes['已过车站号'] := rec.nStation;
subNode.Attributes['上一个站的交路号'] := rec.nToJKLineID;
subNode.Attributes['上一个站的数据交路号'] := rec.nToDataLineID;
subNode.Attributes['上一个站编号'] := rec.nToStation;
subNode.Attributes['车站编号'] := rec.nStationIndex;
end;
end;
procedure TXmlLkjRunTimeFile.ConvertLkjRuntimeFileToXml(LkjFile: TLKJRuntimeFile;XmlFileName : string);
var
xmlDoc : TXMLDocument;
xmlNode : IXMLNode;
NewNode : IXMLNode;
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.Active := True;
xmlDoc.Version := '1.0';
xmlDoc.Encoding := 'gb2312';
xmlDoc.Options := [doNodeAutoCreate,doNodeAutoIndent,doAttrNull,doAutoPrefix,doNamespaceDecl];
xmlDoc.DocumentElement := xmlDoc.CreateNode('FileList');
xmlNode := xmlDoc.DocumentElement;
NewNode := xmlNode.AddChild('HeadInfo');
AddHeadInfoToXML(NewNode,LkjFile.HeadInfo);
NewNode := xmlNode.AddChild('RewList');
AddRewListToXML(NewNode,LkjFile);
xmlDoc.SaveToFile(XmlFileName);
xmlDoc.DocumentElement.ChildNodes.Clear;
finally
xmlDoc.Free;
end;
end;
procedure TXmlLkjRunTimeFile.ConvertXmlToLkjRunTimeFile(XmlFileName: string;
var LkjRuntimeFile: TLKJRuntimeFile);
var
xmlDoc : IXMLDocument;
begin
if Assigned(LkjRuntimeFile) then
LkjRuntimeFile.Free;
LkjRuntimeFile := TLKJRuntimeFile.Create(nil);
xmlDoc := NewXMLDocument();
try
xmlDoc.LoadFromFile(XmlFileName);
AddHeadInfoToLkjFile(xmlDoc.DocumentElement,LkjRuntimeFile);
AddRewListToLkjFile(xmlDoc.DocumentElement,LkjRuntimeFile);
finally
xmlDoc := nil;
end;
end;
end.
|
unit ft232hhw;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, basehw, msgstr, D2XXUnit, utilfunc;
type
{ TFT232HHardware }
TFT232HHardware = class(TBaseHardware)
private
FDevOpened: boolean;
FStrError: string;
procedure SetI2CPins(scl, sda: byte);
public
constructor Create;
destructor Destroy; override;
function GetLastError: string; override;
function DevOpen: boolean; override;
procedure DevClose; override;
//spi
function SPIRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; override;
function SPIWrite(CS: byte; BufferLen: integer; buffer: array of byte): integer; override;
function SPIInit(speed: integer): boolean; override;
procedure SPIDeinit; override;
procedure SetSPIcs(cs: byte);
//I2C
procedure I2CInit; override;
procedure I2CDeinit; override;
function I2CReadWrite(DevAddr: byte;
WBufferLen: integer; WBuffer: array of byte;
RBufferLen: integer; var RBuffer: array of byte): integer; override;
procedure I2CStart; override;
procedure I2CStop; override;
function I2CReadByte(ack: boolean): byte; override;
function I2CWriteByte(data: byte): boolean; override; //return ack
//MICROWIRE
function MWInit(speed: integer): boolean; override;
procedure MWDeinit; override;
function MWRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; override;
function MWWrite(CS: byte; BitsWrite: byte; buffer: array of byte): integer; override;
function MWIsBusy: boolean; override;
end;
implementation
uses main;
const
MSB_RISING_EDGE_CLOCK_BYTE_IN = $20;
MSB_RISING_EDGE_CLOCK_BYTE_OUT = $10;
MSB_RISING_EDGE_CLOCK_BIT_IN = $22;
MSB_RISING_EDGE_CLOCK_BIT_OUT = $12;
procedure TFT232HHardware.SetI2CPins(scl, sda: byte);
var pins: byte;
begin
if scl > 0 then scl := 1;
if sda > 0 then sda := 2;
pins := 0;
pins := pins or scl or sda;
FT_Out_Buffer[0] := $80; //MPSSE Command to set low bits of port
FT_Out_Buffer[1] := pins;
FT_Out_Buffer[2] := %00000011; //Pin directions
Write_USB_Device_Buffer(3);
end;
procedure TFT232HHardware.SetSPIcs(cs: byte);
begin
FT_Out_Buffer[0] := $80; //MPSSE Command to set low bits of port
if cs > 0 then
FT_Out_Buffer[1] := %00001110 else
FT_Out_Buffer[1] := %00000110;
FT_Out_Buffer[2] := %00001011; //Pin directions
Write_USB_Device_Buffer(3);
end;
constructor TFT232HHardware.Create;
begin
FHardwareName := 'FT232H';
FHardwareID := CHW_FT232H;
end;
destructor TFT232HHardware.Destroy;
begin
DevClose;
end;
function TFT232HHardware.GetLastError: string;
begin
result := FStrError;
end;
function TFT232HHardware.DevOpen: boolean;
var
err: integer;
begin
if FDevOpened then DevClose;
err := Open_USB_Device();
if err > 0 then
begin
FStrError := STR_CONNECTION_ERROR+ FHardwareName +'('+IntToStr(err)+')';
FDevOpened := false;
Exit(false);
end;
FDevOpened := true;
Result := true;
end;
procedure TFT232HHardware.DevClose;
begin
if FDevOpened then
begin
Close_USB_Device();
FDevOpened := false;
end;
end;
//SPI___________________________________________________________________________
//SPI speed 0 = 6Mhz; >1 = 30Mhz
function TFT232HHardware.SPIInit(speed: integer): boolean;
var
err: integer;
begin
if not FDevOpened then Exit(false);
Result := True;
Purge_USB_Device_In();
Purge_USB_Device_Out();
err := Set_USB_Device_BitMode($FF, FT_BITMODE_MPSSE);
if err <> FT_OK then Result := False;
err := Set_USB_Device_LatencyTimer(1);
if err <> FT_OK then Result := False;
//Setting Clock Divisor 12Mhz/60Mhz
if speed > 0 then
FT_Out_Buffer[0] := $8A //MPSSE command disable div5
else
FT_Out_Buffer[0] := $8B; //MPSSE command enable div5;
FT_Out_Buffer[1] := $86; //MPSSE command Setting Clock Divisor
FT_Out_Buffer[2] := $00;
FT_Out_Buffer[3] := $00;
FT_Out_Buffer[4] := $8D; //Disable 3 phase data clock
//Setting Port Data and Direction
//Bits assigned on FT232H AD bus
//0 Out SPI CLK (SCK)
//1 Out SPI DO (MOSI)
//2 In SPI DI (MISO)
//3 Out SPI CS0
FT_Out_Buffer[5] := $80; //MPSSE Command to set low bits of port
FT_Out_Buffer[6] := %00001110;
FT_Out_Buffer[7] := %00001011; //Pin directions
FT_Out_Buffer[8] := $9E; //Set I/O to only drive on a ‘0’ and tristate on a ‘1’
FT_Out_Buffer[9] := $00;
FT_Out_Buffer[10] := $00;
err := Write_USB_Device_Buffer(11);
if err <> 11 then Result := False;
end;
procedure TFT232HHardware.SPIDeinit;
begin
if not FDevOpened then Exit;
Set_USB_Device_BitMode($FF, FT_BITMODE_RESET);
end;
function TFT232HHardware.SPIRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer;
begin
if not FDevOpened then Exit(-1);
//SetSPIcs(0);
FT_Out_Buffer[0] := $80; //MPSSE Command to set low bits of port
FT_Out_Buffer[1] := %00000110;
FT_Out_Buffer[2] := %00001011; //Pin directions
FT_Out_Buffer[3] := $24; //MPSSE command to read bytes in from SPI
FT_Out_Buffer[4] := BufferLen-1;
FT_Out_Buffer[5] := (BufferLen-1) shr 8;
FT_Out_Buffer[6] := $87; //Send answer back immediate command
Write_USB_Device_Buffer(7);
result := Read_USB_Device_Buffer(BufferLen);
Move(FT_In_Buffer[0], buffer[0], BufferLen);
if (CS = 1)then SetSPIcs(1); //release cs
end;
function TFT232HHardware.SPIWrite(CS: byte; BufferLen: integer; buffer: array of byte): integer;
begin
if not FDevOpened then Exit(-1);
//SetSPIcs(0);
FT_Out_Buffer[0] := $80; //MPSSE Command to set low bits of port
FT_Out_Buffer[1] := %00000110;
FT_Out_Buffer[2] := %00001011; //Pin directions
FT_Out_Buffer[3] := $11; //MPSSE command to write bytes from from SPI
FT_Out_Buffer[4] := BufferLen-1;
FT_Out_Buffer[5] := (BufferLen-1) shr 8;
Move(buffer[0], FT_Out_Buffer[6], BufferLen);
result := Write_USB_Device_Buffer(BufferLen+6)-6;
if (CS = 1)then SetSPIcs(1); //release cs
end;
//i2c___________________________________________________________________________
procedure TFT232HHardware.I2CInit;
begin
if not FDevOpened then Exit;
Purge_USB_Device_In();
Purge_USB_Device_Out();
Set_USB_Device_BitMode($FF, FT_BITMODE_MPSSE);
Set_USB_Device_LatencyTimer(1);
//Setting Clock Divisor 200Khz
FT_Out_Buffer[0] := $8A; //MPSSE command disable div5
FT_Out_Buffer[1] := $86; //MPSSE command Setting Clock Divisor
FT_Out_Buffer[2] := $95;
FT_Out_Buffer[3] := $00;
FT_Out_Buffer[4] := $97; //Ensure turn off adaptive clocking
FT_Out_Buffer[5] := $8C; //Enable 3 phase data clock, used by I2C to allow data on both clock edges
FT_Out_Buffer[6] := $9E; //Set I/O to only drive on a ‘0’ and tristate on a ‘1’
FT_Out_Buffer[7] := %00000111;
FT_Out_Buffer[8] := $00;
//Setting Port Data and Direction
//Bits assigned on FT232H AD bus
//0 Out SPI CLK (SCK)
//1 Out SPI DO (MOSI)
//2 In SPI DI (MISO)
//3 Out SPI CS0
FT_Out_Buffer[9] := $80; //MPSSE Command to set low bits of port
FT_Out_Buffer[10] := %00000011;
FT_Out_Buffer[11] := %00000011; //Pin directions
Write_USB_Device_Buffer(12);
end;
procedure TFT232HHardware.I2CDeinit;
begin
if not FDevOpened then Exit;
Set_USB_Device_BitMode($FF, FT_BITMODE_RESET);
FT_Out_Buffer[0] := $9E; //Set I/O to only drive on a ‘0’ and tristate on a ‘1’
FT_Out_Buffer[2] := $00;
FT_Out_Buffer[3] := $00;
Write_USB_Device_Buffer(3);
end;
function TFT232HHardware.I2CReadWrite(DevAddr: byte;
WBufferLen: integer; WBuffer: array of byte;
RBufferLen: integer; var RBuffer: array of byte): integer;
var
full_buff: array of byte;
i, j: integer;
begin
if not FDevOpened then Exit(-1);
SetLength(full_buff, WBufferLen+1);
move(WBuffer, full_buff[1], WBufferLen);
full_buff[0] := DevAddr;
ClearBit(full_buff[0], 0);
I2CStart();
j:= 0;
for i:= 0 to WBufferLen do //+devaddr
begin
FT_Out_Buffer[0+j] := MSB_RISING_EDGE_CLOCK_BYTE_OUT; //Clock data byte out on –ve Clock Edge MSB first
FT_Out_Buffer[1+j] := 0;
FT_Out_Buffer[2+j] := 0; //Data length of 0x0000 means 1 byte data to clock out
FT_Out_Buffer[3+j] := full_buff[i]; //Add data to be send
FT_Out_Buffer[4+j] := $80; //Command to set directions of lower 8 pins and force value on bits set as output
FT_Out_Buffer[5+j] := 0; //Set SCL low
FT_Out_Buffer[6+j] := 1; //Set SK to 1, DO and other pins as input with bit ‘0’
FT_Out_Buffer[7+j] := MSB_RISING_EDGE_CLOCK_BIT_IN; //Command to scan in ACK bit , +ve clock Edge MSB first
FT_Out_Buffer[8+j] := 0; //Length of 0x0 means to scan in 1 bit
FT_Out_Buffer[9+j] := $87; //Send answer back immediate command
FT_Out_Buffer[10+j] := $80; //Command to set directions of lower 8 pins and force value on bits set as output
FT_Out_Buffer[11+j] := $02; //Set SDA high, SCL low
FT_Out_Buffer[12+j] := $03; //Set SK,DO pins as output with bit ‘1’, other pins as input with bit ‘0’
Inc(j, 13);
end;
Write_USB_Device_Buffer((WBufferLen+1)*13);
Read_USB_Device_Buffer(WBufferLen+1);
if RBufferLen > 0 then
begin
I2CStart();
DevAddr := SetBit(DevAddr, 0);
I2CWriteByte(DevAddr);
j:= 0;
for i:= 0 to RBufferLen -1 do
begin
FT_Out_Buffer[0+j] := $80; //Command to set directions of lower 8 pins and force value on bits set as output
FT_Out_Buffer[1+j] := %00000000; //Set SCL low
FT_Out_Buffer[2+j] := %00000001; //Set SK, DO and other pins as input
FT_Out_Buffer[3+j] := MSB_RISING_EDGE_CLOCK_BYTE_IN; //Command to clock data byte in
FT_Out_Buffer[4+j] := 0;
FT_Out_Buffer[5+j] := 0;
//Set DO for output
FT_Out_Buffer[6+j] := $80; //Command to set directions of lower 8 pins and force value on bits set as output
FT_Out_Buffer[7+j] := %00000000;
FT_Out_Buffer[8+j] := %00000011;
FT_Out_Buffer[9+j] := $13; //acknowledge bit , +ve clock Edge MSB first
FT_Out_Buffer[10+j] := 0; //Length of 0 means to send 1 bit
if i = RBufferLen-1 then FT_Out_Buffer[11+j] := $FF else FT_Out_Buffer[11+j] := 0;
FT_Out_Buffer[12+j] := $87; //Send answer back immediate command
Inc(j, 13);
end;
Write_USB_Device_Buffer(RBufferLen*13);
Read_USB_Device_Buffer(RBufferLen);
Move(FT_In_Buffer[0], RBuffer[0], RBufferLen);
end;
I2CStop();
result := WBufferLen + RBufferLen;
end;
procedure TFT232HHardware.I2CStart;
var i, num: integer;
begin
if not FDevOpened then Exit;
num := 0;
for i:=0 to 3 do
begin
FT_Out_Buffer[num] := $80; //MPSSE Command to set low bits of port
inc(num);
FT_Out_Buffer[num] := %00000011;
inc(num);
FT_Out_Buffer[num] := %00000011; //Pin directions
inc(num);
end;
for i:=0 to 3 do
begin
FT_Out_Buffer[num] := $80; //MPSSE Command to set low bits of port
inc(num);
FT_Out_Buffer[num] := %00000001;
inc(num);
FT_Out_Buffer[num] := %00000011; //Pin directions
inc(num);
end;
FT_Out_Buffer[num] := $80; //MPSSE Command to set low bits of port
inc(num);
FT_Out_Buffer[num] := %00000000;
inc(num);
FT_Out_Buffer[num] := %00000011; //Pin directions
inc(num);
Write_USB_Device_Buffer(num);
end;
procedure TFT232HHardware.I2CStop;
var i, num: integer;
begin
if not FDevOpened then Exit;
num := 0;
for i:=0 to 3 do
begin
FT_Out_Buffer[num] := $80; //MPSSE Command to set low bits of port
inc(num);
FT_Out_Buffer[num] := %00000000;
inc(num);
FT_Out_Buffer[num] := %00000011; //Pin directions
inc(num);
end;
for i:=0 to 3 do
begin
FT_Out_Buffer[num] := $80; //MPSSE Command to set low bits of port
inc(num);
FT_Out_Buffer[num] := %00000001;
inc(num);
FT_Out_Buffer[num] := %00000011; //Pin directions
inc(num);
end;
for i:=0 to 3 do
begin
FT_Out_Buffer[num] := $80; //MPSSE Command to set low bits of port
inc(num);
FT_Out_Buffer[num] := %00000011;
inc(num);
FT_Out_Buffer[num] := %00000011; //Pin directions
inc(num);
end;
Write_USB_Device_Buffer(num);
end;
function TFT232HHardware.I2CReadByte(ack: boolean): byte;
begin
if not FDevOpened then Exit;
FT_Out_Buffer[0] := $80; //Command to set directions of lower 8 pins and force value on bits set as output
FT_Out_Buffer[1] := %00000000; //Set SCL low
FT_Out_Buffer[2] := %00000001; //Set SK, DO and other pins as input
FT_Out_Buffer[3] := MSB_RISING_EDGE_CLOCK_BYTE_IN; //Command to clock data byte in
FT_Out_Buffer[4] := 0;
FT_Out_Buffer[5] := 0;
//Set DO for output
FT_Out_Buffer[6] := $80; //Command to set directions of lower 8 pins and force value on bits set as output
FT_Out_Buffer[7] := %00000000;
FT_Out_Buffer[8] := %00000011;
FT_Out_Buffer[9] := $13; //acknowledge bit , +ve clock Edge MSB first
FT_Out_Buffer[10] := 0; //Length of 0 means to send 1 bit
if not ack then FT_Out_Buffer[11] := $FF else FT_Out_Buffer[11] := 0;
FT_Out_Buffer[12] := $87; //Send answer back immediate command
// FT_Out_Buffer[13] := $80; //Command to set directions of lower 8 pins and force value on bits set as output
// FT_Out_Buffer[14] := 2; //Set SDA high, SCL low
// FT_Out_Buffer[15] := 3; //Set SK,DO,GPIOL0 pins as output with bit ’’, other pins as input with bit ‘’
Write_USB_Device_Buffer(13);
Read_USB_Device_Buffer(1);
result := FT_In_Buffer[0];
end;
function TFT232HHardware.I2CWriteByte(data: byte): boolean;
begin
if not FDevOpened then Exit;
FT_Out_Buffer[0] := MSB_RISING_EDGE_CLOCK_BYTE_OUT; //Clock data byte out on +ve Clock Edge MSB first
FT_Out_Buffer[1] := 0;
FT_Out_Buffer[2] := 0; //Data length of 0x0000 means 1 byte data to clock out
FT_Out_Buffer[3] := data; //Add data to be send
FT_Out_Buffer[4] := $80; //Command to set directions of lower 8 pins and force value on bits set as output
FT_Out_Buffer[5] := 0; //Set SCL low
FT_Out_Buffer[6] := 1; //Set SK to 1, DO and other pins as input with bit ‘0’
FT_Out_Buffer[7] := MSB_RISING_EDGE_CLOCK_BIT_IN; //Command to scan in ACK bit , +ve clock Edge MSB first
FT_Out_Buffer[8] := 0; //Length of 0x0 means to scan in 1 bit
FT_Out_Buffer[9] := $87; //Send answer back immediate command
FT_Out_Buffer[10] := $80; //Command to set directions of lower 8 pins and force value on bits set as output
FT_Out_Buffer[11] := $02; //Set SDA high, SCL low
FT_Out_Buffer[12] := $03; //Set SK,DO pins as output with bit ‘1’, other pins as input with bit ‘0’
Write_USB_Device_Buffer(13);
Read_USB_Device_Buffer(1);
Result := not IsBitSet(FT_In_Buffer[0], 0);
end;
//MICROWIRE_____________________________________________________________________
function TFT232HHardware.MWInit(speed: integer): boolean;
var
err: integer;
begin
if not FDevOpened then Exit(false);
Result := True;
Purge_USB_Device_In();
Purge_USB_Device_Out();
err := Set_USB_Device_BitMode($FF, FT_BITMODE_MPSSE);
if err <> FT_OK then Result := False;
err := Set_USB_Device_LatencyTimer(1);
if err <> FT_OK then Result := False;
//Setting Clock Divisor
FT_Out_Buffer[0] := $8A; //MPSSE command disable div5
FT_Out_Buffer[1] := $86; //MPSSE command Setting Clock Divisor
FT_Out_Buffer[2] := 29; //1Mhz
FT_Out_Buffer[3] := $00;
FT_Out_Buffer[4] := $8D; //Disable 3 phase data clock
//Setting Port Data and Direction
//Bits assigned on FT232H AD bus
//0 Out SPI CLK (SCK)
//1 Out SPI DO (MOSI)
//2 In SPI DI (MISO)
//3 Out SPI CS0
FT_Out_Buffer[5] := $80; //MPSSE Command to set low bits of port
FT_Out_Buffer[6] := %00001110;
FT_Out_Buffer[7] := %00001011; //Pin directions
FT_Out_Buffer[8] := $9E; //Set I/O to only drive on a ‘0’ and tristate on a ‘1’
FT_Out_Buffer[9] := $00;
FT_Out_Buffer[10] := $00;
err := Write_USB_Device_Buffer(11);
if err <> 11 then Result := False;
end;
procedure TFT232HHardware.MWDeInit;
begin
if not FDevOpened then Exit;
Set_USB_Device_BitMode($FF, FT_BITMODE_RESET);
end;
function TFT232HHardware.MWRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer;
begin
if not FDevOpened then Exit(-1);
SetSPIcs(1); //cs hi
FT_Out_Buffer[0] := $24; //MPSSE command to read bytes in from SPI
FT_Out_Buffer[1] := BufferLen-1;
FT_Out_Buffer[2] := (BufferLen-1) shr 8;
FT_Out_Buffer[3] := $87; //Send answer back immediate command
Write_USB_Device_Buffer(4);
result := Read_USB_Device_Buffer(BufferLen);
Move(FT_In_Buffer[0], buffer[0], BufferLen);
if Boolean(CS) then SetSPIcs(0);
end;
function TFT232HHardware.MWWrite(CS: byte; BitsWrite: byte; buffer: array of byte): integer;
var
i, BuffIndex: integer;
begin
if not FDevOpened then Exit(-1);
if BitsWrite > 0 then
begin
SetSPIcs(1); //cs hi
BuffIndex:= 0;
if (BitsWrite div 8) > 0 then //if we have a whole byte
begin
FT_Out_Buffer[BuffIndex] := $11; //write byte
Inc(BuffIndex);
FT_Out_Buffer[BuffIndex] := (BitsWrite div 8)-1;
Inc(BuffIndex);
FT_Out_Buffer[BuffIndex] := 0;
Inc(BuffIndex);
for i:= 0 to (BitsWrite div 8)-1 do
begin
FT_Out_Buffer[BuffIndex] := buffer[i];
Inc(BuffIndex);
end;
Write_USB_Device_Buffer((BitsWrite div 8)+3);
end;
if (BitsWrite mod 8) > 0 then //bits
begin
FT_Out_Buffer[0] := $13; //write bit
FT_Out_Buffer[1] := (BitsWrite mod 8)-1;
FT_Out_Buffer[2] := buffer[i+1];
FT_Out_Buffer[3] := $87; //Send answer back immediate command
Write_USB_Device_Buffer(4);
end;
end;
if Boolean(CS) then SetSPIcs(0);
end;
function TFT232HHardware.MWIsBusy: boolean;
begin
SetSPIcs(1);
FT_Out_Buffer[0] := $81; //read port lbyte
FT_Out_Buffer[1] := $87; //Send answer back immediate command
Write_USB_Device_Buffer(2);
Read_USB_Device_Buffer(1);
SetSPIcs(0);
result := not IsBitSet(FT_In_Buffer[0], 2);
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit SimpleListCollectionSampleFormUnit1;
interface
uses
System.SysUtils, System.Types, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms,
FMX.Dialogs, System.Rtti, FMX.Edit, Data.Bind.Components, Data.Bind.EngExt, FMX.Menus,
Fmx.Bind.DBEngExt, System.Bindings.Outputs, FMX.ListBox, FMX.Layouts, SampleCollections,
Generics.Collections,
FMX.Bind.Editors; // Used by TBindList to populate a TListBox
type
TForm1 = class(TForm)
BindingsList1: TBindingsList;
EditSourceExpression: TEdit;
ButtonFill: TButton;
EditSourceComponentName: TEdit;
EditControlComponent: TEdit;
EditControlExpression: TEdit;
BindList1: TBindList;
ListBox1: TListBox;
BindScope1: TBindScope;
ButtonClear: TButton;
ButtonFillFromScratch: TButton;
ButtonClearFromScratch: TButton;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
procedure ButtonFillClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ButtonClearClick(Sender: TObject);
procedure BindList1EvalError(Sender: TObject; AException: Exception);
procedure ButtonFillFromScratchClick(Sender: TObject);
procedure ButtonClearFromScratchClick(Sender: TObject);
private
FListData: TObject;
public
destructor Destroy; override;
procedure UpdateDisplayFields;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
type
TListObject = class
private
FStringField: string;
FIntegerField: Integer;
public
constructor Create(const AString: string; AInteger: Integer);
property StringField: string read FStringField write FStringField;
property IntegerField: Integer read FIntegerField write FIntegerField;
end;
{ TListObject }
constructor TListObject.Create(const AString: string; AInteger: Integer);
begin
FStringField := AString;
FIntegerField := AInteger;
end;
procedure TForm1.BindList1EvalError(Sender: TObject; AException: Exception);
begin
// Generate a new exception with more information
raise TBindCompException.CreateFmt(
'Evaluation Exception'#13#10 +
'Component Name: %s'#13#10 +
'Exception Class: %s'#13#10 +
'Exception Message: %s',
[TComponent(Sender).Name, AException.ClassName, AException.Message]);
end;
procedure TForm1.ButtonClearClick(Sender: TObject);
begin
BindList1.ClearList;
end;
procedure TForm1.ButtonClearFromScratchClick(Sender: TObject);
var
LBindList: TBindList;
begin
// This example calls FillList so no need for for autoactivate and autofill.
LBindList := TBindList.Create(nil);
// LBindList.AutoActivate := True;
// LBindList.AutoFill := False;
try
LBindList.ControlComponent := ListBox1;
LBindList.ClearList;
finally
LBindList.Free;
end;
end;
procedure TForm1.ButtonFillClick(Sender: TObject);
var
LData: TList<TListObject>;
I: Integer;
begin
// This example calls FillList so no need for for autoactivate and autofill.
BindList1.AutoActivate := True;
BindList1.AutoFill := False;
LData := TObjectList<TListObject>.Create;
try
for I := 1 to 10 do
LData.Add(TListObject.Create('Item' + IntToStr(I), I));
BindScope1.DataObject := LData;
try
BindList1.FillList;
finally
BindScope1.DataObject := nil; // clear before free data object
end;
finally
LData.Free;
end;
end;
procedure TForm1.ButtonFillFromScratchClick(Sender: TObject);
var
LData: TList<TListObject>;
I: Integer;
LBindList: TBindList;
LBindScope: TBindScope;
begin
LBindList := TBindList.Create(nil);
// This example calls FillList so no need for for autoactivate and autofill.
LBindList.AutoActivate := True;
LBindList.AutoFill := False;
LBindScope := TBindScope.Create(nil);
try
LData := TObjectList<TListObject>.Create;
try
for I := 1 to 10 do
LData.Add(TListObject.Create('Item' + IntToStr(I), I));
LBindList.ControlComponent := ListBox1;
LBindList.SourceComponent := LBindScope;
with LBindList.FormatExpressions.AddExpression do
begin
SourceExpression := 'ToStr(Current.IntegerField) + ": " + Current.StringField';
ControlExpression := 'Text';
end;
LBindScope.DataObject := LData;
LBindList.FillList;
LBindScope.DataObject := nil;
finally
LData.Free;
end;
finally
LBindList.Free;
LBindScope.Free;
end;
end;
destructor TForm1.Destroy;
begin
inherited;
end;
// Display information about binding
procedure TForm1.UpdateDisplayFields;
var
LSourceExpression: string;
LControlExpression: string;
LSourceComponent: string;
LControlComponent: string;
begin
if BindList1.FormatExpressions.Count > 0 then
begin
LSourceExpression := BindList1.FormatExpressions[0].SourceExpression;
LControlExpression := BindList1.FormatExpressions[0].ControlExpression;
end;
if BindList1.ControlComponent <> nil then
LControlComponent := BindList1.ControlComponent.ClassName;
if BindList1.SourceComponent <> nil then
begin
LSourceComponent := BindList1.SourceComponent.ClassName;
if BindList1.SourceComponent is TBindScope then
with TBindScope(BindList1.SourceComponent) do
if DataObject <> nil then
LSourceComponent := LSourceComponent + ' (' +
DataObject.ClassName + ')'
else if Component <> nil then
LSourceComponent := LSourceComponent + ' (' +
Component.ClassName + ')';
end;
EditSourceExpression.Text := LSourceExpression;
EditControlExpression.Text := LControlExpression;
EditControlComponent.Text := LControlComponent;
EditSourceComponentName.Text := LSourceComponent;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
UpdateDisplayFields;
end;
end.
|
{: GLDXFRenderer<p>
OpenGL renderer for DXF objects<p>
<b>History :</b><font size=-1><ul>
<li>19/01/03 - DA - 3DFaces seems to be drawing correctly now
<li>18/01/03 - DA - Unit creation from GLDXFVectorFile,
Now drawing clockwise and counter-clockwise polygons
</ul></font>
}
unit GLDXFRenderer;
interface
uses
OpenGL,
TypesDXF,
FileDXF,
ObjectsDXF,
GLScene,
GLVectorTypes,
GLVectorFileObjects,
GLTexture,
OpenGLTokens,
GLRenderContextInfo;
type
// TGLDXFRenderer
//
{: An OpenGL DXF rendere. }
TGLDXFRenderer = class
private
FHeader: TDXFHeader;
FEntities: TDXFEntitiesList;
public
procedure DrawGLArc(StartAngle, EndAngle, Radius: Double; Position: T3DPoint);
procedure DrawPoint(Point: TDXFPoint);
procedure DrawLine(Line: TDXFLine);
procedure DrawPolyline(Polyline: TDXFPolyline);
procedure DrawArc(Arc: TDXFArc);
procedure DrawCircle(Circle: TDXFCircle);
procedure Draw3DFace(Face: TDXF3DFace);
procedure DrawInsert(Insert: TDXFInsert);
procedure DrawSolid(Solid: TDXFSolid);
procedure DrawEntity(Entity: TDXFEntity);
//: render DXF object with Direct Opengl
procedure Render(Sender: TObject;var rci:TGLRenderContextInfo);
//: DXF header
property Header: TDXFHeader read FHeader write FHeader;
//: list of entities in the DXF file
property Entities: TDXFEntitiesList read FEntities write FEntities;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
uses
OpenGL1x,
GLVectorGeometry,
MathsDXF,
WinProcs, // OutputDebugString()
SysUtils,
Math
;
{ TGLDXFRenderer }
// DrawGLArc
//
procedure TGLDXFRenderer.DrawGLArc(StartAngle, EndAngle, Radius: Double; Position: T3DPoint);
var
a: Double;
begin
// draw the arc
glPushMatrix;
glTranslated(Position.X, Position.Y, Position.Z);
glBegin(GL_LINE_STRIP);
a := StartAngle;
while (a <= EndAngle) do begin
glVertex2f(Cos(DegToRad(a)) * Radius, Sin(DegToRad(a)) * Radius);
// stop exactly at the end angle
if (a < EndAngle) and (a + 1 > EndAngle) then a := EndAngle else a := a + 1;
end;
glEnd;
glPopMatrix;
end;
// DrawPoint
//
procedure TGLDXFRenderer.DrawPoint(Point: TDXFPoint);
begin
with Point do begin
glColor3f(Color.X, Color.Y, Color.Z); // color
glBegin(GL_POINTS);
glVertex3f(Primary.X, Primary.Y, Primary.Z);
glEnd;
end;
end;
// DrawLine
//
procedure TGLDXFRenderer.DrawLine(Line: TDXFLine);
begin
with Line do begin
glColor3f(Color.X, Color.Y, Color.Z); // color
glBegin(GL_LINES);
glVertex3f(Primary.X, Primary.Y, Primary.Z);
glVertex3f(EndPoint.X, EndPoint.Y, EndPoint.Z);
glEnd;
end;
end;
// DrawPolyline
//
procedure TGLDXFRenderer.DrawPolyline(Polyline: TDXFPolyline);
var
v: integer;
procedure DrawPolyElementArc(V1, V2 : TDXFVertex);
var
//Ang: Double;
IncAng, Ang_a, Chord, Rad, ChordAng, Dir: Double;
StartAngle, EndAngle: Double;
StartPoint, EndPoint: TAffineVector;
CP: T3DPoint;
begin
// The bulge is the tangent of one fourth the included angle
// for an arc segment, made negative if the arc goes
// clockwise from the start point to the endpoint.
// A bulge of 0 indicates a straight segment, and a bulge
// of 1 is a semicircle. Thus, Mutiplying the ArcTANgent of the
// bulge factor by 4 gives the included angle (angle formed by
// line form the first vertex to the center point to the
// second vertex)in radians.
IncAng := 4 * ArcTan(Abs(V1.Bulge));
// Ang := RadToDeg(IncAng);
// if not 0 calculate Angle A. Angle A is the angle formed by the
// chord of the arc, the invisible line between the two vertices of
// the defined arc, and the invisible line from a vertex of the arc
// to the center point of the arc.
Ang_a := (Pi / 2) - (IncAng / 2);
// calculate the length of the chord of the polyline arc
// distance between the two vertex that form the polyline arc
StartPoint := AffineVectorMake(V1.Primary.X, V1.Primary.Y, V1.Primary.Z);
EndPoint := AffineVectorMake(V2.Primary.X, V2.Primary.Y, V2.Primary.Z);
Chord := VectorDistance(StartPoint, EndPoint);
// if the Include Angle is not 0, a straight Polyline segment,
// calculate and display Radius of arc, Angle of Chord,
// center point
Rad := (Chord / 2) / Cos(Ang_a);
ChordAng := DegToRad(Angle(V1.Primary, V2.Primary));
// check to see if Bulge Factor is negative or postive
// determines which direction the arc was created
// clockwise or counter clockwise.
if V1.Bulge > 0 then Dir:= ChordAng + Ang_a else Dir:= ChordAng - Ang_a;
// finds center point of ARC
CP := Polar(V1.Primary, Dir, Abs(Rad));
// Compute the start angle and end angle for drawing
StartAngle := Angle(CP, V1.Primary);
EndAngle := Angle(CP, V2.Primary);
if V1.Bulge < 0 then begin // clockwise
StartAngle := StartAngle + EndAngle;
EndAngle := StartAngle - EndAngle;
StartAngle := StartAngle - EndAngle;
end;
if StartAngle > EndAngle then EndAngle := EndAngle + 360;
// Print debug information
// display values for the included angle. The included angle is
// the angle from the center point of the arc to the two vertices
// defining the start and end points of the arc.
{
OutputDebugString(PAnsiChar(
Format('Inc. angle=%f°,%fR Angle A=%f° Chord length=%f Radius=%f Angle of Chord=%f°, Dir=%f°',
[Ang, IncAng, RadToDeg(Ang_a), Chord, Rad, RadToDeg(ChordAng), RadToDeg(Dir)])));
OutputDebugString(PAnsiChar(Format('Center Point of Arc: (%f, %f, %f)',
[CP[0], CP[1], CP[2]])));
OutputDebugString(PAnsiChar(Format('StartAngle=%f° EndAngle=%f° Bulge=%f',
[StartAngle, EndAngle, V1.Bulge])));
}
// draw the polyline arc
DrawGLArc(StartAngle, EndAngle, Rad, CP);
// draw arc vertices
{
glColor3f(0, 200, 0); // color
DrawGLArc(0, 360, 0.01, V1.Primary);
glColor3f(0, 200, 100); // color
DrawGLArc(0, 360, 0.01, V2.Primary);
}
end;
procedure DrawPolyElement(V1, V2 : TDXFVertex);
begin
with V1 do begin
if Bulge = 0 then begin // straight segment
glBegin(GL_LINES);
glVertex3f(Primary.X, Primary.Y, Primary.Z); // 1st point
with V2 do glVertex3f(Primary.X, Primary.Y, Primary.Z); // 2nd point
glEnd;
end
else DrawPolyElementArc(V1, V2); // arc
end;
end;
begin
with Polyline do begin
// only draw standards polylines at this time
if Flag and (Ord(pl3DPolygon) + Ord(plPolyface)) = 0 then begin
glColor3f(Color.X, Color.Y, Color.Z); // color
// draw segments and arcs
for v := 0 to Length(PointList) - 2 do
DrawPolyElement(PointList[v], PointList[v+1]);
// it is a closed polyline ?
if Flag and Ord(plClosed) <> 0 then
DrawPolyElement(PointList[Length(PointList) - 1], PointList[0]);
end else OutputDebugString(PWideChar('Polyline non standard ignored.'));
end;
end;
// DrawArc
//
procedure TGLDXFRenderer.DrawArc(Arc: TDXFArc);
var
ea: integer;
begin
with Arc do begin
// some arcs have an end angle lower than the start angle, correct this
if StartAngle > EndAngle then
ea := Round(EndAngle + 360)
else ea := Round(EndAngle);
glColor3f(Color.X, Color.Y, Color.Z); // color
DrawGLArc(StartAngle, ea, Radius, Primary);
end;
end;
// DrawCircle
//
procedure TGLDXFRenderer.DrawCircle(Circle: TDXFCircle);
begin
with Circle do begin
glColor3f(Color.X, Color.Y, Color.Z); // color
DrawGLArc(0, 360, Radius, Primary);
end;
end;
// Draw3DFace
//
procedure TGLDXFRenderer.Draw3DFace(Face: TDXF3DFace);
begin
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_POLYGON);
with Face do begin
glColor3f(Color.X, Color.Y, Color.Z); // color
glVertex3f(Primary.X, Primary.Y, Primary.Z);
glVertex3f(Second.X, Second.Y, Second.Z);
glVertex3f(Third.X, Third.Y, Third.Z);
glVertex3f(Fourth.X, Fourth.Y, Fourth.Z);
{
OutputDebugString(PAnsiChar(Format('3DFace (%f;%f;%f) (%f;%f;%f) (%f;%f;%f) (%f;%f;%f)',
[Primary[0], Primary[1], Primary[2], Second[0], Second[1], Second[2],
Third[0], Third[1], Third[2], Fourth[0], Fourth[1], Fourth[2]])));
}
end;
glEnd;
end;
// DrawInsert
//
procedure TGLDXFRenderer.DrawInsert(Insert: TDXFInsert);
var
Block : TDXFBlock;
CntEntity : Integer;
begin
with Insert do begin
Block := Blocks.BlockByName[BlockName];
if Assigned(Block) then begin
glPushMatrix;
glTranslated(Primary.X, Primary.Y, Primary.Z);
if Scale.X <> 0 then glScaled(Scale.X, Scale.Y, Scale.Z);
with Block.Entities do
for CntEntity := 0 to Count - 1 do
DrawEntity(Entity[CntEntity]);
glPopMatrix;
end
else OutputDebugString(PWideChar('Block not found : ' + BlockName));
end;
end;
// DrawEntity
//
{: Draw an entity
@param Entity The entity to draw }
procedure TGLDXFRenderer.DrawEntity(Entity: TDXFEntity);
begin
if Entity is TDXFPolyline then DrawPolyline(TDXFPolyline(Entity)) else
if Entity is TDXFLine then DrawLine(TDXFLine(Entity)) else
if Entity is TDXFArc then DrawArc(TDXFArc(Entity)) else
if Entity is TDXFCircle then DrawCircle(TDXFCircle(Entity)) else
if Entity is TDXFText then { drawed with opengl objects } else
if Entity is TDXFSolid then DrawSolid(TDXFSolid(Entity)) else
if Entity is TDXF3DFace then Draw3DFace(TDXF3DFace(Entity)) else
if Entity is TDXFInsert then DrawInsert(TDXFInsert(Entity)) else
if Entity is TDXFPoint then DrawPoint(TDXFPoint(Entity)) else
OutputDebugString(PWideChar('Ne sait pas afficher ' + Entity.ClassName));
end;
// Render
//
procedure TGLDXFRenderer.Render(Sender: TObject;var rci: TGLRenderContextInfo);
var
CntEntity : Integer;
begin
// save attributes before modifications
glPushAttrib(GL_ENABLE_BIT or GL_CURRENT_BIT or GL_LIGHTING_BIT or GL_LINE_BIT or GL_COLOR_BUFFER_BIT);
glDisable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
// glPushMatrix;
// rotate all the scene to render in the same way as DXF
glRotated(180, 0, 1, 0);
// draw entities
with Entities do
for CntEntity := 0 to Count - 1 do
DrawEntity(Entity[CntEntity]);
// restore attributes
// glPopMatrix;
glPopAttrib;
end;
// DrawSolid
//
procedure TGLDXFRenderer.DrawSolid(Solid: TDXFSolid);
var
poly: PGLUtesselator;
v3d: Array[0..3] of TAffineDblVector;
vaff: Array[0..3] of TAffineVector;
v: integer;
begin
poly := gluNewTess;
gluTessCallback(poly, GLU_TESS_BEGIN, @glBegin);
gluTessCallback(poly, GLU_TESS_VERTEX, @glVertex3dv);
gluTessCallback(poly, GLU_TESS_END, @glEnd);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_CULL_FACE);
glutessBeginPolygon(poly, nil);
gluTessBeginContour(poly);
with Solid do begin
glColor3f(Color.X, Color.Y, Color.Z); // color
// The gluTessVertex function need an array of TVector3D
SetVector(v3d[0], Primary);
SetVector(v3d[1], Second);
SetVector(v3d[2], Third);
SetVector(v3d[3], Fourth);
// The PolygonSignedArea function need an array of TAffineVector
vaff[0] := Primary;
vaff[1] := Second;
vaff[2] := Third;
vaff[3] := Fourth;
// OutputDebugString(PAnsiChar(Format('PolygonSignedArea = %f', [PolygonSignedArea(@vaff, 4)])));
// sign of the polygon area
if PolygonSignedArea(@vaff, 4) < 0 then begin
// polygon is drawn counter-clockwise
for v:=3 downto 0 do
gluTessVertex(poly, v3d[v], @v3d[v]);
end else begin
// polygon is drawn clockwise
for v:=0 to 3 do
gluTessVertex(poly, v3d[v], @v3d[v]);
end;
{
OutputDebugString(PAnsiChar(Format('Solid (%f;%f;%f) (%f;%f;%f) (%f;%f;%f) (%f;%f;%f)',
[Primary[0], Primary[1], Primary[2], Second[0], Second[1], Second[2],
Third[0], Third[1], Third[2], Fourth[0], Fourth[1], Fourth[2]])));
}
{
glColor3f(0, 255, 0); // color
// draw points
DrawGLArc(0, 360, 0.01, Primary);
DrawGLArc(0, 360, 0.01, Second);
DrawGLArc(0, 360, 0.01, Third);
DrawGLArc(0, 360, 0.01, Fourth);
// draw lines between points
glBegin(GL_LINE_LOOP);
glVertex3f(Primary[0], Primary[1], Primary[2]);
glVertex3f(Second[0], Second[1], Second[2]);
glVertex3f(Fourth[0], Fourth[1], Fourth[2]);
glVertex3f(Third[0], Third[1], Third[2]);
glEnd;
}
end;
gluTessEndContour(poly);
glutessEndPolygon(poly);
gluDeleteTess(poly);
end;
end.
|
namespace proholz.xsdparser;
interface
type
XsdComplexContentVisitor = public class(XsdAnnotatedElementsVisitor)
private
// *
// * The {@link XsdComplexContent} instance which owns this {@link XsdComplexContentVisitor} instance. This way this
// * visitor instance can perform changes in the {@link XsdComplexContent} object.
//
//
var owner: XsdComplexContent;
public
constructor(aowner: XsdComplexContent);
method visit(element: XsdRestriction); override;
method visit(element: XsdExtension); override;
end;
implementation
constructor XsdComplexContentVisitor(aowner: XsdComplexContent);
begin
inherited constructor(aowner);
self.owner := aowner;
end;
method XsdComplexContentVisitor.visit(element: XsdRestriction);
begin
inherited visit(element);
owner.setRestriction(ReferenceBase.createFromXsd(element));
end;
method XsdComplexContentVisitor.visit(element: XsdExtension);
begin
inherited visit(element);
owner.setExtension(ReferenceBase.createFromXsd(element));
end;
end. |
unit uNewMerchandize;
interface
uses
SysUtils, Classes, uTSBaseClass, uNewUnit;
type
TNewMerchadize = class(TSBaseClass)
private
FID: string;
FKode: string;
FNama: string;
FNewUnit: TUnit;
function FLoadFromDB( aSQL : String ): Boolean;
public
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
procedure ClearProperties;
function CustomTableName: string;
function ExecuteCustomSQLTask: Boolean;
function ExecuteCustomSQLTaskPrior: Boolean;
function ExecuteGenerateSQL: Boolean;
function GenerateInterbaseMetaData: Tstrings;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_Kode: string; dynamic;
function GetFieldNameFor_Nama: string; dynamic;
function GetFieldNameFor_NewUnit: string; dynamic;
function GetGeneratorName: string;
function GetHeaderFlag: Integer;
// function cekdata;
function isKodeExits(aKode, aUnitId: String; aExcludeId: Integer): Boolean;
function LoadByID(aID: string): Boolean;
function LoadByKode(aKode: string): Boolean;
function RemoveFromDB: Boolean;
procedure UpdateData(aID, aKode, aNama, aNewUnit_ID: string);
property ID: string read FID write FID;
property Kode: string read FKode write FKode;
property Nama: string read FNama write FNama;
property NewUnit: TUnit read FNewUnit write FNewUnit;
end;
implementation
uses FireDAC.Comp.Client, FireDAC.Stan.Error, udmMain;
{
******************************** TNewMerchadize ********************************
}
constructor TNewMerchadize.Create(aOwner : TComponent);
begin
inherited create(aOwner);
FNewUnit := TUnit.Create(Self);
end;
destructor TNewMerchadize.Destroy;
begin
FNewUnit.free;
inherited Destroy;
end;
procedure TNewMerchadize.ClearProperties;
begin
ID := '';
Kode := '';
Nama := '';
NewUnit.ClearProperties;
end;
function TNewMerchadize.CustomTableName: string;
begin
result := 'REF$MERCHANDISE';
end;
function TNewMerchadize.ExecuteCustomSQLTask: Boolean;
begin
result := True;
end;
function TNewMerchadize.ExecuteCustomSQLTaskPrior: Boolean;
begin
result := True;
end;
function TNewMerchadize.ExecuteGenerateSQL: Boolean;
var
S: string;
begin
result := False;
if State = csNone then
Begin
raise Exception.create('Tidak bisa generate dalam Mode csNone')
end;
if not ExecuteCustomSQLTaskPrior then
begin
cRollbackTrans;
Exit
end else begin
// If FID <= 0 then
If FID = '' then
begin
// FID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
FID := cGetNextIDGUIDToString;
S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_ID + ', ' + GetFieldNameFor_Kode + ', ' + GetFieldNameFor_Nama + ', ' + GetFieldNameFor_NewUnit + ') values ('
+ QuotedStr( FID) + ', '
+ QuotedStr( FKode ) + ','
+ QuotedStr( FNama ) + ','
+ QuotedStr( FNewUnit.ID) + ');'
end else
begin
S := 'Update ' + CustomTableName + ' Set ' + GetFieldNameFor_Kode + ' = ' + QuotedStr( FKode )
+ ' , ' + GetFieldNameFor_Nama + ' = ' + QuotedStr( FNama )
+ ' where ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr( FNewUnit.ID)
+ ' and ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID) + ';';
end;
if not cExecSQL(S, dbtPOS, False) then
begin
cRollbackTrans;
Exit;
end else
Result := ExecuteCustomSQLTask;
end;
end;
function TNewMerchadize.FLoadFromDB( aSQL : String ): Boolean;
var
iQ: TFDQuery;
begin
result := false;
State := csNone;
ClearProperties;
iQ := cOpenQuery(aSQL);
try
with iQ do
Begin
if not EOF then
begin
FID := FieldByName(GetFieldNameFor_ID).asString;
FKode := FieldByName(GetFieldNameFor_Kode).asString;
FNama := FieldByName(GetFieldNameFor_Nama).asString;
FNewUnit.LoadByID(FieldByName(GetFieldNameFor_NewUnit).asString);
Self.State := csLoaded;
Result := True;
end;
End;
finally
FreeAndNil(iQ);
end;
end;
function TNewMerchadize.GenerateInterbaseMetaData: Tstrings;
begin
result := TstringList.create;
result.Append( '' );
result.Append( 'Create Table TNewMerchadize ( ' );
result.Append( 'TRMSBaseClass_ID Integer not null, ' );
result.Append( 'ID Integer Not Null Unique, ' );
result.Append( 'Kode Varchar(30) Not Null Unique, ' );
result.Append( 'Nama Varchar(30) Not Null , ' );
result.Append( 'NewUnit_ID Integer Not Null, ' );
result.Append( 'Stamp TimeStamp ' );
result.Append( ' ); ' );
end;
function TNewMerchadize.GetFieldNameFor_ID: string;
begin
// Result := 'MERCHAN_ID';// <<-- Rubah string ini untuk mapping
Result := 'REF$MERCHANDISE'
end;
function TNewMerchadize.GetFieldNameFor_Kode: string;
begin
Result := 'MERCHAN_CODE';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchadize.GetFieldNameFor_Nama: string;
begin
Result := 'MERCHAN_NAME';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchadize.GetFieldNameFor_NewUnit: string;
begin
// Result := 'MERCHAN_UNT_ID';// <<-- Rubah string ini untuk mapping
Result := 'AUT$UNIT_ID'
end;
function TNewMerchadize.GetGeneratorName: string;
begin
Result := 'gen_ref$merchandise_id';
end;
function TNewMerchadize.GetHeaderFlag: Integer;
begin
result := 736;
end;
function TNewMerchadize.isKodeExits(aKode, aUnitId: String; aExcludeId:
Integer): Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select count( ' + GetFieldNameFor_ID + ' ) as Jml'
+ ' from ' + CustomTableName
+ ' where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode)
+ ' AND ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(aUnitID)
+ ' AND ' + GetFieldNameFor_ID + ' <> ' + IntToStr(aExcludeId);
with cOpenQuery(sSQL) do
begin
try
while not EOF do
begin
if FieldByName('Jml').AsInteger > 0 then
Result := True;
Next;
end;
finally
Free;
end;
end;
end;
function TNewMerchadize.LoadByID(aID: string): Boolean;
begin
result := FloadFromDB('Select * from ' + CustomTableName + ' Where '
+ GetFieldNameFor_ID + ' = ' + QuotedStr(aID));
end;
function TNewMerchadize.LoadByKode(aKode: string): Boolean;
begin
result := FloadFromDB('Select * from ' + CustomTableName + ' Where '
+ GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode));
end;
function TNewMerchadize.RemoveFromDB: Boolean;
var
sErr: string;
sSQL: String;
begin
Result := False;
sSQL := 'delete from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(ID)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(NewUnit.ID);
try
if cExecSQL(sSQL, dbtPOS, False) then
result := True;
except
on E: EFDDBEngineException do
begin
sErr := e.Message;
if sErr <> '' then
raise Exception.Create(sErr)
else
raise Exception.Create('Error Code: '+IntToStr(e.ErrorCode)+#13#10+e.SQL);
end;
end;
end;
procedure TNewMerchadize.UpdateData(aID, aKode, aNama, aNewUnit_ID: string);
begin
FID := aID;
FKode := trim(aKode);
FNama := trim(aNama);
FNewUnit.LoadByID(aNewUnit_ID);
State := csCreated;
end;
end.
|
unit DevExTrans;
(*********************************************************************************
Перевод сообщений на русский язык библиотек от Developer Express:
ExpressBars Suite 5,
ExpressLibrary,
ExpressDataController,
ExpressEditors Library 5,
ExpressExport Library,
ExpressPageControl 2,
ExpressQuantumGrid 5.
Сделано на основе компонентов с http://www.FreeDevExpressAddons.com
Для использования в раздел INITIALIZATION главной формы программы
нужно добавить вызов DevExTranslate(), а в раздел USES добавить модуль DevExTrans.
Можно, конечно, вызывать DevExTranslate() и при старте программы.
В данной реализации используется стандартная функция cxSetResourceString.
**********************************************************************************)
interface
uses
cxClasses,
cxLibraryStrs, // cxLibrary
// cxPCConsts, // PageControl2
cxGridStrs, // QuantumGrid5
cxEditConsts, // Editors5
cxDataConsts, // Datacontroller
cxFilterConsts, // Filter
cxFilterControlStrs, // Filter in Editors5
cxGridPopupMenuConsts, // GridPopupMenu
cxExportStrs, // GridExport
cxNavigator, // cxNavigator
dxBarStrs; // dxBars5
procedure DevExTranslate;
implementation
procedure DevExTranslate;
begin
//cxLibrary
cxSetResourceString(@scxCantCreateRegistryKey, 'Не можу створити ключ у реєстрі: \%s'); // Can't create the registry key: \%s
cxSetResourceString(@scxInvalidPropertyElement, 'Invalid property element: %s'); // Invalid property element: %s
cxSetResourceString(@scxConverterCantCreateStyleRepository, 'Не можу створити Style Repository'); // Can't create the Style Repository
//PageControl2
{ cxSetResourceString(@scxPCImageListIndexError, 'Индекс (%d) должен быть между 0 и %d'); // Index (%d) must be between 0 and %d
cxSetResourceString(@scxPCNoBaseImages, 'BaseImages is not assigned'); // BaseImages is not assigned
cxSetResourceString(@scxPCNoRegisteredStyles, 'Нет зарегистрированных стилей'); // There are no styles registered
cxSetResourceString(@scxPCPageIndexError, '%d - неверное значение PageIndex. PageIndex должен быть между 0 и %d'); // %d is an invalid PageIndex value. PageIndex must be between 0 and %d
cxSetResourceString(@scxPCPainterClassError, 'PCPainterClass is nil'); // PCPainterClass is nil
cxSetResourceString(@scxPCStandardStyleError, 'Неподдерживаемый стандартный стиль %s'); // %s is an unsupported standard style
cxSetResourceString(@scxPCStyleNameError, 'Незарегистрированное наименование стиля %s'); // %s is an unregistered style name
cxSetResourceString(@scxPCTabCountEqualsZero, 'Tabs.Count = 0'); // Tabs.Count = 0
cxSetResourceString(@scxPCTabIndexError, 'Индекс Tab (%d) вне границ'); // Tab's index (%d) out of bounds
cxSetResourceString(@scxPCTabVisibleIndexOutsOfBounds, 'TabVisibleIndex (%d) must be between 0 and %d'); // TabVisibleIndex (%d) must be between 0 and %d
cxSetResourceString(@scxPCVisibleTabListEmpty, 'Нет видимых закладок'); // There are no visible tabs
cxSetResourceString(@scxPCAllowRotateError, 'Стиль %s не поддерживает поворот закладок'); // %s style does not support rotation of tabs}
//QuantumGrid5
cxSetResourceString(@scxGridRecursiveLevels, 'Ви не можете створювати рекурсивні уровні'); // You cannot create recursive levels
cxSetResourceString(@scxGridDeletingConfirmationCaption, 'Підтвердити'); // Confirm
cxSetResourceString(@scxGridDeletingFocusedConfirmationText, 'Видалити запис?'); // Delete record?
cxSetResourceString(@scxGridDeletingSelectedConfirmationText, 'Видалити цсі обрані записи?'); // Delete all selected records?
// cxSetResourceString(@scxGridNoDataInfoText, '<нет данных для отображения>'); // <No data to display>
cxSetResourceString(@scxGridNewItemRowInfoText, 'Натисніть для вставки строки'); // Click here to add a new row
cxSetResourceString(@scxGridFilterIsEmpty, '<фільтр порожній>'); // <Filter is Empty>
cxSetResourceString(@scxGridCustomizationFormCaption, 'Налаштувати'); // Customization
cxSetResourceString(@scxGridCustomizationFormColumnsPageCaption, 'Стовбці'); // Columns
cxSetResourceString(@scxGridGroupByBoxCaption, 'Перетягніть стовбець сюди для групування'); // Drag a column header here to group by that column
cxSetResourceString(@scxGridFilterCustomizeButtonCaption, 'Налаштувати...'); // Customize...
// cxSetResourceString(@scxGridColumnsQuickCustomizationHint, 'Нажмите для выбора видимых столбцов'); // Click here to select visible columns
cxSetResourceString(@scxGridCustomizationFormBandsPageCaption, 'Секції'); // Bands
// cxSetResourceString(@scxGridBandsQuickCustomizationHint, 'Нажмите для выбора видимых секций'); // Click here to select visible bands
// cxSetResourceString(@scxGridCustomizationFormRowsPageCaption, 'Строки'); // Rows
cxSetResourceString(@scxGridConverterIntermediaryMissing, 'Пропущений проміжний компонент!'#13#10'Пожалуйста добавте компонент %s на форму.'); // Missing an intermediary component! Please add a %s component to the form.
cxSetResourceString(@scxGridConverterNotExistGrid, 'Не існує cxGrid'); // cxGrid does not exist
cxSetResourceString(@scxGridConverterNotExistComponent, 'Компонент не існує'); // Component does not exist
cxSetResourceString(@scxImportErrorCaption, 'Помилка імпорту'); // Import error
cxSetResourceString(@scxNotExistGridView, 'Вид таблиці (GridLevel) не існує'); // Grid view does not exist
cxSetResourceString(@scxNotExistGridLevel, 'Активний рівень (Active GridLevel) не існує'); // Active grid level does not exist
cxSetResourceString(@scxCantCreateExportOutputFile, 'Не можу створити файл для експорту'); // Can't create the export output file
cxSetResourceString(@cxSEditRepositoryExtLookupComboBoxItem, 'ExtLookupComboBox|Represents an ultra-advanced lookup using the QuantumGrid as its drop down control'); // ExtLookupComboBox|Represents an ultra-advanced lookup using the QuantumGrid as its drop down control
// cxSetResourceString(@scxGridChartValueHintFormat, '''%s'' для ''%s'': ''%s'''); // '%s for %s is %s' - series display text, category, value
//Editors5
// cxSetResourceString(@cxSEditDateConvertError, 'Невозможно преобразовать в дату'); // Could not convert to date
cxSetResourceString(@cxSEditInvalidRepositoryItem, 'Элемент из репозитария неприемлем'); // The repository item is not acceptable
cxSetResourceString(@cxSEditNumericValueConvertError, 'Невозможно преобразовать в числовое значение'); // Could not convert to numeric value
cxSetResourceString(@cxSEditPopupCircularReferencingError, 'Циклическая ссылка невозможна'); // Circular referencing is not allowed
cxSetResourceString(@cxSEditPostError, 'Произошла ошибка при применении значения'); // An error occured during posting edit value
cxSetResourceString(@cxSEditTimeConvertError, 'Невозможно преобразовать в формат времени'); // Could not convert to time
cxSetResourceString(@cxSEditValidateErrorText, 'Неверное значение. Используйте клавишу Esc для отмены изменений'); // Invalid input value. Use escape key to abandon changes
cxSetResourceString(@cxSEditValueOutOfBounds, 'Значение за пределами диапазона'); // Value out of bounds
// TODO
cxSetResourceString(@cxSEditCheckBoxChecked, 'True'); // True
cxSetResourceString(@cxSEditCheckBoxGrayed, ''); //
cxSetResourceString(@cxSEditCheckBoxUnchecked, 'False'); // False
cxSetResourceString(@cxSRadioGroupDefaultCaption, ''); //
cxSetResourceString(@cxSTextTrue, 'True'); // True
cxSetResourceString(@cxSTextFalse, 'False'); // False
// blob
cxSetResourceString(@cxSBlobButtonOK, '&OK'); // &OK
cxSetResourceString(@cxSBlobButtonCancel, '&Отмена'); // &Cancel
cxSetResourceString(@cxSBlobButtonClose, '&Закрыть'); // &Close
cxSetResourceString(@cxSBlobMemo, '(MEMO)'); // (MEMO)
cxSetResourceString(@cxSBlobMemoEmpty, '(memo)'); // (memo)
cxSetResourceString(@cxSBlobPicture, '(ИЗОБРАЖЕНИЕ)'); // (PICTURE)
cxSetResourceString(@cxSBlobPictureEmpty, '(изображение)'); // (picture)
// popup menu items
cxSetResourceString(@cxSMenuItemCaptionCut, 'Вы&резать'); // Cu&t
cxSetResourceString(@cxSMenuItemCaptionCopy, '&Копировать'); // &Copy
cxSetResourceString(@cxSMenuItemCaptionPaste, '&Вставить'); // &Paste
cxSetResourceString(@cxSMenuItemCaptionDelete, '&Удалить'); // &Delete
cxSetResourceString(@cxSMenuItemCaptionLoad, '&Загрузить...'); // &Load...
cxSetResourceString(@cxSMenuItemCaptionSave, 'Сохранить &Как...'); // Save &As...
// date
cxSetResourceString(@cxSDatePopupClear, 'Очистить'); // Clear
// cxSetResourceString(@cxSDatePopupNow, 'Сейчас'); // Now
// cxSetResourceString(@cxSDatePopupOK, 'OK'); // OK
cxSetResourceString(@cxSDatePopupToday, 'Сегодня'); // Today
cxSetResourceString(@cxSDateError, 'Неверная Дата'); // Invalid Date
// smart input consts
cxSetResourceString(@cxSDateToday, 'сьогодні'); // today
cxSetResourceString(@cxSDateYesterday, 'вчора'); // yesterday
cxSetResourceString(@cxSDateTomorrow, 'завтра'); // tomorrow
cxSetResourceString(@cxSDateSunday, 'Воскресіння'); // Sunday
cxSetResourceString(@cxSDateMonday, 'Понеділок'); // Monday
cxSetResourceString(@cxSDateTuesday, 'Вівторок'); // Tuesday
cxSetResourceString(@cxSDateWednesday, 'Середа'); // Wednesday
cxSetResourceString(@cxSDateThursday, 'Четвер'); // Thursday
cxSetResourceString(@cxSDateFriday, 'П''ятниця'); // Friday
cxSetResourceString(@cxSDateSaturday, 'Субота'); // Saturday
cxSetResourceString(@cxSDateFirst, 'перший'); // first
cxSetResourceString(@cxSDateSecond, 'другий'); // second
cxSetResourceString(@cxSDateThird, 'третій'); // third
cxSetResourceString(@cxSDateFourth, 'четвертий'); // fourth
cxSetResourceString(@cxSDateFifth, 'п''ятий'); // fifth
cxSetResourceString(@cxSDateSixth, 'шостий'); // sixth
cxSetResourceString(@cxSDateSeventh, 'сьомий'); // seventh
cxSetResourceString(@cxSDateBOM, 'МісНач'); // bom
cxSetResourceString(@cxSDateEOM, 'МісКон'); // eom
cxSetResourceString(@cxSDateNow, 'зараз'); // now
// calculator
cxSetResourceString(@scxSCalcError, 'Error'); // Error
// HyperLink
// cxSetResourceString(@scxSHyperLinkPrefix, 'http://'); // http://
// cxSetResourceString(@scxSHyperLinkDoubleSlash, '//'); // //
// edit repository
cxSetResourceString(@scxSEditRepositoryBlobItem, 'BlobEdit|Represents the BLOB editor'); // BlobEdit|Represents the BLOB editor
cxSetResourceString(@scxSEditRepositoryButtonItem, 'ButtonEdit|Represents an edit control with embedded buttons'); // ButtonEdit|Represents an edit control with embedded buttons
cxSetResourceString(@scxSEditRepositoryCalcItem, 'CalcEdit|Represents an edit control with a dropdown calculator window'); // CalcEdit|Represents an edit control with a dropdown calculator window
cxSetResourceString(@scxSEditRepositoryCheckBoxItem, 'CheckBox|Represents a check box control that allows selecting an option'); // CheckBox|Represents a check box control that allows selecting an option
cxSetResourceString(@scxSEditRepositoryComboBoxItem, 'ComboBox|Represents the combo box editor'); // ComboBox|Represents the combo box editor
cxSetResourceString(@scxSEditRepositoryCurrencyItem, 'CurrencyEdit|Represents an editor enabling editing currency data'); // CurrencyEdit|Represents an editor enabling editing currency data
cxSetResourceString(@scxSEditRepositoryDateItem, 'DateEdit|Represents an edit control with a dropdown calendar'); // DateEdit|Represents an edit control with a dropdown calendar
cxSetResourceString(@scxSEditRepositoryHyperLinkItem , 'HyperLink|Represents a text editor with hyperlink functionality'); // HyperLink|Represents a text editor with hyperlink functionality
cxSetResourceString(@scxSEditRepositoryImageComboBoxItem, 'ImageComboBox|Represents an editor displaying the list of images and text strings within the dropdown window'); // ImageComboBox|Represents an editor displaying the list of images and text strings within the dropdown window
cxSetResourceString(@scxSEditRepositoryImageItem, 'Image|Represents an image editor'); // Image|Represents an image editor
cxSetResourceString(@scxSEditRepositoryLookupComboBoxItem, 'LookupComboBox|Represents a lookup combo box control'); // LookupComboBox|Represents a lookup combo box control
cxSetResourceString(@scxSEditRepositoryMaskItem, 'MaskEdit|Represents a generic masked edit control.'); // MaskEdit|Represents a generic masked edit control.
cxSetResourceString(@scxSEditRepositoryMemoItem, 'Memo|Represents an edit control that allows editing memo data'); // Memo|Represents an edit control that allows editing memo data
cxSetResourceString(@scxSEditRepositoryMRUItem , 'MRUEdit|Represents a text editor displaying the list of most recently used items (MRU) within a dropdown window'); // MRUEdit|Represents a text editor displaying the list of most recently used items (MRU) within a dropdown window
cxSetResourceString(@scxSEditRepositoryPopupItem, 'PopupEdit|Represents an edit control with a dropdown list'); // PopupEdit|Represents an edit control with a dropdown list
cxSetResourceString(@scxSEditRepositorySpinItem, 'SpinEdit|Represents a spin editor'); // SpinEdit|Represents a spin editor
cxSetResourceString(@scxSEditRepositoryRadioGroupItem, 'RadioGroup|Represents a group of radio buttons'); // RadioGroup|Represents a group of radio buttons
cxSetResourceString(@scxSEditRepositoryTextItem, 'TextEdit|Represents a single line text editor'); // TextEdit|Represents a single line text editor
cxSetResourceString(@scxSEditRepositoryTimeItem, 'TimeEdit|Represents an editor displaying time values'); // TimeEdit|Represents an editor displaying time values
//
cxSetResourceString(@scxRegExprLine, 'Строка'); // Line
cxSetResourceString(@scxRegExprChar, 'Символ'); // Char
cxSetResourceString(@scxRegExprNotAssignedSourceStream, 'Не присвоен поток-источник'); // The source stream is not assigned
cxSetResourceString(@scxRegExprEmptySourceStream, 'Поток-источник пуст'); // The source stream is empty
cxSetResourceString(@scxRegExprCantUsePlusQuantifier, 'Квантификатор ''+'' не может быть применен здесь'); // The '+' quantifier cannot be applied here
cxSetResourceString(@scxRegExprCantUseStarQuantifier, 'Квантификатор ''*'' не может быть применен здесь'); // The '*' quantifier cannot be applied here
cxSetResourceString(@scxRegExprCantCreateEmptyAlt, 'The alternative should not be empty'); // The alternative should not be empty
cxSetResourceString(@scxRegExprCantCreateEmptyBlock, 'Блок не должен быть пуст'); // The block should not be empty
cxSetResourceString(@scxRegExprIllegalSymbol, 'Неверно: ''%s'''); // Illegal '%s'
cxSetResourceString(@scxRegExprIllegalQuantifier, 'Неверный квантификатор: ''%s'''); // Illegal quantifier '%s'
cxSetResourceString(@scxRegExprNotSupportQuantifier, 'The parameter quantifiers are not supported'); // The parameter quantifiers are not supported
cxSetResourceString(@scxRegExprIllegalIntegerValue, 'Неверное целое значение'); // Illegal integer value
cxSetResourceString(@scxRegExprTooBigReferenceNumber, 'Число-Ссылка слишком велико'); // Too big reference number
cxSetResourceString(@scxRegExprCantCreateEmptyEnum, 'Не могу создать пустое перечисление'); // Can't create empty enumeration
cxSetResourceString(@scxRegExprSubrangeOrder, 'Начальный символ поддиапазона должен быть меньше конечного'); // The starting character of the subrange must be less than the finishing one
cxSetResourceString(@scxRegExprHexNumberExpected0, 'Ожидается шестнадцатеричное число'); // Hexadecimal number expected
cxSetResourceString(@scxRegExprHexNumberExpected, 'Ожидалось шестнадцатеричное число, но найдено ''%s'''); // Hexadecimal number expected but '%s' found
cxSetResourceString(@scxRegExprMissing, 'Пропущено ''%s'''); // Missing '%s'
cxSetResourceString(@scxRegExprUnnecessary, 'Излишняя ''%s'''); // Unnecessary '%s'
cxSetResourceString(@scxRegExprIncorrectSpace, 'Пробел не позволяется после ''\'''); // The space character is not allowed after '\'
cxSetResourceString(@scxRegExprNotCompiled, 'Регулярное выражение не завершено'); // Regular expression is not compiled
cxSetResourceString(@scxRegExprIncorrectParameterQuantifier, 'Incorrect parameter quantifier'); // Incorrect parameter quantifier
cxSetResourceString(@scxRegExprCantUseParameterQuantifier, 'The parameter quantifier cannot be applied here'); // The parameter quantifier cannot be applied here
//
cxSetResourceString(@scxMaskEditRegExprError, 'Ошибки в регулярном выражении:'); // Regular expression errors:
cxSetResourceString(@scxMaskEditInvalidEditValue, 'Редактируемое значение неверно'); // The edit value is invalid
cxSetResourceString(@scxMaskEditNoMask, 'None'); // None
cxSetResourceString(@scxMaskEditIllegalFileFormat, 'Неверный формат файла'); // Illegal file format
cxSetResourceString(@scxMaskEditEmptyMaskCollectionFile, 'Файл с набором масок пуст'); // The mask collection file is empty
cxSetResourceString(@scxMaskEditMaskCollectionFiles, 'Файлы с наборами масок'); // Mask collection files
// cxSetResourceString(@cxSSpinEditInvalidNumericValue, 'Неверное числовое значение'); // Invalid numeric value
//Datacontroller
cxSetResourceString(@cxSDataReadError, 'Ошибка чтения из потока'); // Stream read error
cxSetResourceString(@cxSDataWriteError, 'Ошибка записи в поток'); // Stream write error
cxSetResourceString(@cxSDataItemExistError, 'Элемент уже существует'); // Item already exists
cxSetResourceString(@cxSDataRecordIndexError, 'Индекс записи за пределами диапазона'); // RecordIndex out of range
cxSetResourceString(@cxSDataItemIndexError, 'Индекс элемента за пределами диапазона'); // ItemIndex out of range
cxSetResourceString(@cxSDataProviderModeError, 'Эта операция не поддерживается в режиме ''provider'''); // This operation is not supported in provider mode
cxSetResourceString(@cxSDataInvalidStreamFormat, 'Неверный формат потока'); // Invalid stream format
cxSetResourceString(@cxSDataRowIndexError, 'Индекс строки за пределами диапазона'); // RowIndex out of range
cxSetResourceString(@cxSDataCustomDataSourceInvalidCompare, 'GetInfoForCompare не реализованно'); // GetInfoForCompare not implemented
cxSetResourceString(@cxSDBDetailFilterControllerNotFound, 'DetailFilterController не найден'); // DetailFilterController not found
cxSetResourceString(@cxSDBNotInGridMode, 'DataController не в режиме GridMode'); // DataController not in GridMode
// cxSetResourceString(@cxSDBKeyFieldNotFound, 'Ключевое поле не найдено'); // Key Field not found
//Filter
cxSetResourceString(@cxSFilterOperatorEqual, 'рівен'); // equals
cxSetResourceString(@cxSFilterOperatorNotEqual, 'не рівен'); // does not equal
cxSetResourceString(@cxSFilterOperatorLess, 'менш ніж'); // is less than
cxSetResourceString(@cxSFilterOperatorLessEqual, 'менш або рівен ніж'); // is less than or equal to
cxSetResourceString(@cxSFilterOperatorGreater, 'більш ніж'); // is greater than
cxSetResourceString(@cxSFilterOperatorGreaterEqual, 'більш або рівен ніж'); // is greater than or equal to
cxSetResourceString(@cxSFilterOperatorLike, 'схожий на'); // like
cxSetResourceString(@cxSFilterOperatorNotLike, 'не схожий на'); // not like
cxSetResourceString(@cxSFilterOperatorBetween, 'між'); // between
cxSetResourceString(@cxSFilterOperatorNotBetween, 'не входить до'); // not between
cxSetResourceString(@cxSFilterOperatorInList, 'в'); // in
cxSetResourceString(@cxSFilterOperatorNotInList, 'не входить до'); // not in
cxSetResourceString(@cxSFilterOperatorYesterday, 'вчора'); // is yesterday
cxSetResourceString(@cxSFilterOperatorToday, 'сьогодні'); // is today
cxSetResourceString(@cxSFilterOperatorTomorrow, 'завтра'); // is tomorrow
cxSetResourceString(@cxSFilterOperatorLastWeek, 'останній тиждень'); // is last week
cxSetResourceString(@cxSFilterOperatorLastMonth, 'останній місяць'); // is last month
cxSetResourceString(@cxSFilterOperatorLastYear, 'останній рік'); // is last year
cxSetResourceString(@cxSFilterOperatorThisWeek, 'у цьому тижні'); // is this week
cxSetResourceString(@cxSFilterOperatorThisMonth, 'у цьому місяці'); // is this month
cxSetResourceString(@cxSFilterOperatorThisYear, 'у цьому році'); // is this year
cxSetResourceString(@cxSFilterOperatorNextWeek, 'наступний тиждень'); // is next week
cxSetResourceString(@cxSFilterOperatorNextMonth, 'наступний місяць'); // is next month
cxSetResourceString(@cxSFilterOperatorNextYear, 'наступний рік'); // is next year
cxSetResourceString(@cxSFilterAndCaption, 'і'); // and
cxSetResourceString(@cxSFilterOrCaption, 'або'); // or
cxSetResourceString(@cxSFilterNotCaption, 'не'); // not
cxSetResourceString(@cxSFilterBlankCaption, 'пусто'); // blank
cxSetResourceString(@cxSFilterOperatorIsNull, 'пустой'); // is blank
cxSetResourceString(@cxSFilterOperatorIsNotNull, 'не пустой'); // is not blank
cxSetResourceString(@cxSFilterOperatorBeginsWith, 'починається з'); // begins with
cxSetResourceString(@cxSFilterOperatorDoesNotBeginWith, 'не починається с'); // does not begin with
cxSetResourceString(@cxSFilterOperatorEndsWith, 'закінчується на'); // ends with
cxSetResourceString(@cxSFilterOperatorDoesNotEndWith, 'не закінчується на'); // does not end with
cxSetResourceString(@cxSFilterOperatorContains, 'містить'); // contains
cxSetResourceString(@cxSFilterOperatorDoesNotContain, 'не містить'); // does not contain
cxSetResourceString(@cxSFilterBoxAllCaption, '(Все)'); // (All)
cxSetResourceString(@cxSFilterBoxCustomCaption, '(Спеціальний...)'); // (Custom...)
cxSetResourceString(@cxSFilterBoxBlanksCaption, '(Порожні)'); // (Blanks)
cxSetResourceString(@cxSFilterBoxNonBlanksCaption, '(Не порожні)'); // (NonBlanks)
cxSetResourceString(@cxSFilterBoolOperatorAnd, 'І'); // AND
cxSetResourceString(@cxSFilterBoolOperatorOr, 'АБО'); // OR
cxSetResourceString(@cxSFilterBoolOperatorNotAnd, 'НЕ І'); // NOT AND
cxSetResourceString(@cxSFilterBoolOperatorNotOr, 'НЕ АБО'); // NOT OR
cxSetResourceString(@cxSFilterRootButtonCaption, 'Фільтр'); // Filter
cxSetResourceString(@cxSFilterAddCondition, 'Додати &Умову'); // Add &Condition
cxSetResourceString(@cxSFilterAddGroup, 'Додати &Групу'); // Add &Group
cxSetResourceString(@cxSFilterRemoveRow, '&Видалити Строку'); // &Remove Row
cxSetResourceString(@cxSFilterClearAll, 'Очистити &Все'); // Clear &All
cxSetResourceString(@cxSFilterFooterAddCondition, 'нажмите, чтобы добавить новое условие'); // press the button to add a new condition
cxSetResourceString(@cxSFilterGroupCaption, 'Применяет следующие условия'); // applies to the following conditions
cxSetResourceString(@cxSFilterRootGroupCaption, '<корень>'); // <root>
cxSetResourceString(@cxSFilterControlNullString, '<пусто>'); // <empty>
cxSetResourceString(@cxSFilterErrorBuilding, 'Невозможно создать фильтр из источника'); // Can't build filter from source
cxSetResourceString(@cxSFilterDialogCaption, 'Настройка фильтра'); // Custom Filter
cxSetResourceString(@cxSFilterDialogInvalidValue, 'Неверное значение'); // Invalid value
cxSetResourceString(@cxSFilterDialogUse, 'Использовать'); // Use
cxSetResourceString(@cxSFilterDialogSingleCharacter, 'для указания одного знака'); // to represent any single character
cxSetResourceString(@cxSFilterDialogCharactersSeries, 'для указания группы знаков'); // to represent any series of characters
cxSetResourceString(@cxSFilterDialogOperationAnd, 'И'); // AND
cxSetResourceString(@cxSFilterDialogOperationOr, 'ИЛИ'); // OR
cxSetResourceString(@cxSFilterDialogRows, 'Показать строки, для которых:'); // Show rows where:
cxSetResourceString(@cxSFilterControlDialogCaption, 'Построитель Фильтра'); // Filter builder
cxSetResourceString(@cxSFilterControlDialogNewFile, 'untitled.flt'); // untitled.flt
cxSetResourceString(@cxSFilterControlDialogOpenDialogCaption, 'Открыть существующий фильтр'); // Open an existing filter
cxSetResourceString(@cxSFilterControlDialogSaveDialogCaption, 'Сохранить активный фильтр в файл'); // Save the active filter to file
cxSetResourceString(@cxSFilterControlDialogActionSaveCaption, 'Со&хранить Как...'); // &Save As...
cxSetResourceString(@cxSFilterControlDialogActionOpenCaption, '&Загрузить...'); // &Open...
cxSetResourceString(@cxSFilterControlDialogActionApplyCaption, '&Применить'); // &Apply
cxSetResourceString(@cxSFilterControlDialogActionOkCaption, 'OK'); // OK
cxSetResourceString(@cxSFilterControlDialogActionCancelCaption, 'Отмена'); // Cancel
cxSetResourceString(@cxSFilterControlDialogFileExt, 'flt'); // flt
cxSetResourceString(@cxSFilterControlDialogFileFilter, 'Фильтры (*.flt)|*.flt'); // Filters (*.flt)|*.flt
//GridPopupMenu
cxSetResourceString(@cxSGridNone, 'Никакой'); // None
cxSetResourceString(@cxSGridSortColumnAsc, 'Сортировка по возрастанию'); // Sort Ascending
cxSetResourceString(@cxSGridSortColumnDesc, 'Сортировка по убыванию'); // Sort Descending
// cxSetResourceString(@cxSGridClearSorting, 'Убрать сортировку'); // Clear Sorting
cxSetResourceString(@cxSGridGroupByThisField, 'Группировать по этому полю'); // Group By This Field
cxSetResourceString(@cxSGridRemoveThisGroupItem, 'Убрать из группировки'); // Remove from grouping
cxSetResourceString(@cxSGridGroupByBox, 'Панель группировки'); // Group By Box
cxSetResourceString(@cxSGridAlignmentSubMenu, 'Выравнивание'); // Alignment
cxSetResourceString(@cxSGridAlignLeft, 'Выровнять по левой'); // Align Left
cxSetResourceString(@cxSGridAlignRight, 'Выровнять по правой'); // Align Right
cxSetResourceString(@cxSGridAlignCenter, 'Выровнять по центру'); // Align Center
cxSetResourceString(@cxSGridRemoveColumn, 'Удалить колонку'); // Remove This Column
cxSetResourceString(@cxSGridFieldChooser, 'Выбор поля'); // Field Chooser
cxSetResourceString(@cxSGridBestFit, 'Авто размещение'); // Best Fit
cxSetResourceString(@cxSGridBestFitAllColumns, 'Авто размещение (все колонки)'); // Best Fit (all columns)
cxSetResourceString(@cxSGridShowFooter, 'Панель итогов'); // Footer
cxSetResourceString(@cxSGridShowGroupFooter, 'Групировать панель итогов'); // Group Footers
cxSetResourceString(@cxSGridSumMenuItem, 'Сумма'); // Sum
cxSetResourceString(@cxSGridMinMenuItem, 'Минимум'); // Min
cxSetResourceString(@cxSGridMaxMenuItem, 'Максимум'); // Max
cxSetResourceString(@cxSGridCountMenuItem, 'Количество'); // Count
cxSetResourceString(@cxSGridAvgMenuItem, 'Среднее'); // Average
cxSetResourceString(@cxSGridNoneMenuItem, 'Нет'); // None
//GridExport
cxSetResourceString(@scxUnsupportedExport, 'Неподдерживаемый тип экспорта: %1'); // Unsupported export type: %1
cxSetResourceString(@scxStyleManagerKill, 'Style Manager в данный момент используется и не может быть освобожден'); // The Style Manager is currently being used elsewhere and can not be released at this stage
cxSetResourceString(@scxStyleManagerCreate, 'Невозможно создать style manager'); // Can't create style manager
cxSetResourceString(@scxExportToHtml, 'Экспорт в Web страницу (*.html)'); // Export to Web page (*.html)
cxSetResourceString(@scxExportToXml, 'Экспорт в XML документ (*.xml)'); // Export to XML document (*.xml)
cxSetResourceString(@scxExportToText, 'Экспорт в формат текста (*.txt)'); // Export to text format (*.txt)
cxSetResourceString(@scxEmptyExportCache, 'Кэш экспорта пуст'); // Export cache is empty
cxSetResourceString(@scxIncorrectUnion, 'Неверное объединение ячеек'); // Incorrect union of cells
cxSetResourceString(@scxIllegalWidth, 'Неверная ширина столбца'); // Illegal width of the column
cxSetResourceString(@scxInvalidColumnRowCount, 'Неверное количество строк или столбцов'); // Invalid column or row count
cxSetResourceString(@scxIllegalHeight, 'Неверная высота строки'); // Illegal height of the row
cxSetResourceString(@scxInvalidColumnIndex, 'Индекс столбца %d за пределами диапазона'); // The column index %d out of bounds
cxSetResourceString(@scxInvalidRowIndex, 'Индекс строки %d за пределами диапазона'); // The row index %d out of bounds
cxSetResourceString(@scxInvalidStyleIndex, 'Неверный индекс стиля %d'); // Invalid style index %d
cxSetResourceString(@scxExportToExcel, 'Экспорт в MS Excel (*.xls)'); // Export to MS Excel (*.xls)
cxSetResourceString(@scxWorkbookWrite, 'Ошибка записи XLS файла'); // Error write XLS file
cxSetResourceString(@scxInvalidCellDimension, 'Неверные размеры столбца'); // Invalid cell dimension
cxSetResourceString(@scxBoolTrue, 'True'); // True
cxSetResourceString(@scxBoolFalse, 'False'); // False
//cxNavigator
cxSetResourceString(@cxNavigatorHint_First, 'Первая запись'); // First record
cxSetResourceString(@cxNavigatorHint_Prior, 'Предыдущая запись'); // Prior record
cxSetResourceString(@cxNavigatorHint_PriorPage, 'Предыдущая страница'); // Prior page
cxSetResourceString(@cxNavigatorHint_Next, 'Следующая запись'); // Next record
cxSetResourceString(@cxNavigatorHint_NextPage, 'Следующая страница'); // Next page
cxSetResourceString(@cxNavigatorHint_Last, 'Последняя запись'); // Last record
cxSetResourceString(@cxNavigatorHint_Insert, 'Вставить запись'); // Insert record
cxSetResourceString(@cxNavigatorHint_Delete, 'Удалить запись'); // Delete record
cxSetResourceString(@cxNavigatorHint_Edit, 'Редактировать запись'); // Edit record
cxSetResourceString(@cxNavigatorHint_Post, 'Сохранить запись'); // Post edit
cxSetResourceString(@cxNavigatorHint_Cancel, 'Отменить редактирование'); // Cancel edit
cxSetResourceString(@cxNavigatorHint_Refresh, 'Обновить данные'); // Refresh data
cxSetResourceString(@cxNavigatorHint_SaveBookmark, 'Сохранить закладку'); // Save Bookmark
cxSetResourceString(@cxNavigatorHint_GotoBookmark, 'Перейти к закладке'); // Goto Bookmark
cxSetResourceString(@cxNavigatorHint_Filter, 'Фильтр данных'); // Filter data
cxSetResourceString(@cxNavigator_DeleteRecordQuestion, 'Удалить запись?'); // Delete record?
// dxBars5
cxSetResourceString(@dxSBAR_LOOKUPDIALOGCAPTION, 'Выберите значение'); // Select value
cxSetResourceString(@dxSBAR_LOOKUPDIALOGOK, 'OK'); // OK
cxSetResourceString(@dxSBAR_LOOKUPDIALOGCANCEL, 'Отмена'); // Cancel
cxSetResourceString(@dxSBAR_DIALOGOK, 'OK'); // OK
cxSetResourceString(@dxSBAR_DIALOGCANCEL, 'Отмена'); // Cancel
cxSetResourceString(@dxSBAR_COLOR_STR_0, 'Черный'); // Black
cxSetResourceString(@dxSBAR_COLOR_STR_1, 'Красно-коричневый'); // Maroon
cxSetResourceString(@dxSBAR_COLOR_STR_2, 'Зеленый'); // Green
cxSetResourceString(@dxSBAR_COLOR_STR_3, 'Оливковый'); // Olive
cxSetResourceString(@dxSBAR_COLOR_STR_4, 'Темно-синий'); // Navy
cxSetResourceString(@dxSBAR_COLOR_STR_5, 'Фиолетовый'); // Purple
cxSetResourceString(@dxSBAR_COLOR_STR_6, 'Телесный'); // Teal
cxSetResourceString(@dxSBAR_COLOR_STR_7, 'Серый'); // Gray
cxSetResourceString(@dxSBAR_COLOR_STR_8, 'Серебряный'); // Silver
cxSetResourceString(@dxSBAR_COLOR_STR_9, 'Красный'); // Red
cxSetResourceString(@dxSBAR_COLOR_STR_10, 'Ярко-зеленый'); // Lime
cxSetResourceString(@dxSBAR_COLOR_STR_11, 'Желтый'); // Yellow
cxSetResourceString(@dxSBAR_COLOR_STR_12, 'Голубой'); // Blue
cxSetResourceString(@dxSBAR_COLOR_STR_13, 'Фуксия'); // Fuchsia
cxSetResourceString(@dxSBAR_COLOR_STR_14, 'Аква'); // Aqua
cxSetResourceString(@dxSBAR_COLOR_STR_15, 'Белый'); // White
cxSetResourceString(@dxSBAR_COLORAUTOTEXT, '(автоматически)'); // (automatic)
cxSetResourceString(@dxSBAR_COLORCUSTOMTEXT, '(произвольно)'); // (custom)
cxSetResourceString(@dxSBAR_DATETODAY, 'Сегодня'); // Today
cxSetResourceString(@dxSBAR_DATECLEAR, 'Очистить'); // Clear
cxSetResourceString(@dxSBAR_DATEDIALOGCAPTION, 'Выберите дату'); // Select the date
cxSetResourceString(@dxSBAR_TREEVIEWDIALOGCAPTION, 'Выберите элемент'); // Select item
cxSetResourceString(@dxSBAR_IMAGEDIALOGCAPTION, 'Выберите элемент'); // Select item
cxSetResourceString(@dxSBAR_IMAGEINDEX, 'Индекс Изображения'); // Image Index
cxSetResourceString(@dxSBAR_IMAGETEXT, 'Текст'); // Text
cxSetResourceString(@dxSBAR_PLACEFORCONTROL, 'Место для'); // The place for the
cxSetResourceString(@dxSBAR_CANTASSIGNCONTROL, 'Вы не можете сопоставить один и тот же контрол более чем одному TdxBarControlContainerItem.'); // You cannot assign the same control to more than one TdxBarControlContainerItem.
cxSetResourceString(@dxSBAR_WANTTORESETTOOLBAR, 'Вы действительно хотите сбросить изменения панели ''%s'' ?'); // Are you sure you want to reset the changes made to the '%s' toolbar?
cxSetResourceString(@dxSBAR_WANTTORESETUSAGEDATA, 'Эта команда удалить все записи о командах, которые вы использовали в этом приложении, и восстановит настройки по умолчанию. Вы хотите продолжить?'); // This will delete the record of the commands you've used in this application and restore the default set of visible commands to the menus and toolbars. It will not undo any explicit customizations. Are you sure you want to proceed?
cxSetResourceString(@dxSBAR_BARMANAGERMORETHENONE, 'Форма должна содержать только один TdxBarManager'); // A Form should contain only a single TdxBarManager
cxSetResourceString(@dxSBAR_BARMANAGERBADOWNER, 'TdxBarManager должен иметь владельца - TForm (TCustomForm)'); // TdxBarManager should have as its Owner - TForm (TCustomForm)
cxSetResourceString(@dxSBAR_NOBARMANAGERS, 'Нет доступных TdxBarManagers'); // There are no TdxBarManagers available
cxSetResourceString(@dxSBAR_WANTTODELETETOOLBAR, 'Вы действительно хотите удалить панель ''%s''?'); // Are you sure you want to delete the '%s' toolbar?
cxSetResourceString(@dxSBAR_WANTTODELETECATEGORY, 'Вы действительно хотите удалить категорию ''%s''?'); // Are you sure you want to delete the '%s' category?
cxSetResourceString(@dxSBAR_WANTTOCLEARCOMMANDS, 'Вы действительно хотите удалить все команды в категории ''%s''?'); // Are you sure you want to delete all commands in the '%s' category?
cxSetResourceString(@dxSBAR_RECURSIVESUBITEMS, 'Вы не можете создавать рекурсивные подменю'); // You cannot create recursive subitems
cxSetResourceString(@dxSBAR_COMMANDNAMECANNOTBEBLANK, 'Имя команды не может быть пустым. Введите имя.'); // A command name cannot be blank. Please enter a name.
cxSetResourceString(@dxSBAR_TOOLBAREXISTS, 'Панель с именем ''%s'' уже существует. Введите другое имя.'); // A toolbar named '%s' already exists. Type another name.
cxSetResourceString(@dxSBAR_RECURSIVEGROUPS, 'Вы не можете создавать рекурсивные группы'); // You cannot create recursive groups
cxSetResourceString(@dxSBAR_DEFAULTCATEGORYNAME, 'По умолчанию'); // Default
cxSetResourceString(@dxSBAR_CP_ADDSUBITEM, 'Добавить &подменю'); // Add &SubItem
cxSetResourceString(@dxSBAR_CP_ADDBUTTON, 'Добавить &кнопку'); // Add &Button
cxSetResourceString(@dxSBAR_CP_ADDITEM, 'Добавить &объект'); // Add &Item
cxSetResourceString(@dxSBAR_CP_DELETEBAR, 'Удалить gанель'); // Delete Bar
cxSetResourceString(@dxSBAR_CP_RESET, 'С&брос'); // &Reset
cxSetResourceString(@dxSBAR_CP_DELETE, '&Удалить'); // &Delete
cxSetResourceString(@dxSBAR_CP_NAME, '&Имя:'); // &Name:
cxSetResourceString(@dxSBAR_CP_CAPTION, '&Заголовок:'); // &Caption:
cxSetResourceString(@dxSBAR_CP_DEFAULTSTYLE, '&Основной стиль'); // Defa&ult style
cxSetResourceString(@dxSBAR_CP_TEXTONLYALWAYS, 'Тол&ько текст (всегда)'); // &Text Only (Always)
cxSetResourceString(@dxSBAR_CP_TEXTONLYINMENUS, 'То&лько текст (в меню)'); // Text &Only (in Menus)
cxSetResourceString(@dxSBAR_CP_IMAGEANDTEXT, 'Картинка &и Текст'); // Image &and Text
cxSetResourceString(@dxSBAR_CP_BEGINAGROUP, 'Начать &группу'); // Begin a &Group
cxSetResourceString(@dxSBAR_CP_VISIBLE, '&Видимый'); // &Visible
cxSetResourceString(@dxSBAR_CP_MOSTRECENTLYUSED, '&Наиболее частро используемое'); // &Most recently used
cxSetResourceString(@dxSBAR_ADDEX, 'Добавить..'); // Add...
cxSetResourceString(@dxSBAR_RENAMEEX, 'Переименовать...'); // Rename...
cxSetResourceString(@dxSBAR_DELETE, 'Удалить'); // Delete
cxSetResourceString(@dxSBAR_CLEAR, 'Очистить'); // Clear
cxSetResourceString(@dxSBAR_VISIBLE, 'Видимый'); // Visible
cxSetResourceString(@dxSBAR_OK, 'OK'); // OK
cxSetResourceString(@dxSBAR_CANCEL, 'Отмена'); // Cancel
cxSetResourceString(@dxSBAR_SUBMENUEDITOR, 'Редактор ПодМеню...'); // SubMenu Editor...
cxSetResourceString(@dxSBAR_SUBMENUEDITORCAPTION, 'Редактор ПодМеню...'); // ExpressBars SubMenu Editor
cxSetResourceString(@dxSBAR_INSERTEX, 'Вставить...'); // Insert...
cxSetResourceString(@dxSBAR_MOVEUP, 'Переместить Вверх'); // Move Up
cxSetResourceString(@dxSBAR_MOVEDOWN, 'Переместить Вниз'); // Move Down
cxSetResourceString(@dxSBAR_POPUPMENUEDITOR, 'Редактор всплыающих меню...'); // PopupMenu Editor...
cxSetResourceString(@dxSBAR_TABSHEET1, 'Панели Инструментов'); // Toolbars
cxSetResourceString(@dxSBAR_TABSHEET2, 'Комманды'); // Commands
cxSetResourceString(@dxSBAR_TABSHEET3, 'Настройки'); // Options
cxSetResourceString(@dxSBAR_TOOLBARS, 'Панели &Инструментов:'); // Toolb&ars:
cxSetResourceString(@dxSBAR_TNEW, '&Новый...'); // &New...
cxSetResourceString(@dxSBAR_TRENAME, 'П&ереименовать...'); // R&ename...
cxSetResourceString(@dxSBAR_TDELETE, '&Удалить'); // &Delete
cxSetResourceString(@dxSBAR_TRESET, '&Сбросить...'); // &Reset...
cxSetResourceString(@dxSBAR_CLOSE, 'Закрыть'); // Close
cxSetResourceString(@dxSBAR_CAPTION, 'Настройка'); // Customize
cxSetResourceString(@dxSBAR_CATEGORIES, 'Кате&гории:'); // Cate&gories:
cxSetResourceString(@dxSBAR_COMMANDS, 'Комманд&ы:'); // Comman&ds:
cxSetResourceString(@dxSBAR_DESCRIPTION, 'Описание'); // Description
cxSetResourceString(@dxSBAR_CUSTOMIZE, '&Настроить...'); // &Customize...
cxSetResourceString(@dxSBAR_ADDREMOVEBUTTONS, '&Добавить или удалить кнопки'); // &Add or Remove Buttons
cxSetResourceString(@dxSBAR_MOREBUTTONS, 'Больше кнопок'); // More Buttons
cxSetResourceString(@dxSBAR_RESETTOOLBAR, '&Сбросить настройки'); // &Reset Toolbar
cxSetResourceString(@dxSBAR_EXPAND, 'Развернуть (Ctrl-Down)'); // Expand (Ctrl-Down)
cxSetResourceString(@dxSBAR_DRAGTOMAKEMENUFLOAT, 'Перетащите, чтобы сделать меню плавающим'); // Drag to make this menu float
cxSetResourceString(@dxSBAR_TOOLBARNEWNAME, 'Custom'); // Custom
cxSetResourceString(@dxSBAR_CATEGORYADD, 'Добавить категорию'); // Add Category
cxSetResourceString(@dxSBAR_CATEGORYINSERT, 'Вставить категорию'); // Insert Category
cxSetResourceString(@dxSBAR_CATEGORYRENAME, 'Переименовать категорию'); // Rename Category
cxSetResourceString(@dxSBAR_TOOLBARADD, 'Добавить панель инструментов'); // Add Toolbar
cxSetResourceString(@dxSBAR_TOOLBARRENAME, 'Переименовать панель'); // Rename Toolbar
cxSetResourceString(@dxSBAR_CATEGORYNAME, '&Имя категории:'); // &Category name:
cxSetResourceString(@dxSBAR_TOOLBARNAME, '&Имя панели:'); // &Toolbar name:
cxSetResourceString(@dxSBAR_CUSTOMIZINGFORM, 'Форма настройки...'); // Customization Form...
cxSetResourceString(@dxSBAR_MODIFY, '... изменить'); // ... modify
cxSetResourceString(@dxSBAR_PERSMENUSANDTOOLBARS, 'Мои настройки меню и панелей'); // Personalized Menus and Toolbars
cxSetResourceString(@dxSBAR_MENUSSHOWRECENTITEMS, '&Недавно использованные команды в Меню'); // Me&nus show recently used commands first
cxSetResourceString(@dxSBAR_SHOWFULLMENUSAFTERDELAY, 'Отображать п&олные меню просле небольшой задержки'); // Show f&ull menus after a short delay
cxSetResourceString(@dxSBAR_RESETUSAGEDATA, '&Сбросить мои настройки'); // &Reset my usage data
cxSetResourceString(@dxSBAR_OTHEROPTIONS, 'Другие'); // Other
cxSetResourceString(@dxSBAR_LARGEICONS, '&Большие иконки'); // &Large icons
cxSetResourceString(@dxSBAR_HINTOPT1, 'Показывать подсказки в панелях'); // Show Tool&Tips on toolbars
cxSetResourceString(@dxSBAR_HINTOPT2, 'Показывать клавиатурные комбинации в подсказках'); // Show s&hortcut keys in ToolTips
cxSetResourceString(@dxSBAR_MENUANIMATIONS, '&Анимация в меню:'); // &Menu animations:
cxSetResourceString(@dxSBAR_MENUANIM1, '(нет)'); // (None)
cxSetResourceString(@dxSBAR_MENUANIM2, 'Случайный выбор'); // Random
cxSetResourceString(@dxSBAR_MENUANIM3, 'Развертывание'); // Unfold
cxSetResourceString(@dxSBAR_MENUANIM4, 'Соскальзывание'); // Slide
cxSetResourceString(@dxSBAR_MENUANIM5, 'Угасание'); // Fade
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, uniGUITypes, uniGUIAbstractClasses,
uniGUIClasses, uniGUIRegClasses, uniGUIForm, Vcl.Menus, uniMainMenu, uniGUIFrame,
uniTreeView, uniLabel, uniGUIBaseClasses, uniPanel, Generics.Collections,
cfs.GCharts.uniGUI;
type
TModule = class
Level: Byte;
ClassName: string;
Title: string;
GoogleLink: string;
constructor Create(Level: Byte; const ClassName, Title, GoogleLink: string);
end;
TMainForm = class(TUniForm)
UniPanel2: TUniPanel;
UniLabel1: TUniLabel;
panCenter: TUniPanel;
UniPanel1: TUniPanel;
TreeView: TUniTreeView;
panFrame: TUniPanel;
UniLabel2: TUniLabel;
procedure UniFormCreate(Sender: TObject);
procedure UniFormDestroy(Sender: TObject);
procedure TreeViewClick(Sender: TObject);
procedure UniFormShow(Sender: TObject);
private
FSep: string;
FModules: TObjectList<TModule>;
FCurrentFrame: TuniFrame;
procedure LoadModules;
procedure LoadViewTree;
function LoadFrame(const Name: string): TUniFrame;
public
end;
function MainForm: TMainForm;
implementation
{$R *.dfm}
uses
uniGUIVars, MainModule, uniGUIApplication, Demo.BaseFrame;
{ TModule }
constructor TModule.Create(Level: Byte; const ClassName, Title, GoogleLink: string);
begin
Self.Level := Level;
Self.ClassName := ClassName;
Self.Title := Title;
Self.GoogleLink := GoogleLink;
end;
function MainForm: TMainForm;
begin
Result := TMainForm(UniMainModule.GetFormInstance(TMainForm));
end;
{ TMainForm }
procedure TMainForm.UniFormCreate(Sender: TObject);
begin
FModules := TObjectList<TModule>.Create;
FSep := ' ' + StringOfChar(Char($2501), 10);
LoadModules;
LoadViewTree;
end;
procedure TMainForm.UniFormDestroy(Sender: TObject);
begin
FModules.Free;
end;
procedure TMainForm.UniFormShow(Sender: TObject);
begin
TreeView.Selected := TreeView.Items[0];
LoadFrame('TDemo_Overview');
end;
procedure TMainForm.LoadModules;
procedure AddModule(Level: Byte; const ClassName, Title, GoogleLink: string);
begin
FModules.Add(TModule.Create(Level, ClassName, Title, GoogleLink));
end;
begin
AddModule(0, 'TDemo_Overview', 'Overview', 'https://developers.google.com/chart/interactive/docs');
AddModule(0, '', FSep, '');
AddModule(0, 'TDemo_AnnotationChart_Sample', 'Annotation', 'https://developers.google.com/chart/interactive/docs/gallery/annotationchart#overview');
AddModule(0, 'TDemo_AreaChart_Sample', 'Area', 'https://developers.google.com/chart/interactive/docs/gallery/areachart#a-simple-example');
AddModule(1, 'TDemo_AreaChart_Stacking', 'Stacked', 'https://developers.google.com/chart/interactive/docs/gallery/areachart#stacking-areas');
AddModule(0, 'TDemo_BarChart_Sample', 'Bar', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#overview');
AddModule(1, 'TDemo_BarChart_Series', 'Series', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#overview');
AddModule(1, 'TDemo_BarChart_Stacked', 'Stacked', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#overview');
AddModule(1, 'TDemo_BarChart_Stacking', 'Stacked vs Stacked 100%', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#stacked-bar-charts');
AddModule(1, 'TDemo_BarChart_Annotations', 'Annotations', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#overview');
AddModule(1, 'TDemo_BarChart_Customizable', 'Customizable', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#overview');
AddModule(1, 'TDemo_BarChart_BarStyles', 'Bar Styles', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#bar-styles');
AddModule(1, 'TDemo_BarChart_ColoringBars', 'Coloring Bars', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#coloring-bars');
AddModule(1, 'TDemo_BarChart_LabelingBars', 'Labeling Bars', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#labeling-bars');
AddModule(1, 'TDemo_MaterialBarChart_Sample', 'Material Design', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#creating-material-bar-charts');
AddModule(2, 'TDemo_MaterialBarChart_DualX', 'Dual X-axes', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#dual-x-charts');
AddModule(2, 'TDemo_MaterialBarChart_RightY', 'Right Y-axis', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#dual-x-charts');
AddModule(2, 'TDemo_MaterialBarChart_TopX', 'Top X', 'https://developers.google.com/chart/interactive/docs/gallery/barchart#top-x-charts');
AddModule(0, 'TDemo_BubbleChart_Sample', 'Bubble', 'https://developers.google.com/chart/interactive/docs/gallery/bubblechart#example');
AddModule(1, 'TDemo_BubbleChart_ColorByNumbers', 'Color By Numbers', 'https://developers.google.com/chart/interactive/docs/gallery/bubblechart#color-by-numbers');
AddModule(1, 'TDemo_BubbleChart_CustomizingLabels', 'Customizing Labels', ' https://developers.google.com/chart/interactive/docs/gallery/bubblechart#customizing-labels');
AddModule(0, 'TDemo_CalendarChart_Sample', 'Calendar', 'https://developers.google.com/chart/interactive/docs/gallery/calendar#a-simple-example');
AddModule(1, 'TDemo_CalendarChart_MultiLanguage', 'Language (uniSession)', 'https://developers.google.com/chart/interactive/docs/gallery/calendar#weeks');
AddModule(0, 'TDemo_CandlestickChart_Sample', 'Candlestick', 'https://developers.google.com/chart/interactive/docs/gallery/candlestickchart#overview');
AddModule(1, 'TDemo_CandlestickChart_Waterfall', 'Waterfall', 'https://developers.google.com/chart/interactive/docs/gallery/candlestickchart#waterfall-charts');
AddModule(0, 'TDemo_ColumnChart_Sample', 'Column', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#examples');
AddModule(1, 'TDemo_ColumnChart_Series', 'Series', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#examples');
AddModule(1, 'TDemo_ColumnChart_Stacked', 'Stacked', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#examples');
AddModule(1, 'TDemo_ColumnChart_Stacking', 'Stacked vs Stacked 100%', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#stacked-column-charts');
AddModule(1, 'TDemo_ColumnChart_Annotations', 'Annotations', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#examples');
AddModule(1, 'TDemo_ColumnChart_Customizable', 'Customizable', 'https://developers.google.com/chart/interactive/docs/gallery/ColumnChart#overview');
AddModule(1, 'TDemo_ColumnChart_Trendlines', 'Trendlines', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#examples');
AddModule(1, 'TDemo_ColumnChart_ColumnStyles', 'Column Styles', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#column-styles');
AddModule(1, 'TDemo_ColumnChart_ColoringColumns', 'Coloring Columns', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#coloring-columns');
AddModule(1, 'TDemo_ColumnChart_LabelingColumns', 'Labeling Columns', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#labeling-columns');
AddModule(1, 'TDemo_MaterialColumnChart_Sample', 'Material Design', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#creating-material-column-charts');
AddModule(2, 'TDemo_MaterialColumnChart_DualY', 'Dual Y-axes', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#dual-y-charts');
AddModule(2, 'TDemo_MaterialColumnChart_RightY', 'Right Y-axis', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#examples');
AddModule(2, 'TDemo_MaterialColumnChart_TopX', 'Top X', 'https://developers.google.com/chart/interactive/docs/gallery/columnchart#top-x-charts');
AddModule(0, 'TDemo_ComboChart_Sample', 'Combo', 'https://developers.google.com/chart/interactive/docs/gallery/combochart#example');
AddModule(0, 'TDemo_DiffChart_Pie', 'Diff', 'https://developers.google.com/chart/interactive/docs/gallery/diffchart#diff-pie-charts');
AddModule(1, 'TDemo_DiffChart_Column', 'Column', 'https://developers.google.com/chart/interactive/docs/gallery/diffchart#diff-bar-and-column-charts');
AddModule(0, 'TDemo_PieChart_Donut', 'Donut', 'https://developers.google.com/chart/interactive/docs/gallery/piechart#making-a-donut-chart');
AddModule(0, 'TDemo_GanttChart_Sample', 'Gantt', 'https://developers.google.com/chart/interactive/docs/gallery/ganttchart#a-simple-example');
AddModule(1, 'TDemo_GanttChart_NoDependencies', 'No Dependencies', 'https://developers.google.com/chart/interactive/docs/gallery/ganttchart#no-dependencies');
AddModule(1, 'TDemo_GanttChart_GroupingResources', 'Grouping Resources', 'https://developers.google.com/chart/interactive/docs/gallery/ganttchart#grouping-resources');
AddModule(1, 'TDemo_GanttChart_ComputingStartEndDuration', 'Computing start/end/duration', 'https://developers.google.com/chart/interactive/docs/gallery/ganttchart#computing-startendduration');
AddModule(1, 'TDemo_GanttChart_CriticalPath', 'Critical Path', 'https://developers.google.com/chart/interactive/docs/gallery/ganttchart#critical-path');
AddModule(1, 'TDemo_GanttChart_StylingArrows', 'Styling Arrows', 'https://developers.google.com/chart/interactive/docs/gallery/ganttchart#styling-arrows');
AddModule(1, 'TDemo_GanttChart_StylingTracks', 'Styling Tracks', 'https://developers.google.com/chart/interactive/docs/gallery/ganttchart#styling-tracks');
AddModule(0, 'TDemo_GaugeChart_Sample', 'Gauge', 'https://developers.google.com/chart/interactive/docs/gallery/gauge#example');
AddModule(0, 'TDemo_GeoChart_Sample', 'Geo', 'https://developers.google.com/chart/interactive/docs/gallery/geochart#region-geocharts');
AddModule(1, 'TDemo_GeoChart_Coloring', 'Coloring', 'https://developers.google.com/chart/interactive/docs/gallery/geochart#coloring-your-chart');
AddModule(1, 'TDemo_GeoChart_Marker', 'Marker', 'https://developers.google.com/chart/interactive/docs/gallery/geochart#marker-geocharts');
AddModule(1, 'TDemo_GeoChart_ProportionalMarkers', 'Proportional Markers', 'https://developers.google.com/chart/interactive/docs/gallery/geochart#displaying-proportional-markers');
AddModule(0, 'TDemo_Histogram_Sample', 'Histogram', 'https://developers.google.com/chart/interactive/docs/gallery/histogram#overview');
AddModule(1, 'TDemo_Histogram_MultipleSeries', 'Multiple Series', 'https://developers.google.com/chart/interactive/docs/gallery/histogram#multiple-series');
AddModule(0, 'TDemo_Intervals_Sample', 'Intervals', 'https://developers.google.com/chart/interactive/docs/gallery/intervals#overview');
AddModule(1, 'TDemo_Intervals_Styles', 'Styles', 'https://developers.google.com/chart/interactive/docs/gallery/intervals#overview');
AddModule(0, 'TDemo_LineChart_Sample', 'Line', 'https://developers.google.com/chart/interactive/docs/gallery/linechart#overview');
AddModule(1, 'TDemo_LineChart_Styles', 'Styles', 'https://developers.google.com/chart/interactive/docs/gallery/linechart#overview');
AddModule(1, 'TDemo_LineChart_Crosshairs', 'Crosshairs', 'https://developers.google.com/chart/interactive/docs/gallery/linechart#overview');
AddModule(1, 'TDemo_LineChart_TrendLines', 'Trend Lines', 'https://developers.google.com/chart/interactive/docs/gallery/linechart#overview');
AddModule(1, 'TDemo_LineChart_LogScales', 'Log Scales', 'https://developers.google.com/chart/interactive/docs/gallery/linechart#overview');
AddModule(1, 'TDemo_LineChart_CurvingLines', 'Curving the Lines', 'https://developers.google.com/chart/interactive/docs/gallery/linechart#curving-the-lines');
AddModule(1, 'TDemo_MaterialLineChart_Sample', 'Material Design', 'https://developers.google.com/chart/interactive/docs/gallery/linechart#creating-material-line-charts');
AddModule(2, 'TDemo_MaterialLineChart_TopX', 'Top X', 'https://developers.google.com/chart/interactive/docs/gallery/linechart#top-x-charts');
AddModule(2, 'TDemo_MaterialLineChart_DualY', 'Dual Y', 'https://developers.google.com/chart/interactive/docs/gallery/linechart#dual-y-charts');
AddModule(0, 'TDemo_OrgChart_Sample', 'Organization', 'https://developers.google.com/chart/interactive/docs/gallery/orgchart#example');
AddModule(0, 'TDemo_PieChart_Sample', 'Pie', 'https://developers.google.com/chart/interactive/docs/gallery/piechart#example');
AddModule(1, 'TDemo_PieChart_3D', '3D', 'https://developers.google.com/chart/interactive/docs/gallery/piechart#making-a-3d-pie-chart');
AddModule(1, 'TDemo_PieChart_Donut', 'Donut', 'https://developers.google.com/chart/interactive/docs/gallery/piechart#making-a-donut-chart');
AddModule(1, 'TDemo_PieChart_Rotating', 'Rotating', 'https://developers.google.com/chart/interactive/docs/gallery/piechart#rotating-a-pie-chart');
AddModule(1, 'TDemo_PieChart_Exploding_a_Slice', 'Exploding a Slice', 'https://developers.google.com/chart/interactive/docs/gallery/piechart#exploding-a-slice');
AddModule(1, 'TDemo_PieChart_Removing_Slices', 'Removing Slices', 'https://developers.google.com/chart/interactive/docs/gallery/piechart#removing-slices');
AddModule(0, 'TDemo_SankeyDiagram_Sample', 'Sankey Diagram', 'https://developers.google.com/chart/interactive/docs/gallery/sankey#a-simple-example');
AddModule(1, 'TDemo_SankeyDiagram_MultiLevels', 'Multilevel', 'https://developers.google.com/chart/interactive/docs/gallery/sankey#multilevel-sankeys');
AddModule(0, 'TDemo_ScatterChart_Sample', 'Scatter', 'https://developers.google.com/chart/interactive/docs/gallery/scatterchart#overview');
AddModule(1, 'TDemo_ScatterChart_DualY', 'Dual Y', 'https://developers.google.com/chart/interactive/docs/gallery/scatterchart#dual-y-charts');
AddModule(1, 'TDemo_MaterialScatterChart_Sample', 'Material Design', 'https://developers.google.com/chart/interactive/docs/gallery/scatterchart#creating-material-scatter-charts');
AddModule(2, 'TDemo_MaterialScatterChart_DualY', 'Dual Y', 'https://developers.google.com/chart/interactive/docs/gallery/scatterchart#dual-y-charts');
AddModule(2, 'TDemo_MaterialScatterChart_TopX', 'Top X', 'https://developers.google.com/chart/interactive/docs/gallery/scatterchart#top-x-charts');
AddModule(0, 'TDemo_SteppedAreaChart_Sample', 'Stepped Area', 'https://developers.google.com/chart/interactive/docs/gallery/steppedareachart#overview');
AddModule(1, 'TDemo_SteppedAreaChart_Custom', 'Custom', 'https://developers.google.com/chart/interactive/docs/gallery/steppedareachart#some-common-options');
AddModule(1, 'TDemo_AreaChart_Stacked', 'Stacked vs Stacked 100%', 'https://developers.google.com/chart/interactive/docs/gallery/steppedareachart#stacked-stepped-area-charts');
AddModule(0, 'TDemo_TableChart_Sample', 'Table', 'https://developers.google.com/chart/interactive/docs/gallery/table#overview');
AddModule(1, 'TDemo_Miscellaneous_Formatters', 'Formatters', 'https://developers.google.com/chart/interactive/docs/reference#arrowformat');
AddModule(0, 'TDemo_TimelineChart_Sample', 'Timeline', 'https://developers.google.com/chart/interactive/docs/gallery/timeline#a-simple-example');
AddModule(1, 'TDemo_TimelineChart_LabelingTheBars', 'Labeling the Bars', 'https://developers.google.com/chart/interactive/docs/gallery/timeline#labeling-the-bars');
AddModule(1, 'TDemo_TimelineChart_Advanced', 'Advanced example', 'https://developers.google.com/chart/interactive/docs/gallery/timeline#an-advanced-example');
AddModule(1, 'TDemo_TimelineChart_ClassroomSchedules', 'Classroom Schedules', 'https://developers.google.com/chart/interactive/docs/gallery/timeline#controlling-the-colors');
AddModule(2, 'TDemo_TimelineChart_ClassroomSchedulesCtrlColors', 'Controlling the colors', 'https://developers.google.com/chart/interactive/docs/gallery/timeline#controlling-the-colors');
AddModule(2, 'TDemo_TimelineChart_ClassroomSchedulesSingleColor', 'Single Color', 'https://developers.google.com/chart/interactive/docs/gallery/timeline#controlling-the-colors');
AddModule(0, 'TDemo_TreeMapChart_Sample', 'Tree Maps', 'https://developers.google.com/chart/interactive/docs/gallery/treemap#overview');
AddModule(0, 'TDemo_Trendlines_Sample', 'Trendlines', 'https://developers.google.com/chart/interactive/docs/gallery/trendlines');
AddModule(1, 'TDemo_Trendlines_Exponential', 'Exponential', 'https://developers.google.com/chart/interactive/docs/gallery/trendlines#exponential-trendlines');
AddModule(1, 'TDemo_Trendlines_Polynomial', 'Polynomial', 'https://developers.google.com/chart/interactive/docs/gallery/trendlines#polynomial-trendlines');
AddModule(0, 'TDemo_CandlestickChart_Waterfall', 'Waterfall', 'https://developers.google.com/chart/interactive/docs/gallery/candlestickchart#waterfall-charts');
AddModule(0, 'TDemo_WordTrees_Sample', 'Word Trees', 'https://developers.google.com/chart/interactive/docs/gallery/wordtree#a-simple-example');
AddModule(0, '', FSep, '');
AddModule(0, 'TDemo_Miscellaneous_Overlays', 'Customize Charts', 'https://developers.google.com/chart/interactive/docs/overlays#overview');
AddModule(1, 'TDemo_Miscellaneous_Animation', 'Animation', 'https://developers.google.com/chart/interactive/docs/animation#overview');
AddModule(1, 'TDemo_Miscellaneous_AxisNumberFormat', 'Axis Number Formats', 'https://developers.google.com/chart/interactive/docs/customizing_axes#number-formats');
AddModule(2, 'TDemo_Miscellaneous_AxisNumberFormatLang', 'Language (uniSession)', '');
AddModule(1, 'TDemo_Miscellaneous_DateTimes', 'Axis Dates & Times', 'https://developers.google.com/chart/interactive/docs/datesandtimes#formatting-axis,-gridline,-and-tick-labels');
AddModule(1, 'TDemo_Miscellaneous_AxisScale', 'Axis Scales', 'https://developers.google.com/chart/interactive/docs/customizing_axes#axis-scale');
AddModule(1, 'TDemo_Miscellaneous_Customize', 'Colors & Fonts', 'https://developers.google.com/chart/interactive/docs/customizing_charts');
AddModule(1, 'TDemo_Miscellaneous_Crosshairs', 'Crosshairs', 'https://developers.google.com/chart/interactive/docs/crosshairs#simple_example');
AddModule(1, 'TDemo_Miscellaneous_CustomizeLines', 'Lines', 'https://developers.google.com/chart/interactive/docs/lines#overview');
AddModule(1, 'TDemo_Miscellaneous_Formatters', 'Formatters', 'https://developers.google.com/chart/interactive/docs/reference#arrowformat');
AddModule(1, 'TDemo_Miscellaneous_CustomizePoints', 'Points', 'https://developers.google.com/chart/interactive/docs/points#overview');
AddModule(1, 'TDemo_Miscellaneous_CustomizeTooltips', 'Tooltips', 'https://developers.google.com/chart/interactive/docs/customizing_tooltip_content#customizing-tooltip-content');
end;
procedure TMainForm.LoadViewTree;
var
M: TModule;
Node: TUniTreeNode;
ChildNode1: TUniTreeNode;
ChildNode2: TUniTreeNode;
begin
Node := nil;
ChildNode1 := nil;
TreeView.BeginUpdate;
try
for M in FModules do
begin
if M.Level = 0 then
begin
Node := TreeView.Items.Add(nil, M.Title);
Node.ImageIndex := -1;
Node.Data := M;
Node.Font.Assign(TreeView.Font);
if M.Title = FSep then
Node.Font.Color := clSilver
else
Node.Font.Style := [fsBold];
end
else if (M.Level = 1) and (Node <> nil) then
begin
ChildNode1 := TreeView.Items.AddChild(Node, M.Title);
ChildNode1.ImageIndex := -1;
ChildNode1.Data := M;
end
else if (M.Level = 2) and (ChildNode1 <> nil) then
begin
ChildNode2 := TreeView.Items.AddChild(ChildNode1, M.Title);
ChildNode2.ImageIndex := -1;
ChildNode2.Data := M;
end;
end;
finally
TreeView.EndUpdate;
end;
end;
procedure TMainForm.TreeViewClick(Sender: TObject);
var
N : TUniTreeNode;
F: TUniFrame;
begin
N := TreeView.Selected;
if Assigned(N) and (N.Data <> nil) then
begin
if N.Text = FSep then
Exit;
if Assigned(FCurrentFrame) then
FreeAndNil(FCurrentFrame);
F := LoadFrame(TModule(N.Data).ClassName);
if Assigned(F) and (F is TDemoBaseFrame) then
(F as TDemoBaseFrame).GoogleGuideLink := TModule(N.Data).GoogleLink;
end;
end;
function TMainForm.LoadFrame(const Name: string): TUniFrame;
begin
Result := nil;
if Name = '' then
Exit;
if Assigned(FCurrentFrame) then
FreeAndNil(FCurrentFrame);
Result := TUniFrameClass(FindClass(Name)).Create(Self);
FCurrentFrame := Result;
Result.Parent := panFrame;
end;
initialization
RegisterAppFormClass(TMainForm);
end.
|
unit Func;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,shellapi,Shlobj,
Vcl.ExtCtrls;
function DelDir(dir: string): Boolean; // 함수 선언
function GetProgramFilesDir: String; // 함수 선언
implementation
uses unit1; //unit1
function GetProgramFilesDir: String;
const
CSIDL_LOCAL_APPDATA = $001c; // 해당 PC 의 Local Appdata 폴더를 찾아줌
var
pidl: PItemIDList;
Path: array [0..MAX_PATH-1] of char;
begin
if Succeeded(SHGetSpecialFolderLocation(Application.Handle, CSIDL_LOCAL_APPDATA, pidl)) then
begin
if SHGetPathFromIDList(pidl, Path) then
Result := StrPas(path);
end;
end;
function DelDir(dir: string): Boolean; //File 삭제 함수
var
fos: TSHFileOpStruct;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := FO_DELETE;
fFlags := FOF_SILENT or FOF_NOCONFIRMATION;
pFrom := PChar(dir + #0);
end;
Result := (0 = ShFileOperation(fos));
end;
end.
|
(*
MOUSE_RIGHT = 0
MOUSE_LEFT = 1
MOUSE_MIDDLE = 2
*)
Var
NAS_LastX, NAS_LastY: integer;
procedure GetMousePos(var x,y: Int32); override
begin
x:=NAS_LastX;
y:=NAS_LastY;
end;
procedure MoveMouse(x, y: Int32); override;
begin
NAS_LastX:=x;
NAS_LastY:=y;
User32.PostMessage(NAS.getGameClient(), WM_MOUSEMOVE, $00000000, MAKELPARAM(x, y));
end;
procedure ClickMouse(x, y, clickType: Int32); override;
begin
NAS_LastX:=x;
NAS_LastY:=y;
case clickType of
0: clickType := WM_RBUTTONDOWN;
1: clickType := WM_LBUTTONDOWN;
2: clickType := WM_MBUTTONDOWN;
end;
User32.PostMessage(NAS.getGameClient(), clickType, $00000001, MAKELPARAM(x, y)); //Down
sleep(20);
User32.PostMessage(NAS.getGameClient(), clickType+1, $00000000, MAKELPARAM(x, y)); //Up
end;
(*
Notes:
Scrolls at the given x/y, it does 'move' the mouse, but unreliable
Use Negative for Down scrolling, Positive for Upward.
EX: -1 will scroll down one 'click', 2 will scroll up two 'clicks'
*)
procedure ScrollMouse(x, y: Integer; Clicks: Integer); override
begin
NAS_LastX:=x;
NAS_LastY:=y;
User32.PostMessage(NAS.getGameClient(), $020A, MAKEWPARAM(0, Clicks*120), MAKELPARAM(x, y)); //Down
end;
(*
MOUSE_RIGHT = 0
MOUSE_LEFT = 1
MOUSE_MIDDLE = 2
*)
(*
Notes:
Does 'move' the mouse, but can be unreliable
*)
procedure HoldMouse(x, y: integer; clickType: integer); override;
begin
NAS_LastX:=x;
NAS_LastY:=y;
case clickType of
0: clickType := WM_RBUTTONDOWN;
1: clickType := WM_LBUTTONDOWN;
2: clickType := WM_MBUTTONDOWN;
end;
User32.PostMessage(NAS.getGameClient(), WM_MOUSEMOVE, $00000000, MAKELPARAM(x, y));
sleep(20);
User32.PostMessage(NAS.getGameClient(), clickType, $00000001, MAKELPARAM(x, y)); //Down
end;
(*
Notes:
Does 'move' the mouse, but can be unreliable
*)
procedure ReleaseMouse(x, y: integer; clickType: integer); override;
begin
NAS_LastX:=x;
NAS_LastY:=y;
case clickType of
0: clickType := WM_RBUTTONDOWN;
1: clickType := WM_LBUTTONDOWN;
2: clickType := WM_MBUTTONDOWN;
end;
User32.PostMessage(NAS.getGameClient(), WM_MOUSEMOVE, $00000000, MAKELPARAM(x, y));
sleep(20);
User32.PostMessage(NAS.getGameClient(), clickType+1, $00000000, MAKELPARAM(x, y)); //Up
end;
|
unit CrtInterface;
{
h = ScreenHeight
w = ScreenWidth
+--------------------------+
|(1, 1) Top panel +
+--------------------------+
|(1, 2) |
| @ |
| @ |
| Viewport |
| #@## |
| #$#$ @@#@$@$ |
|#$$##$ @ @#@$ |
+--------------------------+
|(1, h) Bottom panel |
+--------------------------+
}
interface
uses Game, Geometry;
type
WhichPanel = (Top, Bottom);
WhichPlace = (Left, Center, Right);
{ 2-byte interpretation of a single character on screen with
a color and bgcolor }
CharOnScreen = record
{ high 4 bits: background, low 4 bits: foreground }
colors: byte;
ch: char;
end;
ViewPort = record
{ Where in the battlefield the upper left-hand
corner of the viewport is}
origin: IntVector;
width, height: integer;
{ Screen buffer to make sure only necessary updates are made
and assure the minimal number of IO operations }
screen: array of array of CharOnScreen;
{ Flag }
needs_update: boolean;
{ Current position of the sight marker }
sight_marker: IntVector;
end;
ABInterface = record
width, height: integer;
view: ViewPort;
gc: pGameController;
{ Strings representing what is in 6 sections of panels }
paneltl, paneltc, paneltr, panelbl, panelbc, panelbr: ansistring;
{ Flags used by main program }
exitting, shooting: boolean;
{ Flags }
tpanel_needs_update, bpanel_needs_update: boolean;
player_bar_needs_update, wind_bar_needs_update, force_bar_needs_update, weapon_bar_needs_update: boolean;
{ The length of the current wind bar }
wind_bar: integer;
locked: boolean;
end;
procedure new_abinterface(var iface: ABInterface; gc: pGameController);
procedure iface_step(var iface: ABInterface);
procedure iface_change_player(var iface: ABInterface; p: integer);
implementation
uses Crt, Lists, Types, Physics, StaticConfig, SysUtils, BattleField,
{$ifdef LINUX}
termio, BaseUnix,
{$endif}
strutils, math;
const
{ Special keycodes }
ALeft = chr(75);
ARight = chr(77);
AUp = chr(72);
ADown = chr(80);
{ Normal keycodes }
Space = ' ';
Enter = chr(13);
Escape = chr(27);
{ Colors }
BurningColors: array[0..5] of integer = (4, 5, 6, 12, 13, 14);
Operator =(a, b: CharOnScreen) eq : boolean;
begin
eq := (a.colors = b.colors) and (a.ch = b.ch);
end;
{ Forward declarations }
procedure viewport_update_sight(var iface: ABInterface); forward;
procedure viewport_update_fields(var iface: ABInterface); forward;
procedure viewport_update_rockets(var iface: ABInterface); forward;
function sight_marker_pos(iface: ABInterface) : IntVector; forward;
procedure update_force_bar(var iface: ABInterface); forward;
procedure update_weapon_bar(var iface: ABInterface); forward;
procedure update_panel(var iface: ABInterface; w: WhichPanel); forward;
procedure count_wind_bar(var iface: ABInterface); forward;
procedure update_wind_bar(var iface: ABInterface); forward;
procedure update_players_bar(var iface: ABInterface); forward;
procedure iface_update(var iface: ABInterface); forward;
procedure iface_redraw(var iface: ABInterface); forward;
procedure iface_write_panel(var iface: ABInterface; pan: WhichPanel; place: WhichPlace; s: ansistring); forward;
procedure read_input(var iface: ABInterface); forward;
function render_field(var iface: ABInterface; p: IntVector) : CharOnScreen; forward;
function render_rocket(var iface: ABInterface; r: Rocket) : CharOnScreen; forward;
procedure revert_standard_colors; forward;
procedure ScreenSize(var x, y: integer); forward;
{ ************************ Viewport Section ************************ }
procedure new_viewport(var view: ViewPort; x, y: integer);
begin
view.origin := iv(x, y);
view.height := 0;
view.width := 0;
view.needs_update := True;
end;
{ Changes the size of viewport and resizes the buffer array, if necessary }
procedure resize_viewport(var view: ViewPort; w, h: integer);
begin
if (w > view.width) or (h > view.height) then
setlength(view.screen, w, h);
view.width := w; view.height := h;
end;
{ Checks if a point can be rendered in a viewport }
function field_in_viewport(var view: ViewPort; p: IntVector) : boolean;
begin
field_in_viewport := (p.x >= 0) and (p.x < view.width) and
(p.y >= 0) and (p.y < view.height);
end;
{ Finds the position of a point in the battlefield basing on
its position in the viewport }
function viewport_to_field_position(var view: ViewPort; p: IntVector) : IntVector;
begin
viewport_to_field_position := p + view.origin;
end;
{ Checks where to render a field whose position is (x, y) }
function field_to_viewport_position(var view: ViewPort; p: IntVector) : IntVector;
begin
field_to_viewport_position := p - view.origin;
end;
{ Changes the origin of a viewport }
procedure viewport_move(var view: ViewPort; offset: IntVector);
begin
view.origin := view.origin + offset;
view.needs_update := True;
end;
{ Prints a char to the screen }
procedure viewport_putchar(view: ViewPort; pos: IntVector; c: CharOnScreen);
begin
if field_in_viewport(view, pos) and (view.screen[pos.x, pos.y] <> c) then
begin
view.screen[pos.x, pos.y] := c;
GotoXY(pos.x + 1, pos.y + 2);
TextBackground(c.colors >> 4);
TextColor(c.colors and $0f);
write(c.ch);
end;
end;
{ Does a full redraw of the viewport part of screen }
procedure viewport_redraw(var iface: ABInterface);
var
c: CharOnScreen;
i, j: integer;
begin
c.ch := chr(255);
{ Clean screen buffer }
for j := 0 to iface.view.height - 1 do
for i := 0 to iface.view.width - 1 do
iface.view.screen[i, j] := c;
for j := 0 to iface.view.height - 1 do
begin
for i := 0 to iface.view.width - 1 do
begin
c := render_field(iface, iv(i, j));
viewport_putchar(iface.view, iv(i, j), c);
end;
end;
viewport_update_rockets(iface);
iface.view.needs_update := False;
end;
{ Updates the viewport selectively }
procedure viewport_update(var iface: ABInterface);
begin
viewport_update_fields(iface);
viewport_update_rockets(iface);
viewport_update_sight(iface);
end;
{ Redraws the fields which are being animated }
procedure viewport_update_fields(var iface: ABInterface);
var
cur: pIntVectorNode;
c: CharOnScreen;
pos_viewport: IntVector;
begin
cur := iface.gc^.pc^.animlist.head;
while cur <> nil do
begin
pos_viewport := field_to_viewport_position(iface.view, cur^.v);
c := render_field(iface, pos_viewport);
if gc_field_is_king(iface.gc^, cur^.v) then
iface.player_bar_needs_update := True;
viewport_putchar(iface.view, pos_viewport, c);
cur := cur^.next;
end;
GotoXY(1, 1);
end;
{ Redraws all rockets }
procedure viewport_update_rockets(var iface: ABInterface);
var
cur: pRocketNode;
c: CharOnScreen;
pos: IntVector;
begin
cur := iface.gc^.pc^.rockets.head;
while cur <> nil do
begin
pos := field_to_viewport_position(iface.view, iv(cur^.v.oldpos));
c := render_field(iface, pos);
viewport_putchar(iface.view, pos, c);
pos := field_to_viewport_position(iface.view, iv(cur^.v.position));
c := render_rocket(iface, cur^.v);
if not cur^.v.removed then
viewport_putchar(iface.view, pos, c);
cur := cur^.next;
end;
GotoXY(1,1);
end;
procedure viewport_update_sight(var iface: ABInterface);
var
oview_pos, nview_pos: IntVector;
c: CharOnScreen;
begin
oview_pos := field_to_viewport_position(iface.view, iface.view.sight_marker);
nview_pos := field_to_viewport_position(iface.view, sight_marker_pos(iface));
if oview_pos <> nview_pos then
begin
c := render_field(iface, oview_pos);
viewport_putchar(iface.view, oview_pos, c);
c := render_field(iface, nview_pos);
viewport_putchar(iface.view, nview_pos, c);
iface.view.sight_marker := sight_marker_pos(iface);
GotoXY(1,1);
end;
end;
{ Changes the angle of sight }
procedure viewport_move_sight(var iface: ABInterface; delta: double);
var
current_player: pPlayer;
begin
current_player := @iface.gc^.player[iface.gc^.current_player];
if gc_player_side(iface.gc^, iface.gc^.current_player) = FortLeft then
current_player^.angle := current_player^.angle - delta
else
current_player^.angle := current_player^.angle + delta;
end;
{ Calculates the position of sight marker }
function sight_marker_pos(iface: ABInterface) : IntVector;
var
current_player: pPlayer;
begin
current_player := @iface.gc^.player[iface.gc^.current_player];
sight_marker_pos := iv(fc(current_player^.cannon) +
v(cos(current_player^.angle) * SIGHT_LEN,
sin(current_player^.angle) * SIGHT_LEN));
end;
{ ************************ Interface Section ************************ }
procedure new_abinterface(var iface: ABInterface; gc: pGameController);
begin
new_viewport(iface.view, 0, 0);
iface.width := 0;
iface.height := 0;
iface.gc := gc;
iface.exitting := False;
iface.shooting := False;
iface.tpanel_needs_update := True;
iface.bpanel_needs_update := True;
iface.player_bar_needs_update := True;
iface.wind_bar_needs_update := True;
iface.force_bar_needs_update := True;
iface.view.sight_marker := sight_marker_pos(iface);
iface.wind_bar := 0;
iface.locked := False;
iface_step(iface);
viewport_move(iface.view, iv(
iface.gc^.pc^.field^.width div 2 - iface.view.width div 2,
iface.gc^.pc^.field^.height div 2 - iface.view.height div 2));
end;
{ Performs a single step of the interface processing loop }
procedure iface_step(var iface: ABInterface);
var
old_w, old_h: integer;
begin
old_w := iface.width;
old_h := iface.height;
ScreenSize(iface.width, iface.height);
count_wind_bar(iface);
if (old_w <> iface.width) or (old_h <> iface.height) then
begin
{ Recalculate viewport dimensions }
resize_viewport(iface.view, iface.width, iface.height - 2);
{ Redraw the whole screen }
iface_redraw(iface);
end
else if iface.view.needs_update then
viewport_redraw(iface)
else
{ Perform normal update }
iface_update(iface);
read_input(iface);
end;
{ Changes the player and updates what needs to be updated in such a case }
procedure iface_change_player(var iface: ABInterface; p: integer);
var
cp: pPlayer;
begin
gc_change_player(iface.gc^, p);
cp := @iface.gc^.player[iface.gc^.current_player];
iface.force_bar_needs_update := True;
iface.player_bar_needs_update := True;
if not gc_player_has_weapon(iface.gc^, iface.gc^.current_player, cp^.current_weapon) then
begin
cp^.current_weapon := 1;
while (cp^.current_weapon < 9) and
not gc_player_has_weapon(iface.gc^, iface.gc^.current_player, cp^.current_weapon) do
inc(cp^.current_weapon);
if not gc_player_has_weapon(iface.gc^, iface.gc^.current_player, cp^.current_weapon) then
cp^.current_weapon := 0;
end;
iface.weapon_bar_needs_update := True;
end;
procedure iface_change_force(var iface: ABInterface; delta: double);
var
current_player: pPlayer;
begin
current_player := @iface.gc^.player[iface.gc^.current_player];
current_player^.force := max(0, min(current_player^.max_force, current_player^.force + delta));
iface.force_bar_needs_update := True;
end;
procedure iface_change_weapon(var iface: ABInterface; w: integer);
var
current_player: pPlayer;
begin
current_player := @iface.gc^.player[iface.gc^.current_player];
if gc_player_has_weapon(iface.gc^, iface.gc^.current_player, w) then
begin
current_player^.current_weapon := w;
iface.weapon_bar_needs_update := True;
end;
end;
{ Redraws the whole screen }
procedure iface_redraw(var iface: ABInterface);
begin
revert_standard_colors;
viewport_redraw(iface);
{ Update the panels }
update_force_bar(iface);
update_wind_bar(iface);
update_weapon_bar(iface);
update_panel(iface, Top);
update_panel(iface, Bottom);
GotoXY(1, 1);
end;
procedure iface_update(var iface: ABInterface);
begin
revert_standard_colors;
viewport_update(iface);
if iface.wind_bar_needs_update then
update_wind_bar(iface);
if iface.player_bar_needs_update then
update_players_bar(iface);
if iface.force_bar_needs_update then
update_force_bar(iface);
if iface.weapon_bar_needs_update then
update_weapon_bar(iface);
if iface.tpanel_needs_update then
update_panel(iface, Top);
if iface.bpanel_needs_update then
update_panel(iface, Bottom);
end;
{ Conts the integer version of wind force used to represent wind in the interface }
procedure count_wind_bar(var iface: ABInterface);
var
old_wind: integer;
maxl: integer;
begin
old_wind := iface.wind_bar;
maxl := iface.width div 8;
if abs(iface.gc^.max_wind) = 0 then
iface.wind_bar := 0
else
iface.wind_bar := trunc(iface.gc^.pc^.wind.x / iface.gc^.max_wind * maxl);
if iface.wind_bar <> old_wind then
iface.wind_bar_needs_update := True;
end;
{ Rewrites the wind indicator }
procedure update_wind_bar(var iface: ABInterface);
var
i: integer;
s: ansistring;
maxl: integer;
begin
maxl := iface.width div 8;
s := 'Wind: ';
if iface.wind_bar > 0 then
begin
s := s + '[';
for i := 1 to maxl do
s := s + ' ';
s := s + '$4|$1';
for i := 1 to iface.wind_bar do
s := s + '>';
for i := 1 to maxl - iface.wind_bar do
s := s + ' ';
s := s + '$0]'
end
else
begin
s := s + '[$1';
for i := 1 to maxl + iface.wind_bar do
s := s + ' ';
for i := 1 to -iface.wind_bar do
s := s + '<';
s := s + '$4|$0';
for i := 1 to maxl do
s := s + ' ';
s := s + ']';
end;
iface_write_panel(iface, Top, Center, s);
iface.wind_bar_needs_update := False;
end;
{ Updates information about players - health and who is playing }
procedure update_players_bar(var iface: ABInterface);
var
pstring: ansistring;
pl: pPlayer;
i: integer;
begin
for i := 1 to 2 do
begin
pl := @iface.gc^.player[i];
if iface.gc^.player[i].won then
pstring := pl^.name + ' $4VICTORY!!!$0'
else
pstring := pl^.name + ' (' + IntToStr(gc_player_life(iface.gc^, i)) + ' hp)';
if i = iface.gc^.current_player then
pstring := '$4 > $0' + pstring + '$4 <$0 '
else
pstring := ' ' + pstring + ' ';
if gc_player_side(iface.gc^, i) = FortLeft then
iface_write_panel(iface, Top, Left, pstring)
else
iface_write_panel(iface, Top, Right, pstring);
end;
iface.player_bar_needs_update := False;
end;
procedure update_force_bar(var iface: ABInterface);
var
bar_len, bar_max_len: integer;
bar: ansistring;
current_player: pPlayer;
i: integer;
begin
current_player := @iface.gc^.player[iface.gc^.current_player];
bar_max_len := trunc(iface.width / 4);
bar_len := trunc(bar_max_len * current_player^.force / iface.gc^.max_force);
bar := 'Force: [';
for i := 1 to bar_len do
bar := bar + '=';
for i := bar_len + 1 to bar_max_len do
bar := bar + ' ';
bar := bar + ']';
iface_write_panel(iface, Bottom, Left, bar);
iface.force_bar_needs_update := False;
end;
procedure update_weapon_bar(var iface: ABInterface);
var
current_player: pPlayer;
w: pRocket;
s: ansistring;
begin
current_player := @iface.gc^.player[iface.gc^.current_player];
w := @current_player^.equipment[current_player^.current_weapon];
if gc_player_has_weapon(iface.gc^, iface.gc^.current_player, current_player^.current_weapon) then
begin
s := '[$1' + IntToStr(current_player^.current_weapon) + '$0] ' + w^.name;
s := s + ' r:' + FloatToStr(w^.exp_radius) + ' $4f:' + FloatToStr(w^.exp_force) + '$0';
if w^.num = -1 then
s := s + ' (inf)'
else
s := s + ' (' + IntToStr(w^.num) + ')';
end
else
s := 'No weapon :(';
iface_write_panel(iface, Bottom, Right, s);
iface.weapon_bar_needs_update := False;
end;
{ ************************ Panel Section ************************ }
{ Fills panel buffer, schedules panel update }
procedure iface_write_panel(var iface: ABInterface; pan: WhichPanel; place: WhichPlace; s: ansistring);
begin
if pan = Top then
begin
iface.tpanel_needs_update := True;
case place of
Left: iface.paneltl := s;
Center: iface.paneltc := s;
Right: iface.paneltr := s;
end;
end
else
begin
iface.bpanel_needs_update := True;
case place of
Left: iface.panelbl := s;
Center: iface.panelbc := s;
Right: iface.panelbr := s;
end;
end;
end;
{ Counts the width of a template (counts the characters omitting attribute change characters }
function template_width(t: ansistring) : integer;
var
len: integer;
i: integer;
begin
template_width := 0;
len := length(t);
i := 1;
while i <= len do
begin
if t[i] in ['$', '%'] then
i := i + 2
else if t[i] = '\' then
begin
inc(template_width);
i := i + 2
end
else
begin
inc(template_width);
inc(i);
end;
end;
end;
{ Renders the template to the screen }
procedure write_template(t: ansistring; char_limit: integer);
var
len: integer;
s: ansistring;
i: integer;
begin
len := length(t);
i := 1;
while (i <= len) and (char_limit <> 0) do
begin
case t[i] of
'$': begin
s := t[i+1];
TextColor(Hex2Dec(s));
i := i + 2;
end;
'%': begin
s := t[i+1];
TextBackground(Hex2Dec(s));
i := i + 2;
end;
'\': begin
write(t[i+i]);
dec(char_limit);
i := i + 2
end;
else begin
write(t[i]);
dec(char_limit);
inc(i);
end;
end;
end;
end;
{ Draws the whole panel to the screen }
procedure update_panel(var iface: ABInterface; w: WhichPanel);
var
i: integer;
pos_y: integer;
old_x, old_y: integer;
center_start, right_start: integer;
left, center, right: ^ansistring;
begin
old_x := WhereX;
old_y := WhereY;
if w = Top then
begin
pos_y := 1;
left := @iface.paneltl;
center := @iface.paneltc;
right := @iface.paneltr;
iface.tpanel_needs_update := False;
end
else
begin
pos_y := iface.height;
left := @iface.panelbl;
center := @iface.panelbc;
right := @iface.panelbr;
iface.bpanel_needs_update := False;
end;
GotoXY(1, pos_y);
TextBackground(LightGray);
TextColor(Black);
{ Fill the panel with white background }
for i := 1 to iface.width do
write(' ');
GotoXY(1, pos_y);
write_template(left^, iface.width);
center_start := max(1, (iface.width - template_width(center^)) div 2 + 1);
GotoXY(center_start, pos_y);
write_template(center^, iface.width - center_start + 1);
right_start := max(1, iface.width - template_width(right^) + 1);
GotoXY(right_start, pos_y);
write_template(right^, iface.width - right_start + 1);
revert_standard_colors;
GotoXY(old_x, old_y);
end;
{ ************************ Input Section ************************ }
procedure read_input(var iface: ABInterface);
var
c, prev: char;
i: integer;
begin
if not KeyPressed then
exit;
c := chr(255);
i := 0;
while KeyPressed do
begin
inc(i);
prev := c;
c := ReadKey;
end;
if prev = chr(0) then
begin
if not iface.locked then
case c of
AUp: viewport_move_sight(iface, 0.1);
ADown: viewport_move_sight(iface, -0.1);
ALeft: iface_change_force(iface, -0.5);
ARight: iface_change_force(iface, 0.5);
end
end
else
begin
case c of
Space: if not iface.locked then iface.shooting := True;
Escape: iface.exitting := True;
'w': viewport_move(iface.view, iv(0, -5));
'a': viewport_move(iface.view, iv(-5, 0));
's': viewport_move(iface.view, iv(0, 5));
'd': viewport_move(iface.view, iv(5, 0));
end;
if (c in ['1'..'9']) and not iface.locked then
iface_change_weapon(iface, ord(c) - ord('0'));
end;
end;
{ ************************ Character look Section ************************ }
{ Returns what char should be at position (x, y) relative to the origin of viewport
Takes into account also the sight marker, kings and castles }
function render_field(var iface: ABInterface; p: IntVector) : CharOnScreen;
var
field_pos: IntVector;
which: integer;
bg: shortint;
width, height: integer;
f: BFieldElement;
begin
width := iface.gc^.pc^.field^.width;
height := iface.gc^.pc^.field^.height;
field_pos := viewport_to_field_position(iface.view, p);
if field_pos = sight_marker_pos(iface) then
begin
render_field.ch := '+';
render_field.colors := (Black << 4) or Blue;
exit;
end;
if (field_pos.x < -1) or (field_pos.x > width) or
(field_pos.y < -1) or (field_pos.y > height) then
begin
render_field.ch := ' ';
render_field.colors := (Black << 4) or White;
exit;
end;
if ((field_pos.x = -1) or (field_pos.x = width) or (field_pos.y = height)) then
begin
render_field.ch := '%';
render_field.colors := (Black << 4) or Magenta;
exit;
end;
if (field_pos.y = -1) then
begin
render_field.ch := '-';
render_field.colors := (Black << 4) or DarkGray;
exit;
end;
f := iface.gc^.pc^.field^.arr[field_pos.x, field_pos.y];
if (field_pos = iface.gc^.player[1].cannon) or (field_pos = iface.gc^.player[2].cannon) then
begin
render_field.ch := 'C';
render_field.colors := (Red << 4) or White;
exit;
end;
if ((field_pos = iface.gc^.player[1].king) or (field_pos = iface.gc^.player[2].king)) and (f.current_hp <> 0) then
begin
render_field.ch := 'K';
render_field.colors := (Black << 4) or Blue;
exit;
end;
bg := (Black << 4);
which := trunc(f.current_hp);
if which = 0 then
begin
render_field.ch := ' ';
render_field.colors := (Black << 4) or White;
exit;
end;
render_field.ch := CH[min(10, (which div 15) + 1)];
if field_animated(iface.gc^.pc^, field_pos) and (f.hp < 40) and (f.hp < f.current_hp) then
render_field.colors := bg or BurningColors[random(6)]
else if f.owner > 0 then
render_field.colors := bg or iface.gc^.player[f.owner].color
else
begin
if which < 9 then
render_field.colors := bg or DarkGray
else
render_field.colors := bg or White;
end;
end;
function render_rocket(var iface: ABInterface; r: Rocket) : CharOnScreen;
begin
render_rocket.colors := (Black << 4) or LightRed;
render_rocket.ch := '@';
end;
{ ************************ Auxilliary Section ************************ }
procedure revert_standard_colors;
begin
TextBackground(Black);
TextColor(White);
end;
{ Check the terminal dimensions }
procedure ScreenSize(var x, y: integer);
{$ifdef LINUX}
var
tw: TWinSize;
begin
fpioctl(stdinputhandle, TIOCGWINSZ, @tw);
x := tw.ws_col;
y := tw.ws_row;
{$else}
begin
x := ScreenWidth;
y := ScreenHeight;
{$endif}
end;
begin
end.
|
{=======================================================================================================================
PanelsFrame Unit
Raize Components - Demo Program Source Unit
Copyright © 1995-2002 by Raize Software, Inc. All Rights Reserved.
=======================================================================================================================}
{$I RCDemo.inc}
unit TabsFrame;
interface
uses
Forms,
ImgList,
Controls,
RzTabs,
Graphics,
Classes,
RzBckgnd, StdCtrls, RzLabel, ExtCtrls, RzPanel, RzButton, RzRadChk,
RzRadGrp, Mask, RzEdit, RzBorder, RzCommon, RzSpnEdt, RzTrkBar;
type
TFmeTabs = class(TFrame)
ImageList1: TImageList;
pnlTabsSettings: TRzPanel;
RzSeparator1: TRzSeparator;
GrpTabStyle: TRzGroupBox;
GrpTabOrientation: TRzGroupBox;
btnSingleSlant: TRzToolButton;
btnDoubleSlant: TRzToolButton;
btnCutCorner: TRzToolButton;
btnRoundCorners: TRzToolButton;
optTop: TRzRadioButton;
optBottom: TRzRadioButton;
optLeft: TRzRadioButton;
optRight: TRzRadioButton;
optSingleSlant: TRzRadioButton;
optDoubleSlant: TRzRadioButton;
optCutCorner: TRzRadioButton;
optRoundCorners: TRzRadioButton;
RzPanel1: TRzPanel;
pgcPreview: TRzPageControl;
tabDates: TRzTabSheet;
tabFonts: TRzTabSheet;
tabNotes: TRzTabSheet;
tabSearch: TRzTabSheet;
tabPrint: TRzTabSheet;
grpTabSequence: TRzRadioGroup;
GrpImages: TRzGroupBox;
chkImages: TRzCheckBox;
grpImagePosition: TRzRadioGroup;
GrpHotTrack: TRzGroupBox;
grpHotTrackStyle: TRzRadioGroup;
edtHotTrackColor: TRzColorEdit;
RzLabel1: TRzLabel;
RzLabel2: TRzLabel;
RzLabel3: TRzLabel;
chkComplement: TRzCheckBox;
RzBorder1: TRzBorder;
RzCustomColors1: TRzCustomColors;
GrpTabColors: TRzGroupBox;
RzLabel4: TRzLabel;
edtHighlightBarColor: TRzColorEdit;
RzLabel5: TRzLabel;
edtShadowColor: TRzColorEdit;
RzLabel6: TRzLabel;
edtUnselectedColor: TRzColorEdit;
chkUseGradients: TRzCheckBox;
btnBackSlant: TRzToolButton;
optBackSlant: TRzRadioButton;
chkSoftCorners: TRzCheckBox;
pnlHeader: TRzPanel;
tabHighlighting: TRzTabSheet;
tabTemplates: TRzTabSheet;
tabAutoComplete: TRzTabSheet;
RzMenuController1: TRzMenuController;
btnSquareCorners: TRzToolButton;
optSquareCorners: TRzRadioButton;
trkTabOverlap: TRzTrackBar;
lblTabOverlap: TRzLabel;
lblTabOverlapValue: TRzLabel;
chkHorizontalText: TRzCheckBox;
chkMultiLine: TRzCheckBox;
RzLabel7: TRzLabel;
RzLabel8: TRzLabel;
chkColoredTabs: TRzCheckBox;
edtFrameColor: TRzColorEdit;
edtPageColor: TRzColorEdit;
RzLabel9: TRzLabel;
RzGroupBox1: TRzGroupBox;
chkShowCloseActiveTab: TRzCheckBox;
chkShowMenuButton: TRzCheckBox;
chkShowCloseButton: TRzCheckBox;
chkAllowTabDragging: TRzCheckBox;
RzLabel10: TRzLabel;
procedure btnTabStyleClick(Sender: TObject);
procedure optTabStyleClick(Sender: TObject);
procedure optTabOrientationClick(Sender: TObject);
procedure btnTabOrientationClick(Sender: TObject);
procedure chkImagesClick(Sender: TObject);
procedure grpTabSequenceClick(Sender: TObject);
procedure chkColoredTabsClick(Sender: TObject);
procedure chkMultiLineClick(Sender: TObject);
procedure chkHorizontalTextClick(Sender: TObject);
procedure grpImagePositionClick(Sender: TObject);
procedure grpHotTrackStyleClick(Sender: TObject);
procedure edtHotTrackColorChange(Sender: TObject);
procedure chkComplementClick(Sender: TObject);
procedure chkUseGradientsClick(Sender: TObject);
procedure edtHighlightBarColorChange(Sender: TObject);
procedure edtShadowColorChange(Sender: TObject);
procedure edtUnselectedColorChange(Sender: TObject);
procedure edtFrameColorChange(Sender: TObject);
procedure edtPageColorChange(Sender: TObject);
procedure chkSoftCornersClick(Sender: TObject);
procedure trkTabOverlapChange(Sender: TObject);
procedure pgcPreviewClose(Sender: TObject; var AllowClose: Boolean);
procedure chkShowCloseActiveTabClick(Sender: TObject);
procedure chkShowCloseButtonClick(Sender: TObject);
procedure chkShowMenuButtonClick(Sender: TObject);
procedure chkAllowTabDraggingClick(Sender: TObject);
private
{ Private declarations }
public
procedure Init;
procedure UpdateVisualStyle( VS: TRzVisualStyle; GCS: TRzGradientColorStyle );
end;
implementation
{$R *.dfm}
uses
SysUtils,
Dialogs,
Windows;
procedure TFmeTabs.Init;
begin
if UsingSystemStyle then
begin
//ParentBackground := False;
pnlTabsSettings.Color := DarkerColor( clBtnFace, 10 );
end;
end;
procedure TFmeTabs.UpdateVisualStyle( VS: TRzVisualStyle;
GCS: TRzGradientColorStyle );
begin
pnlHeader.VisualStyle := VS;
pnlHeader.GradientColorStyle := GCS;
RzMenuController1.GradientColorStyle := GCS;
end;
procedure TFmeTabs.btnTabStyleClick(Sender: TObject);
begin
case TRzToolButton( Sender ).Tag of
0: optSingleSlant.Checked := True;
1: optDoubleSlant.Checked := True;
2: optCutCorner.Checked := True;
3: optRoundCorners.Checked := True;
4: optBackSlant.Checked := True;
end;
end;
procedure TFmeTabs.optTabStyleClick(Sender: TObject);
begin
pgcPreview.TabStyle := TRzTabStyle( TRzRadioButton( Sender ).Tag );
chkSoftCorners.Enabled := pgcPreview.TabStyle in [ tsSingleSlant, tsDoubleSlant, tsBackSlant ];
lblTabOverlap.Enabled := not chkSoftCorners.Enabled;
trkTabOverlap.Enabled := not chkSoftCorners.Enabled;
lblTabOverlapValue.Enabled := not chkSoftCorners.Enabled;
pgcPreview.TabOverlap := -1; // reset TabOverlap to default value
trkTabOverlap.Position := -1;
end;
procedure TFmeTabs.btnTabOrientationClick(Sender: TObject);
begin
case TRzToolButton( Sender ).Tag of
0: optTop.Checked := True;
1: optLeft.Checked := True;
2: optBottom.Checked := True;
3: optRight.Checked := True;
end;
end;
procedure TFmeTabs.optTabOrientationClick(Sender: TObject);
begin
pgcPreview.TabOrientation := TRzTabOrientation( TRzRadioButton( Sender ).Tag );
case pgcPreview.TabOrientation of
toTop, toBottom:
begin
pgcPreview.TextOrientation := orHorizontal;
pgcPreview.ImagePosition := ipLeft;
end;
toLeft, toRight:
begin
pgcPreview.TextOrientation := orVertical;
if pgcPreview.TabOrientation = toRight then
pgcPreview.ImagePosition := ipTop
else
pgcPreview.ImagePosition := ipBottom;
end;
end;
ChkHorizontalText.Checked := pgcPreview.TextOrientation = orHorizontal;
GrpImagePosition.ItemIndex := Ord( pgcPreview.ImagePosition );
end;
procedure TFmeTabs.chkImagesClick(Sender: TObject);
begin
if ChkImages.Checked then
pgcPreview.Images := ImageList1
else
pgcPreview.Images := nil;
end;
procedure TFmeTabs.grpTabSequenceClick(Sender: TObject);
begin
pgcPreview.TabSequence := TRzTabSequence( GrpTabSequence.ItemIndex );
end;
procedure TFmeTabs.chkColoredTabsClick(Sender: TObject);
begin
if ChkColoredTabs.Checked then
begin
pgcPreview.UseColoredTabs := True;
tabDates.Color := RGB( 198, 213, 241 );
tabFonts.Color := RGB( 215, 207, 220 );
tabNotes.Color := RGB( 243, 231, 202 );
tabSearch.Color := RGB( 235, 211, 222 );
tabPrint.Color := RGB( 216, 243, 202 );
tabHighlighting.Color := RGB( 198, 213, 241 );
tabTemplates.Color := RGB( 215, 207, 220 );
tabAutoComplete.Color := RGB( 243, 231, 202 );
end
else
begin
pgcPreview.UseColoredTabs := False;
pgcPreview.Color := $00F5F6F7;
end;
end;
procedure TFmeTabs.chkMultiLineClick(Sender: TObject);
begin
pgcPreview.MultiLine := ChkMultiLine.Checked;
end;
procedure TFmeTabs.chkHorizontalTextClick(Sender: TObject);
begin
if ChkHorizontalText.Checked then
pgcPreview.TextOrientation := orHorizontal
else
pgcPreview.TextOrientation := orVertical;
end;
procedure TFmeTabs.grpImagePositionClick(Sender: TObject);
begin
pgcPreview.ImagePosition := TRzImagePosition( GrpImagePosition.ItemIndex );
end;
procedure TFmeTabs.grpHotTrackStyleClick(Sender: TObject);
begin
pgcPreview.HotTrackStyle := TRzTabHotTrackStyle ( GrpHotTrackStyle.ItemIndex );
ChkComplement.Enabled := GrpHotTrackStyle.ItemIndex = 0;
end;
procedure TFmeTabs.edtHotTrackColorChange(Sender: TObject);
begin
pgcPreview.HotTrackColor := EdtHotTrackColor.SelectedColor;
end;
procedure TFmeTabs.chkComplementClick(Sender: TObject);
begin
if ChkComplement.Checked then
pgcPreview.HotTrackColorType := htctComplement
else
pgcPreview.HotTrackColorType := htctActual;
end;
procedure TFmeTabs.chkUseGradientsClick(Sender: TObject);
begin
pgcPreview.UseGradients := ChkUseGradients.Checked;
end;
procedure TFmeTabs.edtHighlightBarColorChange(Sender: TObject);
begin
pgcPreview.TabColors.HighlightBar := EdtHighlightBarColor.SelectedColor;
end;
procedure TFmeTabs.edtShadowColorChange(Sender: TObject);
begin
pgcPreview.TabColors.Shadow := EdtShadowColor.SelectedColor;
end;
procedure TFmeTabs.edtUnselectedColorChange(Sender: TObject);
begin
pgcPreview.TabColors.Unselected := EdtUnselectedColor.SelectedColor;
end;
procedure TFmeTabs.edtFrameColorChange(Sender: TObject);
begin
pgcPreview.FlatColor := EdtFrameColor.SelectedColor;
end;
procedure TFmeTabs.edtPageColorChange(Sender: TObject);
begin
pgcPreview.Color := EdtPageColor.SelectedColor;
end;
procedure TFmeTabs.chkSoftCornersClick(Sender: TObject);
begin
pgcPreview.SoftCorners := chkSoftCorners.Checked;
end;
procedure TFmeTabs.trkTabOverlapChange(Sender: TObject);
begin
pgcPreview.TabOverlap := trkTabOverlap.Position;
lblTabOverlapValue.Caption := IntToStr( trkTabOverlap.Position );
end;
procedure TFmeTabs.pgcPreviewClose(Sender: TObject;
var AllowClose: Boolean);
begin
ShowMessage( 'Clicking the close button causes the OnClose event to be fired.'#13#13 +
'Within the OnClose event handler you can perform any processing ' +
'that should occur before the tab/page is closed. For example, this ' +
'message is being displayed from the OnClose event handler.'#13#13 +
'To actually close the active tab/page, simply set the AllowClose ' +
'parameter in the event handler to True.' );
end;
procedure TFmeTabs.chkShowCloseActiveTabClick(Sender: TObject);
begin
pgcPreview.ShowCloseButtonOnActiveTab := chkShowCloseActiveTab.Checked;
end;
procedure TFmeTabs.chkShowCloseButtonClick(Sender: TObject);
begin
pgcPreview.ShowCloseButton := chkShowCloseButton.Checked;
end;
procedure TFmeTabs.chkShowMenuButtonClick(Sender: TObject);
begin
pgcPreview.ShowMenuButton := chkShowMenuButton.Checked;
end;
procedure TFmeTabs.chkAllowTabDraggingClick(Sender: TObject);
begin
pgcPreview.AllowTabDragging := chkAllowTabDragging.Checked;
end;
end.
|
unit ZC4B.Get;
interface
uses
RESTRequest4D,
ZC4B.Interfaces,
System.JSON;
type
TZC4BGet = class(TInterfacedObject, iZC4BGet)
private
[weak]
FParent: iZC4B;
FContent : TJsonObject;
public
constructor Create(Parent: iZC4B);
destructor Destroy; override;
class function New(Parent: iZC4B): iZC4BGet;
function ZipCode(const aZipCode : string): iZC4BGet;
function ToJson: TJsonObject;
function &End: iZC4B;
end;
implementation
{ TZC4BGet }
function TZC4BGet.&End: iZC4B;
begin
result := FParent;
end;
constructor TZC4BGet.Create(Parent: iZC4B);
begin
FParent := Parent;
end;
destructor TZC4BGet.Destroy;
begin
inherited;
end;
function TZC4BGet.ToJson: TJSONObject;
begin
result := FContent;
end;
function TZC4BGet.ZipCode(const aZipCode : string): iZC4BGet;
var
LResponse: IResponse;
begin
result := Self;
LResponse:=
TRequest.New.BaseURL(FParent.Credential.BaseURL+'/'+aZipCode+'/json')
.ContentType('application/json')
.Accept('*/*')
.Get;
if LResponse.StatusCode = 200 then
FContent:= TJSONObject.ParseJSONValue(LResponse.Content) as TJSONObject;
end;
class function TZC4BGet.New(Parent: iZC4B): iZC4BGet;
begin
result := Self.Create(Parent);
end;
end.
|
function RemoveNumbers(const aString: string): string;
var
C: Char;
begin
Result := '';
for C in aString do
begin
if not CharInSet(C, ['0'..'9']) then
Result := Result + C;
end;
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: PaxCompiler.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PaxCompiler;
interface
uses {$I uses.def}
TypInfo,
SysUtils,
Classes,
PAXCOMP_CONSTANTS,
PAXCOMP_TYPES,
PAXCOMP_SYS,
PAXCOMP_KERNEL,
PAXCOMP_BASESYMBOL_TABLE,
PAXCOMP_PARSER,
PAXCOMP_PASCAL_PARSER,
PAXCOMP_OLE,
PAXCOMP_MODULE,
PAXCOMP_SYMBOL_REC,
PAXCOMP_TYPEINFO,
PAXCOMP_CLASSFACT,
PAXCOMP_BASERUNNER,
PaxRunner,
PaxRegister;
const
PLATFORM_Win32 = 1;
PLATFORM_Win64 = 2;
PLATFORM_OSX32 = 3;
PLATFORM_IOSsim = 4;
PLATFORM_IOSdev = 5;
PLATFORM_ANDROID = 6;
PLATFORM_LINUX32 = 7;
type
TPaxCompiler = class;
TPaxCompilerLanguage = class;
TPaxCompilerNotifyEvent = procedure (Sender: TPaxCompiler) of object;
TPaxCompilerUnitAliasEvent = procedure (Sender: TPaxCompiler;
var UnitName: String) of object;
TPaxCompilerUsedUnitEvent = function (Sender: TPaxCompiler; const UnitName: String;
var SourceCode: String): Boolean of object;
TPaxCompilerImportMemberEvent = procedure (Sender: TPaxCompiler;
Id: Integer;
const AFullName: String) of object;
TPaxCompilerSavePCUEvent = procedure (Sender: TPaxCompiler; const UnitName: String;
var result: TStream) of object;
TPaxCompilerLoadPCUEvent = procedure (Sender: TPaxCompiler; const UnitName: String;
var result: TStream) of object;
TPaxCompilerSavePCUFinishedEvent = procedure (Sender: TPaxCompiler; const UnitName: String; var Stream : TStream) of object; // jason
TPaxCompilerLoadPCUFinishedEvent = procedure(Sender: TPaxCompiler; const UnitName: String; var Stream : TStream) of object; // jason
TPaxCompilerDirectiveEvent = procedure (Sender: TPaxCompiler;
const Directive: String; var ok: Boolean) of object;
TPaxCompilerIncludeEvent = procedure (Sender: TPaxCompiler; const FileName: String;
var Text: String) of object;
TPaxCompilerUndeclaredIdentifierEvent = function (Sender: TPaxCompiler;
const IdentName: String;
var Scope: String;
var FullTypeName: String): boolean
of object;
TPaxCompilerCommentEvent = procedure (Sender: TPaxCompiler;
const Comment: String;
const Context: String;
CommentedTokens: TStrings) of object;
TPaxCompiler = class(TComponent)
private
kernel: TKernel;
function GetTargetPlatform: Integer;
procedure SetTargetPlatform(value: Integer);
procedure CreateMapping(Runner: TBaseRunner);
function GetErrorCount: Integer;
function GetErrorMessage(I: Integer): String;
function GetErrorModuleName(I: Integer): String;
function GetErrorLine(I: Integer): String;
function GetErrorLineNumber(I: Integer): Integer;
function GetErrorLinePos(I: Integer): Integer;
function GetErrorFileName(I: Integer): String;
function GetWarningCount: Integer;
function GetWarningMessage(I: Integer): String;
function GetWarningModuleName(I: Integer): String;
function GetWarningLine(I: Integer): String;
function GetWarningLineNumber(I: Integer): Integer;
function GetWarningLinePos(I: Integer): Integer;
function GetWarningFileName(I: Integer): String;
function GetOnCompilerProgress: TPaxCompilerNotifyEvent;
procedure SetOnCompilerProgress(value: TPaxCompilerNotifyEvent);
function GetOnUsedUnit: TPaxCompilerUsedUnitEvent;
procedure SetOnUsedUnit(value: TPaxCompilerUsedUnitEvent);
function GetOnImportUnit: TPaxCompilerImportMemberEvent;
procedure SetOnImportUnit(value: TPaxCompilerImportMemberEvent);
function GetOnImportType: TPaxCompilerImportMemberEvent;
procedure SetOnImportType(value: TPaxCompilerImportMemberEvent);
function GetOnImportGlobalMembers: TPaxCompilerNotifyEvent;
procedure SetOnImportGlobalMembers(value: TPaxCompilerNotifyEvent);
function GetOnUnitAlias: TPaxCompilerUnitAliasEvent;
procedure SetOnUnitAlias(value: TPaxCompilerUnitAliasEvent);
function GetOnSavePCU: TPaxCompilerSavePCUEvent;
procedure SetOnSavePCU(value: TPaxCompilerSavePCUEvent);
function GetOnLoadPCU: TPaxCompilerLoadPCUEvent;
procedure SetOnLoadPCU(value: TPaxCompilerLoadPCUEvent);
function GetOnInclude: TPaxCompilerIncludeEvent;
procedure SetOnInclude(value: TPaxCompilerIncludeEvent);
function GetOnDefineDirective: TPaxCompilerDirectiveEvent;
procedure SetOnDefineDirective(value: TPaxCompilerDirectiveEvent);
function GetOnUndefineDirective: TPaxCompilerDirectiveEvent;
procedure SetOnUndefineDirective(value: TPaxCompilerDirectiveEvent);
function GetOnUnknownDirective: TPaxCompilerDirectiveEvent;
procedure SetOnUnknownDirective(value: TPaxCompilerDirectiveEvent);
function GetOnUndeclaredIdentifier: TPaxCompilerUndeclaredIdentifierEvent;
procedure SetOnUndeclaredIdentifier(value: TPaxCompilerUndeclaredIdentifierEvent);
function GetOnComment: TPaxCompilerCommentEvent;
procedure SetOnComment(value: TPaxCompilerCommentEvent);
function GetDebugMode: Boolean;
procedure SetDebugMode(value: Boolean);
function GetCondDirectiveList: TStringList;
function GetSourceModule(const ModuleName: String): TStringList;
function GetCurrLineNumber: Integer;
function GetCurrModuleNumber: Integer;
function GetCurrModuleName: String;
function GetAlignment: Integer;
procedure SetAlignment(value: Integer);
function GetCurrLanguage: String;
procedure SetCurrLanguage(const value: String);
function GetNativeSEH: Boolean;
procedure SetNativeSEH(const value: Boolean);
function GetOnSavePCUFinished: TPaxCompilerSavePCUFinishedEvent; // jason
procedure SetOnSavePCUFinished(value: TPaxCompilerSavePCUFinishedEvent); // jason
function GetOnLoadPCUFinished: TPaxCompilerLoadPCUFinishedEvent; // jason
procedure SetOnLoadPCUFinished(value: TPaxCompilerLoadPCUFinishedEvent); // jason
function GetCompletionPrefix: String;
function GetUnicode: Boolean;
procedure SetUnicode(value: Boolean);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Reset;
procedure ResetCompilation;
procedure AddModule(const ModuleName, LanguageName: String);
procedure AddCode(const ModuleName, Text: String);
procedure AddCodeFromFile(const ModuleName, FileName: String);
procedure RegisterLanguage(L: TPaxCompilerLanguage);
procedure RegisterDirective(const Directive: string; const value: Variant);
function RegisterNamespace(LevelId: Integer;
const NamespaceName: String): Integer;
procedure RegisterUsingNamespace(const aNamespaceName: String); overload;
procedure RegisterUsingNamespace(aNamespaceID: Integer); overload;
procedure UnregisterUsingNamespace(aNamespaceID: Integer); overload;
procedure UnregisterUsingNamespaces;
procedure UnregisterUsingNamespace(const aNamespaceName: String); overload;
function RegisterInterfaceType(LevelId: Integer;
const TypeName: String;
const GUID: TGUID): Integer; overload;
function RegisterInterfaceType(LevelId: Integer;
const TypeName: String;
const GUID: TGUID;
const ParentName: String;
const ParentGUID: TGUID): Integer; overload;
procedure RegisterSupportedInterface(TypeId: Integer;
const SupportedInterfaceName: String;
const GUID: TGUID);
function RegisterClassType(LevelId: Integer;
const TypeName: String; AncestorId: Integer): Integer; overload;
function RegisterClassType(LevelId: Integer;
C: TClass): Integer; overload;
function RegisterClassReferenceType(LevelId: Integer;
const TypeName: String; OriginClassId: Integer): Integer;
function RegisterClassHelperType(LevelId: Integer;
const TypeName: String; OriginClassId: Integer): Integer; overload;
function RegisterClassHelperType(LevelID: Integer;
const TypeName, OriginalTypeName: String): Integer; overload;
function RegisterRecordHelperType(LevelId: Integer;
const TypeName: String; OriginRecordId: Integer): Integer; overload;
function RegisterRecordHelperType(LevelID: Integer;
const TypeName, OriginalTypeName: String): Integer; overload;
function RegisterClassTypeField(TypeId: Integer; const FieldName: String;
FieldTypeID: Integer; FieldShift: Integer = -1): Integer;
function RegisterProperty(LevelId: Integer; const PropName: String;
PropTypeID, ReadId, WriteId: Integer;
IsDefault: Boolean): Integer; overload;
function RegisterProperty(LevelId: Integer; const Header: String): Integer; overload;
function RegisterInterfaceProperty(LevelId: Integer;
const PropName: String;
PropTypeID,
ReadIndex,
WriteIndex: Integer): Integer;
function RegisterRecordType(LevelId: Integer;
const TypeName: String;
IsPacked: Boolean = false): Integer;
function RegisterRecordTypeField(TypeId: Integer; const FieldName: String;
FieldTypeID: Integer; FieldShift: Integer = -1): Integer;
function RegisterVariantRecordTypeField(TypeId: Integer; const FieldName: String;
FieldTypeID: Integer;
VarCount: Int64): Integer; overload;
function RegisterVariantRecordTypeField(LevelId: Integer; const Declaration: String;
VarCount: Int64): Integer; overload;
function RegisterSubrangeType(LevelId: Integer;
const TypeName: String;
TypeBaseId: Integer;
B1, B2: Integer): Integer;
function RegisterEnumType(LevelId: Integer;
const TypeName: String;
TypeBaseId: Integer = _typeINTEGER): Integer;
function RegisterEnumValue(EnumTypeId: Integer;
const FieldName: String;
const Value: Integer): Integer;
function RegisterArrayType(LevelId: Integer;
const TypeName: String;
RangeTypeId, ElemTypeId: Integer;
IsPacked: Boolean = false): Integer;
function RegisterDynamicArrayType(LevelId: Integer;
const TypeName: String;
ElemTypeId: Integer): Integer;
function RegisterPointerType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer;
const OriginTypeName: String = ''): Integer;
function RegisterMethodReferenceType(LevelId: Integer;
const TypeName: String;
SubId: Integer): Integer;
function RegisterSetType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer): Integer;
function RegisterProceduralType(LevelId: Integer;
const TypeName: String;
SubId: Integer): Integer;
{$IFNDEF PAXARM}
function RegisterShortStringType(LevelId: Integer;
const TypeName: String;
L: Integer): Integer;
{$ENDIF}
function RegisterEventType(LevelId: Integer;
const TypeName: String;
SubId: Integer): Integer;
function RegisterRTTIType(LevelId: Integer;
pti: PTypeInfo): Integer;
function RegisterTypeAlias(LevelId:Integer;
const TypeName: String;
OriginTypeId: Integer): Integer;
function RegisterVariable(LevelId: Integer;
const VarName: String; TypeId: Integer;
Address: Pointer = nil): Integer; overload;
function RegisterVariable(LevelId: Integer;
const Declaration: String; Address: Pointer): Integer; overload;
function RegisterObject(LevelId: Integer;
const ObjectName: String;
TypeId: Integer;
Address: Pointer = nil): Integer;
function RegisterVirtualObject(LevelId: Integer;
const ObjectName: String): Integer;
function RegisterConstant(LevelId: Integer;
const ConstName: String;
typeID: Integer;
const Value: Variant): Integer; overload;
function RegisterConstant(LevelId: Integer;
const ConstName: String;
const Value: Variant): Integer; overload;
function RegisterPointerConstant(LevelId: Integer;
const ConstName: String;
const Value: Pointer): Integer; overload;
function RegisterConstant(LevelId: Integer;
const ConstName: String;
const Value: Extended): Integer; overload;
function RegisterConstant(LevelId: Integer;
const ConstName: String;
const Value: Int64): Integer; overload;
function RegisterConstant(LevelId: Integer;
const Declaration: String): Integer; overload;
function RegisterRoutine(LevelId: Integer;
const RoutineName: String; ResultTypeID: Integer;
CallConvention: Integer;
Address: Pointer = nil): Integer; overload;
function RegisterRoutine(LevelId: Integer; const Name: String; ResultId: Integer;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
OverCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer; overload;
function RegisterRoutine(LevelId: Integer; const Name, ResultType: String;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
OverCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer; overload;
function RegisterMethod(LevelId: Integer;
const RoutineName: String; ResultTypeID: Integer;
CallConvention: Integer;
Address: Pointer = nil;
IsShared: Boolean = false): Integer; overload;
function RegisterMethod(ClassId: Integer;
const Name: String;
ResultId: Integer;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
IsShared: Boolean = false;
CallMode: Integer = _cmNONE;
MethodIndex: Integer = 0;
OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer; overload;
function RegisterMethod(ClassId: Integer;
const Name, ResultType: String;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
IsShared: Boolean = false;
CallMode: Integer = _cmNONE;
MethodIndex: Integer = 0;
OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer; overload;
function RegisterConstructor(ClassId: Integer;
const Name: String;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
IsShared: Boolean = false;
CallMode: Integer = cmNONE;
i_MethodIndex: Integer = 0;
OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
function RegisterDestructor(ClassId: Integer; const Name: String;
Address: Pointer): Integer;
function RegisterParameter(HSub: Integer; ParamTypeID: Integer;
const DefaultValue: Variant;
ByRef: Boolean = false): Integer; overload;
function RegisterParameter(LevelId: Integer;
const ParameterName: String;
ParamTypeID: Integer;
ParamMod: Integer = 0;
Optional: Boolean = false;
const DefaultValue: String = ''): Integer; overload;
function RegisterParameter(LevelId: Integer;
const ParameterName: String;
const ParameterType: String;
ParamMod: Integer = 0;
Optional: Boolean = false;
const DefaultValue: String = ''): Integer; overload;
function RegisterHeader(LevelId: Integer; const Header: String;
Address: Pointer = nil;
MethodIndex: Integer = 0): Integer;
function RegisterFakeHeader(LevelId: Integer;
const Header: String; Address: Pointer): Integer;
function RegisterTypeDeclaration(LevelId: Integer;
const Declaration: String): Integer;
function RegisterSomeType(LevelId: Integer;
const TypeName: String): Integer;
{$ifdef DRTTI}
procedure RegisterImportUnit(Level: Integer; const AUnitName: String);
{$endif}
function GetHandle(LevelId: Integer; const MemberName: String; Upcase: Boolean): Integer;
function Compile(APaxRunner: TPaxRunner;
BuildAll: Boolean = false;
BuildWithRuntimePackages: Boolean = false): boolean; overload;
function Compile: boolean; overload;
function Parse: boolean;
function CompileExpression(const Expression: String;
APaxRunner: TPaxRunner;
const LangName: String = ''): Boolean;
function CodeCompletion(const ModuleName: String;
X, Y: Integer; L: TStrings; PaxLang: TPaxCompilerLanguage = nil): Boolean;
function FindDeclaration(const ModuleName: String;
X, Y: Integer;
PaxLang: TPaxCompilerLanguage = nil): Integer;
function GetKernelPtr: Pointer;
procedure RegisterGlobalJSObjects(var R: TJS_Record);
function GetUndeclaredTypes: TStringList;
function GetUndeclaredIdentifiers: TStringList;
function LookupId(const FullName: String; UpCase: Boolean = true): Integer;
function LookupTypeId(const TypeName: String): Integer;
function LookupTypeNamespaceId(const TypeName: String): Integer;
function LookupNamespace(LevelId: Integer; const NamespaceName: String;
CaseSensitive: Boolean): Integer; overload;
function LookupNamespace(const NamespaceName: String): Integer; overload;
procedure AssignImportTable(ImportTable: Pointer);
function GetModuleName(Id: Integer): String;
function GetPosition(Id: Integer): Integer;
function GetKind(Id: Integer): Integer;
function GetEvalList: TStringList;
function InScript(const IdentName: String): Boolean;
procedure ExtendAlphabet(B1, B2: Word);
property ErrorCount: Integer read GetErrorCount;
property ErrorMessage[I: Integer]: String read GetErrorMessage;
property ErrorModuleName[I: Integer]: String read GetErrorModuleName;
property ErrorLine[I: Integer]: String read GetErrorLine;
property ErrorLineNumber[I: Integer]: Integer read GetErrorLineNumber;
property ErrorLinePos[I: Integer]: Integer read GetErrorLinePos;
property ErrorFileName[I: Integer]: String read GetErrorFileName;
property WarningCount: Integer read GetWarningCount;
property WarningMessage[I: Integer]: String read GetWarningMessage;
property WarningModuleName[I: Integer]: String read GetWarningModuleName;
property WarningLine[I: Integer]: String read GetWarningLine;
property WarningLineNumber[I: Integer]: Integer read GetWarningLineNumber;
property WarningLinePos[I: Integer]: Integer read GetWarningLinePos;
property WarningFileName[I: Integer]: String read GetWarningFileName;
property Modules[const ModuleName: String]: TStringList read GetSourceModule;
property CurrLineNumber: Integer read GetCurrLineNumber;
property CurrModuleNumber: Integer read GetCurrModuleNumber;
property CurrModuleName: String read GetCurrModuleName;
property CondDirectiveList: TStringList read GetCondDirectiveList;
property CurrLanguage: String read GetCurrLanguage write SetCurrLanguage;
property NativeSEH: Boolean read GetNativeSEH write SetNativeSEH;
property CompletionPrefix: String read GetCompletionPrefix;
property Unicode: Boolean read GetUnicode write SetUnicode;
property TargetPlatform: Integer read GetTargetPlatform write SetTargetPlatform;
published
property Alignment: Integer read GetAlignment write SetAlignment;
property OnCompilerProgress: TPaxCompilerNotifyEvent
read GetOnCompilerProgress write SetOnCompilerProgress;
property OnUnitAlias: TPaxCompilerUnitAliasEvent
read GetOnUnitAlias write SetOnUnitAlias;
property OnUsedUnit: TPaxCompilerUsedUnitEvent
read GetOnUsedUnit write SetOnUsedUnit;
property OnImportUnit: TPaxCompilerImportMemberEvent
read GetOnImportUnit write SetOnImportUnit;
property OnImportType: TPaxCompilerImportMemberEvent
read GetOnImportType write SetOnImportType;
property OnImportGlobalMembers: TPaxCompilerNotifyEvent
read GetOnImportGlobalMembers write SetOnImportGlobalMembers;
property OnSavePCU: TPaxCompilerSavePCUEvent
read GetOnSavePCU write SetOnSavePCU;
property OnLoadPCU: TPaxCompilerLoadPCUEvent
read GetOnLoadPCU write SetOnLoadPCU;
property OnInclude: TPaxCompilerIncludeEvent
read GetOnInclude write SetOnInclude;
property OnSavePCUFinished: TPaxCompilerSavePCUFinishedEvent
read GetOnSavePCUFinished write SetOnSavePCUFinished; // jason
property OnLoadPCUFinished: TPaxCompilerLoadPCUFinishedEvent
read GetOnLoadPCUFinished write SetOnLoadPCUFinished; // jason
property OnDefineDirective: TPaxCompilerDirectiveEvent
read GetOnDefineDirective write SetOnDefineDirective;
property OnUndefineDirective: TPaxCompilerDirectiveEvent
read GetOnUndefineDirective write SetOnUndefineDirective;
property OnUnknownDirective: TPaxCompilerDirectiveEvent
read GetOnUnknownDirective write SetOnUnknownDirective;
property OnUndeclaredIdentifier: TPaxCompilerUndeclaredIdentifierEvent
read GetOnUndeclaredIdentifier write SetOnUndeclaredIdentifier;
property OnComment: TPaxCompilerCommentEvent
read GetOnComment write SetOnComment;
property DebugMode: Boolean read GetDebugMode write SetDebugMode;
end;
TPaxCompilerLanguage = class(TComponent)
private
function GetCompleteBooleanEval: Boolean;
procedure SetCompleteBooleanEval(value: Boolean);
function GetPrintKeyword: String;
function GetPrintlnKeyword: String;
procedure SetPrintKeyword(const value: String);
procedure SetPrintlnKeyword(const value: String);
function GetUnitLookup: Boolean;
procedure SetUnitLookup(value: Boolean);
function GetExplicitOff: Boolean;
procedure SetExplicitOff(value: Boolean);
function GetInitFuncResult: Boolean;
procedure SetInitFuncResult(value: Boolean);
protected
P: TBaseParser;
function GetLanguageName: String; virtual; abstract;
function GetParser: TBaseParser; virtual; abstract;
property ExplicitOff: Boolean read GetExplicitOff write SetExplicitOff;
property CompleteBooleanEval: Boolean read GetCompleteBooleanEval write SetCompleteBooleanEval;
property PrintKeyword: String read GetPrintKeyword write SetPrintKeyword;
property PrintlnKeyword: String read GetPrintlnKeyword write SetPrintlnKeyword;
property UnitLookup: Boolean read GetUnitLookup write SetUnitLookup;
public
destructor Destroy; override;
procedure SetCallConv(CallConv: Integer); virtual; abstract;
property LanguageName: String read GetLanguageName;
property InitFuncResult: Boolean read GetInitFuncResult write SetInitFuncResult;
end;
TPaxCompilerLanguageClass = class of TPaxCompilerLanguage;
TPaxPascalLanguage = class;
TPaxParserNotifyEvent = procedure(Sender: TPaxPascalLanguage) of object;
TPaxParserIdentEvent = procedure(Sender: TPaxPascalLanguage;
const IdentName: String; Id: Integer) of object;
TPaxParserIdentEventEx = procedure(Sender: TPaxPascalLanguage;
const IdentName: String; Id: Integer; const Declaration: String) of object;
TPaxParserNamedValueEvent = procedure(Sender: TPaxPascalLanguage;
const IdentName: String; Id: Integer; const Value: Variant;
const Declaration: String) of object;
TPaxParserTypedIdentEvent = procedure(Sender: TPaxPascalLanguage;
const IdentName: String; Id: Integer; const TypeName: String;
const Declaration: String) of object;
TPaxParserVariantRecordFieldEvent = procedure(Sender: TPaxPascalLanguage;
const IdentName: String; Id: Integer; const TypeName: String; VarCount: Int64;
const Declaration: String) of object;
TPaxParserNamedTypedValueEvent = procedure(Sender: TPaxPascalLanguage;
const IdentName: String; Id: Integer; const TypeName: String;
const DefaultValue: String;
const Declaration: String) of object;
TPaxParserDeclarationEvent = procedure(Sender: TPaxPascalLanguage;
const IdentName: String; Id: Integer; const Declaration: String) of object;
TPaxParserArrayTypeEvent = procedure(Sender: TPaxPascalLanguage;
const IdentName: String; Id: Integer;
Ranges: TStringList;
const ElemTypeName: String) of object;
TPaxPascalLanguage = class(TPaxCompilerLanguage)
private
function GetOnParseUnitName: TPaxParserIdentEvent;
procedure SetOnParseUnitName(value: TPaxParserIdentEvent);
function GetOnParseImplementationSection: TPaxParserNotifyEvent;
procedure SetOnParseImplementationSection(value: TPaxParserNotifyEvent);
function GetOnParseBeginUsedUnitList: TPaxParserNotifyEvent;
procedure SetOnParseBeginUsedUnitList(value: TPaxParserNotifyEvent);
function GetOnParseEndUsedUnitList: TPaxParserNotifyEvent;
procedure SetOnParseEndUsedUnitList(value: TPaxParserNotifyEvent);
function GetOnParseUsedUnitName: TPaxParserIdentEvent;
procedure SetOnParseUsedUnitName(value: TPaxParserIdentEvent);
function GetOnParseBeginClassTypeDeclaration: TPaxParserIdentEventEx;
procedure SetOnParseBeginClassTypeDeclaration(value: TPaxParserIdentEventEx);
function GetOnParseEndClassTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseEndClassTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseForwardTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseForwardTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseAncestorTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseAncestorTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseUsedInterface: TPaxParserIdentEvent;
procedure SetOnParseUsedInterface(value: TPaxParserIdentEvent);
function GetOnParseClassReferenceTypeDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParseClassReferenceTypeDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParseAliasTypeDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParseAliasTypeDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParseProceduralTypeDeclaration: TPaxParserIdentEventEx;
procedure SetOnParseProceduralTypeDeclaration(value: TPaxParserIdentEventEx);
function GetOnParseEventTypeDeclaration: TPaxParserIdentEventEx;
procedure SetOnParseEventTypeDeclaration(value: TPaxParserIdentEventEx);
function GetOnParseMethodReferenceTypeDeclaration: TPaxParserIdentEventEx;
procedure SetOnParseMethodReferenceTypeDeclaration(value: TPaxParserIdentEventEx);
function GetOnParseSetTypeDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParseSetTypeDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParsePointerTypeDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParsePointerTypeDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParseArrayTypeDeclaration: TPaxParserArrayTypeEvent;
procedure SetOnParseArrayTypeDeclaration(value: TPaxParserArrayTypeEvent);
function GetOnParseDynArrayTypeDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParseDynArrayTypeDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParseShortStringTypeDeclaration: TPaxParserNamedValueEvent;
procedure SetOnParseShortStringTypeDeclaration(value: TPaxParserNamedValueEvent);
function GetOnParseSubrangeTypeDeclaration: TPaxParserDeclarationEvent;
procedure SetOnParseSubrangeTypeDeclaration(value: TPaxParserDeclarationEvent);
function GetOnParseBeginRecordTypeDeclaration: TPaxParserIdentEventEx;
procedure SetOnParseBeginRecordTypeDeclaration(value: TPaxParserIdentEventEx);
function GetOnParseEndRecordTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseEndRecordTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseBeginClassHelperTypeDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParseBeginClassHelperTypeDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParseEndClassHelperTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseEndClassHelperTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseBeginRecordHelperTypeDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParseBeginRecordHelperTypeDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParseEndRecordHelperTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseEndRecordHelperTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseBeginInterfaceTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseBeginInterfaceTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseEndInterfaceTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseEndInterfaceTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseBeginEnumTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseBeginEnumTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseEndEnumTypeDeclaration: TPaxParserIdentEvent;
procedure SetOnParseEndEnumTypeDeclaration(value: TPaxParserIdentEvent);
function GetOnParseEnumName: TPaxParserNamedValueEvent;
procedure SetOnParseEnumName(value: TPaxParserNamedValueEvent);
function GetOnParseFieldDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParseFieldDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParseVariantRecordFieldDeclaration: TPaxParserVariantRecordFieldEvent;
procedure SetOnParseVariantRecordFieldDeclaration(value: TPaxParserVariantRecordFieldEvent);
function GetOnParsePropertyDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParsePropertyDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParseConstantDeclaration: TPaxParserNamedValueEvent;
procedure SetOnParseConstantDeclaration(value: TPaxParserNamedValueEvent);
function GetOnParseResourceStringDeclaration: TPaxParserNamedValueEvent;
procedure SetOnParseResourceStringDeclaration(value: TPaxParserNamedValueEvent);
function GetOnParseTypedConstantDeclaration: TPaxParserNamedTypedValueEvent;
procedure SetOnParseTypedConstantDeclaration(value: TPaxParserNamedTypedValueEvent);
function GetOnParseVariableDeclaration: TPaxParserTypedIdentEvent;
procedure SetOnParseVariableDeclaration(value: TPaxParserTypedIdentEvent);
function GetOnParseBeginSubDeclaration: TPaxParserIdentEvent;
procedure SetOnParseBeginSubDeclaration(value: TPaxParserIdentEvent);
function GetOnParseEndSubDeclaration: TPaxParserDeclarationEvent;
procedure SetOnParseEndSubDeclaration(value: TPaxParserDeclarationEvent);
function GetOnParseBeginFormalParameterList: TPaxParserNotifyEvent;
procedure SetOnParseBeginFormalParameterList(value: TPaxParserNotifyEvent);
function GetOnParseEndFormalParameterList: TPaxParserNotifyEvent;
procedure SetOnParseEndFormalParameterList(value: TPaxParserNotifyEvent);
function GetOnParseFormalParameterDeclaration: TPaxParserNamedTypedValueEvent;
procedure SetOnParseFormalParameterDeclaration(value: TPaxParserNamedTypedValueEvent);
function GetOnParseResultType: TPaxParserIdentEvent;
procedure SetOnParseResultType(value: TPaxParserIdentEvent);
function GetOnParseSubDirective: TPaxParserIdentEvent;
procedure SetOnParseSubDirective(value: TPaxParserIdentEvent);
protected
function GetParser: TBaseParser; override;
public
constructor Create(AOwner: TComponent); override;
procedure SetCallConv(CallConv: Integer); override;
function GetLanguageName: String; override;
property OnParseUnitName: TPaxParserIdentEvent read GetOnParseUnitName
write SetOnParseUnitName;
property OnParseImplementationSection: TPaxParserNotifyEvent read GetOnParseImplementationSection
write SetOnParseImplementationSection;
property OnParseBeginUsedUnitList: TPaxParserNotifyEvent read GetOnParseBeginUsedUnitList
write SetOnParseBeginUsedUnitList;
property OnParseEndUsedUnitList: TPaxParserNotifyEvent read GetOnParseEndUsedUnitList
write SetOnParseEndUsedUnitList;
property OnParseUsedUnitName: TPaxParserIdentEvent read GetOnParseUsedUnitName
write SetOnParseUsedUnitName;
property OnParseTypeDeclaration: TPaxParserIdentEvent read GetOnParseTypeDeclaration
write SetOnParseTypeDeclaration;
property OnParseForwardTypeDeclaration: TPaxParserIdentEvent read GetOnParseForwardTypeDeclaration
write SetOnParseForwardTypeDeclaration;
property OnParseBeginClassTypeDeclaration: TPaxParserIdentEventEx read GetOnParseBeginClassTypeDeclaration
write SetOnParseBeginClassTypeDeclaration;
property OnParseEndClassTypeDeclaration: TPaxParserIdentEvent read GetOnParseEndClassTypeDeclaration
write SetOnParseEndClassTypeDeclaration;
property OnParseAncestorTypeDeclaration: TPaxParserIdentEvent read GetOnParseAncestorTypeDeclaration
write SetOnParseAncestorTypeDeclaration;
property OnParseUsedInterface: TPaxParserIdentEvent read GetOnParseUsedInterface
write SetOnParseUsedInterface;
property OnParseClassReferenceTypeDeclaration: TPaxParserTypedIdentEvent read GetOnParseClassReferenceTypeDeclaration
write SetOnParseClassReferenceTypeDeclaration;
property OnParseAliasTypeDeclaration: TPaxParserTypedIdentEvent read GetOnParseAliasTypeDeclaration
write SetOnParseAliasTypeDeclaration;
property OnParseProceduralTypeDeclaration: TPaxParserIdentEventEx read GetOnParseProceduralTypeDeclaration
write SetOnParseProceduralTypeDeclaration;
property OnParseEventTypeDeclaration: TPaxParserIdentEventEx read GetOnParseEventTypeDeclaration
write SetOnParseEventTypeDeclaration;
property OnParseMethodReferenceTypeDeclaration: TPaxParserIdentEventEx read GetOnParseMethodReferenceTypeDeclaration
write SetOnParseMethodReferenceTypeDeclaration;
property OnParseSetTypeDeclaration: TPaxParserTypedIdentEvent read GetOnParseSetTypeDeclaration
write SetOnParseSetTypeDeclaration;
property OnParsePointerTypeDeclaration: TPaxParserTypedIdentEvent read GetOnParsePointerTypeDeclaration
write SetOnParsePointerTypeDeclaration;
property OnParseArrayTypeDeclaration: TPaxParserArrayTypeEvent read GetOnParseArrayTypeDeclaration
write SetOnParseArrayTypeDeclaration;
property OnParseDynArrayTypeDeclaration: TPaxParserTypedIdentEvent read GetOnParseDynArrayTypeDeclaration
write SetOnParseDynArrayTypeDeclaration;
property OnParseShortStringTypeDeclaration: TPaxParserNamedValueEvent read GetOnParseShortStringTypeDeclaration
write SetOnParseShortStringTypeDeclaration;
property OnParseSubrangeTypeDeclaration: TPaxParserDeclarationEvent read GetOnParseSubrangeTypeDeclaration
write SetOnParseSubrangeTypeDeclaration;
property OnParseBeginRecordTypeDeclaration: TPaxParserIdentEventEx read GetOnParseBeginRecordTypeDeclaration
write SetOnParseBeginRecordTypeDeclaration;
property OnParseEndRecordTypeDeclaration: TPaxParserIdentEvent read GetOnParseEndRecordTypeDeclaration
write SetOnParseEndRecordTypeDeclaration;
property OnParseBeginClassHelperTypeDeclaration: TPaxParserTypedIdentEvent read GetOnParseBeginClassHelperTypeDeclaration
write SetOnParseBeginClassHelperTypeDeclaration;
property OnParseEndClassHelperTypeDeclaration: TPaxParserIdentEvent read GetOnParseEndClassHelperTypeDeclaration
write SetOnParseEndClassHelperTypeDeclaration;
property OnParseBeginRecordHelperTypeDeclaration: TPaxParserTypedIdentEvent read GetOnParseBeginRecordHelperTypeDeclaration
write SetOnParseBeginRecordHelperTypeDeclaration;
property OnParseEndRecordHelperTypeDeclaration: TPaxParserIdentEvent read GetOnParseEndRecordHelperTypeDeclaration
write SetOnParseEndRecordHelperTypeDeclaration;
property OnParseBeginInterfaceTypeDeclaration: TPaxParserIdentEvent read GetOnParseBeginInterfaceTypeDeclaration
write SetOnParseBeginInterfaceTypeDeclaration;
property OnParseEndInterfaceTypeDeclaration: TPaxParserIdentEvent read GetOnParseEndInterfaceTypeDeclaration
write SetOnParseEndInterfaceTypeDeclaration;
property OnParseBeginEnumTypeDeclaration: TPaxParserIdentEvent read GetOnParseBeginEnumTypeDeclaration
write SetOnParseBeginEnumTypeDeclaration;
property OnParseEndEnumTypeDeclaration: TPaxParserIdentEvent read GetOnParseEndEnumTypeDeclaration
write SetOnParseEndEnumTypeDeclaration;
property OnParseEnumName: TPaxParserNamedValueEvent read GetOnParseEnumName
write SetOnParseEnumName;
property OnParseFieldDeclaration: TPaxParserTypedIdentEvent read GetOnParseFieldDeclaration
write SetOnParseFieldDeclaration;
property OnParseVariantRecordFieldDeclaration: TPaxParserVariantRecordFieldEvent read GetOnParseVariantRecordFieldDeclaration
write SetOnParseVariantRecordFieldDeclaration;
property OnParsePropertyDeclaration: TPaxParserTypedIdentEvent read GetOnParsePropertyDeclaration
write SetOnParsePropertyDeclaration;
property OnParseConstantDeclaration: TPaxParserNamedValueEvent read GetOnParseConstantDeclaration
write SetOnParseConstantDeclaration;
property OnParseResourceStringDeclaration: TPaxParserNamedValueEvent read GetOnParseResourceStringDeclaration
write SetOnParseResourceStringDeclaration;
property OnParseTypedConstantDeclaration: TPaxParserNamedTypedValueEvent read GetOnParseTypedConstantDeclaration
write SetOnParseTypedConstantDeclaration;
property OnParseVariableDeclaration: TPaxParserTypedIdentEvent read GetOnParseVariableDeclaration
write SetOnParseVariableDeclaration;
property OnParseBeginSubDeclaration: TPaxParserIdentEvent read GetOnParseBeginSubDeclaration
write SetOnParseBeginSubDeclaration;
property OnParseEndSubDeclaration: TPaxParserDeclarationEvent read GetOnParseEndSubDeclaration
write SetOnParseEndSubDeclaration;
property OnParseBeginFormalParameterList: TPaxParserNotifyEvent read GetOnParseBeginFormalParameterList
write SetOnParseBeginFormalParameterList;
property OnParseEndFormalParameterList: TPaxParserNotifyEvent read GetOnParseEndFormalParameterList
write SetOnParseEndFormalParameterList;
property OnParseFormalParameterDeclaration: TPaxParserNamedTypedValueEvent read GetOnParseFormalParameterDeclaration
write SetOnParseFormalParameterDeclaration;
property OnParseResultType: TPaxParserIdentEvent read GetOnParseResultType
write SetOnParseResultType;
property OnParseSubDirective: TPaxParserIdentEvent read GetOnParseSubDirective
write SetOnParseSubDirective;
published
property ExplicitOff;
property CompleteBooleanEval;
property UnitLookup;
property PrintKeyword;
property PrintlnKeyword;
end;
procedure SetDump;
implementation
uses
PAXCOMP_BYTECODE,
PAXCOMP_STDLIB;
//--------------------TPaxCompiler----------------------------------------------
constructor TPaxCompiler.Create(AOwner: TComponent);
begin
inherited;
kernel := TKernel.Create(Self);
end;
destructor TPaxCompiler.Destroy;
begin
FreeAndNil(kernel);
inherited;
end;
procedure TPaxCompiler.Reset;
begin
kernel.Reset;
end;
procedure TPaxCompiler.ResetCompilation;
begin
kernel.ResetCompilation;
end;
procedure TPaxCompiler.AddModule(const ModuleName, LanguageName: String);
begin
kernel.AddModule(ModuleName, LanguageName);
end;
procedure TPaxCompiler.AddCode(const ModuleName, Text: String);
begin
kernel.AddCode(ModuleName, Text);
end;
procedure TPaxCompiler.AddCodeFromFile(const ModuleName, FileName: String);
begin
kernel.AddCodeFromFile(ModuleName, FileName);
end;
procedure TPaxCompiler.CreateMapping(Runner: TBaseRunner);
begin
kernel.code.CreateMapping(Runner.HostMapTable, true,
Runner.HostMapTable, nil);
if kernel.SignCompression then
begin
kernel.CompressHostClassList(Runner.HostMapTable);
kernel.SymbolTable.CreateOffsets(Runner.JS_Record.Id_JS_Object,
Runner.JS_Record.Id_JS_Error);
end;
end;
function TPaxCompiler.CompileExpression(const Expression: String;
APaxRunner: TPaxRunner;
const LangName: String = ''): Boolean;
var
Runner: TBaseRunner;
begin
Runner := APaxRunner.GetProgPtr;
result := false;
try
Runner.Reset;
RegisterGlobalJSObjects(Runner.JS_Record);
kernel.SetProg(Runner);
kernel.ParseExpression(Expression, LangName);
if kernel.HasError then Exit;
kernel.Link;
if kernel.HasError then Exit;
CreateMapping(Runner);
APaxRunner.EmitProc(kernel, Runner);
finally
if kernel.SignCompression then
kernel.SymbolTable.RestoreClassIndexes;
end;
result := true;
end;
function TPaxCompiler.Compile(APaxRunner: TPaxRunner;
BuildAll: Boolean = false;
BuildWithRuntimePackages: Boolean = false): boolean;
var
temp: Pointer;
Runner: TBaseRunner;
begin
if kernel.Modules.Count = 0 then
kernel.RaiseError(errEmptyModuleList, []);
Runner := APaxRunner.GetProgPtr;
result := false;
if BuildWithRuntimePackages then
BuildAll := true;
temp := CurrKernel;
CurrKernel := Kernel;
try
Runner.Reset;
RegisterGlobalJSObjects(Runner.JS_Record);
kernel.SetProg(Runner);
kernel.BuildAll := BuildAll;
kernel.BuildWithRuntimePackages := BuildWithRuntimePackages;
try
kernel.Parse;
if kernel.HasError then Exit;
if kernel.ImportOnly then
begin
result := true;
Exit;
end;
kernel.Link;
if kernel.HasError then Exit;
if kernel.Canceled then
begin
result := true;
Exit;
end;
CreateMapping(Runner);
APaxRunner.EmitProc(kernel, Runner);
finally
if not kernel.ImportOnly then
begin
if not kernel.BuildWithRuntimePackages then
Runner.ProgList.LoadFromStreamList(kernel.PCUStreamList, Runner);
if kernel.SignCompression then
kernel.SymbolTable.RestoreClassIndexes;
if BuildWithRuntimePackages then
Runner.ProgList.Clear;
kernel.BuildAll := false;
kernel.BuildWithRuntimePackages := false;
end;
end;
result := true;
finally
CurrKernel := temp;
end;
end;
function TPaxCompiler.Compile: boolean;
var
ClassFactory: TPaxClassFactory;
TypeInfoList: TPaxTypeInfoList;
ExportList: TExportList;
MessageList: TMessageList;
begin
ClassFactory := TPaxClassFactory.Create;
TypeInfoList := TPaxTypeInfoList.Create;
ExportList := TExportList.Create;
MessageList := TMessageList.Create;
CurrKernel := kernel;
try
kernel.ClassFactory := ClassFactory;
kernel.TypeInfoList := TypeInfoList;
kernel.MessageList := MessageList;
kernel.ExportList := ExportList;
result := false;
kernel.Parse;
if kernel.HasError then Exit;
if kernel.ImportOnly then
begin
result := true;
Exit;
end;
kernel.Link;
if kernel.HasError then Exit;
result := true;
finally
FreeAndNil(ClassFactory);
FreeAndNil(TypeInfoList);
FreeAndNil(ExportList);
FreeAndNil(MessageList);
end;
end;
function TPaxCompiler.Parse: boolean;
var
ClassFactory: TPaxClassFactory;
TypeInfoList: TPaxTypeInfoList;
ExportList: TExportList;
MessageList: TMessageList;
begin
ClassFactory := TPaxClassFactory.Create;
TypeInfoList := TPaxTypeInfoList.Create;
ExportList := TExportList.Create;
MessageList := TMessageList.Create;
CurrKernel := kernel;
try
kernel.ClassFactory := ClassFactory;
kernel.TypeInfoList := TypeInfoList;
kernel.MessageList := MessageList;
kernel.ExportList := ExportList;
result := false;
kernel.Parse;
if kernel.HasError then Exit;
if kernel.ImportOnly then
begin
result := true;
Exit;
end;
// kernel.InterfaceOnly := true;
// kernel.Link;
result := not kernel.HasError;
dmp;
finally
FreeAndNil(ClassFactory);
FreeAndNil(TypeInfoList);
FreeAndNil(ExportList);
FreeAndNil(MessageList);
end;
end;
function TPaxCompiler.CodeCompletion(const ModuleName: String;
X, Y: Integer; L: TStrings; PaxLang: TPaxCompilerLanguage = nil): Boolean;
var
NN, Op, Id, I: Integer;
ClassFactory: TPaxClassFactory;
TypeInfoList: TPaxTypeInfoList;
ExportList : TExportList;
MessageList : TMessageList;
Lst: TIntegerList;
R: TCodeRec;
WithIsAllowed: Boolean;
temp: Pointer;
SkipParams: Integer;
VisSet: TMemberVisibilitySet;
begin
result := false;
ClassFactory := TPaxClassFactory.Create;
TypeInfoList := TPaxTypeInfoList.Create;
ExportList := TExportList.Create;
MessageList := TMessageList.Create;
temp := CurrKernel;
CurrKernel := Kernel;
try
kernel.ClassFactory := ClassFactory;
kernel.TypeInfoList := TypeInfoList;
kernel.MessageList := MessageList;
kernel.ExportList := ExportList;
kernel.ParseCompletion(ModuleName, X, Y);
if kernel.HasError then
begin
CurrKernel := kernel;
Exit;
end;
if kernel.Code.Card = 0 then Exit;
kernel.Link;
finally
CurrKernel := temp;
FreeAndNil(ClassFactory);
FreeAndNil(TypeInfoList);
FreeAndNil(ExportList);
FreeAndNil(MessageList);
end;
CurrKernel := kernel;
kernel.Code.LocateDummyName(NN);
if NN > 0 then
begin
Op := kernel.Code[NN].GenOp;
Id := kernel.Code[NN].Arg1;
if Op = OP_EVAL then
begin
if NN < kernel.Code.Card then
if kernel.Code[NN + 1].GenOp = OP_BEGIN_USING then
begin
Id := kernel.Code.GetLevel(NN);
kernel.SymbolTable.ExtractNamespaces(Id, L);
result := true;
Exit;
end;
if ByteInSet(kernel.CancelChar, [Ord('('), Ord('.')]) then
begin
result := true;
kernel.Errors.Reset;
Exit;
end;
WithIsAllowed := true;
Lst := TIntegerList.Create;
try
for I := NN downto 1 do
begin
R := kernel.Code[I];
if R.Op = OP_BEGIN_MODULE then
break;
if R.Op = OP_INIT_SUB then
WithIsAllowed := false;
if R.Op = OP_END_SUB then
WithIsAllowed := false;
if R.Op = OP_END_WITH then
WithIsAllowed := false;
if R.Op = OP_BEGIN_USING then
// if R.Arg1 > 0 then
Lst.Add(R.Arg1);
if R.Op = OP_BEGIN_WITH then
if WithIsAllowed then
Lst.Add(R.Arg1);
end;
for I := 0 to Lst.Count - 1 do
begin
Id := Lst[I];
if Id > 0 then
begin
if kernel.SymbolTable[Id].Kind <> KindNAMESPACE then
if kernel.SymbolTable[Id].TypeId = 0 then
kernel.Code.RestoreFieldType(NN);
end;
if PaxLang = nil then
kernel.SymbolTable.ExtractMembers(Id, L)
else if PaxLang is TPaxPascalLanguage then
kernel.SymbolTable.ExtractMembers(Id, L)
else
kernel.SymbolTable.ExtractMembers(Id, L, lngBasic);
end;
kernel.Errors.Reset;
finally
FreeAndNil(Lst);
end;
end
else if Op = OP_FIELD then
begin
if kernel.SymbolTable[Id].Kind <> KindNAMESPACE then
if kernel.SymbolTable[Id].TypeId = 0 then
kernel.Code.RestoreFieldType(NN);
VisSet := TKernel(kernel).Code.GetCompletionVisibility(Id, NN);
if PaxLang = nil then
kernel.SymbolTable.ExtractMembers(Id, L, lngPascal, false, VisSet)
else if PaxLang is TPaxPascalLanguage then
kernel.SymbolTable.ExtractMembers(Id, L, lngPascal, false, VisSet)
else
kernel.SymbolTable.ExtractMembers(Id, L, lngBasic, false, VisSet);
if L.Count > 0 then
kernel.Errors.Reset;
end
else if (Op = OP_CALL) or (Op = OP_BEGIN_CALL) then
begin
if not (kernel.SymbolTable[Id].Kind in KindSUBS) then
Exit;
if kernel.CompletionTarget <> '' then
begin
if StrEql(kernel.CompletionTarget, 'New') or
StrEql(kernel.CompletionTarget, 'Dispose') then
begin
L.Add('X: Pointer');
kernel.Errors.Reset;
end;
end
else
begin
if Id = JS_FunctionCallId then
begin
with kernel do
for I := Code.GetStmt(NN) to Code.Card do
if Code[I].Op = OP_PUSH_INST then
if Code[I].Res = JS_FunctionCallId then
begin
Id := Code[I].Arg1;
Inc(Id);
if SymbolTable[Id].Kind = KindSUB then
break
else
begin
kernel.Errors.Reset;
Exit;
end;
end;
end;
SkipParams := 0;
I := NN;
while I > 1 do
begin
Dec(I);
with kernel do
if Code[I].GenOp = OP_PUSH then
if SymbolTable[Code[I].Arg1].Name = DummyName then
break;
end;
while I > 1 do
begin
Dec(I);
Op := kernel.Code[I].GenOp;
with kernel do
if Op = OP_PUSH then
begin
if Code[I].Res = Id then
Inc(SkipParams);
end
else
if Op = OP_BEGIN_CALL then
begin
if Code[I].Arg1 = Id then
break;
end;
end;
kernel.SymbolTable.ExtractParametersEx(Id, L, true, SkipParams);
kernel.Errors.Reset;
end;
end
else if (Op = OP_PRINT) or (Op = OP_PRINT_EX) then
begin
L.Add('P1;[...,PN]');
kernel.Errors.Reset;
end
else if Op = OP_ABS then
begin
L.Add('X: Real');
kernel.Errors.Reset;
end
else if (Op = OP_INC) or (Op = OP_DEC) then
begin
L.Add('var X: Ordinal; [N: Integer]');
kernel.Errors.Reset;
end
else if (Op = OP_PRED) or
(Op = OP_SUCC) or
(Op = OP_ORD) then
begin
L.Add('X: Ordinal');
kernel.Errors.Reset;
end
else if Op = OP_CHR then
begin
L.Add('X: Byte');
kernel.Errors.Reset;
end
else if Op = OP_STR then
begin
L.Add('const X[: Width[:Decimals]]; var S: String');
kernel.Errors.Reset;
end
else if (Op = OP_SIZEOF) or
(Op = OP_ASSIGNED) or
(Op = OP_LOW) or
(Op = OP_HIGH) then
begin
L.Add('var X');
kernel.Errors.Reset;
end
else // error
Exit;
end
else
begin
kernel.Errors.Reset;
end;
result := not kernel.HasError;
end;
function TPaxCompiler.FindDeclaration(const ModuleName: String;
X, Y: Integer;
PaxLang: TPaxCompilerLanguage = nil): Integer;
var
ClassFactory: TPaxClassFactory;
TypeInfoList: TPaxTypeInfoList;
ExportList : TExportList;
MessageList : TMessageList;
temp: Pointer;
Id, TypeId, LevelId: Integer;
S: String;
begin
result := 0;
ClassFactory := TPaxClassFactory.Create;
TypeInfoList := TPaxTypeInfoList.Create;
ExportList := TExportList.Create;
MessageList := TMessageList.Create;
temp := CurrKernel;
CurrKernel := Kernel;
try
kernel.ClassFactory := ClassFactory;
kernel.TypeInfoList := TypeInfoList;
kernel.MessageList := MessageList;
kernel.ExportList := ExportList;
kernel.FindDeclId := -1;
kernel.ParseCompletion(ModuleName, X, Y);
if kernel.HasError then
Exit;
if kernel.Code.Card = 0 then Exit;
kernel.Link;
finally
if kernel.FindDeclId < 0 then
kernel.FindDeclId := 0;
CurrKernel := temp;
FreeAndNil(ClassFactory);
FreeAndNil(TypeInfoList);
FreeAndNil(ExportList);
FreeAndNil(MessageList);
end;
result := kernel.FindDeclId;
if result > 0 then
with kernel do
begin
Id := SymbolTable[result].OwnerId;
if SymbolTable[result].Kind = KindVAR then
if Id > 0 then
begin
S := SymbolTable[result].Name;
TypeId := SymbolTable[Id].TerminalTypeId;
result := SymbolTable.Lookup(S, TypeId, true);
end
else if PaxLang = nil then
begin
LevelId := SymbolTable[result].Level;
if LevelId > 0 then
if SymbolTable[LevelId].Kind = KindSUB then
if result = SymbolTable.GetResultId(LevelId) then
result := LevelId;
end
else if StrEql(PaxLang.LanguageName, 'Pascal') then
begin
LevelId := SymbolTable[result].Level;
if LevelId > 0 then
if SymbolTable[LevelId].Kind = KindSUB then
if result = SymbolTable.GetResultId(LevelId) then
result := LevelId;
end;
end;
end;
procedure TPaxCompiler.RegisterLanguage(L: TPaxCompilerLanguage);
begin
kernel.RegisterParser(L.GetParser);
end;
procedure TPaxCompiler.RegisterDirective(const Directive: string; const value: Variant);
begin
kernel.DefList.Add(Directive, value);
end;
function TPaxCompiler.RegisterNamespace(LevelId: Integer;
const NamespaceName: String): Integer;
begin
result := kernel.SymbolTable.RegisterNamespace(LevelId, NamespaceName);
end;
procedure TPaxCompiler.RegisterUsingNamespace(const aNamespaceName: String);
Var
H: integer;
begin
H := kernel.SymbolTable.LookupNamespace(aNamespaceName, 0, True);
if H > 0 then
RegisterUsingNamespace (H);
end;
procedure TPaxCompiler.RegisterUsingNamespace(aNamespaceID: Integer);
begin
kernel.SymbolTable.HeaderParser.UsedNamespaceList.Add(aNamespaceID);
end;
procedure TPaxCompiler.UnregisterUsingNamespace(aNamespaceID: Integer);
begin
kernel.SymbolTable.HeaderParser.UsedNamespaceList.DeleteValue(aNamespaceID);
end;
procedure TPaxCompiler.UnregisterUsingNamespaces;
begin
kernel.SymbolTable.HeaderParser.UsedNamespaceList.Clear;
end;
procedure TPaxCompiler.UnregisterUsingNamespace(const aNamespaceName: String);
Var
H: integer;
begin
H := kernel.SymbolTable.LookupNamespace(aNamespaceName, 0, True);
if H > 0 then
UnRegisterUsingNamespace (H);
end;
function TPaxCompiler.RegisterInterfaceType(LevelId: Integer;
const TypeName: String;
const GUID: TGUID): Integer;
begin
result := kernel.SymbolTable.RegisterInterfaceType(LevelId, TypeName, GUID);
end;
function TPaxCompiler.RegisterInterfaceType(LevelId: Integer;
const TypeName: String;
const GUID: TGUID;
const ParentName: String;
const ParentGUID: TGUID): Integer;
begin
result := kernel.SymbolTable.RegisterInterfaceType(LevelId, TypeName, GUID);
kernel.SymbolTable.RegisterSupportedInterface(result, ParentName, ParentGUID);
end;
procedure TPaxCompiler.RegisterSupportedInterface(TypeId: Integer;
const SupportedInterfaceName: String;
const GUID: TGUID);
begin
kernel.SymbolTable.RegisterSupportedInterface(TypeId, SupportedInterfaceName, GUID);
end;
function TPaxCompiler.RegisterClassType(LevelId: Integer;
const TypeName: String; AncestorId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterClassType(LevelId, TypeName, AncestorId);
end;
function TPaxCompiler.RegisterClassType(LevelId: Integer;
C: TClass): Integer;
begin
result := kernel.SymbolTable.RegisterClassType(LevelId, C);
end;
function TPaxCompiler.RegisterClassReferenceType(LevelId: Integer;
const TypeName: String; OriginClassId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterClassReferenceType(LevelId, TypeName, OriginClassId);
end;
function TPaxCompiler.RegisterClassHelperType(LevelId: Integer;
const TypeName: String; OriginClassId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterHelperType(LevelId, TypeName, OriginClassId);
end;
function TPaxCompiler.RegisterClassHelperType(LevelID: Integer; const TypeName, OriginalTypeName: String): Integer;
var
OriginClassId: Integer;
begin
OriginClassId := kernel.SymbolTable.LookUpType(OriginalTypeName, 0, true);
result := kernel.SymbolTable.RegisterHelperType(LevelId, TypeName, OriginClassId);
end;
function TPaxCompiler.RegisterRecordHelperType(LevelId: Integer;
const TypeName: String; OriginRecordId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterHelperType(LevelId, TypeName, OriginRecordId);
end;
function TPaxCompiler.RegisterRecordHelperType(LevelID: Integer; const TypeName, OriginalTypeName: String): Integer;
var
OriginRecordId: Integer;
begin
OriginRecordId := kernel.SymbolTable.LookUpType(OriginalTypeName, 0, true);
result := kernel.SymbolTable.RegisterHelperType(LevelId, TypeName, OriginRecordId);
end;
function TPaxCompiler.RegisterClassTypeField(TypeId: Integer; const FieldName: String;
FieldTypeID: Integer; FieldShift: Integer = -1): Integer;
begin
result := kernel.SymbolTable.RegisterTypeField(TypeId, FieldName, FieldTypeID, FieldShift);
end;
function TPaxCompiler.RegisterProperty(LevelId: Integer; const PropName: String;
PropTypeID, ReadId, WriteId: Integer;
IsDefault: Boolean): Integer;
begin
result := kernel.SymbolTable.RegisterProperty(LevelId, PropName, PropTypeId,
ReadId, WriteId, IsDefault);
end;
function TPaxCompiler.RegisterInterfaceProperty(LevelId: Integer;
const PropName: String;
PropTypeID,
ReadIndex,
WriteIndex: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterInterfaceProperty(LevelId, PropName, PropTypeId,
ReadIndex, WriteIndex);
end;
function TPaxCompiler.RegisterProperty(LevelId: Integer; const Header: String): Integer;
begin
result := kernel.SymbolTable.RegisterHeader(LevelId, Header, nil);
end;
function TPaxCompiler.RegisterRecordType(LevelId: Integer;
const TypeName: String;
IsPacked: Boolean = false): Integer;
begin
if IsPacked then
result := kernel.SymbolTable.RegisterRecordType(LevelId, TypeName, 1)
else
result := kernel.SymbolTable.RegisterRecordType(LevelId, TypeName, kernel.Alignment);
end;
function TPaxCompiler.RegisterRecordTypeField(TypeId: Integer; const FieldName: String;
FieldTypeID: Integer; FieldShift: Integer = -1): Integer;
begin
result := kernel.SymbolTable.RegisterTypeField(TypeId, FieldName, FieldTypeID, FieldShift);
end;
function TPaxCompiler.RegisterVariantRecordTypeField(TypeId: Integer; const FieldName: String;
FieldTypeID: Integer;
VarCount: Int64): Integer;
begin
result := kernel.SymbolTable.RegisterVariantRecordTypeField(TypeId,
FieldName,
FieldTypeId,
VarCount);
end;
function TPaxCompiler.RegisterVariantRecordTypeField(LevelId: Integer; const Declaration: String;
VarCount: Int64): Integer;
begin
result := kernel.SymbolTable.RegisterVariantRecordTypeField(LevelId,
Declaration, VarCount);
end;
function TPaxCompiler.RegisterSubrangeType(LevelId: Integer;
const TypeName: String;
TypeBaseId: Integer;
B1, B2: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterSubrangeType(LevelId, TypeName, TypeBaseId, B1, B2);
end;
function TPaxCompiler.RegisterEnumType(LevelId: Integer;
const TypeName: String;
TypeBaseId: Integer = _typeINTEGER): Integer;
begin
result := kernel.SymbolTable.RegisterEnumType(LevelId, TypeName, TypeBaseId);
end;
function TPaxCompiler.RegisterEnumValue(EnumTypeId: Integer;
const FieldName: String;
const Value: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterEnumValue(EnumTypeId, FieldName, Value);
end;
function TPaxCompiler.RegisterArrayType(LevelId: Integer;
const TypeName: String;
RangeTypeId, ElemTypeId: Integer;
IsPacked: Boolean = false): Integer;
begin
if IsPacked then
result := kernel.SymbolTable.RegisterArrayType(LevelId, TypeName, RangeTypeId, ElemTypeId, 1)
else
result := kernel.SymbolTable.RegisterArrayType(LevelId, TypeName, RangeTypeId, ElemTypeId, kernel.Alignment);
end;
function TPaxCompiler.RegisterDynamicArrayType(LevelId: Integer;
const TypeName: String;
ElemTypeId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterDynamicArrayType(LevelId, TypeName, ElemTypeId);
end;
function TPaxCompiler.RegisterPointerType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer;
const OriginTypeName: String = ''): Integer;
begin
result := kernel.SymbolTable.RegisterPointerType(LevelId,
TypeName, OriginTypeId, OriginTypeName);
end;
function TPaxCompiler.RegisterMethodReferenceType(LevelId: Integer;
const TypeName: String;
SubId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterMethodReferenceType(LevelId, TypeName, SubId);
end;
function TPaxCompiler.RegisterTypeDeclaration(LevelId: Integer;
const Declaration: String): Integer;
begin
result := kernel.SymbolTable.RegisterTypeDeclaration(LevelId, Declaration);
end;
function TPaxCompiler.RegisterSomeType(LevelId: Integer;
const TypeName: String): Integer;
begin
result := kernel.SymbolTable.RegisterSomeType(LevelId, TypeName);
end;
function TPaxCompiler.RegisterSetType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterSetType(LevelId, TypeName, OriginTypeId);
end;
function TPaxCompiler.RegisterProceduralType(LevelId: Integer;
const TypeName: String;
SubId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterProceduralType(LevelId, TypeName, SubId);
end;
{$IFNDEF PAXARM}
function TPaxCompiler.RegisterShortStringType(LevelId: Integer;
const TypeName: String;
L: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterShortStringType(LevelId, TypeName, L);
end;
{$ENDIF}
function TPaxCompiler.RegisterEventType(LevelId: Integer;
const TypeName: String;
SubId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterEventType(LevelId, TypeName, SubId);
end;
function TPaxCompiler.RegisterRTTIType(LevelId: Integer; pti: PTypeInfo): Integer;
begin
result := kernel.SymbolTable.RegisterRTTIType(LevelId, pti);
end;
function TPaxCompiler.RegisterTypeAlias(LevelId:Integer; const TypeName: String;
OriginTypeId: Integer): Integer;
begin
result := kernel.SymbolTable.RegisterTypeAlias(LevelId, TypeName, OriginTypeId);
end;
function TPaxCompiler.RegisterObject(LevelId: Integer;
const ObjectName: String;
TypeId: Integer;
Address: Pointer = nil): Integer;
begin
result := kernel.SymbolTable.RegisterObject(LevelId, ObjectName, TypeId, Address);
end;
function TPaxCompiler.RegisterVirtualObject(LevelId: Integer;
const ObjectName: String): Integer;
begin
result := kernel.SymbolTable.RegisterVirtualObject(LevelId, ObjectName);
end;
function TPaxCompiler.RegisterVariable(LevelId: Integer;
const VarName: String;
TypeId: Integer;
Address: Pointer = nil): Integer;
begin
result := kernel.SymbolTable.RegisterVariable(LevelId, VarName, TypeId, Address);
end;
function TPaxCompiler.RegisterVariable(LevelId: Integer;
const Declaration: String; Address: Pointer): Integer;
begin
result := kernel.SymbolTable.RegisterVariable(LevelId, Declaration, Address);
end;
function TPaxCompiler.RegisterConstant(LevelId: Integer;
const ConstName: String;
typeID: Integer;
const Value: Variant): Integer;
begin
result := kernel.SymbolTable.RegisterConstant(LevelId, ConstName, TypeId, Value);
end;
function TPaxCompiler.RegisterConstant(LevelId: Integer;
const ConstName: String;
const Value: Variant): Integer;
begin
result := kernel.SymbolTable.RegisterConstant(LevelId, ConstName, Value);
end;
function TPaxCompiler.RegisterPointerConstant(LevelId: Integer;
const ConstName: String;
const Value: Pointer): Integer;
begin
result := kernel.SymbolTable.RegisterPointerConstant(LevelId, ConstName, Value);
end;
function TPaxCompiler.RegisterConstant(LevelId: Integer;
const ConstName: String;
const Value: Extended): Integer;
begin
result := kernel.SymbolTable.RegisterExtendedConstant(LevelId, ConstName, Value);
end;
function TPaxCompiler.RegisterConstant(LevelId: Integer;
const ConstName: String;
const Value: Int64): Integer;
begin
result := kernel.SymbolTable.RegisterInt64Constant(LevelId, ConstName, Value);
end;
function TPaxCompiler.RegisterConstant(LevelId: Integer;
const Declaration: String): Integer;
begin
result := kernel.SymbolTable.RegisterConstant(LevelId, Declaration);
end;
function TPaxCompiler.RegisterRoutine(LevelId: Integer;
const RoutineName: String; ResultTypeID: Integer;
CallConvention: Integer;
Address: Pointer = nil): Integer;
begin
result := kernel.SymbolTable.RegisterRoutine(LevelId, RoutineName, ResultTypeId,
CallConvention, Address);
end;
function TPaxCompiler.RegisterRoutine(LevelId: Integer; const Name: String;
ResultId: Integer;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
OverCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
begin
result := kernel.SymbolTable.RegisterRoutine(LevelId, Name,
ResultId, CallConvention, Address, OverCount, i_IsDeprecated);
end;
function TPaxCompiler.RegisterRoutine(LevelId: Integer; const Name, ResultType: String;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
OverCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
begin
result := kernel.SymbolTable.RegisterRoutine(LevelId, Name, ResultType,
CallConvention, Address, OverCount, i_IsDeprecated);
end;
function TPaxCompiler.RegisterMethod(LevelId: Integer;
const RoutineName: String; ResultTypeID: Integer;
CallConvention: Integer;
Address: Pointer = nil;
IsShared: Boolean = false): Integer;
begin
result := kernel.SymbolTable.RegisterMethod(LevelId, RoutineName, ResultTypeId,
CallConvention, Address, IsShared);
end;
function TPaxCompiler.RegisterMethod(ClassId: Integer;
const Name: String;
ResultId: Integer;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
IsShared: Boolean = false;
CallMode: Integer = _cmNONE;
MethodIndex: Integer = 0;
OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
begin
result := kernel.SymbolTable.RegisterMethod(ClassId,
Name,
ResultId,
CallConvention,
Address,
IsShared,
CallMode,
MethodIndex,
OverCount,
i_IsAbstract,
i_AbstractMethodCount,
i_IsDeprecated);
end;
function TPaxCompiler.RegisterMethod(ClassId: Integer;
const Name, ResultType: String;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
IsShared: Boolean = false;
CallMode: Integer = _cmNONE;
MethodIndex: Integer = 0;
OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
begin
result := kernel.SymbolTable.RegisterMethod(ClassId,
Name,
ResultType,
CallConvention,
Address,
IsShared,
CallMode,
MethodIndex,
OverCount,
i_IsAbstract,
i_AbstractMethodCount,
i_IsDeprecated);
end;
function TPaxCompiler.RegisterConstructor(ClassId: Integer;
const Name: String;
Address: Pointer;
CallConvention: Integer = _ccREGISTER;
IsShared: Boolean = false;
CallMode: Integer = 0;
i_MethodIndex: Integer = 0;
OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
begin
result := kernel.SymbolTable.RegisterConstructor(ClassId,
Name, Address, IsShared, CallMode, i_MethodIndex, OverCount,
i_IsAbstract, i_AbstractMethodCount, i_IsDeprecated);
end;
function TPaxCompiler.RegisterDestructor(ClassId: Integer; const Name: String;
Address: Pointer): Integer;
begin
result := kernel.SymbolTable.RegisterDestructor(ClassId, Name, Address);
end;
function TPaxCompiler.RegisterParameter(HSub: Integer; ParamTypeID: Integer;
const DefaultValue: Variant;
ByRef: Boolean = false): Integer;
begin
result := kernel.SymbolTable.RegisterParameter(HSub, ParamTypeId, DefaultValue, ByRef);
end;
function TPaxCompiler.RegisterParameter(LevelId: Integer;
const ParameterName: String;
ParamTypeID: Integer;
ParamMod: Integer = 0;
Optional: Boolean = false;
const DefaultValue: String = ''): Integer;
begin
result := kernel.SymbolTable.RegisterParameter(LevelId,
ParameterName,
ParamTypeId,
ParamMod,
Optional,
DefaultValue);
end;
function TPaxCompiler.RegisterParameter(LevelId: Integer;
const ParameterName: String;
const ParameterType: String;
ParamMod: Integer = 0;
Optional: Boolean = false;
const DefaultValue: String = ''): Integer;
begin
result := kernel.SymbolTable.RegisterParameter(LevelId,
ParameterName,
ParameterType,
ParamMod,
Optional,
DefaultValue);
end;
function TPaxCompiler.RegisterHeader(LevelId: Integer; const Header: String;
Address: Pointer = nil;
MethodIndex: Integer = 0): Integer;
begin
result := kernel.SymbolTable.RegisterHeader(LevelId, Header, Address, MethodIndex);
end;
function TPaxCompiler.RegisterFakeHeader(LevelId: Integer;
const Header: String; Address: Pointer): Integer;
begin
result := kernel.SymbolTable.RegisterFakeHeader(LevelId, Header, Address);
end;
function TPaxCompiler.GetHandle(LevelId: Integer; const MemberName: String; Upcase: Boolean): Integer;
begin
result := kernel.GetHandle(LevelId, MemberName, Upcase);
end;
function TPaxCompiler.GetTargetPlatform: Integer;
begin
result := Ord(kernel.TargetPlatform);
end;
procedure TPaxCompiler.SetTargetPlatform(value: Integer);
begin
kernel.TargetPlatform := TTargetPlatform(value);
end;
function TPaxCompiler.GetErrorCount: Integer;
begin
result := kernel.Errors.Count;
end;
function TPaxCompiler.GetErrorMessage(I: Integer): String;
begin
if (I >= 0) and (I < GetErrorCount) then
result := kernel.Errors[I].Message
else
result := '';
end;
function TPaxCompiler.GetErrorModuleName(I: Integer): String;
begin
if (I >= 0) and (I < GetErrorCount) then
result := kernel.Errors[I].ModuleName
else
result := '';
end;
function TPaxCompiler.GetErrorLine(I: Integer): String;
begin
if (I >= 0) and (I < GetErrorCount) then
result := kernel.Errors[I].SourceLine
else
result := '';
end;
function TPaxCompiler.GetErrorFileName(I: Integer): String;
begin
if (I >= 0) and (I < GetErrorCount) then
result := kernel.Errors[I].SourceFileName
else
result := '';
end;
function TPaxCompiler.GetErrorLineNumber(I: Integer): Integer;
begin
if (I >= 0) and (I < GetErrorCount) then
result := kernel.Errors[I].SourceLineNumber
else
result := 0;
end;
function TPaxCompiler.GetErrorLinePos(I: Integer): Integer;
begin
if (I >= 0) and (I < GetErrorCount) then
result := kernel.Errors[I].LinePos
else
result := 0;
end;
function TPaxCompiler.GetWarningCount: Integer;
begin
result := kernel.Warnings.Count;
end;
function TPaxCompiler.GetWarningMessage(I: Integer): String;
begin
if (I >= 0) and (I < GetWarningCount) then
result := kernel.Warnings[I].Message
else
result := '';
end;
function TPaxCompiler.GetWarningModuleName(I: Integer): String;
begin
if (I >= 0) and (I < GetWarningCount) then
result := kernel.Warnings[I].ModuleName
else
result := '';
end;
function TPaxCompiler.GetWarningLine(I: Integer): String;
begin
if (I >= 0) and (I < GetWarningCount) then
result := kernel.Warnings[I].SourceLine
else
result := '';
end;
function TPaxCompiler.GetWarningLineNumber(I: Integer): Integer;
begin
if (I >= 0) and (I < GetWarningCount) then
result := kernel.Warnings[I].SourceLineNumber
else
result := 0;
end;
function TPaxCompiler.GetWarningLinePos(I: Integer): Integer;
begin
if (I >= 0) and (I < GetWarningCount) then
result := kernel.Warnings[I].LinePos
else
result := 0;
end;
function TPaxCompiler.GetWarningFileName(I: Integer): String;
begin
if (I >= 0) and (I < GetWarningCount) then
result := kernel.Warnings[I].SourceFileName
else
result := '';
end;
function TPaxCompiler.GetOnCompilerProgress: TPaxCompilerNotifyEvent;
begin
result := TPaxCompilerNotifyEvent(kernel.OnCompilerProgress);
end;
procedure TPaxCompiler.SetOnCompilerProgress(value: TPaxCompilerNotifyEvent);
begin
kernel.OnCompilerProgress := TNotifyEvent(value);
end;
function TPaxCompiler.GetOnUsedUnit: TPaxCompilerUsedUnitEvent;
begin
result := TPaxCompilerUsedUnitEvent(kernel.OnUsedUnit);
end;
procedure TPaxCompiler.SetOnUsedUnit(value: TPaxCompilerUsedUnitEvent);
begin
kernel.OnUsedUnit := TUsedUnitEvent(value);
end;
function TPaxCompiler.GetOnImportUnit: TPaxCompilerImportMemberEvent;
begin
result := TPaxCompilerImportMemberEvent(kernel.OnImportUnit);
end;
procedure TPaxCompiler.SetOnImportUnit(value: TPaxCompilerImportMemberEvent);
begin
kernel.OnImportUnit := TImportMemberEvent(value);
end;
function TPaxCompiler.GetOnImportType: TPaxCompilerImportMemberEvent;
begin
result := TPaxCompilerImportMemberEvent(kernel.OnImportType);
end;
procedure TPaxCompiler.SetOnImportType(value: TPaxCompilerImportMemberEvent);
begin
kernel.OnImportType := TImportMemberEvent(value);
end;
function TPaxCompiler.GetOnImportGlobalMembers: TPaxCompilerNotifyEvent;
begin
result := TPaxCompilerNotifyEvent(kernel.OnImportGlobalMembers);
end;
procedure TPaxCompiler.SetOnImportGlobalMembers(value: TPaxCompilerNotifyEvent);
begin
kernel.OnImportGlobalMembers := TNotifyEvent(value);
end;
function TPaxCompiler.GetOnUnitAlias: TPaxCompilerUnitAliasEvent;
begin
result := TPaxCompilerUnitAliasEvent(kernel.OnUnitAlias);
end;
procedure TPaxCompiler.SetOnUnitAlias(value: TPaxCompilerUnitAliasEvent);
begin
kernel.OnUnitAlias := TUnitAliasEvent(value);
end;
function TPaxCompiler.GetOnSavePCU: TPaxCompilerSavePCUEvent;
begin
result := TPaxCompilerSavePCUEvent(kernel.OnSavePCU);
end;
procedure TPaxCompiler.SetOnSavePCU(value: TPaxCompilerSavePCUEvent);
begin
kernel.OnSavePCU := TSavePCUEvent(value);
end;
function TPaxCompiler.GetOnLoadPCU: TPaxCompilerLoadPCUEvent;
begin
result := TPaxCompilerLoadPCUEvent(kernel.OnLoadPCU);
end;
procedure TPaxCompiler.SetOnLoadPCU(value: TPaxCompilerLoadPCUEvent);
begin
kernel.OnLoadPCU := TLoadPCUEvent(value);
end;
function TPaxCompiler.GetOnInclude: TPaxCompilerIncludeEvent;
begin
result := TPaxCompilerIncludeEvent(kernel.OnInclude);
end;
procedure TPaxCompiler.SetOnInclude(value: TPaxCompilerIncludeEvent);
begin
kernel.OnInclude := TIncludeEvent(value);
end;
function TPaxCompiler.GetOnDefineDirective: TPaxCompilerDirectiveEvent;
begin
result := TPaxCompilerDirectiveEvent(kernel.OnDefineDirective);
end;
procedure TPaxCompiler.SetOnDefineDirective(value: TPaxCompilerDirectiveEvent);
begin
kernel.OnDefineDirective := TCompilerDirectiveEvent(value);
end;
function TPaxCompiler.GetOnUndefineDirective: TPaxCompilerDirectiveEvent;
begin
result := TPaxCompilerDirectiveEvent(kernel.OnUndefineDirective);
end;
procedure TPaxCompiler.SetOnUndefineDirective(value: TPaxCompilerDirectiveEvent);
begin
kernel.OnUndefineDirective := TCompilerDirectiveEvent(value);
end;
function TPaxCompiler.GetOnUnknownDirective: TPaxCompilerDirectiveEvent;
begin
result := TPaxCompilerDirectiveEvent(kernel.OnUnknownDirective);
end;
procedure TPaxCompiler.SetOnUnknownDirective(value: TPaxCompilerDirectiveEvent);
begin
kernel.OnUnknownDirective := TCompilerDirectiveEvent(value);
end;
function TPaxCompiler.GetSourceModule(const ModuleName: String): TStringList;
var
I: Integer;
begin
I := kernel.Modules.IndexOf(ModuleName);
if I >= 0 then
result := kernel.Modules[I].Lines
else
result := nil;
end;
function TPaxCompiler.GetCurrLineNumber: Integer;
begin
result := kernel.Code.GetSourceLineNumber(kernel.Code.N);
end;
function TPaxCompiler.GetCurrModuleNumber: Integer;
begin
result := kernel.Code.GetModuleNumber(kernel.Code.N);
end;
function TPaxCompiler.GetCurrModuleName: String;
begin
result := kernel.Modules[CurrModuleNumber].Name;
end;
function TPaxCompiler.GetDebugMode: Boolean;
begin
result := kernel.DEBUG_MODE;
end;
procedure TPaxCompiler.SetDebugMode(value: Boolean);
begin
kernel.DEBUG_MODE := value;
end;
// added in v 1.5
function TPaxCompiler.GetKernelPtr: Pointer;
begin
result := kernel;
end;
// added in v 1.6
procedure TPaxCompiler.RegisterGlobalJSObjects(var R: TJS_Record);
begin
with kernel.SymbolTable do
begin
R.H_JS_Object := RegisterVariable(JS_JavaScriptNamespace,
'Object', JS_ObjectClassId, nil);
R.Id_JS_Object := kernel.SymbolTable.Card;
R.H_JS_Boolean := RegisterVariable(JS_JavaScriptNamespace,
'Boolean', JS_BooleanClassId, nil);
R.Id_JS_Boolean := kernel.SymbolTable.Card;
R.H_JS_String := RegisterVariable(JS_JavaScriptNamespace,
'String', JS_StringClassId, nil);
R.Id_JS_String := kernel.SymbolTable.Card;
R.H_JS_Number := RegisterVariable(JS_JavaScriptNamespace,
'Number', JS_NumberClassId, nil);
R.Id_JS_Number := kernel.SymbolTable.Card;
R.H_JS_Date := RegisterVariable(JS_JavaScriptNamespace,
'Date', JS_DateClassId, nil);
R.Id_JS_Date := kernel.SymbolTable.Card;
R.H_JS_Function := RegisterVariable(JS_JavaScriptNamespace,
'Function', JS_FunctionClassId, nil);
R.Id_JS_Function := kernel.SymbolTable.Card;
R.H_JS_Array := RegisterVariable(JS_JavaScriptNamespace,
'Array', JS_ArrayClassId, nil);
R.Id_JS_Array := kernel.SymbolTable.Card;
R.H_JS_RegExp := RegisterVariable(JS_JavaScriptNamespace,
'RegExp', JS_RegExpClassId, nil);
R.Id_JS_RegExp := kernel.SymbolTable.Card;
R.H_JS_Math := RegisterVariable(JS_JavaScriptNamespace,
'Math', JS_MathClassId, nil);
R.Id_JS_Math := kernel.SymbolTable.Card;
R.H_JS_Error := RegisterVariable(JS_JavaScriptNamespace,
'Error', JS_ErrorClassId, nil);
R.Id_JS_Error := kernel.SymbolTable.Card;
end;
end;
// added in v 1.9
function TPaxCompiler.GetCondDirectiveList: TStringList;
begin
result := kernel.CondDirectiveList;
end;
function TPaxCompiler.GetAlignment: Integer;
begin
result := kernel.Alignment;
end;
procedure TPaxCompiler.SetAlignment(value: Integer);
begin
if not
(
(value = 1) or (value = 2) or
(value = 4) or (value = 8)
)
then
raise Exception.Create(Format(errInvalidAlignmentValue, [value]));
kernel.Alignment := value;
end;
function TPaxCompiler.GetUndeclaredTypes: TStringList;
begin
result := kernel.UndeclaredTypes;
end;
function TPaxCompiler.GetUndeclaredIdentifiers: TStringList;
begin
result := kernel.UndeclaredIdents;
end;
function TPaxCompiler.GetCurrLanguage: String;
begin
result := kernel.CurrLanguage;
end;
procedure TPaxCompiler.SetCurrLanguage(const value: String);
begin
kernel.CurrLanguage := value;
end;
function TPaxCompiler.GetOnUndeclaredIdentifier: TPaxCompilerUndeclaredIdentifierEvent;
begin
result := TPaxCompilerUndeclaredIdentifierEvent(TKernel(kernel).OnUndeclaredIdentifier);
end;
procedure TPaxCompiler.SetOnUndeclaredIdentifier(value: TPaxCompilerUndeclaredIdentifierEvent);
begin
TKernel(kernel).OnUndeclaredIdentifier := TUndeclaredIdentifierEvent(value);
end;
function TPaxCompiler.GetOnComment: TPaxCompilerCommentEvent;
begin
result := TPaxCompilerCommentEvent(TKernel(kernel).OnComment);
end;
procedure TPaxCompiler.SetOnComment(value: TPaxCompilerCommentEvent);
begin
TKernel(kernel).OnComment := TCommentEvent(value);
end;
function TPaxCompiler.LookupId(const FullName: String; UpCase: Boolean = true): Integer;
begin
if FullName = '' then
begin
result := 0;
Exit;
end;
result := TKernel(kernel).SymbolTable.LookupFullName(FullName, UpCase);
end;
function TPaxCompiler.LookupTypeId(const TypeName: String): Integer;
begin
result := TKernel(kernel).SymbolTable.LookupType(TypeName, true);
end;
function TPaxCompiler.LookupTypeNamespaceId(const TypeName: String): Integer;
var
R: TSymbolRec;
L, Id: Integer;
begin
result := 0;
Id := LookupTypeId(TypeName);
if Id = 0 then
Exit;
L := TKernel(kernel).SymbolTable[Id].Level;
repeat
if L = 0 then
begin
result := 0;
Exit;
end;
R := TKernel(kernel).SymbolTable[L];
if R.Kind = kindNAMESPACE then
begin
result := R.Id;
Exit;
end;
L := R.Level;
until false;
end;
function TPaxCompiler.LookupNamespace(LevelId: Integer; const NamespaceName: String;
CaseSensitive: Boolean): Integer;
begin
result := TKernel(kernel).SymbolTable.LookupNamespace(NamespaceName, LevelId, not CaseSensitive);
end;
function TPaxCompiler.LookupNamespace(const NamespaceName: String): Integer;
begin
result := LookupNamespace(0, NamespaceName, true);
end;
function TPaxCompiler.GetNativeSEH: Boolean;
begin
result := TKernel(kernel).ModeSEH;
end;
procedure TPaxCompiler.SetNativeSEH(const value: Boolean);
begin
TKernel(kernel).ModeSEH := value;
end;
procedure TPaxCompiler.AssignImportTable(ImportTable: Pointer);
begin
if ImportTable = nil then
ImportTable := GlobalSymbolTable;
TKernel(kernel).AssignImportTable(ImportTable);
end;
function TPaxCompiler.GetOnSavePCUFinished: TPaxCompilerSavePCUFinishedEvent; // jason
begin
result := TPaxCompilerSavePCUFinishedEvent(kernel.OnSavePCUFinished);
end;
procedure TPaxCompiler.SetOnSavePCUFinished(value: TPaxCompilerSavePCUFinishedEvent); // jason
begin
kernel.OnSavePCUFinished := TSavePCUFinishedEvent(value);
end;
function TPaxCompiler.GetOnLoadPCUFinished: TPaxCompilerLoadPCUFinishedEvent; // jason
begin
result := TPaxCompilerLoadPCUFinishedEvent(kernel.OnLoadPCUFinished);
end;
procedure TPaxCompiler.SetOnLoadPCUFinished( value: TPaxCompilerLoadPCUFinishedEvent); // jason
begin
kernel.OnLoadPCUFinished := TLoadPCUFinishedEvent(value);
end;
function TPaxCompiler.GetCompletionPrefix: String;
begin
result := TKernel(kernel).CompletionPrefix;
end;
function TPaxCompiler.GetModuleName(Id: Integer): String;
var
I: Integer;
begin
result := '';
if TKernel(kernel).SymbolTable[Id].Host then
begin
I := TKernel(kernel).SymbolTable[Id].Level;
if I > 0 then
begin
if TKernel(kernel).SymbolTable[I].Kind = KindNAMESPACE then
begin
result := TKernel(kernel).SymbolTable[I].Name;
Exit;
end
else
result := GetModuleName(I);
end;
end;
I := TKernel(kernel).Modules.IndexOfModuleById(Id);
if I = -1 then
Exit;
result := TKernel(kernel).Modules[I].Name;
end;
function TPaxCompiler.GetPosition(Id: Integer): Integer;
begin
result := TKernel(kernel).SymbolTable[Id].Position;
end;
function TPaxCompiler.GetKind(Id: Integer): Integer;
begin
result := TKernel(kernel).SymbolTable[Id].Kind;
end;
function TPaxCompiler.GetUnicode: Boolean;
begin
result := TKernel(kernel).IsUNIC;
end;
procedure TPaxCompiler.SetUnicode(value: Boolean);
begin
TKernel(kernel).IsUNIC := value;
end;
{$ifdef DRTTI}
procedure TPaxCompiler.RegisterImportUnit(Level: Integer; const AUnitName: String);
begin
TKernel(kernel).RegisterImportUnit(Level, AUnitName);
end;
{$endif}
function TPaxCompiler.GetEvalList: TStringList;
begin
result := TKernel(kernel).EvalList;
end;
function TPaxCompiler.InScript(const IdentName: String): Boolean;
begin
result := GetEvalList.IndexOf(IdentName) >= 0;
end;
procedure TPaxCompiler.ExtendAlphabet(B1, B2: Word);
begin
kernel.ExAlphaList.Add(B1, B2);
end;
/////////////// TPaxCompilerLanguage ///////////////////////////////////////////
destructor TPaxCompilerLanguage.Destroy;
begin
FreeAndNil(P);
inherited;
end;
function TPaxCompilerLanguage.GetExplicitOff: Boolean;
begin
result := P.EXPLICIT_OFF;
end;
procedure TPaxCompilerLanguage.SetExplicitOff(value: Boolean);
begin
P.EXPLICIT_OFF := value;
end;
function TPaxCompilerLanguage.GetCompleteBooleanEval: Boolean;
begin
result := P.CompleteBooleanEval;
end;
procedure TPaxCompilerLanguage.SetCompleteBooleanEval(value: Boolean);
begin
P.CompleteBooleanEval := value;
end;
function TPaxCompilerLanguage.GetPrintKeyword: String;
begin
result := P.PrintKeyword;
end;
function TPaxCompilerLanguage.GetPrintlnKeyword: String;
begin
result := P.PrintlnKeyword;
end;
procedure TPaxCompilerLanguage.SetPrintKeyword(const value: String);
begin
P.PrintKeyword := value;
if P.ParsesModule then
P.Gen(OP_PRINT_KWD, P.NewConst(typeSTRING, value), 0, 0);
end;
procedure TPaxCompilerLanguage.SetPrintlnKeyword(const value: String);
begin
P.PrintlnKeyword := value;
if P.ParsesModule then
P.Gen(OP_PRINTLN_KWD, P.NewConst(typeSTRING, value), 0, 0);
end;
function TPaxCompilerLanguage.GetUnitLookup: Boolean;
begin
result := P.UnitLookup;
end;
procedure TPaxCompilerLanguage.SetUnitLookup(value: Boolean);
begin
P.UnitLookup := value;
end;
function TPaxCompilerLanguage.GetInitFuncResult: Boolean;
begin
result := P.InitFuncResult;
end;
procedure TPaxCompilerLanguage.SetInitFuncResult(value: Boolean);
begin
P.InitFuncResult := value;
end;
/////////////// TPaxPascalLanguage /////////////////////////////////////////////
constructor TPaxPascalLanguage.Create(AOwner: TComponent);
begin
inherited;
P := TPascalParser.Create;
P.Owner := Self;
SetCallConv(_ccREGISTER);
end;
procedure TPaxPascalLanguage.SetCallConv(CallConv: Integer);
begin
P.CallConv := CallConv;
end;
function TPaxPascalLanguage.GetParser: TBaseParser;
begin
result := P;
end;
function TPaxPascalLanguage.GetLanguageName: String;
begin
result := P.LanguageName;
end;
function TPaxPascalLanguage.GetOnParseUnitName: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseUnitName);
end;
procedure TPaxPascalLanguage.SetOnParseUnitName(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseUnitName := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseImplementationSection: TPaxParserNotifyEvent;
begin
result := TPaxParserNotifyEvent((P as TPascalParser).OnParseImplementationSection);
end;
procedure TPaxPascalLanguage.SetOnParseImplementationSection(value: TPaxParserNotifyEvent);
begin
(P as TPascalParser).OnParseImplementationSection := TParserNotifyEvent(value);
end;
function TPaxPascalLanguage.GetOnParseBeginUsedUnitList: TPaxParserNotifyEvent;
begin
result := TPaxParserNotifyEvent((P as TPascalParser).OnParseBeginUsedUnitList);
end;
procedure TPaxPascalLanguage.SetOnParseBeginUsedUnitList(value: TPaxParserNotifyEvent);
begin
(P as TPascalParser).OnParseBeginUsedUnitList := TParserNotifyEvent(value);
end;
function TPaxPascalLanguage.GetOnParseEndUsedUnitList: TPaxParserNotifyEvent;
begin
result := TPaxParserNotifyEvent((P as TPascalParser).OnParseEndUsedUnitList);
end;
procedure TPaxPascalLanguage.SetOnParseEndUsedUnitList(value: TPaxParserNotifyEvent);
begin
(P as TPascalParser).OnParseEndUsedUnitList := TParserNotifyEvent(value);
end;
function TPaxPascalLanguage.GetOnParseUsedUnitName: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseUsedUnitName);
end;
procedure TPaxPascalLanguage.SetOnParseUsedUnitName(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseUsedUnitName := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseBeginClassTypeDeclaration: TPaxParserIdentEventEx;
begin
result := TPaxParserIdentEventEx((P as TPascalParser).OnParseBeginClassTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseBeginClassTypeDeclaration(value: TPaxParserIdentEventEx);
begin
(P as TPascalParser).OnParseBeginClassTypeDeclaration := TParserIdentEventEx(value);
end;
function TPaxPascalLanguage.GetOnParseEndClassTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseEndClassTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseEndClassTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseEndClassTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseForwardTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseForwardTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseForwardTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseForwardTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseAncestorTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseAncestorTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseAncestorTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseAncestorTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseUsedInterface: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseUsedInterface);
end;
procedure TPaxPascalLanguage.SetOnParseUsedInterface(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseUsedInterface := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseClassReferenceTypeDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParseClassReferenceTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseClassReferenceTypeDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParseClassReferenceTypeDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseAliasTypeDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParseAliasTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseAliasTypeDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParseAliasTypeDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseProceduralTypeDeclaration: TPaxParserIdentEventEx;
begin
result := TPaxParserIdentEventEx((P as TPascalParser).OnParseProceduralTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseProceduralTypeDeclaration(value: TPaxParserIdentEventEx);
begin
(P as TPascalParser).OnParseProceduralTypeDeclaration := TParserIdentEventEx(value);
end;
function TPaxPascalLanguage.GetOnParseEventTypeDeclaration: TPaxParserIdentEventEx;
begin
result := TPaxParserIdentEventEx((P as TPascalParser).OnParseEventTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseEventTypeDeclaration(value: TPaxParserIdentEventEx);
begin
(P as TPascalParser).OnParseEventTypeDeclaration := TParserIdentEventEx(value);
end;
function TPaxPascalLanguage.GetOnParseMethodReferenceTypeDeclaration: TPaxParserIdentEventEx;
begin
result := TPaxParserIdentEventEx((P as TPascalParser).OnParseMethodReferenceTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseMethodReferenceTypeDeclaration(value: TPaxParserIdentEventEx);
begin
(P as TPascalParser).OnParseMethodReferenceTypeDeclaration := TParserIdentEventEx(value);
end;
function TPaxPascalLanguage.GetOnParseSetTypeDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParseSetTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseSetTypeDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParseSetTypeDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParsePointerTypeDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParsePointerTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParsePointerTypeDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParsePointerTypeDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseArrayTypeDeclaration: TPaxParserArrayTypeEvent;
begin
result := TPaxParserArrayTypeEvent((P as TPascalParser).OnParseArrayTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseArrayTypeDeclaration(value: TPaxParserArrayTypeEvent);
begin
(P as TPascalParser).OnParseArrayTypeDeclaration := TParserArrayTypeEvent(value);
end;
function TPaxPascalLanguage.GetOnParseDynArrayTypeDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParseDynArrayTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseDynArrayTypeDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParseDynArrayTypeDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseShortStringTypeDeclaration: TPaxParserNamedValueEvent;
begin
result := TPaxParserNamedValueEvent((P as TPascalParser).OnParseShortStringTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseShortStringTypeDeclaration(value: TPaxParserNamedValueEvent);
begin
(P as TPascalParser).OnParseShortStringTypeDeclaration := TParserNamedValueEvent(value);
end;
function TPaxPascalLanguage.GetOnParseSubrangeTypeDeclaration: TPaxParserDeclarationEvent;
begin
result := TPaxParserDeclarationEvent((P as TPascalParser).OnParseSubrangeTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseSubrangeTypeDeclaration(value: TPaxParserDeclarationEvent);
begin
(P as TPascalParser).OnParseSubrangeTypeDeclaration := TParserDeclarationEvent(value);
end;
function TPaxPascalLanguage.GetOnParseBeginRecordTypeDeclaration: TPaxParserIdentEventEx;
begin
result := TPaxParserIdentEventEx((P as TPascalParser).OnParseBeginRecordTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseBeginRecordTypeDeclaration(value: TPaxParserIdentEventEx);
begin
(P as TPascalParser).OnParseBeginRecordTypeDeclaration := TParserIdentEventEx(value);
end;
function TPaxPascalLanguage.GetOnParseEndRecordTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseEndRecordTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseEndRecordTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseEndRecordTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseBeginInterfaceTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseBeginInterfaceTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseBeginInterfaceTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseBeginInterfaceTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseEndInterfaceTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseEndInterfaceTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseEndInterfaceTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseEndInterfaceTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseBeginEnumTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseBeginEnumTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseBeginEnumTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseBeginEnumTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseEndEnumTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseEndEnumTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseEndEnumTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseEndEnumTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseEnumName: TPaxParserNamedValueEvent;
begin
result := TPaxParserNamedValueEvent((P as TPascalParser).OnParseEnumName);
end;
procedure TPaxPascalLanguage.SetOnParseEnumName(value: TPaxParserNamedValueEvent);
begin
(P as TPascalParser).OnParseEnumName := TParserNamedValueEvent(value);
end;
function TPaxPascalLanguage.GetOnParseFieldDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParseFieldDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseFieldDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParseFieldDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseVariantRecordFieldDeclaration: TPaxParserVariantRecordFieldEvent;
begin
result := TPaxParserVariantRecordFieldEvent((P as TPascalParser).OnParseVariantRecordFieldDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseVariantRecordFieldDeclaration(value: TPaxParserVariantRecordFieldEvent);
begin
(P as TPascalParser).OnParseVariantRecordFieldDeclaration := TParserVariantRecordFieldEvent(value);
end;
function TPaxPascalLanguage.GetOnParsePropertyDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParsePropertyDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParsePropertyDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParsePropertyDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseConstantDeclaration: TPaxParserNamedValueEvent;
begin
result := TPaxParserNamedValueEvent((P as TPascalParser).OnParseConstantDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseConstantDeclaration(value: TPaxParserNamedValueEvent);
begin
(P as TPascalParser).OnParseConstantDeclaration := TParserNamedValueEvent(value);
end;
function TPaxPascalLanguage.GetOnParseResourceStringDeclaration: TPaxParserNamedValueEvent;
begin
result := TPaxParserNamedValueEvent((P as TPascalParser).OnParseResourceStringDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseResourceStringDeclaration(value: TPaxParserNamedValueEvent);
begin
(P as TPascalParser).OnParseResourceStringDeclaration := TParserNamedValueEvent(value);
end;
function TPaxPascalLanguage.GetOnParseTypedConstantDeclaration: TPaxParserNamedTypedValueEvent;
begin
result := TPaxParserNamedTypedValueEvent((P as TPascalParser).OnParseTypedConstantDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseTypedConstantDeclaration(value: TPaxParserNamedTypedValueEvent);
begin
(P as TPascalParser).OnParseTypedConstantDeclaration := TParserNamedTypedValueEvent(value);
end;
function TPaxPascalLanguage.GetOnParseVariableDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParseVariableDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseVariableDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParseVariableDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseBeginSubDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseBeginSubDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseBeginSubDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseBeginSubDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseEndSubDeclaration: TPaxParserDeclarationEvent;
begin
result := TPaxParserDeclarationEvent((P as TPascalParser).OnParseEndSubDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseEndSubDeclaration(value: TPaxParserDeclarationEvent);
begin
(P as TPascalParser).OnParseEndSubDeclaration := TParserDeclarationEvent(value);
end;
function TPaxPascalLanguage.GetOnParseBeginFormalParameterList: TPaxParserNotifyEvent;
begin
result := TPaxParserNotifyEvent((P as TPascalParser).OnParseBeginFormalParameterList);
end;
procedure TPaxPascalLanguage.SetOnParseBeginFormalParameterList(value: TPaxParserNotifyEvent);
begin
(P as TPascalParser).OnParseBeginFormalParameterList := TParserNotifyEvent(value);
end;
function TPaxPascalLanguage.GetOnParseEndFormalParameterList: TPaxParserNotifyEvent;
begin
result := TPaxParserNotifyEvent((P as TPascalParser).OnParseEndFormalParameterList);
end;
procedure TPaxPascalLanguage.SetOnParseEndFormalParameterList(value: TPaxParserNotifyEvent);
begin
(P as TPascalParser).OnParseEndFormalParameterList := TParserNotifyEvent(value);
end;
function TPaxPascalLanguage.GetOnParseFormalParameterDeclaration: TPaxParserNamedTypedValueEvent;
begin
result := TPaxParserNamedTypedValueEvent((P as TPascalParser).OnParseFormalParameterDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseFormalParameterDeclaration(value: TPaxParserNamedTypedValueEvent);
begin
(P as TPascalParser).OnParseFormalParameterDeclaration := TParserNamedTypedValueEvent(value);
end;
function TPaxPascalLanguage.GetOnParseResultType: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseResultType);
end;
procedure TPaxPascalLanguage.SetOnParseResultType(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseResultType := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseBeginClassHelperTypeDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParseBeginClassHelperTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseBeginClassHelperTypeDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParseBeginClassHelperTypeDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseEndClassHelperTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseEndClassHelperTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseEndClassHelperTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseEndClassHelperTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseBeginRecordHelperTypeDeclaration: TPaxParserTypedIdentEvent;
begin
result := TPaxParserTypedIdentEvent((P as TPascalParser).OnParseBeginRecordHelperTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseBeginRecordHelperTypeDeclaration(value: TPaxParserTypedIdentEvent);
begin
(P as TPascalParser).OnParseBeginRecordHelperTypeDeclaration := TParserTypedIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseEndRecordHelperTypeDeclaration: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseEndRecordHelperTypeDeclaration);
end;
procedure TPaxPascalLanguage.SetOnParseEndRecordHelperTypeDeclaration(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseEndRecordHelperTypeDeclaration := TParserIdentEvent(value);
end;
function TPaxPascalLanguage.GetOnParseSubDirective: TPaxParserIdentEvent;
begin
result := TPaxParserIdentEvent((P as TPascalParser).OnParseSubDirective);
end;
procedure TPaxPascalLanguage.SetOnParseSubDirective(value: TPaxParserIdentEvent);
begin
(P as TPascalParser).OnParseSubDirective := TParserIdentEvent(value);
end;
procedure SetDump;
begin
IsDump := true;
end;
end.
|
unit FMX.TestLib;
interface
uses
System.Types, System.UITypes, System.SysUtils, System.Classes, FMX.Types, FMX.Forms, FMX.Objects,
System.UIConsts, FMX.Controls, FMX.Graphics;
type
PointFArray = array of array[0..1] of Single;
TTestMousePath = class;
TTestLib = class(TObject)
protected
FInitialMousePoint: TPointF;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); virtual; abstract;
procedure MouseMove(Shift: TShiftState; X, Y: Single); virtual; abstract;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); virtual; abstract;
procedure MouseWheel(WheelDelta: Integer); virtual; abstract;
procedure KeyDown(Key: Word); virtual; abstract;
procedure KeyUp(Key: Word); virtual; abstract;
public
procedure SetInitialMousePoint(Pos: TPointF);
procedure RunMouseClick(X, Y: Single); overload;
procedure RunMouseClick(Pt: TPointF); overload;
procedure RunMousePath(AMousePathData: TTestMousePath); overload;
procedure RunMousePath(Path: array of TPointF); overload;
procedure RunMouseMove(Path: array of TPointF);
procedure RunKeyDownShift; virtual; abstract;
procedure RunKeyUpShift; virtual; abstract;
procedure RunKeyPress(Keys: array of Word);
procedure RunMouseWheelUp(X, Y: Single);
procedure RunMouseWheelDown(X, Y: Single);
function GetControlPixelColor(const Control: TControl; const X, Y: Single): TAlphaColor;
function GetBitmapPixelColor(const X, Y: Single): TAlphaColor;
procedure TakeScreenshot(Dest: TBitmap); virtual; abstract;
procedure Delay(ms: Integer);
end;
TTestLibClass = class of TTestLib;
TMousePathData = array of TPointF;
TTestMousePath = class
private
FPaths: array of TPointF;
function GetPath: TMousePathData;
function GetAddPoint(const X, Y: Single): TTestMousePath;
public
procedure Clear;
function New: TTestMousePath;
function Add(const X, Y: Single): TTestMousePath; overload;
function Add(Pos: TPointF): TTestMousePath; overload;
property Path: TMousePathData read GetPath;
property AddPoint[const X, Y: Single]: TTestMousePath read GetAddPoint; default;
end;
var
TestLib: TTestLib;
MousePath: TTestMousePath;
implementation
uses
System.Diagnostics,
{$IFDEF MACOS}
FMX.TestLib.Mac;
{$ENDIF}
{$IFDEF MSWINDOWS}
FMX.TestLib.Win;
{$ENDIF}
{ TTestLib }
procedure TTestLib.SetInitialMousePoint(Pos: TPointF);
begin
FInitialMousePoint := Pos;
end;
procedure TTestLib.Delay(ms: Integer);
var
StopWatch: TStopWatch;
begin
StopWatch := TStopWatch.Create;
StopWatch.Start;
repeat
Application.ProcessMessages;
Sleep(1);
until StopWatch.ElapsedMilliseconds >= ms;
end;
function TTestLib.GetBitmapPixelColor(const X,
Y: Single): TAlphaColor;
var
Bitmap: TBitmap;
BitmapData: TBitmapData;
begin
Result := claBlack;
Application.ProcessMessages;
Sleep(0);
Bitmap := TBitmap.Create(0, 0);
TakeScreenshot(Bitmap);
try
if not Assigned(Bitmap) then
Exit;
// Bitmap.SaveToFile('C:\Users\hjFactory\Downloads\test.bmp');
Bitmap.Map(TMapAccess.maRead, BitmapData);
try
Result := BitmapData.GetPixel(Round(X), Round(Y));
finally
Bitmap.Unmap(BitmapData);
end;
finally
Bitmap.Free;
end;
end;
function TTestLib.GetControlPixelColor(const Control: TControl; const X, Y: Single): TAlphaColor;
var
Bitmap: TBitmap;
BitmapData: TBitmapData;
begin
Result := claBlack;
// Control.PaintTo();
Bitmap := Control.MakeScreenshot;
try
if not Assigned(Bitmap) then
Exit;
Bitmap.Map(TMapAccess.maRead, BitmapData);
try
Result := BitmapData.GetPixel(Round(X), Round(Y));
finally
Bitmap.Unmap(BitmapData);
end;
finally
Bitmap.Free;
end;
end;
procedure TTestLib.RunKeyPress(Keys: array of Word);
var
I: Integer;
W: Word;
begin
for W in Keys do
KeyDown(W);
for I := Length(Keys) - 1 downto 0 do
KeyUp(Keys[I]);
end;
procedure TTestLib.RunMouseClick(X, Y: Single);
begin
MouseDown(TMouseButton.mbLeft, [], FInitialMousePoint.X+X, FInitialMousePoint.Y+Y);
MouseUp(TMouseButton.mbLeft, [], FInitialMousePoint.X+X, FInitialMousePoint.Y+Y);
Application.ProcessMessages;
end;
procedure TTestLib.RunMouseClick(Pt: TPointF);
begin
RunMouseClick(Pt.X, Pt.Y);
end;
procedure TTestLib.RunMousePath(Path: array of TPointF);
var
I: Integer;
Pos: TPointF;
begin
for I := Low(Path) to High(Path) do
begin
Pos := FInitialMousePoint.Add(Path[I]);
if I = Low(Path) then
MouseDown(TMouseButton.mbLeft, [], Pos.X, Pos.Y)
else if I = High(Path) then
MouseUp(TMouseButton.mbLeft, [], Pos.X, Pos.Y)
else
MouseMove([], Pos.X, Pos.Y)
;
Application.ProcessMessages;
end;
end;
procedure TTestLib.RunMouseMove(Path: array of TPointF);
var
I: Integer;
Pos: TPointF;
begin
for I := Low(Path) to High(Path) do
begin
Pos := FInitialMousePoint.Add(Path[I]);
MouseMove([], Pos.X, Pos.Y);
Application.ProcessMessages;
end;
end;
procedure TTestLib.RunMousePath(AMousePathData: TTestMousePath);
begin
RunMousePath(AMousePathData.Path);
end;
procedure TTestLib.RunMouseWheelDown(X, Y: Single);
var
Pos: TPointF;
begin
Pos := FInitialMousePoint.Add(PointF(X, Y));
MouseMove([], Pos.X, Pos.Y);
MouseWheel(120);
end;
procedure TTestLib.RunMouseWheelUp(X, Y: Single);
var
Pos: TPointF;
begin
Pos := FInitialMousePoint.Add(PointF(X, Y));
MouseMove([], Pos.X, Pos.Y);
MouseWheel(-120);
end;
{ TTestMousePath }
procedure TTestMousePath.Clear;
begin
SetLength(FPaths, 0);
end;
function TTestMousePath.Add(const X, Y: Single): TTestMousePath;
begin
Add(PointF(X, Y));
Result := Self;
end;
function TTestMousePath.Add(Pos: TPointF): TTestMousePath;
begin
SetLength(Fpaths, Length(FPaths) + 1);
FPaths[High(FPaths)] := Pos;
Result := Self;
end;
function TTestMousePath.GetAddPoint(const X, Y: Single): TTestMousePath;
begin
Result := Add(X, Y);
end;
function TTestMousePath.GetPath: TMousePathData;
begin
Result := TMousePathData(FPaths);
end;
function TTestMousePath.New: TTestMousePath;
begin
Clear;
Result := Self;
end;
initialization
TestLib := GetTestLibClass.Create;
MousePath := TTestMousePath.Create;
finalization
if Assigned(TestLib) then
TestLib.Free;
if Assigned(MousePath) then
MousePath.Free;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.